text
stringlengths
2
1.04M
meta
dict
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* | ------------------------------------------------------------------- | AUTO-LOADER | ------------------------------------------------------------------- | This file specifies which systems should be loaded by default. | | In order to keep the framework as light-weight as possible only the | absolute minimal resources are loaded by default. For example, | the database is not connected to automatically since no assumption | is made regarding whether you intend to use it. This file lets | you globally define which systems you would like loaded with every | request. | | ------------------------------------------------------------------- | Instructions | ------------------------------------------------------------------- | | These are the things you can load automatically: | | 1. Packages | 2. Libraries | 3. Drivers | 4. Helper files | 5. Custom config files | 6. Language files | 7. Models | */ /* | ------------------------------------------------------------------- | Auto-load Packages | ------------------------------------------------------------------- | Prototype: | | $autoload['packages'] = array(APPPATH.'third_party', '/usr/local/shared'); | */ $autoload['packages'] = array(); /* | ------------------------------------------------------------------- | Auto-load Libraries | ------------------------------------------------------------------- | These are the classes located in the system/libraries folder | or in your application/libraries folder. | | Prototype: | | $autoload['libraries'] = array('database', 'email', 'session'); | | You can also supply an alternative library name to be assigned | in the controller: | | $autoload['libraries'] = array('user_agent' => 'ua'); */ $autoload['libraries'] = array('session'); /* | ------------------------------------------------------------------- | Auto-load Drivers | ------------------------------------------------------------------- | These classes are located in the system/libraries folder or in your | application/libraries folder within their own subdirectory. They | offer multiple interchangeable driver options. | | Prototype: | | $autoload['drivers'] = array('cache'); */ $autoload['drivers'] = array(); /* | ------------------------------------------------------------------- | Auto-load Helper Files | ------------------------------------------------------------------- | Prototype: | | $autoload['helper'] = array('url', 'file'); */ $autoload['helper'] = array('admin','url'); /* | ------------------------------------------------------------------- | Auto-load Config files | ------------------------------------------------------------------- | Prototype: | | $autoload['config'] = array('config1', 'config2'); | | NOTE: This item is intended for use ONLY if you have created custom | config files. Otherwise, leave it blank. | */ $autoload['config'] = array('admin'); /* | ------------------------------------------------------------------- | Auto-load Language files | ------------------------------------------------------------------- | Prototype: | | $autoload['language'] = array('lang1', 'lang2'); | | NOTE: Do not include the "_lang" part of your file. For example | "codeigniter_lang.php" would be referenced as array('codeigniter'); | */ $autoload['language'] = array(); /* | ------------------------------------------------------------------- | Auto-load Models | ------------------------------------------------------------------- | Prototype: | | $autoload['model'] = array('first_model', 'second_model'); | | You can also supply an alternative model name to be assigned | in the controller: | | $autoload['model'] = array('first_model' => 'first'); */ $autoload['model'] = array();
{ "content_hash": "3a747198c0523dfdb9c9504eebeba236", "timestamp": "", "source": "github", "line_count": 140, "max_line_length": 77, "avg_line_length": 27.057142857142857, "alnum_prop": 0.45776135163674764, "repo_name": "skyling/CI", "id": "12f8c56fd496b1065c5d0dfe0e45b20b89916f0c", "size": "3788", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "admin/config/autoload.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "906" }, { "name": "CSS", "bytes": "27495" }, { "name": "HTML", "bytes": "5418905" }, { "name": "JavaScript", "bytes": "175771" }, { "name": "PHP", "bytes": "2071058" } ], "symlink_target": "" }
<?php class ExcelHelper { public static function export ( $items, $fileName = 'export' ) { //MAKE HEADER $header = ''; foreach($items as $item) { foreach($item as $key => $value) $header .= $key . "\t"; break; } //DATA $data = ''; foreach($items as $item) { $line = ''; foreach($item as $value) { $value = str_replace('"', '""', $value); $value = '"' . $value . '"' . "\t"; $line .= $value; } $data .= trim($line)."\n"; } # this line is needed because returns embedded in the data have "\r" # and this looks like a "box character" in Excel $data = str_replace("\r", "", $data); # Nice to let someone know that the search came up empty. # Otherwise only the column name headers will be output to Excel. if ($data == "") { $data = "\nno matching records found\n"; } # This line will stream the file to the user rather than spray it across the screen header("Content-type: application/octet-stream"); # replace excelfile.xls with whatever you want the filename to default to header("Content-Disposition: attachment; filename=" . $fileName . ".xls"); header("Pragma: no-cache"); header("Expires: 0"); echo $header."\n".$data; } } ?>
{ "content_hash": "717ea20b104744a1e92e89de9861ead3", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 85, "avg_line_length": 25.408163265306122, "alnum_prop": 0.5927710843373494, "repo_name": "hugomarin/artBO", "id": "25853b06253c0df03000736cf86e7857d6c7b2ea", "size": "1245", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "en/model/helpers/excelhelper.helper.php", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "124248" }, { "name": "ColdFusion", "bytes": "333388" }, { "name": "JavaScript", "bytes": "4044652" }, { "name": "Lasso", "bytes": "66388" }, { "name": "PHP", "bytes": "1512402" }, { "name": "Perl", "bytes": "74380" }, { "name": "Python", "bytes": "83098" }, { "name": "Ruby", "bytes": "887" }, { "name": "Shell", "bytes": "3304" } ], "symlink_target": "" }
package org.bouncycastle.jcajce.provider.asymmetric; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; import org.bouncycastle.jcajce.provider.util.AsymmetricAlgorithmProvider; public class LMS { private static final String PREFIX = "org.bouncycastle.pqc.jcajce.provider" + ".lms."; public static class Mappings extends AsymmetricAlgorithmProvider { public Mappings() { } public void configure(ConfigurableProvider provider) { provider.addAlgorithm("KeyFactory.LMS", PREFIX + "LMSKeyFactorySpi"); provider.addAlgorithm("Alg.Alias.KeyFactory." + PKCSObjectIdentifiers.id_alg_hss_lms_hashsig, "LMS"); provider.addAlgorithm("KeyPairGenerator.LMS", PREFIX + "LMSKeyPairGeneratorSpi"); provider.addAlgorithm("Alg.Alias.KeyPairGenerator." + PKCSObjectIdentifiers.id_alg_hss_lms_hashsig, "LMS"); provider.addAlgorithm("Signature.LMS", PREFIX + "LMSSignatureSpi$generic"); provider.addAlgorithm("Alg.Alias.Signature." + PKCSObjectIdentifiers.id_alg_hss_lms_hashsig, "LMS"); } } }
{ "content_hash": "d4b8d5c149ba15d7981e1a8a2f121e4a", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 119, "avg_line_length": 39.93333333333333, "alnum_prop": 0.7086811352253757, "repo_name": "bcgit/bc-java", "id": "11bbf8e1ce36fcf6177839f8130db484641077f0", "size": "1198", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/LMS.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "12956" }, { "name": "HTML", "bytes": "66943" }, { "name": "Java", "bytes": "31612485" }, { "name": "Shell", "bytes": "97225" } ], "symlink_target": "" }
package command import ( "errors" "fmt" log "github.com/Sirupsen/logrus" "github.com/NetSys/quilt/api" "github.com/NetSys/quilt/api/client" ) // SubCommand defines the conversion between the user CLI flags and // functionality within the code. type SubCommand interface { // The function to run once the flags have been parsed. The return value // is the exit code. Run() int // Give the command line arguments to the subcommand so that it can parse // it for later execution. Parse(args []string) error // Print out the usage of the SubCommand. Usage() } // Stored in a variable so we can mock it out for the unit tests. var getClient = func(host string) (client.Client, error) { c, err := client.New(host) if err != nil { return nil, DaemonConnectError{ host: host, connectError: err, } } return c, nil } // Get a client connected to the lead minion. func getLeaderClient(localClient client.Client) (client.Client, error) { machines, err := localClient.QueryMachines() if err != nil { return nil, fmt.Errorf("unable to query machines: %s", err.Error()) } // Try to figure out the lead minion's IP by asking each of the machines // tracked by the local daemon. for _, m := range machines { if m.PublicIP == "" { continue } ip, err := getLeaderIP(localClient, m.PublicIP) if err == nil { return getClient(api.RemoteAddress(ip)) } log.WithError(err).Debug("Unable to get leader IP.") } return nil, errors.New("no leader found") } // Get the public IP of the lead minion by querying the remote machine's etcd // table for the private IP, and then searching for the public IP in the local // daemon. func getLeaderIP(localClient client.Client, daemonIP string) (string, error) { remoteClient, err := getClient(api.RemoteAddress(daemonIP)) if err != nil { return "", err } defer remoteClient.Close() etcds, err := remoteClient.QueryEtcd() if err != nil { return "", err } if len(etcds) == 0 || etcds[0].LeaderIP == "" { return "", fmt.Errorf("no leader information on host %s", daemonIP) } return getPublicIP(localClient, etcds[0].LeaderIP) } // Get the public IP of a machine given its private IP. func getPublicIP(c client.Client, privateIP string) (string, error) { machines, err := c.QueryMachines() if err != nil { return "", err } for _, m := range machines { if m.PrivateIP == privateIP { return m.PublicIP, nil } } return "", fmt.Errorf("no machine with private IP %s", privateIP) }
{ "content_hash": "af8e7ddbba14103cb054594395a2dac8", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 78, "avg_line_length": 24.99, "alnum_prop": 0.6874749899959984, "repo_name": "secant/quilt", "id": "4d7c3146e6f96ba73c5e5677ac2764d69dc4aebc", "size": "2499", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "quiltctl/command/command.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "634791" }, { "name": "JavaScript", "bytes": "17567" }, { "name": "Makefile", "bytes": "3684" }, { "name": "Protocol Buffer", "bytes": "886" }, { "name": "Python", "bytes": "8479" }, { "name": "Ruby", "bytes": "4885" }, { "name": "Scala", "bytes": "1423" }, { "name": "Shell", "bytes": "14991" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "322105bdbb2f71a43f7719932cac0228", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "a0352cc15fdbb6cd32cf6a89b96e2ef6a887eb2c", "size": "193", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Tainia/Tainia penangiana/ Syn. Ascotainia siamensis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package fr.free.nrw.commons.nearby; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v7.widget.PopupMenu; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.Unbinder; import fr.free.nrw.commons.R; import fr.free.nrw.commons.location.LatLng; import fr.free.nrw.commons.ui.widget.OverlayDialog; import fr.free.nrw.commons.utils.DialogUtil; public class NearbyInfoDialog extends OverlayDialog { private final static String ARG_TITLE = "placeTitle"; private final static String ARG_DESC = "placeDesc"; private final static String ARG_LATITUDE = "latitude"; private final static String ARG_LONGITUDE = "longitude"; private final static String ARG_SITE_LINK = "sitelink"; @BindView(R.id.link_preview_title) TextView placeTitle; @BindView(R.id.link_preview_extract) TextView placeDescription; @BindView(R.id.link_preview_go_button) TextView goToButton; @BindView(R.id.link_preview_overflow_button) ImageView overflowButton; private Unbinder unbinder; private LatLng location; private Sitelinks sitelinks; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.dialog_nearby_info, container, false); unbinder = ButterKnife.bind(this, view); initUi(); return view; } private void initUi() { Bundle bundle = getArguments(); placeTitle.setText(bundle.getString(ARG_TITLE)); placeDescription.setText(bundle.getString(ARG_DESC)); location = new LatLng(bundle.getDouble(ARG_LATITUDE), bundle.getDouble(ARG_LONGITUDE), 0); getArticleLink(bundle); } private void getArticleLink(Bundle bundle) { this.sitelinks = bundle.getParcelable(ARG_SITE_LINK); if (sitelinks == null || Uri.EMPTY.equals(sitelinks.getWikipediaLink())) { goToButton.setVisibility(View.GONE); } overflowButton.setVisibility(showMenu() ? View.VISIBLE : View.GONE); overflowButton.setOnClickListener(this::popupMenuListener); } private void popupMenuListener(View v) { PopupMenu popupMenu = new PopupMenu(getActivity(), overflowButton); popupMenu.inflate(R.menu.nearby_info_dialog_options); MenuItem commonsArticle = popupMenu.getMenu() .findItem(R.id.nearby_info_menu_commons_article); MenuItem wikiDataArticle = popupMenu.getMenu() .findItem(R.id.nearby_info_menu_wikidata_article); commonsArticle.setEnabled(!sitelinks.getCommonsLink().equals(Uri.EMPTY)); wikiDataArticle.setEnabled(!sitelinks.getWikidataLink().equals(Uri.EMPTY)); popupMenu.setOnMenuItemClickListener(menuListener); popupMenu.show(); } private boolean showMenu() { return !sitelinks.getCommonsLink().equals(Uri.EMPTY) || !sitelinks.getWikidataLink().equals(Uri.EMPTY); } private final PopupMenu.OnMenuItemClickListener menuListener = new PopupMenu .OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.nearby_info_menu_commons_article: openWebView(sitelinks.getCommonsLink()); return true; case R.id.nearby_info_menu_wikidata_article: openWebView(sitelinks.getWikidataLink()); return true; default: break; } return false; } }; public static void showYourself(FragmentActivity fragmentActivity, Place place) { NearbyInfoDialog mDialog = new NearbyInfoDialog(); Bundle bundle = new Bundle(); bundle.putString(ARG_TITLE, place.name); bundle.putString(ARG_DESC, place.getDescription().getText()); bundle.putDouble(ARG_LATITUDE, place.location.getLatitude()); bundle.putDouble(ARG_LONGITUDE, place.location.getLongitude()); bundle.putParcelable(ARG_SITE_LINK, place.siteLinks); mDialog.setArguments(bundle); DialogUtil.showSafely(fragmentActivity, mDialog); } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } @OnClick(R.id.link_preview_directions_button) void onDirectionsClick() { //Open map app at given position Uri gmmIntentUri = Uri.parse( "geo:0,0?q=" + location.getLatitude() + "," + location.getLongitude()); Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri); if (mapIntent.resolveActivity(getActivity().getPackageManager()) != null) { startActivity(mapIntent); } } @OnClick(R.id.link_preview_go_button) void onReadArticleClick() { openWebView(sitelinks.getWikipediaLink()); } private void openWebView(Uri link) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, link); startActivity(browserIntent); } @OnClick(R.id.emptyLayout) void onCloseClicked() { dismissAllowingStateLoss(); } }
{ "content_hash": "696196ae9d8a343fb66e33a634dd0421", "timestamp": "", "source": "github", "line_count": 152, "max_line_length": 103, "avg_line_length": 36.28947368421053, "alnum_prop": 0.6776649746192893, "repo_name": "akaita/apps-android-commons", "id": "1203d5a0df75c60d79e153370750d68cf7b37916", "size": "5516", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/fr/free/nrw/commons/nearby/NearbyInfoDialog.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "476029" }, { "name": "Makefile", "bytes": "595" }, { "name": "PHP", "bytes": "3156" }, { "name": "Shell", "bytes": "1449" } ], "symlink_target": "" }
using System; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; using Bootstrap_Components.Models; namespace Bootstrap_Components.Controllers { [Authorize] public class ManageController : Controller { public ManageController() { } public ManageController(ApplicationUserManager userManager) { UserManager = userManager; } private ApplicationUserManager _userManager; public ApplicationUserManager UserManager { get { return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); } private set { _userManager = value; } } // // GET: /Manage/Index public async Task<ActionResult> Index(ManageMessageId? message) { ViewBag.StatusMessage = message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed." : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set." : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set." : message == ManageMessageId.Error ? "An error has occurred." : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added." : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed." : ""; var model = new IndexViewModel { HasPassword = HasPassword(), PhoneNumber = await UserManager.GetPhoneNumberAsync(User.Identity.GetUserId()), TwoFactor = await UserManager.GetTwoFactorEnabledAsync(User.Identity.GetUserId()), Logins = await UserManager.GetLoginsAsync(User.Identity.GetUserId()), BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(User.Identity.GetUserId()) }; return View(model); } // // GET: /Manage/RemoveLogin public ActionResult RemoveLogin() { var linkedAccounts = UserManager.GetLogins(User.Identity.GetUserId()); ViewBag.ShowRemoveButton = HasPassword() || linkedAccounts.Count > 1; return View(linkedAccounts); } // // POST: /Manage/RemoveLogin [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> RemoveLogin(string loginProvider, string providerKey) { ManageMessageId? message; var result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey)); if (result.Succeeded) { var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInAsync(user, isPersistent: false); } message = ManageMessageId.RemoveLoginSuccess; } else { message = ManageMessageId.Error; } return RedirectToAction("ManageLogins", new { Message = message }); } // // GET: /Manage/AddPhoneNumber public ActionResult AddPhoneNumber() { return View(); } // // POST: /Manage/AddPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> AddPhoneNumber(AddPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } // Generate the token and send it var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), model.Number); if (UserManager.SmsService != null) { var message = new IdentityMessage { Destination = model.Number, Body = "Your security code is: " + code }; await UserManager.SmsService.SendAsync(message); } return RedirectToAction("VerifyPhoneNumber", new { PhoneNumber = model.Number }); } // // POST: /Manage/EnableTwoFactorAuthentication [HttpPost] public async Task<ActionResult> EnableTwoFactorAuthentication() { await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), true); var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInAsync(user, isPersistent: false); } return RedirectToAction("Index", "Manage"); } // // POST: /Manage/DisableTwoFactorAuthentication [HttpPost] public async Task<ActionResult> DisableTwoFactorAuthentication() { await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), false); var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInAsync(user, isPersistent: false); } return RedirectToAction("Index", "Manage"); } // // GET: /Manage/VerifyPhoneNumber public async Task<ActionResult> VerifyPhoneNumber(string phoneNumber) { var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), phoneNumber); // Send an SMS through the SMS provider to verify the phone number return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber }); } // // POST: /Manage/VerifyPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } var result = await UserManager.ChangePhoneNumberAsync(User.Identity.GetUserId(), model.PhoneNumber, model.Code); if (result.Succeeded) { var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInAsync(user, isPersistent: false); } return RedirectToAction("Index", new { Message = ManageMessageId.AddPhoneSuccess }); } // If we got this far, something failed, redisplay form ModelState.AddModelError("", "Failed to verify phone"); return View(model); } // // GET: /Manage/RemovePhoneNumber public async Task<ActionResult> RemovePhoneNumber() { var result = await UserManager.SetPhoneNumberAsync(User.Identity.GetUserId(), null); if (!result.Succeeded) { return RedirectToAction("Index", new { Message = ManageMessageId.Error }); } var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInAsync(user, isPersistent: false); } return RedirectToAction("Index", new { Message = ManageMessageId.RemovePhoneSuccess }); } // // GET: /Manage/ChangePassword public ActionResult ChangePassword() { return View(); } // // POST: /Manage/ChangePassword [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> ChangePassword(ChangePasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword); if (result.Succeeded) { var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInAsync(user, isPersistent: false); } return RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess }); } AddErrors(result); return View(model); } // // GET: /Manage/SetPassword public ActionResult SetPassword() { return View(); } // // POST: /Manage/SetPassword [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> SetPassword(SetPasswordViewModel model) { if (ModelState.IsValid) { var result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword); if (result.Succeeded) { var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInAsync(user, isPersistent: false); } return RedirectToAction("Index", new { Message = ManageMessageId.SetPasswordSuccess }); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Manage/ManageLogins public async Task<ActionResult> ManageLogins(ManageMessageId? message) { ViewBag.StatusMessage = message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed." : message == ManageMessageId.Error ? "An error has occurred." : ""; var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user == null) { return View("Error"); } var userLogins = await UserManager.GetLoginsAsync(User.Identity.GetUserId()); var otherLogins = AuthenticationManager.GetExternalAuthenticationTypes().Where(auth => userLogins.All(ul => auth.AuthenticationType != ul.LoginProvider)).ToList(); ViewBag.ShowRemoveButton = user.PasswordHash != null || userLogins.Count > 1; return View(new ManageLoginsViewModel { CurrentLogins = userLogins, OtherLogins = otherLogins }); } // // POST: /Manage/LinkLogin [HttpPost] [ValidateAntiForgeryToken] public ActionResult LinkLogin(string provider) { // Request a redirect to the external login provider to link a login for the current user return new AccountController.ChallengeResult(provider, Url.Action("LinkLoginCallback", "Manage"), User.Identity.GetUserId()); } // // GET: /Manage/LinkLoginCallback public async Task<ActionResult> LinkLoginCallback() { var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId()); if (loginInfo == null) { return RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error }); } var result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login); return result.Succeeded ? RedirectToAction("ManageLogins") : RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error }); } #region Helpers // Used for XSRF protection when adding external logins private const string XsrfKey = "XsrfId"; private IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } } private async Task SignInAsync(ApplicationUser user, bool isPersistent) { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie); AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager)); } private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError("", error); } } private bool HasPassword() { var user = UserManager.FindById(User.Identity.GetUserId()); if (user != null) { return user.PasswordHash != null; } return false; } private bool HasPhoneNumber() { var user = UserManager.FindById(User.Identity.GetUserId()); if (user != null) { return user.PhoneNumber != null; } return false; } public enum ManageMessageId { AddPhoneSuccess, ChangePasswordSuccess, SetTwoFactorSuccess, SetPasswordSuccess, RemoveLoginSuccess, RemovePhoneSuccess, Error } #endregion } }
{ "content_hash": "90726cac3673071769cc4d5c18af62bd", "timestamp": "", "source": "github", "line_count": 373, "max_line_length": 175, "avg_line_length": 36.85254691689008, "alnum_prop": 0.5701294922159174, "repo_name": "carloszapata/BootstrapMVA", "id": "e21c9b0f8feb3905fcdec1a1758c755558747b90", "size": "13748", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "Module 2 - Components/Bootstrap Components/Bootstrap Components/Controllers/ManageController.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "52042" }, { "name": "C#", "bytes": "753260" }, { "name": "CSS", "bytes": "320326" }, { "name": "JavaScript", "bytes": "256977" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" /> <title>Message from {shop_name}</title> <style> @media only screen and (max-width: 300px){ body { width:218px !important; margin:auto !important; } .table {width:195px !important;margin:auto !important;} .logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto !important;display: block !important;} span.title{font-size:20px !important;line-height: 23px !important} span.subtitle{font-size: 14px !important;line-height: 18px !important;padding-top:10px !important;display:block !important;} td.box p{font-size: 12px !important;font-weight: bold !important;} .table-recap table, .table-recap thead, .table-recap tbody, .table-recap th, .table-recap td, .table-recap tr { display: block !important; } .table-recap{width: 200px!important;} .table-recap tr td, .conf_body td{text-align:center !important;} .address{display: block !important;margin-bottom: 10px !important;} .space_address{display: none !important;} } @media only screen and (min-width: 301px) and (max-width: 500px) { body {width:308px!important;margin:auto!important;} .table {width:285px!important;margin:auto!important;} .logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto!important;display: block!important;} .table-recap table, .table-recap thead, .table-recap tbody, .table-recap th, .table-recap td, .table-recap tr { display: block !important; } .table-recap{width: 293px !important;} .table-recap tr td, .conf_body td{text-align:center !important;} } @media only screen and (min-width: 501px) and (max-width: 768px) { body {width:478px!important;margin:auto!important;} .table {width:450px!important;margin:auto!important;} .logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto!important;display: block!important;} } @media only screen and (max-device-width: 480px) { body {width:308px!important;margin:auto!important;} .table {width:285px;margin:auto!important;} .logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto!important;display: block!important;} .table-recap{width: 285px!important;} .table-recap tr td, .conf_body td{text-align:center!important;} .address{display: block !important;margin-bottom: 10px !important;} .space_address{display: none !important;} } </style> </head> <body style="-webkit-text-size-adjust:none;background-color:#fff;width:650px;font-family:Open-sans, sans-serif;color:#555454;font-size:13px;line-height:18px;margin:auto"> <table class="table table-mail" style="width:100%;margin-top:10px;-moz-box-shadow:0 0 5px #afafaf;-webkit-box-shadow:0 0 5px #afafaf;-o-box-shadow:0 0 5px #afafaf;box-shadow:0 0 5px #afafaf;filter:progid:DXImageTransform.Microsoft.Shadow(color=#afafaf,Direction=134,Strength=5)"> <tr> <td class="space" style="width:20px;padding:7px 0">&nbsp;</td> <td align="center" style="padding:7px 0"> <table class="table" bgcolor="#ffffff" style="width:100%"> <tr> <td align="center" class="logo" style="border-bottom:4px solid #333333;padding:7px 0"> <a title="{shop_name}" href="{shop_url}" style="color:#337ff1"> <img src="{shop_logo}" alt="{shop_name}" /> </a> </td> </tr> <tr> <td align="center" class="titleblock" style="padding:7px 0"> <font size="2" face="Open-sans, sans-serif" color="#555454"> <span class="title" style="font-weight:500;font-size:28px;text-transform:uppercase;line-height:33px">Message from a {shop_name} customer</span> </font> </td> </tr> <tr> <td class="space_footer" style="padding:0!important">&nbsp;</td> </tr> <tr> <td class="box" style="border:1px solid #D6D4D4;background-color:#f8f8f8;padding:7px 0"> <table class="table" style="width:100%"> <tr> <td width="10" style="padding:7px 0">&nbsp;</td> <td style="padding:7px 0"> <font size="2" face="Open-sans, sans-serif" color="#555454"> <span style="color:#777"> <span style="color:#333"><strong>Customer e-mail address: <a href="mailto:{email}" style="color:#337ff1">{email}</a></strong></span><br /><br /> <span style="color:#333"><strong>Customer message:</strong></span> {message} </span> </font> </td> <td width="10" style="padding:7px 0">&nbsp;</td> </tr> </table> </td> </tr> <tr> <td class="space_footer" style="padding:0!important">&nbsp;</td> </tr> <tr> <td class="footer" style="border-top:4px solid #333333;padding:7px 0"> <span><a href="{shop_url}" style="color:#337ff1">{shop_name}</a> powered by <a href="http://kasoko.emmanuelndayiragije.com/" style="color:#337ff1">Kasoko e-Commerce</a></span> </td> </tr> </table> </td> <td class="space" style="width:20px;padding:7px 0">&nbsp;</td> </tr> </table> </body> </html>
{ "content_hash": "bf6777d5ca87563f7e4ef799c69f44d1", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 281, "avg_line_length": 46.26548672566372, "alnum_prop": 0.6599081866870696, "repo_name": "kazinduzi/kasoko", "id": "07fbeb03775869dad06b4eee4867dc722edc5a07", "size": "5228", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "application/front/mails/fr_FR/contact.html", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "47705" }, { "name": "ApacheConf", "bytes": "5189" }, { "name": "Batchfile", "bytes": "270" }, { "name": "CSS", "bytes": "592368" }, { "name": "HTML", "bytes": "1960098" }, { "name": "JavaScript", "bytes": "3765090" }, { "name": "PHP", "bytes": "1843077" }, { "name": "Shell", "bytes": "248" }, { "name": "Smarty", "bytes": "38315" } ], "symlink_target": "" }
import Messente smsSend = send "api-username" "api-password" main = do -- If from is Nothing then messente default 'From' is used -- (configured from API setup at messente.com) result <- smsSend Nothing "+00000000000" "my first sms" putStrLn $ case result of Right id -> "sms sent, id: " ++ id Left (errNo, errStr) -> "not sent: " ++ show errNo ++ ", " ++ errStr -- star http server to get delivery feedback (must configure at messente.com) -- this function doesn't return (runs forever) listen 9000 delivery delivery :: Delivery -> IO () delivery del = putStrLn $ case del of Delivered id -> "delivered " ++ id DeliveryError id errNo errStr -> "not delivered " ++ id ++ ": " ++ errStr DeliveryProgress id status -> "progress " ++ id ++ ": " ++ status
{ "content_hash": "fab07cfcae3d8a4545241c19e681ebdc", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 79, "avg_line_length": 36.40909090909091, "alnum_prop": 0.6441947565543071, "repo_name": "kaiko/messente-haskell", "id": "9fef8919792759f5e1f47d487c50501e96201757", "size": "801", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test.hs", "mode": "33188", "license": "mit", "language": [ { "name": "Haskell", "bytes": "7536" } ], "symlink_target": "" }
This application makes use of the following third party libraries: ## AFNetworking Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) 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 Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## CJBaseUIKit MIT License Copyright (c) 2017 dvlproad 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 Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## CJBaseUtil The MIT License (MIT) Copyright (c) 2015 dvlproad 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 Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## CJNetwork The MIT License (MIT) Copyright (c) 2015 dvlproad 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 Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## MJPopupViewController Copyright (c) 2012 Martin Juhasz 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 Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## MJRefresh Copyright (c) 2013-2015 MJRefresh (https://github.com/CoderMJLee/MJRefresh) 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 Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## Masonry Copyright (c) 2011-2012 Masonry Team - https://github.com/Masonry 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 Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## NSOperationQueueUtil MIT License Copyright (c) 2017 dvlproad 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 Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## PinYin4Objc Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: You must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ## PureLayout This code is distributed under the terms and conditions of the MIT license. Copyright (c) 2014-2015 Tyler Fox 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 Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## SDCycleScrollView The MIT License (MIT) Copyright (c) 2015 GSD_iOS 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 Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## SDWebImage Copyright (c) 2016 Olivier Poitrey rs@dailymotion.com 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 Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Generated by CocoaPods - https://cocoapods.org
{ "content_hash": "ffa88dc0344be49f2dde9a0ba3815f0d", "timestamp": "", "source": "github", "line_count": 456, "max_line_length": 460, "avg_line_length": 49.42982456140351, "alnum_prop": 0.8048358473824312, "repo_name": "dvlproad/AllScrollView", "id": "c743f989a6550f9f98ba4b8380b9d8cd29f36668", "size": "22561", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AllScrollViewDemo/Pods/Target Support Files/Pods-AllScrollViewDemo/Pods-AllScrollViewDemo-acknowledgements.markdown", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "1441544" }, { "name": "Ruby", "bytes": "1501" }, { "name": "Shell", "bytes": "20552" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ Copyright (c) 2010-2017 Evolveum ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ you may not use this file except in compliance with the License. ~ You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, software ~ distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the License for the specific language governing permissions and ~ limitations under the License. --> <!-- This file is an example of Password Policy definition. --> <objects xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3"> <valuePolicy oid="81818181-76e0-59e2-8888-3d4f02d3fffd" xsi:type="c:ValuePolicyType" version="0" xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3" xmlns:c="http://midpoint.evolveum.com/xml/ns/public/common/common-3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <name>Alphanumeric Password Policy</name> <description>Alphanumeric Password policy requires at least one lowercase letter and at least one digit in the password, no special characters are allowed.</description> <lifetime> <expiration>999</expiration> <warnBeforeExpiration>9</warnBeforeExpiration> <lockAfterExpiration>0</lockAfterExpiration> <minPasswordAge>0</minPasswordAge> <passwordHistoryLength>0</passwordHistoryLength> </lifetime> <stringPolicy> <description>String validation policy</description> <limitations> <minLength>4</minLength> <maxLength>32</maxLength> <minUniqueChars>3</minUniqueChars> <!-- not implemented yet <checkAgainstDictionary>true</checkAgainstDictionary> --> <checkPattern /> <limit> <description>Lowercase alphanumeric characters</description> <minOccurs>1</minOccurs> <mustBeFirst>false</mustBeFirst> <characterClass> <value>abcdefghijklmnopqrstuvwxyz</value> </characterClass> </limit> <limit> <description>Uppercase alphanumeric characters</description> <minOccurs>0</minOccurs> <mustBeFirst>false</mustBeFirst> <characterClass> <value>ABCDEFGHIJKLMNOPQRSTUVWXYZ</value> </characterClass> </limit> <limit> <description>Numeric characters</description> <minOccurs>1</minOccurs> <mustBeFirst>false</mustBeFirst> <characterClass> <value>1234567890</value> </characterClass> </limit> </limitations> </stringPolicy> </valuePolicy> </objects>
{ "content_hash": "f44a1b17053cd4d125766bb1b792b49b", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 233, "avg_line_length": 33.43589743589744, "alnum_prop": 0.7289110429447853, "repo_name": "arnost-starosta/midpoint", "id": "0f03dbca2eadcdcfd25e7a277756f0f34a86fb7b", "size": "2608", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "samples/policy/value-policy/alphanumeric-password-policy.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "360626" }, { "name": "CSS", "bytes": "246079" }, { "name": "HTML", "bytes": "1906400" }, { "name": "Java", "bytes": "33331059" }, { "name": "JavaScript", "bytes": "18450" }, { "name": "PLSQL", "bytes": "212132" }, { "name": "PLpgSQL", "bytes": "9834" }, { "name": "Perl", "bytes": "13072" }, { "name": "Shell", "bytes": "52" } ], "symlink_target": "" }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.connector.informationschema; import io.prestosql.spi.connector.ColumnHandle; import io.prestosql.spi.connector.ConnectorHandleResolver; import io.prestosql.spi.connector.ConnectorSplit; import io.prestosql.spi.connector.ConnectorTableHandle; import io.prestosql.spi.connector.ConnectorTransactionHandle; public class InformationSchemaHandleResolver implements ConnectorHandleResolver { @Override public Class<? extends ConnectorTableHandle> getTableHandleClass() { return InformationSchemaTableHandle.class; } @Override public Class<? extends ColumnHandle> getColumnHandleClass() { return InformationSchemaColumnHandle.class; } @Override public Class<? extends ConnectorSplit> getSplitClass() { return InformationSchemaSplit.class; } @Override public Class<? extends ConnectorTransactionHandle> getTransactionHandleClass() { return InformationSchemaTransactionHandle.class; } }
{ "content_hash": "1c635f87af9fb0af2563683602a67caf", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 82, "avg_line_length": 32.708333333333336, "alnum_prop": 0.7547770700636943, "repo_name": "treasure-data/presto", "id": "3a3943aa33057c443eb5d6b4df8f0ec18a009e35", "size": "1570", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "presto-main/src/main/java/io/prestosql/connector/informationschema/InformationSchemaHandleResolver.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "30916" }, { "name": "CSS", "bytes": "17830" }, { "name": "Dockerfile", "bytes": "1490" }, { "name": "Groovy", "bytes": "1547" }, { "name": "HTML", "bytes": "24210" }, { "name": "Java", "bytes": "42427369" }, { "name": "JavaScript", "bytes": "219883" }, { "name": "PLSQL", "bytes": "85" }, { "name": "Python", "bytes": "9315" }, { "name": "Ruby", "bytes": "4592" }, { "name": "Shell", "bytes": "33906" }, { "name": "Thrift", "bytes": "12598" } ], "symlink_target": "" }
docker stop bsimm-web & echo "Creating Docker image for BSIMM-Graph" docker build -t bsimm-graph ./docker-images/1.base-image/. docker build -t bsimm-graph ./docker-images/2.git-pull/. echo "Stopping bsimm-web container" docker rm bsimm-web docker run --name bsimm-web -it -p 3000:3000 -d bsimm-graph #open http://192.168.99.100:3000 docker ps
{ "content_hash": "0405a63ba363c2366666996c77f02ef4", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 59, "avg_line_length": 21.9375, "alnum_prop": 0.7378917378917379, "repo_name": "DinisCruz/BSIMM-Graphs", "id": "eedbc43c5f8c21a0f208e83bfde55f43f5de5e76", "size": "408", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "deploy/docker-images/build.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CoffeeScript", "bytes": "29121" }, { "name": "HTML", "bytes": "7477" }, { "name": "JavaScript", "bytes": "552" }, { "name": "Shell", "bytes": "196" } ], "symlink_target": "" }
#include "graphics3d.h" #include "simple_logger.h" #include "shader.h" static SDL_GLContext __graphics3d_gl_context; static SDL_Window * __graphics3d_window = NULL; static GLuint __graphics3d_shader_program; static Uint32 __graphics3d_frame_delay = 33; void graphics3d_close(); GLuint graphics3d_get_shader_program() { return __graphics3d_shader_program; } void graphics3d_next_frame() { static Uint32 then = 0; Uint32 now; SDL_GL_SwapWindow(__graphics3d_window); now = SDL_GetTicks(); if ((now - then) < __graphics3d_frame_delay) { SDL_Delay(__graphics3d_frame_delay - (now - then)); } then = now; } int graphics3d_init(int sw,int sh,int fullscreen,const char *project,Uint32 frameDelay) { const unsigned char *version; GLenum glew_status; if (SDL_Init(SDL_INIT_VIDEO) < 0) { slog("failed to initialize SDL!"); return -1; } atexit(SDL_Quit); __graphics3d_frame_delay = frameDelay; __graphics3d_window = SDL_CreateWindow(project?project:"gametest3d", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, sw, sh, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL); __graphics3d_gl_context = SDL_GL_CreateContext(__graphics3d_window); if (__graphics3d_gl_context == NULL) { slog("There was an error creating the OpenGL context!\n"); return -1; } version = glGetString(GL_VERSION); if (version == NULL) { slog("There was an error creating the OpenGL context!\n"); return -1; } SDL_GL_MakeCurrent(__graphics3d_window, __graphics3d_gl_context); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); //MUST make a context AND make it current BEFORE glewInit()! glewExperimental = GL_TRUE; glew_status = glewInit(); if (glew_status != 0) { slog("Error: %s", glewGetErrorString(glew_status)); return -1; } //__graphics3d_shader_program = BuildShaderProgram("shaders/vs1.glsl", "shaders/fs1.glsl"); if (__graphics3d_shader_program == -1) { return -1; } slog("Using program %d", __graphics3d_shader_program); atexit(graphics3d_close); return 0; } void graphics3d_close() { SDL_GL_DeleteContext(__graphics3d_gl_context); } /*eol@eof*/
{ "content_hash": "d437e1b4d9dd23e24b081a187cc39b7a", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 95, "avg_line_length": 26.09278350515464, "alnum_prop": 0.5958119320426709, "repo_name": "mtl23/test", "id": "0fe368ebde3d7b5453a1d60b8b4c73df89f7f8c3", "size": "2531", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/graphics3d.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1093828" }, { "name": "C++", "bytes": "1892603" }, { "name": "GLSL", "bytes": "1674" }, { "name": "Makefile", "bytes": "1484" } ], "symlink_target": "" }
/* Includes ------------------------------------------------------------------*/ #include "stm32f4_discovery.h" /** @addtogroup BSP * @{ */ /** @addtogroup STM32F4_DISCOVERY * @{ */ /** @defgroup STM32F4_DISCOVERY_LOW_LEVEL * @brief This file provides set of firmware functions to manage Leds and push-button * available on STM32F4-Discovery Kit from STMicroelectronics. * @{ */ /** @defgroup STM32F4_DISCOVERY_LOW_LEVEL_Private_TypesDefinitions * @{ */ /** * @} */ /** @defgroup STM32F4_DISCOVERY_LOW_LEVEL_Private_Defines * @{ */ /** * @brief STM32F4 DISCO BSP Driver version number V2.0.4 */ #define __STM32F4_DISCO_BSP_VERSION_MAIN (0x02) /*!< [31:24] main version */ #define __STM32F4_DISCO_BSP_VERSION_SUB1 (0x00) /*!< [23:16] sub1 version */ #define __STM32F4_DISCO_BSP_VERSION_SUB2 (0x04) /*!< [15:8] sub2 version */ #define __STM32F4_DISCO_BSP_VERSION_RC (0x00) /*!< [7:0] release candidate */ #define __STM32F4_DISCO_BSP_VERSION ((__STM32F4_DISCO_BSP_VERSION_MAIN << 24)\ |(__STM32F4_DISCO_BSP_VERSION_SUB1 << 16)\ |(__STM32F4_DISCO_BSP_VERSION_SUB2 << 8 )\ |(__STM32F4_DISCO_BSP_VERSION_RC)) /** * @} */ /** @defgroup STM32F4_DISCOVERY_LOW_LEVEL_Private_Macros * @{ */ /** * @} */ /** @defgroup STM32F4_DISCOVERY_LOW_LEVEL_Private_Variables * @{ */ GPIO_TypeDef* GPIO_PORT[LEDn] = {LED4_GPIO_PORT, LED3_GPIO_PORT, LED5_GPIO_PORT, LED6_GPIO_PORT}; const uint16_t GPIO_PIN[LEDn] = {LED4_PIN, LED3_PIN, LED5_PIN, LED6_PIN}; GPIO_TypeDef* BUTTON_PORT[BUTTONn] = {KEY_BUTTON_GPIO_PORT}; const uint16_t BUTTON_PIN[BUTTONn] = {KEY_BUTTON_PIN}; const uint8_t BUTTON_IRQn[BUTTONn] = {KEY_BUTTON_EXTI_IRQn}; uint32_t I2cxTimeout = I2Cx_TIMEOUT_MAX; /*<! Value of Timeout when I2C communication fails */ uint32_t SpixTimeout = SPIx_TIMEOUT_MAX; /*<! Value of Timeout when SPI communication fails */ static SPI_HandleTypeDef SpiHandle; static I2C_HandleTypeDef I2cHandle; /** * @} */ /** @defgroup STM32F4_DISCOVERY_LOW_LEVEL_Private_FunctionPrototypes * @{ */ /** * @} */ /** @defgroup STM32F4_DISCOVERY_LOW_LEVEL_Private_Functions * @{ */ static void I2Cx_Init(void); static void I2Cx_WriteData(uint8_t Addr, uint8_t Reg, uint8_t Value); static uint8_t I2Cx_ReadData(uint8_t Addr, uint8_t Reg); static void I2Cx_MspInit(void); static void I2Cx_Error(uint8_t Addr); static void SPIx_Init(void); static void SPIx_MspInit(void); static uint8_t SPIx_WriteRead(uint8_t Byte); static void SPIx_Error(void); /* Link functions for Accelerometer peripheral */ void ACCELERO_IO_Init(void); void ACCELERO_IO_ITConfig(void); void ACCELERO_IO_Write(uint8_t *pBuffer, uint8_t WriteAddr, uint16_t NumByteToWrite); void ACCELERO_IO_Read(uint8_t *pBuffer, uint8_t ReadAddr, uint16_t NumByteToRead); /* Link functions for Audio peripheral */ void AUDIO_IO_Init(void); void AUDIO_IO_Write(uint8_t Addr, uint8_t Reg, uint8_t Value); uint8_t AUDIO_IO_Read(uint8_t Addr, uint8_t Reg); /** * @} */ /** @defgroup STM32F4_DISCOVERY_LOW_LEVEL_LED_Functions * @{ */ /** * @brief This method returns the STM32F4 DISCO BSP Driver revision * @param None * @retval version : 0xXYZR (8bits for each decimal, R for RC) */ uint32_t BSP_GetVersion(void) { return __STM32F4_DISCO_BSP_VERSION; } /** * @brief Configures LED GPIO. * @param Led: Specifies the Led to be configured. * This parameter can be one of following parameters: * @arg LED4 * @arg LED3 * @arg LED5 * @arg LED6 * @retval None */ void BSP_LED_Init(Led_TypeDef Led) { GPIO_InitTypeDef GPIO_InitStruct; /* Enable the GPIO_LED Clock */ LEDx_GPIO_CLK_ENABLE(Led); /* Configure the GPIO_LED pin */ GPIO_InitStruct.Pin = GPIO_PIN[Led]; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_PULLUP; GPIO_InitStruct.Speed = GPIO_SPEED_FAST; HAL_GPIO_Init(GPIO_PORT[Led], &GPIO_InitStruct); HAL_GPIO_WritePin(GPIO_PORT[Led], GPIO_PIN[Led], GPIO_PIN_RESET); } /** * @brief Turns selected LED On. * @param Led: Specifies the Led to be set on. * This parameter can be one of following parameters: * @arg LED4 * @arg LED3 * @arg LED5 * @arg LED6 * @retval None */ void BSP_LED_On(Led_TypeDef Led) { HAL_GPIO_WritePin(GPIO_PORT[Led], GPIO_PIN[Led], GPIO_PIN_SET); } /** * @brief Turns selected LED Off. * @param Led: Specifies the Led to be set off. * This parameter can be one of following parameters: * @arg LED4 * @arg LED3 * @arg LED5 * @arg LED6 * @retval None */ void BSP_LED_Off(Led_TypeDef Led) { HAL_GPIO_WritePin(GPIO_PORT[Led], GPIO_PIN[Led], GPIO_PIN_RESET); } /** * @brief Toggles the selected LED. * @param Led: Specifies the Led to be toggled. * This parameter can be one of following parameters: * @arg LED4 * @arg LED3 * @arg LED5 * @arg LED6 * @retval None */ void BSP_LED_Toggle(Led_TypeDef Led) { HAL_GPIO_TogglePin(GPIO_PORT[Led], GPIO_PIN[Led]); } /** * @} */ /** @defgroup STM32F4_DISCOVERY_LOW_LEVEL_BUTTON_Functions * @{ */ /** * @brief Configures Button GPIO and EXTI Line. * @param Button: Specifies the Button to be configured. * This parameter should be: BUTTON_KEY * @param Mode: Specifies Button mode. * This parameter can be one of following parameters: * @arg BUTTON_MODE_GPIO: Button will be used as simple IO * @arg BUTTON_MODE_EXTI: Button will be connected to EXTI line with interrupt * generation capability * @retval None */ void BSP_PB_Init(Button_TypeDef Button, ButtonMode_TypeDef Mode) { GPIO_InitTypeDef GPIO_InitStruct; /* Enable the BUTTON Clock */ BUTTONx_GPIO_CLK_ENABLE(Button); if (Mode == BUTTON_MODE_GPIO) { /* Configure Button pin as input */ GPIO_InitStruct.Pin = BUTTON_PIN[Button]; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FAST; HAL_GPIO_Init(BUTTON_PORT[Button], &GPIO_InitStruct); } if (Mode == BUTTON_MODE_EXTI) { /* Configure Button pin as input with External interrupt */ GPIO_InitStruct.Pin = BUTTON_PIN[Button]; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FAST; GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING; HAL_GPIO_Init(BUTTON_PORT[Button], &GPIO_InitStruct); /* Enable and set Button EXTI Interrupt to the lowest priority */ HAL_NVIC_SetPriority((IRQn_Type)(BUTTON_IRQn[Button]), 0x0F, 0); HAL_NVIC_EnableIRQ((IRQn_Type)(BUTTON_IRQn[Button])); } } /** * @brief Returns the selected Button state. * @param Button: Specifies the Button to be checked. * This parameter should be: BUTTON_KEY * @retval The Button GPIO pin value. */ uint32_t BSP_PB_GetState(Button_TypeDef Button) { return HAL_GPIO_ReadPin(BUTTON_PORT[Button], BUTTON_PIN[Button]); } /** * @} */ /** @defgroup STM32F4_DISCOVERY_LOW_LEVEL_BUS_Functions * @{ */ /******************************************************************************* BUS OPERATIONS *******************************************************************************/ /******************************* SPI Routines *********************************/ /** * @brief SPIx Bus initialization * @param None * @retval None */ static void SPIx_Init(void) { if(HAL_SPI_GetState(&SpiHandle) == HAL_SPI_STATE_RESET) { /* SPI configuration -----------------------------------------------------*/ SpiHandle.Instance = DISCOVERY_SPIx; SpiHandle.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16; SpiHandle.Init.Direction = SPI_DIRECTION_2LINES; SpiHandle.Init.CLKPhase = SPI_PHASE_1EDGE; SpiHandle.Init.CLKPolarity = SPI_POLARITY_LOW; SpiHandle.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLED; SpiHandle.Init.CRCPolynomial = 7; SpiHandle.Init.DataSize = SPI_DATASIZE_8BIT; SpiHandle.Init.FirstBit = SPI_FIRSTBIT_MSB; SpiHandle.Init.NSS = SPI_NSS_SOFT; SpiHandle.Init.TIMode = SPI_TIMODE_DISABLED; SpiHandle.Init.Mode = SPI_MODE_MASTER; SPIx_MspInit(); HAL_SPI_Init(&SpiHandle); } } /** * @brief Sends a Byte through the SPI interface and return the Byte received * from the SPI bus. * @param Byte: Byte send. * @retval The received byte value */ static uint8_t SPIx_WriteRead(uint8_t Byte) { uint8_t receivedbyte = 0; /* Send a Byte through the SPI peripheral */ /* Read byte from the SPI bus */ if(HAL_SPI_TransmitReceive(&SpiHandle, (uint8_t*) &Byte, (uint8_t*) &receivedbyte, 1, SpixTimeout) != HAL_OK) { SPIx_Error(); } return receivedbyte; } /** * @brief SPIx error treatment function. * @param None * @retval None */ static void SPIx_Error(void) { /* De-initialize the SPI communication bus */ HAL_SPI_DeInit(&SpiHandle); /* Re-Initialize the SPI communication bus */ SPIx_Init(); } /** * @brief SPI MSP Init. * @param hspi: SPI handle * @retval None */ static void SPIx_MspInit(void) { GPIO_InitTypeDef GPIO_InitStructure; /* Enable the SPI peripheral */ DISCOVERY_SPIx_CLK_ENABLE(); /* Enable SCK, MOSI and MISO GPIO clocks */ DISCOVERY_SPIx_GPIO_CLK_ENABLE(); /* SPI SCK, MOSI, MISO pin configuration */ GPIO_InitStructure.Pin = (DISCOVERY_SPIx_SCK_PIN | DISCOVERY_SPIx_MISO_PIN | DISCOVERY_SPIx_MOSI_PIN); GPIO_InitStructure.Mode = GPIO_MODE_AF_PP; GPIO_InitStructure.Pull = GPIO_PULLDOWN; GPIO_InitStructure.Speed = GPIO_SPEED_MEDIUM; GPIO_InitStructure.Alternate = DISCOVERY_SPIx_AF; HAL_GPIO_Init(DISCOVERY_SPIx_GPIO_PORT, &GPIO_InitStructure); } /******************************* I2C Routines**********************************/ /** * @brief Configures I2C interface. * @param None * @retval None */ static void I2Cx_Init(void) { if(HAL_I2C_GetState(&I2cHandle) == HAL_I2C_STATE_RESET) { /* DISCOVERY_I2Cx peripheral configuration */ I2cHandle.Init.ClockSpeed = BSP_I2C_SPEED; I2cHandle.Init.DutyCycle = I2C_DUTYCYCLE_2; I2cHandle.Init.OwnAddress1 = 0x33; I2cHandle.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT; I2cHandle.Instance = DISCOVERY_I2Cx; /* Init the I2C */ I2Cx_MspInit(); HAL_I2C_Init(&I2cHandle); } } /** * @brief Write a value in a register of the device through BUS. * @param Addr: Device address on BUS Bus. * @param Reg: The target register address to write * @param Value: The target register value to be written * @retval HAL status */ static void I2Cx_WriteData(uint8_t Addr, uint8_t Reg, uint8_t Value) { HAL_StatusTypeDef status = HAL_OK; status = HAL_I2C_Mem_Write(&I2cHandle, Addr, (uint16_t)Reg, I2C_MEMADD_SIZE_8BIT, &Value, 1, I2cxTimeout); /* Check the communication status */ if(status != HAL_OK) { /* Execute user timeout callback */ I2Cx_Error(Addr); } } /** * @brief Read a register of the device through BUS * @param Addr: Device address on BUS * @param Reg: The target register address to read * @retval HAL status */ static uint8_t I2Cx_ReadData(uint8_t Addr, uint8_t Reg) { HAL_StatusTypeDef status = HAL_OK; uint8_t value = 0; status = HAL_I2C_Mem_Read(&I2cHandle, Addr, (uint16_t)Reg, I2C_MEMADD_SIZE_8BIT, &value, 1,I2cxTimeout); /* Check the communication status */ if(status != HAL_OK) { /* Execute user timeout callback */ I2Cx_Error(Addr); } return value; } /** * @brief Manages error callback by re-initializing I2C. * @param Addr: I2C Address * @retval None */ static void I2Cx_Error(uint8_t Addr) { /* De-initialize the I2C communication bus */ HAL_I2C_DeInit(&I2cHandle); /* Re-Initialize the I2C communication bus */ I2Cx_Init(); } /** * @brief I2C MSP Initialization * @param None * @retval None */ static void I2Cx_MspInit(void) { GPIO_InitTypeDef GPIO_InitStruct; /* Enable I2C GPIO clocks */ DISCOVERY_I2Cx_SCL_SDA_GPIO_CLK_ENABLE(); /* DISCOVERY_I2Cx SCL and SDA pins configuration ---------------------------*/ GPIO_InitStruct.Pin = DISCOVERY_I2Cx_SCL_PIN | DISCOVERY_I2Cx_SDA_PIN; GPIO_InitStruct.Mode = GPIO_MODE_AF_OD; GPIO_InitStruct.Speed = GPIO_SPEED_FAST; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Alternate = DISCOVERY_I2Cx_SCL_SDA_AF; HAL_GPIO_Init(DISCOVERY_I2Cx_SCL_SDA_GPIO_PORT, &GPIO_InitStruct); /* Enable the DISCOVERY_I2Cx peripheral clock */ DISCOVERY_I2Cx_CLK_ENABLE(); /* Force the I2C peripheral clock reset */ DISCOVERY_I2Cx_FORCE_RESET(); /* Release the I2C peripheral clock reset */ DISCOVERY_I2Cx_RELEASE_RESET(); /* Enable and set I2Cx Interrupt to the highest priority */ HAL_NVIC_SetPriority(DISCOVERY_I2Cx_EV_IRQn, 0, 0); HAL_NVIC_EnableIRQ(DISCOVERY_I2Cx_EV_IRQn); /* Enable and set I2Cx Interrupt to the highest priority */ HAL_NVIC_SetPriority(DISCOVERY_I2Cx_ER_IRQn, 0, 0); HAL_NVIC_EnableIRQ(DISCOVERY_I2Cx_ER_IRQn); } /******************************************************************************* LINK OPERATIONS *******************************************************************************/ /***************************** LINK ACCELEROMETER *****************************/ /** * @brief Configures the Accelerometer SPI interface. * @param None * @retval None */ void ACCELERO_IO_Init(void) { GPIO_InitTypeDef GPIO_InitStructure; /* Configure the Accelerometer Control pins --------------------------------*/ /* Enable CS GPIO clock and configure GPIO pin for Accelerometer Chip select */ ACCELERO_CS_GPIO_CLK_ENABLE(); /* Configure GPIO PIN for LIS Chip select */ GPIO_InitStructure.Pin = ACCELERO_CS_PIN; GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStructure.Pull = GPIO_NOPULL; GPIO_InitStructure.Speed = GPIO_SPEED_MEDIUM; HAL_GPIO_Init(ACCELERO_CS_GPIO_PORT, &GPIO_InitStructure); /* Deselect: Chip Select high */ ACCELERO_CS_HIGH(); SPIx_Init(); } /** * @brief Configures the Accelerometer INT2. * EXTI0 is already used by user button so INT1 is not configured here. * @param None * @retval None */ void ACCELERO_IO_ITConfig(void) { GPIO_InitTypeDef GPIO_InitStructure; /* Enable INT2 GPIO clock and configure GPIO PINs to detect Interrupts */ ACCELERO_INT_GPIO_CLK_ENABLE(); /* Configure GPIO PINs to detect Interrupts */ GPIO_InitStructure.Pin = ACCELERO_INT2_PIN; GPIO_InitStructure.Mode = GPIO_MODE_IT_RISING; GPIO_InitStructure.Speed = GPIO_SPEED_FAST; GPIO_InitStructure.Pull = GPIO_NOPULL; HAL_GPIO_Init(ACCELERO_INT_GPIO_PORT, &GPIO_InitStructure); /* Enable and set Accelerometer INT2 to the lowest priority */ HAL_NVIC_SetPriority((IRQn_Type)ACCELERO_INT2_EXTI_IRQn, 0x0F, 0); HAL_NVIC_EnableIRQ((IRQn_Type)ACCELERO_INT2_EXTI_IRQn); } /** * @brief Writes one byte to the Accelerometer. * @param pBuffer: pointer to the buffer containing the data to be written to the Accelerometer. * @param WriteAddr: Accelerometer's internal address to write to. * @param NumByteToWrite: Number of bytes to write. * @retval None */ void ACCELERO_IO_Write(uint8_t *pBuffer, uint8_t WriteAddr, uint16_t NumByteToWrite) { /* Configure the MS bit: - When 0, the address will remain unchanged in multiple read/write commands. - When 1, the address will be auto incremented in multiple read/write commands. */ if(NumByteToWrite > 0x01) { WriteAddr |= (uint8_t)MULTIPLEBYTE_CMD; } /* Set chip select Low at the start of the transmission */ ACCELERO_CS_LOW(); /* Send the Address of the indexed register */ SPIx_WriteRead(WriteAddr); /* Send the data that will be written into the device (MSB First) */ while(NumByteToWrite >= 0x01) { SPIx_WriteRead(*pBuffer); NumByteToWrite--; pBuffer++; } /* Set chip select High at the end of the transmission */ ACCELERO_CS_HIGH(); } /** * @brief Reads a block of data from the Accelerometer. * @param pBuffer: pointer to the buffer that receives the data read from the Accelerometer. * @param ReadAddr: Accelerometer's internal address to read from. * @param NumByteToRead: number of bytes to read from the Accelerometer. * @retval None */ void ACCELERO_IO_Read(uint8_t *pBuffer, uint8_t ReadAddr, uint16_t NumByteToRead) { if(NumByteToRead > 0x01) { ReadAddr |= (uint8_t)(READWRITE_CMD | MULTIPLEBYTE_CMD); } else { ReadAddr |= (uint8_t)READWRITE_CMD; } /* Set chip select Low at the start of the transmission */ ACCELERO_CS_LOW(); /* Send the Address of the indexed register */ SPIx_WriteRead(ReadAddr); /* Receive the data that will be read from the device (MSB First) */ while(NumByteToRead > 0x00) { /* Send dummy byte (0x00) to generate the SPI clock to ACCELEROMETER (Slave device) */ *pBuffer = SPIx_WriteRead(DUMMY_BYTE); NumByteToRead--; pBuffer++; } /* Set chip select High at the end of the transmission */ ACCELERO_CS_HIGH(); } /********************************* LINK AUDIO *********************************/ /** * @brief Initializes Audio low level. * @param None * @retval None */ void AUDIO_IO_Init(void) { GPIO_InitTypeDef GPIO_InitStruct; /* Enable Reset GPIO Clock */ AUDIO_RESET_GPIO_CLK_ENABLE(); /* Audio reset pin configuration */ GPIO_InitStruct.Pin = AUDIO_RESET_PIN; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Speed = GPIO_SPEED_FAST; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(AUDIO_RESET_GPIO, &GPIO_InitStruct); I2Cx_Init(); /* Power Down the codec */ HAL_GPIO_WritePin(AUDIO_RESET_GPIO, AUDIO_RESET_PIN, GPIO_PIN_RESET); /* Wait for a delay to insure registers erasing */ HAL_Delay(5); /* Power on the codec */ HAL_GPIO_WritePin(AUDIO_RESET_GPIO, AUDIO_RESET_PIN, GPIO_PIN_SET); /* Wait for a delay to insure registers erasing */ HAL_Delay(5); } /** * @brief Writes a single data. * @param Addr: I2C address * @param Reg: Reg address * @param Value: Data to be written * @retval None */ void AUDIO_IO_Write (uint8_t Addr, uint8_t Reg, uint8_t Value) { I2Cx_WriteData(Addr, Reg, Value); } /** * @brief Reads a single data. * @param Addr: I2C address * @param Reg: Reg address * @retval Data to be read */ uint8_t AUDIO_IO_Read(uint8_t Addr, uint8_t Reg) { return I2Cx_ReadData(Addr, Reg); } /** * @} */ /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
{ "content_hash": "2e4cf9072e92e4549aaae93485433004", "timestamp": "", "source": "github", "line_count": 684, "max_line_length": 111, "avg_line_length": 29.058479532163744, "alnum_prop": 0.6015294827933185, "repo_name": "matianfu/stm32f4cube", "id": "9241d5eb30a471183f2d6ec8327ac57e05271be7", "size": "22077", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "Drivers/BSP/STM32F4-Discovery/stm32f4_discovery.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "6084165" }, { "name": "C", "bytes": "39072064" }, { "name": "C++", "bytes": "863728" }, { "name": "CMake", "bytes": "10718" }, { "name": "CSS", "bytes": "7146" }, { "name": "HTML", "bytes": "2039955" }, { "name": "Makefile", "bytes": "22025" }, { "name": "Objective-C", "bytes": "1848" }, { "name": "Perl", "bytes": "17688" }, { "name": "Shell", "bytes": "23874" }, { "name": "Tcl", "bytes": "72" } ], "symlink_target": "" }
'use strict'; var React = require('react'); var ReactNative = require('react-native'); var { Navigator, StyleSheet, ScrollView, TabBarIOS, Text, TouchableHighlight, View, } = ReactNative; var _getRandomRoute = function() { return { randNumber: Math.ceil(Math.random() * 1000), }; }; class NavButton extends React.Component { render() { return ( <TouchableHighlight style={styles.button} underlayColor="#B5B5B5" onPress={this.props.onPress}> <Text style={styles.buttonText}>{this.props.text}</Text> </TouchableHighlight> ); } } var ROUTE_STACK = [ _getRandomRoute(), _getRandomRoute(), _getRandomRoute(), ]; var INIT_ROUTE_INDEX = 1; class JumpingNavBar extends React.Component { constructor(props) { super(props); this.state = { tabIndex: props.initTabIndex, }; } handleWillFocus(route) { var tabIndex = ROUTE_STACK.indexOf(route); this.setState({ tabIndex, }); } render() { return ( <View style={styles.tabs}> <TabBarIOS> <TabBarIOS.Item icon={require('image!tabnav_notification')} selected={this.state.tabIndex === 0} onPress={() => { this.props.onTabIndex(0); this.setState({ tabIndex: 0, }); }}> <View /> </TabBarIOS.Item> <TabBarIOS.Item icon={require('image!tabnav_list')} selected={this.state.tabIndex === 1} onPress={() => { this.props.onTabIndex(1); this.setState({ tabIndex: 1, }); }}> <View /> </TabBarIOS.Item> <TabBarIOS.Item icon={require('image!tabnav_settings')} selected={this.state.tabIndex === 2} onPress={() => { this.props.onTabIndex(2); this.setState({ tabIndex: 2, }); }}> <View /> </TabBarIOS.Item> </TabBarIOS> </View> ); } } class JumpingNavSample extends React.Component { render() { return ( <Navigator debugOverlay={false} style={styles.appContainer} ref={(navigator) => { this._navigator = navigator; }} initialRoute={ROUTE_STACK[INIT_ROUTE_INDEX]} initialRouteStack={ROUTE_STACK} renderScene={this.renderScene} configureScene={() => ({ ...Navigator.SceneConfigs.HorizontalSwipeJump, })} navigationBar={ <JumpingNavBar ref={(navBar) => { this.navBar = navBar; }} initTabIndex={INIT_ROUTE_INDEX} routeStack={ROUTE_STACK} onTabIndex={(index) => { this._navigator.jumpTo(ROUTE_STACK[index]); }} /> } /> ); } renderScene = (route, navigator) => { var backBtn; var forwardBtn; if (ROUTE_STACK.indexOf(route) !== 0) { backBtn = ( <NavButton onPress={() => { navigator.jumpBack(); }} text="jumpBack" /> ); } if (ROUTE_STACK.indexOf(route) !== ROUTE_STACK.length - 1) { forwardBtn = ( <NavButton onPress={() => { navigator.jumpForward(); }} text="jumpForward" /> ); } return ( <ScrollView style={styles.scene}> <Text style={styles.messageText}>#{route.randNumber}</Text> {backBtn} {forwardBtn} <NavButton onPress={() => { navigator.jumpTo(ROUTE_STACK[1]); }} text="jumpTo middle route" /> <NavButton onPress={() => { this.props.navigator.pop(); }} text="Exit Navigation Example" /> <NavButton onPress={() => { this.props.navigator.push({ message: 'Came from jumping example', }); }} text="Nav Menu" /> </ScrollView> ); }; } var styles = StyleSheet.create({ button: { backgroundColor: 'white', padding: 15, borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: '#CDCDCD', }, buttonText: { fontSize: 17, fontWeight: '500', }, appContainer: { overflow: 'hidden', backgroundColor: '#dddddd', flex: 1, }, messageText: { fontSize: 17, fontWeight: '500', padding: 15, marginTop: 50, marginLeft: 15, }, scene: { flex: 1, paddingTop: 20, backgroundColor: '#EAEAEA', }, tabs: { height: 50, } }); module.exports = JumpingNavSample;
{ "content_hash": "fe08388da1039c50b5867e2714c1a1e9", "timestamp": "", "source": "github", "line_count": 205, "max_line_length": 67, "avg_line_length": 22.82439024390244, "alnum_prop": 0.5137849967941868, "repo_name": "catalinmiron/react-native", "id": "4cb876aa9d8cbafbfa7ddfce19ed5d84d2152cfd", "size": "5607", "binary": false, "copies": "13", "ref": "refs/heads/master", "path": "Examples/UIExplorer/js/Navigator/JumpingNavSample.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "15592" }, { "name": "Awk", "bytes": "121" }, { "name": "Batchfile", "bytes": "683" }, { "name": "C", "bytes": "119585" }, { "name": "C++", "bytes": "570956" }, { "name": "CSS", "bytes": "27709" }, { "name": "HTML", "bytes": "28315" }, { "name": "IDL", "bytes": "897" }, { "name": "Java", "bytes": "2311786" }, { "name": "JavaScript", "bytes": "2228587" }, { "name": "Makefile", "bytes": "6244" }, { "name": "Objective-C", "bytes": "1348435" }, { "name": "Objective-C++", "bytes": "63037" }, { "name": "Prolog", "bytes": "287" }, { "name": "Python", "bytes": "112448" }, { "name": "Ruby", "bytes": "5001" }, { "name": "Shell", "bytes": "16398" } ], "symlink_target": "" }
.. BSD LICENSE Copyright(c) 2016 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Cryptography Device Library =========================== The cryptodev library provides a Crypto device framework for management and provisioning of hardware and software Crypto poll mode drivers, defining generic APIs which support a number of different Crypto operations. The framework currently only supports cipher, authentication, chained cipher/authentication and AEAD symmetric Crypto operations. Design Principles ----------------- The cryptodev library follows the same basic principles as those used in DPDKs Ethernet Device framework. The Crypto framework provides a generic Crypto device framework which supports both physical (hardware) and virtual (software) Crypto devices as well as a generic Crypto API which allows Crypto devices to be managed and configured and supports Crypto operations to be provisioned on Crypto poll mode driver. Device Management ----------------- Device Creation ~~~~~~~~~~~~~~~ Physical Crypto devices are discovered during the PCI probe/enumeration of the EAL function which is executed at DPDK initialization, based on their PCI device identifier, each unique PCI BDF (bus/bridge, device, function). Specific physical Crypto devices, like other physical devices in DPDK can be white-listed or black-listed using the EAL command line options. Virtual devices can be created by two mechanisms, either using the EAL command line options or from within the application using an EAL API directly. From the command line using the --vdev EAL option .. code-block:: console --vdev 'cryptodev_aesni_mb_pmd0,max_nb_queue_pairs=2,max_nb_sessions=1024,socket_id=0' Our using the rte_eal_vdev_init API within the application code. .. code-block:: c rte_eal_vdev_init("cryptodev_aesni_mb_pmd", "max_nb_queue_pairs=2,max_nb_sessions=1024,socket_id=0") All virtual Crypto devices support the following initialization parameters: * ``max_nb_queue_pairs`` - maximum number of queue pairs supported by the device. * ``max_nb_sessions`` - maximum number of sessions supported by the device * ``socket_id`` - socket on which to allocate the device resources on. Device Identification ~~~~~~~~~~~~~~~~~~~~~ Each device, whether virtual or physical is uniquely designated by two identifiers: - A unique device index used to designate the Crypto device in all functions exported by the cryptodev API. - A device name used to designate the Crypto device in console messages, for administration or debugging purposes. For ease of use, the port name includes the port index. Device Configuration ~~~~~~~~~~~~~~~~~~~~ The configuration of each Crypto device includes the following operations: - Allocation of resources, including hardware resources if a physical device. - Resetting the device into a well-known default state. - Initialization of statistics counters. The rte_cryptodev_configure API is used to configure a Crypto device. .. code-block:: c int rte_cryptodev_configure(uint8_t dev_id, struct rte_cryptodev_config *config) The ``rte_cryptodev_config`` structure is used to pass the configuration parameters. In contains parameter for socket selection, number of queue pairs and the session mempool configuration. .. code-block:: c struct rte_cryptodev_config { int socket_id; /**< Socket to allocate resources on */ uint16_t nb_queue_pairs; /**< Number of queue pairs to configure on device */ struct { uint32_t nb_objs; uint32_t cache_size; } session_mp; /**< Session mempool configuration */ }; Configuration of Queue Pairs ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Each Crypto devices queue pair is individually configured through the ``rte_cryptodev_queue_pair_setup`` API. Each queue pairs resources may be allocated on a specified socket. .. code-block:: c int rte_cryptodev_queue_pair_setup(uint8_t dev_id, uint16_t queue_pair_id, const struct rte_cryptodev_qp_conf *qp_conf, int socket_id) struct rte_cryptodev_qp_conf { uint32_t nb_descriptors; /**< Number of descriptors per queue pair */ }; Logical Cores, Memory and Queues Pair Relationships ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The Crypto device Library as the Poll Mode Driver library support NUMA for when a processor’s logical cores and interfaces utilize its local memory. Therefore Crypto operations, and in the case of symmetric Crypto operations, the session and the mbuf being operated on, should be allocated from memory pools created in the local memory. The buffers should, if possible, remain on the local processor to obtain the best performance results and buffer descriptors should be populated with mbufs allocated from a mempool allocated from local memory. The run-to-completion model also performs better, especially in the case of virtual Crypto devices, if the Crypto operation and session and data buffer is in local memory instead of a remote processor's memory. This is also true for the pipe-line model provided all logical cores used are located on the same processor. Multiple logical cores should never share the same queue pair for enqueuing operations or dequeuing operations on the same Crypto device since this would require global locks and hinder performance. It is however possible to use a different logical core to dequeue an operation on a queue pair from the logical core which it was enqueued on. This means that a crypto burst enqueue/dequeue APIs are a logical place to transition from one logical core to another in a packet processing pipeline. Device Features and Capabilities --------------------------------- Crypto devices define their functionality through two mechanisms, global device features and algorithm capabilities. Global devices features identify device wide level features which are applicable to the whole device such as the device having hardware acceleration or supporting symmetric Crypto operations, The capabilities mechanism defines the individual algorithms/functions which the device supports, such as a specific symmetric Crypto cipher or authentication operation. Device Features ~~~~~~~~~~~~~~~ Currently the following Crypto device features are defined: * Symmetric Crypto operations * Asymmetric Crypto operations * Chaining of symmetric Crypto operations * SSE accelerated SIMD vector operations * AVX accelerated SIMD vector operations * AVX2 accelerated SIMD vector operations * AESNI accelerated instructions * Hardware off-load processing Device Operation Capabilities ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Crypto capabilities which identify particular algorithm which the Crypto PMD supports are defined by the operation type, the operation transform, the transform identifier and then the particulars of the transform. For the full scope of the Crypto capability see the definition of the structure in the *DPDK API Reference*. .. code-block:: c struct rte_cryptodev_capabilities; Each Crypto poll mode driver defines its own private array of capabilities for the operations it supports. Below is an example of the capabilities for a PMD which supports the authentication algorithm SHA1_HMAC and the cipher algorithm AES_CBC. .. code-block:: c static const struct rte_cryptodev_capabilities pmd_capabilities[] = { { /* SHA1 HMAC */ .op = RTE_CRYPTO_OP_TYPE_SYMMETRIC, .sym = { .xform_type = RTE_CRYPTO_SYM_XFORM_AUTH, .auth = { .algo = RTE_CRYPTO_AUTH_SHA1_HMAC, .block_size = 64, .key_size = { .min = 64, .max = 64, .increment = 0 }, .digest_size = { .min = 12, .max = 12, .increment = 0 }, .aad_size = { 0 } } } }, { /* AES CBC */ .op = RTE_CRYPTO_OP_TYPE_SYMMETRIC, .sym = { .xform_type = RTE_CRYPTO_SYM_XFORM_CIPHER, .cipher = { .algo = RTE_CRYPTO_CIPHER_AES_CBC, .block_size = 16, .key_size = { .min = 16, .max = 32, .increment = 8 }, .iv_size = { .min = 16, .max = 16, .increment = 0 } } } } } Capabilities Discovery ~~~~~~~~~~~~~~~~~~~~~~ Discovering the features and capabilities of a Crypto device poll mode driver is achieved through the ``rte_cryptodev_info_get`` function. .. code-block:: c void rte_cryptodev_info_get(uint8_t dev_id, struct rte_cryptodev_info *dev_info); This allows the user to query a specific Crypto PMD and get all the device features and capabilities. The ``rte_cryptodev_info`` structure contains all the relevant information for the device. .. code-block:: c struct rte_cryptodev_info { const char *driver_name; enum rte_cryptodev_type dev_type; struct rte_pci_device *pci_dev; uint64_t feature_flags; const struct rte_cryptodev_capabilities *capabilities; unsigned max_nb_queue_pairs; struct { unsigned max_nb_sessions; } sym; }; Operation Processing -------------------- Scheduling of Crypto operations on DPDK's application data path is performed using a burst oriented asynchronous API set. A queue pair on a Crypto device accepts a burst of Crypto operations using enqueue burst API. On physical Crypto devices the enqueue burst API will place the operations to be processed on the devices hardware input queue, for virtual devices the processing of the Crypto operations is usually completed during the enqueue call to the Crypto device. The dequeue burst API will retrieve any processed operations available from the queue pair on the Crypto device, from physical devices this is usually directly from the devices processed queue, and for virtual device's from a ``rte_ring`` where processed operations are place after being processed on the enqueue call. Enqueue / Dequeue Burst APIs ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The burst enqueue API uses a Crypto device identifier and a queue pair identifier to specify the Crypto device queue pair to schedule the processing on. The ``nb_ops`` parameter is the number of operations to process which are supplied in the ``ops`` array of ``rte_crypto_op`` structures. The enqueue function returns the number of operations it actually enqueued for processing, a return value equal to ``nb_ops`` means that all packets have been enqueued. .. code-block:: c uint16_t rte_cryptodev_enqueue_burst(uint8_t dev_id, uint16_t qp_id, struct rte_crypto_op **ops, uint16_t nb_ops) The dequeue API uses the same format as the enqueue API of processed but the ``nb_ops`` and ``ops`` parameters are now used to specify the max processed operations the user wishes to retrieve and the location in which to store them. The API call returns the actual number of processed operations returned, this can never be larger than ``nb_ops``. .. code-block:: c uint16_t rte_cryptodev_dequeue_burst(uint8_t dev_id, uint16_t qp_id, struct rte_crypto_op **ops, uint16_t nb_ops) Operation Representation ~~~~~~~~~~~~~~~~~~~~~~~~ An Crypto operation is represented by an rte_crypto_op structure, which is a generic metadata container for all necessary information required for the Crypto operation to be processed on a particular Crypto device poll mode driver. .. figure:: img/crypto_op.* The operation structure includes the operation type and the operation status, a reference to the operation specific data, which can vary in size and content depending on the operation being provisioned. It also contains the source mempool for the operation, if it allocate from a mempool. Finally an opaque pointer for user specific data is provided. If Crypto operations are allocated from a Crypto operation mempool, see next section, there is also the ability to allocate private memory with the operation for applications purposes. Application software is responsible for specifying all the operation specific fields in the ``rte_crypto_op`` structure which are then used by the Crypto PMD to process the requested operation. Operation Management and Allocation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The cryptodev library provides an API set for managing Crypto operations which utilize the Mempool Library to allocate operation buffers. Therefore, it ensures that the crytpo operation is interleaved optimally across the channels and ranks for optimal processing. A ``rte_crypto_op`` contains a field indicating the pool that it originated from. When calling ``rte_crypto_op_free(op)``, the operation returns to its original pool. .. code-block:: c extern struct rte_mempool * rte_crypto_op_pool_create(const char *name, enum rte_crypto_op_type type, unsigned nb_elts, unsigned cache_size, uint16_t priv_size, int socket_id); During pool creation ``rte_crypto_op_init()`` is called as a constructor to initialize each Crypto operation which subsequently calls ``__rte_crypto_op_reset()`` to configure any operation type specific fields based on the type parameter. ``rte_crypto_op_alloc()`` and ``rte_crypto_op_bulk_alloc()`` are used to allocate Crypto operations of a specific type from a given Crypto operation mempool. ``__rte_crypto_op_reset()`` is called on each operation before being returned to allocate to a user so the operation is always in a good known state before use by the application. .. code-block:: c struct rte_crypto_op *rte_crypto_op_alloc(struct rte_mempool *mempool, enum rte_crypto_op_type type) unsigned rte_crypto_op_bulk_alloc(struct rte_mempool *mempool, enum rte_crypto_op_type type, struct rte_crypto_op **ops, uint16_t nb_ops) ``rte_crypto_op_free()`` is called by the application to return an operation to its allocating pool. .. code-block:: c void rte_crypto_op_free(struct rte_crypto_op *op) Symmetric Cryptography Support ------------------------------ The cryptodev library currently provides support for the following symmetric Crypto operations; cipher, authentication, including chaining of these operations, as well as also supporting AEAD operations. Session and Session Management ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Session are used in symmetric cryptographic processing to store the immutable data defined in a cryptographic transform which is used in the operation processing of a packet flow. Sessions are used to manage information such as expand cipher keys and HMAC IPADs and OPADs, which need to be calculated for a particular Crypto operation, but are immutable on a packet to packet basis for a flow. Crypto sessions cache this immutable data in a optimal way for the underlying PMD and this allows further acceleration of the offload of Crypto workloads. .. figure:: img/cryptodev_sym_sess.* The Crypto device framework provides a set of session pool management APIs for the creation and freeing of the sessions, utilizing the Mempool Library. The framework also provides hooks so the PMDs can pass the amount of memory required for that PMDs private session parameters, as well as initialization functions for the configuration of the session parameters and freeing function so the PMD can managed the memory on destruction of a session. **Note**: Sessions created on a particular device can only be used on Crypto devices of the same type, and if you try to use a session on a device different to that on which it was created then the Crypto operation will fail. ``rte_cryptodev_sym_session_create()`` is used to create a symmetric session on Crypto device. A symmetric transform chain is used to specify the particular operation and its parameters. See the section below for details on transforms. .. code-block:: c struct rte_cryptodev_sym_session * rte_cryptodev_sym_session_create( uint8_t dev_id, struct rte_crypto_sym_xform *xform); **Note**: For AEAD operations the algorithm selected for authentication and ciphering must aligned, eg AES_GCM. Transforms and Transform Chaining ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Symmetric Crypto transforms (``rte_crypto_sym_xform``) are the mechanism used to specify the details of the Crypto operation. For chaining of symmetric operations such as cipher encrypt and authentication generate, the next pointer allows transform to be chained together. Crypto devices which support chaining must publish the chaining of symmetric Crypto operations feature flag. Currently there are two transforms types cipher and authentication, to specify an AEAD operation it is required to chain a cipher and an authentication transform together. Also it is important to note that the order in which the transforms are passed indicates the order of the chaining. .. code-block:: c struct rte_crypto_sym_xform { struct rte_crypto_sym_xform *next; /**< next xform in chain */ enum rte_crypto_sym_xform_type type; /**< xform type */ union { struct rte_crypto_auth_xform auth; /**< Authentication / hash xform */ struct rte_crypto_cipher_xform cipher; /**< Cipher xform */ }; }; The API does not place a limit on the number of transforms that can be chained together but this will be limited by the underlying Crypto device poll mode driver which is processing the operation. .. figure:: img/crypto_xform_chain.* Symmetric Operations ~~~~~~~~~~~~~~~~~~~~ The symmetric Crypto operation structure contains all the mutable data relating to performing symmetric cryptographic processing on a referenced mbuf data buffer. It is used for either cipher, authentication, AEAD and chained operations. As a minimum the symmetric operation must have a source data buffer (``m_src``), the session type (session-based/less), a valid session (or transform chain if in session-less mode) and the minimum authentication/ cipher parameters required depending on the type of operation specified in the session or the transform chain. .. code-block:: c struct rte_crypto_sym_op { struct rte_mbuf *m_src; struct rte_mbuf *m_dst; enum rte_crypto_sym_op_sess_type type; union { struct rte_cryptodev_sym_session *session; /**< Handle for the initialised session context */ struct rte_crypto_sym_xform *xform; /**< Session-less API Crypto operation parameters */ }; struct { struct { uint32_t offset; uint32_t length; } data; /**< Data offsets and length for ciphering */ struct { uint8_t *data; phys_addr_t phys_addr; uint16_t length; } iv; /**< Initialisation vector parameters */ } cipher; struct { struct { uint32_t offset; uint32_t length; } data; /**< Data offsets and length for authentication */ struct { uint8_t *data; phys_addr_t phys_addr; uint16_t length; } digest; /**< Digest parameters */ struct { uint8_t *data; phys_addr_t phys_addr; uint16_t length; } aad; /**< Additional authentication parameters */ } auth; } Asymmetric Cryptography ----------------------- Asymmetric functionality is currently not supported by the cryptodev API. Crypto Device API ~~~~~~~~~~~~~~~~~ The cryptodev Library API is described in the *DPDK API Reference* document.
{ "content_hash": "83d48a04056c3428789f27c42a51b1f5", "timestamp": "", "source": "github", "line_count": 578, "max_line_length": 90, "avg_line_length": 37.92214532871972, "alnum_prop": 0.6935991605456453, "repo_name": "ipdcode/skydns", "id": "ca3f551b93280ee3f6a90912f6c3136083387e8f", "size": "21921", "binary": false, "copies": "15", "ref": "refs/heads/master", "path": "kdns/dpdk-17.02/doc/guides/prog_guide/cryptodev_lib.rst", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "244979" }, { "name": "Shell", "bytes": "3288" } ], "symlink_target": "" }
require 'digest/sha1' module Shooter module Acts module Auditable def self.included(base) base.extend Shooter::Acts::Auditable::ClassMethods end module ClassMethods def audit(options = {}) options.assert_valid_keys(:when, :if, :with_message) unless auditable? include Shooter::Acts::Auditable::InstanceMethods cattr_accessor :audit_items attr_accessor :auditor has_many :audits, :as => :auditable, :order => "created_at DESC" validate :auditor_is_assigned, :if => lambda {|audited_model| audited_model.will_be_audited? } end self.audit_items ||= [] options.merge!(:key => (key = generate_audit_key)) self.audit_items << options self.class_eval <<-EOV #{options[:when]} do |audited_model| item = audit_items.find {|item| item[:key] == "#{key}"} if (should_call = item[:if]).is_a?(Proc) ? should_call.call(audited_model) : audited_model.send(should_call) message = (msg = item[:with_message]).is_a?(Proc) ? msg.call(audited_model) : audited_model.send(msg) audited_model.audits.create(:message => message, :auditor => audited_model.auditor) end end EOV end def auditable? self.included_modules.include?(InstanceMethods) end private def generate_audit_key Digest::SHA1.hexdigest(Time.now.to_s.split(//).sort_by {rand}.join) end end module InstanceMethods def will_be_audited? self.class.audit_items.map {|audit_item| audit_item[:if] }.any? {|item| item.is_a?(Proc) ? item.call(self) : self.send(item) } end protected def auditor_is_assigned errors.add(:auditor, "needs to be assigned") unless self.auditor end end end end end ActiveRecord::Base.send :include, Shooter::Acts::Auditable
{ "content_hash": "ff19029a0b3802c90cd4664ce5cdac6d", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 136, "avg_line_length": 31.62686567164179, "alnum_prop": 0.5526191599811232, "repo_name": "unders/acts_as_auditable", "id": "745477854a7aa0d1557bdb647b5b5627e5168722", "size": "2119", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/shooter/acts/auditable.rb", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
@interface CCKFNavDrawer () @property (nonatomic) BOOL isOpen; @property (nonatomic) float meunHeight; @property (nonatomic) float menuWidth; @property (nonatomic) CGRect outFrame; @property (nonatomic) CGRect inFrame; @property (strong, nonatomic) UIView *shawdowView; @property (strong, nonatomic) DropDownView *dropView; @end @implementation CCKFNavDrawer #pragma mark - VC lifecycle - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. [self setUpDrawer]; // block __weak CCKFNavDrawer *wself = self; self.dropView.closeNaviBlock = ^(NSString *cityName){ CCKFNavDrawer *sself = wself; [sself closeNavigationDrawer]; [sself.CCKFNavDrawerDelegate CCKFNavDrawerSelection:cityName]; }; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark - push & pop - (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated { [super pushViewController:viewController animated:animated]; // disable gesture in next vc [self.panGest setEnabled:NO]; } - (UIViewController *)popViewControllerAnimated:(BOOL)animated { UIViewController *vc = [super popViewControllerAnimated:animated]; // enable gesture in root vc if ([self.viewControllers count]==1){ [self.panGest setEnabled:YES]; } return vc; } #pragma mark - drawer - (void)setUpDrawer { self.isOpen = NO; // load drawer view self.dropView = [[[NSBundle mainBundle] loadNibNamed:@"DropDownView" owner:self options:nil] objectAtIndex:0]; //self.dropView.backgroundColor = [UIColor redColor]; self.meunHeight = (self.view.frame.size.height*3)/4; self.menuWidth = self.view.frame.size.width; //self.dropView.frame.size.width; self.outFrame = CGRectMake(-self.menuWidth,0,self.menuWidth,self.meunHeight); self.inFrame = CGRectMake (0,0,self.menuWidth,self.meunHeight); // drawer shawdow and assign its gesture self.shawdowView = [[UIView alloc] initWithFrame:self.view.frame]; self.shawdowView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.0]; self.shawdowView.hidden = YES; UITapGestureRecognizer *tapIt = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOnShawdow:)]; [self.shawdowView addGestureRecognizer:tapIt]; self.shawdowView.translatesAutoresizingMaskIntoConstraints = NO; [self.view addSubview:self.shawdowView]; // add drawer view [self.dropView setFrame:self.outFrame]; [self.view addSubview:self.dropView]; // drawer list [self.dropView.provinceTableView setContentInset:UIEdgeInsetsMake(64, 0, 0, 0)]; // statuesBarHeight+navBarHeight [self.dropView.cityTableView setContentInset:UIEdgeInsetsMake(64, 0, 0, 0)]; //self.dropView.provinceTable.dataSource = self; //self.dropView.provinceTable.delegate = self; // gesture on self.view self.panGest = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(moveDrawer:)]; self.panGest.maximumNumberOfTouches = 1; self.panGest.minimumNumberOfTouches = 1; [self.view addGestureRecognizer:self.panGest]; [self.view bringSubviewToFront:self.navigationBar]; } - (void)drawerToggle { if (!self.isOpen) { [self openNavigationDrawer]; }else{ [self closeNavigationDrawer]; } } #pragma open and close action - (void)openNavigationDrawer{ float duration = MENU_DURATION/self.menuWidth*fabs(self.dropView.center.x)+MENU_DURATION/2; // y=mx+c // shawdow self.shawdowView.hidden = NO; [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{ self.shawdowView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:SHAWDOW_ALPHA]; } completion:nil]; // drawer [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{ self.dropView.frame = self.inFrame; } completion:nil]; self.isOpen= YES; } - (void)closeNavigationDrawer{ float duration = MENU_DURATION/self.menuWidth*fabs(self.dropView.center.x)+MENU_DURATION/2; // y=mx+c // shawdow [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{ self.shawdowView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.0f]; } completion:^(BOOL finished){ self.shawdowView.hidden = YES; }]; // drawer [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{ self.dropView.frame = self.outFrame; } completion:nil]; self.isOpen= NO; } #pragma gestures - (void)tapOnShawdow:(UITapGestureRecognizer *)recognizer { [self closeNavigationDrawer]; } -(void)moveDrawer:(UIPanGestureRecognizer *)recognizer { CGPoint translation = [recognizer translationInView:self.view]; CGPoint velocity = [(UIPanGestureRecognizer*)recognizer velocityInView:self.view]; // NSLog(@"velocity x=%f",velocity.x); if([(UIPanGestureRecognizer*)recognizer state] == UIGestureRecognizerStateBegan) { // NSLog(@"start"); if ( velocity.x > MENU_TRIGGER_VELOCITY && !self.isOpen) { [self openNavigationDrawer]; }else if (velocity.x < -MENU_TRIGGER_VELOCITY && self.isOpen) { [self closeNavigationDrawer]; } } if([(UIPanGestureRecognizer*)recognizer state] == UIGestureRecognizerStateChanged) { // NSLog(@"changing"); float movingx = self.dropView.center.x + translation.x; if ( movingx > -self.menuWidth/2 && movingx < self.menuWidth/2){ self.dropView.center = CGPointMake(movingx, self.dropView.center.y); [recognizer setTranslation:CGPointMake(0,0) inView:self.view]; float changingAlpha = SHAWDOW_ALPHA/self.menuWidth*movingx+SHAWDOW_ALPHA/2; // y=mx+c self.shawdowView.hidden = NO; self.shawdowView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:changingAlpha]; } } if([(UIPanGestureRecognizer*)recognizer state] == UIGestureRecognizerStateEnded) { // NSLog(@"end"); if (self.dropView.center.x>0){ [self openNavigationDrawer]; }else if (self.dropView.center.x<0){ [self closeNavigationDrawer]; } } } @end
{ "content_hash": "4fe494c66ddfd8550960fa0926042949", "timestamp": "", "source": "github", "line_count": 222, "max_line_length": 126, "avg_line_length": 33.53603603603604, "alnum_prop": 0.6364002686366689, "repo_name": "wanghuahui/MyWeatherApp", "id": "0a7c9b8b9579963f669abb3db18ffd961f794d0e", "size": "7775", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MyWeatherApp/DropDown/CCKFNavDrawer.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "84114" } ], "symlink_target": "" }
package apparmor import ( "bufio" "bytes" "io" "os" "os/exec" "path" "strconv" "strings" "text/template" "github.com/containers/common/pkg/apparmor/internal/supported" "github.com/containers/storage/pkg/unshare" runcaa "github.com/opencontainers/runc/libcontainer/apparmor" "github.com/pkg/errors" "github.com/sirupsen/logrus" ) // profileDirectory is the file store for apparmor profiles and macros. var profileDirectory = "/etc/apparmor.d" // IsEnabled returns true if AppArmor is enabled on the host. It also checks // for the existence of the `apparmor_parser` binary, which will be required to // apply profiles. func IsEnabled() bool { return supported.NewAppArmorVerifier().IsSupported() == nil } // profileData holds information about the given profile for generation. type profileData struct { // Name is profile name. Name string // Imports defines the apparmor functions to import, before defining the profile. Imports []string // InnerImports defines the apparmor functions to import in the profile. InnerImports []string // Version is the {major, minor, patch} version of apparmor_parser as a single number. Version int } // generateDefault creates an apparmor profile from ProfileData. func (p *profileData) generateDefault(apparmorParserPath string, out io.Writer) error { compiled, err := template.New("apparmor_profile").Parse(defaultProfileTemplate) if err != nil { return errors.Wrap(err, "create AppArmor profile from template") } if macroExists("tunables/global") { p.Imports = append(p.Imports, "#include <tunables/global>") } else { p.Imports = append(p.Imports, "@{PROC}=/proc/") } if macroExists("abstractions/base") { p.InnerImports = append(p.InnerImports, "#include <abstractions/base>") } ver, err := getAAParserVersion(apparmorParserPath) if err != nil { return errors.Wrap(err, "get AppArmor version") } p.Version = ver return errors.Wrap(compiled.Execute(out, p), "execute compiled profile") } // macrosExists checks if the passed macro exists. func macroExists(m string) bool { _, err := os.Stat(path.Join(profileDirectory, m)) return err == nil } // InstallDefault generates a default profile and loads it into the kernel // using 'apparmor_parser'. func InstallDefault(name string) error { if unshare.IsRootless() { return ErrApparmorRootless } p := profileData{ Name: name, } apparmorParserPath, err := supported.NewAppArmorVerifier().FindAppArmorParserBinary() if err != nil { return errors.Wrap(err, "find `apparmor_parser` binary") } cmd := exec.Command(apparmorParserPath, "-Kr") pipe, err := cmd.StdinPipe() if err != nil { return errors.Wrapf(err, "execute %s", apparmorParserPath) } if err := cmd.Start(); err != nil { if pipeErr := pipe.Close(); pipeErr != nil { logrus.Errorf("unable to close AppArmor pipe: %q", pipeErr) } return errors.Wrapf(err, "start %s command", apparmorParserPath) } if err := p.generateDefault(apparmorParserPath, pipe); err != nil { if pipeErr := pipe.Close(); pipeErr != nil { logrus.Errorf("unable to close AppArmor pipe: %q", pipeErr) } if cmdErr := cmd.Wait(); cmdErr != nil { logrus.Errorf("unable to wait for AppArmor command: %q", cmdErr) } return errors.Wrap(err, "generate default profile into pipe") } if pipeErr := pipe.Close(); pipeErr != nil { logrus.Errorf("unable to close AppArmor pipe: %q", pipeErr) } return errors.Wrap(cmd.Wait(), "wait for AppArmor command") } // DefaultContent returns the default profile content as byte slice. The // profile is named as the provided `name`. The function errors if the profile // generation fails. func DefaultContent(name string) ([]byte, error) { p := profileData{Name: name} buffer := &bytes.Buffer{} apparmorParserPath, err := supported.NewAppArmorVerifier().FindAppArmorParserBinary() if err != nil { return nil, errors.Wrap(err, "find `apparmor_parser` binary") } if err := p.generateDefault(apparmorParserPath, buffer); err != nil { return nil, errors.Wrap(err, "generate default AppAmor profile") } return buffer.Bytes(), nil } // IsLoaded checks if a profile with the given name has been loaded into the // kernel. func IsLoaded(name string) (bool, error) { if name != "" && unshare.IsRootless() { return false, errors.Wrapf(ErrApparmorRootless, "cannot load AppArmor profile %q", name) } file, err := os.Open("/sys/kernel/security/apparmor/profiles") if err != nil { if os.IsNotExist(err) { return false, nil } return false, errors.Wrap(err, "open AppArmor profile path") } defer file.Close() r := bufio.NewReader(file) for { p, err := r.ReadString('\n') if err == io.EOF { break } if err != nil { return false, errors.Wrap(err, "reading AppArmor profile") } if strings.HasPrefix(p, name+" ") { return true, nil } } return false, nil } // execAAParser runs `apparmor_parser` with the passed arguments. func execAAParser(apparmorParserPath, dir string, args ...string) (string, error) { c := exec.Command(apparmorParserPath, args...) c.Dir = dir output, err := c.Output() if err != nil { return "", errors.Errorf("running `%s %s` failed with output: %s\nerror: %v", c.Path, strings.Join(c.Args, " "), output, err) } return string(output), nil } // getAAParserVersion returns the major and minor version of apparmor_parser. func getAAParserVersion(apparmorParserPath string) (int, error) { output, err := execAAParser(apparmorParserPath, "", "--version") if err != nil { return -1, errors.Wrap(err, "execute apparmor_parser") } return parseAAParserVersion(output) } // parseAAParserVersion parses the given `apparmor_parser --version` output and // returns the major and minor version number as an integer. func parseAAParserVersion(output string) (int, error) { // output is in the form of the following: // AppArmor parser version 2.9.1 // Copyright (C) 1999-2008 Novell Inc. // Copyright 2009-2012 Canonical Ltd. lines := strings.SplitN(output, "\n", 2) words := strings.Split(lines[0], " ") version := words[len(words)-1] // split by major minor version v := strings.Split(version, ".") if len(v) == 0 || len(v) > 3 { return -1, errors.Errorf("parsing version failed for output: `%s`", output) } // Default the versions to 0. var majorVersion, minorVersion, patchLevel int majorVersion, err := strconv.Atoi(v[0]) if err != nil { return -1, errors.Wrap(err, "convert AppArmor major version") } if len(v) > 1 { minorVersion, err = strconv.Atoi(v[1]) if err != nil { return -1, errors.Wrap(err, "convert AppArmor minor version") } } if len(v) > 2 { patchLevel, err = strconv.Atoi(v[2]) if err != nil { return -1, errors.Wrap(err, "convert AppArmor patch version") } } // major*10^5 + minor*10^3 + patch*10^0 numericVersion := majorVersion*1e5 + minorVersion*1e3 + patchLevel return numericVersion, nil } // CheckProfileAndLoadDefault checks if the specified profile is loaded and // loads the DefaultLibpodProfile if the specified on is prefixed by // DefaultLipodProfilePrefix. This allows to always load and apply the latest // default AppArmor profile. Note that AppArmor requires root. If it's a // default profile, return DefaultLipodProfilePrefix, otherwise the specified // one. func CheckProfileAndLoadDefault(name string) (string, error) { if name == "unconfined" { return name, nil } // AppArmor is not supported in rootless mode as it requires root // privileges. Return an error in case a specific profile is specified. if unshare.IsRootless() { if name != "" { return "", errors.Wrapf(ErrApparmorRootless, "cannot load AppArmor profile %q", name) } else { logrus.Debug("skipping loading default AppArmor profile (rootless mode)") return "", nil } } // Check if AppArmor is disabled and error out if a profile is to be set. if !runcaa.IsEnabled() { if name == "" { return "", nil } else { return "", errors.Errorf("profile %q specified but AppArmor is disabled on the host", name) } } if name == "" { name = Profile } else if !strings.HasPrefix(name, ProfilePrefix) { // If the specified name is not a default one, ignore it and return the // name. isLoaded, err := IsLoaded(name) if err != nil { return "", errors.Wrapf(err, "verify if profile %s is loaded", name) } if !isLoaded { return "", errors.Errorf("AppArmor profile %q specified but not loaded", name) } return name, nil } // To avoid expensive redundant loads on each invocation, check // if it's loaded before installing it. isLoaded, err := IsLoaded(name) if err != nil { return "", errors.Wrapf(err, "verify if profile %s is loaded", name) } if !isLoaded { err = InstallDefault(name) if err != nil { return "", errors.Wrapf(err, "install profile %s", name) } logrus.Infof("successfully loaded AppAmor profile %q", name) } else { logrus.Infof("AppAmor profile %q is already loaded", name) } return name, nil }
{ "content_hash": "727fd5be20d2e8e5ffea8e6cd660a530", "timestamp": "", "source": "github", "line_count": 299, "max_line_length": 127, "avg_line_length": 30.00334448160535, "alnum_prop": 0.7011481440196188, "repo_name": "kubernetes-incubator/cri-o", "id": "4f11e4ed2598e989573561bbea59e5def9fbac32", "size": "8997", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "vendor/github.com/containers/common/pkg/apparmor/apparmor_linux.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "55743" }, { "name": "Dockerfile", "bytes": "8011" }, { "name": "Go", "bytes": "421420" }, { "name": "Makefile", "bytes": "10175" }, { "name": "Python", "bytes": "6483" }, { "name": "Shell", "bytes": "112484" } ], "symlink_target": "" }
[![Build Status](https://travis-ci.org/MonetDB/npm-csv-sniffer.svg)](https://travis-ci.org/MonetDB/npm-csv-sniffer) [![npm version](https://badge.fury.io/js/csv-sniffer.svg)](http://badge.fury.io/js/csv-sniffer) Takes a sample of CSV text and tries to guess newline character, col delimiter, quote character, and whether or not the first row in the file contains labels. # Installation npm install [-g] csv-sniffer # Example usage ``` var CSVSniffer = require("csv-sniffer")(); var sniffer = new CSVSniffer(); var sample = obtain_a_sample_somehow(); sniffResult = sniffer.sniff(sample); console.log("Sniff result: "+ "Newline string: " +sniffResult.newlineStr+ "Delimiter: " +sniffResult.delimiter+ "Quote character: " +sniffResult.quoteChar+ "First line contains labels: " +sniffResult.hasHeader+ "Labels: " +sniffResult.labels+ "# Records: " +sniffResult.records.length ); ``` # API #### CSVSniffer(delims) The constructor of a CSV sniffer takes one optional argument: an array of possible column delimiters. Auto detection will never propose a character outside of this set. If delims is not provided, all ASCII characters are considered. #### CSVSniffer.sniff(sample, [options]) This function is the only function in the CSVSniffer object. It operates based on the given options in the optional options object. Options that are not provided are attempted to be auto detected. Possible options: - newlineStr [string]: Line separator in sample - delimiter [string]: Column delimiter in sample (null or ) - quoteChar [string]: Quoting character in sample (null or empty string means no quote character) - hasHeader [boolean]: Boolean indicating whether or not the first line in sample contains header labels. <a name="sniffresult"></a>**Returns object with the following properties:** - newlineStr [string]: If auto detected, will be one of "\r", "\n", "\r\n", "\n\r" - delimiter [string]: If auto detected, can be any ASCII character. Will be null if no delimiter was found. - quoteChar [string]: Can be either ' or " or null. - hasHeader [boolean]: true if first line is treated as header. - warnings [array]: Can contain some warnings that were generated during the sniffing. Will be empty in most cases. - types [array]: Contains the types of the columns. One of "string", "float", "integer". - labels [array]: Contains column labels, taken from the first line of the sample. If 'hasHeader' is false, this variable will be set to null. - records [array]: Contains the parsed data from the sample, using the information that was found during the sniffing process. This array of arrays will not contain the labels if 'hasHeader' evaluated to true. **Please report any suggestions/bugs to robin.cijvat@monetdbsolutions.com**
{ "content_hash": "bf754594a8731094f039c37824084e3c", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 209, "avg_line_length": 47.152542372881356, "alnum_prop": 0.7422717469446442, "repo_name": "MonetDB/npm-csv-sniffer", "id": "cdb9dedf70012afe0551a98827c1754af11c43fe", "size": "2796", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "23284" } ], "symlink_target": "" }
module.exports = { 'after': require('lodash/function/after'), 'ary': require('lodash/function/ary'), 'backflow': require('lodash/function/backflow'), 'before': require('lodash/function/before'), 'bind': require('lodash/function/bind'), 'bindAll': require('lodash/function/bindAll'), 'bindKey': require('lodash/function/bindKey'), 'compose': require('lodash/function/compose'), 'curry': require('lodash/function/curry'), 'curryRight': require('lodash/function/curryRight'), 'debounce': require('lodash/function/debounce'), 'defer': require('lodash/function/defer'), 'delay': require('lodash/function/delay'), 'flow': require('lodash/function/flow'), 'flowRight': require('lodash/function/flowRight'), 'memoize': require('lodash/function/memoize'), 'modArgs': require('lodash/function/modArgs'), 'negate': require('lodash/function/negate'), 'once': require('lodash/function/once'), 'partial': require('lodash/function/partial'), 'partialRight': require('lodash/function/partialRight'), 'rearg': require('lodash/function/rearg'), 'restParam': require('lodash/function/restParam'), 'spread': require('lodash/function/spread'), 'throttle': require('lodash/function/throttle'), 'wrap': require('lodash/function/wrap') };
{ "content_hash": "7af1577446fe255f5a9e14b25cd29c10", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 58, "avg_line_length": 45.25, "alnum_prop": 0.7063930544593529, "repo_name": "zhaojizhuang/zhaojizhuang.github.io", "id": "b6a8ef34eb0f0cb1fe5dfef7b81fc88c9467e510", "size": "1267", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ebook-note/node_modules/lodash/function.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "62343" }, { "name": "HTML", "bytes": "1174869" }, { "name": "JavaScript", "bytes": "21756" }, { "name": "Shell", "bytes": "123" } ], "symlink_target": "" }
import json import bpy import os from bpy.types import Operator from . import utils from .assets.scripts.evertims import ( Evertims, evertUtils ) # to launch EVERTims raytracing client import subprocess # --------------------------------------------------------------- # import components necessary to report EVERTims raytracing client # logs in console import sys import threading try: from Queue import Queue, Empty except ImportError: from queue import Queue, Empty # python 3.x ON_POSIX = 'posix' in sys.builtin_module_names ASSET_FILE_NAME = "evertims-assets.blend" class EVERTimsImportObject(Operator): """Import default EVERTims element (KX_GameObject) into scene""" bl_label = "Import an object (KX_GameObject, Empty, etc.) from anther .blend file" bl_idname = 'evert.import_template' bl_options = {'REGISTER', 'UNDO'} arg = bpy.props.StringProperty() def execute(self, context): loadType = self.arg evertims = context.scene.evertims # cancel if simulation is running if evertims.enable_edit_mode: self.report({'WARNING'}, 'Cannot import element while simulation is running') return {'CANCELLED'} # cleanup before we start bpy.ops.object.select_all(action='DESELECT') # set asset .blend file name filename = ASSET_FILE_NAME obj = None if loadType == 'scene': # load each object separately for access to resulting obj.name obj = self.loadAsset(filename, ('Room')) evertims.room_object = obj.name obj = self.loadAsset(filename, ('Source')) evertims.source_object = obj.name obj = self.loadAsset(filename, ('Listener_Rotate', 'Listener')) evertims.listener_object = obj.name # load others self.loadAsset(filename, ('Logic_EVERTims')) if loadType == 'logic': obj = self.loadAsset(filename, ('Logic_EVERTims')) if loadType == 'room': obj = self.loadAsset(filename, ('Room')) evertims.room_object = obj.name if loadType == 'source': obj = self.loadAsset(filename, ('Source')) evertims.source_object = obj.name if loadType == 'listener': obj = self.loadAsset(filename, ('Listener_Rotate', 'Listener')) evertims.listener_object = obj.name if not obj: self.report({'ERROR'}, 'something went wrong') return {'CANCELLED'} else: obj.select = True bpy.context.scene.objects.active = obj return {'FINISHED'} def loadAsset(self, filename, objList): scriptPath = os.path.realpath(__file__) assetPath = os.path.join(os.path.dirname(scriptPath), 'assets', filename) try: with bpy.data.libraries.load(assetPath) as (data_from, data_to): data_to.objects = [name for name in data_from.objects if name in objList] except: return 'Asset file not found' for obj in data_to.objects: bpy.context.scene.objects.link(obj) return obj class EVERTimsImportText(Operator): """Import the list of available EVERTims acoustic materials as a text file""" bl_label = "Import a text file from anther .blend file" bl_idname = 'evert.import_script' bl_options = {'REGISTER', 'UNDO'} arg = bpy.props.StringProperty() def execute(self, context): loadType = self.arg # set asset .blend file name filename = ASSET_FILE_NAME if loadType == 'materialList': isLoaded = self.loadAsset(filename, ('evertims-materials.txt')) if not isLoaded: self.report({'ERROR'}, 'something went wrong') return {'CANCELLED'} else: self.report({'INFO'}, 'EVERTims material file imported in Text Editor window.') return {'FINISHED'} def loadAsset(self, filename, objList): scriptPath = os.path.realpath(__file__) assetPath = os.path.join(os.path.dirname(scriptPath), 'assets', filename) try: with bpy.data.libraries.load(assetPath) as (data_from, data_to): data_to.texts = [name for name in data_from.texts if name in objList] except: return False return True class EVERTimsInBge(Operator): """setup EVERTims for BGE session""" bl_label = "setup EVERTims in BGE" bl_idname = 'evert.evertims_in_bge' bl_options = {'REGISTER'} arg = bpy.props.StringProperty() def execute(self, context): loadType = self.arg evertims = context.scene.evertims logic_obj = bpy.context.scene.objects.get('Logic_EVERTims') if loadType == 'ENABLE': # check if evertims setup properly if not evertims.room_object or not evertims.source_object or not evertims.listener_object or not logic_obj: self.report({'ERROR'}, 'Create at least 1 room (with material), 1 listener, 1 source and import EVERTims Logic object') return {'CANCELLED'} # update logic object properties for in-BGE access self.init_evertims_module_path(context) # update flag evertims.enable_bge = True elif loadType == 'DISABLE': # update flag evertims.enable_bge = False # update logic object properties for in-BGE access self.update_evertims_props(context) return {'FINISHED'} def update_evertims_props(self, context): evertims = context.scene.evertims # remember current active object old_obj = bpy.context.scene.objects.active # get logic object obj = bpy.context.scene.objects.get('Logic_EVERTims') if obj: bpy.context.scene.objects.active = obj propList = [ 'enable_bge', 'debug_logs', 'debug_rays', 'ip_local', 'ip_raytracing', 'ip_auralization', 'port_read', 'port_write_raytracing', 'port_write_auralization', 'movement_threshold_loc', 'movement_threshold_rot', 'room_object', 'source_object', 'listener_object'] # sync. properties (for bge access) with GUI's for propName in propList: propValue = eval('evertims.' + propName) obj.game.properties[propName].value = propValue # get room object, update its RT60 values (not possible in bge, based on bpy routines) room = bpy.context.scene.objects.get(evertims.room_object) rt60Values = evertUtils.getRt60Values(utils.str2dict(evertims.mat_list), room) obj.game.properties['rt60Values'].value = json.dumps(rt60Values) # reset old active object bpy.context.scene.objects.active = old_obj def init_evertims_module_path(self, context): # get add-on path current_script_file = os.path.realpath(__file__) current_script_directory = os.path.dirname(current_script_file) addon_path = os.path.join(current_script_directory, 'assets', 'scripts') # get logic object obj = context.scene.objects.get('Logic_EVERTims') if obj: obj.game.properties['evertims_path'].value = addon_path class EVERTimsInEditMode(Operator): """Start OSC sync. with EVERTims raytracing client. Continuous upload of scene info (room, listener, etc.) for auralization and download of raytracing results for visual feedback.""" bl_label = "Enable Blender to EVERTims raytracing client connection in edit mode (as opposed to BGE mode)" bl_idname = 'evert.evertims_in_edit_mode' bl_options = {'REGISTER'} arg = bpy.props.StringProperty() _evertims = Evertims() _handle_timer = None @staticmethod def handle_add(self, context): # EVERTimsInEditMode._handle_draw_callback = bpy.types.SpaceView3D.draw_handler_add(EVERTimsInEditMode._draw_callback, (self,context), 'WINDOW', 'PRE_VIEW') context.window_manager.modal_handler_add(self) EVERTimsInEditMode._handle_timer = context.window_manager.event_timer_add(0.075, context.window) if context.scene.evertims.debug_logs: print('added evertims callback to draw_handler') @staticmethod def handle_remove(context): if EVERTimsInEditMode._handle_timer is not None: context.window_manager.event_timer_remove(EVERTimsInEditMode._handle_timer) EVERTimsInEditMode._handle_timer = None # context.window_manager.modal_handler_add(self) # bpy.types.SpaceView3D.draw_handler_remove(EVERTimsInEditMode._handle_draw_callback, 'WINDOW') # EVERTimsInEditMode._handle_draw_callback = None if context.scene.evertims.debug_logs: print('removed evertims callback from draw_handler') @classmethod def poll(cls, context): return context.area.type == 'VIEW_3D' def invoke(self, context, event): scene = context.scene evertims = scene.evertims loadType = self.arg # get active object # obj = bpy.context.scene.objects.active if loadType == 'PLAY': # load mat file if not loaded already evertims.mat_list = utils.loadMatFile(context) self._evertims.setMaterials(utils.str2dict(evertims.mat_list)) # check room materials definition roomMatError = self.checkRoomMaterials(context) if roomMatError: self.report({'ERROR'}, roomMatError) return {'CANCELLED'} # init evertims isInitOk = self.initEvertims(context) if isInitOk: # update enable flag evertims.enable_edit_mode = True # add callback self.handle_add(self,context) return {'RUNNING_MODAL'} else: self.report({'ERROR'}, 'Create at least 1 room (with material), 1 listener, 1 source and import EVERTims Logic object') return {'CANCELLED'} elif loadType == 'STOP': # update enable flag evertims.enable_edit_mode = False # erase rays from screen context.area.tag_redraw() return {'CANCELLED'} elif loadType == 'CRYSTALIZE': self._evertims.crystalizeVisibleRays() return {'FINISHED'} def modal(self, context, event): """ modal method, run always, call cancel function when Blender quit / load new scene """ # kill modal if not context.scene.evertims.enable_edit_mode: self.cancel(context) # return flag to notify callback manager that this callback is no longer running return {'CANCELLED'} # execute modal elif event.type == 'TIMER': # run evertims internal callbacks self._evertims.bpy_modal() # force bgl rays redraw (else only redraw rays on user input event) if not context.area is None: context.area.tag_redraw() return {'PASS_THROUGH'} def cancel(self, context): """ called when Blender quit / load new scene. Remove local callback from stack """ # remove local callback self.handle_remove(context) # remove nested callback self._evertims.handle_remove() # erase rays from screen if not context.area is None: context.area.tag_redraw() def checkRoomMaterials(self, context): """ check if all room materials are defined in mat file, return error msg (string) """ evertims = context.scene.evertims objects = bpy.context.scene.objects room = objects.get(evertims.room_object) if not room: return 'no room defined' slots = room.material_slots evertMat = utils.str2dict(evertims.mat_list) for mat in slots: if not mat.name in evertMat: return 'undefined room material: ' + mat.name return '' def initEvertims(self, context): """ init the Evertims() class instance, using GUI defined parameters (in EVERTims add-on pannel) """ evertims = context.scene.evertims IP_RAYTRACING = evertims.ip_raytracing # EVERTims client IP address IP_AURALIZATION = evertims.ip_auralization # Auralization Engine IP address PORT_W_RAYTRACING = evertims.port_write_raytracing # port used by EVERTims client to read data sent by the BGE PORT_W_AURALIZATION = evertims.port_write_auralization # port used by EVERTims client to read data sent by the BGE IP_LOCAL = evertims.ip_local # local host (this computer) IP address, running the BGE PORT_R = evertims.port_read # port used by the BGE to read data sent by the EVERTims client DEBUG_LOG = evertims.debug_logs # enable / disable console log DEBUG_RAYS = evertims.debug_rays # enable / disable visual feedback on traced rays MOVE_UPDATE_THRESHOLD_VALUE_LOC = evertims.movement_threshold_loc # minimum value a listener / source must move to be updated on EVERTims client (m) MOVE_UPDATE_THRESHOLD_VALUE_ROT = evertims.movement_threshold_rot # minimum value a listener / source must rotate to be updated on EVERTims client (deg) # set debug mode self._evertims.setDebugMode(DEBUG_LOG) # self._evertims.setBufferSize(4096) # define EVERTs elements: room, listener and source # 1. reset local dicts if already filled self._evertims.resetObjDict() # (in case something changed, don't want to keep old evertims elmt instances) # 2. define new elements objects = bpy.context.scene.objects # add room obj = objects.get(evertims.room_object) if obj: self._evertims.addRoom(obj) if evertims.debug_logs: print('adding room: ', obj.name) # add source obj = objects.get(evertims.source_object) if obj: self._evertims.addSource(obj) if evertims.debug_logs: print('adding source: ', obj.name) # add listener obj = objects.get(evertims.listener_object) if obj: self._evertims.addListener(obj) if evertims.debug_logs: print('adding listener: ', obj.name) # get logic object logic_obj = bpy.context.scene.objects.get('Logic_EVERTims') # get room for later check room_obj = self._evertims.getRoom() # limit listener / source position updates in EVERTims Client self._evertims.setMovementUpdateThreshold(MOVE_UPDATE_THRESHOLD_VALUE_LOC, MOVE_UPDATE_THRESHOLD_VALUE_ROT) # init network connections self._evertims.initConnection_writeRaytracing(IP_RAYTRACING, PORT_W_RAYTRACING) self._evertims.initConnection_writeAuralization(IP_AURALIZATION, PORT_W_AURALIZATION) self._evertims.initConnection_read(IP_LOCAL, PORT_R) # activate raytracing self._evertims.activateRayTracingFeedback(DEBUG_RAYS) # check if evertims module is ready to start # print (self._evertims.isReady(), logic_obj, room_obj.material_slots) if self._evertims.isReady() and logic_obj: # print('isready', [e for e in room_obj.material_slots]) if room_obj.material_slots: # print('2') # start EVERTims client if evertims.debug_logs: print ('start simulation...') # print('3') self._evertims.startClientSimulation() # print('4') return True print ('\n###### EVERTims SIMULATION ABORTED ###### \nYou should create at least 1 room (with an EVERTims material), 1 listener, 1 source, \nimport the EVERTims Logic object \nand define EVERTims client parameters.\n') return False class EVERTimsRaytracingClient(Operator): """Start the Evertims raytracing client as a subprocess""" bl_label = "Start / Stop the EVERTims raytracing client from Blender GUI" bl_idname = 'evert.evertims_raytracing_client' bl_options = {'REGISTER'} _raytracing_process = None _raytracing_debug_log_thread = None _raytracing_debug_log_queue = None _handle_timer = None _raytracing_debug_thread_stop_event = None arg = bpy.props.StringProperty() @staticmethod def handle_add(self, context, debugEnabled): """ called when starting the EVERTims raytracing client, starts necessary callbacks to output client logs in Blender console. called even if debug mode disabled, the modal then runs uselessly yet we're sure that the self.cancel method is called if blender is closed, hence giving us a handle to kill the evertims ims sub process. """ # start thread for non-blocking log if debugEnabled: EVERTimsRaytracingClient._raytracing_debug_log_queue = Queue() EVERTimsRaytracingClient._raytracing_debug_thread_stop_event = threading.Event() # used to stop the thread EVERTimsRaytracingClient._raytracing_debug_log_thread = threading.Thread(target=self.enqueue_output, args=(self._raytracing_process.stdout, EVERTimsRaytracingClient._raytracing_debug_log_queue, EVERTimsRaytracingClient._raytracing_debug_thread_stop_event)) EVERTimsRaytracingClient._raytracing_debug_log_thread.daemon = True # thread dies with the program EVERTimsRaytracingClient._raytracing_debug_log_thread.start() # start modal context.window_manager.modal_handler_add(self) EVERTimsRaytracingClient._handle_timer = context.window_manager.event_timer_add(0.075, context.window) if context.scene.evertims.debug_logs: print('added evertims raytracing modal callback to draw_handler') @staticmethod def handle_remove(context): """ called when terminating the EVERTims raytracing client, remove callbacks added in handle_add method. """ # skip if somehow this runs while handle time not defined in handle_add if EVERTimsRaytracingClient._handle_timer is None: return # kill modal context.window_manager.event_timer_remove(EVERTimsRaytracingClient._handle_timer) EVERTimsRaytracingClient._handle_timer = None # context.window_manager.modal_handler_add(self) # indicate it's ok to finish log in stdout thread # EVERTimsRaytracingClient._raytracing_debug_log_thread.daemon = False if EVERTimsRaytracingClient._raytracing_debug_thread_stop_event is not None: EVERTimsRaytracingClient._raytracing_debug_thread_stop_event.set() if context.scene.evertims.debug_logs_raytracing: print('removed raytracing modal callback from modal stack') @classmethod def poll(cls, context): return context.area.type == 'VIEW_3D' def enqueue_output(self, out, queue, stop_event): """ Based on the Queue python module, this callback runs when debug mode enabled, allowing non-blocking print of EVERTims raytracing client logs in Blender console. """ if not stop_event.is_set(): for line in iter(out.readline, b''): queue.put(line) out.close() else: EVERTimsRaytracingClient._raytracing_debug_log_thread.stop() if evertims.debug_logs_raytracing: print('removed raytracing client log callback from modal stack') def invoke(self, context, event): """ Method called when button attached to local bl_idname clicked """ evertims = context.scene.evertims addon_prefs = context.user_preferences.addons[__package__].preferences loadType = self.arg # start Evertims raytracing client (subprocess) if loadType == 'PLAY': # get launch command out of GUI properties # cmd = "/Users/.../evertims/bin/ims -s 3858 -a 'listener_1/127.0.0.1:3860' -v 'listener_1/localhost:3862' -d 1 -D 2 -m /Users/.../evertims/resources/materials.dat -p 'listener_1/'" client_cmd = bpy.path.abspath(addon_prefs.raytracing_client_path_to_binary) client_cmd += " -s " + str(evertims.port_write_raytracing) # reader port client_cmd += " -a " + "listener_1" + "/" + evertims.ip_auralization + ":" + str(evertims.port_write_auralization) client_cmd += " -v " + "listener_1" + "/" + evertims.ip_local + ":" + str(evertims.port_read) client_cmd += " -d " + str(evertims.min_reflection_order) client_cmd += " -D " + str(evertims.max_reflection_order) client_cmd += " -p " + "listener_1/ " client_cmd += " -m " + bpy.path.abspath(addon_prefs.raytracing_client_path_to_matFile) # launch subprocess EVERTimsRaytracingClient._raytracing_process = subprocess.Popen(client_cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, close_fds=ON_POSIX) evertims.enable_raytracing_client = True # enable log in Blender console if debug mode enabled if evertims.debug_logs_raytracing: print('launch EVERTims raytracing client subprocess') print('command: \n', client_cmd) self.handle_add(self, context, evertims.debug_logs_raytracing) return {'RUNNING_MODAL'} # terminate Evertims raytracing client (subprocess) elif loadType == 'STOP': # terminate subprocess if self._raytracing_process: # if process has been (e.g. manually) closed since self._raytracing_process.terminate() evertims.enable_raytracing_client = False # terminate modal thread if self._handle_timer: if self._raytracing_debug_thread_stop_event is not None: # debug enabled self.handle_remove(context) else: self.handle_remove(context) if evertims.debug_logs_raytracing: print('terminate EVERTims raytracing client subprocess') return {'CANCELLED'} def modal(self, context, event): """ modal method, run always, call cancel function when Blender quit / load new scene """ # useful only if debug mode not enabled if event.type == 'TIMER' and EVERTimsRaytracingClient._raytracing_debug_log_queue is not None: try: # get line from non-blocking Queue, attached to debug-log thread line = EVERTimsRaytracingClient._raytracing_debug_log_queue.get_nowait() # or q.get(timeout=.1) except Empty: # no output to print yet pass else: # got line, ready to print sys.stdout.write(line.decode('utf-8')) return {'PASS_THROUGH'} def cancel(self, context): """ function called when Blender quit / load new scene. Remove local callback from stack """ # kill ims process if blender exit while modal still running if self._raytracing_process: # if process has been (e.g. manually) closed since self._raytracing_process.terminate() # remove modal self.handle_remove(context) class EVERTimsAuralizationClient(Operator): """Start the EVERTims auralization client as a subprocess""" bl_label = "Start / Stop the EVERTims auralization client from Blender GUI" bl_idname = 'evert.evertims_auralization_client' bl_options = {'REGISTER'} _process = None arg = bpy.props.StringProperty() def invoke(self, context, event): """ Method called when button attached to local bl_idname clicked """ evertims = context.scene.evertims addon_prefs = context.user_preferences.addons[__package__].preferences loadType = self.arg # start Evertims auralization client (subprocess) if loadType == 'PLAY': # get launch command out of GUI properties client_cmd = bpy.path.abspath(addon_prefs.auralization_client_path_to_binary) # launch subprocess EVERTimsAuralizationClient._process = subprocess.Popen(client_cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, close_fds=ON_POSIX) evertims.enable_auralization_client = True return {'FINISHED'} # terminate Evertims raytracing client (subprocess) elif loadType == 'STOP': # terminate subprocess if self._process: # if process has been (e.g. manually) closed since self._process.terminate() evertims.enable_auralization_client = False return {'CANCELLED'} class EVERTimsUtils(Operator): """Miscellaneous utilities""" bl_label = "Mist. utils operators" bl_idname = 'evert.misc_utils' bl_options = {'REGISTER'} arg = bpy.props.StringProperty() def invoke(self, context, event): """ Method called when button attached to local bl_idname clicked """ evertims = context.scene.evertims loadType = self.arg # flag that mat file needs update (will happend just before next auralization session) if loadType == 'FLAG_MAT_UPDATE': evertims.mat_list_need_update = True return {'FINISHED'} # ############################################################ # Un/Registration # ############################################################ classes = ( EVERTimsImportObject, EVERTimsImportText, EVERTimsInBge, EVERTimsInEditMode, EVERTimsRaytracingClient, EVERTimsAuralizationClient, EVERTimsUtils ) def register(): for cls in classes: bpy.utils.register_class(cls) def unregister(): for cls in classes: bpy.utils.unregister_class(cls)
{ "content_hash": "69f1aa9574aeaba2d09dbcf0b2c30a45", "timestamp": "", "source": "github", "line_count": 666, "max_line_length": 282, "avg_line_length": 39.249249249249246, "alnum_prop": 0.6285003825554706, "repo_name": "EVERTims/game_engine_evertims", "id": "f786220a92332d5b685721e30cc6a892f7994bf6", "size": "26140", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "operators.py", "mode": "33261", "license": "mit", "language": [ { "name": "Python", "bytes": "179065" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../_static/javascripts/modernizr.js"></script> <title>statsmodels.genmod.generalized_linear_model.GLM.loglike_mu &#8212; statsmodels</title> <link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png"> <link rel="manifest" href="../_static/icons/site.webmanifest"> <link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191"> <meta name="msapplication-TileColor" content="#2b5797"> <meta name="msapplication-config" content="../_static/icons/browserconfig.xml"> <link rel="stylesheet" href="../_static/stylesheets/examples.css"> <link rel="stylesheet" href="../_static/stylesheets/deprecation.css"> <link rel="stylesheet" href="../_static/material.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/doctools.js"></script> <script src="../_static/language_data.js"></script> <script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script> <script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.genmod.generalized_linear_model.GLM.predict" href="statsmodels.genmod.generalized_linear_model.GLM.predict.html" /> <link rel="prev" title="statsmodels.genmod.generalized_linear_model.GLM.loglike" href="statsmodels.genmod.generalized_linear_model.GLM.loglike.html" /> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=blue> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#generated/statsmodels.genmod.generalized_linear_model.GLM.loglike_mu" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../index.html" title="statsmodels" class="md-header-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" height="26" alt="statsmodels logo"> </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">statsmodels v0.12.1</span> <span class="md-header-nav__topic"> statsmodels.genmod.generalized_linear_model.GLM.loglike_mu </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../search.html" method="GET" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <div class="md-header-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> </div> <script src="../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../_static/versions.json", target_loc = "../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li> <li class="md-tabs__item"><a href="../glm.html" class="md-tabs__link">Generalized Linear Models</a></li> <li class="md-tabs__item"><a href="statsmodels.genmod.generalized_linear_model.GLM.html" class="md-tabs__link">statsmodels.genmod.generalized_linear_model.GLM</a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../index.html" title="statsmodels" class="md-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48"> </a> <a href="../index.html" title="statsmodels">statsmodels v0.12.1</a> </label> <div class="md-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../install.html" class="md-nav__link">Installing statsmodels</a> </li> <li class="md-nav__item"> <a href="../gettingstarted.html" class="md-nav__link">Getting started</a> </li> <li class="md-nav__item"> <a href="../user-guide.html" class="md-nav__link">User Guide</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../user-guide.html#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../regression.html" class="md-nav__link">Linear Regression</a> </li> <li class="md-nav__item"> <a href="../glm.html" class="md-nav__link">Generalized Linear Models</a> </li> <li class="md-nav__item"> <a href="../gee.html" class="md-nav__link">Generalized Estimating Equations</a> </li> <li class="md-nav__item"> <a href="../gam.html" class="md-nav__link">Generalized Additive Models (GAM)</a> </li> <li class="md-nav__item"> <a href="../rlm.html" class="md-nav__link">Robust Linear Models</a> </li> <li class="md-nav__item"> <a href="../mixed_linear.html" class="md-nav__link">Linear Mixed Effects Models</a> </li> <li class="md-nav__item"> <a href="../discretemod.html" class="md-nav__link">Regression with Discrete Dependent Variable</a> </li> <li class="md-nav__item"> <a href="../mixed_glm.html" class="md-nav__link">Generalized Linear Mixed Effects Models</a> </li> <li class="md-nav__item"> <a href="../anova.html" class="md-nav__link">ANOVA</a> </li></ul> </li> <li class="md-nav__item"> <a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a> </li></ul> </li> <li class="md-nav__item"> <a href="../examples/index.html" class="md-nav__link">Examples</a> </li> <li class="md-nav__item"> <a href="../api.html" class="md-nav__link">API Reference</a> </li> <li class="md-nav__item"> <a href="../about.html" class="md-nav__link">About statsmodels</a> </li> <li class="md-nav__item"> <a href="../dev/index.html" class="md-nav__link">Developer Page</a> </li> <li class="md-nav__item"> <a href="../release/index.html" class="md-nav__link">Release Notes</a> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.genmod.generalized_linear_model.GLM.loglike_mu.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <h1 id="generated-statsmodels-genmod-generalized-linear-model-glm-loglike-mu--page-root">statsmodels.genmod.generalized_linear_model.GLM.loglike_mu<a class="headerlink" href="#generated-statsmodels-genmod-generalized-linear-model-glm-loglike-mu--page-root" title="Permalink to this headline">¶</a></h1> <dl class="py method"> <dt id="statsmodels.genmod.generalized_linear_model.GLM.loglike_mu"> <code class="sig-prename descclassname">GLM.</code><code class="sig-name descname">loglike_mu</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">mu</span></em>, <em class="sig-param"><span class="n">scale</span><span class="o">=</span><span class="default_value">1.0</span></em><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/genmod/generalized_linear_model.html#GLM.loglike_mu"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#statsmodels.genmod.generalized_linear_model.GLM.loglike_mu" title="Permalink to this definition">¶</a></dt> <dd><p>Evaluate the log-likelihood for a generalized linear model.</p> </dd></dl> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="statsmodels.genmod.generalized_linear_model.GLM.loglike.html" title="statsmodels.genmod.generalized_linear_model.GLM.loglike" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> statsmodels.genmod.generalized_linear_model.GLM.loglike </span> </div> </a> <a href="statsmodels.genmod.generalized_linear_model.GLM.predict.html" title="statsmodels.genmod.generalized_linear_model.GLM.predict" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> statsmodels.genmod.generalized_linear_model.GLM.predict </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. </div> Last updated on Oct 29, 2020. <br/> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 3.2.1. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html>
{ "content_hash": "0d8c32622a5fb84809265563fd503b84", "timestamp": "", "source": "github", "line_count": 491, "max_line_length": 999, "avg_line_length": 38.05906313645621, "alnum_prop": 0.5959758120618612, "repo_name": "statsmodels/statsmodels.github.io", "id": "9b3c78dadd5855f892496f4a98c2b8e2e617a8b3", "size": "18691", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "v0.12.1/generated/statsmodels.genmod.generalized_linear_model.GLM.loglike_mu.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
using System.Diagnostics; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; namespace System.Reflection.Internal { [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] internal unsafe struct MemoryBlock { internal readonly byte* Pointer; internal readonly int Length; internal MemoryBlock(byte* buffer, int length) { Debug.Assert(length >= 0 && (buffer != null || length == 0)); this.Pointer = buffer; this.Length = length; } internal static MemoryBlock CreateChecked(byte* buffer, int length) { if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length)); } if (buffer == null && length != 0) { throw new ArgumentNullException(nameof(buffer)); } // the reader performs little-endian specific operations if (!BitConverter.IsLittleEndian) { throw new PlatformNotSupportedException(SR.LitteEndianArchitectureRequired); } return new MemoryBlock(buffer, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void CheckBounds(int offset, int byteCount) { if (unchecked((ulong)(uint)offset + (uint)byteCount) > (ulong)Length) { Throw.OutOfBounds(); } } [MethodImpl(MethodImplOptions.NoInlining)] internal static void ThrowValueOverflow() { throw new BadImageFormatException(SR.ValueTooLarge); } internal byte[] ToArray() { return Pointer == null ? null : PeekBytes(0, Length); } private string GetDebuggerDisplay() { if (Pointer == null) { return "<null>"; } int displayedBytes; return GetDebuggerDisplay(out displayedBytes); } internal string GetDebuggerDisplay(out int displayedBytes) { displayedBytes = Math.Min(Length, 64); string result = BitConverter.ToString(PeekBytes(0, displayedBytes)); if (displayedBytes < Length) { result += "-..."; } return result; } internal string GetDebuggerDisplay(int offset) { if (Pointer == null) { return "<null>"; } int displayedBytes; string display = GetDebuggerDisplay(out displayedBytes); if (offset < displayedBytes) { display = display.Insert(offset * 3, "*"); } else if (displayedBytes == Length) { display += "*"; } else { display += "*..."; } return display; } internal MemoryBlock GetMemoryBlockAt(int offset, int length) { CheckBounds(offset, length); return new MemoryBlock(Pointer + offset, length); } internal byte PeekByte(int offset) { CheckBounds(offset, sizeof(byte)); return Pointer[offset]; } internal int PeekInt32(int offset) { uint result = PeekUInt32(offset); if (unchecked((int)result != result)) { ThrowValueOverflow(); } return (int)result; } internal uint PeekUInt32(int offset) { CheckBounds(offset, sizeof(uint)); return *(uint*)(Pointer + offset); } /// <summary> /// Decodes a compressed integer value starting at offset. /// See Metadata Specification section II.23.2: Blobs and signatures. /// </summary> /// <param name="offset">Offset to the start of the compressed data.</param> /// <param name="numberOfBytesRead">Bytes actually read.</param> /// <returns> /// Value between 0 and 0x1fffffff, or <see cref="BlobReader.InvalidCompressedInteger"/> if the value encoding is invalid. /// </returns> internal int PeekCompressedInteger(int offset, out int numberOfBytesRead) { CheckBounds(offset, 0); byte* ptr = Pointer + offset; long limit = Length - offset; if (limit == 0) { numberOfBytesRead = 0; return BlobReader.InvalidCompressedInteger; } byte headerByte = ptr[0]; if ((headerByte & 0x80) == 0) { numberOfBytesRead = 1; return headerByte; } else if ((headerByte & 0x40) == 0) { if (limit >= 2) { numberOfBytesRead = 2; return ((headerByte & 0x3f) << 8) | ptr[1]; } } else if ((headerByte & 0x20) == 0) { if (limit >= 4) { numberOfBytesRead = 4; return ((headerByte & 0x1f) << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]; } } numberOfBytesRead = 0; return BlobReader.InvalidCompressedInteger; } internal ushort PeekUInt16(int offset) { CheckBounds(offset, sizeof(ushort)); return *(ushort*)(Pointer + offset); } // When reference has tag bits. internal uint PeekTaggedReference(int offset, bool smallRefSize) { return PeekReferenceUnchecked(offset, smallRefSize); } // Use when searching for a tagged or non-tagged reference. // The result may be an invalid reference and shall only be used to compare with a valid reference. internal uint PeekReferenceUnchecked(int offset, bool smallRefSize) { return smallRefSize ? PeekUInt16(offset) : PeekUInt32(offset); } // When reference has at most 24 bits. internal int PeekReference(int offset, bool smallRefSize) { if (smallRefSize) { return PeekUInt16(offset); } uint value = PeekUInt32(offset); if (!TokenTypeIds.IsValidRowId(value)) { Throw.ReferenceOverflow(); } return (int)value; } // #String, #Blob heaps internal int PeekHeapReference(int offset, bool smallRefSize) { if (smallRefSize) { return PeekUInt16(offset); } uint value = PeekUInt32(offset); if (!HeapHandleType.IsValidHeapOffset(value)) { Throw.ReferenceOverflow(); } return (int)value; } internal Guid PeekGuid(int offset) { CheckBounds(offset, sizeof(Guid)); return *(Guid*)(Pointer + offset); } internal string PeekUtf16(int offset, int byteCount) { CheckBounds(offset, byteCount); // doesn't allocate a new string if byteCount == 0 return new string((char*)(Pointer + offset), 0, byteCount / sizeof(char)); } internal string PeekUtf8(int offset, int byteCount) { CheckBounds(offset, byteCount); return Encoding.UTF8.GetString(Pointer + offset, byteCount); } /// <summary> /// Read UTF8 at the given offset up to the given terminator, null terminator, or end-of-block. /// </summary> /// <param name="offset">Offset in to the block where the UTF8 bytes start.</param> /// <param name="prefix">UTF8 encoded prefix to prepend to the bytes at the offset before decoding.</param> /// <param name="utf8Decoder">The UTF8 decoder to use that allows user to adjust fallback and/or reuse existing strings without allocating a new one.</param> /// <param name="numberOfBytesRead">The number of bytes read, which includes the terminator if we did not hit the end of the block.</param> /// <param name="terminator">A character in the ASCII range that marks the end of the string. /// If a value other than '\0' is passed we still stop at the null terminator if encountered first.</param> /// <returns>The decoded string.</returns> internal string PeekUtf8NullTerminated(int offset, byte[] prefix, MetadataStringDecoder utf8Decoder, out int numberOfBytesRead, char terminator = '\0') { Debug.Assert(terminator <= 0x7F); CheckBounds(offset, 0); int length = GetUtf8NullTerminatedLength(offset, out numberOfBytesRead, terminator); return EncodingHelper.DecodeUtf8(Pointer + offset, length, prefix, utf8Decoder); } /// <summary> /// Get number of bytes from offset to given terminator, null terminator, or end-of-block (whichever comes first). /// Returned length does not include the terminator, but numberOfBytesRead out parameter does. /// </summary> /// <param name="offset">Offset in to the block where the UTF8 bytes start.</param> /// <param name="terminator">A character in the ASCII range that marks the end of the string. /// If a value other than '\0' is passed we still stop at the null terminator if encountered first.</param> /// <param name="numberOfBytesRead">The number of bytes read, which includes the terminator if we did not hit the end of the block.</param> /// <returns>Length (byte count) not including terminator.</returns> internal int GetUtf8NullTerminatedLength(int offset, out int numberOfBytesRead, char terminator = '\0') { CheckBounds(offset, 0); Debug.Assert(terminator <= 0x7f); byte* start = Pointer + offset; byte* end = Pointer + Length; byte* current = start; while (current < end) { byte b = *current; if (b == 0 || b == terminator) { break; } current++; } int length = (int)(current - start); numberOfBytesRead = length; if (current < end) { // we also read the terminator numberOfBytesRead++; } return length; } internal int Utf8NullTerminatedOffsetOfAsciiChar(int startOffset, char asciiChar) { CheckBounds(startOffset, 0); Debug.Assert(asciiChar != 0 && asciiChar <= 0x7f); for (int i = startOffset; i < Length; i++) { byte b = Pointer[i]; if (b == 0) { break; } if (b == asciiChar) { return i; } } return -1; } // comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first. internal bool Utf8NullTerminatedEquals(int offset, string text, MetadataStringDecoder utf8Decoder, char terminator, bool ignoreCase) { int firstDifference; FastComparisonResult result = Utf8NullTerminatedFastCompare(offset, text, 0, out firstDifference, terminator, ignoreCase); if (result == FastComparisonResult.Inconclusive) { int bytesRead; string decoded = PeekUtf8NullTerminated(offset, null, utf8Decoder, out bytesRead, terminator); return decoded.Equals(text, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } return result == FastComparisonResult.Equal; } // comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first. internal bool Utf8NullTerminatedStartsWith(int offset, string text, MetadataStringDecoder utf8Decoder, char terminator, bool ignoreCase) { int endIndex; FastComparisonResult result = Utf8NullTerminatedFastCompare(offset, text, 0, out endIndex, terminator, ignoreCase); switch (result) { case FastComparisonResult.Equal: case FastComparisonResult.BytesStartWithText: return true; case FastComparisonResult.Unequal: case FastComparisonResult.TextStartsWithBytes: return false; default: Debug.Assert(result == FastComparisonResult.Inconclusive); int bytesRead; string decoded = PeekUtf8NullTerminated(offset, null, utf8Decoder, out bytesRead, terminator); return decoded.StartsWith(text, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } } internal enum FastComparisonResult { Equal, BytesStartWithText, TextStartsWithBytes, Unequal, Inconclusive } // comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first. internal FastComparisonResult Utf8NullTerminatedFastCompare(int offset, string text, int textStart, out int firstDifferenceIndex, char terminator, bool ignoreCase) { CheckBounds(offset, 0); Debug.Assert(terminator <= 0x7F); byte* startPointer = Pointer + offset; byte* endPointer = Pointer + Length; byte* currentPointer = startPointer; int ignoreCaseMask = StringUtils.IgnoreCaseMask(ignoreCase); int currentIndex = textStart; while (currentIndex < text.Length && currentPointer != endPointer) { byte currentByte = *currentPointer; // note that terminator is not compared case-insensitively even if ignore case is true if (currentByte == 0 || currentByte == terminator) { break; } char currentChar = text[currentIndex]; if ((currentByte & 0x80) == 0 && StringUtils.IsEqualAscii(currentChar, currentByte, ignoreCaseMask)) { currentIndex++; currentPointer++; } else { firstDifferenceIndex = currentIndex; // uncommon non-ascii case --> fall back to slow allocating comparison. return (currentChar > 0x7F) ? FastComparisonResult.Inconclusive : FastComparisonResult.Unequal; } } firstDifferenceIndex = currentIndex; bool textTerminated = currentIndex == text.Length; bool bytesTerminated = currentPointer == endPointer || *currentPointer == 0 || *currentPointer == terminator; if (textTerminated && bytesTerminated) { return FastComparisonResult.Equal; } return textTerminated ? FastComparisonResult.BytesStartWithText : FastComparisonResult.TextStartsWithBytes; } // comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first. internal bool Utf8NullTerminatedStringStartsWithAsciiPrefix(int offset, string asciiPrefix) { // Assumes stringAscii only contains ASCII characters and no nil characters. CheckBounds(offset, 0); // Make sure that we won't read beyond the block even if the block doesn't end with 0 byte. if (asciiPrefix.Length > Length - offset) { return false; } byte* p = Pointer + offset; for (int i = 0; i < asciiPrefix.Length; i++) { Debug.Assert(asciiPrefix[i] > 0 && asciiPrefix[i] <= 0x7f); if (asciiPrefix[i] != *p) { return false; } p++; } return true; } internal int CompareUtf8NullTerminatedStringWithAsciiString(int offset, string asciiString) { // Assumes stringAscii only contains ASCII characters and no nil characters. CheckBounds(offset, 0); byte* p = Pointer + offset; int limit = Length - offset; for (int i = 0; i < asciiString.Length; i++) { Debug.Assert(asciiString[i] > 0 && asciiString[i] <= 0x7f); if (i > limit) { // Heap value is shorter. return -1; } if (*p != asciiString[i]) { // If we hit the end of the heap value (*p == 0) // the heap value is shorter than the string, so we return negative value. return *p - asciiString[i]; } p++; } // Either the heap value name matches exactly the given string or // it is longer so it is considered "greater". return (*p == 0) ? 0 : +1; } internal byte[] PeekBytes(int offset, int byteCount) { CheckBounds(offset, byteCount); if (byteCount == 0) { return EmptyArray<byte>.Instance; } byte[] result = new byte[byteCount]; Marshal.Copy((IntPtr)(Pointer + offset), result, 0, byteCount); return result; } internal int IndexOf(byte b, int start) { CheckBounds(start, 0); byte* p = Pointer + start; byte* end = Pointer + Length; while (p < end) { if (*p == b) { return (int)(p - Pointer); } p++; } return -1; } // same as Array.BinarySearch, but without using IComparer internal int BinarySearch(string[] asciiKeys, int offset) { var low = 0; var high = asciiKeys.Length - 1; while (low <= high) { var middle = low + ((high - low) >> 1); var midValue = asciiKeys[middle]; int comparison = CompareUtf8NullTerminatedStringWithAsciiString(offset, midValue); if (comparison == 0) { return middle; } if (comparison < 0) { high = middle - 1; } else { low = middle + 1; } } return ~low; } /// <summary> /// In a table that specifies children via a list field (e.g. TypeDef.FieldList, TypeDef.MethodList), /// searches for the parent given a reference to a child. /// </summary> /// <returns>Returns row number [0..RowCount).</returns> internal int BinarySearchForSlot( int rowCount, int rowSize, int referenceListOffset, uint referenceValue, bool isReferenceSmall) { int startRowNumber = 0; int endRowNumber = rowCount - 1; uint startValue = PeekReferenceUnchecked(startRowNumber * rowSize + referenceListOffset, isReferenceSmall); uint endValue = PeekReferenceUnchecked(endRowNumber * rowSize + referenceListOffset, isReferenceSmall); if (endRowNumber == 1) { if (referenceValue >= endValue) { return endRowNumber; } return startRowNumber; } while (endRowNumber - startRowNumber > 1) { if (referenceValue <= startValue) { return referenceValue == startValue ? startRowNumber : startRowNumber - 1; } if (referenceValue >= endValue) { return referenceValue == endValue ? endRowNumber : endRowNumber + 1; } int midRowNumber = (startRowNumber + endRowNumber) / 2; uint midReferenceValue = PeekReferenceUnchecked(midRowNumber * rowSize + referenceListOffset, isReferenceSmall); if (referenceValue > midReferenceValue) { startRowNumber = midRowNumber; startValue = midReferenceValue; } else if (referenceValue < midReferenceValue) { endRowNumber = midRowNumber; endValue = midReferenceValue; } else { return midRowNumber; } } return startRowNumber; } /// <summary> /// In a table ordered by a column containing entity references searches for a row with the specified reference. /// </summary> /// <returns>Returns row number [0..RowCount) or -1 if not found.</returns> internal int BinarySearchReference( int rowCount, int rowSize, int referenceOffset, uint referenceValue, bool isReferenceSmall) { int startRowNumber = 0; int endRowNumber = rowCount - 1; while (startRowNumber <= endRowNumber) { int midRowNumber = (startRowNumber + endRowNumber) / 2; uint midReferenceValue = PeekReferenceUnchecked(midRowNumber * rowSize + referenceOffset, isReferenceSmall); if (referenceValue > midReferenceValue) { startRowNumber = midRowNumber + 1; } else if (referenceValue < midReferenceValue) { endRowNumber = midRowNumber - 1; } else { return midRowNumber; } } return -1; } // Row number [0, ptrTable.Length) or -1 if not found. internal int BinarySearchReference( int[] ptrTable, int rowSize, int referenceOffset, uint referenceValue, bool isReferenceSmall) { int startRowNumber = 0; int endRowNumber = ptrTable.Length - 1; while (startRowNumber <= endRowNumber) { int midRowNumber = (startRowNumber + endRowNumber) / 2; uint midReferenceValue = PeekReferenceUnchecked((ptrTable[midRowNumber] - 1) * rowSize + referenceOffset, isReferenceSmall); if (referenceValue > midReferenceValue) { startRowNumber = midRowNumber + 1; } else if (referenceValue < midReferenceValue) { endRowNumber = midRowNumber - 1; } else { return midRowNumber; } } return -1; } /// <summary> /// Calculates a range of rows that have specified value in the specified column in a table that is sorted by that column. /// </summary> internal void BinarySearchReferenceRange( int rowCount, int rowSize, int referenceOffset, uint referenceValue, bool isReferenceSmall, out int startRowNumber, // [0, rowCount) or -1 out int endRowNumber) // [0, rowCount) or -1 { int foundRowNumber = BinarySearchReference( rowCount, rowSize, referenceOffset, referenceValue, isReferenceSmall ); if (foundRowNumber == -1) { startRowNumber = -1; endRowNumber = -1; return; } startRowNumber = foundRowNumber; while (startRowNumber > 0 && PeekReferenceUnchecked((startRowNumber - 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue) { startRowNumber--; } endRowNumber = foundRowNumber; while (endRowNumber + 1 < rowCount && PeekReferenceUnchecked((endRowNumber + 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue) { endRowNumber++; } } /// <summary> /// Calculates a range of rows that have specified value in the specified column in a table that is sorted by that column. /// </summary> internal void BinarySearchReferenceRange( int[] ptrTable, int rowSize, int referenceOffset, uint referenceValue, bool isReferenceSmall, out int startRowNumber, // [0, ptrTable.Length) or -1 out int endRowNumber) // [0, ptrTable.Length) or -1 { int foundRowNumber = BinarySearchReference( ptrTable, rowSize, referenceOffset, referenceValue, isReferenceSmall ); if (foundRowNumber == -1) { startRowNumber = -1; endRowNumber = -1; return; } startRowNumber = foundRowNumber; while (startRowNumber > 0 && PeekReferenceUnchecked((ptrTable[startRowNumber - 1] - 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue) { startRowNumber--; } endRowNumber = foundRowNumber; while (endRowNumber + 1 < ptrTable.Length && PeekReferenceUnchecked((ptrTable[endRowNumber + 1] - 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue) { endRowNumber++; } } // Always RowNumber.... internal int LinearSearchReference( int rowSize, int referenceOffset, uint referenceValue, bool isReferenceSmall) { int currOffset = referenceOffset; int totalSize = this.Length; while (currOffset < totalSize) { uint currReference = PeekReferenceUnchecked(currOffset, isReferenceSmall); if (currReference == referenceValue) { return currOffset / rowSize; } currOffset += rowSize; } return -1; } internal bool IsOrderedByReferenceAscending( int rowSize, int referenceOffset, bool isReferenceSmall) { int offset = referenceOffset; int totalSize = this.Length; uint previous = 0; while (offset < totalSize) { uint current = PeekReferenceUnchecked(offset, isReferenceSmall); if (current < previous) { return false; } previous = current; offset += rowSize; } return true; } internal int[] BuildPtrTable( int numberOfRows, int rowSize, int referenceOffset, bool isReferenceSmall) { int[] ptrTable = new int[numberOfRows]; uint[] unsortedReferences = new uint[numberOfRows]; for (int i = 0; i < ptrTable.Length; i++) { ptrTable[i] = i + 1; } ReadColumn(unsortedReferences, rowSize, referenceOffset, isReferenceSmall); Array.Sort(ptrTable, (int a, int b) => { return unsortedReferences[a - 1].CompareTo(unsortedReferences[b - 1]); }); return ptrTable; } private void ReadColumn( uint[] result, int rowSize, int referenceOffset, bool isReferenceSmall) { int offset = referenceOffset; int totalSize = this.Length; int i = 0; while (offset < totalSize) { result[i] = PeekReferenceUnchecked(offset, isReferenceSmall); offset += rowSize; i++; } Debug.Assert(i == result.Length); } internal bool PeekHeapValueOffsetAndSize(int index, out int offset, out int size) { int bytesRead; int numberOfBytes = PeekCompressedInteger(index, out bytesRead); if (numberOfBytes == BlobReader.InvalidCompressedInteger) { offset = 0; size = 0; return false; } offset = index + bytesRead; size = numberOfBytes; return true; } } }
{ "content_hash": "e432913f4528a19481c195ae66deb0ab", "timestamp": "", "source": "github", "line_count": 885, "max_line_length": 171, "avg_line_length": 33.833898305084745, "alnum_prop": 0.5200881675182848, "repo_name": "SGuyGe/corefx", "id": "4b2402ecb0255b336e610c51ee9120f27c012052", "size": "30147", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "src/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/MemoryBlock.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "25588" }, { "name": "C", "bytes": "1120594" }, { "name": "C#", "bytes": "97540100" }, { "name": "C++", "bytes": "331826" }, { "name": "CMake", "bytes": "38893" }, { "name": "DIGITAL Command Language", "bytes": "26402" }, { "name": "Groff", "bytes": "4236" }, { "name": "Groovy", "bytes": "33972" }, { "name": "Makefile", "bytes": "9085" }, { "name": "Perl", "bytes": "3895" }, { "name": "PowerShell", "bytes": "18952" }, { "name": "Python", "bytes": "1535" }, { "name": "Shell", "bytes": "54393" }, { "name": "Visual Basic", "bytes": "829972" } ], "symlink_target": "" }
using System; using System.Threading.Tasks; using Nest; namespace Profiling.Async { public class ClearScrollAsync : IAsyncProfiledOperation { public Task RunAsync(IElasticClient client, ColoredConsoleWriter output) { throw new NotImplementedException(); } } }
{ "content_hash": "5726f687fc0aa33fd0c638e86ec21179", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 74, "avg_line_length": 19.428571428571427, "alnum_prop": 0.7830882352941176, "repo_name": "TheFireCookie/elasticsearch-net", "id": "0a33065b589bd459603128936e141247d10343e0", "size": "272", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "src/Profiling/Async/ClearScrollAsync.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1511" }, { "name": "C#", "bytes": "7306106" }, { "name": "F#", "bytes": "33028" }, { "name": "HTML", "bytes": "401915" }, { "name": "Shell", "bytes": "698" }, { "name": "Smalltalk", "bytes": "3426" } ], "symlink_target": "" }
require 'amor/constraint' module Amor describe Constraint do describe '.new' do before(:each) do @lhs = Expression.new(4) @rhs = Expression.new(8) end it 'returns a Constraint with the given left hand side' do expect(Constraint.new(@lhs, :lesser_equal, @rhs).lhs).to eql(@lhs) end it 'returns a Constraint with the given right hand side' do expect(Constraint.new(@lhs, :lesser_equal, @rhs).rhs).to eql(@rhs) end it 'returns a Constraint with the given relation' do expect(Constraint.new(@lhs, :lesser_equal, @rhs).relation).to eq(:lesser_equal) end end describe '#lp_string' do it 'returns a LP format ready version of the constraint' do model = Model.new v1 = model.x(1) v2 = model.x(2) v3 = model.x(3) constraint = model.st(Constraint.new(Expression.new([[3, v1], [-2.0, v2], [2, :constant], [2.5, v3]]), :lesser_equal, Expression.new(5))) expect(constraint.lp_string).to eq('c1: 3 x1 - 2.0 x2 + 2.5 x3 <= 3') end end describe '#lp_name' do it 'returns the indexed contraint name' do model = Model.new v1 = model.x(1) v2 = model.x(2) v3 = model.x(3) constraint = model.st(Constraint.new(Expression.new([[3, v1], [-2.0, v2], [2, :constant], [2.5, v3]]), :lesser_equal, Expression.new(5))) expect(constraint.lp_name).to eq("c1") end end end end
{ "content_hash": "081974d24b30192bc48768f7176d9139", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 145, "avg_line_length": 31.659574468085108, "alnum_prop": 0.5860215053763441, "repo_name": "philosophus/amor", "id": "a40b6111f7fc89877be0d9d68288d26c0bb61d2d", "size": "1488", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/amor/constraint_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "44093" } ], "symlink_target": "" }
package org.codehaus.groovy.runtime; import groovy.util.GroovyTestCase; import java.util.Iterator; import java.util.Map; /** * @author <a href="mailto:james@coredevelopers.net">James Strachan</a> */ public class TupleListTest extends GroovyTestCase { public void testIterateOverTuple() throws Exception { StringBuilder buffer = new StringBuilder(); for (Iterator iter = InvokerHelper.asIterator(InvokerHelper.createTuple(new Object[]{"a", "b", "c"})); iter.hasNext(); ) { Object i = iter.next(); buffer.append(i); } assertEquals("buffer", "abc", buffer.toString()); } public void testIterateOverList() throws Exception { StringBuilder buffer = new StringBuilder(); for (Iterator iter = InvokerHelper.asIterator(InvokerHelper.createList(new Object[]{"a", "b", "c"})); iter.hasNext(); ) { Object i = iter.next(); buffer.append(i); } assertEquals("buffer", "abc", buffer.toString()); } public void testCreateMap() throws Exception { Map map = InvokerHelper.createMap(new Object[]{"a", "x", "b", "y"}); assertNotNull("map", map); assertEquals("size", 2, map.size()); assertEquals("value of a", "x", map.get("a")); assertEquals("value of b", "y", map.get("b")); } }
{ "content_hash": "90729d5c70746329c42e321190c87ca5", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 110, "avg_line_length": 29.95744680851064, "alnum_prop": 0.5894886363636364, "repo_name": "OpenBEL/kam-nav", "id": "bc393548b4211a1aed4cab7007a49549c9f7116d", "size": "2230", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tools/groovy/src/src/test/org/codehaus/groovy/runtime/TupleListTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "163791" }, { "name": "Shell", "bytes": "8325" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Tavis.OpenApi; using Xunit; namespace OpenApiTests { public class OAIExampleTests { HttpClient client; public OAIExampleTests() { client = new HttpClient(); client.BaseAddress = new Uri("https://raw.githubusercontent.com/OAI/OpenAPI-Specification/OpenAPI.next/examples/v3.0/"); } [Fact] public async Task SimplePetStore() { var stream = await client.GetStreamAsync("petstore.yaml"); var context = OpenApiParser.Parse(stream); var openApiDoc = context.OpenApiDocument; Assert.Equal(0,context.ParseErrors.Count()); } [Fact] public async Task UberExample() { var stream = await client.GetStreamAsync("uber.yaml"); var context = OpenApiParser.Parse(stream); var openApiDoc = context.OpenApiDocument; Assert.Equal(0, context.ParseErrors.Count()); } [Fact] public async Task PetStoreExpandedExample() { var stream = await client.GetStreamAsync("petstore-expanded.yaml"); var context = OpenApiParser.Parse(stream); var openApiDoc = context.OpenApiDocument; Assert.Equal(0, context.ParseErrors.Count()); } [Fact(Skip = "Example is not updated yet")] public async Task ApiWithExamples() { var stream = await client.GetStreamAsync("api-with-examples.yaml"); var context = OpenApiParser.Parse(stream); var openApiDoc = context.OpenApiDocument; Assert.Equal(0, context.ParseErrors.Count()); } } }
{ "content_hash": "29ecd289ecf983552fc67e8262f1849d", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 132, "avg_line_length": 30.229508196721312, "alnum_prop": 0.6117136659436009, "repo_name": "tavis-software/Tavis.OpenApi", "id": "f2e7b6258c8ffd21597fc9d757f144d3ff20a3f5", "size": "1846", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/OpenApiTests/OAIExampleTests.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "104" }, { "name": "Batchfile", "bytes": "222" }, { "name": "C#", "bytes": "234375" }, { "name": "CSS", "bytes": "33351" }, { "name": "HTML", "bytes": "2943" }, { "name": "JavaScript", "bytes": "302750" } ], "symlink_target": "" }
cask :v1 => 'spacemonkey' do version :latest sha256 :no_check url 'http://downloads.spacemonkey.com/client/mac/latest' appcast 'https://rink.hockeyapp.net/api/2/apps/aa33b6780fdfc71247b2995fa47b5d7c' homepage 'https://www.spacemonkey.com' license :unknown app 'SpaceMonkey.app' end
{ "content_hash": "6a8b246b139cd1de10950e7b05039191", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 82, "avg_line_length": 27.09090909090909, "alnum_prop": 0.7449664429530202, "repo_name": "L2G/homebrew-cask", "id": "e3817ad098d37fdca268e69a4700883f22975b1d", "size": "298", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "Casks/spacemonkey.rb", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Ruby", "bytes": "1147444" }, { "name": "Shell", "bytes": "53923" } ], "symlink_target": "" }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE190_Integer_Overflow__unsigned_int_fscanf_add_03.c Label Definition File: CWE190_Integer_Overflow.label.xml Template File: sources-sinks-03.tmpl.c */ /* * @description * CWE: 190 Integer Overflow * BadSource: fscanf Read data from the console using fscanf() * GoodSource: Set data to a small, non-zero number (two) * Sinks: add * GoodSink: Ensure there will not be an overflow before adding 1 to data * BadSink : Add 1 to data, which can cause an overflow * Flow Variant: 03 Control flow: if(5==5) and if(5!=5) * * */ #include "std_testcase.h" #ifndef OMITBAD void CWE190_Integer_Overflow__unsigned_int_fscanf_add_03_bad() { unsigned int data; data = 0; if(5==5) { /* POTENTIAL FLAW: Use a value input from the console */ fscanf (stdin, "%u", &data); } if(5==5) { { /* POTENTIAL FLAW: Adding 1 to data could cause an overflow */ unsigned int result = data + 1; printUnsignedLine(result); } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodB2G1() - use badsource and goodsink by changing the second 5==5 to 5!=5 */ static void goodB2G1() { unsigned int data; data = 0; if(5==5) { /* POTENTIAL FLAW: Use a value input from the console */ fscanf (stdin, "%u", &data); } if(5!=5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Add a check to prevent an overflow from occurring */ if (data < UINT_MAX) { unsigned int result = data + 1; printUnsignedLine(result); } else { printLine("data value is too large to perform arithmetic safely."); } } } /* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */ static void goodB2G2() { unsigned int data; data = 0; if(5==5) { /* POTENTIAL FLAW: Use a value input from the console */ fscanf (stdin, "%u", &data); } if(5==5) { /* FIX: Add a check to prevent an overflow from occurring */ if (data < UINT_MAX) { unsigned int result = data + 1; printUnsignedLine(result); } else { printLine("data value is too large to perform arithmetic safely."); } } } /* goodG2B1() - use goodsource and badsink by changing the first 5==5 to 5!=5 */ static void goodG2B1() { unsigned int data; data = 0; if(5!=5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Use a small, non-zero value that will not cause an overflow in the sinks */ data = 2; } if(5==5) { { /* POTENTIAL FLAW: Adding 1 to data could cause an overflow */ unsigned int result = data + 1; printUnsignedLine(result); } } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */ static void goodG2B2() { unsigned int data; data = 0; if(5==5) { /* FIX: Use a small, non-zero value that will not cause an overflow in the sinks */ data = 2; } if(5==5) { { /* POTENTIAL FLAW: Adding 1 to data could cause an overflow */ unsigned int result = data + 1; printUnsignedLine(result); } } } void CWE190_Integer_Overflow__unsigned_int_fscanf_add_03_good() { goodB2G1(); goodB2G2(); goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE190_Integer_Overflow__unsigned_int_fscanf_add_03_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE190_Integer_Overflow__unsigned_int_fscanf_add_03_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
{ "content_hash": "771712f03aad241c9e7ac965dd98b371", "timestamp": "", "source": "github", "line_count": 179, "max_line_length": 91, "avg_line_length": 26.212290502793294, "alnum_prop": 0.565004262574595, "repo_name": "JianpingZeng/xcc", "id": "451552f32a96835bcc521c65542c3b64a205026e", "size": "4692", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "xcc/test/juliet/testcases/CWE190_Integer_Overflow/s05/CWE190_Integer_Overflow__unsigned_int_fscanf_add_03.c", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package org.openeos.services.ui.form.abstractform; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import org.abstractform.binding.BFormInstance; import org.abstractform.core.FormInstance; import org.abstractform.core.fluent.selector.AbstractSelectorProvider; import org.hibernate.Criteria; import org.hibernate.SessionFactory; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Restrictions; import org.hibernate.type.BooleanType; import org.hibernate.type.StringType; import org.hibernate.type.Type; import org.mvel2.CompileException; import org.mvel2.MVEL; import org.openeos.services.dictionary.IIdentificationCapable; import org.openeos.services.ui.internal.UIBeanImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.transaction.annotation.Transactional; public class UIBeanSelectorProvider<T> extends AbstractSelectorProvider<T> { private static final Logger LOG = LoggerFactory.getLogger(UIBeanSelectorProvider.class); private SessionFactory sessionFactory; private Class<T> beanClass; private FormInstance formInstance; private String sqlRestriction; public UIBeanSelectorProvider(SessionFactory sessionFactory, Class<T> beanClass, FormInstance formInstance, String sqlRestriction) { this.sessionFactory = sessionFactory; this.beanClass = beanClass; this.formInstance = formInstance; this.sqlRestriction = sqlRestriction; if (sqlRestriction != null && formInstance instanceof BFormInstance<?, ?>) { this.formInstance.addFieldChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { // TODO This is not good idea, maybe cached query, check if query changed and fire if it changed. fireElementsChanged(); } }); } } @Override @Transactional(readOnly = true) public SortedSet<T> getElements() { Criteria crit = sessionFactory.getCurrentSession().createCriteria(beanClass); if (sqlRestriction != null && formInstance instanceof BFormInstance<?, ?>) { Object value = ((BFormInstance<?, ?>) formInstance).getValue(); if (value instanceof UIBeanImpl) { value = ((UIBeanImpl) value).getBeanWrapped(); } crit.add(buildSqlRestriction(sqlRestriction, value)); } final List<T> listElements = crit.list(); TreeSet<T> result = new TreeSet<T>(new Comparator<T>() { @Override public int compare(T o1, T o2) { return Integer.compare(listElements.indexOf(o1), listElements.indexOf(o2)); } }); result.addAll(listElements); return result; } private Criterion buildSqlRestriction(String sqlRestriction, Object value) { try { String result = sqlRestriction; int first = result.indexOf("@"); List<Object> values = new ArrayList<Object>(); List<Type> types = new ArrayList<Type>(); while (first != -1) { String parameter = result.substring(first); int second = parameter.indexOf("@", 1); if (second == -1) { LOG.warn("There are a sql restrictoion not well formed, the sql restriction is: '{}' for bean class {} ", sqlRestriction, beanClass.getName()); break; } parameter = parameter.substring(0, second + 1); String parameterWithoutRim = parameter.substring(1, parameter.length() - 1); Map<String, Object> mvelContext = new HashMap<String, Object>(); mvelContext.put("source", value); Object parameterValue = MVEL.eval(parameterWithoutRim, mvelContext); // TODO Make more types if (String.class.isAssignableFrom(parameterValue.getClass())) { values.add(parameterValue); types.add(StringType.INSTANCE); } else if (Boolean.class.isAssignableFrom(parameterValue.getClass())) { values.add(parameterValue); types.add(BooleanType.INSTANCE); } else { throw new UnsupportedOperationException(); } result = result.substring(0, first) + "? " + result.substring(second + first + 1); first = result.indexOf("@"); } Type[] t = new Type[types.size()]; return Restrictions.sqlRestriction(result, values.toArray(), types.toArray(t)); } catch (CompileException ex) { LOG.warn(String.format("Compiling validation expression '%s' of class '%s' has thrown an error: %s", sqlRestriction, beanClass.toString(), ex.getMessage()), ex); return Restrictions.sqlRestriction("0=1"); } } @Override public String getText(T element) { if (element instanceof IIdentificationCapable) { IIdentificationCapable identif = (IIdentificationCapable) element; return identif.getIdentifier(); } return element.toString(); } }
{ "content_hash": "62b7d087e83d71a5a8735148c39819da", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 119, "avg_line_length": 35.88721804511278, "alnum_prop": 0.7399958097632516, "repo_name": "frincon/openeos", "id": "b05a7cfca5c89455c492bf5331cc6d320b3b9e1d", "size": "5403", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/org.openeos.services.ui/src/main/java/org/openeos/services/ui/form/abstractform/UIBeanSelectorProvider.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "37665" }, { "name": "CSS", "bytes": "439" }, { "name": "Groovy", "bytes": "4095" }, { "name": "Java", "bytes": "1395884" }, { "name": "Shell", "bytes": "6138" } ], "symlink_target": "" }
enum { WORKER_SHUTDOWN = 0 }; // Master event types enum { WORKER_DIED = -1, WORKER_ONLINE }; typedef struct master_event master_event; typedef struct worker_event worker_event; struct worker_event { int type; void *data; }; struct master_event { int type; void *data; }; void *zeromq_context; int init_event_system(uv_loop_t **event_loop); void cleanup_event_system(uv_loop_t *event_loop); void event_process(uv_loop_t *event_loop); #endif
{ "content_hash": "d7b2dc2547878c4c684fa31fddaffbb8", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 49, "avg_line_length": 12.378378378378379, "alnum_prop": 0.7030567685589519, "repo_name": "CloudSites/OpenBalance", "id": "a098fecb0c3d8eff0b8e1c23716e7872f6f99b45", "size": "597", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/event.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "65546" }, { "name": "C++", "bytes": "208" }, { "name": "Makefile", "bytes": "260" }, { "name": "Python", "bytes": "1930" } ], "symlink_target": "" }
/* DO NOT EDIT THIS FILE - the content was created using a source code generator */ #ifndef QCANDLESTICKMODELMAPPERSLOTS_H #define QCANDLESTICKMODELMAPPERSLOTS_H #include <QtCore/QObject> #include <QtCore/QCoreApplication> #include <QtCore/QString> #if (QT_VERSION >= QT_VERSION_CHECK(5,8,0)) #include <QtCharts/QCandlestickModelMapper> #endif #include "qt5xhb_common.h" #include "qt5xhb_macros.h" #include "qt5xhb_utils.h" #include "qt5xhb_signals.h" #if (QT_VERSION >= QT_VERSION_CHECK(5,8,0)) using namespace QtCharts; #endif class QCandlestickModelMapperSlots: public QObject { Q_OBJECT public: QCandlestickModelMapperSlots( QObject *parent = 0 ); ~QCandlestickModelMapperSlots(); public slots: #if (QT_VERSION >= QT_VERSION_CHECK(5,8,0)) void modelReplaced(); #endif #if (QT_VERSION >= QT_VERSION_CHECK(5,8,0)) void seriesReplaced(); #endif }; #endif /* QCANDLESTICKMODELMAPPERSLOTS_H */
{ "content_hash": "a27a33526a24d6ad9c36c101f91c3a28", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 79, "avg_line_length": 22.857142857142858, "alnum_prop": 0.7104166666666667, "repo_name": "marcosgambeta/Qt5xHb", "id": "5a22ebaa6128a94d38a0fffb7d117abb02df0a40", "size": "1123", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "source/QtCharts/QCandlestickModelMapperSlots.h", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "32864" }, { "name": "C", "bytes": "450079" }, { "name": "C++", "bytes": "2140920" }, { "name": "Charity", "bytes": "8108" }, { "name": "Makefile", "bytes": "250157" }, { "name": "QML", "bytes": "894" }, { "name": "xBase", "bytes": "18166801" } ], "symlink_target": "" }
<?php /** * @package SugiPHP.Money */ namespace SugiPHP\Money; class UnknownCurrencyException extends \Exception { }
{ "content_hash": "e27a1c5419fb1c97b4f4e34b353f11ab", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 49, "avg_line_length": 11.090909090909092, "alnum_prop": 0.7213114754098361, "repo_name": "SugiPHP/Money", "id": "1f6aaeac090c8ae8c12905acb5e5bf13c524efba", "size": "122", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "UnknownCurrencyException.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "35501" } ], "symlink_target": "" }
// Copyright 2014 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.rules.cpp; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.actions.ParameterFile; import com.google.devtools.build.lib.analysis.ConfiguredTarget; import com.google.devtools.build.lib.analysis.OutputGroupProvider; import com.google.devtools.build.lib.analysis.RuleConfiguredTarget.Mode; import com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder; import com.google.devtools.build.lib.analysis.RuleContext; import com.google.devtools.build.lib.analysis.Runfiles; import com.google.devtools.build.lib.analysis.RunfilesProvider; import com.google.devtools.build.lib.analysis.RunfilesSupport; import com.google.devtools.build.lib.analysis.TransitiveInfoCollection; import com.google.devtools.build.lib.analysis.actions.FileWriteAction; import com.google.devtools.build.lib.analysis.actions.SpawnAction; import com.google.devtools.build.lib.collect.nestedset.NestedSet; import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder; import com.google.devtools.build.lib.collect.nestedset.Order; import com.google.devtools.build.lib.packages.TargetUtils; import com.google.devtools.build.lib.rules.RuleConfiguredTargetFactory; import com.google.devtools.build.lib.rules.apple.Platform; import com.google.devtools.build.lib.rules.cpp.CcToolchainFeatures.FeatureConfiguration; import com.google.devtools.build.lib.rules.cpp.CppConfiguration.DynamicMode; import com.google.devtools.build.lib.rules.cpp.Link.LinkStaticness; import com.google.devtools.build.lib.rules.cpp.Link.LinkTargetType; import com.google.devtools.build.lib.rules.cpp.LinkerInputs.LibraryToLink; import com.google.devtools.build.lib.rules.test.ExecutionInfoProvider; import com.google.devtools.build.lib.rules.test.InstrumentedFilesProvider; import com.google.devtools.build.lib.syntax.Type; import com.google.devtools.build.lib.util.FileTypeSet; import com.google.devtools.build.lib.util.OsUtils; import com.google.devtools.build.lib.util.Preconditions; import com.google.devtools.build.lib.vfs.FileSystemUtils; import com.google.devtools.build.lib.vfs.PathFragment; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * A ConfiguredTarget for <code>cc_binary</code> rules. */ public abstract class CcBinary implements RuleConfiguredTargetFactory { private final CppSemantics semantics; protected CcBinary(CppSemantics semantics) { this.semantics = semantics; } // TODO(bazel-team): should this use Link.SHARED_LIBRARY_FILETYPES? private static final FileTypeSet SHARED_LIBRARY_FILETYPES = FileTypeSet.of( CppFileTypes.SHARED_LIBRARY, CppFileTypes.VERSIONED_SHARED_LIBRARY); /** * The maximum number of inputs for any single .dwp generating action. For cases where * this value is exceeded, the action is split up into "batches" that fall under the limit. * See {@link #createDebugPackagerActions} for details. */ @VisibleForTesting public static final int MAX_INPUTS_PER_DWP_ACTION = 100; /** * Intermediate dwps are written to this subdirectory under the main dwp's output path. */ @VisibleForTesting public static final String INTERMEDIATE_DWP_DIR = "_dwps"; private static Runfiles collectRunfiles( RuleContext context, CcLinkingOutputs linkingOutputs, CppCompilationContext cppCompilationContext, LinkStaticness linkStaticness, NestedSet<Artifact> filesToBuild, Iterable<Artifact> fakeLinkerInputs, boolean fake, ImmutableSet<CppSource> cAndCppSources) { Runfiles.Builder builder = new Runfiles.Builder( context.getWorkspaceName(), context.getConfiguration().legacyExternalRunfiles()); Function<TransitiveInfoCollection, Runfiles> runfilesMapping = CppRunfilesProvider.runfilesFunction(linkStaticness != LinkStaticness.DYNAMIC); boolean linkshared = isLinkShared(context); builder.addTransitiveArtifacts(filesToBuild); // Add the shared libraries to the runfiles. This adds any shared libraries that are in the // srcs of this target. builder.addArtifacts(linkingOutputs.getLibrariesForRunfiles(true)); builder.addRunfiles(context, RunfilesProvider.DEFAULT_RUNFILES); builder.add(context, runfilesMapping); CcToolchainProvider toolchain = CppHelper.getToolchain(context); // Add the C++ runtime libraries if linking them dynamically. if (linkStaticness == LinkStaticness.DYNAMIC) { builder.addTransitiveArtifacts(toolchain.getDynamicRuntimeLinkInputs()); } // For cc_binary and cc_test rules, there is an implicit dependency on // the malloc library package, which is specified by the "malloc" attribute. // As the BUILD encyclopedia says, the "malloc" attribute should be ignored // if linkshared=1. if (!linkshared) { TransitiveInfoCollection malloc = CppHelper.mallocForTarget(context); builder.addTarget(malloc, RunfilesProvider.DEFAULT_RUNFILES); builder.addTarget(malloc, runfilesMapping); } if (fake) { // Add the object files, libraries, and linker scripts that are used to // link this executable. builder.addSymlinksToArtifacts(Iterables.filter(fakeLinkerInputs, Artifact.MIDDLEMAN_FILTER)); // The crosstool inputs for the link action are not sufficient; we also need the crosstool // inputs for compilation. Node that these cannot be middlemen because Runfiles does not // know how to expand them. builder.addTransitiveArtifacts(toolchain.getCrosstool()); builder.addTransitiveArtifacts(toolchain.getLibcLink()); // Add the sources files that are used to compile the object files. // We add the headers in the transitive closure and our own sources in the srcs // attribute. We do not provide the auxiliary inputs, because they are only used when we // do FDO compilation, and cc_fake_binary does not support FDO. ImmutableSet.Builder<Artifact> sourcesBuilder = ImmutableSet.<Artifact>builder(); for (CppSource cppSource : cAndCppSources) { sourcesBuilder.add(cppSource.getSource()); } builder.addSymlinksToArtifacts(sourcesBuilder.build()); builder.addSymlinksToArtifacts(cppCompilationContext.getDeclaredIncludeSrcs()); // Add additional files that are referenced from the compile command, like module maps // or header modules. builder.addSymlinksToArtifacts( cppCompilationContext.getAdditionalInputs( CppHelper.usePic(context, !isLinkShared(context)))); } return builder.build(); } @Override public ConfiguredTarget create(RuleContext context) throws InterruptedException, RuleErrorException { return CcBinary.init(semantics, context, /*fake =*/ false, /*isTest =*/ false); } public static ConfiguredTarget init(CppSemantics semantics, RuleContext ruleContext, boolean fake, boolean isTest) throws InterruptedException { ruleContext.checkSrcsSamePackage(true); FeatureConfiguration featureConfiguration = CcCommon.configureFeatures(ruleContext); CcCommon common = new CcCommon(ruleContext); CppConfiguration cppConfiguration = ruleContext.getFragment(CppConfiguration.class); PrecompiledFiles precompiledFiles = new PrecompiledFiles(ruleContext); LinkTargetType linkType = isLinkShared(ruleContext) ? LinkTargetType.DYNAMIC_LIBRARY : LinkTargetType.EXECUTABLE; List<String> linkopts = common.getLinkopts(); LinkStaticness linkStaticness = getLinkStaticness(ruleContext, linkopts, cppConfiguration); CcLibraryHelper helper = new CcLibraryHelper(ruleContext, semantics, featureConfiguration) .fromCommon(common) .addSources(common.getSources()) .addDeps(ImmutableList.of(CppHelper.mallocForTarget(ruleContext))) .setFake(fake) .setLinkType(linkType) .addPrecompiledFiles(precompiledFiles); CcLibraryHelper.Info info = helper.build(); CppCompilationContext cppCompilationContext = info.getCppCompilationContext(); CcCompilationOutputs ccCompilationOutputs = info.getCcCompilationOutputs(); // if cc_binary includes "linkshared=1", then gcc will be invoked with // linkopt "-shared", which causes the result of linking to be a shared // library. In this case, the name of the executable target should end // in ".so" or "dylib" or ".dll". PathFragment binaryPath = new PathFragment(ruleContext.getTarget().getName()); if (!isLinkShared(ruleContext)) { binaryPath = new PathFragment(binaryPath.getPathString() + OsUtils.executableExtension()); } Artifact binary = ruleContext.getPackageRelativeArtifact( binaryPath, ruleContext.getConfiguration().getBinDirectory()); CppLinkActionBuilder linkActionBuilder = determineLinkerArguments( ruleContext, common, precompiledFiles, ccCompilationOutputs, cppCompilationContext.getTransitiveCompilationPrerequisites(), fake, binary, linkStaticness, linkopts); linkActionBuilder.setUseTestOnlyFlags(isTest); linkActionBuilder.addNonLibraryInputs(ccCompilationOutputs.getHeaderTokenFiles()); CcToolchainProvider ccToolchain = CppHelper.getToolchain(ruleContext); if (linkStaticness == LinkStaticness.DYNAMIC) { linkActionBuilder.setRuntimeInputs( ccToolchain.getDynamicRuntimeLinkMiddleman(), ccToolchain.getDynamicRuntimeLinkInputs()); } else { linkActionBuilder.setRuntimeInputs( ccToolchain.getStaticRuntimeLinkMiddleman(), ccToolchain.getStaticRuntimeLinkInputs()); // Only force a static link of libgcc if static runtime linking is enabled (which // can't be true if runtimeInputs is empty). // TODO(bazel-team): Move this to CcToolchain. if (!ccToolchain.getStaticRuntimeLinkInputs().isEmpty()) { linkActionBuilder.addLinkopt("-static-libgcc"); } } linkActionBuilder.setLinkType(linkType); linkActionBuilder.setLinkStaticness(linkStaticness); linkActionBuilder.setFake(fake); linkActionBuilder.setFeatureConfiguration(featureConfiguration); CcToolchainFeatures.Variables.Builder buildVariables = new CcToolchainFeatures.Variables.Builder(); buildVariables.addAllVariables(CppHelper.getToolchain(ruleContext).getBuildVariables()); linkActionBuilder.setBuildVariables(buildVariables.build()); if (CppLinkAction.enableSymbolsCounts(cppConfiguration, fake, linkType)) { linkActionBuilder.setSymbolCountsOutput(ruleContext.getPackageRelativeArtifact( CppLinkAction.symbolCountsFileName(binaryPath), ruleContext.getConfiguration().getBinDirectory())); } // Store immutable context for use in other *_binary rules that are implemented by // linking the interpreter (Java, Python, etc.) together with native deps. CppLinkAction.Context linkContext = new CppLinkAction.Context(linkActionBuilder); if (featureConfiguration.isEnabled(CppRuleClasses.THIN_LTO)) { linkActionBuilder.setLTOIndexing(true); CppLinkAction indexAction = linkActionBuilder.build(); ruleContext.registerAction(indexAction); for (LTOBackendArtifacts ltoArtifacts : indexAction.getAllLTOBackendArtifacts()) { boolean usePic = CppHelper.usePic(ruleContext, !isLinkShared(ruleContext)); ltoArtifacts.scheduleLTOBackendAction(ruleContext, usePic); } linkActionBuilder.setLTOIndexing(false); } CppLinkAction linkAction = linkActionBuilder.build(); ruleContext.registerAction(linkAction); LibraryToLink outputLibrary = linkAction.getOutputLibrary(); Iterable<Artifact> fakeLinkerInputs = fake ? linkAction.getInputs() : ImmutableList.<Artifact>of(); Artifact executable = outputLibrary.getArtifact(); CcLinkingOutputs.Builder linkingOutputsBuilder = new CcLinkingOutputs.Builder(); if (isLinkShared(ruleContext)) { if (CppFileTypes.SHARED_LIBRARY.matches(binary.getFilename())) { linkingOutputsBuilder.addDynamicLibrary(outputLibrary); linkingOutputsBuilder.addExecutionDynamicLibrary(outputLibrary); } else { ruleContext.attributeError("linkshared", "'linkshared' used in non-shared library"); } } // Also add all shared libraries from srcs. for (Artifact library : precompiledFiles.getSharedLibraries()) { LibraryToLink symlink = common.getDynamicLibrarySymlink(library, true); linkingOutputsBuilder.addDynamicLibrary(symlink); linkingOutputsBuilder.addExecutionDynamicLibrary(symlink); } CcLinkingOutputs linkingOutputs = linkingOutputsBuilder.build(); NestedSet<Artifact> filesToBuild = NestedSetBuilder.create(Order.STABLE_ORDER, executable); // Create the stripped binary, but don't add it to filesToBuild; it's only built when requested. Artifact strippedFile = ruleContext.getImplicitOutputArtifact( CppRuleClasses.CC_BINARY_STRIPPED); CppHelper.createStripAction(ruleContext, cppConfiguration, executable, strippedFile); DwoArtifactsCollector dwoArtifacts = collectTransitiveDwoArtifacts(ruleContext, ccCompilationOutputs, linkStaticness); Artifact dwpFile = ruleContext.getImplicitOutputArtifact(CppRuleClasses.CC_BINARY_DEBUG_PACKAGE); createDebugPackagerActions(ruleContext, cppConfiguration, dwpFile, dwoArtifacts); // The debug package should include the dwp file only if it was explicitly requested. Artifact explicitDwpFile = dwpFile; if (!cppConfiguration.useFission()) { explicitDwpFile = null; } else { // For cc_test rules, include the dwp in the runfiles if Fission is enabled and the test was // built statically. if (TargetUtils.isTestRule(ruleContext.getRule()) && linkStaticness != LinkStaticness.DYNAMIC && cppConfiguration.shouldBuildTestDwp()) { filesToBuild = NestedSetBuilder.fromNestedSet(filesToBuild).add(dwpFile).build(); } } // TODO(bazel-team): Do we need to put original shared libraries (along with // mangled symlinks) into the RunfilesSupport object? It does not seem // logical since all symlinked libraries will be linked anyway and would // not require manual loading but if we do, then we would need to collect // their names and use a different constructor below. Runfiles runfiles = collectRunfiles( ruleContext, linkingOutputs, cppCompilationContext, linkStaticness, filesToBuild, fakeLinkerInputs, fake, helper.getCompilationUnitSources()); RunfilesSupport runfilesSupport = RunfilesSupport.withExecutable( ruleContext, runfiles, executable, ruleContext.getConfiguration().buildRunfiles()); TransitiveLipoInfoProvider transitiveLipoInfo; if (cppConfiguration.isLipoContextCollector()) { transitiveLipoInfo = common.collectTransitiveLipoLabels(ccCompilationOutputs); } else { transitiveLipoInfo = TransitiveLipoInfoProvider.EMPTY; } RuleConfiguredTargetBuilder ruleBuilder = new RuleConfiguredTargetBuilder(ruleContext); addTransitiveInfoProviders( ruleContext, cppConfiguration, common, ruleBuilder, filesToBuild, ccCompilationOutputs, cppCompilationContext, linkingOutputs, dwoArtifacts, transitiveLipoInfo, fake); Map<Artifact, IncludeScannable> scannableMap = new LinkedHashMap<>(); Map<PathFragment, Artifact> sourceFileMap = new LinkedHashMap<>(); if (cppConfiguration.isLipoContextCollector()) { for (IncludeScannable scannable : transitiveLipoInfo.getTransitiveIncludeScannables()) { // These should all be CppCompileActions, which should have only one source file. // This is also checked when they are put into the nested set. Artifact source = Iterables.getOnlyElement(scannable.getIncludeScannerSources()); scannableMap.put(source, scannable); sourceFileMap.put(source.getExecPath(), source); } } // Support test execution on darwin. if (Platform.isApplePlatform(cppConfiguration.getTargetCpu()) && TargetUtils.isTestRule(ruleContext.getRule())) { ruleBuilder.add( ExecutionInfoProvider.class, new ExecutionInfoProvider(ImmutableMap.of("requires-darwin", ""))); } return ruleBuilder .add(RunfilesProvider.class, RunfilesProvider.simple(runfiles)) .add( CppDebugPackageProvider.class, new CppDebugPackageProvider( ruleContext.getLabel(), strippedFile, executable, explicitDwpFile)) .setRunfilesSupport(runfilesSupport, executable) .addProvider(LipoContextProvider.class, new LipoContextProvider( cppCompilationContext, ImmutableMap.copyOf(scannableMap), ImmutableMap.copyOf(sourceFileMap))) .addProvider(CppLinkAction.Context.class, linkContext) .addSkylarkTransitiveInfo(CcSkylarkApiProvider.NAME, new CcSkylarkApiProvider()) .build(); } /** * Given 'temps', traverse this target and its dependencies and collect up all the object files, * libraries, linker options, linkstamps attributes and linker scripts. */ private static CppLinkActionBuilder determineLinkerArguments( RuleContext context, CcCommon common, PrecompiledFiles precompiledFiles, CcCompilationOutputs compilationOutputs, ImmutableSet<Artifact> compilationPrerequisites, boolean fake, Artifact binary, LinkStaticness linkStaticness, List<String> linkopts) { CppLinkActionBuilder builder = new CppLinkActionBuilder(context, binary) .setCrosstoolInputs(CppHelper.getToolchain(context).getLink()) .addNonLibraryInputs(compilationPrerequisites); // Determine the object files to link in. boolean usePic = CppHelper.usePic(context, !isLinkShared(context)); Iterable<Artifact> objectFiles = compilationOutputs.getObjectFiles(usePic); if (fake) { builder.addFakeNonLibraryInputs(objectFiles); } else { builder.addNonLibraryInputs(objectFiles); } builder.addLTOBitcodeFiles(compilationOutputs.getLtoBitcodeFiles()); builder.addNonLibraryInputs(common.getLinkerScripts()); // Determine the libraries to link in. // First libraries from srcs. Shared library artifacts here are substituted with mangled symlink // artifacts generated by getDynamicLibraryLink(). This is done to minimize number of -rpath // entries during linking process. for (Artifact library : precompiledFiles.getLibraries()) { if (SHARED_LIBRARY_FILETYPES.matches(library.getFilename())) { builder.addLibrary(common.getDynamicLibrarySymlink(library, true)); } else { builder.addLibrary(LinkerInputs.opaqueLibraryToLink(library)); } } // Then the link params from the closure of deps. CcLinkParams linkParams = collectCcLinkParams( context, linkStaticness != LinkStaticness.DYNAMIC, isLinkShared(context), linkopts); builder.addLinkParams(linkParams, context); return builder; } /** * Returns "true" if the {@code linkshared} attribute exists and is set. */ private static final boolean isLinkShared(RuleContext context) { return context.attributes().has("linkshared", Type.BOOLEAN) && context.attributes().get("linkshared", Type.BOOLEAN); } private static final boolean dashStaticInLinkopts(List<String> linkopts, CppConfiguration cppConfiguration) { return linkopts.contains("-static") || cppConfiguration.getLinkOptions().contains("-static"); } private static final LinkStaticness getLinkStaticness(RuleContext context, List<String> linkopts, CppConfiguration cppConfiguration) { if (cppConfiguration.getDynamicMode() == DynamicMode.FULLY) { return LinkStaticness.DYNAMIC; } else if (dashStaticInLinkopts(linkopts, cppConfiguration)) { return LinkStaticness.FULLY_STATIC; } else if (cppConfiguration.getDynamicMode() == DynamicMode.OFF || context.attributes().get("linkstatic", Type.BOOLEAN)) { return LinkStaticness.MOSTLY_STATIC; } else { return LinkStaticness.DYNAMIC; } } /** * Collects .dwo artifacts either transitively or directly, depending on the link type. * * <p>For a cc_binary, we only include the .dwo files corresponding to the .o files that are * passed into the link. For static linking, this includes all transitive dependencies. But * for dynamic linking, dependencies are separately linked into their own shared libraries, * so we don't need them here. */ private static DwoArtifactsCollector collectTransitiveDwoArtifacts(RuleContext context, CcCompilationOutputs compilationOutputs, LinkStaticness linkStaticness) { if (linkStaticness == LinkStaticness.DYNAMIC) { return DwoArtifactsCollector.directCollector(compilationOutputs); } else { return CcCommon.collectTransitiveDwoArtifacts(context, compilationOutputs); } } @VisibleForTesting public static Iterable<Artifact> getDwpInputs( RuleContext context, NestedSet<Artifact> picDwoArtifacts, NestedSet<Artifact> dwoArtifacts) { return CppHelper.usePic(context, !isLinkShared(context)) ? picDwoArtifacts : dwoArtifacts; } /** * Creates the actions needed to generate this target's "debug info package" * (i.e. its .dwp file). */ private static void createDebugPackagerActions(RuleContext context, CppConfiguration cppConfiguration, Artifact dwpOutput, DwoArtifactsCollector dwoArtifactsCollector) { Iterable<Artifact> allInputs = getDwpInputs(context, dwoArtifactsCollector.getPicDwoArtifacts(), dwoArtifactsCollector.getDwoArtifacts()); // No inputs? Just generate a trivially empty .dwp. // // Note this condition automatically triggers for any build where fission is disabled. // Because rules referencing .dwp targets may be invoked with or without fission, we need // to support .dwp generation even when fission is disabled. Since no actual functionality // is expected then, an empty file is appropriate. if (Iterables.isEmpty(allInputs)) { context.registerAction( new FileWriteAction(context.getActionOwner(), dwpOutput, "", false)); return; } // Get the tool inputs necessary to run the dwp command. NestedSet<Artifact> dwpTools = CppHelper.getToolchain(context).getDwp(); Preconditions.checkState(!dwpTools.isEmpty()); List<SpawnAction.Builder> packagers = createIntermediateDwpPackagers( context, dwpOutput, cppConfiguration, dwpTools, allInputs, 1); // We apply a hierarchical action structure to limit the maximum number of inputs to any // single action. // // While the dwp tool consumes .dwo files, it can also consume intermediate .dwp files, // allowing us to split a large input set into smaller batches of arbitrary size and order. // Aside from the parallelism performance benefits this offers, this also reduces input // size requirements: if a.dwo, b.dwo, c.dwo, and e.dwo are each 1 KB files, we can apply // two intermediate actions DWP(a.dwo, b.dwo) --> i1.dwp and DWP(c.dwo, e.dwo) --> i2.dwp. // When we then apply the final action DWP(i1.dwp, i2.dwp) --> finalOutput.dwp, the inputs // to this action will usually total far less than 4 KB. // // The actions form an n-ary tree with n == MAX_INPUTS_PER_DWP_ACTION. The tree is fuller // at the leaves than the root, but that both increases parallelism and reduces the final // action's input size. context.registerAction(Iterables.getOnlyElement(packagers) .addArgument("-o") .addOutputArgument(dwpOutput) .setMnemonic("CcGenerateDwp") .build(context)); } /** * Creates the intermediate actions needed to generate this target's * "debug info package" (i.e. its .dwp file). */ private static List<SpawnAction.Builder> createIntermediateDwpPackagers(RuleContext context, Artifact dwpOutput, CppConfiguration cppConfiguration, NestedSet<Artifact> dwpTools, Iterable<Artifact> inputs, int intermediateDwpCount) { List<SpawnAction.Builder> packagers = new ArrayList<>(); // Step 1: generate our batches. We currently break into arbitrary batches of fixed maximum // input counts, but we can always apply more intelligent heuristics if the need arises. SpawnAction.Builder currentPackager = newDwpAction(cppConfiguration, dwpTools); int inputsForCurrentPackager = 0; for (Artifact dwoInput : inputs) { if (inputsForCurrentPackager == MAX_INPUTS_PER_DWP_ACTION) { packagers.add(currentPackager); currentPackager = newDwpAction(cppConfiguration, dwpTools); inputsForCurrentPackager = 0; } currentPackager.addInputArgument(dwoInput); inputsForCurrentPackager++; } packagers.add(currentPackager); // Step 2: given the batches, create the actions. if (packagers.size() > 1) { // If we have multiple batches, make them all intermediate actions, then pipe their outputs // into an additional level. List<Artifact> intermediateOutputs = new ArrayList<>(); for (SpawnAction.Builder packager : packagers) { Artifact intermediateOutput = getIntermediateDwpFile(context, dwpOutput, intermediateDwpCount++); context.registerAction(packager .addArgument("-o") .addOutputArgument(intermediateOutput) .setMnemonic("CcGenerateIntermediateDwp") .build(context)); intermediateOutputs.add(intermediateOutput); } return createIntermediateDwpPackagers( context, dwpOutput, cppConfiguration, dwpTools, intermediateOutputs, intermediateDwpCount); } return packagers; } /** * Returns a new SpawnAction builder for generating dwp files, pre-initialized with * standard settings. */ private static SpawnAction.Builder newDwpAction(CppConfiguration cppConfiguration, NestedSet<Artifact> dwpTools) { return new SpawnAction.Builder() .addTransitiveInputs(dwpTools) .setExecutable(cppConfiguration.getDwpExecutable()) .useParameterFile(ParameterFile.ParameterFileType.UNQUOTED); } /** * Creates an intermediate dwp file keyed off the name and path of the final output. */ private static Artifact getIntermediateDwpFile(RuleContext ruleContext, Artifact dwpOutput, int orderNumber) { PathFragment outputPath = dwpOutput.getRootRelativePath(); PathFragment intermediatePath = FileSystemUtils.appendWithoutExtension(outputPath, "-" + orderNumber); return ruleContext.getPackageRelativeArtifact( new PathFragment(INTERMEDIATE_DWP_DIR + "/" + intermediatePath.getPathString()), dwpOutput.getRoot()); } /** * Collect link parameters from the transitive closure. */ private static CcLinkParams collectCcLinkParams(RuleContext context, boolean linkingStatically, boolean linkShared, List<String> linkopts) { CcLinkParams.Builder builder = CcLinkParams.builder(linkingStatically, linkShared); if (isLinkShared(context)) { // CcLinkingOutputs is empty because this target is not configured yet builder.addCcLibrary(context, false, linkopts, CcLinkingOutputs.EMPTY); } else { builder.addTransitiveTargets( context.getPrerequisites("deps", Mode.TARGET), CcLinkParamsProvider.TO_LINK_PARAMS, CcSpecificLinkParamsProvider.TO_LINK_PARAMS); builder.addTransitiveTarget(CppHelper.mallocForTarget(context)); builder.addLinkOpts(linkopts); } return builder.build(); } private static void addTransitiveInfoProviders( RuleContext ruleContext, CppConfiguration cppConfiguration, CcCommon common, RuleConfiguredTargetBuilder builder, NestedSet<Artifact> filesToBuild, CcCompilationOutputs ccCompilationOutputs, CppCompilationContext cppCompilationContext, CcLinkingOutputs linkingOutputs, DwoArtifactsCollector dwoArtifacts, TransitiveLipoInfoProvider transitiveLipoInfo, boolean fake) { List<Artifact> instrumentedObjectFiles = new ArrayList<>(); instrumentedObjectFiles.addAll(ccCompilationOutputs.getObjectFiles(false)); instrumentedObjectFiles.addAll(ccCompilationOutputs.getObjectFiles(true)); InstrumentedFilesProvider instrumentedFilesProvider = common.getInstrumentedFilesProvider( instrumentedObjectFiles, !TargetUtils.isTestRule(ruleContext.getRule()) && !fake); NestedSet<Artifact> filesToCompile = ccCompilationOutputs.getFilesToCompile( cppConfiguration.isLipoContextCollector(), cppConfiguration.processHeadersInDependencies(), CppHelper.usePic(ruleContext, false)); NestedSet<Artifact> artifactsToForce = collectHiddenTopLevelArtifacts(ruleContext); builder .setFilesToBuild(filesToBuild) .add(CppCompilationContext.class, cppCompilationContext) .add(TransitiveLipoInfoProvider.class, transitiveLipoInfo) .add( CcExecutionDynamicLibrariesProvider.class, new CcExecutionDynamicLibrariesProvider( collectExecutionDynamicLibraryArtifacts( ruleContext, linkingOutputs.getExecutionDynamicLibraries()))) .add( CcNativeLibraryProvider.class, new CcNativeLibraryProvider( collectTransitiveCcNativeLibraries( ruleContext, linkingOutputs.getDynamicLibraries()))) .add(InstrumentedFilesProvider.class, instrumentedFilesProvider) .add( CppDebugFileProvider.class, new CppDebugFileProvider( dwoArtifacts.getDwoArtifacts(), dwoArtifacts.getPicDwoArtifacts())) .addOutputGroup( OutputGroupProvider.TEMP_FILES, getTemps(cppConfiguration, ccCompilationOutputs)) .addOutputGroup(OutputGroupProvider.FILES_TO_COMPILE, filesToCompile) .addOutputGroup(OutputGroupProvider.HIDDEN_TOP_LEVEL, artifactsToForce) .addOutputGroup( OutputGroupProvider.COMPILATION_PREREQUISITES, CcCommon.collectCompilationPrerequisites(ruleContext, cppCompilationContext)); } private static NestedSet<Artifact> collectHiddenTopLevelArtifacts(RuleContext ruleContext) { // Ensure that we build all the dependencies, otherwise users may get confused. NestedSetBuilder<Artifact> artifactsToForceBuilder = NestedSetBuilder.stableOrder(); for (OutputGroupProvider dep : ruleContext.getPrerequisites("deps", Mode.TARGET, OutputGroupProvider.class)) { artifactsToForceBuilder.addTransitive( dep.getOutputGroup(OutputGroupProvider.HIDDEN_TOP_LEVEL)); } return artifactsToForceBuilder.build(); } private static NestedSet<Artifact> collectExecutionDynamicLibraryArtifacts( RuleContext ruleContext, List<LibraryToLink> executionDynamicLibraries) { Iterable<Artifact> artifacts = LinkerInputs.toLibraryArtifacts(executionDynamicLibraries); if (!Iterables.isEmpty(artifacts)) { return NestedSetBuilder.wrap(Order.STABLE_ORDER, artifacts); } Iterable<CcExecutionDynamicLibrariesProvider> deps = ruleContext .getPrerequisites("deps", Mode.TARGET, CcExecutionDynamicLibrariesProvider.class); NestedSetBuilder<Artifact> builder = NestedSetBuilder.stableOrder(); for (CcExecutionDynamicLibrariesProvider dep : deps) { builder.addTransitive(dep.getExecutionDynamicLibraryArtifacts()); } return builder.build(); } private static NestedSet<LinkerInput> collectTransitiveCcNativeLibraries( RuleContext ruleContext, List<? extends LinkerInput> dynamicLibraries) { NestedSetBuilder<LinkerInput> builder = NestedSetBuilder.linkOrder(); builder.addAll(dynamicLibraries); for (CcNativeLibraryProvider dep : ruleContext.getPrerequisites("deps", Mode.TARGET, CcNativeLibraryProvider.class)) { builder.addTransitive(dep.getTransitiveCcNativeLibraries()); } return builder.build(); } private static NestedSet<Artifact> getTemps(CppConfiguration cppConfiguration, CcCompilationOutputs compilationOutputs) { return cppConfiguration.isLipoContextCollector() ? NestedSetBuilder.<Artifact>emptySet(Order.STABLE_ORDER) : compilationOutputs.getTemps(); } }
{ "content_hash": "999f14e3a0a15e926cb4d534caaddf15", "timestamp": "", "source": "github", "line_count": 727, "max_line_length": 100, "avg_line_length": 46.38101788170564, "alnum_prop": 0.7378925828168095, "repo_name": "abergmeier-dsfishlabs/bazel", "id": "f83158feb5b73f745ed68bdd82c1bb55fb593913", "size": "33719", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/com/google/devtools/build/lib/rules/cpp/CcBinary.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "78" }, { "name": "C", "bytes": "49306" }, { "name": "C++", "bytes": "358480" }, { "name": "HTML", "bytes": "17135" }, { "name": "Java", "bytes": "17824773" }, { "name": "Objective-C", "bytes": "6820" }, { "name": "Protocol Buffer", "bytes": "94374" }, { "name": "Python", "bytes": "237314" }, { "name": "Shell", "bytes": "491747" } ], "symlink_target": "" }
Subscribe all members of a room to one or more additional rooms. ```js sails.sockets.addRoomMembersToRooms(sourceRoom, destRooms, cb); ``` ### Usage | | Argument | Type | Details | |---|------------|:-----------:|:--------| | 1 | sourceRoom | ((string)) | The room to retrieve members from. | 2 | destRooms | ((string)), ((array)) | The room or rooms to subscribe the members of `sourceRoom` to. | 3 | _cb_ | ((function?))| An optional callback which will be called when the operation is complete on the current server (see notes below for more information), or if fatal errors were encountered. In the case of errors, it will be called with a single argument (`err`). ### Example In a controller action: ```javascript subscribeFunRoomMembersToFunnerRooms: function(req, res) { sails.sockets.addRoomMembersToRooms('funRoom', ['greatRoom', 'awesomeRoom'], function(err) { if (err) {return res.serverError(err);} res.json({ message: 'Subscribed all members of `funRoom` to `greatRoom` and `awesomeRoom`!' }); }); } ``` ### Notes > + In a multi-server environment, the callback function (`cb`) will be executed when the `.addRoomMembersToRooms()` call completes _on the current server_. This does not guarantee that other servers in the cluster have already finished running the operation. <docmeta name="displayName" value=".addRoomMembersToRooms()"> <docmeta name="pageType" value="method">
{ "content_hash": "8f031f879ae26205999517788a60befd", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 279, "avg_line_length": 39.027027027027025, "alnum_prop": 0.6869806094182825, "repo_name": "yoshioka-s/sails-docs-ja", "id": "1802a10b75c2d904209bc13c4d3d8dfe30ac8541", "size": "1473", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "reference/websockets/sails.sockets/sails.sockets.addRoomMembersToRooms.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "3888" } ], "symlink_target": "" }
SYNONYM #### According to GRIN Taxonomy for Plants #### Published in null #### Original name null ### Remarks null
{ "content_hash": "d5bd8cdd4cf3393926b2cdc65a17fe2c", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 24, "avg_line_length": 9.076923076923077, "alnum_prop": 0.6864406779661016, "repo_name": "mdoering/backbone", "id": "f095289334e9afae42c8ea164c6b2dc66f3cacb5", "size": "163", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Passifloraceae/Passiflora/ Syn. Tetrapathea/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php namespace app\controllers; use Yii; use app\models\form\Contact; use yii\web\Controller; /** * Site controller */ class SiteController extends Controller { /** * @inheritdoc */ public function actions() { return [ 'error' => [ 'class' => 'yii\web\ErrorAction', ], 'captcha' => [ 'class' => 'yii\captcha\CaptchaAction', 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null, ], 'page' => [ 'class' => 'yii\web\ViewAction' ] ]; } public function actionIndex() { return $this->render('index'); } public function actionContact() { $model = new Contact(); if ($model->load(Yii::$app->request->post()) && $model->validate()) { if ($model->sendEmail(Yii::$app->params['adminEmail'])) { Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.'); } else { Yii::$app->session->setFlash('error', 'There was an error sending email.'); } return $this->refresh(); } else { return $this->render('contact', [ 'model' => $model, ]); } } public function actionAbout() { return $this->render('about'); } }
{ "content_hash": "c3242fdd5ffc098e5dd314f4574fd1fa", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 132, "avg_line_length": 23.672131147540984, "alnum_prop": 0.4792243767313019, "repo_name": "GAMITG/yii2-app-angular", "id": "6de6a638b97875a5f0da1723b50463930b6a4fe9", "size": "1444", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/controllers/SiteController.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "270" }, { "name": "Batchfile", "bytes": "1541" }, { "name": "CSS", "bytes": "1364" }, { "name": "PHP", "bytes": "98732" } ], "symlink_target": "" }
#include "condor_common.h" #include "classad/common.h" #include "classad/collection.h" #include "collectionServer.h" #include "classad/transaction.h" using namespace std; BEGIN_NAMESPACE( classad ) //-------------collection server templates------------- // view content template multiset<ViewMember, ViewMemberLT>; template multiset<ViewMember, ViewMemberLT>::iterator; // list of sub-views template slist<View*>; // view registry template hash_map<string,View*,StringHash>; template hash_map<string,View*,StringHash>::iterator; // index template hash_map<string,multiset<ViewMember,ViewMemberLT>::iterator, StringHash>::iterator; template hash_map<string,multiset<ViewMember,ViewMemberLT>::iterator, StringHash>; // main classad table template map<string, int>; template hash_map<string,int,StringHash>; template hash_map<string,int,StringHash>::iterator; template hash_map<string, ClassAdProxy, StringHash>; template hash_map<string, ClassAdProxy, StringHash>::iterator; // transaction registry template hash_map<string, ServerTransaction*, StringHash>; template hash_map<string, ServerTransaction*, StringHash>::iterator; // operations in transaction template list<XactionRecord>; END_NAMESPACE
{ "content_hash": "db24c4df83bb234d67a151bc79318624", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 69, "avg_line_length": 28.930232558139537, "alnum_prop": 0.7516077170418006, "repo_name": "clalancette/condor-dcloud", "id": "0de2ed1bd3e4bdc9483af67f6147b8495232a05c", "size": "2052", "binary": false, "copies": "1", "ref": "refs/heads/7.6.0_and_patches", "path": "src/classad_support/coll-serv-inst.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "5541080" }, { "name": "C++", "bytes": "14834293" }, { "name": "FORTRAN", "bytes": "110251" }, { "name": "Java", "bytes": "254868" }, { "name": "Objective-C", "bytes": "20250" }, { "name": "PHP", "bytes": "136301" }, { "name": "Perl", "bytes": "1138002" }, { "name": "Python", "bytes": "48633" }, { "name": "Shell", "bytes": "66481" } ], "symlink_target": "" }
package org.jetbrains.plugins.dotty.lang.parser.parsing /** * @author adkozlov */ object CompilationUnit extends org.jetbrains.plugins.scala.lang.parser.parsing.CompilationUnit { override protected def topStatSeq = TopStatSeq }
{ "content_hash": "b7328430480b6fcad8e54d67542a7c19", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 96, "avg_line_length": 29.375, "alnum_prop": 0.7914893617021277, "repo_name": "loskutov/intellij-scala", "id": "d80434819260472d92144f6ac5fafb8c7a01c034", "size": "235", "binary": false, "copies": "4", "ref": "refs/heads/idea172.x-better-implicits", "path": "src/org/jetbrains/plugins/dotty/lang/parser/parsing/CompilationUnit.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "55566" }, { "name": "Java", "bytes": "1397858" }, { "name": "Lex", "bytes": "35728" }, { "name": "Scala", "bytes": "11387086" }, { "name": "Shell", "bytes": "537" } ], "symlink_target": "" }
package com.xinfan.msgbox.http.session.provider; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ProviderUtils { /** * cookie session键值 */ public static String getRequestedSessionId(HttpServletRequest request) { String sid = request.getRequestedSessionId(); String ctx = request.getContextPath(); String sessionId = (String) request.getAttribute(SessionProvider.CURRENT_SESSION_ID); if (sessionId != null && sessionId.length() > 0) { return sessionId; } sessionId = (String) request.getSession().getAttribute(SessionProvider.CURRENT_SESSION_ID); if (sessionId != null && sessionId.length() > 0) { return sessionId; } // 手动从cookie获取 Cookie cookie = getCookie(request, SessionProvider.COOKIE_SESSION_ID); if (cookie != null) { return cookie.getValue(); } else { return null; } } public static Cookie getCookie(HttpServletRequest request, String name) { Cookie[] cookies = request.getCookies(); if (cookies != null && cookies.length > 0) { for (Cookie c : cookies) { if (c.getName().equals(name)) { return c; } } } return null; } public static Cookie createCookie(HttpServletRequest request, String value) { Cookie cookie = new Cookie(SessionProvider.COOKIE_SESSION_ID, value); String ctx = request.getContextPath(); cookie.setPath((ctx == null || ctx.length() == 0) ? "/" : ctx); return cookie; } public static void clear(HttpServletRequest request, HttpServletResponse response) { String root = ProviderUtils.getRequestedSessionId(request); request.removeAttribute(SessionProvider.CURRENT_SESSION_ID); request.getSession().invalidate(); if (root != null && root.trim().length() > 0) { Cookie cookie = createCookie(request, null); cookie.setMaxAge(0); response.addCookie(cookie); } } }
{ "content_hash": "151e713d0a79189f5d69583ac049481c", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 93, "avg_line_length": 28.3, "alnum_prop": 0.679454820797577, "repo_name": "xinfan123/blue-server", "id": "1b42b8476da9ca74e265fd27931b341d66665fa2", "size": "1995", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bulu-service/src/main/java/com/xinfan/msgbox/http/session/provider/ProviderUtils.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "1445" }, { "name": "Java", "bytes": "1215214" } ], "symlink_target": "" }
:runner: Simple workout tracker API Exposes the following interface for tracking workouts: * report_workout: * workout_type * date (default: today) * notes * report_class (include one of class_id or class_type) * class_id * class_type * get_workouts * start_date (default: beginning of the current month?) * end_date (default: now)
{ "content_hash": "63c070a8143f8e3f7b4546592bce9120", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 57, "avg_line_length": 26.615384615384617, "alnum_prop": 0.7167630057803468, "repo_name": "kylemarsh/fitness", "id": "e9f1fbd90dc3d2914a7ce3b36c87926b369ae26c", "size": "356", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "11302" }, { "name": "HTML", "bytes": "1893" } ], "symlink_target": "" }
'use strict' const nodemailer = require('nodemailer') const config = require('../../../config/config') class Mailer { constructor () { this.transporter = nodemailer.createTransport({ host: config.smtp.host, port: config.smtp.port, secure: config.smtp.secure, auth: config.smtp.auth }) } sendMail (from, to, subject, html, callback) { const mailOptions = { from: '"' + from + '" <' + config.smtp.auth.user + '>', to, subject, html } this.transporter.sendMail(mailOptions, (error, info) => { if (error) return callback(error) callback(null, true) }) } } module.exports = Mailer
{ "content_hash": "8ab321dd978987374a8719e89cbd83da", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 61, "avg_line_length": 22.4, "alnum_prop": 0.5967261904761905, "repo_name": "SherlockStd/ME4N-Starter", "id": "9e471a2b5998e20a86009b230e1e6abcbccd794e", "size": "672", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "server/utils/mailer/mailer.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4066" }, { "name": "HTML", "bytes": "26745" }, { "name": "JavaScript", "bytes": "78084" }, { "name": "TypeScript", "bytes": "35330" } ], "symlink_target": "" }
use actix_web::http::header::HeaderName; use anyhow::Context; use anyhow::Result; use crate::config::AuthenticatorConfig; /// Headers to store user identity information from the authenticator. #[derive(Clone, Debug)] pub struct IdentityHeaders { /// Header to place the user ID in. pub user_id: HeaderName, } impl IdentityHeaders { /// Load the headers to report user identity in from the configuration. pub fn from_config(config: &AuthenticatorConfig) -> Result<IdentityHeaders> { let user_id = HeaderName::from_bytes(config.user_id_header.as_bytes()) .with_context(|| "user ID identity reporting is not valid")?; Ok(IdentityHeaders { user_id }) } } impl Default for IdentityHeaders { fn default() -> IdentityHeaders { IdentityHeaders { user_id: HeaderName::from_static("x-auth-request-user"), } } }
{ "content_hash": "0c5d5079e41d1cf1db3a4989b018baec", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 81, "avg_line_length": 30.655172413793103, "alnum_prop": 0.6760404949381328, "repo_name": "stefano-pogliani/auth-gateway", "id": "49582015ff1f90b197096baeef172b20a4ace794", "size": "889", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/authenticator/identity_headers.rs", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "695" }, { "name": "HTML", "bytes": "4033" }, { "name": "JavaScript", "bytes": "9404" }, { "name": "Rust", "bytes": "89684" }, { "name": "Shell", "bytes": "241" } ], "symlink_target": "" }
package alluxio.underfs.options; import static org.junit.Assert.assertEquals; import alluxio.test.util.CommonUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException; /** * Tests for the {@link FileLocationOptions} class. */ @RunWith(PowerMockRunner.class) public final class FileLocationOptionsTest { /** * Tests for default {@link FileLocationOptions}. */ @Test public void defaults() throws IOException { FileLocationOptions options = FileLocationOptions.defaults(); assertEquals(0, options.getOffset()); } /** * Tests getting and setting fields. */ @Test public void fields() { FileLocationOptions options = FileLocationOptions.defaults(); long[] offsets = {100, 110, 150, 200}; for (long offset : offsets) { options.setOffset(offset); assertEquals(offset, options.getOffset()); } } @Test public void equalsTest() throws Exception { CommonUtils.testEquals(FileLocationOptions.class); } }
{ "content_hash": "d541b8268290ca290e215bba86a4a944", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 65, "avg_line_length": 22.1875, "alnum_prop": 0.7136150234741784, "repo_name": "calvinjia/tachyon", "id": "45dafadad1395d91698ded03a0bd3e43b3efc169", "size": "1577", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "core/common/src/test/java/alluxio/underfs/options/FileLocationOptionsTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "10146" }, { "name": "Dockerfile", "bytes": "5206" }, { "name": "Go", "bytes": "27246" }, { "name": "HTML", "bytes": "7039" }, { "name": "Java", "bytes": "11063149" }, { "name": "JavaScript", "bytes": "6914" }, { "name": "Python", "bytes": "11519" }, { "name": "Roff", "bytes": "5919" }, { "name": "Ruby", "bytes": "19102" }, { "name": "Shell", "bytes": "164560" }, { "name": "Smarty", "bytes": "7836" }, { "name": "TypeScript", "bytes": "274301" } ], "symlink_target": "" }
using System; using System.Data; using System.Linq; using Premotion.Mansion.Core; using Premotion.Mansion.Core.Data; using Premotion.Mansion.Repository.SqlServer.Queries; namespace Premotion.Mansion.Repository.SqlServer.Schemas { /// <summary> /// Represens a <see cref="NodePointer"/> property column. /// </summary> public class NodePointerPropertyColumn : Column { #region Constants private static readonly string[] ReservedPropertyName = new[] {"depth", "pointer", "path", "strucutre", "parentId", "parentPointer", "parentPath", "parentStructure"}; #endregion #region Constructors /// <summary> /// Constructs a column. /// </summary> /// <param name="table">The <see cref="Table"/>.</param> /// <param name="propertyName">The name of the property.</param> public NodePointerPropertyColumn(Table table, string propertyName) : base(propertyName, propertyName, 150) { // validate arguments if (table == null) throw new ArgumentNullException("table"); // add marker columns table.Add(new VirtualColumn("name")); table.Add(new VirtualColumn("type")); table.Add(new VirtualColumn("depth")); table.Add(new VirtualColumn("parentId")); table.Add(new VirtualColumn("parentPointer")); table.Add(new VirtualColumn("parentPath")); table.Add(new VirtualColumn("parentStructure")); } #endregion #region Overrides of Column /// <summary> /// /// </summary> /// <param name="context"></param> /// <param name="queryBuilder"></param> /// <param name="properties"></param> protected override void DoToInsertStatement(IMansionContext context, ModificationQueryBuilder queryBuilder, IPropertyBag properties) { var newPointer = properties.Get<NodePointer>(context, "_newPointer"); queryBuilder.AddColumnValue("name", newPointer.Name.Trim(), DbType.String); queryBuilder.AddColumnValue("type", newPointer.Type.Trim(), DbType.String); queryBuilder.AddColumnValue("depth", newPointer.Depth, DbType.Int32); queryBuilder.AddColumnValue("parentId", newPointer.HasParent ? (object) newPointer.Parent.Id : null, DbType.Int32); queryBuilder.AddColumnValue("parentPointer", newPointer.HasParent ? newPointer.Parent.PointerString + NodePointer.PointerSeparator : null, DbType.String); queryBuilder.AddColumnValue("parentPath", newPointer.HasParent ? newPointer.Parent.PathString + NodePointer.PathSeparator : null, DbType.String); queryBuilder.AddColumnValue("parentStructure", newPointer.HasParent ? newPointer.Parent.StructureString + NodePointer.StructureSeparator : null, DbType.String); } /// <summary> /// /// </summary> /// <param name="context"></param> /// <param name="queryBuilder"></param> /// <param name="record"> </param> /// <param name="modifiedProperties"></param> protected override void DoToUpdateStatement(IMansionContext context, ModificationQueryBuilder queryBuilder, Record record, IPropertyBag modifiedProperties) { // allow update of relational column on special cases, most likely used when fixing the repository integrity if (modifiedProperties.Get(context, "_allowRelationPropertiesUpdate", false)) { string name; if (modifiedProperties.TryGet(context, "name", out name)) queryBuilder.AddColumnValue("name", name, DbType.String); string type; if (modifiedProperties.TryGet(context, "type", out type)) queryBuilder.AddColumnValue("type", type, DbType.String); int depth; if (modifiedProperties.TryGet(context, "depth", out depth)) queryBuilder.AddColumnValue("depth", depth, DbType.Int32); int parentId; if (modifiedProperties.TryGet(context, "parentId", out parentId)) queryBuilder.AddColumnValue("parentId", parentId, DbType.Int32); string parentPointer; if (modifiedProperties.TryGet(context, "parentPointer", out parentPointer)) queryBuilder.AddColumnValue("parentPointer", parentPointer, DbType.String); string parentPath; if (modifiedProperties.TryGet(context, "parentPath", out parentPath)) queryBuilder.AddColumnValue("parentPath", parentPath, DbType.String); string parentStructure; if (modifiedProperties.TryGet(context, "parentStructure", out parentStructure)) queryBuilder.AddColumnValue("parentStructure", parentStructure, DbType.String); return; } // make sure the relational intgrety is not comprimised if (modifiedProperties.Names.Intersect(ReservedPropertyName, StringComparer.OrdinalIgnoreCase).Any()) throw new InvalidOperationException("The relational properties can not be changed"); // get the pointer NodePointer pointer; if (!record.TryGet(context, "pointer", out pointer)) throw new InvalidOperationException("Could not update this record because it did not contain a pointer"); // add the id an pointer parameters var idParameterName = queryBuilder.AddParameter("id", pointer.Id, DbType.Int32); var pointerParameterName = queryBuilder.AddParameter("pointer", pointer.PointerString + "-%", DbType.String); // check if the name changed string newName; if (modifiedProperties.TryGetAndRemove(context, "name", out newName)) { newName = newName.Trim(); if (string.IsNullOrEmpty(newName)) throw new InvalidOperationException("Can not update column name with empty string"); if (newName.Contains(NodePointer.PathSeparator)) throw new InvalidOperationException(string.Format("Name '{0}' contains invalid characters", newName)); if (!pointer.Name.Equals(newName)) { // add the name column modification queryBuilder.AddColumnValue("name", newName, DbType.String); // update the paths var oldPathLengthParameterName = queryBuilder.AddParameter("oldPathLength", pointer.PathString.Length + 1, DbType.String); var newPathParameterName = queryBuilder.AddParameter("newPath", NodePointer.Rename(pointer, newName).PathString + NodePointer.PathSeparator, DbType.String); queryBuilder.AppendQuery(string.Format(@" UPDATE [Nodes] SET [parentPath] = {0} + RIGHT( [parentPath], LEN( [parentPath] ) - {1} ) WHERE ( [parentId] = {2} OR [parentPointer] LIKE {3} )", newPathParameterName, oldPathLengthParameterName, idParameterName, pointerParameterName)); } } // check if the type changed string newType; if (modifiedProperties.TryGetAndRemove(context, "type", out newType)) { newType = newType.Trim(); if (string.IsNullOrEmpty(newType)) throw new InvalidOperationException("Can not update column type with empty string"); if (newType.Contains(NodePointer.StructureSeparator)) throw new InvalidOperationException(string.Format("Type '{0}' contains invalid characters", newType)); if (!string.IsNullOrEmpty(newType) && !pointer.Type.Equals(newType, StringComparison.OrdinalIgnoreCase)) { // add the name column modification queryBuilder.AddColumnValue("type", newType, DbType.String); // update the structures var newStructureParameterName = queryBuilder.AddParameter("newStructure", NodePointer.ChangeType(pointer, newType).StructureString + NodePointer.StructureSeparator, DbType.String); var oldStructureLengthParameterName = queryBuilder.AddParameter("oldStructureLength", pointer.StructureString.Length + 1, DbType.Int32); queryBuilder.AppendQuery(string.Format("UPDATE [Nodes] SET [parentStructure] = {0} + RIGHT( [parentStructure], LEN( [parentStructure] ) - {1} ) WHERE ( [parentId] = {2} OR [parentPointer] LIKE {3} )", newStructureParameterName, oldStructureLengthParameterName, idParameterName, pointerParameterName)); } } } #endregion } }
{ "content_hash": "330fa99d7f4e0b43877d8fcbb3a645b4", "timestamp": "", "source": "github", "line_count": 152, "max_line_length": 306, "avg_line_length": 49.96052631578947, "alnum_prop": 0.7387411114037398, "repo_name": "devatwork/Premotion-Mansion", "id": "c0ae0ca17f8d411a4e5e024192932aa4fa2172f2", "size": "7594", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Premotion.Mansion.Repository.SqlServer/Schemas/NodePointerPropertyColumn.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "768" }, { "name": "Batchfile", "bytes": "3262" }, { "name": "C#", "bytes": "2762697" }, { "name": "CSS", "bytes": "158664" }, { "name": "HTML", "bytes": "61257" }, { "name": "JavaScript", "bytes": "1100387" }, { "name": "PHP", "bytes": "20246" }, { "name": "Pascal", "bytes": "3805" }, { "name": "Smarty", "bytes": "52063" } ], "symlink_target": "" }
namespace Data { using System; using System.Collections.Generic; public partial class Entity_DurationProfile { public int Id { get; set; } public Nullable<int> TypeId { get; set; } public Nullable<int> FromYears { get; set; } public Nullable<int> FromMonths { get; set; } public Nullable<int> FromWeeks { get; set; } public Nullable<int> FromDays { get; set; } public Nullable<int> FromHours { get; set; } public Nullable<int> ToYears { get; set; } public Nullable<int> ToMonths { get; set; } public Nullable<int> ToWeeks { get; set; } public Nullable<int> ToDays { get; set; } public Nullable<int> ToHours { get; set; } public string DurationComment { get; set; } public Nullable<decimal> TotalHours { get; set; } public string FromDuration { get; set; } public string ToDuration { get; set; } public Nullable<System.DateTime> Created { get; set; } public Nullable<int> CreatedById { get; set; } public Nullable<System.DateTime> LastUpdated { get; set; } public Nullable<int> LastUpdatedById { get; set; } public Nullable<int> EntityId { get; set; } public Nullable<int> FromMinutes { get; set; } public Nullable<int> ToMinutes { get; set; } public string ProfileName { get; set; } public Nullable<int> AverageMinutes { get; set; } public virtual Entity Entity { get; set; } } }
{ "content_hash": "d723029b0440cb604ea20348e62284a9", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 66, "avg_line_length": 42.166666666666664, "alnum_prop": 0.61133069828722, "repo_name": "CredentialTransparencyInitiative/CredentialFinderSearch", "id": "2efc07eb346898bceff891b56bf913d389798e8c", "size": "1942", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Data/Entity_DurationProfile.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "104" }, { "name": "C#", "bytes": "3800151" }, { "name": "CSS", "bytes": "151860" }, { "name": "HTML", "bytes": "277" }, { "name": "JavaScript", "bytes": "993409" } ], "symlink_target": "" }
all: src src: ${MAKE} -C src lib: lib/config.mk ${MAKE} -C lib deps: ${MAKE} -Csrc deps clean: ${MAKE} -C src clean ${MAKE} -C lib clean cleanall: clean ./configure clean # see also check-bootstrap check: all lib cd test && ./run_tests -i ignores -j4 cases ALL_SRC = $(shell find src -iname '*.[ch]') tags: ${ALL_SRC} ctags '--exclude=_*' -R src lib include Bootstrap.mk .PHONY: all clean cleanall src
{ "content_hash": "1fc92724d90443e688c9879fb670eaa0", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 44, "avg_line_length": 14, "alnum_prop": 0.6428571428571429, "repo_name": "bobrippling/ucc-c-compiler", "id": "a699e4b79f387e21d2b14b5832904bdc9d8ead26", "size": "420", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Makefile", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "3172" }, { "name": "C", "bytes": "1993174" }, { "name": "Makefile", "bytes": "10681" }, { "name": "Perl", "bytes": "28974" }, { "name": "Raku", "bytes": "732" }, { "name": "Shell", "bytes": "6678" } ], "symlink_target": "" }
/* $Id$ */ /* Copyright (c) 2008-2017 Pierre Pronchery <khorben@defora.org> */ /* This file is part of DeforaOS System libc */ /* All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef LIBC_FLOAT_H # define LIBC_FLOAT_H /* constants */ # ifdef __DBL_DIG__ # define DBL_DIG __DBL_DIG__ # endif # ifdef __DBL_EPSILON__ # define DBL_EPSILON __DBL_EPSILON__ # endif # ifdef __DBL_MANT_DIG__ # define DBL_MANT_DIG __DBL_MANT_DIG__ # endif # ifdef __DBL_MAX__ # define DBL_MAX __DBL_MAX__ # endif # ifdef __DBL_MAX_10_EXP__ # define DBL_MAX_10_EXP __DBL_MAX_10_EXP__ # endif # ifdef __DBL_MAX_EXP__ # define DBL_MAX_EXP __DBL_MAX_EXP__ # endif # ifdef __DBL_MIN__ # define DBL_MIN __DBL_MIN__ # endif # ifdef __DBL_MIN_10_EXP__ # define DBL_MIN_10_EXP __DBL_MIN_10_EXP__ # endif # ifdef __DBL_MIN_EXP__ # define DBL_MIN_EXP __DBL_MIN_EXP__ # endif # ifdef __DECIMAL_DIG__ # define DECIMAL_DIG __DECIMAL_DIG__ # endif # ifdef __FLT_EVAL_METHOD__ # define FLT_EVAL_METHOD __FLT_EVAL_METHOD__ # else # define FLT_EVAL_METHOD -1 # endif # ifdef __FLT_RADIX__ # define FLT_RADIX __FLT_RADIX__ # endif # ifdef __FLT_ROUNDS__ # define FLT_ROUNDS __FLT_ROUNDS__ # else # define FLT_ROUNDS -1 # endif # ifdef __FLT_DIG__ # define FLT_DIG __FLT_DIG__ # endif # ifdef __FLT_EPSILON__ # define FLT_EPSILON __FLT_EPSILON__ # endif # ifdef __FLT_MANT_DIG__ # define FLT_MANT_DIG __FLT_MANT_DIG__ # endif # ifdef __FLT_MAX__ # define FLT_MAX __FLT_MAX__ # endif # ifdef __FLT_MAX_10_EXP__ # define FLT_MAX_10_EXP __FLT_MAX_10_EXP__ # endif # ifdef __FLT_MAX_EXP__ # define FLT_MAX_EXP __FLT_MAX_EXP__ # endif # ifdef __FLT_MIN__ # define FLT_MIN __FLT_MIN__ # endif # ifdef __FLT_MIN_10_EXP__ # define FLT_MIN_10_EXP __FLT_MIN_10_EXP__ # endif # ifdef __FLT_MIN_EXP__ # define FLT_MIN_EXP __FLT_MIN_EXP__ # endif # ifdef __LDBL_DIG__ # define LDBL_DIG __LDBL_DIG__ # endif # ifdef __LDBL_EPSILON__ # define LDBL_EPSILON __LDBL_EPSILON__ # endif # ifdef __LDBL_MANT_DIG__ # define LDBL_MANT_DIG __LDBL_MANT_DIG__ # endif # ifdef __LDBL_MAX__ # define LDBL_MAX __LDBL_MAX__ # endif # ifdef __LDBL_MAX_10_EXP__ # define LDBL_MAX_10_EXP __LDBL_MAX_10_EXP__ # endif # ifdef __LDBL_MAX_EXP__ # define LDBL_MAX_EXP __LDBL_MAX_EXP__ # endif # ifdef __LDBL_MIN__ # define LDBL_MIN __LDBL_MIN__ # endif # ifdef __LDBL_MIN_10_EXP__ # define LDBL_MIN_10_EXP __LDBL_MIN_10_EXP__ # endif # ifdef __LDBL_MIN_EXP__ # define LDBL_MIN_EXP __LDBL_MIN_EXP__ # endif #endif /* !LIBC_FLOAT_H */
{ "content_hash": "ed262264e0f4fba2235898463202e588", "timestamp": "", "source": "github", "line_count": 138, "max_line_length": 75, "avg_line_length": 27.594202898550726, "alnum_prop": 0.6720063025210085, "repo_name": "DeforaOS/libc", "id": "bdc116cf217e941227d30333d9e5c5689c1d4910", "size": "3808", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/float.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Assembly", "bytes": "171932" }, { "name": "C", "bytes": "2717971" }, { "name": "Shell", "bytes": "36541" } ], "symlink_target": "" }
<section class="row" data-ng-controller="AuthenticationController"> <h3 class="col-md-12 text-center">Sign up using your social accounts</h3> <div class="col-md-12 text-center"> <!--a href="/auth/facebook" class="undecorated-link"> <img src="/modules/users/img/buttons/facebook.png"> </a--> <a href="/auth/twitter" class="undecorated-link"> <img src="/modules/users/img/buttons/twitter.png"> </a> <!--a href="/auth/google" class="undecorated-link"> <img src="/modules/users/img/buttons/google.png"> </a> <a href="/auth/linkedin" class="undecorated-link"> <img src="/modules/users/img/buttons/linkedin.png"> </a> <a href="/auth/github" class="undecorated-link"> <img src="/modules/users/img/buttons/github.png"> </a--> </div> <!--h3 class="col-md-12 text-center">Or with your email</h3> <div class="col-xs-offset-2 col-xs-8 col-md-offset-5 col-md-2"> <form name="userForm" data-ng-submit="signup()" class="signin form-horizontal" novalidate autocomplete="off"> <fieldset> <div class="form-group"> <label for="firstName">First Name</label> <input type="text" required id="firstName" name="firstName" class="form-control" data-ng-model="credentials.firstName" placeholder="First Name"> </div> <div class="form-group"> <label for="lastName">Last Name</label> <input type="text" id="lastName" name="lastName" class="form-control" data-ng-model="credentials.lastName" placeholder="Last Name"> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" id="email" name="email" class="form-control" data-ng-model="credentials.email" placeholder="Email"> </div> <div class="form-group"> <label for="username">Username</label> <input type="text" id="username" name="username" class="form-control" data-ng-model="credentials.username" placeholder="Username"> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" id="password" name="password" class="form-control" data-ng-model="credentials.password" placeholder="Password"> </div> <div class="text-center form-group"> <button type="submit" class="btn btn-large btn-primary">Sign up</button>&nbsp; or&nbsp; <a href="/#!/signin" class="show-signup">Sign in</a> </div> <div data-ng-show="error" class="text-center text-danger"> <strong data-ng-bind="error"></strong> </div> </fieldset> </form> </div--> </section>
{ "content_hash": "0981f656128bb64f069b38b62226d4df", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 149, "avg_line_length": 46.074074074074076, "alnum_prop": 0.6663987138263665, "repo_name": "bogoquiz/trendtwitter", "id": "e6d1f46bea457eb9c72d94c2882ab789678a7b44", "size": "2488", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/modules/users/views/authentication/signup.client.view.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1152" }, { "name": "HTML", "bytes": "32115" }, { "name": "JavaScript", "bytes": "138466" }, { "name": "Shell", "bytes": "414" } ], "symlink_target": "" }
import { Component, OnInit, AfterViewInit, OnDestroy, ViewChild, ElementRef } from '@angular/core'; @Component({ selector: 'app-card-canvas', templateUrl: './card-canvas.component.html', styleUrls: ['./card-canvas.component.css'] }) export class CardCanvasComponent implements OnInit, AfterViewInit, OnDestroy { @ViewChild('canvas') canvasRef:ElementRef; cardImgObj; baseImgObj; overImgObj; cardImgHandler; baseImgHandler; overImgHandler; isCardImgLoaded: boolean = false; isBaseImgLoaded: boolean = false; isOverImgLoaded: boolean = false; initialized: boolean = false; canvas: any; ctx: any; width: number = 500; height: number = 732; size: number = 360; x: number = 71; y: number = 161; constructor() { } ngOnInit() { } ngAfterViewInit() { this.canvas = this.canvasRef.nativeElement; this.ctx = this.canvas.getContext('2d'); this.ctx.save(); } ngOnDestroy() { if (this.initialized) { this.cardImgObj.removeEventListener("onload", this.cardImgHandler, false); this.baseImgObj.removeEventListener("onload", this.baseImgHandler, false); this.overImgObj.removeEventListener("onload", this.overImgHandler, false); this.cardImgObj = null; this.baseImgObj = null; this.overImgObj = null; } } loadCardImage(src: string): void { this.cardImgObj.src = src; } loadBaseImage(src: string): void { this.baseImgObj.src = src; } loadOverImage(src: string): void { this.overImgObj.src = src; } updateCanvas(): void { this.ctx.restore() this.ctx.save(); if (this.isBaseImgLoaded) { this.ctx.drawImage(this.baseImgObj, 0, 0, this.width, this.height); if (this.isOverImgLoaded) { this.ctx.drawImage(this.overImgObj, this.x, this.y, this.size, this.size); } else if (this.isCardImgLoaded) { this.ctx.beginPath(); this.ctx.rect(this.x, this.y, this.size, this.size); this.ctx.clip(); this.ctx.drawImage(this.cardImgObj, 0, 0, this.width, this.height); } } else { if (this.isCardImgLoaded) { this.ctx.drawImage(this.cardImgObj, 0, 0, this.width, this.height); if (this.isOverImgLoaded) { this.ctx.drawImage(this.overImgObj, this.x, this.y, this.size, this.size); } } } } initializeCanvas(): void { if (!this.initialized) this.initializeImageObjects(); } initializeImageObjects(): void { this.cardImgObj = new Image(); this.baseImgObj = new Image(); this.overImgObj = new Image(); var _cardImgHandler = function() { this.isCardImgLoaded = true; this.updateCanvas(); }; var _baseImgHandler = function() { this.isBaseImgLoaded = true; this.updateCanvas(); }; var _overImgHandler = function() { this.isOverImgLoaded = true; this.updateCanvas(); }; this.cardImgHandler = _cardImgHandler.bind(this); this.baseImgHandler = _baseImgHandler.bind(this); this.overImgHandler = _overImgHandler.bind(this); this.cardImgObj.onload = this.cardImgHandler; this.baseImgObj.onload = this.baseImgHandler; this.overImgObj.onload = this.overImgHandler; this.initialized = true; } getCanvasDataURL(): string { return this.canvas.toDataURL(); } getCanvasImageBlob() { var base64 = this.canvas.toDataURL('image/png'); var bin = atob(base64.replace(/^.*,/, '')); var buffer = new Uint8Array(bin.length); for (var i = 0; i < bin.length; i++) { buffer[i] = bin.charCodeAt(i); } var blob = new Blob([buffer.buffer], {type: "image/png"}); return blob; } }
{ "content_hash": "367ae51b086bd92c0c21728015e389ae", "timestamp": "", "source": "github", "line_count": 132, "max_line_length": 99, "avg_line_length": 27.65909090909091, "alnum_prop": 0.6485894275540948, "repo_name": "s-onuma/9cards-bluemix", "id": "5bfd8ce510636bedea4041ed97ebe1a3389152de", "size": "3651", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/app/cards/card-canvas/card-canvas.component.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "9561" }, { "name": "HTML", "bytes": "29857" }, { "name": "JavaScript", "bytes": "60917" }, { "name": "TypeScript", "bytes": "76773" } ], "symlink_target": "" }
<vector android:alpha="0.87" android:height="24dp" android:tint="#FFFFFF" android:viewportHeight="24.0" android:viewportWidth="24.0" android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android"> <path android:fillColor="#FF000000" android:pathData="M19,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/> </vector>
{ "content_hash": "a5bb3e3b20c45dfec77869cc6009ac1f", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 113, "avg_line_length": 65.8, "alnum_prop": 0.7386018237082067, "repo_name": "doerfli/hacked", "id": "840cce4952f911993bbab11ec66c7679d037a265", "size": "329", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/drawable/ic_add.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "42640" }, { "name": "Kotlin", "bytes": "103456" }, { "name": "Shell", "bytes": "724" } ], "symlink_target": "" }
<?php namespace Illuminate\Tests\Foundation; use Exception; use Mockery as m; use PHPUnit\Framework\TestCase; use Illuminate\Routing\Redirector; use Illuminate\Container\Container; use Illuminate\Routing\UrlGenerator; use Illuminate\Http\RedirectResponse; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Contracts\Translation\Translator; use Illuminate\Validation\Factory as ValidationFactory; use Illuminate\Contracts\Validation\Factory as ValidationFactoryContract; class FoundationFormRequestTest extends TestCase { protected $mocks = []; public function tearDown() { m::close(); $this->mocks = []; } public function test_validated_method_returns_the_validated_data() { $request = $this->createRequest(['name' => 'specified', 'with' => 'extras']); $request->validateResolved(); $this->assertEquals(['name' => 'specified'], $request->validated()); } /** * @expectedException \Illuminate\Validation\ValidationException */ public function test_validate_throws_when_validation_fails() { $request = $this->createRequest(['no' => 'name']); $this->mocks['redirect']->shouldReceive('withInput->withErrors'); $request->validateResolved(); } /** * @expectedException \Illuminate\Auth\Access\AuthorizationException * @expectedExceptionMessage This action is unauthorized. */ public function test_validate_method_throws_when_authorization_fails() { $this->createRequest([], FoundationTestFormRequestForbiddenStub::class)->validateResolved(); } public function test_prepare_for_validation_runs_before_validation() { $this->createRequest([], FoundationTestFormRequestHooks::class)->validateResolved(); } /** * Catch the given exception thrown from the executor, and return it. * * @param string $class * @param \Closure $excecutor * @return \Exception */ protected function catchException($class, $excecutor) { try { $excecutor(); } catch (Exception $e) { if (is_a($e, $class)) { return $e; } throw $e; } throw new Exception("No exception thrown. Expected exception {$class}"); } /** * Create a new request of the given type. * * @param array $payload * @param string $class * @return \Illuminate\Foundation\Http\FormRequest */ protected function createRequest($payload = [], $class = FoundationTestFormRequestStub::class) { $container = tap(new Container, function ($container) { $container->instance( ValidationFactoryContract::class, $this->createValidationFactory($container) ); }); $request = $class::create('/', 'GET', $payload); return $request->setRedirector($this->createMockRedirector($request)) ->setContainer($container); } /** * Create a new validation factory. * * @param \Illuminate\Container\Container $container * @return \Illuminate\Validation\Factory */ protected function createValidationFactory($container) { $translator = m::mock(Translator::class)->shouldReceive('trans') ->zeroOrMoreTimes()->andReturn('error')->getMock(); return new ValidationFactory($translator, $container); } /** * Create a mock redirector. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Routing\Redirector */ protected function createMockRedirector($request) { $redirector = $this->mocks['redirector'] = m::mock(Redirector::class); $redirector->shouldReceive('getUrlGenerator')->zeroOrMoreTimes() ->andReturn($generator = $this->createMockUrlGenerator()); $redirector->shouldReceive('to')->zeroOrMoreTimes() ->andReturn($this->createMockRedirectResponse()); $generator->shouldReceive('previous')->zeroOrMoreTimes() ->andReturn('previous'); return $redirector; } /** * Create a mock URL generator. * * @return \Illuminate\Routing\UrlGenerator */ protected function createMockUrlGenerator() { return $this->mocks['generator'] = m::mock(UrlGenerator::class); } /** * Create a mock redirect response. * * @return \Illuminate\Http\RedirectResponse */ protected function createMockRedirectResponse() { return $this->mocks['redirect'] = m::mock(RedirectResponse::class); } } class FoundationTestFormRequestStub extends FormRequest { public function rules() { return ['name' => 'required']; } public function authorize() { return true; } } class FoundationTestFormRequestForbiddenStub extends FormRequest { public function authorize() { return false; } } class FoundationTestFormRequestHooks extends FormRequest { public function rules() { return ['name' => 'required']; } public function authorize() { return true; } public function prepareForValidation() { $this->replace(['name' => 'Taylor']); } }
{ "content_hash": "ee41904d5dab79fd6f907821a6dbc61e", "timestamp": "", "source": "github", "line_count": 200, "max_line_length": 100, "avg_line_length": 26.775, "alnum_prop": 0.6222222222222222, "repo_name": "billmn/framework", "id": "7e365465f8fb263ba968e2f3b2ddffab5fb1aaad", "size": "5355", "binary": false, "copies": "2", "ref": "refs/heads/5.6", "path": "tests/Foundation/FoundationFormRequestTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4599" }, { "name": "HTML", "bytes": "23886" }, { "name": "JavaScript", "bytes": "1981" }, { "name": "PHP", "bytes": "5189273" }, { "name": "Vue", "bytes": "552" } ], "symlink_target": "" }
import unittest import snippet class SnippetTest(unittest.TestCase): def testParseWithImage(self): img_snp = snippet.Snippet("2011-10-28T16:51:00.000-07:00") self.assertEquals(datetime.datetime(2011, 10, 28, 16, 51), published) if __name__ == '__main__': unittest.main()
{ "content_hash": "53dc7150fec8d29983769fe19dfaf55b", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 73, "avg_line_length": 26, "alnum_prop": 0.7027972027972028, "repo_name": "starpow971/Stanford-Humanities-Center-Updater", "id": "b5aa8e92b7d4a563ac35ee6397e9fbfc89ad86c0", "size": "512", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "snippet_test.py", "mode": "33261", "license": "bsd-2-clause", "language": [ { "name": "Python", "bytes": "80689" }, { "name": "Shell", "bytes": "74" } ], "symlink_target": "" }
import { Drop } from '../drop/drop' export const toString = Object.prototype.toString const toLowerCase = String.prototype.toLowerCase export const hasOwnProperty = Object.hasOwnProperty export function isString (value: any): value is string { return typeof value === 'string' } // eslint-disable-next-line @typescript-eslint/ban-types export function isFunction (value: any): value is Function { return typeof value === 'function' } export function isPromise<T> (val: any): val is Promise<T> { return val && isFunction(val.then) } export function isIterator (val: any): val is IterableIterator<any> { return val && isFunction(val.next) && isFunction(val.throw) && isFunction(val.return) } export function escapeRegex (str: string) { return str.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&') } export function promisify<T1, T2> (fn: (arg1: T1, cb: (err: Error | null, result: T2) => void) => void): (arg1: T1) => Promise<T2>; export function promisify<T1, T2, T3> (fn: (arg1: T1, arg2: T2, cb: (err: Error | null, result: T3) => void) => void): (arg1: T1, arg2: T2) => Promise<T3>; export function promisify (fn: any) { return function (...args: any[]) { return new Promise((resolve, reject) => { fn(...args, (err: Error, result: any) => { err ? reject(err) : resolve(result) }) }) } } export function stringify (value: any): string { value = toValue(value) if (isString(value)) return value if (isNil(value)) return '' if (isArray(value)) return value.map(x => stringify(x)).join('') return String(value) } export function toValue (value: any): any { return (value instanceof Drop && isFunction(value.valueOf)) ? value.valueOf() : value } export function isNumber (value: any): value is number { return typeof value === 'number' } export function toLiquid (value: any): any { if (value && isFunction(value.toLiquid)) return toLiquid(value.toLiquid()) return value } export function isNil (value: any): boolean { return value == null } export function isArray (value: any): value is any[] { // be compatible with IE 8 return toString.call(value) === '[object Array]' } export function isIterable (value: any): value is Iterable<any> { return isObject(value) && Symbol.iterator in value } /* * Iterates over own enumerable string keyed properties of an object and invokes iteratee for each property. * The iteratee is invoked with three arguments: (value, key, object). * Iteratee functions may exit iteration early by explicitly returning false. * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @return {Object} Returns object. */ export function forOwn <T> ( obj: {[key: string]: T} | undefined, iteratee: ((val: T, key: string, obj: {[key: string]: T}) => boolean | void) ) { obj = obj || {} for (const k in obj) { if (hasOwnProperty.call(obj, k)) { if (iteratee(obj[k], k, obj) === false) break } } return obj } export function last <T>(arr: T[]): T; export function last (arr: string): string; export function last (arr: any[] | string): any | string { return arr[arr.length - 1] } /* * Checks if value is the language type of Object. * (e.g. arrays, functions, objects, regexes, new Number(0), and new String('')) * @param {any} value The value to check. * @return {Boolean} Returns true if value is an object, else false. */ export function isObject (value: any): value is object { const type = typeof value return value !== null && (type === 'object' || type === 'function') } export function range (start: number, stop: number, step = 1) { const arr: number[] = [] for (let i = start; i < stop; i += step) { arr.push(i) } return arr } export function padStart (str: any, length: number, ch = ' ') { return pad(str, length, ch, (str, ch) => ch + str) } export function padEnd (str: any, length: number, ch = ' ') { return pad(str, length, ch, (str, ch) => str + ch) } export function pad (str: any, length: number, ch: string, add: (str: string, ch: string) => string) { str = String(str) let n = length - str.length while (n-- > 0) str = add(str, ch) return str } export function identify<T> (val: T): T { return val } export function snakeCase (str: string) { return str.replace( /(\w?)([A-Z])/g, (_, a, b) => (a ? a + '_' : '') + b.toLowerCase() ) } export function changeCase (str: string): string { const hasLowerCase = [...str].some(ch => ch >= 'a' && ch <= 'z') return hasLowerCase ? str.toUpperCase() : str.toLowerCase() } export function ellipsis (str: string, N: number): string { return str.length > N ? str.slice(0, N - 3) + '...' : str } // compare string in case-insensitive way, undefined values to the tail export function caseInsensitiveCompare (a: any, b: any) { if (a == null && b == null) return 0 if (a == null) return 1 if (b == null) return -1 a = toLowerCase.call(a) b = toLowerCase.call(b) if (a < b) return -1 if (a > b) return 1 return 0 } export function argumentsToValue<F extends (...args: any) => any> (fn: F) { return (...args: Parameters<F>) => fn(...args.map(toValue)) } export function escapeRegExp (text: string) { return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') }
{ "content_hash": "b36588a1b9bbade791a11597c88a2f14", "timestamp": "", "source": "github", "line_count": 174, "max_line_length": 155, "avg_line_length": 30.379310344827587, "alnum_prop": 0.6456678017404465, "repo_name": "harttle/liquidjs", "id": "96f80c35d04d86050614fef65e9b4ef412e5ebb0", "size": "5286", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/util/underscore.ts", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "47" }, { "name": "Handlebars", "bytes": "2003" }, { "name": "JavaScript", "bytes": "19255" }, { "name": "Liquid", "bytes": "5254" }, { "name": "Shell", "bytes": "3587" }, { "name": "TypeScript", "bytes": "446048" } ], "symlink_target": "" }
extern "C" char* secure_getenv(const char* name) { return getenv(name); }
{ "content_hash": "36772501311effa9983b1ba5d382b325", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 37, "avg_line_length": 15, "alnum_prop": 0.6933333333333334, "repo_name": "AndreasAakesson/IncludeOS", "id": "7b015c560dec1ea10c803cd32e4efbcc1ef68fd8", "size": "95", "binary": false, "copies": "6", "ref": "refs/heads/dev", "path": "src/posix/secure_getenv.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "74689" }, { "name": "C", "bytes": "42647" }, { "name": "C++", "bytes": "3355508" }, { "name": "CMake", "bytes": "121023" }, { "name": "Dockerfile", "bytes": "846" }, { "name": "GDB", "bytes": "255" }, { "name": "JavaScript", "bytes": "2898" }, { "name": "Makefile", "bytes": "1719" }, { "name": "Python", "bytes": "96273" }, { "name": "Ruby", "bytes": "586" }, { "name": "Shell", "bytes": "35133" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_55) on Mon May 26 23:23:41 CEST 2014 --> <title>DoubleParameter</title> <meta name="date" content="2014-05-26"> <link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="DoubleParameter"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-all.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev Class</li> <li><a href="../../framework/parameters/Parameter.html" title="class in framework.parameters"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../index.html?framework/parameters/DoubleParameter.html" target="_top">Frames</a></li> <li><a href="DoubleParameter.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">framework.parameters</div> <h2 title="Class DoubleParameter" class="title">Class DoubleParameter</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>java.util.Observable</li> <li> <ul class="inheritance"> <li><a href="../../framework/parameters/Parameter.html" title="class in framework.parameters">framework.parameters.Parameter</a>&lt;java.lang.Double&gt;</li> <li> <ul class="inheritance"> <li>framework.parameters.DoubleParameter</li> </ul> </li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="strong">DoubleParameter</span> extends <a href="../../framework/parameters/Parameter.html" title="class in framework.parameters">Parameter</a>&lt;java.lang.Double&gt;</pre> <div class="block">Class that represents a Parameter of Double type.</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../framework/parameters/DoubleParameter.html#DoubleParameter(java.util.Observer, java.lang.String, java.lang.Double, java.lang.Double, java.lang.Double)">DoubleParameter</a></strong>(java.util.Observer&nbsp;o, java.lang.String&nbsp;n, java.lang.Double&nbsp;v, java.lang.Double&nbsp;min, java.lang.Double&nbsp;max)</code> <div class="block">Create a DoubleParameter object.</div> </td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.Double</code></td> <td class="colLast"><code><strong><a href="../../framework/parameters/DoubleParameter.html#parseValue(java.lang.Double)">parseValue</a></strong>(java.lang.Double&nbsp;v)</code> <div class="block">Parse the value to see if it fits the requirements.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.Double</code></td> <td class="colLast"><code><strong><a href="../../framework/parameters/DoubleParameter.html#parseValue(java.lang.String)">parseValue</a></strong>(java.lang.String&nbsp;s)</code> <div class="block">Parse the value from a String and see if it fits the requirements.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_framework.parameters.Parameter"> <!-- --> </a> <h3>Methods inherited from class&nbsp;framework.parameters.<a href="../../framework/parameters/Parameter.html" title="class in framework.parameters">Parameter</a></h3> <code><a href="../../framework/parameters/Parameter.html#attachEditor()">attachEditor</a>, <a href="../../framework/parameters/Parameter.html#getName()">getName</a>, <a href="../../framework/parameters/Parameter.html#getValue()">getValue</a>, <a href="../../framework/parameters/Parameter.html#setValue(java.lang.String)">setValue</a>, <a href="../../framework/parameters/Parameter.html#setValue(T)">setValue</a>, <a href="../../framework/parameters/Parameter.html#toString()">toString</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.util.Observable"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.util.Observable</h3> <code>addObserver, clearChanged, countObservers, deleteObserver, deleteObservers, hasChanged, notifyObservers, notifyObservers, setChanged</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="DoubleParameter(java.util.Observer, java.lang.String, java.lang.Double, java.lang.Double, java.lang.Double)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>DoubleParameter</h4> <pre>public&nbsp;DoubleParameter(java.util.Observer&nbsp;o, java.lang.String&nbsp;n, java.lang.Double&nbsp;v, java.lang.Double&nbsp;min, java.lang.Double&nbsp;max)</pre> <div class="block">Create a DoubleParameter object.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>o</code> - the observer of the Parameter</dd><dd><code>n</code> - the name of the parameter</dd><dd><code>v</code> - the initial value of the parameter</dd><dd><code>min</code> - the minimal value of the parameter</dd><dd><code>max</code> - the maximal value of the parameter</dd><dt><span class="strong">Precondition:</span></dt> <dd>v <= max && v >= min</dd></dl> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="parseValue(java.lang.Double)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>parseValue</h4> <pre>public&nbsp;java.lang.Double&nbsp;parseValue(java.lang.Double&nbsp;v)</pre> <div class="block"><strong>Description copied from class:&nbsp;<code><a href="../../framework/parameters/Parameter.html#parseValue(T)">Parameter</a></code></strong></div> <div class="block">Parse the value to see if it fits the requirements.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../framework/parameters/Parameter.html#parseValue(T)">parseValue</a></code>&nbsp;in class&nbsp;<code><a href="../../framework/parameters/Parameter.html" title="class in framework.parameters">Parameter</a>&lt;java.lang.Double&gt;</code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>v</code> - the value to be tested</dd> <dt><span class="strong">Returns:</span></dt><dd>the value or null if it doesn't fit</dd><dt><span class="strong">Postcondition</span></dt> <dd>returnValue <= maxValue && returnValue >= minValue</dd></dl> </li> </ul> <a name="parseValue(java.lang.String)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>parseValue</h4> <pre>public&nbsp;java.lang.Double&nbsp;parseValue(java.lang.String&nbsp;s)</pre> <div class="block"><strong>Description copied from class:&nbsp;<code><a href="../../framework/parameters/Parameter.html#parseValue(java.lang.String)">Parameter</a></code></strong></div> <div class="block">Parse the value from a String and see if it fits the requirements.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../framework/parameters/Parameter.html#parseValue(java.lang.String)">parseValue</a></code>&nbsp;in class&nbsp;<code><a href="../../framework/parameters/Parameter.html" title="class in framework.parameters">Parameter</a>&lt;java.lang.Double&gt;</code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>s</code> - the String to parse</dd> <dt><span class="strong">Returns:</span></dt><dd>the value or null if it doesn't fit</dd><dt><span class="strong">Postcondition</span></dt> <dd>returnValue <= maxValue && returnValue >= minValue</dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-all.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev Class</li> <li><a href="../../framework/parameters/Parameter.html" title="class in framework.parameters"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../index.html?framework/parameters/DoubleParameter.html" target="_top">Frames</a></li> <li><a href="DoubleParameter.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "90a13492cc5c70e9098a48a4638f6f24", "timestamp": "", "source": "github", "line_count": 325, "max_line_length": 501, "avg_line_length": 39.79692307692308, "alnum_prop": 0.6615122931807639, "repo_name": "remigourdon/sound-editors", "id": "30eeea315658ece79970bc3ff481b6cf75e8ccbc", "size": "12934", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/framework/parameters/DoubleParameter.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "11139" }, { "name": "Java", "bytes": "58743" } ], "symlink_target": "" }
require 'erb' require 'cgi' require 'fileutils' require 'digest/sha1' require 'time' class SimpleCov::Formatter::HTMLFormatter def format(result) Dir[File.join(File.dirname(__FILE__), 'html_formatter/public/*')].each do |path| FileUtils.cp_r(path, asset_output_path) end File.open(File.join(output_path, "index.html"), "w+") do |file| file.puts template('layout').result(binding) end puts output_message(result) end def output_message(result) "Coverage report generated for #{result.command_name} to #{output_path}. #{result.covered_lines} / #{result.total_lines} LOC (#{result.covered_percent.round(2)}%) covered." end private # Returns the an erb instance for the template of given name def template(name) ERB.new(File.read(File.join(File.dirname(__FILE__), 'html_formatter/views/', "#{name}.erb"))) end def output_path SimpleCov.coverage_path end def asset_output_path return @asset_output_path if defined? @asset_output_path and @asset_output_path @asset_output_path = File.join(output_path, 'assets', SimpleCov::Formatter::HTMLFormatter::VERSION) FileUtils.mkdir_p(@asset_output_path) @asset_output_path end def assets_path(name) File.join('./assets', SimpleCov::Formatter::HTMLFormatter::VERSION, name) end # Returns the html for the given source_file def formatted_source_file(source_file) template('source_file').result(binding) end # Returns a table containing the given source files def formatted_file_list(title, source_files) title_id = title.gsub(/^[^a-zA-Z]+/, '').gsub(/[^a-zA-Z0-9\-\_]/, '') title_id # Ruby will give a warning when we do not use this except via the binding :( FIXME template('file_list').result(binding) end def coverage_css_class(covered_percent) if covered_percent > 90 'green' elsif covered_percent > 80 'yellow' else 'red' end end def strength_css_class(covered_strength) if covered_strength > 1 'green' elsif covered_strength == 1 'yellow' else 'red' end end # Return a (kind of) unique id for the source file given. Uses SHA1 on path for the id def id(source_file) Digest::SHA1.hexdigest(source_file.filename) end def timeago(time) "<abbr class=\"timeago\" title=\"#{time.iso8601}\">#{time.iso8601}</abbr>" end def shortened_filename(source_file) source_file.filename.gsub(SimpleCov.root, '.').gsub(/^\.\//, '') end def link_to_source_file(source_file) %Q(<a href="##{id source_file}" class="src_link" title="#{shortened_filename source_file}">#{shortened_filename source_file}</a>) end end $LOAD_PATH.unshift(File.join(File.dirname(__FILE__))) require 'html_formatter/version'
{ "content_hash": "f0569fe38d5eeac1520ab5f6fef927a4", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 176, "avg_line_length": 28.802083333333332, "alnum_prop": 0.6734177215189874, "repo_name": "ruby/simplecov", "id": "71fb3ef9aea9f24a1f40d32848c93a2e067885e0", "size": "2765", "binary": false, "copies": "1", "ref": "refs/heads/ruby", "path": "lib/simplecov/formatter/html_formatter.rb", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
require 'helper' class Nanoc::Filters::RelativizePathsTest < Nanoc::TestCase def test_filter_html_with_double_quotes # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/bar/baz/', ), :blah, ) @item_rep.paths[:last] = ['/foo/bar/baz/'] end # Set content raw_content = %(<a href="/foo">foo</a>) expected_content = %(<a href="../..">foo</a>) # Test actual_content = filter.setup_and_run(raw_content, type: :html) assert_equal(expected_content, actual_content) end def test_filter_html_with_single_quotes # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/bar/baz/', ), :blah, ) @item_rep.paths[:last] = ['/foo/bar/baz/'] end # Set content raw_content = %(<a href='/foo'>foo</a>) expected_content = %(<a href="../..">foo</a>) # Test actual_content = filter.setup_and_run(raw_content, type: :html) assert_equal(expected_content, actual_content) end def test_filter_html_without_quotes # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/bar/baz/', ), :blah, ) @item_rep.paths[:last] = ['/foo/bar/baz/'] end # Set content raw_content = %(<a href=/foo>foo</a>) expected_content = %(<a href="../..">foo</a>) # Test actual_content = filter.setup_and_run(raw_content, type: :html) assert_equal(expected_content, actual_content) end def test_filter_html_with_boilerplate # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/bar/baz/', ), :blah, ) @item_rep.paths[:last] = ['/foo/bar/baz/'] end # Set content raw_content = <<EOS <!DOCTYPE html> <html> <head> <title>Hello</title> </head> <body> <a href=/foo>foo</a> </body> </html> EOS expected0 = %r{<a href="\.\./\.\.">foo</a>} expected1 = %r{\A\s*<!DOCTYPE html\s*>\s*<html>\s*<head>(.|\s)*<title>Hello</title>\s*</head>\s*<body>\s*<a href="../..">foo</a>\s*</body>\s*</html>\s*\Z}m # Test actual_content = filter.setup_and_run(raw_content, type: :html) assert_match(expected0, actual_content) assert_match(expected1, actual_content) end def test_filter_html_multiple # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/bar/baz/', ), :blah, ) @item_rep.paths[:last] = ['/foo/bar/baz/'] end # Set content raw_content = %(<a href="/foo">foo</a> <a href="/bar">bar</a>) expected_content = %(<a href="../..">foo</a> <a href="../../../bar">bar</a>) # Test actual_content = filter.setup_and_run(raw_content, type: :html) assert_equal(expected_content, actual_content) end def test_filter_html_nested # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/bar/baz/', ), :blah, ) @item_rep.paths[:last] = ['/foo/bar/baz/'] end # Set content raw_content = %(<a href="/"><img src="/bar.png" /></a>) expected_content = %(<a href="../../../"><img src="../../../bar.png"></a>) # Test actual_content = filter.setup_and_run(raw_content, type: :html) assert_equal(expected_content, actual_content) end def test_filter_html_outside_tag # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/bar/baz/', ), :blah, ) @item_rep.paths[:last] = ['/foo/bar/baz/'] end # Set content raw_content = %(stuff href="/foo" more stuff) expected_content = %(stuff href="/foo" more stuff) # Test actual_content = filter.setup_and_run(raw_content, type: :html) assert_equal(expected_content, actual_content) end def test_filter_html_root # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/bar/baz/', ), :blah, ) @item_rep.paths[:last] = ['/woof/meow/'] end # Set content raw_content = %(<a href="/">foo</a>) expected_content = %(<a href="../../">foo</a>) # Test actual_content = filter.setup_and_run(raw_content, type: :html) assert_equal(expected_content, actual_content) end def test_filter_html_network_path # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/bar/baz/', ), :blah, ) @item_rep.paths[:last] = ['/woof/meow/'] end # Set content raw_content = %(<a href="//example.com/">example.com</a>) expected_content = %(<a href="//example.com/">example.com</a>) # Test actual_content = filter.setup_and_run(raw_content, type: :html) assert_equal(expected_content, actual_content) end def test_filter_html_with_anchor # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/bar/baz/', ), :blah, ) @item_rep.paths[:last] = ['/woof/meow/'] end # Set content raw_content = %(<a href="#max-payne">Max Payne</a>) expected_content = %(<a href="#max-payne">Max Payne</a>) # Test actual_content = filter.setup_and_run(raw_content, type: :html) assert_equal(expected_content, actual_content) end def test_filter_html_with_url # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/bar/baz/', ), :blah, ) @item_rep.paths[:last] = ['/woof/meow/'] end # Set content raw_content = %(<a href="http://example.com/">Example</a>) expected_content = %(<a href="http://example.com/">Example</a>) # Test actual_content = filter.setup_and_run(raw_content, type: :html) assert_equal(expected_content, actual_content) end def test_filter_html_with_relative_path # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/bar/baz/', ), :blah, ) @item_rep.paths[:last] = ['/woof/meow/'] end # Set content raw_content = %(<a href="example">Example</a>) expected_content = %(<a href="example">Example</a>) # Test actual_content = filter.setup_and_run(raw_content, type: :html) assert_equal(expected_content, actual_content) end def test_filter_html_object_with_relative_path # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/bar/baz/', ), :blah, ) @item_rep.paths[:last] = ['/woof/meow/'] end raw_content = %(<object data="/example"><param name="movie" content="/example"></object>) actual_content = filter.setup_and_run(raw_content, type: :html) assert_match(/<object data="..\/..\/example">/, actual_content) assert_match(/<param (name="movie" )?content="..\/..\/example"/, actual_content) end def test_filter_form # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/bar/baz/', ), :blah, ) @item_rep.paths[:last] = ['/foo/bar/baz/'] end # Set content raw_content = %(<form action="/example"></form>) expected_content = %(<form action="../../../example"></form>) # Test actual_content = filter.setup_and_run(raw_content, type: :html) assert_equal(expected_content, actual_content) end def test_filter_implicit # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Test assert_raises(RuntimeError) do filter.setup_and_run('moo') end end def test_filter_css_with_double_quotes # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/bar/baz/', ), :blah, ) @item_rep.paths[:last] = ['/foo/bar/baz/'] end # Set content raw_content = %[background: url("/foo/bar/background.png");] expected_content = %[background: url("../background.png");] # Test actual_content = filter.setup_and_run(raw_content, type: :css) assert_equal(expected_content, actual_content) end def test_filter_css_with_single_quotes # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/bar/baz/', ), :blah, ) @item_rep.paths[:last] = ['/foo/bar/baz/'] end # Set content raw_content = %[background: url('/foo/bar/background.png');] expected_content = %[background: url('../background.png');] # Test actual_content = filter.setup_and_run(raw_content, type: :css) assert_equal(expected_content, actual_content) end def test_filter_css_without_quotes # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/bar/baz/', ), :blah, ) @item_rep.paths[:last] = ['/foo/bar/baz/'] end # Set content raw_content = %[background: url(/foo/bar/background.png);] expected_content = %[background: url(../background.png);] # Test actual_content = filter.setup_and_run(raw_content, type: :css) assert_equal(expected_content, actual_content) end def test_filter_css_multiple # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/bar/baz/', ), :blah, ) @item_rep.paths[:last] = ['/foo/bar/baz/'] end # Set content raw_content = %[background: url(/foo/bar/a.png) url(/foo/bar/b.png);] expected_content = %[background: url(../a.png) url(../b.png);] # Test actual_content = filter.setup_and_run(raw_content, type: :css) assert_equal(expected_content, actual_content) end def test_filter_css_root # It is probably a bit weird to have “url(/)” in CSS, but I’ve made a # test case for this situation anyway. Can’t hurt… # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/bar/baz/', ), :blah, ) @item_rep.paths[:last] = ['/woof/meow/'] end # Set content raw_content = %[background: url(/);] expected_content = %[background: url(../../);] # Test actual_content = filter.setup_and_run(raw_content, type: :css) assert_equal(expected_content, actual_content) end def test_filter_css_network_path # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/bar/baz/', ), :blah, ) @item_rep.paths[:last] = ['/woof/meow/'] end # Set content raw_content = %[background: url(//example.com);] expected_content = %[background: url(//example.com);] # Test actual_content = filter.setup_and_run(raw_content, type: :css) assert_equal(expected_content, actual_content) end def test_filter_xml if_have 'nokogiri' do # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/bar/baz/', ), :blah, ) @item_rep.paths[:last] = ['/foo/bar/baz/'] end # Set content expected = /<bar boo="\.\.\/\.\.">baz<\/bar>/ raw_content = <<-XML <?xml version="1.0" encoding="utf-8"?> <foo> <bar boo="/foo">baz</bar> </foo> XML actual_content = filter.setup_and_run(raw_content, type: :xml, select: ['*/@boo']) assert_match(expected, actual_content) end end def test_filter_fragment_xml if_have 'nokogiri' do # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/bar/baz/', ), :blah, ) @item_rep.paths[:last] = ['/foo/bar/baz/'] end # Set content raw_content = <<-XML <foo> <bar><far href="/foo">baz</far></bar> </foo> XML actual_content = filter.setup_and_run(raw_content, type: :xml, select: ['far/@href']) assert_match(/<foo>/, actual_content) assert_match(/<bar><far href="..\/..">baz<\/far><\/bar>/, actual_content) end end def test_filter_xml_with_namespaces if_have 'nokogiri' do # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/bar/baz/', ), :blah, ) @item_rep.paths[:last] = ['/foo/bar/baz/'] end # Set content raw_content = <<-XML <foo xmlns="http://example.org"> <bar><a href="/foo">baz</a></bar> </foo> XML options = { type: :xml, namespaces: { ex: 'http://example.org' }, select: ['ex:a/@href'], } actual_content = filter.setup_and_run(raw_content, options) assert_match(/<foo xmlns="http:\/\/example.org">/, actual_content) assert_match(/<bar><a href="..\/..">baz<\/a><\/bar>/, actual_content) end end def test_filter_xhtml if_have 'nokogiri' do # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/bar/baz/', ), :blah, ) @item_rep.paths[:last] = ['/foo/bar/baz/'] end # Set content raw_content = <<-XML <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <link rel="stylesheet" href="/css"/> <script src="/js"></script> </head> <body> <a href="/foo">bar</a> <img src="/img"/> </body> </html> XML actual_content = filter.setup_and_run(raw_content, type: :xhtml) assert_match(/<link[^>]*href="..\/..\/..\/css"[^>]*\/>/, actual_content) assert_match(/<script src="..\/..\/..\/js">/, actual_content) assert_match(/<img src="..\/..\/..\/img"[^>]*\/>/, actual_content) assert_match(/<a href="..\/..">bar<\/a>/, actual_content) end end def test_filter_fragment_xhtml if_have 'nokogiri' do # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/bar/baz/', ), :blah, ) @item_rep.paths[:last] = ['/foo/bar/baz/'] end # Set content raw_content = <<-XML <a href="/foo">bar</a> <p> <img src="/img"/> </p> XML expected_content = %r{\A\s*<a href="../..">bar</a>\s*<p>\s*<img src="../../../img" />\s*</p>\s*\Z}m # Test actual_content = filter.setup_and_run(raw_content.freeze, type: :xhtml) assert_match(expected_content, actual_content) end end def test_filter_fragment_xhtml_with_comments if_have 'nokogiri' do # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/baz/', ), :blah, ) @item_rep.paths[:last] = ['/foo/baz/'] end # Set content raw_content = %( <link rel="stylesheet" href="/foo.css" /> <!--[if lt IE 9]> <script src="/js/lib/html5shiv.js"></script> <![endif]--> ) actual_content = filter.setup_and_run(raw_content.freeze, type: :xhtml) assert_match(/<link (rel="stylesheet" )?href="..\/..\/foo.css" /, actual_content) assert_match(/<script src="..\/..\/js\/lib\/html5shiv.js"><\/script>/, actual_content) end end def test_filter_fragment_html_with_comments if_have 'nokogiri' do # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/baz/', ), :blah, ) @item_rep.paths[:last] = ['/foo/baz/'] end # Set content raw_content = %( <!--[if lt IE 9]> <script src="/js/lib/html5shiv.js"></script> <![endif]--> ) # Test actual_content = filter.setup_and_run(raw_content.freeze, type: :html) assert actual_content.include? %(<script src="../../js/lib/html5shiv.js">) end end def test_filter_html_doctype # Create filter with mock item filter = Nanoc::Filters::RelativizePaths.new # Mock item filter.instance_eval do @item_rep = Nanoc::Int::ItemRep.new( Nanoc::Int::Item.new( 'content', {}, '/foo/bar/baz/', ), :blah, ) @item_rep.paths[:last] = ['/foo/bar/baz/'] end # Set content raw_content = %(&lt;!DOCTYPE html>) expected_content = %(&lt;!DOCTYPE html&gt;) # Test actual_content = filter.setup_and_run(raw_content, type: :html) assert_equal(expected_content, actual_content) end end
{ "content_hash": "64887feea48bb3f83414cdd81c74b553", "timestamp": "", "source": "github", "line_count": 817, "max_line_length": 159, "avg_line_length": 25.58996328029376, "alnum_prop": 0.5490027263595925, "repo_name": "RubenVerborgh/nanoc", "id": "56538af0e9c786dd18757bfcf49344220723851e", "size": "20917", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/filters/test_relativize_paths.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "1202854" } ], "symlink_target": "" }
<?php namespace Iivannov\Branchio; class Link { /** * @var string */ public $channel; /** * @var string */ public $feature; /** * @var string */ public $campaign; /** * @var string */ public $stage; /** * @var array */ public $tags; /** * @var string */ public $alias; /** * @var int */ public $type = 0; /** * @var array */ public $data; private $properties = [ 'channel', 'feature', 'campaign', 'stage', 'tags', 'alias', 'type', 'data' ]; public function __construct($json = null) { if ($json) { if (!$json instanceof \stdClass) { throw new \InvalidArgumentException(); } $this->makeFromLinkObject($json); } } /** * @param string $channel * @return Link */ public function setChannel(string $channel): Link { $this->channel = $channel; return $this; } /** * @param string $feature * @return Link */ public function setFeature(string $feature): Link { $this->feature = $feature; return $this; } /** * @param string $campaign * @return Link */ public function setCampaign(string $campaign): Link { $this->campaign = $campaign; return $this; } /** * @param string $stage * @return Link */ public function setStage(string $stage): Link { $this->stage = $stage; return $this; } public function setTags(array $tags): Link { $this->tags = $tags; return $this; } /** * @param string $alias * @return Link */ public function setAlias(string $alias): Link { $this->alias = $alias; return $this; } /** * @param int $type * @return Link */ public function setType(int $type): Link { $this->type = $type; return $this; } /** * @param array $data * @return Link */ public function setData(array $data): Link { $this->data = (object)$data; return $this; } public function toArray($ignore = []) { $array = []; foreach ($this->properties as $property) { if(in_array($property, $ignore)) { continue; } $array[$property] = $this->{$property}; } return $array; } private function makeFromLinkObject(\stdClass $json) { foreach ($this->properties as $property) { if (isset($json->{$property})) { $this->{$property} = $json->{$property}; } } } }
{ "content_hash": "fbab0364b7fee88972766d6b52a3b717", "timestamp": "", "source": "github", "line_count": 172, "max_line_length": 56, "avg_line_length": 16.686046511627907, "alnum_prop": 0.4578397212543554, "repo_name": "iivannov/branchio", "id": "004baa1688e9e9f8f85fc7327095e0f7b959a3ff", "size": "2870", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Link.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "11439" } ], "symlink_target": "" }
<?php /* Unsafe sample input : use shell_exec to cat /tmp/tainted.txt SANITIZE : use of pg_escape_string construction : interpretation with simple quote */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ $tainted = shell_exec('cat /tmp/tainted.txt'); $tainted = pg_escape_string($tainted); $query = "name=' $tainted '"; //flaw $ds=ldap_connect("localhost"); $r=ldap_bind($ds); $sr=ldap_search($ds,"o=My Company, c=US", $query); ldap_close($ds); ?>
{ "content_hash": "0f46da257afef93571afa17e158ba12c", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 75, "avg_line_length": 23.12280701754386, "alnum_prop": 0.7594840667678301, "repo_name": "stivalet/PHP-Vulnerability-test-suite", "id": "862218dbdade6b3bc41f368acacc02a6a8b3987c", "size": "1318", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Injection/CWE_90/unsafe/CWE_90__shell_exec__func_pg_escape_string__name-interpretation_simple_quote.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "64184004" } ], "symlink_target": "" }
import * as React from 'react' import { useSelector, useDispatch } from 'react-redux' import capitalize from 'lodash/capitalize' import { selectors as robotSelectors, actions as robotActions, } from '../../robot' import { Card, LabeledValue, OutlineButton, Icon } from '@opentrons/components' import { CONNECTABLE } from '../../discovery' import { CardContentHalf } from '../layout' import type { Dispatch } from '../../types' import type { ViewableRobot } from '../../discovery/types' type Props = {| robot: ViewableRobot |} // TODO(mc, 2020-03-30): i18n const TITLE = 'Status' const STATUS_LABEL = 'This robot is currently' const STATUS_VALUE_DISCONNECTED = 'Unknown - connect to view status' const STATUS_VALUE_NOT_CONNECTABLE = 'Not connectable' const STATUS_VALUE_DEFAULT = 'Idle' const CONNECT = 'connect' const DISCONNECT = 'disconnect' export function StatusCard(props: Props): React.Node { const { robot } = props const dispatch = useDispatch<Dispatch>() const connectable = robot.status === CONNECTABLE const connected = robot.connected != null && robot.connected === true const sessionStatus = useSelector(robotSelectors.getSessionStatus) const connectRequest = useSelector(robotSelectors.getConnectRequest) const connectButtonDisabled = !connectable || connectRequest.inProgress let status = STATUS_VALUE_DEFAULT if (!connectable) { status = STATUS_VALUE_NOT_CONNECTABLE } else if (!connected) { status = STATUS_VALUE_DISCONNECTED } else if (sessionStatus) { status = capitalize(sessionStatus) } const handleClick = () => { if (connected) { dispatch(robotActions.disconnect()) } else { dispatch(robotActions.connect(robot.name)) } } return ( <Card title={TITLE}> <CardContentHalf> <LabeledValue label={STATUS_LABEL} value={status} /> </CardContentHalf> <CardContentHalf> <OutlineButton onClick={handleClick} disabled={connectButtonDisabled}> {connected ? ( DISCONNECT ) : connectRequest.name === robot.name ? ( <Icon name="ot-spinner" height="1em" spin /> ) : ( CONNECT )} </OutlineButton> </CardContentHalf> </Card> ) }
{ "content_hash": "ec57ea711bccda153ec41762150bdc4c", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 79, "avg_line_length": 31.194444444444443, "alnum_prop": 0.6749777382012466, "repo_name": "OpenTrons/opentrons-api", "id": "1132ecc34f78ed73eeaed592619360169163db54", "size": "2294", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "app/src/components/RobotSettings/StatusCard.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "11593" }, { "name": "CSS", "bytes": "30408" }, { "name": "HTML", "bytes": "15337" }, { "name": "JavaScript", "bytes": "89667" }, { "name": "Makefile", "bytes": "9280" }, { "name": "Python", "bytes": "642726" }, { "name": "Ruby", "bytes": "17204" }, { "name": "Shell", "bytes": "6478" }, { "name": "Vue", "bytes": "28755" } ], "symlink_target": "" }
import java.io._ import java.nio.file.Files import scala.io.Source import scala.util.Properties import scala.collection.JavaConverters._ import scala.collection.mutable.Stack import sbt._ import sbt.Classpaths.publishTask import sbt.Keys._ import sbtunidoc.Plugin.UnidocKeys.unidocGenjavadocVersion import com.simplytyped.Antlr4Plugin._ import com.typesafe.sbt.pom.{PomBuild, SbtPomKeys} import com.typesafe.tools.mima.plugin.MimaKeys import org.scalastyle.sbt.ScalastylePlugin._ import org.scalastyle.sbt.Tasks import spray.revolver.RevolverPlugin._ object BuildCommons { private val buildLocation = file(".").getAbsoluteFile.getParentFile val sqlProjects@Seq(catalyst, sql, hive, hiveThriftServer, sqlKafka010) = Seq( "catalyst", "sql", "hive", "hive-thriftserver", "sql-kafka-0-10" ).map(ProjectRef(buildLocation, _)) val streamingProjects@Seq( streaming, streamingFlumeSink, streamingFlume, streamingKafka, streamingKafka010 ) = Seq( "streaming", "streaming-flume-sink", "streaming-flume", "streaming-kafka-0-8", "streaming-kafka-0-10" ).map(ProjectRef(buildLocation, _)) val allProjects@Seq( core, graphx, mllib, mllibLocal, repl, networkCommon, networkShuffle, launcher, unsafe, tags, sketch, _* ) = Seq( "core", "graphx", "mllib", "mllib-local", "repl", "network-common", "network-shuffle", "launcher", "unsafe", "tags", "sketch" ).map(ProjectRef(buildLocation, _)) ++ sqlProjects ++ streamingProjects val optionallyEnabledProjects@Seq(mesos, yarn, java8Tests, sparkGangliaLgpl, streamingKinesisAsl, dockerIntegrationTests, kubernetes, _*) = Seq("mesos", "yarn", "java8-tests", "ganglia-lgpl", "streaming-kinesis-asl", "docker-integration-tests", "kubernetes", "kubernetes-integration-tests", "kubernetes-integration-tests-spark-jobs", "kubernetes-integration-tests-spark-jobs-helpers", "kubernetes-docker-minimal-bundle" ).map(ProjectRef(buildLocation, _)) val assemblyProjects@Seq(networkYarn, streamingFlumeAssembly, streamingKafkaAssembly, streamingKafka010Assembly, streamingKinesisAslAssembly) = Seq("network-yarn", "streaming-flume-assembly", "streaming-kafka-0-8-assembly", "streaming-kafka-0-10-assembly", "streaming-kinesis-asl-assembly") .map(ProjectRef(buildLocation, _)) val copyJarsProjects@Seq(assembly, examples) = Seq("assembly", "examples") .map(ProjectRef(buildLocation, _)) val tools = ProjectRef(buildLocation, "tools") // Root project. val spark = ProjectRef(buildLocation, "spark") val sparkHome = buildLocation val testTempDir = s"$sparkHome/target/tmp" val javacJVMVersion = settingKey[String]("source and target JVM version for javac") val scalacJVMVersion = settingKey[String]("source and target JVM version for scalac") } object SparkBuild extends PomBuild { import BuildCommons._ import scala.collection.mutable.Map val projectsMap: Map[String, Seq[Setting[_]]] = Map.empty // Provides compatibility for older versions of the Spark build def backwardCompatibility = { import scala.collection.mutable var profiles: mutable.Seq[String] = mutable.Seq("sbt") // scalastyle:off println if (Properties.envOrNone("SPARK_GANGLIA_LGPL").isDefined) { println("NOTE: SPARK_GANGLIA_LGPL is deprecated, please use -Pspark-ganglia-lgpl flag.") profiles ++= Seq("spark-ganglia-lgpl") } if (Properties.envOrNone("SPARK_HIVE").isDefined) { println("NOTE: SPARK_HIVE is deprecated, please use -Phive and -Phive-thriftserver flags.") profiles ++= Seq("hive", "hive-thriftserver") } Properties.envOrNone("SPARK_HADOOP_VERSION") match { case Some(v) => println("NOTE: SPARK_HADOOP_VERSION is deprecated, please use -Dhadoop.version=" + v) System.setProperty("hadoop.version", v) case None => } if (Properties.envOrNone("SPARK_YARN").isDefined) { println("NOTE: SPARK_YARN is deprecated, please use -Pyarn flag.") profiles ++= Seq("yarn") } // scalastyle:on println profiles } override val profiles = { val profiles = Properties.envOrNone("SBT_MAVEN_PROFILES") match { case None => backwardCompatibility case Some(v) => if (backwardCompatibility.nonEmpty) // scalastyle:off println println("Note: We ignore environment variables, when use of profile is detected in " + "conjunction with environment variable.") // scalastyle:on println v.split("(\\s+|,)").filterNot(_.isEmpty).map(_.trim.replaceAll("-P", "")).toSeq } if (System.getProperty("scala-2.10") == "") { // To activate scala-2.10 profile, replace empty property value to non-empty value // in the same way as Maven which handles -Dname as -Dname=true before executes build process. // see: https://github.com/apache/maven/blob/maven-3.0.4/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java#L1082 System.setProperty("scala-2.10", "true") } profiles } Properties.envOrNone("SBT_MAVEN_PROPERTIES") match { case Some(v) => v.split("(\\s+|,)").filterNot(_.isEmpty).map(_.split("=")).foreach(x => System.setProperty(x(0), x(1))) case _ => } override val userPropertiesMap = System.getProperties.asScala.toMap lazy val MavenCompile = config("m2r") extend(Compile) lazy val publishLocalBoth = TaskKey[Unit]("publish-local", "publish local for m2 and ivy") lazy val sparkGenjavadocSettings: Seq[sbt.Def.Setting[_]] = Seq( libraryDependencies += compilerPlugin( "com.typesafe.genjavadoc" %% "genjavadoc-plugin" % unidocGenjavadocVersion.value cross CrossVersion.full), scalacOptions ++= Seq( "-P:genjavadoc:out=" + (target.value / "java"), "-P:genjavadoc:strictVisibility=true" // hide package private types ) ) lazy val scalaStyleRules = Project("scalaStyleRules", file("scalastyle")) .settings( libraryDependencies += "org.scalastyle" %% "scalastyle" % "0.8.0" ) lazy val scalaStyleOnCompile = taskKey[Unit]("scalaStyleOnCompile") lazy val scalaStyleOnTest = taskKey[Unit]("scalaStyleOnTest") // We special case the 'println' lint rule to only be a warning on compile, because adding // printlns for debugging is a common use case and is easy to remember to remove. val scalaStyleOnCompileConfig: String = { val in = "scalastyle-config.xml" val out = "scalastyle-on-compile.generated.xml" val replacements = Map( """customId="println" level="error"""" -> """customId="println" level="warn"""" ) var contents = Source.fromFile(in).getLines.mkString("\n") for ((k, v) <- replacements) { require(contents.contains(k), s"Could not rewrite '$k' in original scalastyle config.") contents = contents.replace(k, v) } new PrintWriter(out) { write(contents) close() } out } // Return a cached scalastyle task for a given configuration (usually Compile or Test) private def cachedScalaStyle(config: Configuration) = Def.task { val logger = streams.value.log // We need a different cache dir per Configuration, otherwise they collide val cacheDir = target.value / s"scalastyle-cache-${config.name}" val cachedFun = FileFunction.cached(cacheDir, FilesInfo.lastModified, FilesInfo.exists) { (inFiles: Set[File]) => { val args: Seq[String] = Seq.empty val scalaSourceV = Seq(file(scalaSource.in(config).value.getAbsolutePath)) val configV = (baseDirectory in ThisBuild).value / scalaStyleOnCompileConfig val configUrlV = scalastyleConfigUrl.in(config).value val streamsV = streams.in(config).value val failOnErrorV = true val scalastyleTargetV = scalastyleTarget.in(config).value val configRefreshHoursV = scalastyleConfigRefreshHours.in(config).value val targetV = target.in(config).value val configCacheFileV = scalastyleConfigUrlCacheFile.in(config).value logger.info(s"Running scalastyle on ${name.value} in ${config.name}") Tasks.doScalastyle(args, configV, configUrlV, failOnErrorV, scalaSourceV, scalastyleTargetV, streamsV, configRefreshHoursV, targetV, configCacheFileV) Set.empty } } cachedFun(findFiles(scalaSource.in(config).value)) } private def findFiles(file: File): Set[File] = if (file.isDirectory) { file.listFiles().toSet.flatMap(findFiles) + file } else { Set(file) } def enableScalaStyle: Seq[sbt.Def.Setting[_]] = Seq( scalaStyleOnCompile := cachedScalaStyle(Compile).value, scalaStyleOnTest := cachedScalaStyle(Test).value, logLevel in scalaStyleOnCompile := Level.Warn, logLevel in scalaStyleOnTest := Level.Warn, (compile in Compile) := { scalaStyleOnCompile.value (compile in Compile).value }, (compile in Test) := { scalaStyleOnTest.value (compile in Test).value } ) lazy val sharedSettings = sparkGenjavadocSettings ++ (if (sys.env.contains("NOLINT_ON_COMPILE")) Nil else enableScalaStyle) ++ Seq( exportJars in Compile := true, exportJars in Test := false, javaHome := sys.env.get("JAVA_HOME") .orElse(sys.props.get("java.home").map { p => new File(p).getParentFile().getAbsolutePath() }) .map(file), incOptions := incOptions.value.withNameHashing(true), publishMavenStyle := true, unidocGenjavadocVersion := "0.10", // Override SBT's default resolvers: resolvers := Seq( DefaultMavenRepository, Resolver.mavenLocal, Resolver.file("local", file(Path.userHome.absolutePath + "/.ivy2/local"))(Resolver.ivyStylePatterns) ), externalResolvers := resolvers.value, otherResolvers <<= SbtPomKeys.mvnLocalRepository(dotM2 => Seq(Resolver.file("dotM2", dotM2))), publishLocalConfiguration in MavenCompile <<= (packagedArtifacts, deliverLocal, ivyLoggingLevel) map { (arts, _, level) => new PublishConfiguration(None, "dotM2", arts, Seq(), level) }, publishMavenStyle in MavenCompile := true, publishLocal in MavenCompile <<= publishTask(publishLocalConfiguration in MavenCompile, deliverLocal), publishLocalBoth <<= Seq(publishLocal in MavenCompile, publishLocal).dependOn, javacOptions in (Compile, doc) ++= { val versionParts = System.getProperty("java.version").split("[+.\\-]+", 3) var major = versionParts(0).toInt if (major == 1) major = versionParts(1).toInt if (major >= 8) Seq("-Xdoclint:all", "-Xdoclint:-missing") else Seq.empty }, javacJVMVersion := "1.7", scalacJVMVersion := "1.7", javacOptions in Compile ++= Seq( "-encoding", "UTF-8", "-source", javacJVMVersion.value ), // This -target option cannot be set in the Compile configuration scope since `javadoc` doesn't // play nicely with it; see https://github.com/sbt/sbt/issues/355#issuecomment-3817629 for // additional discussion and explanation. javacOptions in (Compile, compile) ++= Seq( "-target", javacJVMVersion.value ) ++ sys.env.get("JAVA_7_HOME").toSeq.flatMap { jdk7 => if (javacJVMVersion.value == "1.7") { Seq("-bootclasspath", s"$jdk7/jre/lib/rt.jar${File.pathSeparator}$jdk7/jre/lib/jce.jar") } else { Nil } }, scalacOptions in Compile ++= Seq( s"-target:jvm-${scalacJVMVersion.value}", "-sourcepath", (baseDirectory in ThisBuild).value.getAbsolutePath // Required for relative source links in scaladoc ) ++ sys.env.get("JAVA_7_HOME").toSeq.flatMap { jdk7 => if (javacJVMVersion.value == "1.7") { Seq("-javabootclasspath", s"$jdk7/jre/lib/rt.jar${File.pathSeparator}$jdk7/jre/lib/jce.jar") } else { Nil } }, // Implements -Xfatal-warnings, ignoring deprecation warnings. // Code snippet taken from https://issues.scala-lang.org/browse/SI-8410. compile in Compile := { val analysis = (compile in Compile).value val out = streams.value def logProblem(l: (=> String) => Unit, f: File, p: xsbti.Problem) = { l(f.toString + ":" + p.position.line.fold("")(_ + ":") + " " + p.message) l(p.position.lineContent) l("") } var failed = 0 analysis.infos.allInfos.foreach { case (k, i) => i.reportedProblems foreach { p => val deprecation = p.message.contains("is deprecated") if (!deprecation) { failed = failed + 1 } val printer: (=> String) => Unit = s => if (deprecation) { out.log.warn(s) } else { out.log.error("[warn] " + s) } logProblem(printer, k, p) } } if (failed > 0) { sys.error(s"$failed fatal warnings") } analysis } ) def enable(settings: Seq[Setting[_]])(projectRef: ProjectRef) = { val existingSettings = projectsMap.getOrElse(projectRef.project, Seq[Setting[_]]()) projectsMap += (projectRef.project -> (existingSettings ++ settings)) } // Note ordering of these settings matter. /* Enable shared settings on all projects */ (allProjects ++ optionallyEnabledProjects ++ assemblyProjects ++ copyJarsProjects ++ Seq(spark, tools)) .foreach(enable(sharedSettings ++ DependencyOverrides.settings ++ ExcludedDependencies.settings)) /* Enable tests settings for all projects except examples, assembly and tools */ (allProjects ++ optionallyEnabledProjects).foreach(enable(TestSettings.settings)) val mimaProjects = allProjects.filterNot { x => Seq( spark, hive, hiveThriftServer, catalyst, repl, networkCommon, networkShuffle, networkYarn, unsafe, tags, sqlKafka010 ).contains(x) } mimaProjects.foreach { x => enable(MimaBuild.mimaSettings(sparkHome, x))(x) } /* Generate and pick the spark build info from extra-resources */ enable(Core.settings)(core) /* Unsafe settings */ enable(Unsafe.settings)(unsafe) /* * Set up tasks to copy dependencies during packaging. This step can be disabled in the command * line, so that dev/mima can run without trying to copy these files again and potentially * causing issues. */ if (!"false".equals(System.getProperty("copyDependencies"))) { copyJarsProjects.foreach(enable(CopyDependencies.settings)) } /* Enable Assembly for all assembly projects */ assemblyProjects.foreach(enable(Assembly.settings)) /* Package pyspark artifacts in a separate zip file for YARN. */ enable(PySparkAssembly.settings)(assembly) /* Enable unidoc only for the root spark project */ enable(Unidoc.settings)(spark) /* Catalyst ANTLR generation settings */ enable(Catalyst.settings)(catalyst) /* Spark SQL Core console settings */ enable(SQL.settings)(sql) /* Hive console settings */ enable(Hive.settings)(hive) enable(Flume.settings)(streamingFlumeSink) enable(Java8TestSettings.settings)(java8Tests) // SPARK-14738 - Remove docker tests from main Spark build // enable(DockerIntegrationTests.settings)(dockerIntegrationTests) /** * Adds the ability to run the spark shell directly from SBT without building an assembly * jar. * * Usage: `build/sbt sparkShell` */ val sparkShell = taskKey[Unit]("start a spark-shell.") val sparkPackage = inputKey[Unit]( s""" |Download and run a spark package. |Usage `builds/sbt "sparkPackage <group:artifact:version> <MainClass> [args] """.stripMargin) val sparkSql = taskKey[Unit]("starts the spark sql CLI.") enable(Seq( connectInput in run := true, fork := true, outputStrategy in run := Some (StdoutOutput), javaOptions ++= Seq("-Xmx2G", "-XX:MaxPermSize=256m"), sparkShell := { (runMain in Compile).toTask(" org.apache.spark.repl.Main -usejavacp").value }, sparkPackage := { import complete.DefaultParsers._ val packages :: className :: otherArgs = spaceDelimited("<group:artifact:version> <MainClass> [args]").parsed.toList val scalaRun = (runner in run).value val classpath = (fullClasspath in Runtime).value val args = Seq("--packages", packages, "--class", className, (Keys.`package` in Compile in "core").value.getCanonicalPath) ++ otherArgs println(args) scalaRun.run("org.apache.spark.deploy.SparkSubmit", classpath.map(_.data), args, streams.value.log) }, javaOptions in Compile += "-Dspark.master=local", sparkSql := { (runMain in Compile).toTask(" org.apache.spark.sql.hive.thriftserver.SparkSQLCLIDriver").value } ))(assembly) enable(Seq(sparkShell := sparkShell in "assembly"))(spark) // TODO: move this to its upstream project. override def projectDefinitions(baseDirectory: File): Seq[Project] = { super.projectDefinitions(baseDirectory).map { x => if (projectsMap.exists(_._1 == x.id)) x.settings(projectsMap(x.id): _*) else x.settings(Seq[Setting[_]](): _*) } ++ Seq[Project](OldDeps.project) } } object Core { lazy val settings = Seq( resourceGenerators in Compile += Def.task { val buildScript = baseDirectory.value + "/../build/spark-build-info" val targetDir = baseDirectory.value + "/target/extra-resources/" val command = Seq("bash", buildScript, targetDir, version.value) Process(command).!! val propsFile = baseDirectory.value / "target" / "extra-resources" / "spark-version-info.properties" Seq(propsFile) }.taskValue ) } object Unsafe { lazy val settings = Seq( // This option is needed to suppress warnings from sun.misc.Unsafe usage javacOptions in Compile += "-XDignore.symbol.file" ) } object Flume { lazy val settings = sbtavro.SbtAvro.avroSettings } object DockerIntegrationTests { // This serves to override the override specified in DependencyOverrides: lazy val settings = Seq( dependencyOverrides += "com.google.guava" % "guava" % "18.0", resolvers += "DB2" at "https://app.camunda.com/nexus/content/repositories/public/", libraryDependencies += "com.oracle" % "ojdbc6" % "11.2.0.1.0" from "https://app.camunda.com/nexus/content/repositories/public/com/oracle/ojdbc6/11.2.0.1.0/ojdbc6-11.2.0.1.0.jar" // scalastyle:ignore ) } /** * Overrides to work around sbt's dependency resolution being different from Maven's. */ object DependencyOverrides { lazy val settings = Seq( dependencyOverrides += "com.google.guava" % "guava" % "14.0.1") } /** * This excludes library dependencies in sbt, which are specified in maven but are * not needed by sbt build. */ object ExcludedDependencies { lazy val settings = Seq( libraryDependencies ~= { libs => libs.filterNot(_.name == "groovy-all") } ) } /** * Project to pull previous artifacts of Spark for generating Mima excludes. */ object OldDeps { lazy val project = Project("oldDeps", file("dev"), settings = oldDepsSettings) lazy val allPreviousArtifactKeys = Def.settingDyn[Seq[Option[ModuleID]]] { SparkBuild.mimaProjects .map { project => MimaKeys.previousArtifact in project } .map(k => Def.setting(k.value)) .join } def oldDepsSettings() = Defaults.coreDefaultSettings ++ Seq( name := "old-deps", scalaVersion := "2.10.5", libraryDependencies := allPreviousArtifactKeys.value.flatten ) } object Catalyst { lazy val settings = antlr4Settings ++ Seq( antlr4PackageName in Antlr4 := Some("org.apache.spark.sql.catalyst.parser"), antlr4GenListener in Antlr4 := true, antlr4GenVisitor in Antlr4 := true ) } object SQL { lazy val settings = Seq( initialCommands in console := """ |import org.apache.spark.SparkContext |import org.apache.spark.sql.SQLContext |import org.apache.spark.sql.catalyst.analysis._ |import org.apache.spark.sql.catalyst.dsl._ |import org.apache.spark.sql.catalyst.errors._ |import org.apache.spark.sql.catalyst.expressions._ |import org.apache.spark.sql.catalyst.plans.logical._ |import org.apache.spark.sql.catalyst.rules._ |import org.apache.spark.sql.catalyst.util._ |import org.apache.spark.sql.execution |import org.apache.spark.sql.functions._ |import org.apache.spark.sql.types._ | |val sc = new SparkContext("local[*]", "dev-shell") |val sqlContext = new SQLContext(sc) |import sqlContext.implicits._ |import sqlContext._ """.stripMargin, cleanupCommands in console := "sc.stop()" ) } object Hive { lazy val settings = Seq( javaOptions += "-XX:MaxPermSize=256m", // Specially disable assertions since some Hive tests fail them javaOptions in Test := (javaOptions in Test).value.filterNot(_ == "-ea"), // Supporting all SerDes requires us to depend on deprecated APIs, so we turn off the warnings // only for this subproject. scalacOptions <<= scalacOptions map { currentOpts: Seq[String] => currentOpts.filterNot(_ == "-deprecation") }, initialCommands in console := """ |import org.apache.spark.SparkContext |import org.apache.spark.sql.catalyst.analysis._ |import org.apache.spark.sql.catalyst.dsl._ |import org.apache.spark.sql.catalyst.errors._ |import org.apache.spark.sql.catalyst.expressions._ |import org.apache.spark.sql.catalyst.plans.logical._ |import org.apache.spark.sql.catalyst.rules._ |import org.apache.spark.sql.catalyst.util._ |import org.apache.spark.sql.execution |import org.apache.spark.sql.functions._ |import org.apache.spark.sql.hive._ |import org.apache.spark.sql.hive.test.TestHive._ |import org.apache.spark.sql.hive.test.TestHive.implicits._ |import org.apache.spark.sql.types._""".stripMargin, cleanupCommands in console := "sparkContext.stop()", // Some of our log4j jars make it impossible to submit jobs from this JVM to Hive Map/Reduce // in order to generate golden files. This is only required for developers who are adding new // new query tests. fullClasspath in Test := (fullClasspath in Test).value.filterNot { f => f.toString.contains("jcl-over") } ) } object Assembly { import sbtassembly.AssemblyUtils._ import sbtassembly.Plugin._ import AssemblyKeys._ val hadoopVersion = taskKey[String]("The version of hadoop that spark is compiled against.") lazy val settings = assemblySettings ++ Seq( test in assembly := {}, hadoopVersion := { sys.props.get("hadoop.version") .getOrElse(SbtPomKeys.effectivePom.value.getProperties.get("hadoop.version").asInstanceOf[String]) }, jarName in assembly <<= (version, moduleName, hadoopVersion) map { (v, mName, hv) => if (mName.contains("streaming-flume-assembly") || mName.contains("streaming-kafka-0-8-assembly") || mName.contains("streaming-kafka-0-10-assembly") || mName.contains("streaming-kinesis-asl-assembly")) { // This must match the same name used in maven (see external/kafka-0-8-assembly/pom.xml) s"${mName}-${v}.jar" } else { s"${mName}-${v}-hadoop${hv}.jar" } }, jarName in (Test, assembly) <<= (version, moduleName, hadoopVersion) map { (v, mName, hv) => s"${mName}-test-${v}.jar" }, mergeStrategy in assembly := { case m if m.toLowerCase.endsWith("manifest.mf") => MergeStrategy.discard case m if m.toLowerCase.matches("meta-inf.*\\.sf$") => MergeStrategy.discard case "log4j.properties" => MergeStrategy.discard case m if m.toLowerCase.startsWith("meta-inf/services/") => MergeStrategy.filterDistinctLines case "reference.conf" => MergeStrategy.concat case _ => MergeStrategy.first } ) } object PySparkAssembly { import sbtassembly.Plugin._ import AssemblyKeys._ import java.util.zip.{ZipOutputStream, ZipEntry} lazy val settings = Seq( // Use a resource generator to copy all .py files from python/pyspark into a managed directory // to be included in the assembly. We can't just add "python/" to the assembly's resource dir // list since that will copy unneeded / unwanted files. resourceGenerators in Compile <+= resourceManaged in Compile map { outDir: File => val src = new File(BuildCommons.sparkHome, "python/pyspark") val zipFile = new File(BuildCommons.sparkHome , "python/lib/pyspark.zip") zipFile.delete() zipRecursive(src, zipFile) Seq[File]() } ) private def zipRecursive(source: File, destZipFile: File) = { val destOutput = new ZipOutputStream(new FileOutputStream(destZipFile)) addFilesToZipStream("", source, destOutput) destOutput.flush() destOutput.close() } private def addFilesToZipStream(parent: String, source: File, output: ZipOutputStream): Unit = { if (source.isDirectory()) { output.putNextEntry(new ZipEntry(parent + source.getName())) for (file <- source.listFiles()) { addFilesToZipStream(parent + source.getName() + File.separator, file, output) } } else { val in = new FileInputStream(source) output.putNextEntry(new ZipEntry(parent + source.getName())) val buf = new Array[Byte](8192) var n = 0 while (n != -1) { n = in.read(buf) if (n != -1) { output.write(buf, 0, n) } } output.closeEntry() in.close() } } } object Unidoc { import BuildCommons._ import sbtunidoc.Plugin._ import UnidocKeys._ private def ignoreUndocumentedPackages(packages: Seq[Seq[File]]): Seq[Seq[File]] = { packages .map(_.filterNot(_.getName.contains("$"))) .map(_.filterNot(_.getCanonicalPath.contains("org/apache/spark/deploy"))) .map(_.filterNot(_.getCanonicalPath.contains("org/apache/spark/examples"))) .map(_.filterNot(_.getCanonicalPath.contains("org/apache/spark/memory"))) .map(_.filterNot(_.getCanonicalPath.contains("org/apache/spark/network"))) .map(_.filterNot(_.getCanonicalPath.contains("org/apache/spark/shuffle"))) .map(_.filterNot(_.getCanonicalPath.contains("org/apache/spark/executor"))) .map(_.filterNot(_.getCanonicalPath.contains("org/apache/spark/unsafe"))) .map(_.filterNot(_.getCanonicalPath.contains("python"))) .map(_.filterNot(_.getCanonicalPath.contains("org/apache/spark/util/collection"))) .map(_.filterNot(_.getCanonicalPath.contains("org/apache/spark/sql/catalyst"))) .map(_.filterNot(_.getCanonicalPath.contains("org/apache/spark/sql/execution"))) .map(_.filterNot(_.getCanonicalPath.contains("org/apache/spark/sql/hive/test"))) } private def ignoreClasspaths(classpaths: Seq[Classpath]): Seq[Classpath] = { classpaths .map(_.filterNot(_.data.getCanonicalPath.matches(""".*kafka-clients-0\.10.*"""))) .map(_.filterNot(_.data.getCanonicalPath.matches(""".*kafka_2\..*-0\.10.*"""))) } val unidocSourceBase = settingKey[String]("Base URL of source links in Scaladoc.") lazy val settings = scalaJavaUnidocSettings ++ Seq ( publish := {}, unidocProjectFilter in(ScalaUnidoc, unidoc) := inAnyProject -- inProjects(OldDeps.project, repl, examples, tools, streamingFlumeSink, yarn, tags, streamingKafka010, sqlKafka010), unidocProjectFilter in(JavaUnidoc, unidoc) := inAnyProject -- inProjects(OldDeps.project, repl, examples, tools, streamingFlumeSink, yarn, tags, streamingKafka010, sqlKafka010), unidocAllClasspaths in (ScalaUnidoc, unidoc) := { ignoreClasspaths((unidocAllClasspaths in (ScalaUnidoc, unidoc)).value) }, unidocAllClasspaths in (JavaUnidoc, unidoc) := { ignoreClasspaths((unidocAllClasspaths in (JavaUnidoc, unidoc)).value) }, // Skip actual catalyst, but include the subproject. // Catalyst is not public API and contains quasiquotes which break scaladoc. unidocAllSources in (ScalaUnidoc, unidoc) := { ignoreUndocumentedPackages((unidocAllSources in (ScalaUnidoc, unidoc)).value) }, // Skip class names containing $ and some internal packages in Javadocs unidocAllSources in (JavaUnidoc, unidoc) := { ignoreUndocumentedPackages((unidocAllSources in (JavaUnidoc, unidoc)).value) .map(_.filterNot(_.getCanonicalPath.contains("org/apache/hadoop"))) }, javacOptions in (JavaUnidoc, unidoc) := Seq( "-windowtitle", "Spark " + version.value.replaceAll("-SNAPSHOT", "") + " JavaDoc", "-public", "-noqualifier", "java.lang", "-tag", """example:a:Example\:""", "-tag", """note:a:Note\:""", "-tag", "group:X", "-tag", "tparam:X", "-tag", "constructor:X", "-tag", "todo:X", "-tag", "groupname:X" ), // Use GitHub repository for Scaladoc source links unidocSourceBase := s"https://github.com/apache/spark/tree/v${version.value}", scalacOptions in (ScalaUnidoc, unidoc) ++= Seq( "-groups", // Group similar methods together based on the @group annotation. "-skip-packages", "org.apache.hadoop" ) ++ ( // Add links to sources when generating Scaladoc for a non-snapshot release if (!isSnapshot.value) { Opts.doc.sourceUrl(unidocSourceBase.value + "€{FILE_PATH}.scala") } else { Seq() } ) ) } object CopyDependencies { val copyDeps = TaskKey[Unit]("copyDeps", "Copies needed dependencies to the build directory.") val destPath = (crossTarget in Compile) / "jars" lazy val settings = Seq( copyDeps := { val dest = destPath.value if (!dest.isDirectory() && !dest.mkdirs()) { throw new IOException("Failed to create jars directory.") } (dependencyClasspath in Compile).value.map(_.data) .filter { jar => jar.isFile() } .foreach { jar => val destJar = new File(dest, jar.getName()) if (destJar.isFile()) { destJar.delete() } Files.copy(jar.toPath(), destJar.toPath()) } }, crossTarget in (Compile, packageBin) := destPath.value, packageBin in Compile <<= (packageBin in Compile).dependsOn(copyDeps) ) } object Java8TestSettings { import BuildCommons._ lazy val settings = Seq( javacJVMVersion := "1.8", // Targeting Java 8 bytecode is only supported in Scala 2.11.4 and higher: scalacJVMVersion := (if (System.getProperty("scala-2.10") == "true") "1.7" else "1.8") ) } object TestSettings { import BuildCommons._ private val scalaBinaryVersion = if (System.getProperty("scala-2.10") == "true") { "2.10" } else { "2.11" } lazy val settings = Seq ( // Fork new JVMs for tests and set Java options for those fork := true, // Setting SPARK_DIST_CLASSPATH is a simple way to make sure any child processes // launched by the tests have access to the correct test-time classpath. envVars in Test ++= Map( "SPARK_DIST_CLASSPATH" -> (fullClasspath in Test).value.files.map(_.getAbsolutePath).mkString(":").stripSuffix(":"), "SPARK_PREPEND_CLASSES" -> "1", "SPARK_SCALA_VERSION" -> scalaBinaryVersion, "SPARK_TESTING" -> "1", "JAVA_HOME" -> sys.env.get("JAVA_HOME").getOrElse(sys.props("java.home"))), javaOptions in Test += s"-Djava.io.tmpdir=$testTempDir", javaOptions in Test += "-Dspark.test.home=" + sparkHome, javaOptions in Test += "-Dspark.testing=1", javaOptions in Test += "-Dspark.port.maxRetries=100", javaOptions in Test += "-Dspark.master.rest.enabled=false", javaOptions in Test += "-Dspark.memory.debugFill=true", javaOptions in Test += "-Dspark.ui.enabled=false", javaOptions in Test += "-Dspark.ui.showConsoleProgress=false", javaOptions in Test += "-Dspark.unsafe.exceptionOnMemoryLeak=true", javaOptions in Test += "-Dsun.io.serialization.extendedDebugInfo=false", javaOptions in Test += "-Dderby.system.durability=test", javaOptions in Test ++= System.getProperties.asScala.filter(_._1.startsWith("spark")) .map { case (k,v) => s"-D$k=$v" }.toSeq, javaOptions in Test += "-ea", javaOptions in Test ++= "-Xmx3g -Xss4096k -XX:PermSize=128M -XX:MaxNewSize=256m -XX:MaxPermSize=1g" .split(" ").toSeq, javaOptions += "-Xmx3g", // Exclude tags defined in a system property testOptions in Test += Tests.Argument(TestFrameworks.ScalaTest, sys.props.get("test.exclude.tags").map { tags => tags.split(",").flatMap { tag => Seq("-l", tag) }.toSeq }.getOrElse(Nil): _*), testOptions in Test += Tests.Argument(TestFrameworks.JUnit, sys.props.get("test.exclude.tags").map { tags => Seq("--exclude-categories=" + tags) }.getOrElse(Nil): _*), // Show full stack trace and duration in test cases. testOptions in Test += Tests.Argument("-oDF"), testOptions in Test += Tests.Argument(TestFrameworks.JUnit, "-v", "-a"), // Enable Junit testing. libraryDependencies += "com.novocode" % "junit-interface" % "0.11" % "test", // Only allow one test at a time, even across projects, since they run in the same JVM parallelExecution in Test := false, // Make sure the test temp directory exists. resourceGenerators in Test <+= resourceManaged in Test map { outDir: File => var dir = new File(testTempDir) if (!dir.isDirectory()) { // Because File.mkdirs() can fail if multiple callers are trying to create the same // parent directory, this code tries to create parents one at a time, and avoids // failures when the directories have been created by somebody else. val stack = new Stack[File]() while (!dir.isDirectory()) { stack.push(dir) dir = dir.getParentFile() } while (stack.nonEmpty) { val d = stack.pop() require(d.mkdir() || d.isDirectory(), s"Failed to create directory $d") } } Seq[File]() }, concurrentRestrictions in Global += Tags.limit(Tags.Test, 1), // Remove certain packages from Scaladoc scalacOptions in (Compile, doc) := Seq( "-groups", "-skip-packages", Seq( "org.apache.spark.api.python", "org.apache.spark.network", "org.apache.spark.deploy", "org.apache.spark.util.collection" ).mkString(":"), "-doc-title", "Spark " + version.value.replaceAll("-SNAPSHOT", "") + " ScalaDoc" ) ) }
{ "content_hash": "9d2a7e81e17e7f75369b7e0f10f7160f", "timestamp": "", "source": "github", "line_count": 885, "max_line_length": 208, "avg_line_length": 38.948022598870054, "alnum_prop": 0.6662218225071803, "repo_name": "kimoonkim/spark", "id": "01e7e445713ac94c5d8d2a95b0f73b86febcbe23", "size": "35271", "binary": false, "copies": "1", "ref": "refs/heads/branch-2.1-kubernetes", "path": "project/SparkBuild.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "31399" }, { "name": "Batchfile", "bytes": "24063" }, { "name": "C", "bytes": "1493" }, { "name": "CSS", "bytes": "23868" }, { "name": "HTML", "bytes": "8567" }, { "name": "Java", "bytes": "2715989" }, { "name": "JavaScript", "bytes": "133737" }, { "name": "Makefile", "bytes": "7774" }, { "name": "PLpgSQL", "bytes": "3797" }, { "name": "PowerShell", "bytes": "3735" }, { "name": "Python", "bytes": "2071544" }, { "name": "R", "bytes": "876839" }, { "name": "Roff", "bytes": "29382" }, { "name": "SQLPL", "bytes": "6233" }, { "name": "Scala", "bytes": "21156284" }, { "name": "Shell", "bytes": "151958" }, { "name": "Thrift", "bytes": "33605" } ], "symlink_target": "" }
body { font-family: 'PFAgoraSansPro-Regular', 'Arial'; background: #ffffff; color: #000000; margin: 0; padding: 0; } /* ---------------------------------------------- */ .scroll-disable-hover, .scroll-disable-hover * { pointer-events: none !important; } /**/ /* placeholder */ textarea::-webkit-input-placeholder { color: #ffffff; opacity: 1; } textarea::-moz-placeholder { color: #ffffff; opacity: 1; } textarea:-moz-placeholder { color: #ffffff; opacity: 1; } textarea:-ms-input-placeholder { color: #ffffff; opacity: 1; } textarea:focus::-webkit-input-placeholder {opacity: 0; transition: opacity 0.3s ease;} textarea:focus::-moz-placeholder {opacity: 0; transition: opacity 0.3s ease;} textarea:focus:-moz-placeholder {opacity: 0; transition: opacity 0.3s ease;} textarea:focus:-ms-input-placeholder {opacity: 0; transition: opacity 0.3s ease;} /*/placeholder/*/ /* input contact form footer */ input::-webkit-input-placeholder { color: #ffffff; opacity: 1; } input::-moz-placeholder { color: #ffffff; opacity: 1; } input:-moz-placeholder { color: #ffffff; opacity: 1; } input:-ms-input-placeholder { color: #ffffff; opacity: 1; } input:focus::-webkit-input-placeholder {opacity: 0; transition: opacity 0.3s ease;} input:focus::-moz-placeholder {opacity: 0; transition: opacity 0.3s ease;} input:focus:-moz-placeholder {opacity: 0; transition: opacity 0.3s ease;} input:focus:-ms-input-placeholder {opacity: 0; transition: opacity 0.3s ease;} /*/input contact form footer/*/ /* input contact form fly */ input.fly-form-input::-webkit-input-placeholder { color: #565a6e; opacity: 1; } input.fly-form-input::-moz-placeholder { color: #565a6e; opacity: 1; } input.fly-form-input:-moz-placeholder { color: #565a6e; opacity: 1; } input.fly-form-input:-ms-input-placeholder { color: #565a6e; opacity: 1; } input.fly-form-input:focus::-webkit-input-placeholder {opacity: 0; transition: opacity 0.3s ease;} input.fly-form-input:focus::-moz-placeholder {opacity: 0; transition: opacity 0.3s ease;} input.fly-form-input:focus:-moz-placeholder {opacity: 0; transition: opacity 0.3s ease;} input.fly-form-input:focus:-ms-input-placeholder {opacity: 0; transition: opacity 0.3s ease;} /*/input contact form fly/*/ /**/ .row-container { display: block; width: 100%; position: relative; z-index: 10; } .row-container.first-margin { margin-top: 900px; } .row-container.bg-dark { background: #eceff5; } .row-container.bg-white { background: #ffffff; } .row-container.bg-footer { background: url('../images/i_contacts/background.png') no-repeat; background-size: cover; } .row-container .rc-title { display: block; width: 100%; padding: 50px 0 0 0; text-align: center; } .row-container .rc-title h3 { margin: 0; padding: 0; font-family: 'PFAgoraSansPro-Thin'; font-size: 48px; color: #474d6e; text-transform: uppercase; } /* ---------------------------------------------- */ .container { -webkit-transition: 0.3s; -moz-transition: 0.3s; -ms-transition: 0.3s; -o-transition: 0.3s; transition: 0.3s; } .transit-200 { -webkit-transition: 0.2s; -moz-transition: 0.2s; -ms-transition: 0.2s; -o-transition: 0.2s; transition: 0.2s; } .transit-300 { -webkit-transition: 0.3s; -moz-transition: 0.3s; -ms-transition: 0.3s; -o-transition: 0.3s; transition: 0.3s; } .transit-500 { -webkit-transition: 0.5s; -moz-transition: 0.5s; -ms-transition: 0.5s; -o-transition: 0.5s; transition: 0.5s; } .transit-800 { -webkit-transition: 0.8s; -moz-transition: 0.8s; -ms-transition: 0.8s; -o-transition: 0.8s; transition: 0.8s; } .transit-1000 { -webkit-transition: 1s; -moz-transition: 1s; -ms-transition: 1s; -o-transition: 1s; transition: 1s; } .transit-3000 { -webkit-transition: 3s; -moz-transition: 3s; -ms-transition: 3s; -o-transition: 3s; transition: 3s; } .no-pad { padding: 0; } a:focus, input:focus, textarea:focus, button:focus, select:focus { outline: none; text-decoration: none; } .loader-img { width: 200px; height: 200px; position: fixed; top: 48%; left: 1%; right: 1%; margin: auto; z-index: 1000; text-align: center; } .loader-img img { width: 40px; height: 40px; border: none; } .loader-none { display: none; }
{ "content_hash": "c8e67adc3f12d24f833c026cee26217b", "timestamp": "", "source": "github", "line_count": 124, "max_line_length": 150, "avg_line_length": 36.145161290322584, "alnum_prop": 0.6345381526104418, "repo_name": "zserg84/webteam", "id": "6f8b13820088d03431fef564ac5a7ddaa5f1ee89", "size": "4482", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "frontend/web/style/css/management.css", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "1183" }, { "name": "Batchfile", "bytes": "1541" }, { "name": "CSS", "bytes": "1191597" }, { "name": "HTML", "bytes": "1357656" }, { "name": "JavaScript", "bytes": "1577281" }, { "name": "PHP", "bytes": "703721" } ], "symlink_target": "" }
package com.fly.firefly.ui.module; import com.fly.firefly.AppModule; import com.fly.firefly.ui.fragment.LoginFragment; import com.fly.firefly.ui.presenter.LoginPresenter; import com.squareup.otto.Bus; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; @Module( injects = LoginFragment.class, addsTo = AppModule.class, complete = false ) public class LoginModule { private final LoginPresenter.LoginView loginView; public LoginModule(LoginPresenter.LoginView loginView) { this.loginView = loginView; } @Provides @Singleton LoginPresenter provideLoginPresenter(Bus bus) { return new LoginPresenter(loginView, bus); } }
{ "content_hash": "a4d494917d91e4fa200fcc24c24e4192", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 60, "avg_line_length": 23.161290322580644, "alnum_prop": 0.7298050139275766, "repo_name": "imalpasha/flyfirefly", "id": "db8dab9b532b9f96ceade77db0302409b5bbf71a", "size": "718", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rhymecity/src/main/java/com/fly/firefly/ui/module/LoginModule.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "222181" } ], "symlink_target": "" }
package set import ( "encoding/json" "errors" "fmt" "io" "os" "regexp" "sort" "strings" "github.com/spf13/cobra" kapi "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/fieldpath" "k8s.io/kubernetes/pkg/kubectl" kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" "k8s.io/kubernetes/pkg/kubectl/resource" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util/strategicpatch" cmdutil "github.com/openshift/origin/pkg/cmd/util" "github.com/openshift/origin/pkg/cmd/util/clientcmd" ) const ( envLong = ` Update environment variables on a pod template or a build config List environment variable definitions in one or more pods, pod templates or build configuration. Add, update, or remove container environment variable definitions in one or more pod templates (within replication controllers or deployment configurations) or build configurations. View or modify the environment variable definitions on all containers in the specified pods or pod templates, or just those that match a wildcard. If "--env -" is passed, environment variables can be read from STDIN using the standard env syntax.` envExample = ` # Update deployment 'registry' with a new environment variable %[1]s env dc/registry STORAGE_DIR=/local # List the environment variables defined on a build config 'sample-build' %[1]s env bc/sample-build --list # List the environment variables defined on all pods %[1]s env pods --all --list # Output modified build config in YAML, and does not alter the object on the server %[1]s env bc/sample-build STORAGE_DIR=/data -o yaml # Update all containers in all replication controllers in the project to have ENV=prod %[1]s env rc --all ENV=prod # Import environment from a secret %[1]s env --from=secret/mysecret dc/myapp # Import environment from a config map with a prefix %[1]s env --from=configmap/myconfigmap --prefix=MYSQL_ dc/myapp # Remove the environment variable ENV from container 'c1' in all deployment configs %[1]s env dc --all --containers="c1" ENV- # Remove the environment variable ENV from a deployment config definition on disk and # update the deployment config on the server %[1]s env -f dc.json ENV- # Set some of the local shell environment into a deployment config on the server env | grep RAILS_ | %[1]s env -e - dc/registry` ) // NewCmdEnv implements the OpenShift cli env command func NewCmdEnv(fullName string, f *clientcmd.Factory, in io.Reader, out io.Writer) *cobra.Command { var filenames []string var env []string cmd := &cobra.Command{ Use: "env RESOURCE/NAME KEY_1=VAL_1 ... KEY_N=VAL_N", Short: "Update environment variables on a pod template", Long: envLong, Example: fmt.Sprintf(envExample, fullName), Run: func(cmd *cobra.Command, args []string) { err := RunEnv(f, in, out, cmd, args, env, filenames) if err == cmdutil.ErrExit { os.Exit(1) } kcmdutil.CheckErr(err) }, } cmd.Flags().StringP("containers", "c", "*", "The names of containers in the selected pod templates to change - may use wildcards") cmd.Flags().StringP("from", "", "", "The name of a resource from which to inject enviroment variables") cmd.Flags().StringP("prefix", "", "", "Prefix to append to variable names") cmd.Flags().StringSliceVarP(&env, "env", "e", env, "Specify key value pairs of environment variables to set into each container.") cmd.Flags().Bool("list", false, "Display the environment and any changes in the standard format") cmd.Flags().Bool("resolve", false, "Show secret or configmap references when listing variables") cmd.Flags().StringP("selector", "l", "", "Selector (label query) to filter on") cmd.Flags().Bool("all", false, "Select all resources in the namespace of the specified resource types") cmd.Flags().StringSliceVarP(&filenames, "filename", "f", filenames, "Filename, directory, or URL to file to use to edit the resource.") cmd.Flags().Bool("overwrite", true, "If true, allow environment to be overwritten, otherwise reject updates that overwrite existing environment.") cmd.Flags().String("resource-version", "", "If non-empty, the labels update will only succeed if this is the current resource-version for the object. Only valid when specifying a single resource.") cmd.Flags().StringP("output", "o", "", "Display the changed objects instead of updating them. One of: json|yaml.") cmd.Flags().String("output-version", "", "Output the changed objects with the given version (default api-version).") cmd.MarkFlagFilename("filename", "yaml", "yml", "json") return cmd } func validateNoOverwrites(existing []kapi.EnvVar, env []kapi.EnvVar) error { for _, e := range env { if current, exists := findEnv(existing, e.Name); exists && current.Value != e.Value { return fmt.Errorf("'%s' already has a value (%s), and --overwrite is false", current.Name, current.Value) } } return nil } func keyToEnvName(key string) string { validEnvNameRegexp := regexp.MustCompile("[^a-zA-Z0-9_]") return strings.ToUpper(validEnvNameRegexp.ReplaceAllString(key, "_")) } type resourceStore struct { secretStore map[string]*kapi.Secret configMapStore map[string]*kapi.ConfigMap } func newResourceStore() *resourceStore { return &resourceStore{ secretStore: make(map[string]*kapi.Secret), configMapStore: make(map[string]*kapi.ConfigMap), } } func getSecretRefValue(f *clientcmd.Factory, store *resourceStore, secretSelector *kapi.SecretKeySelector) (string, error) { secret, ok := store.secretStore[secretSelector.Name] if !ok { kubeClient, err := f.Client() if err != nil { return "", err } namespace, _, err := f.DefaultNamespace() if err != nil { return "", err } secret, err = kubeClient.Secrets(namespace).Get(secretSelector.Name) if err != nil { return "", err } store.secretStore[secretSelector.Name] = secret } if data, ok := secret.Data[secretSelector.Key]; ok { return string(data), nil } return "", fmt.Errorf("key %s not found in secret %s", secretSelector.Key, secretSelector.Name) } func getConfigMapRefValue(f *clientcmd.Factory, store *resourceStore, configMapSelector *kapi.ConfigMapKeySelector) (string, error) { configMap, ok := store.configMapStore[configMapSelector.Name] if !ok { kubeClient, err := f.Client() if err != nil { return "", err } namespace, _, err := f.DefaultNamespace() if err != nil { return "", err } configMap, err = kubeClient.ConfigMaps(namespace).Get(configMapSelector.Name) if err != nil { return "", err } store.configMapStore[configMapSelector.Name] = configMap } if data, ok := configMap.Data[configMapSelector.Key]; ok { return string(data), nil } return "", fmt.Errorf("key %s not found in config map %s", configMapSelector.Key, configMapSelector.Name) } func getEnvVarRefValue(f *clientcmd.Factory, store *resourceStore, from *kapi.EnvVarSource, obj runtime.Object, c *kapi.Container) (string, error) { if from.SecretKeyRef != nil { return getSecretRefValue(f, store, from.SecretKeyRef) } if from.ConfigMapKeyRef != nil { return getConfigMapRefValue(f, store, from.ConfigMapKeyRef) } if from.FieldRef != nil { return fieldpath.ExtractFieldPathAsString(obj, from.FieldRef.FieldPath) } if from.ResourceFieldRef != nil { return fieldpath.ExtractContainerResourceValue(from.ResourceFieldRef, c) } return "", fmt.Errorf("invalid valueFrom") } func getEnvVarRefString(from *kapi.EnvVarSource) string { if from.ConfigMapKeyRef != nil { return fmt.Sprintf("configmap %s, key %s", from.ConfigMapKeyRef.Name, from.ConfigMapKeyRef.Key) } if from.SecretKeyRef != nil { return fmt.Sprintf("secret %s, key %s", from.SecretKeyRef.Name, from.SecretKeyRef.Key) } if from.FieldRef != nil { return fmt.Sprintf("field path %s", from.FieldRef.FieldPath) } if from.ResourceFieldRef != nil { containerPrefix := "" if from.ResourceFieldRef.ContainerName != "" { containerPrefix = fmt.Sprintf("%s/", from.ResourceFieldRef.ContainerName) } return fmt.Sprintf("resource field %s%s", containerPrefix, from.ResourceFieldRef.Resource) } return "invalid valueFrom" } // RunEnv contains all the necessary functionality for the OpenShift cli env command // TODO: refactor to share the common "patch resource" pattern of probe func RunEnv(f *clientcmd.Factory, in io.Reader, out io.Writer, cmd *cobra.Command, args []string, envParams, filenames []string) error { resources, envArgs, ok := cmdutil.SplitEnvironmentFromResources(args) if !ok { return kcmdutil.UsageError(cmd, "all resources must be specified before environment changes: %s", strings.Join(args, " ")) } if len(filenames) == 0 && len(resources) < 1 { return kcmdutil.UsageError(cmd, "one or more resources must be specified as <resource> <name> or <resource>/<name>") } containerMatch := kcmdutil.GetFlagString(cmd, "containers") list := kcmdutil.GetFlagBool(cmd, "list") resolve := kcmdutil.GetFlagBool(cmd, "resolve") selector := kcmdutil.GetFlagString(cmd, "selector") all := kcmdutil.GetFlagBool(cmd, "all") overwrite := kcmdutil.GetFlagBool(cmd, "overwrite") resourceVersion := kcmdutil.GetFlagString(cmd, "resource-version") outputFormat := kcmdutil.GetFlagString(cmd, "output") from := kcmdutil.GetFlagString(cmd, "from") prefix := kcmdutil.GetFlagString(cmd, "prefix") if list && len(outputFormat) > 0 { return kcmdutil.UsageError(cmd, "--list and --output may not be specified together") } clientConfig, err := f.ClientConfig() if err != nil { return err } cmdNamespace, explicit, err := f.DefaultNamespace() if err != nil { return err } env, remove, err := cmdutil.ParseEnv(append(envParams, envArgs...), in) if err != nil { return err } if len(from) != 0 { mapper, typer := f.Object(false) b := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), kapi.Codecs.UniversalDecoder()). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). FilenameParam(explicit, false, filenames...). SelectorParam(selector). ResourceTypeOrNameArgs(all, from). Flatten() one := false infos, err := b.Do().IntoSingular(&one).Infos() if err != nil { return err } for _, info := range infos { switch from := info.Object.(type) { case *kapi.Secret: for key := range from.Data { envVar := kapi.EnvVar{ Name: keyToEnvName(key), ValueFrom: &kapi.EnvVarSource{ SecretKeyRef: &kapi.SecretKeySelector{ LocalObjectReference: kapi.LocalObjectReference{ Name: from.Name, }, Key: key, }, }, } env = append(env, envVar) } case *kapi.ConfigMap: for key := range from.Data { envVar := kapi.EnvVar{ Name: keyToEnvName(key), ValueFrom: &kapi.EnvVarSource{ ConfigMapKeyRef: &kapi.ConfigMapKeySelector{ LocalObjectReference: kapi.LocalObjectReference{ Name: from.Name, }, Key: key, }, }, } env = append(env, envVar) } default: return fmt.Errorf("unsupported resource specified in --from") } } } if len(prefix) != 0 { for i := range env { env[i].Name = fmt.Sprintf("%s%s", prefix, env[i].Name) } } mapper, typer := f.Object(false) b := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), kapi.Codecs.UniversalDecoder()). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). FilenameParam(explicit, false, filenames...). SelectorParam(selector). ResourceTypeOrNameArgs(all, resources...). Flatten() one := false infos, err := b.Do().IntoSingular(&one).Infos() if err != nil { return err } // only apply resource version locking on a single resource if !one && len(resourceVersion) > 0 { return kcmdutil.UsageError(cmd, "--resource-version may only be used with a single resource") } // Keep a copy of the original objects prior to updating their environment. // Used in constructing the patch(es) that will be applied in the server. gv := *clientConfig.GroupVersion oldObjects, err := resource.AsVersionedObjects(infos, gv, kapi.Codecs.LegacyCodec(gv)) if err != nil { return err } if len(oldObjects) != len(infos) { return fmt.Errorf("could not convert all objects to API version %q", clientConfig.GroupVersion) } oldData := make([][]byte, len(infos)) for i := range oldObjects { old, err := json.Marshal(oldObjects[i]) if err != nil { return err } oldData[i] = old } skipped := 0 errored := []*resource.Info{} for _, info := range infos { ok, err := f.UpdatePodSpecForObject(info.Object, func(spec *kapi.PodSpec) error { resolutionErrorsEncountered := false containers, _ := selectContainers(spec.Containers, containerMatch) if len(containers) == 0 { fmt.Fprintf(cmd.OutOrStderr(), "warning: %s/%s does not have any containers matching %q\n", info.Mapping.Resource, info.Name, containerMatch) return nil } for _, c := range containers { if !overwrite { if err := validateNoOverwrites(c.Env, env); err != nil { errored = append(errored, info) return err } } c.Env = updateEnv(c.Env, env, remove) if list { resolveErrors := map[string][]string{} store := newResourceStore() fmt.Fprintf(out, "# %s %s, container %s\n", info.Mapping.Resource, info.Name, c.Name) for _, env := range c.Env { // Print the simple value if env.ValueFrom == nil { fmt.Fprintf(out, "%s=%s\n", env.Name, env.Value) continue } // Print the reference version if !resolve { fmt.Fprintf(out, "# %s from %s\n", env.Name, getEnvVarRefString(env.ValueFrom)) continue } value, err := getEnvVarRefValue(f, store, env.ValueFrom, info.Object, c) // Print the resolved value if err == nil { fmt.Fprintf(out, "%s=%s\n", env.Name, value) continue } // Print the reference version and save the resolve error fmt.Fprintf(out, "# %s from %s\n", env.Name, getEnvVarRefString(env.ValueFrom)) errString := err.Error() resolveErrors[errString] = append(resolveErrors[errString], env.Name) resolutionErrorsEncountered = true } // Print any resolution errors errs := []string{} for err, vars := range resolveErrors { sort.Strings(vars) errs = append(errs, fmt.Sprintf("error retrieving reference for %s: %v", strings.Join(vars, ", "), err)) } sort.Strings(errs) for _, err := range errs { fmt.Fprintln(cmd.OutOrStderr(), err) } } } if resolutionErrorsEncountered { errored = append(errored, info) return errors.New("failed to retrieve valueFrom references") } return nil }) if !ok { // This is a fallback function for objects that don't have pod spec. ok, err = f.UpdateObjectEnvironment(info.Object, func(vars *[]kapi.EnvVar) error { if vars == nil { return fmt.Errorf("no environment variables provided") } if !overwrite { if err := validateNoOverwrites(*vars, env); err != nil { errored = append(errored, info) return err } } *vars = updateEnv(*vars, env, remove) if list { fmt.Fprintf(out, "# %s %s\n", info.Mapping.Resource, info.Name) for _, env := range *vars { fmt.Fprintf(out, "%s=%s\n", env.Name, env.Value) } } return nil }) if !ok { skipped++ continue } } if err != nil { fmt.Fprintf(cmd.OutOrStderr(), "error: %s/%s %v\n", info.Mapping.Resource, info.Name, err) continue } } if one && skipped == len(infos) { return fmt.Errorf("%s/%s is not a pod or does not have a pod template", infos[0].Mapping.Resource, infos[0].Name) } if len(errored) == len(infos) { return cmdutil.ErrExit } if list { return nil } if len(outputFormat) != 0 { outputVersion, err := kcmdutil.OutputVersion(cmd, clientConfig.GroupVersion) if err != nil { return err } objects, err := resource.AsVersionedObjects(infos, outputVersion, kapi.Codecs.LegacyCodec(outputVersion)) if err != nil { return err } if len(objects) != len(infos) { return fmt.Errorf("could not convert all objects to API version %q", outputVersion) } p, _, err := kubectl.GetPrinter(outputFormat, "", false) if err != nil { return err } for _, object := range objects { if err := p.PrintObj(object, out); err != nil { return err } } return nil } objects, err := resource.AsVersionedObjects(infos, gv, kapi.Codecs.LegacyCodec(gv)) if err != nil { return err } if len(objects) != len(infos) { return fmt.Errorf("could not convert all objects to API version %q", clientConfig.GroupVersion) } failed := false updates: for i, info := range infos { for _, erroredInfo := range errored { if info == erroredInfo { continue updates } } newData, err := json.Marshal(objects[i]) if err != nil { return err } patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData[i], newData, objects[i]) if err != nil { return err } obj, err := resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, kapi.StrategicMergePatchType, patchBytes) if err != nil { handlePodUpdateError(cmd.OutOrStderr(), err, "environment variables") failed = true continue } info.Refresh(obj, true) // make sure arguments to set or replace environment variables are set // before returning a successful message if len(env) == 0 && len(envArgs) == 0 { return fmt.Errorf("at least one environment variable must be provided") } shortOutput := kcmdutil.GetFlagString(cmd, "output") == "name" kcmdutil.PrintSuccess(mapper, shortOutput, out, info.Mapping.Resource, info.Name, "updated") } if failed { return cmdutil.ErrExit } return nil }
{ "content_hash": "ecd588b03cfb9337b9b1856304cd8ff8", "timestamp": "", "source": "github", "line_count": 545, "max_line_length": 198, "avg_line_length": 32.67339449541284, "alnum_prop": 0.6856292469253664, "repo_name": "inlandsee/origin", "id": "49cb1e8382f59ae97bb3f2d4e971db8c6dbb690c", "size": "17807", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "pkg/cmd/cli/cmd/set/env.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "921" }, { "name": "DIGITAL Command Language", "bytes": "117" }, { "name": "Go", "bytes": "11915906" }, { "name": "Groff", "bytes": "2049" }, { "name": "Makefile", "bytes": "7213" }, { "name": "Protocol Buffer", "bytes": "121278" }, { "name": "Python", "bytes": "15724" }, { "name": "Ruby", "bytes": "363" }, { "name": "Shell", "bytes": "2146451" } ], "symlink_target": "" }
delete from employee where id=6
{ "content_hash": "44b76eab74d4613016cd04ac4e5c9b77", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 31, "avg_line_length": 32, "alnum_prop": 0.8125, "repo_name": "dbastin/donkey", "id": "2511a6391e42292088346c7c3ae4b5b0a061e84e", "size": "32", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "data/expected/synchronator/employee-delete.sql", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "2577" }, { "name": "Java", "bytes": "289490" }, { "name": "Shell", "bytes": "2801" }, { "name": "XSLT", "bytes": "7541" } ], "symlink_target": "" }
<?php /** * Plugin public functions. * * @package Meta Box */ if ( ! function_exists( 'rwmb_meta' ) ) { /** * Get post meta. * * @param string $key Meta key. Required. * @param array $args Array of arguments. Optional. * @param int|null $post_id Post ID. null for current post. Optional. * * @return mixed */ function rwmb_meta( $key, $args = array(), $post_id = null ) { $args = wp_parse_args( $args ); /* * If meta boxes is registered in the backend only, we can't get field's params. * This is for backward compatibility with version < 4.8.0. */ $field = RWMB_Helper::find_field( $key, $post_id ); /* * If field is not found, which can caused by registering meta boxes for the backend only or conditional registration. * Then fallback to the old method to retrieve meta (which uses get_post_meta() as the latest fallback). */ if ( false === $field ) { return apply_filters( 'rwmb_meta', RWMB_Helper::meta( $key, $args, $post_id ) ); } $meta = in_array( $field['type'], array( 'oembed', 'map' ), true ) ? rwmb_the_value( $key, $args, $post_id, false ) : rwmb_get_value( $key, $args, $post_id ); return apply_filters( 'rwmb_meta', $meta, $key, $args, $post_id ); } } if ( ! function_exists( 'rwmb_get_value' ) ) { /** * Get value of custom field. * This is used to replace old version of rwmb_meta key. * * @param string $field_id Field ID. Required. * @param array $args Additional arguments. Rarely used. See specific fields for details. * @param int|null $post_id Post ID. null for current post. Optional. * * @return mixed false if field doesn't exist. Field value otherwise. */ function rwmb_get_value( $field_id, $args = array(), $post_id = null ) { $args = wp_parse_args( $args ); $field = RWMB_Helper::find_field( $field_id, $post_id ); // Get field value. $value = $field ? RWMB_Field::call( 'get_value', $field, $args, $post_id ) : false; /* * Allow developers to change the returned value of field. * For version < 4.8.2, the filter name was 'rwmb_get_field'. * * @param mixed $value Field value. * @param array $field Field parameters. * @param array $args Additional arguments. Rarely used. See specific fields for details. * @param int|null $post_id Post ID. null for current post. Optional. */ $value = apply_filters( 'rwmb_get_value', $value, $field, $args, $post_id ); return $value; } } if ( ! function_exists( 'rwmb_the_value' ) ) { /** * Display the value of a field * * @param string $field_id Field ID. Required. * @param array $args Additional arguments. Rarely used. See specific fields for details. * @param int|null $post_id Post ID. null for current post. Optional. * @param bool $echo Display field meta value? Default `true` which works in almost all cases. We use `false` for the [rwmb_meta] shortcode. * * @return string */ function rwmb_the_value( $field_id, $args = array(), $post_id = null, $echo = true ) { $args = wp_parse_args( $args ); $field = RWMB_Helper::find_field( $field_id, $post_id ); if ( ! $field ) { return ''; } $output = RWMB_Field::call( 'the_value', $field, $args, $post_id ); /* * Allow developers to change the returned value of field. * For version < 4.8.2, the filter name was 'rwmb_get_field'. * * @param mixed $value Field HTML output. * @param array $field Field parameters. * @param array $args Additional arguments. Rarely used. See specific fields for details. * @param int|null $post_id Post ID. null for current post. Optional. */ $output = apply_filters( 'rwmb_the_value', $output, $field, $args, $post_id ); if ( $echo ) { echo $output; // WPCS: XSS OK. } return $output; } }// End if(). if ( ! function_exists( 'rwmb_meta_shortcode' ) ) { /** * Shortcode to display meta value. * * @param array $atts Shortcode attributes, same as rwmb_meta() function, but has more "meta_key" parameter. * * @return string */ function rwmb_meta_shortcode( $atts ) { $atts = wp_parse_args( $atts, array( 'post_id' => get_the_ID(), ) ); if ( empty( $atts['meta_key'] ) ) { return ''; } $field_id = $atts['meta_key']; $post_id = $atts['post_id']; unset( $atts['meta_key'], $atts['post_id'] ); return rwmb_the_value( $field_id, $atts, $post_id, false ); } add_shortcode( 'rwmb_meta', 'rwmb_meta_shortcode' ); }
{ "content_hash": "117aa678f486bc2f34f37efe6ab23f4a", "timestamp": "", "source": "github", "line_count": 138, "max_line_length": 151, "avg_line_length": 32.56521739130435, "alnum_prop": 0.6188251001335113, "repo_name": "1001hz/wpnoonan", "id": "3ac9f2397182f9eff6d5e8abb60331406a833c9a", "size": "4494", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "plugins/meta-box/inc/functions.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "616" }, { "name": "CSS", "bytes": "1118696" }, { "name": "HTML", "bytes": "17775" }, { "name": "JavaScript", "bytes": "602452" }, { "name": "PHP", "bytes": "2743716" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Struct torr_base_unit</title> <link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.79.1"> <link rel="home" href="../../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset"> <link rel="up" href="../../../boost_units/Reference.html#header.boost.units.base_units.metric.torr_hpp" title="Header &lt;boost/units/base_units/metric/torr.hpp&gt;"> <link rel="prev" href="../ba_1_3_45_10_10_6_17_1_1_1.html" title="Struct base_unit_info&lt;metric::ton_base_unit&gt;"> <link rel="next" href="../ba_1_3_45_10_10_6_19_1_1_1.html" title="Struct base_unit_info&lt;metric::year_base_unit&gt;"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td> <td align="center"><a href="../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../ba_1_3_45_10_10_6_17_1_1_1.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../boost_units/Reference.html#header.boost.units.base_units.metric.torr_hpp"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../ba_1_3_45_10_10_6_19_1_1_1.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="boost.units.metric.torr_base_unit"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Struct torr_base_unit</span></h2> <p>boost::units::metric::torr_base_unit</p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="../../../boost_units/Reference.html#header.boost.units.base_units.metric.torr_hpp" title="Header &lt;boost/units/base_units/metric/torr.hpp&gt;">boost/units/base_units/metric/torr.hpp</a>&gt; </span> <span class="keyword">struct</span> <a class="link" href="torr_base_unit.html" title="Struct torr_base_unit">torr_base_unit</a> <span class="special">:</span> <span class="keyword">public</span> boost::units::base_unit&lt; torr_base_unit, si::pressure ::dimension_type, -401 &gt; <span class="special">{</span> <span class="comment">// <a class="link" href="torr_base_unit.html#id-1_3_45_10_10_6_18_1_1_1_1_2-bb">public static functions</a></span> <span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">char</span> <span class="special">*</span> <a class="link" href="torr_base_unit.html#id-1_3_45_10_10_6_18_1_1_1_1_2_1-bb"><span class="identifier">name</span></a><span class="special">(</span><span class="special">)</span><span class="special">;</span> <span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">char</span> <span class="special">*</span> <a class="link" href="torr_base_unit.html#id-1_3_45_10_10_6_18_1_1_1_1_2_2-bb"><span class="identifier">symbol</span></a><span class="special">(</span><span class="special">)</span><span class="special">;</span> <span class="special">}</span><span class="special">;</span></pre></div> <div class="refsect1"> <a name="id-1.3.45.10.10.6.18.3.4"></a><h2>Description</h2> <div class="refsect2"> <a name="id-1.3.45.10.10.6.18.3.4.2"></a><h3> <a name="id-1_3_45_10_10_6_18_1_1_1_1_2-bb"></a><code class="computeroutput">torr_base_unit</code> public static functions</h3> <div class="orderedlist"><ol class="orderedlist" type="1"> <li class="listitem"><pre class="literallayout"><span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">char</span> <span class="special">*</span> <a name="id-1_3_45_10_10_6_18_1_1_1_1_2_1-bb"></a><span class="identifier">name</span><span class="special">(</span><span class="special">)</span><span class="special">;</span></pre></li> <li class="listitem"><pre class="literallayout"><span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">char</span> <span class="special">*</span> <a name="id-1_3_45_10_10_6_18_1_1_1_1_2_2-bb"></a><span class="identifier">symbol</span><span class="special">(</span><span class="special">)</span><span class="special">;</span></pre></li> </ol></div> </div> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright © 2003-2008 Matthias Christian Schabel<br>Copyright © 2007-2010 Steven Watanabe<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../ba_1_3_45_10_10_6_17_1_1_1.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../boost_units/Reference.html#header.boost.units.base_units.metric.torr_hpp"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../ba_1_3_45_10_10_6_19_1_1_1.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
{ "content_hash": "74443f7f68ec8f28475768f1668d7ec3", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 524, "avg_line_length": 90.8840579710145, "alnum_prop": 0.6525275075745495, "repo_name": "davehorton/drachtio-server", "id": "fbd88eb00f86fee38f058cb2aa3f685855568b6c", "size": "6273", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "deps/boost_1_77_0/doc/html/boost/units/metric/torr_base_unit.html", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "662596" }, { "name": "Dockerfile", "bytes": "1330" }, { "name": "JavaScript", "bytes": "60639" }, { "name": "M4", "bytes": "35273" }, { "name": "Makefile", "bytes": "5960" }, { "name": "Shell", "bytes": "47298" } ], "symlink_target": "" }
namespace AjErl.Tests { using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using AjErl.Compiler; using AjErl.Expressions; using AjErl.Forms; using AjErl.Language; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class EvaluateTests { private Machine machine; private Context context; [TestInitialize] public void Setup() { this.machine = new Machine(); this.context = this.machine.RootContext; } [TestMethod] public void EvaluateInteger() { Assert.AreEqual(1, this.EvaluateExpression("1.")); } [TestMethod] public void EvaluateSum() { Assert.AreEqual(3, this.EvaluateExpression("1+2.")); } [TestMethod] public void EvaluateVariableMatch() { Assert.AreEqual(3, this.EvaluateExpression("X=1+2.")); Assert.AreEqual(3, this.context.GetValue("X")); } [TestMethod] public void EvaluateList() { var result = this.EvaluateExpression("[1,2,1+2]."); Assert.IsNotNull(result); Assert.IsInstanceOfType(result, typeof(List)); Assert.AreEqual("[1,2,3]", result.ToString()); } [TestMethod] public void EvaluateListWithTail() { var result = this.EvaluateExpression("[1,2|[3,4]]."); Assert.IsNotNull(result); Assert.IsInstanceOfType(result, typeof(List)); Assert.AreEqual("[1,2,3,4]", result.ToString()); } [TestMethod] public void EvaluateListWithExpressions() { var result = this.EvaluateExpression("[1+7,hello,2-2,{cost, apple, 30-20},3]."); Assert.IsNotNull(result); Assert.IsInstanceOfType(result, typeof(List)); Assert.AreEqual("[8,hello,0,{cost,apple,10},3]", result.ToString()); } [TestMethod] public void EvaluateListWithBoundVariableAsTail() { this.EvaluateExpression("ThingsToBuy = [{apples,10},{pears,6},{milk,3}]."); var result = this.EvaluateExpression("ThingsToBuy1 = [{oranges,4},{newspaper,1}|ThingsToBuy]."); Assert.IsNotNull(result); Assert.IsInstanceOfType(result, typeof(List)); Assert.AreEqual("[{oranges,4},{newspaper,1},{apples,10},{pears,6},{milk,3}]", result.ToString()); } [TestMethod] public void EvaluateMathHeadTailToList() { this.EvaluateExpression("[Buy|ThingsToBuy] = [{oranges,4},{newspaper,1},{apples,10},{pears,6},{milk,3}]."); Assert.AreEqual("{oranges,4}", this.context.GetValue("Buy").ToString()); Assert.AreEqual("[{newspaper,1},{apples,10},{pears,6},{milk,3}]", this.context.GetValue("ThingsToBuy").ToString()); } [TestMethod] public void EvaluateMathHeadMemberTailToList() { this.EvaluateExpression("[Buy1,Buy2|ThingsToBuy] = [{oranges,4},{newspaper,1},{apples,10},{pears,6},{milk,3}]."); Assert.AreEqual("{oranges,4}", this.context.GetValue("Buy1").ToString()); Assert.AreEqual("{newspaper,1}", this.context.GetValue("Buy2").ToString()); Assert.AreEqual("[{apples,10},{pears,6},{milk,3}]", this.context.GetValue("ThingsToBuy").ToString()); } [TestMethod] public void EvaluateUnboundVariable() { this.EvaluateWithError("X.", "variable 'X' is unbound"); } [TestMethod] public void EvaluateNoMatch() { this.EvaluateWithError("{X,Y,X} = {{abc,12},42,true}.", "no match of right hand side value {{abc,12},42,true}"); this.EvaluateWithError("X.", "variable 'X' is unboud"); this.EvaluateWithError("Y.", "variable 'Y' is unboud"); } [TestMethod] public void EvaluateMatch() { this.EvaluateTo("{X,Y,Z} = {{abc,12},42,true}.", "{{abc,12},42,true}"); this.EvaluateTo("X.", "{abc,12}"); this.EvaluateTo("Y.", "42"); this.EvaluateTo("Z.", "true"); } [TestMethod] public void EvaluateEmptyList() { this.EvaluateTo("[].", "[]"); } [TestMethod] public void EvaluateSimpleForm() { var result = this.EvaluateForm("add(X,Y) -> X+Y."); Assert.IsNotNull(result); Assert.IsInstanceOfType(result, typeof(Function)); Assert.AreSame(result, this.context.GetValue("add/2")); } [TestMethod] public void EvaluateAndCallSimpleForm() { this.EvaluateAndCallForm("add(X,Y) -> X+Y.", new object[] { 1, 2 }, 3); } [TestMethod] public void EvaluateAndCallForMultiForm() { var twice = this.EvaluateExpression("fun(X) -> X*2 end."); this.EvaluateAndCallForm("for(Max,Max,F) -> [F(Max)]; for(I,Max,F) -> [F(I)|for(I+1,Max,F)].", new object[] { 1, 3, twice }, List.MakeList(new object[] { 2, 4, 6 })); } [TestMethod] public void EvaluateAndCallSimpleFun() { this.EvaluateExpression("Add = fun(X,Y) -> X+Y end."); var result = this.EvaluateExpression("Add(1,2)."); Assert.IsNotNull(result); Assert.AreEqual(3, result); } [TestMethod] public void EvaluateAndCallTimes() { this.EvaluateExpression("Mult = fun(Times) -> (fun(X) -> X * Times end) end."); this.EvaluateExpression("Triple = Mult(3)."); var result = this.EvaluateExpression("Triple(4)."); Assert.IsNotNull(result); Assert.AreEqual(12, result); } [TestMethod] public void EvaluateAndCallMultiFun() { this.EvaluateExpression("TempConvert = fun({c,C}) -> {f, 32 + C*9/5}; ({f,F}) -> {c, (F-32)*5/9} end."); var result = this.EvaluateExpression("TempConvert({c, 100})."); Assert.IsNotNull(result); Assert.AreEqual("{f,212}", result.ToString()); result = this.EvaluateExpression("TempConvert({f, 212})."); Assert.IsNotNull(result); Assert.AreEqual("{c,100}", result.ToString()); } [TestMethod] public void EvaluateStrictEqual() { Assert.AreEqual(true, this.EvaluateExpression("1 =:= 1.")); Assert.AreEqual(true, this.EvaluateExpression("\"foo\" =:= \"foo\".")); Assert.AreEqual(false, this.EvaluateExpression("1 =:= 2.")); Assert.AreEqual(false, this.EvaluateExpression("\"foo\" =:= \"bar\".")); Assert.AreEqual(false, this.EvaluateExpression("1 =:= 1.0.")); } [TestMethod] public void EvaluateEqual() { Assert.AreEqual(true, this.EvaluateExpression("1 == 1.")); Assert.AreEqual(true, this.EvaluateExpression("\"foo\" == \"foo\".")); Assert.AreEqual(false, this.EvaluateExpression("1 == 2.")); Assert.AreEqual(false, this.EvaluateExpression("\"foo\" == \"bar\".")); Assert.AreEqual(true, this.EvaluateExpression("1 == 1.0.")); } [TestMethod] public void EvaluateRem() { Assert.AreEqual(0, this.EvaluateExpression("4 rem 2.")); Assert.AreEqual(1, this.EvaluateExpression("5 rem 2.")); } [TestMethod] public void EvaluateBooleans() { Assert.AreEqual(false, this.EvaluateExpression("false.")); Assert.AreEqual(true, this.EvaluateExpression("true.")); } [TestMethod] public void EvaluateListsMap() { this.EvaluateTo("lists:map(fun(X) -> X*2 end, [1,2,3]).", "[2,4,6]"); this.EvaluateTo("lists:map(fun(X) -> (X rem 2) =:= 0 end, [1,2,3]).", "[false,true,false]"); } [TestMethod] public void EvaluateListsFilter() { this.EvaluateTo("lists:filter(fun(X) -> (X rem 2) =:= 0 end, [1,2,3,4,5]).", "[2,4]"); } [TestMethod] public void EvaluateListsSum() { this.EvaluateTo("lists:sum([1,2,3,4]).", "10"); this.EvaluateTo("lists:sum([1.2,3.4]).", "4.6"); this.EvaluateTo("lists:sum([]).", "0"); } [TestMethod] public void EvaluateListsAll() { this.EvaluateTo("lists:all(fun (X) -> (X rem 2) =:= 0 end, [1,2,3,4]).", "false"); this.EvaluateTo("lists:all(fun (X) -> (X rem 2) =:= 0 end, [2,4]).", "true"); this.EvaluateTo("lists:all(fun (X) -> (X rem 2) =:= 0 end, []).", "true"); } [TestMethod] public void EvaluateListsAny() { this.EvaluateTo("lists:any(fun (X) -> (X rem 2) =:= 0 end, [1,2,3,4]).", "true"); this.EvaluateTo("lists:any(fun (X) -> (X rem 2) =:= 0 end, [1,3]).", "false"); this.EvaluateTo("lists:any(fun (X) -> (X rem 2) =:= 0 end, []).", "false"); } [TestMethod] public void EvaluateListConstruct() { this.EvaluateTo("[1|[2,3]].", "[1,2,3]"); this.EvaluateExpression("X=1."); this.EvaluateExpression("Y=[2,3,4]."); this.EvaluateTo("[X|Y].", "[1,2,3,4]"); } [TestMethod] public void EvaluateIoWrite() { StringWriter writer = new StringWriter(); this.machine.TextWriter = writer; this.EvaluateTo("io:write(\"foo\").", "ok"); Assert.AreEqual("foo", writer.ToString()); } [TestMethod] public void EvaluateIoNl() { StringWriter writer = new StringWriter(); this.machine.TextWriter = writer; this.EvaluateTo("io:nl().", "ok"); Assert.AreEqual("\r\n", writer.ToString()); } [TestMethod] public void EvaluateProcessConversation() { Process process = new Process(); Process.Current = process; this.EvaluateExpression("Pid = spawn(fun() -> receive { Sender, ping } -> Sender ! { self(), pong } end end)."); this.EvaluateExpression("Pid ! { self(), ping }."); var result = this.EvaluateExpression("receive X -> X end."); Assert.IsNotNull(result); Assert.IsInstanceOfType(result, typeof(Tuple)); var tuple = (Tuple)result; Assert.AreEqual(2, tuple.Arity); Assert.AreSame(this.context.GetValue("Pid"), tuple.ElementAt(0)); Assert.IsInstanceOfType(tuple.ElementAt(1), typeof(Atom)); Assert.AreEqual(((Atom)tuple.ElementAt(1)).Name, "pong"); } private void EvaluateWithError(string text, string message) { try { this.EvaluateExpression(text); } catch (System.Exception ex) { Assert.AreEqual(message, ex.Message); } } private void EvaluateTo(string text, string value) { var result = this.EvaluateExpression(text); Assert.IsNotNull(result); Assert.AreEqual(value, Machine.ToString(result)); } private void EvaluateAndCallForm(string text, IList<object> arguments, object expected) { var result = this.EvaluateForm(text); Assert.IsNotNull(result); Assert.IsInstanceOfType(result, typeof(IFunction)); var func = (IFunction)result; Assert.AreEqual(expected, func.Apply(null, arguments)); } private object EvaluateExpression(string text) { Parser parser = new Parser(text); IExpression expression = parser.ParseExpression(); return expression.Evaluate(this.context); } private object EvaluateForm(string text) { Parser parser = new Parser(text); IForm form = parser.ParseForm(); return form.Evaluate(this.context); } } }
{ "content_hash": "1f7a528cb8b3bf6146b8332a64a0c845", "timestamp": "", "source": "github", "line_count": 357, "max_line_length": 178, "avg_line_length": 35.523809523809526, "alnum_prop": 0.5228670556694528, "repo_name": "ajlopez/AjErl", "id": "ebbb0e7c122d7c14f0c32d307132143663186993", "size": "12684", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Src/AjErl.Tests/EvaluateTests.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "295135" }, { "name": "Erlang", "bytes": "629" } ], "symlink_target": "" }
package com.cognifide.aet.sanity.functional.suites; import com.cognifide.aet.sanity.functional.cucumber.Filtering; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({Filtering.class}) public class CucumberSuite { }
{ "content_hash": "ecfb383ed7e652425e30310e113375cc", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 62, "avg_line_length": 23, "alnum_prop": 0.8079710144927537, "repo_name": "Cognifide/AET", "id": "acd441e87563b38529d125a244a120413e2e966c", "size": "881", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "integration-tests/sanity-functional/src/test/java/com/cognifide/aet/sanity/functional/suites/CucumberSuite.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "FreeMarker", "bytes": "82199" }, { "name": "HTML", "bytes": "5669" }, { "name": "Java", "bytes": "1499671" }, { "name": "JavaScript", "bytes": "924783" }, { "name": "Shell", "bytes": "5472" } ], "symlink_target": "" }
name: Bug report about: Help us stomp out bugs! title: '' labels: bug assignees: '' --- <!-- If you run into SDK issues, please go [here](https://community.hologram.io/c/hardware/sdk) for help and support: --> ### Describe the problem ### Expected behavior <!-- Please describe what you think the program should be doing here. --> ### Actual behavior <!-- Please provide any useful debug logs/output here. This will help us diagnose problems that you might have. Full stack traces can be extremely helpful here. --> ### Steps to reproduce the behavior <!--Please provide the exact command(s) to reproduce the error. If it's non-deterministic, try your best to describe your observations that might help us troubleshoot the error. --> ### System information - **OS Platform and Distribution (e.g., Linux Ubuntu 16.04)**: - **Python SDK installed via PyPI or GitHub**: - **SDK version (use command below)**: - **Python version**: - **Hardware (modem) model**: <!-- We will be adding an environment capture script soon for your convenience. You can obtain the Python SDK version with: `hologram version` -->
{ "content_hash": "f360e2894f4b46f3f321f8c5abb1dbf0", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 117, "avg_line_length": 29.36842105263158, "alnum_prop": 0.717741935483871, "repo_name": "hologram-io/hologram-python", "id": "bec632afc66477b5616970d3ac38412f4193a7e1", "size": "1120", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": ".github/ISSUE_TEMPLATE/bug_report.md", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "136" }, { "name": "Python", "bytes": "223458" }, { "name": "Shell", "bytes": "8209" } ], "symlink_target": "" }
This repository contains the code for the workshop. Totally written in HTML, CSS and JavaScript. In this workshop, you are going to rewrite the app [Sarahah](https://sarahah.com) both the front-end and the back-end. The code in part 1 is for the front-end. You will use HTML, CSS, JavaScript, jQuery and Bootstrap to design the UI for 6 pages: - Home - Login - Register - Manage account - Send message - Message index. Website demo: https://youthcodeproject.github.io/ws1-sahar-frontend/
{ "content_hash": "9682563304cd505d259f51cb2f98295c", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 159, "avg_line_length": 37.84615384615385, "alnum_prop": 0.7621951219512195, "repo_name": "YouthCodeProject/ws1-sahar-frontend", "id": "dbeb5e4912b9a4f9e64bc3053a0727ff306c4d63", "size": "580", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1077" }, { "name": "HTML", "bytes": "24799" } ], "symlink_target": "" }
package stark.skshare; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import stark.skshare.utlis.ImageUtil; /** * Created by jihongwen on 16/8/4. * 图片压缩 */ public class ImageCompress { public static byte[] getImageData(Bitmap bitmap, int maxLength) { // TODO: 16/9/5 等比缩放 Bitmap scaledBitmap = ImageUtil.getScaledBitmap(bitmap, 720, 960); return getScaledImageBytes(scaledBitmap, maxLength); } public static byte[] getImageData(Context context, File file, int maxLength) { String filePath = file.getAbsolutePath(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(filePath, options); Bitmap bitmap = ImageUtil.getScaledBitmap(context, Uri.fromFile(file), options.outWidth, options.outHeight); return getScaledImageBytes(bitmap, maxLength); } public static byte[] getThumbImageData(Bitmap bitmap, int maxLength, int thumbWidth, int thumbHeight) { Bitmap scaledBitmap = ImageUtil.getScaledBitmap(bitmap, thumbWidth, thumbHeight); return getScaledImageBytes(scaledBitmap, maxLength); } public static byte[] getThumbImageData(Context context, File file, int maxLength, int thumbWidth, int thumbHeight) { Bitmap bitmap = ImageUtil.getScaledBitmap(context, Uri.fromFile(file), thumbWidth, thumbHeight); return getScaledImageBytes(bitmap, maxLength); } /** * 对缩放过的图片进行质量压缩,并检验是否符合要求,如果不符合在进行最后的尺寸压缩 * * @param bitmap * @param maxLength * @return */ private static byte[] getScaledImageBytes(Bitmap bitmap, int maxLength) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); int quality = 80; bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream); while (outputStream.toByteArray().length > maxLength) { if (quality < 20) { break; } outputStream.reset(); bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream); quality -= 5; } if (outputStream.toByteArray().length > maxLength) { return getImageDataByScale(outputStream, maxLength); } return outputStream.toByteArray(); } /** * 缩放压缩 * * @param outStream * @param maxLength * @return */ private static byte[] getImageDataByScale(ByteArrayOutputStream outStream, int maxLength) { Bitmap bitmap = BitmapFactory.decodeByteArray(outStream.toByteArray(), 0, outStream.toByteArray().length); int w = bitmap.getWidth(); int h = bitmap.getHeight(); int scale = Math.max(w, h); int step = 0; while (bitmap.getByteCount() > maxLength) { int rate = scale - (step += 20) / scale; int nw = w * rate; int nh = h * rate; Bitmap.createScaledBitmap(bitmap, nw, nh, true); } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); return outputStream.toByteArray(); } }
{ "content_hash": "853b23cf3be60fdee226ec1ec4abdcb0", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 120, "avg_line_length": 35.473684210526315, "alnum_prop": 0.6632047477744807, "repo_name": "jhwing/SKShare", "id": "da104316cde4eef70147d0b6af8e0611ed0cdd94", "size": "3468", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SKShareLib/src/main/java/stark/skshare/ImageCompress.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "73981" } ], "symlink_target": "" }
package com.mmnaseri.dragonfly.runtime.repo.impl.strategies; import com.mmnaseri.dragonfly.data.DataAccess; import com.mmnaseri.dragonfly.entity.EntityHandler; import com.mmnaseri.dragonfly.runtime.repo.QueryAlias; import java.lang.reflect.Method; import java.util.List; /** * @author Milad Naseri (mmnaseri@programmer.net) * @since 1.0 (14/9/3 AD, 14:39) */ public class QueryAliasMethodInterceptionStrategy extends AbstractQueryingMethodInterceptionStrategy { public QueryAliasMethodInterceptionStrategy(Class entityType, DataAccess dataAccess, EntityHandler entityHandler) { super(entityType, dataAccess, entityHandler); } @Override public boolean accepts(Method method) { return method.isAnnotationPresent(QueryAlias.class) && (method.getReturnType().equals(void.class) || method.getReturnType().isAssignableFrom(getEntityType()) || List.class.isAssignableFrom(method.getReturnType())); } @Override protected String getQueryName(Method method) { return method.getAnnotation(QueryAlias.class).value(); } }
{ "content_hash": "0aac72adc76e46741538562cca3295fb", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 222, "avg_line_length": 33.65625, "alnum_prop": 0.766016713091922, "repo_name": "agileapes/dragonfly", "id": "408e2de0f9371eec4669a87b6d2d17497362a057", "size": "2219", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dragonfly-runtime/src/main/java/com/mmnaseri/dragonfly/runtime/repo/impl/strategies/QueryAliasMethodInterceptionStrategy.java", "mode": "33188", "license": "mit", "language": [ { "name": "FreeMarker", "bytes": "12834" }, { "name": "GAP", "bytes": "1894" }, { "name": "Java", "bytes": "1808990" }, { "name": "PLSQL", "bytes": "185" }, { "name": "SQLPL", "bytes": "499" } ], "symlink_target": "" }
"""This module contains regression tests for flows-related API handlers.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from absl import app from grr_response_core.lib import registry from grr_response_core.lib import utils from grr_response_core.lib.rdfvalues import client as rdf_client from grr_response_core.lib.rdfvalues import paths as rdf_paths from grr_response_server import data_store from grr_response_server import flow from grr_response_server import flow_base from grr_response_server.flows.general import discovery from grr_response_server.flows.general import file_finder from grr_response_server.flows.general import processes from grr_response_server.flows.general import transfer from grr_response_server.gui import api_regression_test_lib from grr_response_server.gui.api_plugins import flow as flow_plugin from grr_response_server.output_plugins import email_plugin from grr_response_server.rdfvalues import flow_objects as rdf_flow_objects from grr_response_server.rdfvalues import flow_runner as rdf_flow_runner from grr_response_server.rdfvalues import output_plugin as rdf_output_plugin from grr.test_lib import acl_test_lib from grr.test_lib import action_mocks from grr.test_lib import flow_test_lib from grr.test_lib import hunt_test_lib from grr.test_lib import test_lib class ApiGetFlowHandlerRegressionTest(api_regression_test_lib.ApiRegressionTest ): """Regression test for ApiGetFlowHandler.""" api_method = "GetFlow" handler = flow_plugin.ApiGetFlowHandler def Run(self): # Fix the time to avoid regressions. with test_lib.FakeTime(42): client_id = self.SetupClient(0) flow_id = flow_test_lib.StartFlow( discovery.Interrogate, client_id=client_id, creator=self.token.username) replace = api_regression_test_lib.GetFlowTestReplaceDict( client_id, flow_id, "F:ABCDEF12") self.Check( "GetFlow", args=flow_plugin.ApiGetFlowArgs(client_id=client_id, flow_id=flow_id), replace=replace) flow_base.TerminateFlow(client_id, flow_id, "Pending termination: Some reason") replace = api_regression_test_lib.GetFlowTestReplaceDict( client_id, flow_id, "F:ABCDEF13") # Fetch the same flow which is now should be marked as pending # termination. self.Check( "GetFlow", args=flow_plugin.ApiGetFlowArgs(client_id=client_id, flow_id=flow_id), replace=replace) class ApiListFlowsHandlerRegressionTest( api_regression_test_lib.ApiRegressionTest): """Test client flows list handler.""" api_method = "ListFlows" handler = flow_plugin.ApiListFlowsHandler def Run(self): acl_test_lib.CreateUser(self.token.username) with test_lib.FakeTime(42): client_id = self.SetupClient(0) with test_lib.FakeTime(43): flow_id_1 = flow_test_lib.StartFlow( discovery.Interrogate, client_id, creator=self.token.username) with test_lib.FakeTime(44): flow_id_2 = flow_test_lib.StartFlow( processes.ListProcesses, client_id, creator=self.token.username) replace = api_regression_test_lib.GetFlowTestReplaceDict( client_id, flow_id_1, "F:ABCDEF10") replace.update( api_regression_test_lib.GetFlowTestReplaceDict(client_id, flow_id_2, "F:ABCDEF11")) self.Check( "ListFlows", args=flow_plugin.ApiListFlowsArgs(client_id=client_id), replace=replace) class ApiListFlowRequestsHandlerRegressionTest( api_regression_test_lib.ApiRegressionTest): """Regression test for ApiListFlowRequestsHandler.""" api_method = "ListFlowRequests" handler = flow_plugin.ApiListFlowRequestsHandler def Run(self): client_id = self.SetupClient(0) with test_lib.FakeTime(42): flow_id = flow_test_lib.StartFlow( processes.ListProcesses, client_id, creator=self.token.username) test_process = rdf_client.Process(name="test_process") mock = flow_test_lib.MockClient( client_id, action_mocks.ListProcessesMock([test_process]), token=self.token) mock.Next() replace = api_regression_test_lib.GetFlowTestReplaceDict(client_id, flow_id) self.Check( "ListFlowRequests", args=flow_plugin.ApiListFlowRequestsArgs( client_id=client_id, flow_id=flow_id), replace=replace) class ApiListFlowResultsHandlerRegressionTest( api_regression_test_lib.ApiRegressionTest): """Regression test for ApiListFlowResultsHandler.""" api_method = "ListFlowResults" handler = flow_plugin.ApiListFlowResultsHandler def _RunFlow(self, client_id): flow_args = transfer.GetFileArgs( pathspec=rdf_paths.PathSpec( path="/tmp/evil.txt", pathtype=rdf_paths.PathSpec.PathType.OS)) client_mock = hunt_test_lib.SampleHuntMock(failrate=2) with test_lib.FakeTime(42): return flow_test_lib.StartAndRunFlow( transfer.GetFile, client_id=client_id, client_mock=client_mock, flow_args=flow_args) def Run(self): acl_test_lib.CreateUser(self.token.username) client_id = self.SetupClient(0) flow_id = self._RunFlow(client_id) self.Check( "ListFlowResults", args=flow_plugin.ApiListFlowResultsArgs( client_id=client_id, flow_id=flow_id, filter="evil"), replace={flow_id: "W:ABCDEF"}) self.Check( "ListFlowResults", args=flow_plugin.ApiListFlowResultsArgs( client_id=client_id, flow_id=flow_id, filter="benign"), replace={flow_id: "W:ABCDEF"}) class ApiListFlowLogsHandlerRegressionTest( api_regression_test_lib.ApiRegressionTest): """Regression test for ApiListFlowResultsHandler.""" api_method = "ListFlowLogs" handler = flow_plugin.ApiListFlowLogsHandler def _AddLogToFlow(self, client_id, flow_id, log_string): entry = rdf_flow_objects.FlowLogEntry( client_id=client_id, flow_id=flow_id, message=log_string) data_store.REL_DB.WriteFlowLogEntries([entry]) def Run(self): client_id = self.SetupClient(0) flow_id = flow_test_lib.StartFlow( processes.ListProcesses, client_id, creator=self.token.username) with test_lib.FakeTime(52): self._AddLogToFlow(client_id, flow_id, "Sample message: foo.") with test_lib.FakeTime(55): self._AddLogToFlow(client_id, flow_id, "Sample message: bar.") replace = {flow_id: "W:ABCDEF"} self.Check( "ListFlowLogs", args=flow_plugin.ApiListFlowLogsArgs( client_id=client_id, flow_id=flow_id), replace=replace) self.Check( "ListFlowLogs", args=flow_plugin.ApiListFlowLogsArgs( client_id=client_id, flow_id=flow_id, count=1), replace=replace) self.Check( "ListFlowLogs", args=flow_plugin.ApiListFlowLogsArgs( client_id=client_id, flow_id=flow_id, count=1, offset=1), replace=replace) class ApiGetFlowResultsExportCommandHandlerRegressionTest( api_regression_test_lib.ApiRegressionTest): """Regression test for ApiGetFlowResultsExportCommandHandler.""" api_method = "GetFlowResultsExportCommand" handler = flow_plugin.ApiGetFlowResultsExportCommandHandler def Run(self): client_id = self.SetupClient(0) flow_urn = "F:ABCDEF" self.Check( "GetFlowResultsExportCommand", args=flow_plugin.ApiGetFlowResultsExportCommandArgs( client_id=client_id, flow_id=flow_urn)) class ApiListFlowOutputPluginsHandlerRegressionTest( api_regression_test_lib.ApiRegressionTest): """Regression test for ApiListFlowOutputPluginsHandler.""" api_method = "ListFlowOutputPlugins" handler = flow_plugin.ApiListFlowOutputPluginsHandler # ApiOutputPlugin's state is an AttributedDict containing URNs that # are always random. Given that currently their JSON representation # is proto-serialized and then base64-encoded, there's no way # we can replace these URNs with something stable. uses_legacy_dynamic_protos = True def Run(self): client_id = self.SetupClient(0) email_descriptor = rdf_output_plugin.OutputPluginDescriptor( plugin_name=email_plugin.EmailOutputPlugin.__name__, plugin_args=email_plugin.EmailOutputPluginArgs( email_address="test@localhost", emails_limit=42)) with test_lib.FakeTime(42): flow_id = flow.StartFlow( flow_cls=processes.ListProcesses, client_id=client_id, output_plugins=[email_descriptor]) self.Check( "ListFlowOutputPlugins", args=flow_plugin.ApiListFlowOutputPluginsArgs( client_id=client_id, flow_id=flow_id), replace={flow_id: "W:ABCDEF"}) class ApiListFlowOutputPluginLogsHandlerRegressionTest( api_regression_test_lib.ApiRegressionTest): """Regression test for ApiListFlowOutputPluginLogsHandler.""" api_method = "ListFlowOutputPluginLogs" handler = flow_plugin.ApiListFlowOutputPluginLogsHandler # ApiOutputPlugin's state is an AttributedDict containing URNs that # are always random. Given that currently their JSON representation # is proto-serialized and then base64-encoded, there's no way # we can replace these URNs with something stable. uses_legacy_dynamic_protos = True def Run(self): client_id = self.SetupClient(0) email_descriptor = rdf_output_plugin.OutputPluginDescriptor( plugin_name=email_plugin.EmailOutputPlugin.__name__, plugin_args=email_plugin.EmailOutputPluginArgs( email_address="test@localhost", emails_limit=42)) with test_lib.FakeTime(42): flow_id = flow_test_lib.StartAndRunFlow( flow_cls=flow_test_lib.DummyFlowWithSingleReply, client_id=client_id, output_plugins=[email_descriptor]) self.Check( "ListFlowOutputPluginLogs", args=flow_plugin.ApiListFlowOutputPluginLogsArgs( client_id=client_id, flow_id=flow_id, plugin_id="EmailOutputPlugin_0"), replace={flow_id: "W:ABCDEF"}) class ApiListFlowOutputPluginErrorsHandlerRegressionTest( api_regression_test_lib.ApiRegressionTest): """Regression test for ApiListFlowOutputPluginErrorsHandler.""" api_method = "ListFlowOutputPluginErrors" handler = flow_plugin.ApiListFlowOutputPluginErrorsHandler # ApiOutputPlugin's state is an AttributedDict containing URNs that # are always random. Given that currently their JSON representation # is proto-serialized and then base64-encoded, there's no way # we can replace these URNs with something stable. uses_legacy_dynamic_protos = True def Run(self): client_id = self.SetupClient(0) failing_descriptor = rdf_output_plugin.OutputPluginDescriptor( plugin_name=hunt_test_lib.FailingDummyHuntOutputPlugin.__name__) with test_lib.FakeTime(42): flow_id = flow_test_lib.StartAndRunFlow( flow_cls=flow_test_lib.DummyFlowWithSingleReply, client_id=client_id, output_plugins=[failing_descriptor]) self.Check( "ListFlowOutputPluginErrors", args=flow_plugin.ApiListFlowOutputPluginErrorsArgs( client_id=client_id, flow_id=flow_id, plugin_id="FailingDummyHuntOutputPlugin_0"), replace={flow_id: "W:ABCDEF"}) class ApiCreateFlowHandlerRegressionTest( api_regression_test_lib.ApiRegressionTest): """Regression test for ApiCreateFlowHandler.""" api_method = "CreateFlow" handler = flow_plugin.ApiCreateFlowHandler def Run(self): client_id = self.SetupClient(0) def ReplaceFlowId(): flows = data_store.REL_DB.ReadAllFlowObjects(client_id=client_id) self.assertNotEmpty(flows) flow_id = flows[0].flow_id return api_regression_test_lib.GetFlowTestReplaceDict(client_id, flow_id) with test_lib.FakeTime(42): self.Check( "CreateFlow", args=flow_plugin.ApiCreateFlowArgs( client_id=client_id, flow=flow_plugin.ApiFlow( name=processes.ListProcesses.__name__, args=processes.ListProcessesArgs( filename_regex=".", fetch_binaries=True), runner_args=rdf_flow_runner.FlowRunnerArgs( output_plugins=[], notify_to_user=True))), replace=ReplaceFlowId) class ApiCancelFlowHandlerRegressionTest( api_regression_test_lib.ApiRegressionTest): """Regression test for ApiCancelFlowHandler.""" api_method = "CancelFlow" handler = flow_plugin.ApiCancelFlowHandler def Run(self): client_id = self.SetupClient(0) flow_id = flow.StartFlow( flow_cls=processes.ListProcesses, client_id=client_id) self.Check( "CancelFlow", args=flow_plugin.ApiCancelFlowArgs( client_id=client_id, flow_id=flow_id), replace={flow_id: "W:ABCDEF"}) class ApiListFlowDescriptorsHandlerRegressionTest( api_regression_test_lib.ApiRegressionTest, acl_test_lib.AclTestMixin): """Regression test for ApiListFlowDescriptorsHandler.""" api_method = "ListFlowDescriptors" handler = flow_plugin.ApiListFlowDescriptorsHandler def Run(self): test_registry = { processes.ListProcesses.__name__: processes.ListProcesses, file_finder.FileFinder.__name__: file_finder.FileFinder, } with utils.Stubber(registry.FlowRegistry, "FLOW_REGISTRY", test_registry): self.CreateAdminUser(u"test") self.Check("ListFlowDescriptors") def main(argv): api_regression_test_lib.main(argv) if __name__ == "__main__": app.run(main)
{ "content_hash": "c30818c4498bc08329f2e0050f38f4a0", "timestamp": "", "source": "github", "line_count": 400, "max_line_length": 80, "avg_line_length": 34.51, "alnum_prop": 0.6952332657200812, "repo_name": "dunkhong/grr", "id": "dbe5ad2a358198d33e2abbe08d766562b167cdb3", "size": "13826", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "grr/server/grr_response_server/gui/api_plugins/flow_regression_test.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "227" }, { "name": "Batchfile", "bytes": "882" }, { "name": "C", "bytes": "11321" }, { "name": "C++", "bytes": "54535" }, { "name": "CSS", "bytes": "36745" }, { "name": "Dockerfile", "bytes": "1822" }, { "name": "HCL", "bytes": "8451" }, { "name": "HTML", "bytes": "193751" }, { "name": "JavaScript", "bytes": "12795" }, { "name": "Jupyter Notebook", "bytes": "199190" }, { "name": "Makefile", "bytes": "3139" }, { "name": "PowerShell", "bytes": "1984" }, { "name": "Python", "bytes": "7430923" }, { "name": "Roff", "bytes": "444" }, { "name": "Shell", "bytes": "49155" }, { "name": "Standard ML", "bytes": "8172" }, { "name": "TSQL", "bytes": "10560" }, { "name": "TypeScript", "bytes": "56756" } ], "symlink_target": "" }
package com.google.template.soy.types; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableSet; import com.google.template.soy.soytree.SoyTypeP; /** Base type for all imported symbol types. */ public abstract class ImportType extends SoyType { @Override public <T> T accept(SoyTypeVisitor<T> visitor) { return visitor.visit(this); } @Override void doToProto(SoyTypeP.Builder builder) { throw new UnsupportedOperationException(); } @Override boolean doIsAssignableFromNonUnionType(SoyType srcType) { // Nothing is assignable to this placeholder type. return false; } /** Returns the full list of any valid nested symbols, of any type, within this type. */ public ImmutableCollection<String> getNestedSymbolNames() { return ImmutableSet.of(); } }
{ "content_hash": "e842fd7cd6f54fc82f087102c880937b", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 90, "avg_line_length": 27.096774193548388, "alnum_prop": 0.7464285714285714, "repo_name": "google/closure-templates", "id": "699a13de6a7d6b530c5f7ccb6aaadf72aa480040", "size": "1434", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "java/src/com/google/template/soy/types/ImportType.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Closure Templates", "bytes": "3332" }, { "name": "HTML", "bytes": "21890" }, { "name": "Java", "bytes": "8407238" }, { "name": "JavaScript", "bytes": "248481" }, { "name": "Python", "bytes": "92193" }, { "name": "Starlark", "bytes": "239786" }, { "name": "TypeScript", "bytes": "52777" } ], "symlink_target": "" }
Coral::Application.config.session_store :active_record_store
{ "content_hash": "b10132cf5232b1aae5b56c92100ae576", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 60, "avg_line_length": 61, "alnum_prop": 0.8360655737704918, "repo_name": "cthree/coral", "id": "b04ed9eb58fd110e8086226027f2d73a371e5424", "size": "407", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/initializers/session_store.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1988" }, { "name": "CoffeeScript", "bytes": "687" }, { "name": "JavaScript", "bytes": "463" }, { "name": "Ruby", "bytes": "25110" } ], "symlink_target": "" }
/* * Description: * lock abstraction * * Revision history: * Mar., 2015, @imzhenyu (Zhenyu Guo), first version * xxxx-xx-xx, author, fix bug about xxx */ #pragma once # include <dsn/internal/extensible_object.h> namespace dsn { namespace service { class zlock; class zrwlock_nr; class zsemaphore; }} namespace dsn { class ilock { public: virtual ~ilock() {} virtual void lock() = 0; virtual bool try_lock() = 0; virtual void unlock() = 0; }; class lock_provider : public ilock, public extensible_object<lock_provider, 4> { public: template <typename T> static lock_provider* create(lock_provider* inner_provider) { return new T(inner_provider); } typedef lock_provider* (*factory)(lock_provider*); public: lock_provider(lock_provider* inner_provider) { _inner_provider = inner_provider; } virtual ~lock_provider() { if (nullptr != _inner_provider) delete _inner_provider; } lock_provider* get_inner_provider() const { return _inner_provider; } private: lock_provider *_inner_provider; }; class lock_nr_provider : public ilock, public extensible_object<lock_nr_provider, 4> { public: template <typename T> static lock_nr_provider* create(lock_nr_provider* inner_provider) { return new T(inner_provider); } typedef lock_nr_provider* (*factory)(lock_nr_provider*); public: lock_nr_provider(lock_nr_provider* inner_provider) { _inner_provider = inner_provider; } virtual ~lock_nr_provider() { if (nullptr != _inner_provider) delete _inner_provider; } lock_nr_provider* get_inner_provider() const { return _inner_provider; } private: lock_nr_provider *_inner_provider; }; class rwlock_nr_provider : public extensible_object<rwlock_nr_provider, 4> { public: template <typename T> static rwlock_nr_provider* create(rwlock_nr_provider* inner_provider) { return new T(inner_provider); } typedef rwlock_nr_provider* (*factory)(rwlock_nr_provider*); public: rwlock_nr_provider(rwlock_nr_provider* inner_provider) { _inner_provider = inner_provider; } virtual ~rwlock_nr_provider() { if (nullptr != _inner_provider) delete _inner_provider; } virtual void lock_read() = 0; virtual void unlock_read() = 0; virtual bool try_lock_read() = 0; virtual void lock_write() = 0; virtual void unlock_write() = 0; virtual bool try_lock_write() = 0; rwlock_nr_provider* get_inner_provider() const { return _inner_provider; } private: rwlock_nr_provider *_inner_provider; }; class semaphore_provider : public extensible_object<semaphore_provider, 4> { public: template <typename T> static semaphore_provider* create(int initCount, semaphore_provider* inner_provider) { return new T(initCount, inner_provider); } typedef semaphore_provider* (*factory)(int, semaphore_provider*); public: semaphore_provider(int initial_count, semaphore_provider* inner_provider) { _inner_provider = inner_provider; } virtual ~semaphore_provider() { if (nullptr != _inner_provider) delete _inner_provider; } public: virtual void signal(int count) = 0; virtual bool wait(int timeout_milliseconds = TIME_MS_MAX) = 0; semaphore_provider* get_inner_provider() const { return _inner_provider; } private: semaphore_provider *_inner_provider; }; } // end namespace
{ "content_hash": "aa06c06658cb17a7eb93e34a3900299f", "timestamp": "", "source": "github", "line_count": 122, "max_line_length": 115, "avg_line_length": 27.65573770491803, "alnum_prop": 0.6840545346769413, "repo_name": "mcfatealan/rDSN", "id": "acc7beb1265a5b1f53b7a268c759aade51f66eb1", "size": "4584", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "include/dsn/internal/zlock_provider.h", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "25290" }, { "name": "C", "bytes": "23337" }, { "name": "C++", "bytes": "2963723" }, { "name": "CMake", "bytes": "52713" }, { "name": "Objective-C", "bytes": "3073" }, { "name": "PHP", "bytes": "90028" }, { "name": "Protocol Buffer", "bytes": "331" }, { "name": "Shell", "bytes": "52656" }, { "name": "Thrift", "bytes": "13492" } ], "symlink_target": "" }
<?php namespace Opl\Autoloader\Exception; use RuntimeException; /** * The exception allows to report class-to-filename translation problems. * It is used in the toolset. The autoloaders are not allowed to throw * sophisticated exceptions, as they are not a part of the application, but * the runtime environment. * * @author Tomasz Jędrzejewski * @copyright Invenzzia Group <http://www.invenzzia.org/> and contributors. * @license http://www.invenzzia.org/license/new-bsd New BSD License */ class TranslationException extends RuntimeException { } // end TranslationException;
{ "content_hash": "8c54e1f5b7bfb6adcbc51cf987ffa2c4", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 75, "avg_line_length": 31, "alnum_prop": 0.765704584040747, "repo_name": "OPL/opl3-autoloader", "id": "3f719b010b4a11453cb106faa46df930bf0d9cec", "size": "958", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Opl/Autoloader/Exception/TranslationException.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PHP", "bytes": "149231" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <CIM CIMVERSION="2.0" DTDVERSION="2.0"> <MESSAGE ID="52004" PROTOCOLVERSION="1.0"> <SIMPLEREQ> <IMETHODCALL NAME="GetInstance"> <LOCALNAMESPACEPATH> <NAMESPACE NAME="test"/> <NAMESPACE NAME="static"/> </LOCALNAMESPACEPATH> <IPARAMVALUE NAME="InstanceName"> <INSTANCENAME CLASSNAME="PG_TestPropertyTypes"> <KEYBINDING NAME="CreationClassName"> <KEYVALUE VALUETYPE="string"> &1;PG_TestPropertyTypes </KEYVALUE> </KEYBINDING> <KEYBINDING NAME="InstanceId"> <KEYVALUE VALUETYPE="numeric"> 1 </KEYVALUE> </KEYBINDING> </INSTANCENAME> </IPARAMVALUE> </IMETHODCALL> </SIMPLEREQ> </MESSAGE> </CIM>
{ "content_hash": "397c3c9e101eb3f664a0c682065066d1", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 57, "avg_line_length": 31.88888888888889, "alnum_prop": 0.5435540069686411, "repo_name": "ncultra/Pegasus-2.5", "id": "144fe4a71302b54a2cce25774a6fdc02ef7318f3", "size": "861", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/wetest/static/ErrorXml/BadEntityReference03.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Awk", "bytes": "8389" }, { "name": "C", "bytes": "2094310" }, { "name": "C++", "bytes": "16778278" }, { "name": "Erlang", "bytes": "59698" }, { "name": "Java", "bytes": "477479" }, { "name": "Objective-C", "bytes": "165760" }, { "name": "Perl", "bytes": "16616" }, { "name": "Scala", "bytes": "255" }, { "name": "Shell", "bytes": "61767" } ], "symlink_target": "" }
/** * @fileoverview Externs for Angular 1. * * TODO: Mocks. * TODO: Remaining Services: * $cookies * $cookieStore * $document * $httpBackend * $interpolate * $locale * $resource * $rootElement * $rootScope * $rootScopeProvider * * TODO: Resolve two issues with angular.$http * 1) angular.$http isn't declared as a * callable type. It should be declared as a function, and properties * added following the technique used by $timeout, $parse and * $interval. * 2) angular.$http.delete cannot be added as an extern * as it is a reserved keyword. * Its use is potentially not supported in IE. * It may be aliased as 'remove' in a future version. * * @see http://angularjs.org/ * @externs */ /** * @typedef {(Window|Document|Element|Array.<Element>|string|!angular.JQLite| * NodeList|{length: number})} */ var JQLiteSelector; /** * @type {Object} * @const */ var angular = {}; /** * @param {T} self Specifies the object which this should point to when the * function is run. * @param {?function(this:T, ...)} fn A function to partially apply. * @return {!Function} A partially-applied form of the function bind() was * invoked as a method of. * @param {...*} args Additional arguments that are partially applied to the * function. * @template T */ angular.bind = function(self, fn, args) {}; /** @typedef {{strictDi: (boolean|undefined)}} */ angular.BootstrapOptions; /** * @param {Element|HTMLDocument} element * @param {Array.<string|Function>=} opt_modules * @param {angular.BootstrapOptions=} opt_config * @return {!angular.$injector} */ angular.bootstrap = function(element, opt_modules, opt_config) {}; /** * @param {T} source * @param {(Object|Array)=} opt_dest * @return {T} * @template T */ angular.copy = function(source, opt_dest) {}; /** * @param {(JQLiteSelector|Object)} element * @param {(JQLiteSelector|Object)=} opt_context * @return {!angular.JQLite} */ angular.element = function(element, opt_context) {}; /** * @param {*} o1 * @param {*} o2 * @return {boolean} */ angular.equals = function(o1, o2) {}; /** * @param {Object} dest * @param {...Object} srcs */ angular.extend = function(dest, srcs) {}; /** * @param {Object|Array} obj * @param {Function} iterator * @param {Object=} opt_context * @return {Object|Array} */ angular.forEach = function(obj, iterator, opt_context) {}; /** * @param {string|T} json * @return {Object|Array|Date|T} * @template T */ angular.fromJson = function(json) {}; /** * @param {*} arg * @return {*} */ angular.identity = function(arg) {}; /** * @param {Array.<string|Function>} modules * @return {!angular.$injector} */ angular.injector = function(modules) {}; /** * @param {*} value * @return {boolean} */ angular.isArray = function(value) {}; /** * @param {*} value * @return {boolean} */ angular.isDate = function(value) {}; /** * @param {*} value * @return {boolean} */ angular.isDefined = function(value) {}; /** * @param {*} value * @return {boolean} */ angular.isElement = function(value) {}; /** * @param {*} value * @return {boolean} */ angular.isFunction = function(value) {}; /** * @param {*} value * @return {boolean} */ angular.isNumber = function(value) {}; /** * @param {*} value * @return {boolean} */ angular.isObject = function(value) {}; /** * @param {*} value * @return {boolean} */ angular.isString = function(value) {}; /** * @param {*} value * @return {boolean} */ angular.isUndefined = function(value) {}; /** * @param {string} s * @return {string} */ angular.lowercase = function(s) {}; angular.mock = {}; /** * @param {string} name * @param {Array.<string>=} opt_requires * @param {angular.Injectable=} opt_configFn * @return {!angular.Module} */ angular.module = function(name, opt_requires, opt_configFn) {}; angular.noop = function() {}; /** * @param {Object|Array|Date|string|number} obj * @param {boolean=} opt_pretty * @return {string} */ angular.toJson = function(obj, opt_pretty) {}; /** * @param {string} s * @return {string} */ angular.uppercase = function(s) {}; /** * @typedef {{ * animate: (function(!angular.JQLite, string, !Object, !Object, !Function, * !Object=):(!Function|undefined)|undefined), * enter: (function(!angular.JQLite, !Function, !Object=): * (!Function|undefined)|undefined), * leave: (function(!angular.JQLite, !Function, !Object=): * (!Function|undefined)|undefined), * move: (function(!angular.JQLite, !Function, !Object=): * (!Function|undefined)|undefined), * beforeAddClass: (function(!angular.JQLite, string, !Function, !Object=): * (!Function|undefined)|undefined), * addClass: (function(!angular.JQLite, string, !Function, !Object=): * (!Function|undefined)|undefined), * beforeRemoveClass: (function(!angular.JQLite, string, !Function, !Object=): * (!Function|undefined)|undefined), * removeClass: (function(!angular.JQLite, string, !Function, !Object=): * (!Function|undefined)|undefined), * beforeSetClass: (function(!angular.JQLite, string, string, !Function, * !Object=):(!Function|undefined)|undefined), * setClass: (function(!angular.JQLite, string, string, !Function, !Object=): * (!Function|undefined)|undefined) * }} */ angular.Animation; /** * @param {!angular.JQLite} element * @param {string} className * @param {!Object} from * @param {!Object} to * @param {!Function} doneFn * @param {!Object=} opt_options */ angular.Animation.animate = function(element, className, from, to, doneFn, opt_options) {}; /** * @param {!angular.JQLite} element * @param {!Function} doneFn * @param {!Object=} opt_options * @return {(!Function|undefined)} */ angular.Animation.enter = function(element, doneFn, opt_options) {}; /** * @param {!angular.JQLite} element * @param {!Function} doneFn * @param {!Object=} opt_options * @return {(!Function|undefined)} */ angular.Animation.leave = function(element, doneFn, opt_options) {}; /** * @param {!angular.JQLite} element * @param {!Function} doneFn * @param {!Object=} opt_options * @return {(!Function|undefined)} */ angular.Animation.move = function(element, doneFn, opt_options) {}; /** * @param {!angular.JQLite} element * @param {string} className * @param {!Function} doneFn * @param {!Object=} opt_options * @return {(!Function|undefined)} */ angular.Animation.beforeAddClass = function(element, className, doneFn, opt_options) {}; /** * @param {!angular.JQLite} element * @param {string} className * @param {!Function} doneFn * @param {!Object=} opt_options * @return {(!Function|undefined)} */ angular.Animation.addClass = function(element, className, doneFn, opt_options) {}; /** * @param {!angular.JQLite} element * @param {string} className * @param {!Function} doneFn * @param {!Object=} opt_options * @return {(!Function|undefined)} */ angular.Animation.beforeRemoveClass = function(element, className, doneFn, opt_options) {}; /** * @param {!angular.JQLite} element * @param {string} className * @param {!Function} doneFn * @param {!Object=} opt_options * @return {(!Function|undefined)} */ angular.Animation.removeClass = function(element, className, doneFn, opt_options) {}; /** * @param {!angular.JQLite} element * @param {string} addedClass * @param {string} removedClass * @param {!Function} doneFn * @param {!Object=} opt_options * @return {(!Function|undefined)} */ angular.Animation.beforeSetClass = function(element, addedClass, removedClass, doneFn, opt_options) {}; /** * @param {!angular.JQLite} element * @param {string} addedClass * @param {string} removedClass * @param {!Function} doneFn * @param {!Object=} opt_options * @return {(!Function|undefined)} */ angular.Animation.setClass = function(element, addedClass, removedClass, doneFn, opt_options) {}; /** * @typedef {{ * $attr: Object.<string,string>, * $normalize: function(string): string, * $observe: function(string, function(*)): function(), * $set: function(string, ?(string|boolean), boolean=, string=) * }} */ angular.Attributes; /** * @type {Object.<string, string>} */ angular.Attributes.$attr; /** * @param {string} classVal */ angular.Attributes.$addClass = function(classVal) {}; /** * @param {string} classVal */ angular.Attributes.$removeClass = function(classVal) {}; /** * @param {string} newClasses * @param {string} oldClasses */ angular.Attributes.$updateClass = function(newClasses, oldClasses) {}; /** * @param {string} name * @return {string} */ angular.Attributes.$normalize = function(name) {}; /** * @param {string} key * @param {function(*)} fn * @return {function()} */ angular.Attributes.$observe = function(key, fn) {}; /** * @param {string} key * @param {?(string|boolean)} value * @param {boolean=} opt_writeAttr * @param {string=} opt_attrName */ angular.Attributes.$set = function(key, value, opt_writeAttr, opt_attrName) {}; /** * @typedef {{ * pre: (function( * !angular.Scope=, * !angular.JQLite=, * !angular.Attributes=, * (!Object|!Array.<!Object>)=)| * undefined), * post: (function( * !angular.Scope=, * !angular.JQLite=, * !angular.Attributes=, * (!Object|Array.<!Object>)=)| * undefined) * }} */ angular.LinkingFunctions; /** * @param {!angular.Scope=} scope * @param {!angular.JQLite=} iElement * @param {!angular.Attributes=} iAttrs * @param {(!Object|!Array.<!Object>)=} controller */ angular.LinkingFunctions.pre = function(scope, iElement, iAttrs, controller) {}; /** * @param {!angular.Scope=} scope * @param {!angular.JQLite=} iElement * @param {!angular.Attributes=} iAttrs * @param {(!Object|!Array.<!Object>)=} controller */ angular.LinkingFunctions.post = function(scope, iElement, iAttrs, controller) { }; /** * @typedef {{ * bindToController: (boolean|undefined), * compile: (function( * !angular.JQLite=, !angular.Attributes=, Function=)|undefined), * controller: (angular.Injectable|string|undefined), * controllerAs: (string|undefined), * link: (function( * !angular.Scope=, !angular.JQLite=, !angular.Attributes=, * (!Object|!Array.<!Object>)=)| * !angular.LinkingFunctions| * undefined), * name: (string|undefined), * priority: (number|undefined), * replace: (boolean|undefined), * require: (string|Array.<string>|undefined), * restrict: (string|undefined), * scope: (boolean|Object.<string, string>|undefined), * template: (string| * function(!angular.JQLite=,!angular.Attributes=): string| * undefined), * templateNamespace: (string|undefined), * templateUrl: (string| * function(!angular.JQLite=,!angular.Attributes=)| * undefined), * terminal: (boolean|undefined), * transclude: (boolean|string|undefined) * }} */ angular.Directive; /** * @param {!angular.JQLite=} tElement * @param {!angular.Attributes=} tAttrs * @param {Function=} transclude * @return {Function|angular.LinkingFunctions|undefined} */ angular.Directive.compile = function(tElement, tAttrs, transclude) {}; angular.Directive.controller = function() {}; /** * @type {string|undefined} */ angular.Directive.controllerAs; /** * @type {( * function(!angular.Scope=, !angular.JQLite=, !angular.Attributes=, * (!Object|!Array.<!Object>)=)| * !angular.LinkingFunctions| * undefined * )} */ angular.Directive.link; /** * @type {(string|undefined)} */ angular.Directive.name; /** * @type {(number|undefined)} */ angular.Directive.priority; /** * @type {(boolean|undefined)} */ angular.Directive.replace; /** * @type {(string|Array.<string>|undefined)} */ angular.Directive.require; /** * @type {(string|undefined)} */ angular.Directive.restrict; /** * @type {(boolean|Object.<string, string>|undefined)} */ angular.Directive.scope; /** * @type {( * string| * function(!angular.JQLite=,!angular.Attributes=): string| * undefined * )} */ angular.Directive.template; /** * @type {(string|function(!angular.JQLite=, !angular.Attributes=)|undefined)} */ angular.Directive.templateUrl; /** * @type {(boolean|undefined)} */ angular.Directive.terminal; /** * @type {(boolean|string|undefined)} */ angular.Directive.transclude; /** * @typedef {(Function|Array.<string|Function>)} */ angular.Injectable; /** * @typedef {{ * addClass: function(string): !angular.JQLite, * after: function(JQLiteSelector): !angular.JQLite, * append: function(JQLiteSelector): !angular.JQLite, * attr: function(string, (string|boolean)=): * (!angular.JQLite|string|boolean), * bind: function(string, Function): !angular.JQLite, * children: function(): !angular.JQLite, * clone: function(): !angular.JQLite, * contents: function(): !angular.JQLite, * controller: function(string=): Object, * css: function((string|!Object), string=): (!angular.JQLite|string), * data: function(string=, *=): *, * detach: function(): !angular.JQLite, * empty: function(): !angular.JQLite, * eq: function(number): !angular.JQLite, * find: function(string): !angular.JQLite, * hasClass: function(string): boolean, * html: function(string=): (!angular.JQLite|string), * inheritedData: function(string=, *=): *, * injector: function(): !angular.$injector, * isolateScope: function(): (!angular.Scope|undefined), * length: number, * next: function(): !angular.JQLite, * on: function(string, Function): !angular.JQLite, * off: function(string=, Function=): !angular.JQLite, * one: function(string, Function): !angular.JQLite, * parent: function(): !angular.JQLite, * prepend: function(JQLiteSelector): !angular.JQLite, * prop: function(string, *=): *, * ready: function(Function): !angular.JQLite, * remove: function(): !angular.JQLite, * removeAttr: function(string): !angular.JQLite, * removeClass: function(string): !angular.JQLite, * removeData: function(string=): !angular.JQLite, * replaceWith: function(JQLiteSelector): !angular.JQLite, * scope: function(): !angular.Scope, * text: function(string=): (!angular.JQLite|string), * toggleClass: function(string, boolean=): !angular.JQLite, * triggerHandler: function(string, *=): !angular.JQLite, * unbind: function(string=, Function=): !angular.JQLite, * val: function(string=): (!angular.JQLite|string), * wrap: function(JQLiteSelector): !angular.JQLite * }} */ angular.JQLite; /** * @param {string} name * @return {!angular.JQLite} */ angular.JQLite.addClass = function(name) {}; /** * @param {JQLiteSelector} element * @return {!angular.JQLite} */ angular.JQLite.after = function(element) {}; /** * @param {JQLiteSelector} element * @return {!angular.JQLite} */ angular.JQLite.append = function(element) {}; /** * @param {string} name * @param {(string|boolean)=} opt_value * @return {!angular.JQLite|string|boolean} */ angular.JQLite.attr = function(name, opt_value) {}; /** * @param {string} type * @param {Function} fn * @return {!angular.JQLite} */ angular.JQLite.bind = function(type, fn) {}; /** * @return {!angular.JQLite} */ angular.JQLite.children = function() {}; /** * @return {!angular.JQLite} */ angular.JQLite.clone = function() {}; /** * @return {!angular.JQLite} */ angular.JQLite.contents = function() {}; /** * @param {string=} opt_name * @return {Object} */ angular.JQLite.controller = function(opt_name) {}; /** * @param {(string|!Object)} nameOrObject * @param {string=} opt_value * @return {!angular.JQLite|string} */ angular.JQLite.css = function(nameOrObject, opt_value) {}; /** * @param {string=} opt_key * @param {*=} opt_value * @return {*} */ angular.JQLite.data = function(opt_key, opt_value) {}; /** * @param {number} index * @return {!angular.JQLite} */ angular.JQLite.eq = function(index) {}; /** * @param {string} selector * @return {!angular.JQLite} */ angular.JQLite.find = function(selector) {}; /** * @param {string} name * @return {boolean} */ angular.JQLite.hasClass = function(name) {}; /** * @param {string=} opt_value * @return {!angular.JQLite|string} */ angular.JQLite.html = function(opt_value) {}; /** * @param {string=} opt_key * @param {*=} opt_value * @return {*} */ angular.JQLite.inheritedData = function(opt_key, opt_value) {}; /** * @return {!angular.$injector} */ angular.JQLite.injector = function() {}; /** @type {number} */ angular.JQLite.length; /** * @return {!angular.JQLite} */ angular.JQLite.next = function() {}; /** * @param {string} type * @param {Function} fn * @return {!angular.JQLite} */ angular.JQLite.on = function(type, fn) {}; /** * @param {string=} opt_type * @param {Function=} opt_fn * @return {!angular.JQLite} */ angular.JQLite.off = function(opt_type, opt_fn) {}; /** * @return {!angular.JQLite} */ angular.JQLite.parent = function() {}; /** * @param {JQLiteSelector} element * @return {!angular.JQLite} */ angular.JQLite.prepend = function(element) {}; /** * @param {string} name * @param {*=} opt_value * @return {*} */ angular.JQLite.prop = function(name, opt_value) {}; /** * @param {Function} fn * @return {!angular.JQLite} */ angular.JQLite.ready = function(fn) {}; /** * @return {!angular.JQLite} */ angular.JQLite.remove = function() {}; /** * @param {string} name * @return {!angular.JQLite} */ angular.JQLite.removeAttr = function(name) {}; /** * @param {string} name * @return {!angular.JQLite} */ angular.JQLite.removeClass = function(name) {}; /** * @param {string=} opt_name * @return {!angular.JQLite} */ angular.JQLite.removeData = function(opt_name) {}; /** * @param {JQLiteSelector} element * @return {!angular.JQLite} */ angular.JQLite.replaceWith = function(element) {}; /** * @return {!angular.Scope} */ angular.JQLite.scope = function() {}; /** * @param {string=} opt_value * @return {!angular.JQLite|string} */ angular.JQLite.text = function(opt_value) {}; /** * @param {string} name * @param {boolean=} opt_condition * @return {!angular.JQLite} */ angular.JQLite.toggleClass = function(name, opt_condition) {}; /** * @param {string} type * @param {*=} opt_value * @return {!angular.JQLite} */ angular.JQLite.triggerHandler = function(type, opt_value) {}; /** * @param {string=} opt_type * @param {Function=} opt_fn * @return {!angular.JQLite} */ angular.JQLite.unbind = function(opt_type, opt_fn) {}; /** * @param {string=} opt_value * @return {!angular.JQLite|string} */ angular.JQLite.val = function(opt_value) {}; /** * @param {JQLiteSelector} element * @return {!angular.JQLite} */ angular.JQLite.wrap = function(element) {}; /** * @typedef {{ * animation: * function(string, angular.Injectable):!angular.Module, * config: function(angular.Injectable):!angular.Module, * constant: function(string, *):angular.Module, * controller: * (function(string, angular.Injectable):!angular.Module| * function(!Object.<angular.Injectable>):!angular.Module), * directive: * (function(string, angular.Injectable):!angular.Module| * function(!Object.<angular.Injectable>):!angular.Module), * factory: * function(string, angular.Injectable):!angular.Module, * filter: * function(string, angular.Injectable):!angular.Module, * name: string, * provider: function(string, * (angular.$provide.Provider|angular.Injectable)): * !angular.Module, * requires: !Array.<string>, * run: function(angular.Injectable):!angular.Module, * service: function(string, angular.Injectable):!angular.Module, * value: function(string, *):!angular.Module * }} */ angular.Module; /** * @param {string} name * @param {angular.Injectable} animationFactory */ angular.Module.animation = function(name, animationFactory) {}; /** * @param {angular.Injectable} configFn * @return {!angular.Module} */ angular.Module.config = function(configFn) {}; /** * @param {string} name * @param {*} object * @return {!angular.Module} */ angular.Module.constant = function(name, object) {}; /** * @param {string} name * @param {angular.Injectable} constructor * @return {!angular.Module} */ angular.Module.controller = function(name, constructor) {}; /** * @param {string} name * @param {angular.Injectable} directiveFactory * @return {!angular.Module} */ angular.Module.directive = function(name, directiveFactory) {}; /** * @param {string} name * @param {angular.Injectable} providerFunction * @return {!angular.Module} */ angular.Module.factory = function(name, providerFunction) {}; /** * @param {string} name * @param {angular.Injectable} filterFactory * @return {!angular.Module} */ angular.Module.filter = function(name, filterFactory) {}; /** * @param {string} name * @param {angular.$provide.Provider|angular.Injectable} providerType * @return {!angular.Module} */ angular.Module.provider = function(name, providerType) {}; /** * @param {angular.Injectable} initializationFn * @return {!angular.Module} */ angular.Module.run = function(initializationFn) {}; /** * @param {string} name * @param {angular.Injectable} constructor * @return {!angular.Module} */ angular.Module.service = function(name, constructor) {}; /** * @param {string} name * @param {*} object * @return {!angular.Module} */ angular.Module.value = function(name, object) {}; /** * @type {string} */ angular.Module.name = ''; /** * @type {Array.<string>} */ angular.Module.requires; /** * @typedef {{ * $$phase: string, * $apply: function((string|function(!angular.Scope))=):*, * $applyAsync: function((string|function(!angular.Scope))=), * $broadcast: function(string, ...*), * $destroy: function(), * $digest: function(), * $emit: function(string, ...*), * $eval: function((string|function(!angular.Scope))=, Object=):*, * $evalAsync: function((string|function())=), * $id: string, * $new: function(boolean=):!angular.Scope, * $on: function(string, function(!angular.Scope.Event, ...?)):function(), * $parent: !angular.Scope, * $root: !angular.Scope, * $watch: function( * (string|Function), (string|Function)=, boolean=):function(), * $watchCollection: function( * (string|Function), (string|Function)=):function(), * $watchGroup: function( * Array.<string|Function>, (string|Function)=):function() * }} */ angular.Scope; /** @type {string} */ angular.Scope.$$phase; /** * @param {(string|function(!angular.Scope))=} opt_exp * @return {*} */ angular.Scope.$apply = function(opt_exp) {}; /** * @param {(string|function(!angular.Scope))=} opt_exp */ angular.Scope.$applyAsync = function(opt_exp) {}; /** * @param {string} name * @param {...*} args */ angular.Scope.$broadcast = function(name, args) {}; angular.Scope.$destroy = function() {}; angular.Scope.$digest = function() {}; /** * @param {string} name * @param {...*} args */ angular.Scope.$emit = function(name, args) {}; /** * @param {(string|function())=} opt_exp * @param {Object=} opt_locals * @return {*} */ angular.Scope.$eval = function(opt_exp, opt_locals) {}; /** * @param {(string|function())=} opt_exp */ angular.Scope.$evalAsync = function(opt_exp) {}; /** @type {string} */ angular.Scope.$id; /** * @param {boolean=} opt_isolate * @return {!angular.Scope} */ angular.Scope.$new = function(opt_isolate) {}; /** * @param {string} name * @param {function(!angular.Scope.Event, ...?)} listener * @return {function()} */ angular.Scope.$on = function(name, listener) {}; /** @type {!angular.Scope} */ angular.Scope.$parent; /** @type {!angular.Scope} */ angular.Scope.$root; /** * @param {string|!Function} exp * @param {(string|Function)=} opt_listener * @param {boolean=} opt_objectEquality * @return {function()} */ angular.Scope.$watch = function(exp, opt_listener, opt_objectEquality) {}; /** * @param {string|!Function} exp * @param {(string|Function)=} opt_listener * @return {function()} */ angular.Scope.$watchCollection = function(exp, opt_listener) {}; /** * @typedef {{ * currentScope: !angular.Scope, * defaultPrevented: boolean, * name: string, * preventDefault: function(), * stopPropagation: function(), * targetScope: !angular.Scope * }} */ angular.Scope.Event; /** @type {!angular.Scope} */ angular.Scope.Event.currentScope; /** @type {boolean} */ angular.Scope.Event.defaultPrevented; /** @type {string} */ angular.Scope.Event.name; angular.Scope.Event.preventDefault = function() {}; angular.Scope.Event.stopPropagation = function() {}; /** @type {!angular.Scope} */ angular.Scope.Event.targetScope; /** * @type {Object} */ angular.version = {}; /** * @type {string} */ angular.version.full = ''; /** * @type {number} */ angular.version.major = 0; /** * @type {number} */ angular.version.minor = 0; /** * @type {number} */ angular.version.dot = 0; /** * @type {string} */ angular.version.codeName = ''; /****************************************************************************** * $anchorScroll Service *****************************************************************************/ /** * @typedef {function()} */ angular.$anchorScroll; /****************************************************************************** * $anchorScrollProvider Service *****************************************************************************/ /** * @typedef {{ * disableAutoScrolling: function() * }} */ angular.$anchorScrollProvider; /** * @type {function()} */ angular.$anchorScrollProvider.disableAutoScrolling = function() {}; /****************************************************************************** * $animate Service *****************************************************************************/ /** * @constructor */ angular.$animate = function() {}; /** * @param {JQLiteSelector} element * @param {Object} from * @param {Object} to * @param {string=} opt_className * @param {Object.<string, *>=} opt_options * @return {!angular.$q.Promise} */ angular.$animate.prototype.animate = function( element, from, to, opt_className, opt_options) {}; /** * @param {JQLiteSelector} element * @param {JQLiteSelector} parentElement * @param {JQLiteSelector} afterElement * @param {Object.<string, *>=} opt_options * @return {!angular.$q.Promise} */ angular.$animate.prototype.enter = function( element, parentElement, afterElement, opt_options) {}; /** * @param {JQLiteSelector} element * @param {Object.<string, *>=} opt_options * @return {!angular.$q.Promise} */ angular.$animate.prototype.leave = function(element, opt_options) {}; /** * @param {JQLiteSelector} element * @param {JQLiteSelector} parentElement * @param {JQLiteSelector} afterElement * @param {Object.<string, *>=} opt_options * @return {!angular.$q.Promise} */ angular.$animate.prototype.move = function( element, parentElement, afterElement, opt_options) {}; /** * @param {JQLiteSelector} element * @param {string} className * @param {Object.<string, *>=} opt_options * @return {!angular.$q.Promise} */ angular.$animate.prototype.addClass = function( element, className, opt_options) {}; /** * @param {JQLiteSelector} element * @param {string} className * @param {Object.<string, *>=} opt_options * @return {!angular.$q.Promise} */ angular.$animate.prototype.removeClass = function( element, className, opt_options) {}; /** * @param {JQLiteSelector} element * @param {string} add * @param {string} remove * @param {Object.<string, *>=} opt_options * @return {!angular.$q.Promise} */ angular.$animate.prototype.setClass = function( element, add, remove, opt_options) {}; /** * @param {boolean=} opt_value * @param {JQLiteSelector=} opt_element * @return {boolean} */ angular.$animate.prototype.enabled = function(opt_value, opt_element) {}; /** * @param {angular.$q.Promise} animationPromise */ angular.$animate.prototype.cancel = function(animationPromise) {}; /****************************************************************************** * $animateProvider Service *****************************************************************************/ /** * @constructor */ angular.$animateProvider = function() {}; /** * @param {string} name * @param {Function} factory */ angular.$animateProvider.prototype.register = function(name, factory) {}; /** * @param {RegExp=} opt_expression */ angular.$animateProvider.prototype.classNameFilter = function( opt_expression) {}; /****************************************************************************** * $ariaProvider Service *****************************************************************************/ /** * @constructor */ angular.$ariaProvider = function() {}; /** * @param {!{ * ariaHidden: (boolean|undefined), * ariaChecked: (boolean|undefined), * ariaDisabled: (boolean|undefined), * ariaRequired: (boolean|undefined), * ariaInvalid: (boolean|undefined), * ariaMultiline: (boolean|undefined), * ariaValue: (boolean|undefined), * tabindex: (boolean|undefined), * bindKeypress: (boolean|undefined), * bindRoleForClick: (boolean|undefined) * }} config */ angular.$ariaProvider.prototype.config = function(config) {}; /****************************************************************************** * $compile Service *****************************************************************************/ /** * @typedef { * function( * (JQLiteSelector|Object), * function(!angular.Scope, Function=)=, number=): * function(!angular.Scope, * function(!angular.JQLite, !angular.Scope=)=, * angular.$compile.LinkOptions=): !angular.JQLite} */ angular.$compile; /** * @typedef {{ * parentBoundTranscludeFn: (Function|undefined), * transcludeControllers: (Object|undefined), * futureParentElement: (angular.JQLite|undefined) * }} */ angular.$compile.LinkOptions; // TODO(martinprobst): remaining $compileProvider methods. /** * @constructor */ angular.$compileProvider = function() {}; /** * @param {boolean=} opt_enabled * @return {boolean|!angular.$compileProvider} */ angular.$compileProvider.prototype.debugInfoEnabled = function(opt_enabled) {}; /****************************************************************************** * $cacheFactory Service *****************************************************************************/ /** * @typedef { * function(string, angular.$cacheFactory.Options=): * !angular.$cacheFactory.Cache} */ angular.$cacheFactory; /** * @typedef {function(string): ?angular.$cacheFactory.Cache} */ angular.$cacheFactory.get; /** @typedef {{capacity: (number|undefined)}} */ angular.$cacheFactory.Options; /** * @template T * @constructor */ angular.$cacheFactory.Cache = function() {}; /** * @return {!angular.$cacheFactory.Cache.Info} */ angular.$cacheFactory.Cache.prototype.info = function() {}; /** * @param {string} key * @param {T} value */ angular.$cacheFactory.Cache.prototype.put = function(key, value) {}; /** * @param {string} key * @return {T} */ angular.$cacheFactory.Cache.prototype.get = function(key) {}; /** * @param {string} key */ angular.$cacheFactory.Cache.prototype.remove = function(key) {}; angular.$cacheFactory.Cache.prototype.removeAll = function() {}; angular.$cacheFactory.Cache.prototype.destroy = function() {}; /** * @typedef {{ * id: string, * size: number, * options: angular.$cacheFactory.Options * }} */ angular.$cacheFactory.Cache.Info; /****************************************************************************** * $controller Service *****************************************************************************/ /** * @typedef {function((Function|string), Object):Object} */ angular.$controller; /****************************************************************************** * $controllerProvider Service *****************************************************************************/ /** * @typedef {{ * register: function((string|Object), angular.Injectable=), * allowGlobals: function() * }} */ angular.$controllerProvider; /****************************************************************************** * $exceptionHandler Service *****************************************************************************/ /** * @typedef {function(Error, string=)} */ angular.$exceptionHandler; /****************************************************************************** * $filter Service *****************************************************************************/ /** * @typedef {function(string): !Function} */ angular.$filter; /** * The 'orderBy' filter is available through $filterProvider and AngularJS * injection; but is not accessed through a documented public API of AngularJS. * <p>In current AngularJS version the injection is satisfied by * angular.orderByFunction, where the implementation is found. * <p>See http://docs.angularjs.org/api/ng.filter:orderBy. * @typedef {function(Array, * (string|function(?):*|Array.<(string|function(?):*)>), * boolean=): Array} */ angular.$filter.orderBy; /** * @typedef {function(Array, * (string|Object|function(?):*), * (function(?):*|boolean)=): Array} */ angular.$filter.filter; /****************************************************************************** * $filterProvider Service *****************************************************************************/ /** * @typedef {{register: function(string, angular.Injectable)}} */ angular.$filterProvider; /** * @param {string} name * @param {angular.Injectable} fn */ angular.$filterProvider.register = function(name, fn) {}; /****************************************************************************** * $http Service *****************************************************************************/ /** * This is a typedef because the closure compiler does not allow * defining a type that is a function with properties. * If you are trying to use the $http service as a function, try * using one of the helper functions instead. * @typedef {{ * delete: function(string, angular.$http.Config=):!angular.$http.HttpPromise, * get: function(string, angular.$http.Config=):!angular.$http.HttpPromise, * head: function(string, angular.$http.Config=):!angular.$http.HttpPromise, * jsonp: function(string, angular.$http.Config=):!angular.$http.HttpPromise, * patch: function(string, *, angular.$http.Config=): * !angular.$http.HttpPromise, * post: function(string, *, angular.$http.Config=): * !angular.$http.HttpPromise, * put: function(string, *, angular.$http.Config=):!angular.$http.HttpPromise, * defaults: angular.$http.Config, * pendingRequests: !Array.<angular.$http.Config> * }} */ angular.$http; /** * @typedef {{ * cache: (boolean|!angular.$cacheFactory.Cache|undefined), * data: (string|Object|undefined), * headers: (Object|undefined), * method: (string|undefined), * params: (Object.<(string|Object)>|undefined), * responseType: (string|undefined), * timeout: (number|!angular.$q.Promise|undefined), * transformRequest: * (function((string|Object), Object):(string|Object)| * Array.<function((string|Object), Object):(string|Object)>|undefined), * transformResponse: * (function((string|Object), Object):(string|Object)| * Array.<function((string|Object), Object):(string|Object)>|undefined), * url: (string|undefined), * withCredentials: (boolean|undefined), * xsrfCookieName: (string|undefined), * xsrfHeaderName: (string|undefined) * }} */ angular.$http.Config; angular.$http.Config.transformRequest; angular.$http.Config.transformResponse; // /** // * This extern is currently incomplete as delete is a reserved word. // * To use delete, index $http. // * Example: $http['delete'](url, opt_config); // * @param {string} url // * @param {angular.$http.Config=} opt_config // * @return {!angular.$http.HttpPromise} // */ // angular.$http.delete = function(url, opt_config) {}; /** * @param {string} url * @param {angular.$http.Config=} opt_config * @return {!angular.$http.HttpPromise} */ angular.$http.get = function(url, opt_config) {}; /** * @param {string} url * @param {angular.$http.Config=} opt_config * @return {!angular.$http.HttpPromise} */ angular.$http.head = function(url, opt_config) {}; /** * @param {string} url * @param {angular.$http.Config=} opt_config * @return {!angular.$http.HttpPromise} */ angular.$http.jsonp = function(url, opt_config) {}; /** * @param {string} url * @param {*} data * @param {angular.$http.Config=} opt_config * @return {!angular.$http.HttpPromise} */ angular.$http.patch = function(url, data, opt_config) {}; /** * @param {string} url * @param {*} data * @param {angular.$http.Config=} opt_config * @return {!angular.$http.HttpPromise} */ angular.$http.post = function(url, data, opt_config) {}; /** * @param {string} url * @param {*} data * @param {angular.$http.Config=} opt_config * @return {!angular.$http.HttpPromise} */ angular.$http.put = function(url, data, opt_config) {}; /** * @type {angular.$http.Config} */ angular.$http.defaults; /** * @type {Array.<angular.$http.Config>} * @const */ angular.$http.pendingRequests; /** * @typedef {{ * request: (undefined|(function(!angular.$http.Config): * !angular.$http.Config|!angular.$q.Promise.<!angular.$http.Config>)), * requestError: (undefined|(function(Object): !angular.$q.Promise|Object)), * response: (undefined|(function(!angular.$http.Response): * !angular.$http.Response|!angular.$q.Promise.<!angular.$http.Response>)), * responseError: (undefined|(function(Object): !angular.$q.Promise|Object)) * }} */ angular.$http.Interceptor; /** * @typedef {{ * defaults: !angular.$http.Config, * interceptors: !Array.<string|function(...*): !angular.$http.Interceptor>, * useApplyAsync: function(boolean=):(boolean|!angular.$HttpProvider) * }} */ angular.$HttpProvider; /** * @type {angular.$http.Config} */ angular.$HttpProvider.defaults; /** * @type {!Array.<string|function(...*): !angular.$http.Interceptor>} */ angular.$HttpProvider.interceptors; /** * @param {boolean=} opt_value * @return {boolean|!angular.$HttpProvider} */ angular.$HttpProvider.useApplyAsync = function(opt_value) {}; /****************************************************************************** * $injector Service *****************************************************************************/ /** * @typedef {{ * annotate: function(angular.Injectable):Array.<string>, * get: function(string):(?), * has: function(string):boolean, * instantiate: function(Function, Object=):Object, * invoke: function(angular.Injectable, Object=, Object=):(?) * }} */ angular.$injector; /** * @param {angular.Injectable} fn * @return {Array.<string>} */ angular.$injector.annotate = function(fn) {}; /** * @param {string} name * @return {?} */ angular.$injector.get = function(name) {}; /** * @param {string} name * @return {boolean} */ angular.$injector.has = function(name) {}; /** * @param {!Function} type * @param {Object=} opt_locals * @return {Object} */ angular.$injector.instantiate = function(type, opt_locals) {}; /** * @param {angular.Injectable} fn * @param {Object=} opt_self * @param {Object=} opt_locals * @return {?} */ angular.$injector.invoke = function(fn, opt_self, opt_locals) {}; /****************************************************************************** * $interpolateProvider Service *****************************************************************************/ /** * @typedef {{ * startSymbol: function(string), * endSymbol: function(string) * }} */ angular.$interpolateProvider; /** @type {function(string)} */ angular.$interpolateProvider.startSymbol; /** @type {function(string)} */ angular.$interpolateProvider.endSymbol; /****************************************************************************** * $interval Service *****************************************************************************/ /** * @typedef { * function(function(), number=, number=, boolean=):!angular.$q.Promise * } */ angular.$interval; /** * Augment the angular.$interval type definition by reopening the type via an * artificial angular.$interval instance. * * This allows us to define methods on function objects which is something * that can't be expressed via typical type annotations. * * @type {angular.$interval} */ angular.$interval_; /** * @type {function(!angular.$q.Promise):boolean} */ angular.$interval_.cancel = function(promise) {}; /****************************************************************************** * $location Service *****************************************************************************/ /** * @typedef {{ * absUrl: function():string, * hash: function(string=):string, * host: function():string, * path: function(string=):(string|!angular.$location), * port: function():number, * protocol: function():string, * replace: function(), * search: function((string|Object.<string, string>)=, * ?(string|Array.<string>|boolean|number)=): (!Object|angular.$location), * url: function(string=):string * }} */ angular.$location; /** * @return {string} */ angular.$location.absUrl = function() {}; /** * @param {string=} opt_hash * @return {string} */ angular.$location.hash = function(opt_hash) {}; /** * @return {string} */ angular.$location.host = function() {}; /** * @param {string=} opt_path * @return {string|!angular.$location} */ angular.$location.path = function(opt_path) {}; /** * @return {number} */ angular.$location.port = function() {}; /** * @return {string} */ angular.$location.protocol = function() {}; /** * @type {function()} */ angular.$location.replace = function() {}; /** * @param {(string|Object.<string, string>)=} opt_search * @param {?(string|Array.<string>|boolean|number)=} opt_paramValue * @return {(!Object|angular.$location)} */ angular.$location.search = function(opt_search, opt_paramValue) {}; /** * @param {string=} opt_url * @return {string} */ angular.$location.url = function(opt_url) {}; /****************************************************************************** * $locationProvider Service *****************************************************************************/ /** * @typedef {{ * enabled: (boolean|undefined), * requireBase: (boolean|undefined) * }} */ angular.$locationProvider.html5ModeConfig; /** * @typedef {{ * hashPrefix: * function(string=): (string|!angular.$locationProvider), * html5Mode: * function( * (boolean|angular.$locationProvider.html5ModeConfig)=): * (boolean|!angular.$locationProvider) * }} */ angular.$locationProvider; /** * @param {string=} opt_prefix * @return {string|!angular.$locationProvider} */ angular.$locationProvider.hashPrefix = function(opt_prefix) {}; /** * @param {(boolean|angular.$locationProvider.html5ModeConfig)=} opt_mode * @return {boolean|!angular.$locationProvider} */ angular.$locationProvider.html5Mode = function(opt_mode) {}; /****************************************************************************** * $log Service *****************************************************************************/ /** * @typedef {{ * error: function(...*), * info: function(...*), * log: function(...*), * warn: function(...*) * }} */ angular.$log; /** * @param {...*} var_args */ angular.$log.error = function(var_args) {}; /** * @param {...*} var_args */ angular.$log.info = function(var_args) {}; /** * @param {...*} var_args */ angular.$log.log = function(var_args) {}; /** * @param {...*} var_args */ angular.$log.warn = function(var_args) {}; /****************************************************************************** * NgModelController *****************************************************************************/ /** * @constructor */ angular.NgModelController = function() {}; /** * @type {?} */ angular.NgModelController.prototype.$modelValue; /** * @type {boolean} */ angular.NgModelController.prototype.$dirty; /** * @type {!Object.<boolean>} */ angular.NgModelController.prototype.$error; /** * @type {!Array.<function(?):*>} */ angular.NgModelController.prototype.$formatters; /** * @type {boolean} */ angular.NgModelController.prototype.$invalid; /** * @type {!Array.<function(?):*>} */ angular.NgModelController.prototype.$parsers; /** * @type {boolean} */ angular.NgModelController.prototype.$pristine; angular.NgModelController.prototype.$render = function() {}; /** * @param {string} key * @param {boolean} isValid */ angular.NgModelController.prototype.$setValidity = function(key, isValid) {}; /** * @param {?} value */ angular.NgModelController.prototype.$setViewValue = function(value) {}; /** * @type {boolean} */ angular.NgModelController.prototype.$valid; /** * @type {!Array.<function()>} */ angular.NgModelController.prototype.$viewChangeListeners; /** * @type {?} */ angular.NgModelController.prototype.$viewValue; /** * @type {!Object.<string, function(?, ?):*>} */ angular.NgModelController.prototype.$validators; /** * @type {Object.<string, function(?, ?):*>} */ angular.NgModelController.prototype.$asyncValidators; /** * @type {boolean} */ angular.NgModelController.prototype.$untouched; /** * @type {boolean} */ angular.NgModelController.prototype.$touched; /** * @param {?} value */ angular.NgModelController.prototype.$isEmpty = function(value) {}; /** * @type {function()} */ angular.NgModelController.prototype.$setPristine = function() {}; /** * @type {function()} */ angular.NgModelController.prototype.$setDirty = function() {}; /** * @type {function()} */ angular.NgModelController.prototype.$setUntouched = function() {}; /** * @type {function()} */ angular.NgModelController.prototype.$setTouched = function() {}; /** * @type {function()} */ angular.NgModelController.prototype.$rollbackViewValue = function() {}; /** * @type {function()} */ angular.NgModelController.prototype.$validate = function() {}; /** * @type {function()} */ angular.NgModelController.prototype.$commitViewValue = function() {}; /****************************************************************************** * FormController *****************************************************************************/ /** * @constructor */ angular.FormController = function() {}; /** * @param {*} control */ angular.FormController.prototype.$addControl = function(control) {}; /** * @type {function()} */ angular.FormController.prototype.$rollbackViewValue = function() {}; /** * @type {function()} */ angular.FormController.prototype.$commitViewValue = function() {}; /** * @type {boolean} */ angular.FormController.prototype.$dirty; /** * @type {!Object.<boolean|!Array.<*>>} */ angular.FormController.prototype.$error; /** * @type {boolean} */ angular.FormController.prototype.$invalid; /** * @type {string} */ angular.FormController.prototype.$name; /** * @type {boolean} */ angular.FormController.prototype.$pristine; /** * @param {*} control */ angular.FormController.prototype.$removeControl = function(control) {}; /** * @type {function()} */ angular.FormController.prototype.$setDirty = function() {}; /** * @type {function()} */ angular.FormController.prototype.$setPristine = function() {}; /** * @type {function()} */ angular.FormController.prototype.$setUntouched = function() {}; /** * @type {function()} */ angular.FormController.prototype.$setSubmitted = function() {}; /** * @type {boolean} */ angular.FormController.prototype.$submitted; /** * @param {string} validationToken * @param {boolean} isValid * @param {*} control */ angular.FormController.prototype.$setValidity = function( validationToken, isValid, control) {}; /** * @type {boolean} */ angular.FormController.prototype.$valid; /****************************************************************************** * $parse Service *****************************************************************************/ /** * @typedef {function(string):!angular.$parse.Expression} */ angular.$parse; /** * @typedef {function((!angular.Scope|!Object), Object=):*} */ angular.$parse.Expression; /** * Augment the angular.$parse.Expression type definition by reopening the type * via an artificial angular.$parse instance. * * This allows us to define methods on function objects which is something * that can't be expressed via typical type annotations. * * @type {angular.$parse.Expression} */ angular.$parse_; /** * @type {function((!angular.Scope|!Object), *)} */ angular.$parse_.assign = function(scope, newValue) {}; /****************************************************************************** * $provide Service *****************************************************************************/ /** * @typedef {{ * constant: function(string, *): Object, * decorator: function(string, angular.Injectable), * factory: function(string, angular.Injectable): Object, * provider: function(string, ( * angular.Injectable|angular.$provide.Provider)): Object, * service: function(string, angular.Injectable): Object, * value: function(string, *): Object * }} */ angular.$provide; /** @typedef {{$get: (!Array.<string|!Function>|!Function)}} */ angular.$provide.Provider; /** @typedef {(!Array.<string|!Function>|!Function)} */ angular.$provide.Provider.$get; /** * @param {string} name * @param {*} object * @return {Object} */ angular.$provide.constant = function(name, object) {}; /** * @param {string} name * @param {angular.Injectable} decorator */ angular.$provide.decorator = function(name, decorator) {}; /** * @param {string} name * @param {angular.Injectable} providerFunction * @return {Object} */ angular.$provide.factory = function(name, providerFunction) {}; /** * @param {string} name * @param {angular.Injectable|angular.$provide.Provider} providerType * @return {Object} */ angular.$provide.provider = function(name, providerType) {}; /** * @param {string} name * @param {angular.Injectable} constructor * @return {Object} */ angular.$provide.service = function(name, constructor) {}; /** * @param {string} name * @param {*} object * @return {Object} */ angular.$provide.value = function(name, object) {}; /****************************************************************************** * $route Service *****************************************************************************/ /** * @typedef {{ * reload: function(), * updateParams: function(!Object<string,string>), * current: !angular.$route.Route, * routes: Array.<!angular.$route.Route> * }} */ angular.$route; /** @type {function()} */ angular.$route.reload = function() {}; /** * @param {!Object<string,string>} object */ angular.$route.updateParams = function(object) {}; /** @type {!angular.$route.Route} */ angular.$route.current; /** @type {Array.<!angular.$route.Route>} */ angular.$route.routes; /** * @typedef {{ * $route: angular.$routeProvider.Params, * locals: Object.<string, *>, * params: Object.<string, string>, * pathParams: Object.<string, string>, * scope: Object.<string, *>, * originalPath: (string|undefined), * regexp: (RegExp|undefined) * }} */ angular.$route.Route; /** @type {angular.$routeProvider.Params} */ angular.$route.Route.$route; /** @type {Object.<string, *>} */ angular.$route.Route.locals; /** @type {Object.<string, string>} */ angular.$route.Route.params; /** @type {Object.<string, string>} */ angular.$route.Route.pathParams; /** @type {Object.<string, *>} */ angular.$route.Route.scope; /** @type {string|undefined} */ angular.$route.Route.originalPath; /** @type {RegExp|undefined} */ angular.$route.Route.regexp; /****************************************************************************** * $routeParams Service *****************************************************************************/ // TODO: This should be !Object.<string|boolean> because valueless query params // (without even an equal sign) come through as boolean "true". /** @typedef {!Object.<string>} */ angular.$routeParams; /****************************************************************************** * $routeProvider Service *****************************************************************************/ /** * @typedef {{ * otherwise: * function( * (string|!angular.$routeProvider.Params)): !angular.$routeProvider, * when: * function( * string, angular.$routeProvider.Params): !angular.$routeProvider * }} */ angular.$routeProvider; /** * @param {(string|!angular.$routeProvider.Params)} params * @return {!angular.$routeProvider} */ angular.$routeProvider.otherwise = function(params) {}; /** * @param {string} path * @param {angular.$routeProvider.Params} route * @return {!angular.$routeProvider} */ angular.$routeProvider.when = function(path, route) {}; /** * @typedef {{ * controller: (angular.Injectable|string|undefined), * controllerAs: (string|undefined), * template: (string|undefined), * templateUrl: (string|function(!Object.<string,string>=)|undefined), * resolve: (Object.<string, ( * string|angular.Injectable|!angular.$q.Promise * )>|undefined), * redirectTo: ( * string|function(Object.<string>, string, Object): string|undefined), * reloadOnSearch: (boolean|undefined) * }} */ angular.$routeProvider.Params; /** @type {angular.Injectable|string} */ angular.$routeProvider.Params.controller; /** @type {string} */ angular.$routeProvider.Params.controllerAs; /** @type {string} */ angular.$routeProvider.Params.template; /** @type {string|function(!Object.<string,string>=)} */ angular.$routeProvider.Params.templateUrl; /** @type {Object.<string, (string|angular.Injectable|!angular.$q.Promise)>} */ angular.$routeProvider.Params.resolve; /** @type {string|function(Object.<string>, string, Object): string} */ angular.$routeProvider.Params.redirectTo; /** @type {boolean} */ angular.$routeProvider.Params.reloadOnSearch; /****************************************************************************** * $sanitize Service *****************************************************************************/ /** @typedef {function(string):string} */ angular.$sanitize; /****************************************************************************** * $sce Service *****************************************************************************/ /** * Ref: http://docs.angularjs.org/api/ng.$sce * * @typedef {{ * HTML: string, * CSS: string, * URL: string, * JS: string, * RESOURCE_URL: string, * isEnabled: function(): boolean, * parseAs: function(string, string): !angular.$parse.Expression, * getTrusted: function(string, *): string, * trustAs: function(string, string): *, * parseAsHtml: function(string): !angular.$parse.Expression, * parseAsCss: function(string): !angular.$parse.Expression, * parseAsUrl: function(string): !angular.$parse.Expression, * parseAsJs: function(string): !angular.$parse.Expression, * parseAsResourceUrl: function(string): !angular.$parse.Expression, * getTrustedHtml: function(*): string, * getTrustedCss: function(*): string, * getTrustedUrl: function(*): string, * getTrustedJs: function(*): string, * getTrustedResourceUrl: function(*): string, * trustAsHtml: function(string): *, * trustAsCss: function(string): *, * trustAsUrl: function(string): *, * trustAsJs: function(string): *, * trustAsResourceUrl: function(string): * * }} *****************************************************************************/ angular.$sce; /** @const {string} */ angular.$sce.HTML; /** @const {string} */ angular.$sce.CSS; /** @const {string} */ angular.$sce.URL; /** @const {string} */ angular.$sce.JS; /** @const {string} */ angular.$sce.RESOURCE_URL; /** @return {boolean} */ angular.$sce.isEnabled = function() {}; /** * @param {string} type * @param {string} expression * @return {!angular.$parse.Expression} */ angular.$sce.parseAs = function(type, expression) {}; /** * @param {string} type * @param {*} maybeTrusted * @return {string} */ angular.$sce.getTrusted = function(type, maybeTrusted) {}; /** * @param {string} type * @param {string} trustedValue * @return {*} */ angular.$sce.trustAs = function(type, trustedValue) {}; /** * @param {string} expression * @return {!angular.$parse.Expression} */ angular.$sce.parseAsHtml = function(expression) {}; /** * @param {string} expression * @return {!angular.$parse.Expression} */ angular.$sce.parseAsCss = function(expression) {}; /** * @param {string} expression * @return {!angular.$parse.Expression} */ angular.$sce.parseAsUrl = function(expression) {}; /** * @param {string} expression * @return {!angular.$parse.Expression} */ angular.$sce.parseAsJs = function(expression) {}; /** * @param {string} expression * @return {!angular.$parse.Expression} */ angular.$sce.parseAsResourceUrl = function(expression) {}; /** * @param {*} maybeTrusted * @return {string} */ angular.$sce.getTrustedHtml = function(maybeTrusted) {}; /** * @param {*} maybeTrusted * @return {string} */ angular.$sce.getTrustedCss = function(maybeTrusted) {}; /** * @param {*} maybeTrusted * @return {string} */ angular.$sce.getTrustedUrl = function(maybeTrusted) {}; /** * @param {*} maybeTrusted * @return {string} */ angular.$sce.getTrustedJs = function(maybeTrusted) {}; /** * @param {*} maybeTrusted * @return {string} */ angular.$sce.getTrustedResourceUrl = function(maybeTrusted) {}; /** * @param {string} trustedValue * @return {*} */ angular.$sce.trustAsHtml = function(trustedValue) {}; /** * @param {string} trustedValue * @return {*} */ angular.$sce.trustAsCss = function(trustedValue) {}; /** * @param {string} trustedValue * @return {*} */ angular.$sce.trustAsUrl = function(trustedValue) {}; /** * @param {string} trustedValue * @return {*} */ angular.$sce.trustAsJs = function(trustedValue) {}; /** * @param {string} trustedValue * @return {*} */ angular.$sce.trustAsResourceUrl = function(trustedValue) {}; /****************************************************************************** * $sceDelegate Service *****************************************************************************/ /** * Ref: http://docs.angularjs.org/api/ng/service/$sceDelegate * * @constructor */ angular.$sceDelegate = function() {}; /** * @param {string} type * @param {*} value * @return {*} */ angular.$sceDelegate.prototype.trustAs = function(type, value) {}; /** * Note: because this method overrides Object.prototype.valueOf, the value * parameter needs to be annotated as optional to keep the compiler happy (as * otherwise the signature won't match Object.prototype.valueOf). * * @override * @param {*=} value * @return {*} */ angular.$sceDelegate.prototype.valueOf = function(value) {}; /** * @param {string} type * @param {*} maybeTrusted * @return {*} */ angular.$sceDelegate.prototype.getTrusted = function(type, maybeTrusted) {}; /****************************************************************************** * $sceDelegateProvider Service *****************************************************************************/ /** * Ref: http://docs.angularjs.org/api/ng/provider/$sceDelegateProvider * * @constructor */ angular.$sceDelegateProvider = function() {}; /** * @param {Array.<string>=} opt_whitelist * @return {!Array.<string>} */ angular.$sceDelegateProvider.prototype.resourceUrlWhitelist = function( opt_whitelist) {}; /** * @param {Array.<string>=} opt_blacklist * @return {!Array.<string>} */ angular.$sceDelegateProvider.prototype.resourceUrlBlacklist = function( opt_blacklist) {}; /****************************************************************************** * $templateCache Service *****************************************************************************/ /** * @typedef {!angular.$cacheFactory.Cache.<string>} */ angular.$templateCache; /****************************************************************************** * $timeout Service *****************************************************************************/ /** * @typedef {function(function(), number=, boolean=):!angular.$q.Promise} */ angular.$timeout; /** * Augment the angular.$timeout type definition by reopening the type via an * artificial angular.$timeout instance. * * This allows us to define methods on function objects which is something * that can't be expressed via typical type annotations. * * @type {angular.$timeout} */ angular.$timeout_; /** * @type {function(angular.$q.Promise=):boolean} */ angular.$timeout_.cancel = function(promise) {}; /****************************************************************************** * $window Service *****************************************************************************/ /** @typedef {!Window} */ angular.$window;
{ "content_hash": "fa2afb4241b4cbe3ed3a13833ad5a1a6", "timestamp": "", "source": "github", "line_count": 2522, "max_line_length": 81, "avg_line_length": 24.451625693893735, "alnum_prop": 0.5925049053788899, "repo_name": "rintaro/closure-compiler", "id": "293d9514b78387eee4fb850d2c855e2f68e6ba31", "size": "62279", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "contrib/externs/angular-1.3.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "1805" }, { "name": "Java", "bytes": "11965535" }, { "name": "JavaScript", "bytes": "4311497" }, { "name": "Protocol Buffer", "bytes": "7715" } ], "symlink_target": "" }
disable_dfss CHANGELOG ====================== This file is used to list changes made in each version of the disable_dfss cookbook. 0.1.0 ----- - [your_name] - Initial release of disable_dfss - - - Check the [Markdown Syntax Guide](http://daringfireball.net/projects/markdown/syntax) for help with Markdown. The [Github Flavored Markdown page](http://github.github.com/github-flavored-markdown/) describes the differences between markdown on github and standard markdown.
{ "content_hash": "f88ed8f42f389011571461df98a739b1", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 163, "avg_line_length": 36.53846153846154, "alnum_prop": 0.7368421052631579, "repo_name": "pigram86/chef-repo", "id": "2d8117d0146c4f725181de39296972c8c27d0eba", "size": "475", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cookbooks/disable_dfss/CHANGELOG.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Perl", "bytes": "847" }, { "name": "Ruby", "bytes": "581021" } ], "symlink_target": "" }
package oghamsendgridv2.ut; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.RETURNS_SMART_NULLS; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import org.junit.Before; import org.junit.Test; import com.sendgrid.SendGrid; import fr.sii.ogham.core.message.content.Content; import fr.sii.ogham.core.message.content.MultiContent; import fr.sii.ogham.core.message.content.StringContent; import fr.sii.ogham.email.exception.handler.ContentHandlerException; import fr.sii.ogham.email.sendgrid.v2.sender.impl.sendgrid.handler.MultiContentHandler; import fr.sii.ogham.email.sendgrid.v2.sender.impl.sendgrid.handler.SendGridContentHandler; import fr.sii.ogham.email.sendgrid.v2.sender.impl.sendgrid.handler.StringContentHandler; /** * Test campaign for the {@link MultiContentHandler} class. */ public final class MultiContentHandlerTest { private SendGridContentHandler delegate; private MultiContentHandler instance; @Before public void setUp() { delegate = mock(SendGridContentHandler.class, RETURNS_SMART_NULLS); this.instance = new MultiContentHandler(delegate); } @Test(expected = IllegalArgumentException.class) public void emailParamCannotBeNull() throws ContentHandlerException { instance.setContent(null, null, new StringContent("")); } @Test(expected = IllegalArgumentException.class) public void contentParamCannotBeNull() throws ContentHandlerException { instance.setContent(null, new SendGrid.Email(), null); } @Test(expected = IllegalArgumentException.class) public void providerParamCannotBeNull() { new StringContentHandler(null); } @Test(expected = IllegalArgumentException.class) public void constructor_delegateParamCannotBeNull() { new MultiContentHandler(null); } @Test public void setContent_single() throws ContentHandlerException { final Content exp = new StringContent("Insignificant"); final Content content = new MultiContent(exp); final SendGrid.Email email = new SendGrid.Email(); instance.setContent(null, email, content); verify(delegate).setContent(any(), any(SendGrid.Email.class), eq(exp)); } @Test public void setContent_multiple() throws ContentHandlerException { final Content exp1 = new StringContent("Insignificant 1"); final Content exp2 = new StringContent("Insignificant 2"); final Content content = new MultiContent(exp1, exp2); final SendGrid.Email email = new SendGrid.Email(); instance.setContent(null, email, content); verify(delegate).setContent(any(), any(SendGrid.Email.class), eq(exp1)); verify(delegate).setContent(any(), any(SendGrid.Email.class), eq(exp2)); } @Test(expected = IllegalArgumentException.class) public void setContent_notMultiContent() throws ContentHandlerException { final Content content = new StringContent("Insignificant"); final SendGrid.Email email = new SendGrid.Email(); instance.setContent(null, email, content); } @Test(expected = ContentHandlerException.class) public void setContent_delegateFailure() throws ContentHandlerException { final Content exp = new StringContent("Insignificant"); final Content content = new MultiContent(exp); final SendGrid.Email email = new SendGrid.Email(); final ContentHandlerException e = new ContentHandlerException("Thrown by mock", exp); doThrow(e).when(delegate).setContent(null, email, exp); instance.setContent(null, email, content); } }
{ "content_hash": "7b6d0f6f4fe96deb09acb1495afb1276", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 90, "avg_line_length": 35.490196078431374, "alnum_prop": 0.7624309392265194, "repo_name": "groupe-sii/ogham", "id": "dd5fe680d82f5a3bedfc7f825fb10d463747a694", "size": "3620", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ogham-email-sendgrid-v2/src/test/java/oghamsendgridv2/ut/MultiContentHandlerTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "11322" }, { "name": "Dockerfile", "bytes": "206" }, { "name": "FreeMarker", "bytes": "34582" }, { "name": "Groovy", "bytes": "478648" }, { "name": "HTML", "bytes": "1651483" }, { "name": "Java", "bytes": "3886709" }, { "name": "JavaScript", "bytes": "14796" }, { "name": "Python", "bytes": "33553" }, { "name": "SCSS", "bytes": "28548" }, { "name": "Shell", "bytes": "13021" } ], "symlink_target": "" }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.sql.tree; import com.google.common.collect.ImmutableList; import java.util.List; import java.util.Objects; import java.util.Optional; import static com.google.common.base.MoreObjects.toStringHelper; import static java.util.Objects.requireNonNull; public final class Insert extends Statement { private final QualifiedName target; private final Query query; private final Optional<List<Identifier>> columns; public Insert(QualifiedName target, Optional<List<Identifier>> columns, Query query) { this(Optional.empty(), columns, target, query); } private Insert(Optional<NodeLocation> location, Optional<List<Identifier>> columns, QualifiedName target, Query query) { super(location); this.target = requireNonNull(target, "target is null"); this.columns = requireNonNull(columns, "columns is null"); this.query = requireNonNull(query, "query is null"); } public QualifiedName getTarget() { return target; } public Optional<List<Identifier>> getColumns() { return columns; } public Query getQuery() { return query; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitInsert(this, context); } @Override public List<Node> getChildren() { return ImmutableList.of(query); } @Override public int hashCode() { return Objects.hash(target, columns, query); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if ((obj == null) || (getClass() != obj.getClass())) { return false; } Insert o = (Insert) obj; return Objects.equals(target, o.target) && Objects.equals(columns, o.columns) && Objects.equals(query, o.query); } @Override public String toString() { return toStringHelper(this) .add("target", target) .add("columns", columns) .add("query", query) .toString(); } }
{ "content_hash": "19251d93629ce55de8f08580e981771b", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 122, "avg_line_length": 26.970588235294116, "alnum_prop": 0.6321337695383497, "repo_name": "hgschmie/presto", "id": "2d9ae0e249443c7bf4090c7250cee1dc2971dad9", "size": "2751", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "presto-parser/src/main/java/io/prestosql/sql/tree/Insert.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "28776" }, { "name": "CSS", "bytes": "13019" }, { "name": "Dockerfile", "bytes": "1328" }, { "name": "HTML", "bytes": "28633" }, { "name": "Java", "bytes": "33806380" }, { "name": "JavaScript", "bytes": "217040" }, { "name": "Makefile", "bytes": "6830" }, { "name": "PLSQL", "bytes": "2990" }, { "name": "Python", "bytes": "10747" }, { "name": "SQLPL", "bytes": "926" }, { "name": "Shell", "bytes": "34068" }, { "name": "TSQL", "bytes": "162799" }, { "name": "Thrift", "bytes": "12631" } ], "symlink_target": "" }
require "quickeebooks" require "quickeebooks/windows/model/meta_data" require "quickeebooks/windows/model/account_detail_type" module Quickeebooks module Windows module Model class Account < Quickeebooks::Windows::Model::IntuitType include ActiveModel::Validations XML_COLLECTION_NODE = 'Accounts' XML_NODE = 'Account' # https://services.intuit.com/sb/account/v2/<realmID> REST_RESOURCE = "account" xml_convention :camelcase xml_accessor :id, :from => 'Id', :as => Quickeebooks::Windows::Model::Id xml_accessor :sync_token, :from => 'SyncToken', :as => Integer xml_accessor :meta_data, :from => 'MetaData', :as => Quickeebooks::Windows::Model::MetaData xml_accessor :external_key, :from => 'ExternalKey' xml_accessor :synchronized, :from => 'Synchronized' xml_accessor :custom_fields, :from => 'CustomField', :as => [Quickeebooks::Windows::Model::CustomField] xml_accessor :draft xml_accessor :object_state, :from => 'ObjectState' xml_accessor :account_parent_id, :from => 'AccountParentId' xml_accessor :account_parent_name, :from => 'AccountParentName' xml_accessor :name, :from => 'Name' xml_accessor :desc, :from => 'Desc' xml_accessor :active xml_accessor :type, :from => 'Type' xml_accessor :sub_type, :from => 'SubType' xml_accessor :acct_num, :from => 'AcctNum' xml_accessor :bank_num, :from => 'BankNum' xml_accessor :routing_num, :from => 'RoutingNum' xml_accessor :opening_balance, :from => 'OpeningBalance', :as => Float xml_accessor :current_balance, :from => 'CurrentBalance', :as => Float xml_accessor :opening_balance_date, :from => 'OpeningBalanceDate', :as => Date xml_accessor :current_balance_with_sub_accounts, :from => 'CurrentBalanceWithSubAccounts', :as => Float validates_presence_of :name, :sub_type validates_inclusion_of :sub_type, :in => Quickeebooks::Windows::Model::AccountDetailType::TYPES validate :ensure_name_is_valid def valid_for_update? if sync_token.nil? errors.add(:sync_token, "Missing required attribute SyncToken for update") end valid? errors.empty? end # To delete an account Intuit requires we provide Id and SyncToken fields def valid_for_deletion? return false if(id.nil? || sync_token.nil?) id.to_i > 0 && !sync_token.to_s.empty? && sync_token.to_i >= 0 end private def ensure_name_is_valid if name.nil? errors.add(:name, "Missing required attribute: name") end if name.is_a?(String) && name.index(':') != nil errors.add(:name, "Attribute :name cannot contain a colon") end end end end end end
{ "content_hash": "77761e1c3050ca0505b1b3311d935e55", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 111, "avg_line_length": 39.54054054054054, "alnum_prop": 0.6155160628844839, "repo_name": "shipci/quickeebooks", "id": "8badeb2b8388e0fe1e70147d9428fa453d52bbf0", "size": "2926", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "lib/quickeebooks/windows/model/account.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "362298" } ], "symlink_target": "" }
{% extends "base.html" %} {% load i18n static rest_framework %} {% block title %}{% trans "Review Financial Aid" %}{% endblock %} {% block extrahead %} <style> .btn { height: 34px; padding: 8px 18px; } </style> {% endblock %} {% block content %} {% include "header.html" %} <div class="page-content"> <div class="single-column" style="max-width: 1000px;"> <div class="blocks-sm-2"> <li> <h4 style="margin-top: 0;">Financial Aid Submissions</h4> </li> <!-- Filters --> <li> <div class="pull-right input-group"> <span class="input-group-addon" style="padding-top: 8px;">Show:</span> <select class="form-control" onchange="location = this.options[this.selectedIndex].value;"> {% for status, message in financial_aid_statuses %} <option value="{% url 'review_financial_aid' program_id=current_program_id status=status %}" {% if selected_status == status %}selected{% endif %}> {{ message }} </option> {% endfor %} </select> </div> </li> <!-- /Filters --> </div> <div style="background-color: #ffffff; font-size: 14px; padding: 20px;"> <ul class="blocks-sm-3"> <!-- Search bar --> <li> <div class="input-group"> <input type="text" id="search-query" class="form-control" placeholder="Search" value="{{ search_query }}" onkeydown="if (event.keyCode == 13) { financialAidReview.initiateSearch(); }"> <span class="input-group-btn"> <button class="btn btn-default" onclick="financialAidReview.initiateSearch();"> <span class="glyphicon glyphicon-search"></span> </button> </span> </div> </li> <!-- /Search bar --> <!-- Currency selection --> <li style="padding-top: 7px;"> <div class="radio-inline"> <label> <input type="radio" name="currency-selection" id="currency-selector-usd" onclick="financialAidReview.toggleCurrency('USD');" checked> USD </label> </div> <div class="radio-inline"> <label> <input type="radio" name="currency-selection" id="currency-selector-original" onclick="financialAidReview.toggleCurrency('local');"> Local Currency </label> </div> </li> <!-- /Currency selection --> <!-- Pagination buttons --> <li> <div class="pull-right"> <span style="color: #999999; margin-right: 12px; position: relative; top: 2px;"> Page {{ page_obj.number }} of {{ paginator.num_pages }} </span> <span> {% if page_obj.has_previous %} <a href="?page={{ page_obj.previous_page_number }}&sort_by={{ current_sort_field }}{% if search_query %}&search_query={{search_query}}{% endif %}" class="btn btn-default" style="padding: 8px 10px 8px 12px;"> <span class="glyphicon glyphicon-chevron-left" style="color: #000000;"></span> </a> {% else %} <button class="btn btn-default disabled" style="padding: 8px 10px 8px 12px;"> <span class="glyphicon glyphicon-chevron-left" style="color: #000000;"></span> </button> {% endif %} {% if page_obj.has_next %} <a href="?page={{ page_obj.next_page_number }}&sort_by={{ current_sort_field }}{% if search_query %}&search_query={{search_query}}{% endif %}" class="btn btn-default" style="padding: 8px 12px 8px 10px;"> <span class="glyphicon glyphicon-chevron-right" style="color: #000000;"></span> </a> {% else %} <button class="btn btn-default disabled" style="padding: 8px 12px 8px 10px;"> <span class="glyphicon glyphicon-chevron-right" style="color: #000000;"></span> </button> {% endif %} </span> </div> </li> <!-- /Pagination buttons --> </ul> <!-- Messages --> <div id="messages"></div> <!-- Message template --> <div id="message-template" class="alert alert-dismissible" style="display: none;"> <button class="close" data-dismiss="alert"><span>&times;</span></button> <span></span> </div> <!-- /Message template --> <!-- /Messages --> <!-- Financial aid application table --> <div class="table-responsive"> <table class="table"> <thead> <tr style="color: #999999;"> <th></th> <th style="font-weight: normal;"> {% include "common/sort_links.html" with field=sort_fields.last_name %} </th> <th style="font-weight: normal;"> {% include "common/sort_links.html" with field=sort_fields.reported_income %} </th> <th style="font-weight: normal;"> {% include "common/sort_links.html" with field=sort_fields.date_calculated %} </th> {% if selected_status == statuses.DOCS_SENT %} <th style="font-weight: normal;"> {% include "common/sort_links.html" with field=sort_fields.date_documents_sent %} </th> {% endif %} <th style="font-weight: normal; min-width: 104px;"> {% include "common/sort_links.html" with field=sort_fields.adjusted_cost %} </th> {% if selected_status == statuses.PENDING_MANUAL_APPROVAL or selected_status == statuses.APPROVED %} <th style="font-weight: normal;">Justification</th> {% endif %} {% if selected_status == statuses.PENDING_MANUAL_APPROVAL or selected_status == statuses.PENDING_DOCS or selected_status == statuses.DOCS_SENT %} <th style="font-weight: normal;">Actions</th> {% endif %} </tr> </thead> <tbody> {% for financial_aid in financial_aid_objects %} <!-- Financial aid application information --> <tr id="application-row-{{ financial_aid.id }}" class="alert-dismissible"> <!-- Profile picture --> <td> {% if financial_aid.user.profile.image %} <img src="{{ financial_aid.user.profile.image.url }}" {% else %} <img src="{% static 'images/avatar_default.png' %}" {% endif %} style="height: 35px; border-radius: 18px; border: 1px solid rgba(180, 180, 180, 0.5)"> </td> <!-- /Profile picture --> <!-- Name/location --> <td style="white-space: nowrap"> <span id="full-name-{{ financial_aid.id }}"> <b>{{ financial_aid.user.profile.first_name }} {{ financial_aid.user.profile.last_name }}</b> </span> <br> <small> {{ financial_aid.user.profile.city }}, <span class="country-code">{{ financial_aid.user.profile.country }}</span> </small> </td> <!-- /Name/location --> <!-- Income --> <td style="white-space: nowrap"> <span class="income-usd"><b>$</b>{{ financial_aid.income_usd|floatformat:0 }}</span> <span class="income-local" style="display: none;"> {{ financial_aid.original_income|floatformat:0 }} <b>{{ financial_aid.original_currency }}</b> </span> </td> <!-- /Income --> <!-- Date calculated --> <td>{{ financial_aid.created_on|date:"SHORT_DATE_FORMAT" }}</td> <!-- /Date calculated --> <!-- Date docs sent --> {% if selected_status == statuses.DOCS_SENT %} <td>{{ financial_aid.date_documents_sent|date:"SHORT_DATE_FORMAT" }}</td> {% endif %} <!-- /Date docs sent --> <!-- Adjusted cost --> <td> {% if selected_status == statuses.PENDING_MANUAL_APPROVAL %} <select id="tier-program-id-{{ financial_aid.id }}" class="form-control"> {% for tier_program in tier_programs %} <option value="{{ tier_program.id }}" {% if tier_program == financial_aid.tier_program %}selected{% endif %}> ${{ tier_program.adjusted_cost }} </option> {% endfor %} </select> {% else %} <input type="text" class="form-control" value="${{ financial_aid.adjusted_cost }}" disabled> {% endif %} </td> <!-- /Adjusted cost --> <!-- Justification --> {% if selected_status == statuses.PENDING_MANUAL_APPROVAL or selected_status == statuses.APPROVED %} <td> {% if selected_status == statuses.PENDING_MANUAL_APPROVAL %} <select id="justification-{{ financial_aid.id }}" class="form-control"> <option value="">--</option> {% for justification in justifications %} <option value="{{ justification }}"> {{ justification }} </option> {% endfor %} </select> {% else %} <input type="text" class="form-control" value="{{ financial_aid.justification|default_if_none:'--' }}" disabled> {% endif %} </td> {% endif %} <!-- /Justification --> <!-- Actions --> {% if selected_status == statuses.PENDING_MANUAL_APPROVAL or selected_status == statuses.PENDING_DOCS or selected_status == statuses.DOCS_SENT %} <td style="white-space: nowrap;"> <!-- Mark docs as received --> {% if selected_status == statuses.PENDING_DOCS or selected_status == statuses.DOCS_SENT %} <button class="btn btn-default mark-docs-as-received" style="color: #0074e1; padding-top: 7px;" onclick="financialAidReview.submitDocsReceived({{ financial_aid.id }}, '{% url 'financial_aid_action' financial_aid_id=financial_aid.id %}', '{{ statuses.PENDING_MANUAL_APPROVAL }}');"> Mark Docs Received </button> {% endif %} <!-- /Mark docs as received --> <!-- Submit approval --> {% if selected_status == statuses.PENDING_MANUAL_APPROVAL %} <button class="btn btn-default" style="color: #0074e1; padding-top: 7px;" onclick="financialAidReview.submitApproval({{ financial_aid.id }}, '{% url 'financial_aid_action' financial_aid_id=financial_aid.id %}', '{{ statuses.APPROVED }}');"> Save </button> {% endif %} <!-- /Submit approval --> <button class="btn btn-default" style="color: #0074e1;" onclick="financialAidReview.toggleEmailDisplay('{{ financial_aid.id }}');"> <span class="glyphicon glyphicon-envelope"></span> </button> </td> {% endif %} <td style="white-space: nowrap;"> <button class="btn btn-default" style="color: #0074e1; padding-top: 7px;" onclick="financialAidReview.actionReset({{ financial_aid.id }}, '{% url 'financial_aid_action' financial_aid_id=financial_aid.id %}', '{{ statuses.RESET }}');"> Reset </button> </td> <!-- /Actions --> </tr> <!-- /Financial aid application information --> <!-- Financial aid application email form --> {% if selected_status == statuses.PENDING_MANUAL_APPROVAL or selected_status == statuses.PENDING_DOCS or selected_status == statuses.DOCS_SENT %} <tr id="application-email-row-{{ financial_aid.id }}" style="display: none;"> <td colspan="9" style="border-top: 0;"> <form id="email-form-{{ financial_aid.id }}" class="email-form form-horizontal"> {% render_form email_serializer template_pack="rest_framework/horizontal" %} </form> <button class="btn btn-primary pull-right" onclick="financialAidReview.sendEmail({{ financial_aid.id }}, '{% url 'financial_aid_mail_api' financial_aid_id=financial_aid.id %}');">Send Email</button> <br> </td> </tr> {% endif %} <!-- /Financial aid application email form --> {% endfor %} </tbody> </table> </div> <!-- /Financial aid application table --> </div> </div> </div> {% include "faqs.html" %} {% include "footer.html" %} <script> window.CSRF_TOKEN = "{{ csrf_token }}"; window.BASE_PATH = "{{ request.path }}?sort_by={{ current_sort_field }}&search_query=" </script> {% load render_bundle %} {% render_bundle "financial_aid" %} {% endblock %}
{ "content_hash": "c5ea01a534395377d9c3acb891181438", "timestamp": "", "source": "github", "line_count": 288, "max_line_length": 210, "avg_line_length": 49.083333333333336, "alnum_prop": 0.4825268817204301, "repo_name": "mitodl/micromasters", "id": "ad87319437cc4903585b3a6a2e7699397970be69", "size": "14136", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "financialaid/templates/review_financial_aid.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "9764" }, { "name": "Dockerfile", "bytes": "958" }, { "name": "HTML", "bytes": "84519" }, { "name": "JavaScript", "bytes": "1462849" }, { "name": "Procfile", "bytes": "407" }, { "name": "Python", "bytes": "2098424" }, { "name": "SCSS", "bytes": "135082" }, { "name": "Shell", "bytes": "10764" } ], "symlink_target": "" }
namespace arangodb { namespace application_features { GreetingsFeaturePhase::GreetingsFeaturePhase(ApplicationServer& server, bool isClient) : ApplicationFeaturePhase(server, "GreetingsPhase") { setOptional(false); startsAfter<ConfigFeature>(); startsAfter<LoggerFeature>(); startsAfter<RandomFeature>(); startsAfter<ShellColorsFeature>(); startsAfter<VersionFeature>(); if (!isClient) { // These are server only features startsAfter<GreetingsFeature>(); startsAfter<LoggerBufferFeature>(); } } } // namespace application_features } // namespace arangodb
{ "content_hash": "c6111bad61ff02dd83b5fd006fff553a", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 86, "avg_line_length": 26.90909090909091, "alnum_prop": 0.7516891891891891, "repo_name": "fceller/arangodb", "id": "30150074964eecee2c030cc3b97e2b86f94303fe", "size": "1831", "binary": false, "copies": "1", "ref": "refs/heads/devel", "path": "lib/ApplicationFeatures/GreetingsFeaturePhase.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ada", "bytes": "89080" }, { "name": "AppleScript", "bytes": "1429" }, { "name": "Assembly", "bytes": "142084" }, { "name": "Batchfile", "bytes": "9073" }, { "name": "C", "bytes": "1938354" }, { "name": "C#", "bytes": "55625" }, { "name": "C++", "bytes": "79379178" }, { "name": "CLIPS", "bytes": "5291" }, { "name": "CMake", "bytes": "109718" }, { "name": "CSS", "bytes": "1341035" }, { "name": "CoffeeScript", "bytes": "94" }, { "name": "DIGITAL Command Language", "bytes": "27303" }, { "name": "Emacs Lisp", "bytes": "15477" }, { "name": "Go", "bytes": "1018005" }, { "name": "Groff", "bytes": "263567" }, { "name": "HTML", "bytes": "459886" }, { "name": "JavaScript", "bytes": "55446690" }, { "name": "LLVM", "bytes": "39361" }, { "name": "Lua", "bytes": "16189" }, { "name": "Makefile", "bytes": "178253" }, { "name": "Module Management System", "bytes": "1545" }, { "name": "NSIS", "bytes": "26909" }, { "name": "Objective-C", "bytes": "4430" }, { "name": "Objective-C++", "bytes": "1857" }, { "name": "Pascal", "bytes": "145262" }, { "name": "Perl", "bytes": "227308" }, { "name": "Protocol Buffer", "bytes": "5837" }, { "name": "Python", "bytes": "3563935" }, { "name": "Ruby", "bytes": "1000962" }, { "name": "SAS", "bytes": "1847" }, { "name": "Scheme", "bytes": "19885" }, { "name": "Shell", "bytes": "488846" }, { "name": "VimL", "bytes": "4075" }, { "name": "Yacc", "bytes": "36950" } ], "symlink_target": "" }
package com.geobeacondev.geobeacon; import java.util.ArrayList; import java.util.Collections; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import android.app.ActionBar; import android.app.ActionBar.Tab; import android.app.FragmentTransaction; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.database.Cursor; import android.media.AudioManager; import android.media.SoundPool; import android.os.Bundle; import android.provider.ContactsContract; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.ListView; import android.widget.TextView; public class ContactList extends FragmentActivity implements ActionBar.TabListener { private FragmentActivity a = this; private ViewPager viewPager; private TabsPagerAdapter mAdapter; private ActionBar actionBar; // Tab titles private String[] tabs = { "All", "Recent" }; private ArrayList<Contact> mContactList; private ArrayList<Contact> mSelectedContactList; private ArrayList<Contact> mPrevSelectedContactList; private ArrayList<Contact> mRecentContacts; private SharedPreferences mPrefs; private AllContactsAdapter mAllDataAdapter; private RecentContactsAdapter mRecentDataAdapter; private ListView allLV; private ListView recentLV; // Sound private SoundPool mSounds; private boolean mSoundOn; private int mClickSoundID; private static final String TAG = "GEOBEACON_CONTACT_LIST"; @Override protected void onCreate(Bundle savedInstanceState) { Log.d(TAG, "in onCreate"); super.onCreate(savedInstanceState); setContentView(R.layout.contact_list_contacts); // Initilization viewPager = (ViewPager) findViewById(R.id.pager); actionBar = getActionBar(); mAdapter = new TabsPagerAdapter(getSupportFragmentManager()); viewPager.setAdapter(mAdapter); actionBar.setHomeButtonEnabled(false); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Adding Tabs for (String tab_name : tabs) { actionBar.addTab(actionBar.newTab().setText(tab_name) .setTabListener(this)); } // on swiping the viewpager make respective tab selected viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageSelected(int position) { // on changing the page // make respected tab selected actionBar.setSelectedNavigationItem(position); } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageScrollStateChanged(int arg0) { } }); mPrefs = getSharedPreferences("ttt_prefs", Context.MODE_PRIVATE); // Get the selected contacts from the caller Intent intent = getIntent(); mPrevSelectedContactList = intent.getParcelableArrayListExtra("SELECTED_CONTACTS"); initRecentContacts(); } public void initializeAllContactsAdapter(ListView lv) { allLV = lv; initAllContacts(); mAllDataAdapter = new AllContactsAdapter(this, R.layout.contact_info, mContactList); allLV.setAdapter(mAllDataAdapter); } public void initializeRecentContactsAdapter(ListView lv) { recentLV = lv; mRecentDataAdapter = new RecentContactsAdapter(this, R.layout.contact_info, mRecentContacts); recentLV.setAdapter(mRecentDataAdapter); } @Override public void onResume() { super.onResume(); Log.d(TAG, "in on Resume"); createSoundPool(); } @Override public void onPause() { super.onPause(); Log.d(TAG, "in onPause"); if(mSounds != null) { mSounds.release(); mSounds = null; } } private void createSoundPool() { mSoundOn = mPrefs.getBoolean("sound", true); mSounds = new SoundPool(2, AudioManager.STREAM_MUSIC, 0); // 2 = maximum sounds to play at the same time, // AudioManager.STREAM_MUSIC is the stream type typically used for games // 0 is the "the sample-rate converter quality. Currently has no effect. Use 0 for the default." mClickSoundID = mSounds.load(this, R.raw.click, 1); } private void playSound(int soundID) { if (mSoundOn && mSounds != null) mSounds.play(soundID, 1, 1, 1, 0, 1); } @Override public void onDestroy() { super.onDestroy(); saveRecentContacts(); } @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { } @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { // on tab selected // show respected fragment view viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { } public void exitActivity(View v) { Log.d(TAG, "exitActivity"); playSound(mClickSoundID); updateSelectedContacts(); saveRecentContacts(); Intent returnIntent = new Intent(); returnIntent.putExtra("SELECTED_CONTACTS", mSelectedContactList); setResult(RESULT_OK, returnIntent); finish(); } public void sortContacts() { Collections.sort(mContactList); } private void clearRecentContacts() { boolean needsUpdate = false; for (Contact contact: mRecentContacts) { if (contact.selected) { Log.d(TAG, "contact " + contact.contactName + " was selected, clearing check in all contacts too"); needsUpdate = true; int i = mContactList.indexOf(contact); if (i != -1) { Log.d(TAG, "setting allcontacts[" + i + "] to " + false); mContactList.get(i).setSelected(false); } if (mPrevSelectedContactList != null) { i = mPrevSelectedContactList.indexOf(contact); if (i != -1) { Log.d(TAG, "removing selected contacts[" + i + "]"); mPrevSelectedContactList.remove(i); } } } } if (needsUpdate) { Log.d(TAG, "needs update, so we are updating"); mAllDataAdapter = new AllContactsAdapter(a, R.layout.contact_info, mContactList); allLV.setAdapter(mAllDataAdapter); } mRecentContacts.clear(); Gson gson = new Gson(); Editor prefsEditor = mPrefs.edit(); prefsEditor.remove("recentContacts"); prefsEditor.commit(); mRecentDataAdapter = new RecentContactsAdapter(a, R.layout.contact_info, mRecentContacts); recentLV.setAdapter(mRecentDataAdapter); } private void initRecentContacts() { Log.d(TAG, "in initRecentContacts, is mRecentContacts null? " + (mRecentContacts == null)); if (mRecentContacts != null) return; Gson gson = new Gson(); String recentJson = mPrefs.getString("recentContacts", ""); java.lang.reflect.Type listType = new TypeToken<ArrayList<Contact>>() {}.getType(); mRecentContacts = gson.fromJson(recentJson, listType); if (mRecentContacts == null) mRecentContacts = new ArrayList<Contact>(); for (Contact c: mRecentContacts) { Log.v(TAG, "initrec contact " + c.contactName + "is selected? " + c.isSelected()); } } private void saveRecentContacts() { if (mSelectedContactList == null) return; for (Contact c: mSelectedContactList) { if (!mRecentContacts.contains(c)) { mRecentContacts.add(0, c); } } for (Contact c: mRecentContacts) { c.selected = false; } Gson gson = new Gson(); String recentContactsJSON = gson.toJson(mRecentContacts); Editor prefsEditor = mPrefs.edit(); prefsEditor.putString("recentContacts", recentContactsJSON); prefsEditor.commit(); } public class AllContactsAdapter extends ArrayAdapter<Contact>{ private ArrayList<Contact> contactsList; public AllContactsAdapter(Context context, int textViewResourceId, ArrayList<Contact> contactsList){ super(context, textViewResourceId, contactsList); this.contactsList = new ArrayList<Contact>(); this.contactsList.addAll(contactsList); } public class ViewHolder { TextView phoneNo; CheckBox name; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = new ViewHolder(); if (convertView == null) { LayoutInflater vi = (LayoutInflater)getSystemService( Context.LAYOUT_INFLATER_SERVICE); convertView = vi.inflate(R.layout.contact_info, null); holder.phoneNo = (TextView) convertView.findViewById(R.id.code); holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1); final CheckBox fcb = holder.name; convertView.setTag(holder); holder.name.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { CheckBox cb = (CheckBox)(v); Contact contact = (Contact) cb.getTag(); boolean value = cb.isChecked(); contact.setSelected(value); String s = value ? "checking" : "unchecking"; Log.d(TAG, s + " " + contact.contactName); int i = mRecentContacts.indexOf(contact); if (i != -1) { Log.d(TAG, "setting recentcontacts[" + i + "] to " + value); mRecentContacts.get(i).setSelected(value); } else { mRecentContacts.add(0, contact); } if (mPrevSelectedContactList != null) { i = mPrevSelectedContactList.indexOf(contact); if (i != -1) { Log.d(TAG, "removing selected contacts[" + i + "]"); mPrevSelectedContactList.remove(i); } } mRecentDataAdapter = new RecentContactsAdapter(a, R.layout.contact_info, mRecentContacts); recentLV.setAdapter(mRecentDataAdapter); } }); holder.phoneNo.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { CheckBox cb = fcb; Contact contact = (Contact) cb.getTag(); cb.setChecked(!cb.isChecked()); boolean value = cb.isChecked(); String s = value ? "checking" : "unchecking"; Log.d(TAG, s + " " + contact.contactName); contact.setSelected(value); int i = mRecentContacts.indexOf(contact); if (i != -1) { Log.d(TAG, "setting recentcontacts[" + i + "] to " + value); mRecentContacts.get(i).setSelected(value); } else { mRecentContacts.add(0, contact); } if (mPrevSelectedContactList != null) { i = mPrevSelectedContactList.indexOf(contact); if (i != -1) { Log.d(TAG, "removing selected contacts[" + i + "]"); mPrevSelectedContactList.remove(i); } } saveRecentContacts(); mRecentDataAdapter = new RecentContactsAdapter(a, R.layout.contact_info, mRecentContacts); recentLV.setAdapter(mRecentDataAdapter); } }); } else { holder = (ViewHolder) convertView.getTag(); } Contact contact = contactsList.get(position); Log.d(TAG, "all contact " + contact.contactName + " is selected? " + contact.isSelected()); if (mPrevSelectedContactList != null && mPrevSelectedContactList.contains(contact)) contact.setSelected(true); holder.phoneNo.setText(contact.getPhoneNo()); holder.name.setText(contact.getName()); holder.name.setChecked(contact.isSelected()); holder.name.setTag(contact); return convertView; } } public class RecentContactsAdapter extends ArrayAdapter<Contact>{ private ArrayList<Contact> contactsList; public RecentContactsAdapter(Context context, int textViewResourceId, ArrayList<Contact> contactsList){ super(context, textViewResourceId, contactsList); this.contactsList = new ArrayList<Contact>(); this.contactsList.addAll(contactsList); } public class ViewHolder { TextView phoneNo; CheckBox name; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = new ViewHolder(); if (convertView == null) { LayoutInflater vi = (LayoutInflater)getSystemService( Context.LAYOUT_INFLATER_SERVICE); convertView = vi.inflate(R.layout.contact_info, null); holder.phoneNo = (TextView) convertView.findViewById(R.id.code); holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1); final CheckBox fcb = holder.name; convertView.setTag(holder); holder.name.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { CheckBox cb = (CheckBox)(v); Contact contact = (Contact) cb.getTag(); boolean value = cb.isChecked(); String s = value ? "checking" : "unchecking"; Log.d(TAG, s + " " + contact.contactName); contact.setSelected(value); int i = mContactList.indexOf(contact); if (i != -1) { Log.d(TAG, "setting allcontacts[" + i + "] to " + value); mContactList.get(i).setSelected(value); mAllDataAdapter = new AllContactsAdapter(a, R.layout.contact_info, mContactList); allLV.setAdapter(mAllDataAdapter); } if (mPrevSelectedContactList != null) { i = mPrevSelectedContactList.indexOf(contact); if (i != -1) { Log.d(TAG, "removing selected contacts[" + i + "]"); mPrevSelectedContactList.remove(i); } } } }); holder.phoneNo.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { CheckBox cb = fcb; Contact contact = (Contact) cb.getTag(); cb.setChecked(!cb.isChecked()); boolean value = cb.isChecked(); String s = value ? "checking" : "unchecking"; Log.d(TAG, s + " " + contact.contactName); contact.setSelected(value); int i = mContactList.indexOf(contact); if (i != -1) { Log.d(TAG, "setting allcontacts[" + i + "] to " + value); mContactList.get(i).setSelected(value); mAllDataAdapter = new AllContactsAdapter(a, R.layout.contact_info, mContactList); allLV.setAdapter(mAllDataAdapter); } if (mPrevSelectedContactList != null) { i = mPrevSelectedContactList.indexOf(contact); if (i != -1) { Log.d(TAG, "removing selected contacts[" + i + "]"); mPrevSelectedContactList.remove(i); } } } }); } else { holder = (ViewHolder) convertView.getTag(); } Contact contact = contactsList.get(position); Log.d(TAG, "recent contact " + contact.contactName + " is selected? " + contact.isSelected()); if (mPrevSelectedContactList != null && mPrevSelectedContactList.contains(contact)) contact.setSelected(true); holder.phoneNo.setText(contact.getPhoneNo()); holder.name.setText(contact.getName()); holder.name.setChecked(contact.isSelected()); holder.name.setTag(contact); Log.d(TAG, "recent contact " + contact.contactName + "'s box is checked? " + holder.name.isChecked()); return convertView; } } private void initAllContacts(){ Log.d(TAG, "IN INIT ALL CONTACTS "); ArrayList<Contact> contacts = new ArrayList<Contact>(); ContentResolver cr = getContentResolver(); Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); if (cur.getCount() > 0) { while (cur.moveToNext()) { String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID)); String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) { Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{id}, null); while (pCur.moveToNext()) { int phoneType = pCur.getInt(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE)); String phoneNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); Contact contact = new Contact(phoneNumber, name, false); // if (mPrevSelectedContactList != null && mPrevSelectedContactList.contains(contact)) // contact.setSelected(true); contacts.add(contact); } pCur.close(); } } } mContactList = contacts; sortContacts(); } public void updateSelectedContacts(){ Log.d(TAG, "in init selected contacts"); mSelectedContactList = new ArrayList<Contact>(); for (Contact c: mContactList) { Log.d(TAG, "all contact " + c.contactName + " is selected? " + (c.isSelected())); if (c.isSelected() && !mSelectedContactList.contains(c)) mSelectedContactList.add(c); } for (Contact c: mRecentContacts) { Log.d(TAG, "recent contact " + c.contactName + " is selected? " + (c.isSelected())); if (c.isSelected() && !mSelectedContactList.contains(c)) mSelectedContactList.add(c); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.contact_list, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. switch (item.getItemId()){ case R.id.action_clear: clearRecentContacts(); return true; } return false; } }
{ "content_hash": "de8433bf909d3ca6786497811a8f8205", "timestamp": "", "source": "github", "line_count": 526, "max_line_length": 110, "avg_line_length": 32.68821292775665, "alnum_prop": 0.6977433988600674, "repo_name": "lijeffreytli/GeoBeacon", "id": "45f96e637e919705fbbbb5c08f4b6baca53e5221", "size": "17194", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/geobeacondev/geobeacon/ContactList.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9356" }, { "name": "HTML", "bytes": "3982" }, { "name": "Java", "bytes": "91312" } ], "symlink_target": "" }
import React from 'react'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import PropTypes from 'prop-types'; const propTypes = { children: PropTypes.array.isRequired, }; const muiTheme = getMuiTheme({ palette: { primary1Color: '#1E88E5', accent1Color: '#FFC107', }, }); function AppWrapper(props) { return ( <MuiThemeProvider muiTheme={muiTheme}> <div style={{ height: '100%' }}> {props.children} </div> </MuiThemeProvider> ); } AppWrapper.propTypes = propTypes; export default AppWrapper;
{ "content_hash": "7dd42d7bf2579546af93bd87261de30e", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 67, "avg_line_length": 21.413793103448278, "alnum_prop": 0.6908212560386473, "repo_name": "yanhao-li/menu-plus", "id": "7072c009ddb6208b0f2f3ba38d9fb39a293f6229", "size": "621", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "client/app/components/App/AppWrapper.js", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1787" }, { "name": "HTML", "bytes": "9748" }, { "name": "JavaScript", "bytes": "156665" }, { "name": "Shell", "bytes": "85" } ], "symlink_target": "" }
@interface AppDelegate : NSObject <NSApplicationDelegate> @property (assign) IBOutlet NSWindow *window; @end
{ "content_hash": "885f344a5525956f6cfb276e501ad71c", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 57, "avg_line_length": 22.2, "alnum_prop": 0.7927927927927928, "repo_name": "abarisain/iBooster", "id": "faee49b5b084a162a0fc35805bb94978a0805551", "size": "298", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Mac/dBooster/AppDelegate.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "733" }, { "name": "JavaScript", "bytes": "11667" }, { "name": "Objective-C", "bytes": "793963" } ], "symlink_target": "" }
namespace diagnostic_msgs { static const char SELFTEST[] = "diagnostic_msgs/SelfTest"; class SelfTestRequest : public ros::Msg { public: SelfTestRequest() { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; return offset; } const char * getType(){ return SELFTEST; }; const char * getMD5(){ return "d41d8cd98f00b204e9800998ecf8427e"; }; }; class SelfTestResponse : public ros::Msg { public: const char* id; int8_t passed; uint8_t status_length; diagnostic_msgs::DiagnosticStatus st_status; diagnostic_msgs::DiagnosticStatus * status; SelfTestResponse(): id(""), passed(0), status_length(0), status(NULL) { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; uint32_t length_id = strlen(this->id); memcpy(outbuffer + offset, &length_id, sizeof(uint32_t)); offset += 4; memcpy(outbuffer + offset, this->id, length_id); offset += length_id; union { int8_t real; uint8_t base; } u_passed; u_passed.real = this->passed; *(outbuffer + offset + 0) = (u_passed.base >> (8 * 0)) & 0xFF; offset += sizeof(this->passed); *(outbuffer + offset++) = status_length; *(outbuffer + offset++) = 0; *(outbuffer + offset++) = 0; *(outbuffer + offset++) = 0; for( uint8_t i = 0; i < status_length; i++){ offset += this->status[i].serialize(outbuffer + offset); } return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; uint32_t length_id; memcpy(&length_id, (inbuffer + offset), sizeof(uint32_t)); offset += 4; for(unsigned int k= offset; k< offset+length_id; ++k){ inbuffer[k-1]=inbuffer[k]; } inbuffer[offset+length_id-1]=0; this->id = (char *)(inbuffer + offset-1); offset += length_id; union { int8_t real; uint8_t base; } u_passed; u_passed.base = 0; u_passed.base |= ((uint8_t) (*(inbuffer + offset + 0))) << (8 * 0); this->passed = u_passed.real; offset += sizeof(this->passed); uint8_t status_lengthT = *(inbuffer + offset++); if(status_lengthT > status_length) this->status = (diagnostic_msgs::DiagnosticStatus*)realloc(this->status, status_lengthT * sizeof(diagnostic_msgs::DiagnosticStatus)); offset += 3; status_length = status_lengthT; for( uint8_t i = 0; i < status_length; i++){ offset += this->st_status.deserialize(inbuffer + offset); memcpy( &(this->status[i]), &(this->st_status), sizeof(diagnostic_msgs::DiagnosticStatus)); } return offset; } const char * getType(){ return SELFTEST; }; const char * getMD5(){ return "ac21b1bab7ab17546986536c22eb34e9"; }; }; class SelfTest { public: typedef SelfTestRequest Request; typedef SelfTestResponse Response; }; } #endif
{ "content_hash": "2658a21661f07ce55be6d793e37d02e3", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 141, "avg_line_length": 27.06896551724138, "alnum_prop": 0.5853503184713376, "repo_name": "gKouros/my_arduino_sketches", "id": "50b599d46a4851a84833559b31a801cf4fa2d1d7", "size": "3332", "binary": false, "copies": "22", "ref": "refs/heads/master", "path": "libraries/ros_lib/diagnostic_msgs/SelfTest.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Arduino", "bytes": "7782" }, { "name": "C", "bytes": "3137" }, { "name": "C++", "bytes": "1401029" }, { "name": "Processing", "bytes": "20189" }, { "name": "Python", "bytes": "422" } ], "symlink_target": "" }
<?php /** * ExhibitPage model. * * @package ExhibitBuilder */ class ExhibitPage extends Omeka_Record_AbstractRecord { /** * ID of parent page, if any * * @var integer */ public $parent_id; /** * ID of the exhibit this page is in * * @var integer */ public $exhibit_id; /** * URL slug for this page * * @var string */ public $slug; /** * Title for the page * * @var string */ public $title; /** * Order of the page underneath its parent/exhibit * * @var integer */ public $order; /** * Related record linkages. * * @var array */ protected $_related = array('ExhibitPageBlocks' => 'getPageBlocks'); /** * Whether to automatically shift the page's children up a level when the page is deleted. * * @var boolean */ private $_fixChildrenOnDelete = true; /** * Define mixins. * * @see Mixin_Slug * @see Mixin_Search */ public function _initializeMixins() { $this->_mixins[] = new Mixin_Slug($this, array( 'parentFields' => array('exhibit_id', 'parent_id'), 'slugEmptyErrorMessage' => __('A slug must be given for each page of an exhibit.'), 'slugLengthErrorMessage' => __('A slug must be 30 characters or less.'), 'slugUniqueErrorMessage' => __('This page slug has already been used. Please modify the slug so that it is unique.'))); $this->_mixins[] = new Mixin_Search($this); } /** * In order to validate an exhibit must have a title. */ protected function _validate() { if (!strlen($this->title)) { $this->addError('title', __('Exhibit pages must be given a title.')); } } /** * After save callback. * * Update block data and search data after saving. * * @var array $args */ protected function afterSave($args) { if ($args['post']) { $post = $args['post']; if (!empty($post['blocks'])) { $this->setPageBlocks($post['blocks']); } else { $this->setPageBlocks(array()); } } foreach ($this->getPageBlocks() as $block) { $this->addSearchText($block->text); foreach ($block->getAttachments() as $attachment) { $this->addSearchText($attachment->caption); } } $exhibit = $this->getExhibit(); if (!$exhibit->public) { $this->setSearchTextPrivate(); } $this->setSearchTextTitle($this->title); $this->addSearchText($this->title); } /** * Get the previous page. * * @return ExhibitPage */ public function previous() { return $this->getDb()->getTable('ExhibitPage')->findPrevious($this); } /** * Get the next page. * * @return ExhibitPage */ public function next() { return $this->getDb()->getTable('ExhibitPage')->findNext($this); } /** * Get the next page, preferring to step down to this page's children first. * * @return ExhibitPage */ public function firstChildOrNext() { if($firstChild = $this->getFirstChildPage()) { return $firstChild; } else { //see if there's a next page on the same level $next = $this->next(); if($next) { return $next; } // no next on same level, so bump up one level and go to next page // keep going up until we hit the top $current = $this; while (($current = $current->getParent())) { if (($parentNext = $current->next())) { return $parentNext; } } } } /** * Get the previous page, or this page's parent if there are none. * * @return ExhibitPage */ public function previousOrParent() { $previous = $this->previous(); if($previous) { while (($lastChild = $previous->getLastChildPage())) { $previous = $lastChild; } return $previous; } else { $parent = $this->getParent(); if($parent) { return $parent; } } } /** * Get this page's parent. * * @return ExhibitPage */ public function getParent() { return $this->getTable()->find($this->parent_id); } /** * Get all this page's children. * * @return ExhibitPage[] */ public function getChildPages() { return $this->getTable()->findBy(array('parent'=>$this->id, 'sort_field'=>'order')); } /** * Get this page's first child. * * @return ExhibitPage */ public function getFirstChildPage() { return $this->getTable()->findEndChild($this, 'first'); } /** * Get this page's last child. * * @return ExhibitPage */ public function getLastChildPage() { return $this->getTable()->findEndChild($this, 'last'); } /** * Count the number of child pages for this page. * * @return integer */ public function countChildPages() { return $this->getTable()->count(array('parent'=>$this->id)); } /** * Get the ancestors of this page. * * @return ExhibitPage[] */ public function getAncestors() { $ancestors = array(); $page = $this; while ($page->parent_id) { $page = $page->getParent(); $ancestors[] = $page; } $ancestors = array_reverse($ancestors); return $ancestors; } /** * Get this page's owning exhibit. * * @return Exhibit */ public function getExhibit() { return $this->getTable('Exhibit')->find($this->exhibit_id); } /** * Delete owned blocks when deleting the page. * * Also, move childen of the page up a level in the hierarchy. */ protected function _delete() { if ($this->ExhibitPageBlocks) { foreach ($this->ExhibitPageBlocks as $block) { $block->delete(); } } if (!$this->_fixChildrenOnDelete) { return; } //bump all child pages up to being children of the parent $childPages = $this->getChildPages(); foreach($childPages as $child) { if($this->parent_id) { $child->parent_id = $this->parent_id; } else { $child->parent_id = NULL; } $child->save(); } } /** * Get all blocks for this page. * * @return ExhibitPageBlock[] */ public function getPageBlocks() { return $this->getTable('ExhibitPageBlock')->findByPage($this); } /** * Get all attachments for all this page's blocks. * * @return ExhibitBlockAttachment[] */ public function getAllAttachments() { return $this->getTable('ExhibitBlockAttachment')->findByPage($this); } /** * Set data for this page's blocks. * * @param array $blocksData An array of key-value arrays for each block. * @param boolean $deleteExtras Whether to delete any extra preexisting * blocks. */ public function setPageBlocks($blocksData, $deleteExtras = true) { $existingBlocks = $this->getPageBlocks(); foreach ($blocksData as $i => $blockData) { if (!empty($existingBlocks)) { $block = array_pop($existingBlocks); } else { $block = new ExhibitPageBlock; $block->page_id = $this->id; } $block->order = $i; $block->setData($blockData); $block->save(); } // Any leftover blocks beyond the new data get erased. if ($deleteExtras) { foreach ($existingBlocks as $extraBlock) { $extraBlock->delete(); } } } /** * Get the URL to this page, with the specified action. * * @param string $action The action to link to * @return string */ public function getRecordUrl($action = 'show') { if ('show' == $action) { return exhibit_builder_exhibit_uri($this->getExhibit(), $this); } return array('module' => 'exhibit-builder', 'controller' => 'exhibits', 'action' => $action, 'id' => $this->id); } /** * Set whether to automatically shift the page's children up a level when the page is deleted. * * @param boolean $fix */ public function setFixChildrenOnDelete($fix) { $this->_fixChildrenOnDelete = (bool) $fix; } }
{ "content_hash": "4a09aeb52b658b142f41a684676e11ed", "timestamp": "", "source": "github", "line_count": 367, "max_line_length": 132, "avg_line_length": 24.653950953678475, "alnum_prop": 0.5108311229000884, "repo_name": "jbfink/docker-omeka", "id": "81e32f55735c025fae6ee2ce18478dd7ee1cfa02", "size": "9207", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "omeka/omeka-2.4.1/plugins/ExhibitBuilder/models/ExhibitPage.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1702" }, { "name": "Batchfile", "bytes": "1036" }, { "name": "CSS", "bytes": "353082" }, { "name": "HTML", "bytes": "4259" }, { "name": "JavaScript", "bytes": "82133" }, { "name": "PHP", "bytes": "19884720" }, { "name": "PowerShell", "bytes": "1028" }, { "name": "Shell", "bytes": "727" }, { "name": "XSLT", "bytes": "6298" } ], "symlink_target": "" }
$packageName = 'disksmartview' $url = 'http://www.nirsoft.net/utils/disksmartview.zip' $checksum = '8d10b7f4c8b60a39e33f28dc45782f734ce4af84bac33945251786c0c361f9dd' $checksumType = 'sha256' $toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)" $installFile = Join-Path $toolsDir "$($packageName).exe" Install-ChocolateyZipPackage -PackageName "$packageName" ` -Url "$url" ` -UnzipLocation "$toolsDir" ` -Checksum "$checksum" ` -ChecksumType "$checksumType" Set-Content -Path ("$installFile.gui") ` -Value $null
{ "content_hash": "5aa20ce5abe9f427b829a75f52e3fb9f", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 78, "avg_line_length": 43.93333333333333, "alnum_prop": 0.6115326251896813, "repo_name": "dtgm/chocolatey-packages", "id": "dbe72866bc6e6f38335c6905947e9ce46e564670", "size": "661", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "automatic/_output/disksmartview/1.21/tools/chocolateyInstall.ps1", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AutoHotkey", "bytes": "347616" }, { "name": "AutoIt", "bytes": "13530" }, { "name": "Batchfile", "bytes": "1404" }, { "name": "C#", "bytes": "8134" }, { "name": "HTML", "bytes": "80818" }, { "name": "PowerShell", "bytes": "13124493" } ], "symlink_target": "" }
<?php namespace App\Controller; use App\DataTable\DataTableModel; use App\DataTable\DataTableResponseFactory; use App\DataTable\Response\SectionListResponse; use App\Entity\Section; use App\Enum\SectionVoterEnum; use App\Enum\UserRoleEnum; use App\Form\SectionType; use App\Repository\CityRepository; use App\Repository\SectionRepository; use Doctrine\Common\Persistence\ObjectManager; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use Symfony\Contracts\Translation\TranslatorInterface; /** * @Route("/admin/sections") */ class SectionController extends BaseController { /** * @Route("", name="section_index") * @Security("has_role('ROLE_ADMIN')") */ public function index(CityRepository $cityRepo): Response { return $this->render('Section/index.html.twig', [ 'cities' => $cityRepo->findBy([], ['name' => 'asc']), ]); } /** * @Route( * "/list_sections", * name="section_list", * options={"expose" : true}, * methods={"GET"}, * condition="request.isXmlHttpRequest()" * ) * @Security("has_role('ROLE_ADMIN')") */ public function getListSections( Request $request, SectionRepository $sectionRepo, DataTableResponseFactory $responseFactory ): JsonResponse { $dataTableColumns = new DataTableModel($request); $response = [ 'draw' => $dataTableColumns->getDraw(), 'recordsFiltered' => $sectionRepo->getNbSections($dataTableColumns->getSearch()), 'data' => $responseFactory->getResponse( SectionListResponse::class, $sectionRepo->getListInfo($dataTableColumns) ), ]; return new JSonResponse($response); } /** * @Route("/new", name="section_new", methods={"GET", "POST"}) * @Security("has_role('ROLE_ADMIN')") * * @return RedirectResponse|Response */ public function new(ObjectManager $om, TranslatorInterface $translator, Request $request): Response { $section = new Section(); $form = $this->createForm(SectionType::class, $section); $form->handleRequest($request); if ($form->isSubmitted()) { if ($form->isValid()) { $om->persist($section); $om->flush(); $this->addFlash('success', $translator->trans('section.flash.saved', [], 'admin')); return $this->redirectToRoute('section_index'); } $this->addFlash('error', $translator->trans('section.flash.error', [], 'admin')); } return $this->render('Section/new.html.twig', [ 'section' => $section, 'form' => $form->createView(), ]); } /** * @Route("/{id}/edit", name="section_edit", methods={"GET", "POST"}) */ public function edit( ObjectManager $om, Request $request, TranslatorInterface $translator, Section $section ): Response { $this->denyAccessUnlessGranted(SectionVoterEnum::EDIT, $section); $editForm = $this->createForm(SectionType::class, $section); $editForm->handleRequest($request); if ($editForm->isSubmitted()) { if ($editForm->isValid()) { $om->persist($section); $om->flush(); $this->addFlash('success', $translator->trans('section.flash.updated')); $redirect = ($this->isGranted(UserRoleEnum::ROLE_ADMIN)) ? $this->redirectToRoute('section_index') : $this->redirectToRoute('section_edit', ['id' => $section->getId()]); return $redirect; } $this->addFlash('error', $translator->trans('section.flash.errors')); } return $this->render('Section/edit.html.twig', [ 'section' => $section, 'edit_form' => $editForm->createView(), 'id' => $section->getId(), ]); } }
{ "content_hash": "2a1cfe9b01a4b276eb740dd04dacf959", "timestamp": "", "source": "github", "line_count": 132, "max_line_length": 103, "avg_line_length": 32.60606060606061, "alnum_prop": 0.5885223048327137, "repo_name": "ESNFranceG33kTeam/sf_buddysystem", "id": "e5bf0cc7b5a6fe053fd99e4f8a451a041325d7a8", "size": "4304", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Controller/SectionController.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "34292" }, { "name": "Dockerfile", "bytes": "2237" }, { "name": "Gherkin", "bytes": "40524" }, { "name": "HTML", "bytes": "315665" }, { "name": "JavaScript", "bytes": "48634" }, { "name": "Makefile", "bytes": "7945" }, { "name": "PHP", "bytes": "486247" }, { "name": "TSQL", "bytes": "15129" } ], "symlink_target": "" }
namespace OKHOSTING.Code.Templates { public class GenericModuleTemplate : Template { public GenericModuleTemplate() { } } }
{ "content_hash": "5dbf313abe68c6e26e8699132fc5c461", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 46, "avg_line_length": 14.777777777777779, "alnum_prop": 0.7368421052631579, "repo_name": "okhosting/OKHOSTING.Code", "id": "3b302c3ffd69fc996b1d5e38e0733745defed114", "size": "135", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Standard/OKHOSTING.Code/Templates/GenericModuleTemplate.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "112996" }, { "name": "PowerShell", "bytes": "3633" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>It has been since 1971 and is fed by natural feeds &middot; Verily</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="robots" content="noindex,nofollow"> <!-- FB open graph tags --> <meta property="og:site_name" content="Verily"/> <meta property="og:url" content="https://veri.ly/crisis/1/question/11/answer/12" /> <meta property="og:image" content="https://efe8ea3fb0a1c1b.s3.amazonaws.com/images/verily-v-logo.png"/> <meta property="og:title" content="It has been since 1971 and is fed by natural feeds "/> <meta property="og:description" content="We live in the Information Age... or the Disinformation Age. Finding out the truth in the vast amount of contradictory information is becoming increasingly difficult for everyone. Join the Verily Challenge to search for the truth."/> <!-- Latest compiled and minified Bootstrap CSS --> <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <!-- TODO Use bower and modify Bootstrap to our needs --> <link href="https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Abril+Fatface|Cinzel+Decorative:900" rel="stylesheet" type="text/css"> <link rel="shortcut icon" href="../../../../../static/images/favicon.png"> <link rel="apple-touch-icon-precomposed" href="../../../../../static/images/favicon.png" > <link href="../../../../../static/css/style.css" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/plug-ins/be7019ee387/integration/bootstrap/3/dataTables.bootstrap.css"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <![endif]--> <!-- jQuery --> <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script> <!-- Jquery Datatable --> <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.0/js/jquery.dataTables.min.js"></script> <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/plug-ins/be7019ee387/integration/bootstrap/3/dataTables.bootstrap.js"></script> <!-- Common JS --> <script type="text/javascript" src="../../../../../static/js/common.js"></script> <!-- Latest compiled and minified Bootstrap JavaScript --> <script src="https://netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <!-- Load general functions JS --> <script type="text/javascript" src="../../../../../static/js/load.js"></script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-52527080-1', 'auto'); ga('require', 'displayfeatures'); ga('send', 'pageview'); </script> <script type="text/javascript"> var sc_project=9897798; var sc_invisible=1; var sc_security="741aa466"; var scJsHost = (("https:" == document.location.protocol) ? "https://secure." : "http://www."); document.write("<sc"+"ript type='text/javascript' src='" + scJsHost+ "statcounter.com/counter/counter.js'></"+"script>"); </script> </head> <body class=""> <!-- provisional user confirm login modal --> <div class="modal fade" id="provisionalUserConfirmLoginModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button> <h4 class="modal-title" id="myModalLabel">Are you sure you want to withdraw from <strong>user-185179dc</strong>?</h4> </div> <div class="modal-body"> Submissions made under your provisional username, <strong>user-185179dc</strong>, will be lost if you log in now. To transfer your content, <a href="../../../../../register/index.html">sign up</a>. </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button> <a href="../../../../../login%3Fvia=%252Flogout.html" type="button" class="btn btn-danger">Withdraw and log in</a> </div> </div> </div> </div> <!-- / provisional user confirm login modal --> <div id="login-register" class="modal auth-modal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <div class="login-aside-button text-center"> <a href="../../../../../auth/facebook.html" class="btn btn-default btn-lg facebook-button"><i class="fa fa-facebook"></i> Login with Facebook</a> </div> <div class="row"> <div class="col-sm-6"> <p class="lead"> Login </p> <form class="login-form" role="form" action="../../../../../user.html" method="POST" novalidate> <input type="hidden" name="_csrf" value="snpizaE8yCZQKXLiLfZK1DxpsNkTe79+Byq2g=" /> <!-- <input type="hidden" name="_method" value="POST"> <input type="hidden" id="form-question-type" name="type"> --> <div class="form-group" > <input type="email" class="form-control input-lg form-email" name="email" placeholder="Email" tabindex="1"> </div> <div class="form-group"> <input type="password" class="form-control input-lg form-password" name="password" placeholder="Password" tabindex="2"> </div> <div class="form-group"> <label> <input type="checkbox" id="form-transfer-from-provisional" name="transferFromProvisional" checked value="true"> Associate content posted as a guest user under user-185179dc with this account. </label> </div> <div> <a href="../../../../../forgot.html">Forgot Password</a> </div> <button type="submit" class="btn btn-primary btn-lg pull-right centre-when-viewport-narrowed" id="login-button">Login</button> </form> <script type="text/javascript"> var loginForm = $('.login-form'); loginForm.on('submit', function(e) { var valid = true; var message; var formSubmitted = $(e.currentTarget); var loginAlert = formSubmitted.find('.login-alert') if (formSubmitted.find('.form-email').val() === '' || formSubmitted.find('.form-password').val() === '') { valid = false; message = 'Enter your login details.'; } if (valid) { // Whole form is valid, submit form to endpoint return; } else { // The form is not valid, don't submit form. e.preventDefault(); loginAlert.text(message); loginAlert.css('display', 'block'); } }) </script> </div> <div class="col-sm-6"> <p class="lead"> Signup </p> <form id="signup" role="form" action="../../../../../user.html" method="POST"> <input type="hidden" name="_csrf" value="snpizaE8yCZQKXLiLfZK1DxpsNkTe79+Byq2g=" /> <!-- <input type="hidden" name="_method" value="POST"> <input type="hidden" id="form-question-type" name="type"> --> <div class="form-group"> <input type="email" class="form-control input-lg" id="form-email" name="email" placeholder="Email"> </div> <div class="form-group"> <input type="text" class="form-control input-lg" id="form-name" name="name" placeholder="Choose a username"> </div> <div class="form-group"> <input type="password" class="form-control input-lg" id="form-password" name="password" placeholder="Create a password"> </div> <div class="form-group"> <input type="password" class="form-control input-lg" id="form-verifyPassword" name="verifyPassword" placeholder="Enter password again"> </div> <div class="form-group"> <label> <input type="checkbox" id="terms-agreement" name="termsAgreement"> I agree with the <a href="../../../../../terms.html" target="_blank">Terms and Conditions</a>. </label> </div> <button type="submit" class="btn btn-primary btn-lg pull-right" id="submit-button">Signup with Email</button> <div class="form-group"> <label> <input type="checkbox" id="form-transfer-from-provisional" name="transferFromProvisional" checked value="true"> Associate content posted as a guest user under user-185179dc with the new account. </label> </div> <b>IMPORTANT :</b> This website is part of an academic research project at the University of Southampton (Ethics reference number: ERGO/FPSE/10709). Your data will be used only for academic research purposes and it will be treated in accordance to the UK Data Protection Act 1998. Full details in our <a href="../../../../../terms.html" target="_blank">Terms and Conditions</a>. </form> </div> </div> </div> <div class="modal-footer"> <a class="btn btn-default" data-dismiss="modal">Cancel</a> </div> </div> </div> </div> <div id="alert-window" style="display:none; position:fixed;" class="alert alert-warning alert-dismissable"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <h4 class="alert-title"></h4> <span class="alert-message"></span> </div> <a href="12.html#content" class="sr-only">Skip to main content</a> <nav class="navbar navbar-default" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#vly-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand active logo " href="../../../../../index.html" title="Home"> <span class="first-char">V</span>erily </a> <ul class="nav navbar-nav pull-right"> <li> <a href="../../../../../user.html" class="username" title="provisional username"> <i class="fa fa-ticket"></i> user-185179dc </a> </li> </ul> </div> <div class="collapse navbar-collapse" id="vly-navbar-collapse-1"> <ul class="nav navbar-nav"> <li><a href="../../../../1.html">All questions</a></li> <li> <form action="https://veri.ly/search" method="POST" class="navbar-form nav-search"> <input type="hidden" name="_csrf" value="snpizaE8yCZQKXLiLfZK1DxpsNkTe79+Byq2g=" /> <div class="input-group"> <input type="search" class="form-control" name="search" id="search" data-placeholder="Search Questions"> <span class="input-group-btn"> <button class="btn btn-default" type="submit"><i class="fa fa-search"></i></button> </span> </div> </form> </li> <script> $('#search').focus(function(e) { var headerWidth = $('.navbar-header').css('width'); var searchBoxWidth = $('.nav-search .input-group').css('width'); $('#search').attr('placeholder', $('#search').data('placeholder')); $('.nav-search button').toggleClass('focused'); if (headerWidth !== searchBoxWidth) { // search box is not full viewport width, // so not on mobile or xs devices. $('.nav-search .input-group').width('20vw'); } }); $('#search').blur(function(e) { $('#search').attr('placeholder', ''); $('.nav-search button').toggleClass('focused'); if (!e.relatedTarget || e.relatedTarget.nodeName != 'BUTTON') { $('.nav-search .input-group').removeAttr('style'); } }); </script> </ul> <ul class="nav navbar-nav pull-right"> <li> <a href="../../../../../register/index.html"> Signup </a> </li> <li><a href="../../../../../user.html">Login</a></li> </ul> </div> </div> </nav> <main role="main" id="content" class="container"> <!-- <ol class="breadcrumb"> --> <!-- <li> <a href="/" title="Home">Home</a> </li> --> <!-- --> <!-- </ol> --> <!-- question --> <div class="page-header"> <div class="row"> <div class="col-sm-10"> <div> <a href="../../../../1.html" title="Crisis"> <i class="fa fa-fw fa-dot-circle-o"></i> #VerilyLive Challenge </a> <span class="text-muted">/</span> <a href="../../11.1.html" title="Verification Request"> <i class="fa fa-fw fa-question-circle"></i> Is the gas burning today at the Door to... </a> <span class="text-muted">/</span> <i class="fa fa-check success"></i> <span class="success">True because</span> </div> <h2 class="question-title">It has been since 1971 and is fed by natural feeds </h2> <p class="lead description-text"> </p> <p class="metadata"> <i class="fa fa-bullhorn fa-lg fa-fw"></i> <span class=""><abbr title="Sat, 12 Jul 2014 10:53:32 GMT">2014-07-12 10:53:32</abbr></span> by LifeSVR </p> <div class="action-buttons"> <div class="row"> <div class="answer-buttons"> <!-- button-vote-up --> <div class="mini action-button-ctr btn-group"> <button data-crisis-id="1" data-question-id="11" data-answer-id="12" class="btn btn-default btn-large mini-action-button btn_upvote " title="Upvote"><i class="fa fa-arrow-up"></i></button> <a href="12.html#" class="btn btn-default action-button-count disabled upvote_count">0</a> </div> <!-- / button-vote-up --> <!-- button-vote-down --> <div class="mini action-button-ctr btn-group"> <button data-crisis-id="1" data-question-id="11" data-answer-id="12" class="btn btn-default btn-large mini-action-button btn_downvote " title="Downvote"><i class="fa fa-arrow-down"></i></button> <a href="12.html#" class="btn btn-default action-button-count disabled downvote_count answer_number_12">0</a> </div> <!-- / button-vote-down --> <!-- button-comment --> <div class="mini action-button-ctr btn-group"> <button data-crisis-id="1" data-question-id="11" data-answer-id="12" data-fragment="comment" class="btn btn-default btn-large mini-action-button btn_comment " title="Comment"><i class="fa fa-comment"></i></button> <a href="12.html#" class="btn btn-default action-button-count disabled">0</a> </div> <!-- / button-comment --> </div> </div> </div> </div> <!-- / .question-image-and-map-ctr --> </div> <!-- / question header row --> <div class="btn-group"> <div class="additional-button-ctr"> <button class="btn btn-default btn-sm" style="display: none;"><i class="fa fa-flag"></i> <strong>Flag</strong></button> </div> </div> <!-- / small buttons --> <!-- / video --> </div> <div class="evidence-content"> </div> <!-- / Evidence --> <!-- / create comment --> <!-- create comment --> <div id="form-ctr" class="well form"> <h3><span class="fa fa-reply"></span> <span id="form-label-question-type" class="label"></span></h3> <form id="create-answer-comment" class="post-form" role="form" action="https://veri.ly/crisis/1/question/11/answer/12/comments" method="POST" enctype="multipart/form-data"> <input type="hidden" name="_csrf" value="snpizaE8yCZQKXLiLfZK1DxpsNkTe79+Byq2g=" /> <div class="form-group"> <label for="form-text" class="control-label">Comment</label> <textarea class="form-control" id="form-text" name="text" rows="2" placeholder="Write here..."></textarea> </div> <button id="submit" type="submit" class="btn btn-sm btn-primary ">Submit Comment</button> </form> </div> <script type="text/javascript"> $(function(){ var label = $('#form-text').prev(); var originalHtml = label.html(); $('#create-answer-comment').submit( function(e){ validateComment($('#form-text').val(), function(error, value){ if(error){ label.html(originalHtml + ' &ndash; ' + error); $('#form-text').parent('div').addClass('has-error has-feedback'); e.preventDefault(); return false; } }); }); document.getElementById('form-text').addEventListener('keyup', function(e) { validateComment($('#form-text').val(), function(error, value){ if(!error){ label.html(originalHtml); $('#form-text').parent('div').removeClass('has-error has-feedback'); } }); }); }); </script> <div class="comments-content"> <h3>0 comments</h3> <div class="answer-comments"> </div> </div> <script type="text/javascript"> $(function(){ $("div .btn_downvote").click( function(){ var button = $(this); $.post('/crisis/'+button.attr('data-crisis-id')+'/question/'+button.attr('data-question-id') +'/answer/'+button.attr('data-answer-id')+'/downvote', {_csrf: "snpizaE8yCZQKXLiLfZK1DxpsNkTe79+Byq2g=" }, function(data){ var answer = data; update_votes(answer, button); }).fail(function(){ var error_message = 'There was an unknown error, please try again later.'; if (!common.challengePublished()) { error_message = 'The Verily Challenge has now closed. Thank you for taking part!'; } show_alert_message('danger', 5000, "Error", error_message); }); }); $("div .btn_upvote").click(function(){ var button = $(this); $.post('/crisis/'+button.attr('data-crisis-id')+'/question/'+button.attr('data-question-id') +'/answer/'+button.attr('data-answer-id')+'/upvote', {_csrf: "snpizaE8yCZQKXLiLfZK1DxpsNkTe79+Byq2g=" }, function(data){ var answer = data; update_votes(answer, button); }).fail(function(){ var error_message = 'There was an unknown error, please try again later.'; if (!common.challengePublished()) { error_message = 'The Verily Challenge has now closed. Thank you for taking part!'; } show_alert_message('danger', 5000, "Error", error_message); }); }); }); var update_votes = function(answer, element){ element.parents('.answer-wrapper').attr('data-upvotes', answer.post.upvoteCount); element.parents('.answer-wrapper').attr('data-popularity', answer.popularityCoefficient); element.parents('.answer-buttons').find('.upvote_count').html(answer.post.upvoteCount); element.parents('.answer-buttons').find('.downvote_count').html(answer.post.downvoteCount); element.parents('.answer-buttons').find('.btn_downvote').removeClass('active').removeClass('disabled'); element.parents('.answer-buttons').find('.btn_upvote').removeClass('active').removeClass('disabled'); element.addClass('active').addClass('disabled'); } </script> <script type="text/javascript"> // Remove all children from an element function resetElement(target) { while (target.firstChild) { labelQuestionType.removeChild(target.firstChild); } } $(function(){ $('.btn_comment').click(function(){ focusForm(); }); }) function focusForm() { var formText = document.getElementById('form-text'); formText.focus(); } if (window.location.search.indexOf('action=comment') !== -1) { // focus comment box focusForm(); } </script> <script type="text/javascript"> function urlify(text) { var urlRegex = /(https?:\/\/[^\s]+)/g; return text.replace(urlRegex, function(url) { return '<a href="https://veri.ly/crisis/1/question/11/answer/'&#32;+&#32;url&#32;+&#32;'" target="_blank">' + url + '</a>'; }) // or alternatively // return text.replace(urlRegex, '<a href="https://veri.ly/crisis/1/question/11/answer/$1">$1</a>') } $(document).ready(function(){ $(".description-text").html(urlify($(".description-text").text())); $(".question-title").html(urlify($(".question-title").text())); $(".comment-text").each(function (index) { $(this).html(urlify($(this).text())); }); }); </script> <footer> <div class="pull-left"> <div class="text-muted"> <a href="../../../../../terms.html#copyright">&copy; 2014 Verily</a> </div> <div class="text-muted"> <a href="../../../../../about.html">About</a> &middot; <a href="../../../../../terms.html">Terms &amp; Privacy</a> &middot; <a href="../../../../../help.html">Contact</a> </div> </div> </footer> </main> </body> </html>
{ "content_hash": "44a14ab67f077c062e822ee2c552c86d", "timestamp": "", "source": "github", "line_count": 664, "max_line_length": 276, "avg_line_length": 39.18825301204819, "alnum_prop": 0.4952154029437762, "repo_name": "verily-org/verily", "id": "927fd190fd5ada437f0bb4e66bb77b66b0af4474", "size": "26021", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "static/snapshots/snapshot-2014-10-01-2030/crisis/1/question/11/answer/12.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "49473" }, { "name": "HTML", "bytes": "16064346" }, { "name": "JavaScript", "bytes": "584721" } ], "symlink_target": "" }
% A program to create a video of the computed results clear all; format compact, format short, set(0,'defaultaxesfontsize',14,'defaultaxeslinewidth',.7,... 'defaultlinelinewidth',2,'defaultpatchlinewidth',3.5); % Load data % Get coordinates X=load('./xcoord.dat'); Y=load('./ycoord.dat'); Z=load('./zcoord.dat'); TIME=load('./tdata.dat'); En=load('./en.dat'); EnStr=load('./enstr.dat'); EnPot=load('./enpot.dat'); EnKin=load('./enkin.dat'); % find number of grid points Nx=length(X); Ny=length(Y); Nz=length(Z); % reshape coordinates to allow easy plotting [xx,yy,zz]=meshgrid(X,Y,Z); figure(5); clf; semilogy(TIME,En,'r',TIME,EnKin,'b:',TIME,EnPot,'g.',TIME,EnStr,'y+'); xlabel time; ylabel Energy; legend('Total','Kinetic','Potential','Strain'); saveas(5,'./EnerPlot.jpg','jpg'); % reshape coordinates to allow easy plotting [xx,yy]=ndgrid(X,Y); nplots=length(TIME); for i =1:nplots % % Open file and dataset using the default properties. % FILE=['./data/u',num2str(9999999+i),'.datbin']; FILEPIC=['./data/pic',num2str(9999999+i),'.jpg']; fid=fopen(FILE,'r'); [fname,mode,mformat]=fopen(fid); u=fread(fid,Nx*Ny,'real*8'); u=reshape(u,Nx,Ny); % close files fclose(fid); % % Plot data on the screen. % figure(2);clf; % coordinate slice to show plots on sx=[0]; sy=[0]; sz=[0]; slice(xx,yy,zz,u,sx,sy,sz); colormap jet; title(['Time ',num2str(TIME(i))]); colorbar('location','EastOutside'); drawnow; colorbar; frame=getframe(2); saveas(2,FILEPIC,'jpg'); figure(4); clf; UP = u; p1 = patch(isosurface(X,Y,Z,UP,.1),... 'FaceColor','yellow','EdgeColor','none'); p2 = patch(isocaps(X,Y,Z,UP,.1),... 'FaceColor','interp','EdgeColor','none'); isonormals(UP,p1); lighting phong; xlabel('x'); ylabel('y'); zlabel('z'); axis equal; axis square; view(3); title(['Time ',num2str(TIME(i))]); drawnow; saveas(4,FILEPIC2,'jpg'); end
{ "content_hash": "763831a3b77d354752ae353ab3b77468", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 72, "avg_line_length": 27.428571428571427, "alnum_prop": 0.640625, "repo_name": "openmichigan/PSNM", "id": "81d6b8ceb753f10ab01057a4dd171295c64ace6d", "size": "1920", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "KleinGordon/Programs/KleinGordon3dThreadFFT/video.m", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "27049" }, { "name": "C++", "bytes": "18529" }, { "name": "Cuda", "bytes": "49615" }, { "name": "Fortran", "bytes": "665234" }, { "name": "MATLAB", "bytes": "96338" }, { "name": "Makefile", "bytes": "13535" }, { "name": "Python", "bytes": "255733" }, { "name": "Shell", "bytes": "6089" }, { "name": "TeX", "bytes": "221906" } ], "symlink_target": "" }
QQFileInfo::QQFileInfo() { }
{ "content_hash": "d52cfa3f172e89ba9e312f7086b4adcc", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 24, "avg_line_length": 9.666666666666666, "alnum_prop": 0.6896551724137931, "repo_name": "eirTony/EIRC2", "id": "b11fa23a50e1ce06bc64299cee73f257cf17ed32", "size": "54", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "src/lib/core/type/_hold/QQFileInfo.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "190130" }, { "name": "C++", "bytes": "443358" }, { "name": "IDL", "bytes": "454" }, { "name": "Python", "bytes": "2855" }, { "name": "QMake", "bytes": "25546" } ], "symlink_target": "" }