code
stringlengths
0
29.6k
language
stringclasses
9 values
AST_depth
int64
3
30
alphanumeric_fraction
float64
0.2
0.86
max_line_length
int64
13
399
avg_line_length
float64
5.02
139
num_lines
int64
7
299
source
stringclasses
4 values
@GetMapping("/category") public String getProductsByCategoryPage(@RequestParam("id") Long categoryId, Model model) { Category category = categoryService.getCategoryById(categoryId); List<Product> products = productService.getProductsByCategory(category); Collections.shuffle(products, new Random()); model.addAttribute("products", products); //brings the ads List<Advert> adverts = advertService.getAdverts(); model.addAttribute("adverts", adverts); //brings categories List<Category> categories = categoryService.getCategories(); model.addAttribute("categories", categories); model.addAttribute("currentCategoryId", category.getId()); return "index"; }
java
8
0.687254
95
39.105263
19
inline
#pragma once #include "ofMain.h" #include "ofxLaserManager.h" #include "ofxGui.h" #include "Asteroids.h" #include "FlappyBird.h" class ofApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void exit(); void keyPressed(int key); void keyReleased(int key); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void audioIn(float * input, int bufferSize, int numChannels); void showLaserEffect(int effectnum); ofParameter currentLaserEffect; int numLaserEffects; ofParameter timeSpeed; ofxLaser::Manager laser; bool drawingShape = false; int laserWidth; int laserHeight; ofxPanel laserGui; ofxPanel colourGui; bool showGui; bool blankAll; float elapsedTime; float deltaTime; Asteroids asteroids; FlappyBird flappyBird; ofSoundStream soundStream; vector left; vector right; float smoothedInputVolume; };
c
8
0.725823
62
15.716667
60
starcoderdata
var xstreamer_8h = [ [ "XStrm_RxFifoStreamer", "group__llfifo__v5__0.html#ga4f27ac6f38ad77d7b92014a52eb5c16b", null ], [ "XStrm_TxFifoStreamer", "group__llfifo__v5__0.html#ga3d1351f115d97cbce95da390d0ea4033", null ], [ "XStrm_Read", "group__llfifo__v5__0.html#ga915d68a9cce0f2464fc7644383cb887a", null ], [ "XStrm_RxGetLen", "group__llfifo__v5__0.html#ga479d2eb3193ad0a5efc3c3b432a78381", null ], [ "XStrm_TxInitialize", "group__llfifo__v5__0.html#ga8a67c77f811a505b658e06642eb9c964", null ], [ "XStrm_TxSetLen", "group__llfifo__v5__0.html#ga1e99fb51e0cfab7d0e8de5e93c27fd9c", null ], [ "XStrm_Write", "group__llfifo__v5__0.html#ga1f43ea833af99162745ceef66849b666", null ] ];
javascript
3
0.732648
101
69.818182
11
starcoderdata
import { createThemedIcon } from './utils/createThemedIcon'; import { FilledDevicesOther } from './FilledDevicesOther'; import { OutlineDevicesOther } from './OutlineDevicesOther'; import { RoundDevicesOther } from './RoundDevicesOther'; import { SharpDevicesOther } from './SharpDevicesOther'; import { TwoToneDevicesOther } from './TwoToneDevicesOther'; export var DevicesOther = /*#__PURE__*/ function DevicesOther(props) { return createThemedIcon(props, FilledDevicesOther, OutlineDevicesOther, RoundDevicesOther, SharpDevicesOther, TwoToneDevicesOther); };
javascript
9
0.788632
133
50.272727
11
starcoderdata
/******************************************************************************* * Copyright [2015] [Onboard team of SERC, Peking University] * * 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.onboard.test.model; import java.util.Date; import com.onboard.domain.mapper.model.common.BaseItem; import com.onboard.domain.model.type.BaseProjectItem; import com.onboard.test.moduleutils.ModuleHelper; public class BaseProjectItemImpl implements BaseProjectItem { private static final long serialVersionUID = 2098285158250422435L; private Integer id; private String type; private Integer projectId = ModuleHelper.projectId; private Integer companyId = ModuleHelper.companyId; private Integer creatorId = ModuleHelper.creatorId; private String creatorName = ModuleHelper.creatorName; private String creatorAvatar = ModuleHelper.creatorAvatar; private Date created = ModuleHelper.created; private Date updated = ModuleHelper.updated; private Boolean deleted = false; private boolean trashRequired = false; public BaseProjectItemImpl() { super(); } public BaseProjectItemImpl(Integer id, String type){ super(); this.id = id; this.type = type; } @Override public Integer getId() { return id; } @Override public void setId(Integer id) { this.id = id; } @Override public Integer getProjectId() { return projectId; } @Override public void setProjectId(Integer projectId) { this.projectId = projectId; } @Override public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public Integer getCompanyId() { return companyId; } @Override public void setCompanyId(Integer companyId) { this.companyId = companyId; } @Override public Integer getCreatorId() { return creatorId; } @Override public void setCreatorId(Integer creatorId) { this.creatorId = creatorId; } @Override public String getCreatorName() { return creatorName; } @Override public void setCreatorName(String creatorName) { this.creatorName = creatorName; } @Override public String getCreatorAvatar() { return creatorAvatar; } @Override public void setCreatorAvatar(String creatorAvatar) { this.creatorAvatar = creatorAvatar; } @Override public Date getCreated() { return created; } @Override public void setCreated(Date created) { this.created = created; } @Override public Date getUpdated() { return updated; } @Override public void setUpdated(Date updated) { this.updated = updated; } @Override public Boolean getDeleted() { return deleted; } @Override public void setDeleted(Boolean deleted) { this.deleted = deleted; } public boolean isTrashRequired() { return trashRequired; } public void setTrashRequired(boolean trashRequired) { this.trashRequired = trashRequired; } @Override public boolean trashRequried() { return trashRequired; } @Override public BaseItem copy() { return this; } }
java
8
0.636023
81
26.798611
144
starcoderdata
#include <bits/stdc++.h> #include <unistd.h> #define ll long long #define inf 1000000007 #define inf16 0x3f3f3f3f #define INF 1000000000000000007LL #define VI vector<int> #define VPII vector<pair<int, int> > #define VLL vector<ll> #define PII pair<int, int> #define st first #define nd second #define pb push_back #define mp make_pair #define eb emplace_back #define endl '\n' #define ALL(c) (c).begin(), (c).end() using namespace std; string s; int n; void check() { if(s=="Vacant") exit(0); } void query(int i) { cout << i << endl; fflush(stdout); cin >> s; check(); } int32_t main() { cin >> n; query(0); if(s=="Male") { query(n-1); int l = 1, r = n-2; while(l<r) { int m = (l+r)/2; query(m); if((m%2==0 && s=="Female") || (m%2==1 && s=="Male")) r = m-1; else l = m+1; } query(l); } else { query(n-1); int l = 1, r = n-2; while(l<r) { int m = (l+r)/2; query(m); if((m%2==1 && s=="Female") || (m%2==0 && s=="Male")) r = m-1; else l = m+1; } query(l); } }
c++
15
0.542776
55
11.535714
84
codenet
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; using System.IO; public class GameManager : MonoBehaviour { private const string SAVE_SEPARATOR = "\n"; [SerializeField] private TextMeshProUGUI goldText; [SerializeField] private TextMeshProUGUI emissionText; [SerializeField] private TextMeshProUGUI powerText; [SerializeField] private PowerBar powerBar; [SerializeField] private EmissionBar emissionBar; public Timer timer; public float gold = 5000000f; public float goldPerTick = 1; public float emission; public float maxEmission = 800f; public float emissionPerTick; public float power; public float maxPower = 1000f; public float powerPerTick; public GameObject coal; public GameObject geo; public GameObject hydro; public GameObject nuclear; public GameObject solar; public GameObject wind; public GameObject winScreen; public GameObject loseScreen; void Start() { TimeTickSystem.Create(); Load(); emissionBar.SetMaxEmission(maxEmission); powerBar.SetMaxPower(maxPower); TimeTickSystem.OnTick += delegate (object sender, TimeTickSystem.OnTickEventArgs e) { UpdateGold(); UpdateEmission(); UpdatePower(); goldText.text = "$" + gold.ToString(); emissionText.text = emission.ToString() + "/" + maxEmission.ToString(); powerText.text = power.ToString() + "/" + maxPower.ToString(); }; } public void ChangeGoldPerTick(float amount) { goldPerTick = goldPerTick + amount; } public void UpdateGold() { gold += goldPerTick; } public void ChangeGold(float amount) { gold = gold - amount; } public void ChangeEmissionPerTick(float amount) { emissionPerTick = emissionPerTick + amount; } public void UpdateEmission() { emission += emissionPerTick; if (emission >= maxEmission) { loseScreen.SetActive(true); Time.timeScale = 0f; } emissionBar.SetEmission(emission); } public void ChangePowerPerTick(float amount) { powerPerTick = powerPerTick + amount; } public void UpdatePower() { power += powerPerTick; if (power >= maxPower) { winScreen.SetActive(true); Time.timeScale = 0f; } powerBar.SetPower(power); } public void Save() { string[] contents = new string[] { ""+gold, ""+emission, ""+power, ""+goldPerTick, ""+emissionPerTick, ""+powerPerTick, ""+timer.timeSpent, ""+coal.transform.position.x, ""+coal.transform.position.y, ""+geo.transform.position.x, ""+geo.transform.position.y, ""+hydro.transform.position.x, ""+hydro.transform.position.y, ""+nuclear.transform.position.x, ""+nuclear.transform.position.y, ""+solar.transform.position.x, ""+solar.transform.position.y, ""+wind.transform.position.x, ""+wind.transform.position.y, }; string saveString = string.Join(SAVE_SEPARATOR, contents); File.WriteAllText(Application.dataPath + "/save.txt", saveString); } void Load() { if (File.Exists(Application.dataPath + "/save.txt")) { string saveString = File.ReadAllText(Application.dataPath + "/save.txt"); string[] contents = saveString.Split(new[] {SAVE_SEPARATOR}, System.StringSplitOptions.None); gold = float.Parse(contents[0]); emission = float.Parse(contents[1]); power = float.Parse(contents[2]); goldPerTick = float.Parse(contents[3]); emissionPerTick = float.Parse(contents[4]); powerPerTick = float.Parse(contents[5]); timer.timeSpent = float.Parse(contents[6]); float x = float.Parse(contents[7]); float y = float.Parse(contents[8]); coal.transform.position = new Vector3(x, y, 0f); x = float.Parse(contents[9]); y = float.Parse(contents[10]); geo.transform.position = new Vector3(x, y, 0f); x = float.Parse(contents[11]); y = float.Parse(contents[12]); hydro.transform.position = new Vector3(x, y, 0f); x = float.Parse(contents[13]); y = float.Parse(contents[14]); nuclear.transform.position = new Vector3(x, y, 0f); x = float.Parse(contents[15]); y = float.Parse(contents[16]); solar.transform.position = new Vector3(x, y, 0f); x = float.Parse(contents[17]); y = float.Parse(contents[18]); wind.transform.position = new Vector3(x, y, 0f); } else { emission = power = 0f; emissionPerTick = powerPerTick = 0f; timer.timeSpent = 0f; } } }
c#
17
0.583479
105
29.736527
167
starcoderdata
#include "boss.h" Boss::Boss(char const* n, int s, char const* algo, double t, unsigned d, unsigned lvl, unsigned dmg) : Player(n, s), Hero(n, s, lvl), Bot(n, s, algo, t, d), damage(dmg) {} void Boss::print(std::ostream& os) const { Player::print(os); printDirect(os); } void Boss::printDirect(std::ostream& os) const { os << ", който е boss"; Hero::printDirect(os); Bot::printDirect(os); os << " и нанася поражения " << getDamage(); }
c++
7
0.602105
70
25.388889
18
starcoderdata
def _insdc_location_string_ignoring_strand_and_subfeatures(location, rec_length): if location.ref: ref = "%s:" % location.ref else: ref = "" assert not location.ref_db if ( isinstance(location.start, SeqFeature.ExactPosition) and isinstance(location.end, SeqFeature.ExactPosition) and location.start.position == location.end.position ): # Special case, for 12:12 return 12^13 # (a zero length slice, meaning the point between two letters) if location.end.position == rec_length: # Very special case, for a between position at the end of a # sequence (used on some circular genomes, Bug 3098) we have # N:N so return N^1 return "%s%i^1" % (ref, rec_length) else: return "%s%i^%i" % (ref, location.end.position, location.end.position + 1) if ( isinstance(location.start, SeqFeature.ExactPosition) and isinstance(location.end, SeqFeature.ExactPosition) and location.start.position + 1 == location.end.position ): # Special case, for 11:12 return 12 rather than 12..12 # (a length one slice, meaning a single letter) return "%s%i" % (ref, location.end.position) elif isinstance(location.start, SeqFeature.UnknownPosition) or isinstance( location.end, SeqFeature.UnknownPosition ): # Special case for features from SwissProt/UniProt files if isinstance(location.start, SeqFeature.UnknownPosition) and isinstance( location.end, SeqFeature.UnknownPosition ): # warnings.warn("Feature with unknown location", BiopythonWarning) # return "?" raise ValueError("Feature with unknown location") elif isinstance(location.start, SeqFeature.UnknownPosition): # Treat the unknown start position as a BeforePosition return "%s<%i..%s" % ( ref, location.nofuzzy_end, _insdc_feature_position_string(location.end), ) else: # Treat the unknown end position as an AfterPosition return "%s%s..>%i" % ( ref, _insdc_feature_position_string(location.start, +1), location.nofuzzy_start + 1, ) else: # Typical case, e.g. 12..15 gets mapped to 11:15 return ( ref + _insdc_feature_position_string(location.start, +1) + ".." + _insdc_feature_position_string(location.end) )
python
15
0.594917
86
42.3
60
inline
# -*- coding:utf-8 -*- __author__ = 'randolph' import os import sys import time import torch sys.path.append('../') from layers import MOOCNet, Loss from utils import checkmate as cm from utils import data_helpers as dh from utils import param_parser as parser from tqdm import tqdm, trange import torch.nn.utils.rnn as rnn_utils from torch.utils.data import TensorDataset, DataLoader from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_auc_score, average_precision_score args = parser.parameter_parser() MODEL = dh.get_model_name() logger = dh.logger_fn("ptlog", "logs/Test-{0}.log".format(time.asctime())) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') CPT_DIR = os.path.abspath(os.path.join(os.path.curdir, "runs", MODEL)) SAVE_DIR = os.path.abspath(os.path.join(os.path.curdir, "outputs", MODEL)) def create_input_data(record): """ Creating features and targets with Torch tensors. """ x_activity, x_lens, x_tsp, y = record batch_x_pack = rnn_utils.pack_padded_sequence(x_activity, x_lens, batch_first=True) batch_x_pack = batch_x_pack.to(device) return batch_x_pack, x_tsp, y def test(): logger.info("Loading Data...") logger.info("Data processing...") test_data = dh.load_data_and_labels(args.test_file) test_dataset = dh.MyData(test_data.activity, test_data.timestep, test_data.labels) test_loader = DataLoader(test_dataset, batch_size=args.batch_size, shuffle=False, collate_fn=dh.collate_fn) # Load word2vec model COURSE_SIZE = dh.course2vec(args.course2vec_file) criterion = Loss() net = MOOCNet(args, COURSE_SIZE).to(device) checkpoint_file = cm.get_best_checkpoint(CPT_DIR, select_maximum_value=False) checkpoint = torch.load(checkpoint_file) net.load_state_dict(checkpoint['model_state_dict']) net.eval() logger.info("Scoring...") true_labels, predicted_scores, predicted_labels = [], [], [] batches = trange(len(test_loader), desc="Batches", leave=True) for batch_cnt, batch in zip(batches, test_loader): x_test, tsp_test, y_test = create_input_data(batch) logits, scores = net(x_test, tsp_test) for i in y_test.tolist(): true_labels.append(i) for j in scores.tolist(): predicted_scores.append(j) if j >= 0.5: predicted_labels.append(1) else: predicted_labels.append(0) # Calculate the Metrics logger.info('Test Finished.') logger.info('Creating the prediction file...') dh.create_prediction_file(save_dir=SAVE_DIR, identifiers=test_data.id, predictions=predicted_labels) logger.info('All Finished.') if __name__ == "__main__": test()
python
13
0.674991
123
31.593023
86
starcoderdata
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/signin/dice_turn_sync_on_helper_delegate_impl.h" #include "base/bind.h" #include "base/check.h" #include "base/feature_list.h" #include "base/metrics/user_metrics.h" #include "base/metrics/user_metrics_action.h" #include "base/notreached.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/new_tab_page/chrome_colors/selected_colors_info.h" #include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/browser/profiles/profile_window.h" #include "chrome/browser/signin/signin_features.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/signin/profile_colors_util.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/webui/signin/enterprise_profile_welcome_ui.h" #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" #include "chrome/browser/ui/webui/signin/signin_email_confirmation_dialog.h" #include "chrome/browser/ui/webui/signin/signin_ui_error.h" #include "chrome/common/url_constants.h" #include "google_apis/gaia/gaia_auth_util.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/skia/include/core/SkColor.h" namespace { // If the |browser| argument is non-null, returns the pointer directly. // Otherwise creates a new browser for the profile, adds an empty tab and makes // sure the browser is visible. Browser* EnsureBrowser(Browser* browser, Profile* profile) { if (!browser) { // The user just created a new profile or has closed the browser that // we used previously. Grab the most recently active browser or else // create a new one. browser = chrome::FindLastActiveWithProfile(profile); if (!browser) { browser = Browser::Create(Browser::CreateParams(profile, true)); chrome::AddTabAt(browser, GURL(), -1, true); } browser->window()->Show(); } return browser; } // Converts SigninEmailConfirmationDialog::Action to // DiceTurnSyncOnHelper::SigninChoice and invokes |callback| on it. void OnEmailConfirmation(DiceTurnSyncOnHelper::SigninChoiceCallback callback, SigninEmailConfirmationDialog::Action action) { DCHECK(callback) << "This function should be called only once."; switch (action) { case SigninEmailConfirmationDialog::START_SYNC: std::move(callback).Run(DiceTurnSyncOnHelper::SIGNIN_CHOICE_CONTINUE); return; case SigninEmailConfirmationDialog::CREATE_NEW_USER: std::move(callback).Run(DiceTurnSyncOnHelper::SIGNIN_CHOICE_NEW_PROFILE); return; case SigninEmailConfirmationDialog::CLOSE: std::move(callback).Run(DiceTurnSyncOnHelper::SIGNIN_CHOICE_CANCEL); return; } NOTREACHED(); } void OnProfileCheckComplete(const AccountInfo& account_info, DiceTurnSyncOnHelper::SigninChoiceCallback callback, base::WeakPtr browser, bool prompt_for_new_profile) { if (!browser) { std::move(callback).Run(DiceTurnSyncOnHelper::SIGNIN_CHOICE_CANCEL); return; } if (base::FeatureList::IsEnabled(kAccountPoliciesLoadedWithoutSync)) { ProfileAttributesEntry* entry = g_browser_process->profile_manager() ->GetProfileAttributesStorage() .GetProfileAttributesWithPath(browser->profile()->GetPath()); browser->signin_view_controller()->ShowModalEnterpriseConfirmationDialog( account_info, GenerateNewProfileColor(entry).color, base::BindOnce( [](DiceTurnSyncOnHelper::SigninChoiceCallback callback, Browser* browser, bool prompt_for_new_profile, bool create_profile) { browser->signin_view_controller()->CloseModalSignin(); std::move(callback).Run( create_profile ? prompt_for_new_profile ? DiceTurnSyncOnHelper::SIGNIN_CHOICE_NEW_PROFILE : DiceTurnSyncOnHelper::SIGNIN_CHOICE_CONTINUE : DiceTurnSyncOnHelper::SIGNIN_CHOICE_CANCEL); }, std::move(callback), browser.get(), prompt_for_new_profile)); return; } DiceTurnSyncOnHelper::Delegate::ShowEnterpriseAccountConfirmationForBrowser( account_info.email, /*prompt_for_new_profile=*/prompt_for_new_profile, std::move(callback), browser.get()); } } // namespace DiceTurnSyncOnHelperDelegateImpl::DiceTurnSyncOnHelperDelegateImpl( Browser* browser) : browser_(browser), profile_(browser_->profile()) { DCHECK(browser); DCHECK(profile_); BrowserList::AddObserver(this); } DiceTurnSyncOnHelperDelegateImpl::~DiceTurnSyncOnHelperDelegateImpl() { BrowserList::RemoveObserver(this); } void DiceTurnSyncOnHelperDelegateImpl::ShowLoginError( const SigninUIError& error) { DCHECK(!error.IsOk()); DiceTurnSyncOnHelper::Delegate::ShowLoginErrorForBrowser(error, browser_); } void DiceTurnSyncOnHelperDelegateImpl:: ShouldEnterpriseConfirmationPromptForNewProfile( Profile* profile, base::OnceCallback callback) { ui::CheckShouldPromptForNewProfile(profile, std::move(callback)); } void DiceTurnSyncOnHelperDelegateImpl::ShowEnterpriseAccountConfirmation( const AccountInfo& account_info, DiceTurnSyncOnHelper::SigninChoiceCallback callback) { browser_ = EnsureBrowser(browser_, profile_); // Checking whether to show the prompt for a new profile is sometimes // asynchronous. ShouldEnterpriseConfirmationPromptForNewProfile( profile_, base::BindOnce(&OnProfileCheckComplete, account_info, std::move(callback), browser_->AsWeakPtr())); } void DiceTurnSyncOnHelperDelegateImpl::ShowSyncConfirmation( base::OnceCallback callback) { DCHECK(callback); sync_confirmation_callback_ = std::move(callback); scoped_login_ui_service_observation_.Observe( LoginUIServiceFactory::GetForProfile(profile_)); browser_ = EnsureBrowser(browser_, profile_); browser_->signin_view_controller()->ShowModalSyncConfirmationDialog(); } void DiceTurnSyncOnHelperDelegateImpl::ShowSyncDisabledConfirmation( bool is_managed_account, base::OnceCallback callback) { // This is handled by the same UI element as the normal sync confirmation. ShowSyncConfirmation(std::move(callback)); } void DiceTurnSyncOnHelperDelegateImpl::ShowMergeSyncDataConfirmation( const std::string& previous_email, const std::string& new_email, DiceTurnSyncOnHelper::SigninChoiceCallback callback) { DCHECK(callback); browser_ = EnsureBrowser(browser_, profile_); browser_->signin_view_controller()->ShowModalSigninEmailConfirmationDialog( previous_email, new_email, base::BindOnce(&OnEmailConfirmation, std::move(callback))); } void DiceTurnSyncOnHelperDelegateImpl::ShowSyncSettings() { browser_ = EnsureBrowser(browser_, profile_); chrome::ShowSettingsSubPage(browser_, chrome::kSyncSetupSubPage); } void DiceTurnSyncOnHelperDelegateImpl::SwitchToProfile(Profile* new_profile) { profile_ = new_profile; browser_ = nullptr; } void DiceTurnSyncOnHelperDelegateImpl::OnSyncConfirmationUIClosed( LoginUIService::SyncConfirmationUIClosedResult result) { DCHECK(sync_confirmation_callback_); // Treat closing the ui as an implicit ABORT_SYNC action. if (result == LoginUIService::UI_CLOSED) result = LoginUIService::ABORT_SYNC; browser_->signin_view_controller()->CloseModalSignin(); std::move(sync_confirmation_callback_).Run(result); } void DiceTurnSyncOnHelperDelegateImpl::OnBrowserRemoved(Browser* browser) { if (browser == browser_) browser_ = nullptr; }
c++
20
0.728184
82
39.706468
201
starcoderdata
boolean MKMath::writeBuffer(float *buffer, byte bufferLength) // used float for compatibility but! can cause Memory Issues. { byte i=0; this->mathBuffer = buffer; //copy the pointer only this->usedBuffer = bufferLength; /* Using Pointers here is much more memory efficient! * 2MByte with float array is quickly filled. * if (this->verbose) { this->debugSerial->print("Writing Buffer with length="); this->debugSerial->println(bufferLength); } //bufferLength should be shorter than MAX_MATH_BUFFER if (bufferLength>MAX_MATH_BUFFER) { return false; } for (i=0; i<bufferLength; i++) { this->mathBuffer[i] = buffer[i]; } //Clear Buffer for (i=bufferLength; i<MAX_MATH_BUFFER; i++) { this->mathBuffer[i] = 0.0; } if (this->verbose) { for (i=0; i<MAX_MATH_BUFFER; i++) { this->debugSerial->print(this->mathBuffer[i]); this->debugSerial->print("\t"); } this->debugSerial->println(); } this->usedBuffer = bufferLength; */ this->calculated = false; return true; }
c++
6
0.65643
123
28.705882
34
inline
Node::~Node() { COGLOGDEBUG("Node", "Destructing node %s", tag.c_str()); // move elements from collection to insert so they can be removed from classic collections InsertElementsForAdding(false, false); // delete all behaviors for (auto& beh : behaviors) { if (scene != nullptr) { this->scene->RemoveBehavior(beh); } if (!beh->IsExternal()) { delete beh; } } behaviors.clear(); // delete all children for (auto it = children.begin(); it != children.end(); ++it) { if (scene != nullptr) { scene->RemoveNode(*it); } if (!(*it)->IsExternal()) { delete (*it); } } children.clear(); for (auto childToAdd : childrenToAdd) { if (!childToAdd->IsExternal()) { delete childToAdd; } } for (auto childToRemove : childrenToRemove) { if (!childToRemove.first->IsExternal()) { delete childToRemove.first; } } // delete not shared attributes for (auto attr : attributes) { if (!attr.second->IsShared()) { delete attr.second; } } delete groups; delete states; }
c++
12
0.611632
92
18.759259
54
inline
@Test public void testHasAnySample() { // Without labels Counter.build().name("testHasAnySample").help("help") .create().register(); MetricFamilySamples mfsCounter = getMetricFamilySamples("testHasAnySample"); assertThat(mfsCounter).hasAnySamples(); // With labels Counter counterWithLabels = Counter.build().name("testHasAnySample_withLabels").help("help") .labelNames("label") .create().register(); MetricFamilySamples mfsCounterWithLabels = getMetricFamilySamples("testHasAnySample_withLabels"); expectAssertionError(() -> assertThat(mfsCounterWithLabels).hasAnySamples()); counterWithLabels.labels("value").inc(); assertThat(getMetricFamilySamples("testHasAnySample_withLabels")) // Need to fetch again! .hasAnySamples(); }
java
12
0.655329
105
45.473684
19
inline
package xyz.winmyataung.movie_shelf.delegates; /** * Created by DELL on 12/20/2017. */ public interface MoviesActionDelegates { void onTapMoviesItem(); void onTapMoviesOverview(); }
java
5
0.694581
46
17.454545
11
starcoderdata
void BufferedWriter::next_hdl() { //set fileName char fname[20]; if (me_ >= 0) { sprintf(fname, "part_%d_%d", me_, next_part_); } else { sprintf(fname, "part_%d", next_part_); } //flush old file if (next_part_ > 0) { if (hdfsFlush(fs_, cur_hdl_)) { fprintf(stderr, "Failed to 'flush' %s\n", path_); exit(-1); } hdfsCloseFile(fs_, cur_hdl_); } //open new file next_part_++; char* file_path = new char[strlen(path_) + strlen(fname) + 2]; sprintf(file_path, "%s/%s", path_, fname); cur_hdl_ = get_w_handle(file_path, fs_); delete[] file_path; }
c++
11
0.578584
63
17.709677
31
inline
import os from Jumpscale import j from .GedisServer import GedisServer from .GedisCmds import GedisCmds from .GedisChatBot import GedisChatBotFactory class GedisFactory(j.baseclasses.object_config_collection, j.baseclasses.testtools): __jslocation__ = "j.servers.gedis" _CHILDCLASS = GedisServer def get_gevent_server(self, name="", **kwargs): """ return gedis_server as gevent server j.servers.gedis.get("test") """ server = self.get(name=name, **kwargs) return server.gevent_server def _cmds_get(self, key, data): """ Used in client only, starts from data (python client) """ namespace, name = key.split("__") return GedisCmds(namespace=namespace, name=name, data=data) def test(self, name="basic"): """ it's run all tests kosmos 'j.servers.gedis.test()' """ # we don't support running gevent as stdallone any longer # make sure we have a threebot life cl = j.servers.threebot.local_start_default() cl.actors.package_manager.package_add( "threebot_phonebook", git_url="https://github.com/threefoldtech/jumpscaleX_threebot/tree/master/ThreeBotPackages/threefold/phonebook", ) self._threebot_client_default = cl self._test_run(name=name)
python
11
0.631004
124
25.941176
51
starcoderdata
<?php /** * Framework * ------------------------------------------------ * A minimalist PHP framework. * * @copyright Copyright (c) 2010 - 2021 * @license https://opensource.org/licenses/MIT * @link https://github.com/coreyolson/framework * * // ######################################################################################## * * A helper class for working with HTML markup * * @method helpers\html::tag('h3#id.classone.classtwo', 'contents'); * @method helpers\html::tag('p#intro', 'hello world'); * @method helpers\html::tag('a.submit', 'submit', ['href' => '/link/path/']); */ namespace helpers; class html { // Framework traits use __aliases, __singleton; // Alternative method names public static $__aliases = [ 'tag' => ['element'], ]; /** * An array of all valid HTML elements. * * @var array */ private static $tags = array('a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'command', 'datalist', 'dd', 'del', 'details', 'dfn', 'div', 'dl', 'doctype', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'menu', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', ); /** * An array of all valid HTML elements without closing tags. * * @var array */ private static $singleTags = array('area', 'base', 'br', 'col', 'command', 'doctype', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'meta', 'source', 'track', 'wbr', ); /** * Prepares an HTML element tag for self::create(). Attempts to detect CSS * selectors to make tags with ID and Classes. Only creates valid tags. * * @param string * @param string * @param array * * @return string */ public static function tag($str, $contents = false, $attributes = array()) { // Split by # and . to get element $iArr = preg_split('/(#|\.)/', $str); // Get the element $tag = strtolower($iArr[0]); // Check if this is a valid element if (!in_array($tag, self::$tags)) { // Not a valid tag return false; } // Search for an element ID preg_match('/#\w+/', $str, $idArr); // Get the ID if specified $id = (isset($idArr[0])) ? substr($idArr[0], 1) : false; // Search for class names preg_match_all('/\.[\w-]+/', $str, $classArr); // Check for classes if (count($classArr[0])) { // Get the classes foreach ($classArr[0] as $class) { // Add classes and remove CSS selection $classes[] = substr($class, 1); } } else { // No classes provided $classes = array(); } // Create the tag return self::create($tag, $id, $classes, $contents, $attributes); } /** * Forms the HTML tag string based on parameters. * * @param string * @param string * @param array * @param string * * @return string */ private static function create($tag, $id, $classes, $contents, $attributes) { // Create a string $str = ''; // Add the opening tag $str .= '<'.$tag; // Check if an ID has been specified if ($id) { // Add ID to the element if specified $str .= ' id="'.$id.'"'; } // Check if there are any classes if (count($classes)) { // Add class(es) to the HTML element $str .= ' class="'.implode(' ', $classes).'"'; } // Check if there are any attributes to add if (count($attributes)) { // Iterate through the attributes foreach ($attributes as $attr => $value) { // Add the attributes $str .= ' '.$attr.'="'.$value.'"'; } } // Check for the type of HTML element if (in_array($tag, self::$singleTags)) { // Add closing tag for single tag elements return $str .= ' />'; } else { // This is a normal HTML element $str .= '>'; } // Add contents to the element string $str .= $contents; // Add closing tag for normal tag elements $str .= ' // Return HTML element string return $str; } /** * Create a mailto link with optional ordinal encoding. * * @param string * @param bool * * @return object */ public static function mailto($email, $encode = false) { // Create a variable for output $ordinal = ''; // Iterate through each letter in the email string for ($i = 0; $i < strlen($email); ++$i) { // Begin concatenation of the email string $ordinal .= ($encode) ? '&#'.ord($email[$i]).';' : $email[$i]; } // Return mailto tag return $ordinal; } }
php
17
0.483955
94
28.564103
195
starcoderdata
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.test.j2ee.lib; import java.lang.reflect.Method; import javax.swing.JDialog; import org.netbeans.jemmy.JemmyException; import org.netbeans.jemmy.Waitable; import org.netbeans.jemmy.Waiter; import org.netbeans.jemmy.operators.Operator; /** * Handle Progress bars at the main window of NetBeans. * * @author Jiri.Skrivane */ public class ProgressOperator { /** Wait process started. */ public static void waitStarted(final String name, long timeout) { try { Waiter waiter = new Waiter(new Waitable() { public Object actionProduced(Object anObject) { return processInProgress(name) ? Boolean.TRUE : null; } public String getDescription() { return("Wait process "+name+" is started."); } }); waiter.getTimeouts().setTimeout("Waiter.WaitingTime", timeout); waiter.waitAction(null); } catch (InterruptedException e) { throw new JemmyException("Interrupted.", e); } } /** Wait process with given name finished. */ public static void waitFinished(final String name, long timeout) { try { Waiter waiter = new Waiter(new Waitable() { public Object actionProduced(Object anObject) { return processInProgress(name) ? null : Boolean.TRUE; } public String getDescription() { return("Wait process "+name+" is finished."); } }); waiter.getTimeouts().setTimeout("Waiter.WaitingTime", timeout); waiter.waitAction(null); } catch (InterruptedException e) { throw new JemmyException("Interrupted.", e); } } /** Wait all processes finished. */ public static void waitFinished(long timeout) { waitFinished("", timeout); // NOI18N } private static boolean processInProgress(String name) { try { Class clazz = Class.forName("org.netbeans.progress.module.Controller"); Method getDefaultMethod = clazz.getDeclaredMethod("getDefault", (Class[])null); getDefaultMethod.setAccessible(true); Object controllerInstance = getDefaultMethod.invoke(null, (Object[])null); Method getModelMethod = clazz.getDeclaredMethod("getModel", (Class[])null); getModelMethod.setAccessible(true); Object taskModelInstance = getModelMethod.invoke(controllerInstance, (Object[])null); //Method getSizeMethod = taskModelInstance.getClass().getDeclaredMethod("getSize", (Class[])null); //Object size = getSizeMethod.invoke(taskModelInstance, (Object[])null); //System.out.println("SIZE="+((Integer)size)); Method getHandlesMethod = taskModelInstance.getClass().getDeclaredMethod("getHandles", (Class[])null); Object[] handles = (Object[])getHandlesMethod.invoke(taskModelInstance, (Object[])null); for(int i=0;i<handles.length;i++) { Method getDisplayNameMethod = handles[i].getClass().getDeclaredMethod("getDisplayName", (Class[])null); String displayName = (String)getDisplayNameMethod.invoke(handles[i], (Object[])null); //System.out.println("DISPLAY_NAME="+displayName); if(Operator.getDefaultStringComparator().equals(displayName, name)) { return true; } } return false; //Method addListDataListenerMethod = taskModelInstance.getClass().getDeclaredMethod("addListDataListener", ListDataListener.class); //addListDataListenerMethod.invoke(taskModelInstance, new TestProgressBar()); } catch (Exception e) { throw new JemmyException("Reflection operation failed.", e); } } }
java
20
0.626833
143
40.840336
119
starcoderdata
const { module } = require("angular"); module.exports = [ {'userID' : 1, 'name' : 'Kevin'}, {'userID' : 2, 'name' : 'Jeff'}, {'userID' : 3, 'name' : 'Bryan'}, {'userID' : 4, 'name' : 'Gabbey'}, ]
javascript
6
0.520661
38
26
9
starcoderdata
/** Copyright 2017 ( 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 ktrack.repository; import java.io.InputStream; import java.util.Collection; import ktrack.entity.DogName; import ktrack.entity.Sex; public interface DogNamesRepositoryCustom { /** * Gets a random dog name for the specified sex. * * @param sex * The sex. */ DogName getRandomName(Sex sex); /** * Saves an image in the repository * @param inputStream The input stream of the image file. * @param fileName The name of the image file. * @param contentType The content type. * @return The id of the saved image. */ String saveImage(InputStream inputStream, String fileName, String contentType); /** * Removes orphaned images i.e. images that have no dogId specified in their metadata. */ void removeOrphanedImages(); /** * Associates the image ids with the dog id. */ void associateImages(String dogId, Collection imageIds); /** * Dis-Associates the image ids with the dog id. */ void disAssociateImages(String dogId, Collection imageIds); /** * Returns the image as bytes from the image file specified by the id. * @param imageFileId The image file id. * * @return The image data as bytes. Null if an error occurs or if the file corresponding to the id does not exist. */ byte[] getImage(String imageFileId); /** * Returns the image file name and length. * @param imageFileId The image file id * @return an object array of length 2, the first item is the name of the file and the second * item is the size of the file. */ Object[] getImageNameAndLength(String imageFileId); }
java
8
0.686515
115
28.052632
76
starcoderdata
using System; using Newtonsoft.Json; namespace FortniteDotNet.Models.Fortnite.Storefront { public class CatalogEntryPrice { [JsonProperty("currencyType")] public string CurrencyType { get; set; } [JsonProperty("currencySubType")] public string CurrencySubType { get; set; } [JsonProperty("regularPrice")] public int RegularPrice { get; set; } [JsonProperty("dynamicRegularPrice")] public int DynamicRegularPrice { get; set; } [JsonProperty("finalPrice")] public int FinalPrice { get; set; } [JsonProperty("saleExpiration")] public DateTime SaleExpiration { get; set; } [JsonProperty("basePrice")] public int BasePrice { get; set; } } }
c#
11
0.634941
52
25.482759
29
starcoderdata
import sys import pprint def main() -> int: chess_board = { '1h': 'bking', '6c': 'wqueen', '2g': 'bbishop', '5h': 'bqueen', '3e': 'wking', } print('Chess board:') pprint.pprint(chess_board) print() if is_valid_chessboard(chess_board): print('This is a valid chessboard.') else: print('This is an invalid chessboard.') return 0 def is_valid_chessboard(chess_board: dict) -> bool: count_pieces = {} for piece in chess_board.values(): count_pieces.setdefault(piece, 0) count_pieces[piece] += 1 # check for valid number of kings and queens if ( count_pieces.get('bking', 0) > 1 or count_pieces.get('wking', 0) > 1 or count_pieces.get('wqueen', 0) > 1 or count_pieces.get('bqueen', 0) > 1 ): print('~> Invalid number of kings/queens.') print( f" ~> Black kings: {count_pieces.get('bking', 0)}\n" f" ~> White Kings: {count_pieces.get('wking', 0)}\n" f" ~> Black queens: {count_pieces.get('bqueen', 0)}\n" f" ~> White queens: {count_pieces.get('wqueen', 0)}" ) return False # check for valid names valid_pieces = ['pawn', 'knight', 'bishop', 'rook', 'queen', 'king'] for piece in chess_board.values(): if piece[0] != 'w' and piece[0] != 'b': print(f'~> Invalid piece name: {piece}') return False if piece[1:] not in valid_pieces: print(f'~> Invalid piece name: {piece}') return False # check for correct number of pieces for each player white_pieces_count = 0 black_pieces_count = 0 for piece, count in count_pieces.items(): if piece.startswith('b'): black_pieces_count += 1 elif piece.startswith('w'): white_pieces_count += 1 if white_pieces_count > 16 or black_pieces_count > 16: print('~> Invalid number of pieces for either black or white.') print(f' ~> black total pieces: {black_pieces_count}') print(f' ~> white total pieces: {white_pieces_count}') return False # check for valid positions valid_positions = [str(n) + c for n in range(1, 9) for c in 'abcdefgh'] for pos in chess_board.keys(): if pos not in valid_positions: print( f'~> Invalid position for piece ' f'`{chess_board.get(pos)}`: {pos}' ) return False return True if __name__ == '__main__': sys.exit(main())
python
15
0.553022
75
31.085366
82
starcoderdata
package main import ( "bufio" "flag" "fmt" "io" "log" "math" "os" "regexp" "strconv" ) var version = "v1.2.1" type options struct { isBinary bool minValue float64 preserveFormatting bool } // numToHuman returns a replacement function used by rexexp.ReplaceAllStringFunc // to replace numbers in a string with more human-readable values func numToHuman(opt options) func(string) string { var suffixes = []string{"K", "M", "G", "T", "P", "E", "Z", "Y"} var base = 10.0 // float because it reduces the number of casts we have to do below var expdivisor = 3.0 // each successive suffix represents a Pow(base, expdivisor) increase if opt.isBinary { base = 2 expdivisor = 10 } return func(numstr string) string { // we parse as a float64 because it allows us to handle much larger values than uint64 if num, err := strconv.ParseFloat(numstr, 64); err == nil { // don't bother if it's small enough if num < opt.minValue { return numstr } exp := math.Log(num) / math.Log(base) // same as Log suffidx := int((exp / expdivisor) - 1) if suffidx >= len(suffixes) { suffidx = len(suffixes) - 1 } else if suffidx < 0 { suffidx = 0 } shortnum := int(math.Round(num / math.Pow(base, float64(suffidx+1)*expdivisor))) if shortnum < 0 { // oops, overflowed float64 return numstr } var suffix = suffixes[suffidx] if opt.isBinary { suffix = suffix + "i" } if opt.preserveFormatting { // left-pad with spaces return fmt.Sprintf("%*d%s", len(numstr)-1, shortnum, suffix) } else { return fmt.Sprintf("%d%s", shortnum, suffix) } } else { // if we failed to parse the number for whatever reason, just return the original return numstr } } } // humanize takes a Reader and configuration flags and replaces any numbers it reads // with more human-readable versions func humanize(reader io.Reader, writer io.Writer, opt options) { numre := regexp.MustCompile(`\d+`) bufreader := bufio.NewReader(reader) //bufwriter := bufio.NewWriter(*writer) for { line, err := bufreader.ReadString('\n') fmt.Fprint(writer, numre.ReplaceAllStringFunc(line, numToHuman(opt))) if err == io.EOF { break } if err != nil { log.Fatal(err) } } } func main() { var opt options flag.BoolVar(&opt.isBinary, "binary", false, "use base-2 divisors instead of base-10") flag.Float64Var(&opt.minValue, "min", 1000, "minimum absolute value to humanize") flag.BoolVar(&opt.preserveFormatting, "preserve", false, "preserve formatting when replacing") var versionFlag bool flag.BoolVar(&versionFlag, "version", false, "print version and exit") flag.Parse() if versionFlag { fmt.Printf("humanize %s\n", version) os.Exit(0) } humanize(os.Stdin, os.Stdout, opt) }
go
22
0.666192
95
24.545455
110
starcoderdata
/* * The contents of this file are subject to the Initial * Developer's Public License Version 1.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.ibphoenix.com/main.nfs?a=ibphoenix&page=ibp_idpl. * * Software distributed under the License is distributed AS IS, * WITHOUT WARRANTY OF ANY KIND, either express or implied. * See the License for the specific language governing rights * and limitations under the License. * * The Original Code was created by * for the Firebird Open Source RDBMS project. * * Copyright (c) 2006 * and all contributors signed below. * * All Rights Reserved. * Contributor(s): ______________________________________. */ #include "firebird.h" #include "../jrd/Attachment.h" #include "../jrd/DebugInterface.h" #include "../jrd/blb_proto.h" using namespace Jrd; using namespace Firebird; void DBG_parse_debug_info(thread_db* tdbb, bid* blob_id, DbgInfo& dbgInfo) { Jrd::Attachment* attachment = tdbb->getAttachment(); blb* blob = blb::open(tdbb, attachment->getSysTransaction(), blob_id); const ULONG length = blob->blb_length; HalfStaticArray<UCHAR, 128> tmp; UCHAR* temp = tmp.getBuffer(length); blob->BLB_get_data(tdbb, temp, length); DBG_parse_debug_info(length, temp, dbgInfo); } void DBG_parse_debug_info(ULONG length, const UCHAR* data, DbgInfo& dbgInfo) { const UCHAR* const end = data + length; bool bad_format = false; if ((*data++ != fb_dbg_version) || (end[-1] != fb_dbg_end)) bad_format = true; UCHAR version = UCHAR(0); if (!bad_format) { version = *data++; if (!version || version > CURRENT_DBG_INFO_VERSION) bad_format = true; } while (!bad_format && (data < end)) { UCHAR code = *data++; switch (code) { case fb_dbg_map_src2blr: { const unsigned length = (version == DBG_INFO_VERSION_1) ? 6 : 12; if (data + length > end) { bad_format = true; break; } MapBlrToSrcItem i; i.mbs_src_line = *data++; i.mbs_src_line |= *data++ << 8; if (version > DBG_INFO_VERSION_1) { i.mbs_src_line |= *data++ << 16; i.mbs_src_line |= *data++ << 24; } i.mbs_src_col = *data++; i.mbs_src_col |= *data++ << 8; if (version > DBG_INFO_VERSION_1) { i.mbs_src_col |= *data++ << 16; i.mbs_src_col |= *data++ << 24; } i.mbs_offset = *data++; i.mbs_offset |= *data++ << 8; if (version > DBG_INFO_VERSION_1) { i.mbs_offset |= *data++ << 16; i.mbs_offset |= *data++ << 24; } dbgInfo.blrToSrc.add(i); } break; case fb_dbg_map_varname: case fb_dbg_map_curname: { if (data + 3 > end) { bad_format = true; break; } // variable/cursor number USHORT index = *data++; index |= *data++ << 8; // variable/cursor name string length USHORT length = *data++; if (data + length > end) { bad_format = true; break; } if (code == fb_dbg_map_varname) dbgInfo.varIndexToName.put(index, MetaName((const TEXT*) data, length)); else dbgInfo.curIndexToName.put(index, MetaName((const TEXT*) data, length)); // variable/cursor name string data += length; } break; case fb_dbg_map_argument: { if (data + 4 > end) { bad_format = true; break; } ArgumentInfo info; // argument type info.type = *data++; // argument number info.index = *data++; info.index |= *data++ << 8; // argument name string length USHORT length = *data++; if (data + length > end) { bad_format = true; break; } dbgInfo.argInfoToName.put(info, MetaName((const TEXT*) data, length)); // variable name string data += length; } break; case fb_dbg_subproc: case fb_dbg_subfunc: { if (version == DBG_INFO_VERSION_1 || data >= end) { bad_format = true; break; } // argument name string length ULONG length = *data++; if (data + length >= end) { bad_format = true; break; } MetaName name((const TEXT*) data, length); data += length; if (data + 4 >= end) { bad_format = true; break; } length = *data++; length |= *data++ << 8; length |= *data++ << 16; length |= *data++ << 24; if (data + length >= end) { bad_format = true; break; } AutoPtr sub(FB_NEW_POOL(dbgInfo.getPool()) DbgInfo(dbgInfo.getPool())); DBG_parse_debug_info(length, data, *sub); data += length; if (code == fb_dbg_subproc) dbgInfo.subProcs.put(name, sub.release()); else dbgInfo.subFuncs.put(name, sub.release()); break; } case fb_dbg_end: if (data != end) bad_format = true; break; default: bad_format = true; } } if (bad_format || data != end) { dbgInfo.clear(); ERR_post_warning(Arg::Warning(isc_bad_debug_format)); } }
c++
19
0.579984
84
19.598361
244
starcoderdata
const Game = require('./game.js'); const Message = require('../message.js'); let room = {}; setInterval(() => { if (room) { room.update(); } }, 1000 / 60); process.on('message', (m) => { switch (m.type) { case 'initData': { room = new Game(m.data.room); room.addPlayer({ hash: m.data.playerHash, id: m.data.playerId, name: m.data.playerName, }); process.send(new Message('initData', { id: m.data.playerId, state: room.state, players: room.players, enemy: room.enemy.getClientData(), bullets: room.bullets, })); break; } case 'addPlayer': { room.addPlayer({ hash: m.data.playerHash, id: m.data.playerId, name: m.data.playerName, }); process.send(new Message('initData', { id: m.data.playerId, state: room.state, players: room.players, enemy: room.enemy.getClientData(), bullets: room.bullets, })); process.send(new Message('addPlayer', { hash: m.data.playerHash, player: room.players[m.data.playerHash], })); break; } case 'deletePlayer': { if (room.players[m.data.playerHash]) { delete room.players[m.data.playerHash]; } process.send(new Message('deletePlayer', { hash: m.data.playerHash, })); break; } case 'updatePlayer': { if (room.state === 'preparing') { room.players[m.data.playerHash].updatePreparing(m.data.player); } else if (room.state === 'playing') { room.players[m.data.playerHash].updatePlaying(m.data.player); } break; } default: { console.log(`unclear type: ${m.type} from sockets.js`); break; } } });
javascript
15
0.544199
71
22.506494
77
starcoderdata
import unittest import os import shutil import sys from pathlib import Path # give the test runner the import access pysixdesk_path = str(Path(__file__).parents[3].absolute()) sys.path.insert(0, pysixdesk_path) # setting environment variable for htcondor job. if 'PYTHONPATH' in os.environ.keys(): os.environ['PYTHONPATH'] = f"{pysixdesk_path}:{os.environ['PYTHONPATH']}" else: os.environ['PYTHONPATH'] = f"{pysixdesk_path}" import pysixdesk from .test_mysql import MySqlStudy class MySqlDBColl(MySqlStudy, unittest.TestCase): def setUp(self): self.test_folder = Path('integration_test/mysql_coll') self.test_folder.mkdir(parents=True, exist_ok=True) self.ws_name = 'integration_test' self.ws = pysixdesk.WorkSpace(str(self.test_folder / self.ws_name)) self.st_name = 'mysql_coll' self.st = None def test_mysql_study(self): self.mysql_study(config='MySqlCollConfig') # add additional checks def tearDown(self): # need to remove database if self.st is not None and self.st.db_info['db_type'] == 'mysql': conn = self.st.db.conn with conn.cursor() as c: sql = f"DROP DATABASE admin_{self.ws_name}_{self.st_name};" c.execute(sql) # remove directory shutil.rmtree('integration_test', ignore_errors=True) if __name__ == '__main__': unittest.main()
python
14
0.647265
77
30.688889
45
starcoderdata
#include <bits/stdc++.h> using namespace std; int n; int dist[2][100000],id,s; vector<int>g[100000]; bool dfs(int idx,int par=-1) { if(~par)dist[id][idx]=dist[id][par]+1; for(auto &to:g[idx]) { if(to!=par)dfs(to,idx); } } int main() { cin>>n; for(int i=0;i<n-1;i++) { int a,b; cin>>a>>b; a--; b--; g[a].push_back(b); g[b].push_back(a); } id=0; dfs(0); id=1; dfs(n-1); for(int i=0;i<n;i++) { if(dist[0][i]<=dist[1][i])s++; } if(s>=(n+2)/2)cout<<"Fennec\n";else cout<<"Snuke\n"; return 0; }
c++
11
0.532567
53
13.5
36
codenet
import sys import devs import pytest def test_infinity(): assert devs.infinity == sys.float_info.max
python
7
0.731481
46
12.5
8
starcoderdata
#pragma once #include #include namespace chainer_compiler { #define CLOG() \ if (g_compiler_log) std::cerr } // namespace chainer_compiler
c
5
0.698324
33
13.916667
12
starcoderdata
private void loadDefaultUsers() throws IOException { // BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/users.csv"))); String line = reader.readLine(); // skip first line while ((line = reader.readLine()) != null) { String[] arr = StringUtils.commaDelimitedListToStringArray(line); if (arr.length != 10) continue; if (repository.findByEmail(arr[6]) == null) { Registration reg = new Registration(); try { reg.setName(arr[3]); reg.setSurname(arr[4]); reg.setEmail(arr[6]); reg.setConfirmed(true); reg.setPassword(PasswordHash.createHash(arr[2])); repository.save(reg); User globalUser = updateUser("internal", toMap(reg), null); reg.setUserId(""+globalUser.getId()); repository.save(reg); } catch (Exception e) { logger.error(e.getMessage()); } } } }
java
15
0.633909
114
30
29
inline
using System; using System.Collections.Generic; using System.Reflection.Emit; using KontrolSystem.TO2; using KontrolSystem.TO2.AST; namespace KontrolSystem.KSP.Runtime.KSPMath { public static class Vector3Binding { public static readonly RecordStructType Vector3Type = new RecordStructType("ksp::math", "Vec3", "A 3-dimensional vector.", typeof(Vector3d), new[] { new RecordStructField("x", "x-coordinate", BuiltinType.Float, typeof(Vector3d).GetField("x")), new RecordStructField("y", "y-coordinate", BuiltinType.Float, typeof(Vector3d).GetField("y")), new RecordStructField("z", "z-coordinate", BuiltinType.Float, typeof(Vector3d).GetField("z")), }, new OperatorCollection { { Operator.Neg, new StaticMethodOperatorEmitter(() => BuiltinType.Unit, () => Vector3Type, typeof(Vector3d).GetMethod("op_UnaryNegation", new[] {typeof(Vector3d)})) }, { Operator.Mul, new StaticMethodOperatorEmitter(() => BuiltinType.Float, () => Vector3Type, typeof(Vector3d).GetMethod("op_Multiply", new[] {typeof(double), typeof(Vector3d)})) }, }, new OperatorCollection { { Operator.Add, new StaticMethodOperatorEmitter(() => Vector3Type, () => Vector3Type, typeof(Vector3d).GetMethod("op_Addition", new[] {typeof(Vector3d), typeof(Vector3d)})) }, { Operator.AddAssign, new StaticMethodOperatorEmitter(() => Vector3Type, () => Vector3Type, typeof(Vector3d).GetMethod("op_Addition", new[] {typeof(Vector3d), typeof(Vector3d)})) }, { Operator.Sub, new StaticMethodOperatorEmitter(() => Vector3Type, () => Vector3Type, typeof(Vector3d).GetMethod("op_Subtraction", new[] {typeof(Vector3d), typeof(Vector3d)})) }, { Operator.SubAssign, new StaticMethodOperatorEmitter(() => Vector3Type, () => Vector3Type, typeof(Vector3d).GetMethod("op_Subtraction", new[] {typeof(Vector3d), typeof(Vector3d)})) }, { Operator.Mul, new StaticMethodOperatorEmitter(() => BuiltinType.Float, () => Vector3Type, typeof(Vector3d).GetMethod("op_Multiply", new[] {typeof(Vector3d), typeof(double)})) }, { Operator.Mul, new StaticMethodOperatorEmitter(() => Vector3Type, () => BuiltinType.Float, typeof(Vector3d).GetMethod("Dot")) }, { Operator.MulAssign, new StaticMethodOperatorEmitter(() => BuiltinType.Float, () => Vector3Type, typeof(Vector3d).GetMethod("op_Multiply", new[] {typeof(Vector3d), typeof(double)})) }, { Operator.Div, new StaticMethodOperatorEmitter(() => BuiltinType.Float, () => Vector3Type, typeof(Vector3d).GetMethod("op_Division", new[] {typeof(Vector3d), typeof(double)})) }, { Operator.DivAssign, new StaticMethodOperatorEmitter(() => BuiltinType.Float, () => Vector3Type, typeof(Vector3d).GetMethod("op_Division", new[] {typeof(Vector3d), typeof(double)})) }, { Operator.Eq, new StaticMethodOperatorEmitter(() => Vector3Type, () => BuiltinType.Bool, typeof(Vector3d).GetMethod("op_Equality", new[] {typeof(Vector3d), typeof(Vector3d)})) }, { Operator.NotEq, new StaticMethodOperatorEmitter(() => Vector3Type, () => BuiltinType.Bool, typeof(Vector3d).GetMethod("op_Equality", new[] {typeof(Vector3d), typeof(Vector3d)}), OpCodes.Ldc_I4_0, OpCodes.Ceq) }, }, new Dictionary<string, IMethodInvokeFactory> { { "cross", new BoundMethodInvokeFactory("Calculate the cross/other product with `other` vector.", true, () => Vector3Type, () => new List {new RealizedParameter("other", Vector3Type)}, false, typeof(Vector3d), typeof(Vector3d).GetMethod("Cross")) }, { "dot", new BoundMethodInvokeFactory("Calculate the dot/inner product with `other` vector.", true, () => BuiltinType.Float, () => new List {new RealizedParameter("other", Vector3Type)}, false, typeof(Vector3d), typeof(Vector3d).GetMethod("Dot")) }, { "angle_to", new BoundMethodInvokeFactory("Calculate the angle in degree to `other` vector.", true, () => BuiltinType.Float, () => new List {new RealizedParameter("other", Vector3Type)}, false, typeof(Vector3d), typeof(Vector3d).GetMethod("Angle")) }, { "lerp_to", new BoundMethodInvokeFactory( "Linear interpolate position between this and `other` vector, where `t = 0.0` is this and `t = 1.0` is `other`.", true, () => Vector3Type, () => new List { new RealizedParameter("other", Vector3Type), new RealizedParameter("t", BuiltinType.Float) }, false, typeof(Vector3d), typeof(Vector3d).GetMethod("Lerp")) }, { "project_to", new BoundMethodInvokeFactory("Project this on `other` vector.", true, () => Vector3Type, () => new List {new RealizedParameter("other", Vector3Type)}, false, typeof(Vector3d), typeof(Vector3d).GetMethod("Project")) }, { "distance_to", new BoundMethodInvokeFactory("Calculate the distance between this and `other` vector.", true, () => Vector3Type, () => new List {new RealizedParameter("other", Vector3Type)}, false, typeof(Vector3d), typeof(Vector3d).GetMethod("Distance")) }, { "exclude_from", new BoundMethodInvokeFactory("Exclude this from `other` vector.", true, () => Vector3Type, () => new List {new RealizedParameter("other", Vector3Type)}, false, typeof(Vector3d), typeof(Vector3d).GetMethod("Exclude")) }, { "to_string", new BoundMethodInvokeFactory("Convert vector to string.", true, () => BuiltinType.String, () => new List false, typeof(Vector3d), typeof(Vector3d).GetMethod("ToString", new Type[0])) }, { "to_fixed", new BoundMethodInvokeFactory("Convert the vector to string with fixed number of `decimals`.", true, () => BuiltinType.String, () => new List {new RealizedParameter("decimals", BuiltinType.Int)}, false, typeof(Vector3Binding), typeof(Vector3Binding).GetMethod("ToFixed")) }, { "to_direction", new BoundMethodInvokeFactory("Point in direction of this vector.", true, () => DirectionBinding.DirectionType, () => new List false, typeof(Vector3Binding), typeof(Vector3Binding).GetMethod("ToDirection")) } }, new Dictionary<string, IFieldAccessFactory> { { "magnitude", new BoundPropertyLikeFieldAccessFactory("Magnitude/length of the vector", () => BuiltinType.Float, typeof(Vector3d), typeof(Vector3d).GetProperty("magnitude")) }, { "sqr_magnitude", new BoundPropertyLikeFieldAccessFactory("Squared magnitude of the vector", () => BuiltinType.Float, typeof(Vector3d), typeof(Vector3d).GetProperty("sqrMagnitude")) }, { "normalized", new BoundPropertyLikeFieldAccessFactory("Normalized vector (i.e. scaled to length 1)", () => Vector3Type, typeof(Vector3d), typeof(Vector3d).GetProperty("normalized")) }, { "xzy", new BoundPropertyLikeFieldAccessFactory("Swapped y- and z-coordinate", () => Vector3Type, typeof(Vector3d), typeof(Vector3d).GetProperty("xzy")) } }); public static Vector3d Vec3(double x, double y, double z) => new Vector3d(x, y, z); public static string ToFixed(Vector3d v, long decimals) => v.ToString(decimals <= 0 ? "F0" : "F" + decimals); public static Direction ToDirection(Vector3d v) => new Direction(v, false); } }
c#
25
0.515194
137
58.35119
168
starcoderdata
base::Optional<std::string> LogLineReader::Backward() { DCHECK_LE(0, pos_); if (pos_ == 0) return base::nullopt; // Calculates the maximum traversable range in the file and allocate a buffer. int64_t pos_traversal_start = std::max(pos_ - g_max_line_length, INT64_C(0)); int64_t traversal_length = pos_ - pos_traversal_start; DCHECK_GE(traversal_length, 0); // Allocates a buffer of the segment from |pos_traversal_start| to |pos_|. auto buffer = reader_->MapBuffer(pos_traversal_start, traversal_length); CHECK(buffer->valid()) << "Mmap failed. Maybe the file has been truncated" << " and the current read position got invalid."; // Ensures the current position is the beginning of the previous line. if (buffer->GetChar(pos_ - 1) != '\n') { LOG(WARNING) << "The line is too long or the file is unexpectedly changed." << " The lines read may be broken."; } // Finds the next LF (at the beginning of the line). int64_t last_start = pos_ - 1; while (last_start > pos_traversal_start && buffer->GetChar(last_start - 1) != '\n') { last_start--; } // Ensures the next LF is found. if (last_start != 0 && last_start <= pos_traversal_start) { LOG(ERROR) << "A line is too long to handle (more than " << g_max_line_length << "bytes). Lines around here may be broken."; } // Updates the current position. int64_t line_length = pos_ - last_start - 1; pos_ = last_start; return GetString(std::move(buffer), last_start, line_length); }
c++
11
0.629371
80
37.390244
41
inline
/* Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ /* error.hpp provides a taocrypt error numbers * */ #ifndef TAO_CRYPT_ERROR_HPP #define TAO_CRYPT_ERROR_HPP namespace TaoCrypt { enum ErrorNumber { NO_ERROR_E = 0, // "not in error state" // RandomNumberGenerator WINCRYPT_E = 1001, // "bad wincrypt acquire" CRYPTGEN_E = 1002, // "CryptGenRandom error" OPEN_RAN_E = 1003, // "open /dev/urandom error" READ_RAN_E = 1004, // "read /dev/urandom error" // Integer INTEGER_E = 1010, // "bad DER Integer Header" // ASN.1 SEQUENCE_E = 1020, // "bad Sequence Header" SET_E = 1021, // "bad Set Header" VERSION_E = 1022, // "version length not 1" SIG_OID_E = 1023, // "signature OID mismatch" BIT_STR_E = 1024, // "bad BitString Header" UNKNOWN_OID_E = 1025, // "unknown key OID type" OBJECT_ID_E = 1026, // "bad Ojbect ID Header" TAG_NULL_E = 1027, // "expected TAG NULL" EXPECT_0_E = 1028, // "expected 0" OCTET_STR_E = 1029, // "bad Octet String Header" TIME_E = 1030, // "bad TIME" DATE_SZ_E = 1031, // "bad Date Size" SIG_LEN_E = 1032, // "bad Signature Length" UNKOWN_SIG_E = 1033, // "unknown signature OID" UNKOWN_HASH_E = 1034, // "unknown hash OID" DSA_SZ_E = 1035, // "bad DSA r or s size" BEFORE_DATE_E = 1036, // "before date in the future" AFTER_DATE_E = 1037, // "after date in the past" SIG_CONFIRM_E = 1038, // "bad self signature confirmation" SIG_OTHER_E = 1039, // "bad other signature confirmation" CONTENT_E = 1040, // "bad content processing" PEM_E = 1041 // "bad pem format error" // add error string to yassl/src/yassl_error.cpp !!! }; struct Error { ErrorNumber what_; // description number, 0 for no error explicit Error(ErrorNumber w = NO_ERROR_E) : what_(w) {} ErrorNumber What() const { return what_; } void SetError(ErrorNumber w) { what_ = w; } }; } // namespace TaoCrypt #endif // TAO_CRYPT_ERROR_HPP
c++
10
0.647659
79
30.921348
89
starcoderdata
package com.example.library.service; import com.example.library.domain.bookSearch.BookFact; import com.example.library.domain.bookSearch.VolumeInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; @Service public class BookSearchService { private RestTemplate restTemplate; @NotNull @NotEmpty private String bookTitle = ""; private String url = "https://www.googleapis.com/books/v1/volumes?q=" + bookTitle + "&key=AIzaSyDQ5S3dnCdR3YKAviYoyqsQFCekLK-1cZs&startIndex=1&maxResults=1"; public BookSearchService() { super(); } @Autowired public BookSearchService(RestTemplate restTemplate) { super(); this.restTemplate = restTemplate; } public VolumeInfo getBooks(String bookTitle) { this.bookTitle = bookTitle; ResponseEntity bookFact = restTemplate.exchange( "https://www.googleapis.com/books/v1/volumes?q=" + bookTitle + "&startIndex=1&maxResults=1", HttpMethod.GET, HttpEntity.EMPTY, BookFact.class); VolumeInfo volumeInfo = bookFact.getBody().getItems().stream().findFirst().get(). getVolumeInfo(); return volumeInfo; } }
java
12
0.706938
161
28.857143
56
starcoderdata
#include #if defined(__mips_msa) # include # define CV_MSA 1 #endif #if defined CV_MSA int test() { const float src[] = { 0.0f, 0.0f, 0.0f, 0.0f }; v4f32 val = (v4f32)__msa_ld_w((const float*)(src), 0); return __msa_copy_s_w(__builtin_msa_ftint_s_w (val), 0); } #else #error "MSA is not supported" #endif int main() { printf("%d\n", test()); return 0; }
c++
12
0.607477
60
16.833333
24
starcoderdata
def test_read_dataset_single_epoch(self): config = input_reader_pb2.InputReader() config.num_epochs = 1 config.num_readers = 1 config.shuffle = False def graph_fn(): return self._get_dataset_next( [self._path_template % '0'], config, batch_size=30) data = self.execute(graph_fn, []) # Note that the execute function extracts single outputs if the return # value is of size 1. self.assertAllEqual(data, [1, 10]) # First batch will retrieve as much as it can, second batch will fail. def graph_fn_second_batch(): return self._get_dataset_next( [self._path_template % '0'], config, batch_size=30, num_batches_skip=1) self.assertRaises(tf.errors.OutOfRangeError, self.execute, compute_fn=graph_fn_second_batch, inputs=[])
python
11
0.639089
74
33.791667
24
inline
function(event) { // Look if the search is for an issuenumber var issuenumber = $('.query').val().match(/^#(\d+)$/); if (issuenumber) { // It is, prevent default search and go to issue page event.preventDefault(); window.location.href = '/issues/' + issuenumber[1]; } }
javascript
13
0.585209
59
33.666667
9
inline
using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; namespace MySqlConnector.Tests; public sealed class FakeMySqlServer { public FakeMySqlServer() { m_tcpListener = new(IPAddress.Any, 0); m_lock = new(); m_connections = new(); m_tasks = new(); } public void Start() { m_activeConnections = 0; m_cts = new(); m_tcpListener.Start(); m_tasks.Add(AcceptConnectionsAsync()); } public void Stop() { if (m_cts is not null) { m_cts.Cancel(); m_tcpListener.Stop(); try { Task.WaitAll(m_tasks.ToArray()); } catch (AggregateException) { } m_connections.Clear(); m_tasks.Clear(); m_cts.Dispose(); m_cts = null; } } public int Port => ((IPEndPoint) m_tcpListener.LocalEndpoint).Port; public int ActiveConnections => m_activeConnections; public string ServerVersion { get; set; } = "5.7.10-test"; public bool SuppressAuthPluginNameTerminatingNull { get; set; } public bool SendIncompletePostHandshakeResponse { get; set; } public bool BlockOnConnect { get; set; } internal void CancelQuery(int connectionId) { lock (m_lock) { if (connectionId >= 1 && connectionId <= m_connections.Count) m_connections[connectionId - 1].CancelQueryEvent.Set(); } } internal void ClientDisconnected() => Interlocked.Decrement(ref m_activeConnections); private async Task AcceptConnectionsAsync() { while (true) { var tcpClient = await m_tcpListener.AcceptTcpClientAsync(); Interlocked.Increment(ref m_activeConnections); lock (m_lock) { var connection = new FakeMySqlServerConnection(this, m_tasks.Count); m_connections.Add(connection); m_tasks.Add(connection.RunAsync(tcpClient, m_cts.Token)); } } } readonly object m_lock; readonly TcpListener m_tcpListener; readonly List m_connections; readonly List m_tasks; CancellationTokenSource m_cts; int m_activeConnections; }
c#
18
0.704071
86
21.377778
90
starcoderdata
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Tipoestudiociclo_model extends CI_Model{ var $table; public function __construct(){ parent::__construct(); $this->table = "ant_tipoestudiociclo"; $this->table_ciclo = "ant_ciclo"; $this->table_tipoestudio = "ant_tipoestudio"; } public function seleccionar($default='',$filter='',$filter_not='',$number_items='',$offset=''){ if($default!="") $arreglo = array($default=>':: Seleccione ::'); foreach($this->listar($filter,$filter_not='',$number_items='',$offset='') as $indice=>$valor) { $indice1 = $valor->TIPCICLOP_Codigo; $valor1 = $valor->TIPC_Nombre; $arreglo[$indice1] = $valor1; } return $arreglo; } public function listar($filter,$filter_not='',$number_items='',$offset=''){ $this->db->select('*'); $this->db->from($this->table." as c",$number_items,$offset); $this->db->join($this->table_ciclo.' as d','d.CICLOP_Codigo=c.CICLOP_Codigo','inner'); $this->db->join($this->table_tipoestudio.' as e','e.TIPP_Codigo=c.TIPP_Codigo','inner'); if(isset($filter->ciclo)) $this->db->where(array("c.CICLOP_Codigo"=>$filter->ciclo)); if(isset($filter->tipoestudiociclo)) $this->db->where(array("c.TIPCICLOP_Codigo"=>$filter->tipoestudiociclo)); if(isset($filter->tipoestudio) && $filter->tipoestudio!='') $this->db->where(array("c.TIPP_Codigo"=>$filter->tipoestudio)); if(isset($filter->order_by) && count($filter->order_by)>0){ foreach($filter->order_by as $indice=>$value){ $this->db->order_by($indice,$value); } } $query = $this->db->get(); $resultado = array(); if($query->num_rows>0){ $resultado = $query->result(); } return $resultado; } public function obtener($filter,$filter_not=''){ $listado = $this->listar($filter,$filter_not='',$number_items='',$offset=''); if(count($listado)>1) $resultado = "Existe mas de un resultado"; else $resultado = isset($listado[0])?(object)$listado[0]:""; return $resultado; } public function modificar($codigo,$data){ $this->db->where("TIPCICLOP_Codigo",$codigo); $this->db->update($this->table,$data); } public function eliminar($codigo){ $this->db->delete($this->table,array('TIPCICLOP_Codigo' => $codigo)); } public function insertar($data){ $this->db->insert($this->table,$data); return $this->db->insert_id(); } } ?>
php
15
0.552747
131
39.761194
67
starcoderdata
<?php namespace App\Http\Controllers\frontend; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Model\PropertyDetails; use App\Model\Home; use App\Model\HomeCity; use App\Model\Blog; use Config; use App\Model\Users; use App\Model\Propertyreview; use App\Model\Userssearch; class HomeController extends Controller { function __construct(){ parent::__construct(); } public function home(Request $request){ $session = $request->session()->all(); if ($request->isMethod("post")) { if(isset($session['logindata'])){ $objUserssearch = new Userssearch(); $res = $objUserssearch->addEdituser($request,$session['logindata'][0]['id']); if($res){ return redirect('property'); } }else{ return redirect('property'); } } $objPropertyDetails = new PropertyDetails(); $data['property_type'] = $objPropertyDetails->getPropertyType(); $objUsers = new Users(); $data['agentListSerch'] = $objUsers->agentListSerch(); $objUsers = new Users(); $data['agentList'] = $objUsers->agentListHome(); $objPropertyreview = new Propertyreview(); $data['review'] = $objPropertyreview->reviewList(); $objUsers = new Users(); $data['companyList'] = $objUsers->companyList(); $objUsers = new Users(); $data['companyListSerch'] = $objUsers->companyListSerch(); $objUsers = new Users(); $data['agencyListSerch'] = $objUsers->agencyListSerch(); $objBlog = new Blog(); $data['blogDetails'] = $objBlog->getBlogList(); $data['title'] = Config::get( 'constants.PROJECT_NAME' ) . ' || Real Estate'; $data['description'] = Config::get( 'constants.PROJECT_NAME' ) . ' || Real Estate'; $data['keywords'] = Config::get( 'constants.PROJECT_NAME' ) . ' || Real Estate'; $data['css'] = array( 'select2/select2.css', 'range-slider/ion.rangeSlider.css', 'owl-carousel/owl.carousel.min.css', 'magnific-popup/magnific-popup.css', 'typeahead/typeahead.css', 'jquery-ui/jquery-ui.min.css' ); $data['plugincss'] = array(); $data['pluginjs'] = array( 'jquery.appear.js', 'counter/jquery.countTo.js', 'select2/select2.full.js', 'range-slider/ion.rangeSlider.min.js', 'owl-carousel/owl.carousel.min.js', 'magnific-popup/jquery.magnific-popup.min.js', 'countdown/jquery.downCount.js', 'typeahead/handlebars.min.js', 'typeahead/typeahead.bundle.min.js', 'jquery-ui/jquery-ui.min.js' ); $data['js'] = array( 'home.js', ); $data['funinit'] = array( 'Home.init()' ); $objhomePage = new Home(); $data['property_location'] = $objhomePage->propertiesByLocation(); $data['feature_property'] = $objhomePage->featuredProperty(); $objhomeCity = new HomeCity(); $data['homecity'] = $objhomeCity->gethomeCity(); return view('frontend.pages.home.home', $data); } public function language($lang){ setcookie('language', $lang, time() + (86400 * 30), "/"); // 86400 = 1 day return redirect()->route('home'); } }
php
18
0.550169
93
32.158879
107
starcoderdata
'use strict'; var DONATION_STATS_URL = 'https://gamesdonequick.com/tracker/12?json'; var POLL_INTERVAL = 3 * 60 * 1000; var util = require('util'); var Q = require('q'); var request = require('request'); var nodecg = null; module.exports = function (extensionApi) { nodecg = extensionApi; nodecg.declareSyncedVar({ name: 'total', initialVal: 0 }); nodecg.declareSyncedVar({ name: 'totalAutoUpdate', initialVal: true, setter: function(newVal) { if (newVal) { nodecg.log.info('Automatic updating of donation total enabled'); updateTotal(true); } else { nodecg.log.warn('Automatic updating of donation total DISABLED'); clearInterval(updateInterval); } } }); // Get initial data update(); // Get latest prize data every POLL_INTERVAL milliseconds nodecg.log.info("Polling donation total every %d seconds...", POLL_INTERVAL / 1000); var updateInterval = setInterval(update.bind(this), POLL_INTERVAL); // Dashboard can invoke manual updates nodecg.listenFor('updateTotal', updateTotal); function updateTotal(silent, cb) { if (!silent) nodecg.log.info("Manual donation total update button pressed, invoking update..."); clearInterval(updateInterval); updateInterval = setInterval(update.bind(this), POLL_INTERVAL); update() .then(function (updated) { cb(null, updated); }, function (error) { cb(error); }); } }; function update() { var deferred = Q.defer(); request(DONATION_STATS_URL, function (error, response, body) { if (!error && response.statusCode == 200) { var stats = JSON.parse(body); var total = parseFloat(stats.agg.amount || 0); if (total != nodecg.variables.total) { nodecg.variables.total = total; nodecg.log.info("Updated total:", total); deferred.resolve(true); } else { nodecg.log.info("Total unchanged:", total); deferred.resolve(false); } } else { var msg = ''; if (error) msg = util.format("Could not get donation total:", error.message); else if (response) msg = util.format("Could not get donation total, response code %d", response.statusCode); else msg = util.format("Could not get donation total, unknown error"); nodecg.log.error(msg); deferred.reject(msg); } }); return deferred.promise; }
javascript
25
0.577548
120
32.02439
82
starcoderdata
import os from surili_core.pipelines import pipeline, step from surili_core.worker import Worker from surili_core.workspace import Workspace def test_pipeline(): class MyWorker(Worker): def run(self, ws: Workspace): assert ws.path != ws.root.path assert ws.path.startswith(ws.root.path) print('my personal worker : ws={}'.format(str(ws))) with Workspace.from_path('generated/my_workspace/test') as _: assert os.path.exists(_.path) pipeline( steps=[ step(step_id='step_01', worker=None), step(step_id='step_02', worker=lambda ws: print('ok STEP 2')), step(step_id='step_03', worker=MyWorker()) ] )(_) assert os.path.exists(_.path_to('out.txt')) assert os.path.exists(_.path_to('err.txt')) assert not os.path.exists(_.path)
python
18
0.597665
78
29.387097
31
starcoderdata
using System.Threading.Tasks; namespace System.Net.Mqtt.Sdk.Flows { internal interface IServerPublishReceiverFlow : IProtocolFlow { Task SendWillAsync (string clientId); } }
c#
8
0.72449
65
20.777778
9
starcoderdata
package v2action import "code.cloudfoundry.org/cli/api/cloudcontroller/ccv2" type FeatureFlagState string const ( FeatureFlagEnabled FeatureFlagState = "enabled" FeatureFlagDisabled FeatureFlagState = "disabled" ) type FeatureFlag ccv2.FeatureFlag func (f FeatureFlag) State() FeatureFlagState { if f.Enabled { return FeatureFlagEnabled } return FeatureFlagDisabled } func (actor Actor) GetFeatureFlags() ([]FeatureFlag, Warnings, error) { featureFlags, warnings, err := actor.CloudControllerClient.GetConfigFeatureFlags() if err != nil { return nil, Warnings(warnings), err } var convertedFeatureFlags []FeatureFlag for _, flag := range featureFlags { convertedFeatureFlags = append(convertedFeatureFlags, FeatureFlag(flag)) } return convertedFeatureFlags, Warnings(warnings), nil }
go
11
0.778986
83
23.352941
34
starcoderdata
public static ConnectorDoc createDocForNode(BLangConnector connectorNode) { String connectorName = connectorNode.getName().value; List<Variable> parameters = new ArrayList<>(); List<Documentable> actions = new ArrayList<>(); // Iterate through the connector parameters if (connectorNode.getParameters().size() > 0) { for (BLangVariable param : connectorNode.getParameters()) { String dataType = type(param); String desc = paramAnnotation(connectorNode, param); Variable variable = new Variable(param.getName().value, dataType, desc); parameters.add(variable); } } //Iterate through the actions of the connectors if (connectorNode.getActions().size() > 0) { for (BLangAction action : connectorNode.getActions()) { actions.add(createDocForNode(action)); } } return new ConnectorDoc(connectorName, description(connectorNode), actions, parameters); }
java
14
0.620755
96
45.130435
23
inline
const prompts = require('prompts') const kleur = require('kleur') const Table = require('cli-table3') const envinfo = require('envinfo') const Command = require('./lib/command') const shouldUseYarn = require('./lib/shouldUseYarn') const { install, uninstall, pkgi, pkgrm } = require('./lib/install') module.exports.shouldUseYarn = shouldUseYarn module.exports.install = install module.exports.uninstall = uninstall module.exports.pkgi = pkgi module.exports.pkgrm = pkgrm module.exports.Command = Command module.exports.prompts = prompts module.exports.kleur = kleur module.exports.Table = Table module.exports.envinfo = envinfo
javascript
6
0.768621
68
30.55
20
starcoderdata
#ifndef Navigation_MuonForwardNavigableLayer_H #define Navigation_MuonForwardNavigableLayer_H /** \class MuonForwardNavigableLayer * * Navigable layer for Forward Muon * * * \author : Stefano Lacaprara - INFN Padova <[email protected]> * * Modification: * Chang Liu: * compatibleLayers(dir) and compatibleLayers(fts, dir) are added, * which return ALL DetLayers that are compatible with a given DetLayer. */ /* Collaborating Class Declarations */ #include "RecoMuon/Navigation/interface/MuonDetLayerMap.h" #include "RecoMuon/Navigation/interface/MuonEtaRange.h" class DetLayer; class ForwardDetLayer; /* Base Class Headers */ #include "RecoMuon/Navigation/interface/MuonNavigableLayer.h" /* C++ Headers */ /* ====================================================================== */ /* Class MuonForwardNavigableLayer Interface */ class MuonForwardNavigableLayer : public MuonNavigableLayer { public: MuonForwardNavigableLayer(const ForwardDetLayer* fdl, const MapB& innerBarrel, const MapE& outerEndcap, const MapE& innerEndcap, const MapB& allInnerBarrel, const MapE& allOuterEndcap, const MapE& allInnerEndcap) : theDetLayer(fdl), theInnerBarrelLayers(innerBarrel), theOuterEndcapLayers(outerEndcap), theInnerEndcapLayers(innerEndcap), theAllInnerBarrelLayers(allInnerBarrel), theAllOuterEndcapLayers(allOuterEndcap), theAllInnerEndcapLayers(allInnerEndcap) {} /// Constructor with outer layers only MuonForwardNavigableLayer(const ForwardDetLayer* fdl, const MapE& outerEndcap) : theDetLayer(fdl), theOuterEndcapLayers(outerEndcap) {} /// Constructor with all outer layers only MuonForwardNavigableLayer(const ForwardDetLayer* fdl, const MapE& outerEndcap, const MapE& allOuterEndcap) : theDetLayer(fdl), theOuterEndcapLayers(outerEndcap), theAllOuterEndcapLayers(allOuterEndcap) {} /// NavigableLayer interface std::vector<const DetLayer*> nextLayers(NavigationDirection dir) const override; /// NavigableLayer interface std::vector<const DetLayer*> nextLayers(const FreeTrajectoryState& fts, PropagationDirection dir) const override; std::vector<const DetLayer*> compatibleLayers(NavigationDirection dir) const override; /// NavigableLayer interface std::vector<const DetLayer*> compatibleLayers(const FreeTrajectoryState& fts, PropagationDirection dir) const override; /// return DetLayer const DetLayer* detLayer() const override; /// set DetLayer void setDetLayer(const DetLayer*) override; /// Operations MapE getOuterEndcapLayers() const { return theOuterEndcapLayers; } MapE getInnerEndcapLayers() const { return theInnerEndcapLayers; } MapB getInnerBarrelLayers() const { return theInnerBarrelLayers; } MapE getAllOuterEndcapLayers() const { return theAllOuterEndcapLayers; } MapE getAllInnerEndcapLayers() const { return theAllInnerEndcapLayers; } MapB getAllInnerBarrelLayers() const { return theAllInnerBarrelLayers; } /// set inward links void setInwardLinks(const MapB&, const MapE&); void setInwardCompatibleLinks(const MapB&, const MapE&); private: void pushResult(std::vector<const DetLayer*>& result, const MapB& map) const; void pushResult(std::vector<const DetLayer*>& result, const MapE& map) const; void pushResult(std::vector<const DetLayer*>& result, const MapB& map, const FreeTrajectoryState& fts) const; void pushResult(std::vector<const DetLayer*>& result, const MapE& map, const FreeTrajectoryState& fts) const; void pushCompatibleResult(std::vector<const DetLayer*>& result, const MapB& map, const FreeTrajectoryState& fts) const; void pushCompatibleResult(std::vector<const DetLayer*>& result, const MapE& map, const FreeTrajectoryState& fts) const; private: const ForwardDetLayer* theDetLayer; MapB theInnerBarrelLayers; MapE theOuterEndcapLayers; MapE theInnerEndcapLayers; MapB theAllInnerBarrelLayers; MapE theAllOuterEndcapLayers; MapE theAllInnerEndcapLayers; }; #endif
c
18
0.70337
115
37.336283
113
research_code
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using AForge.Math; namespace STPConverter { public class MeshModel { public string Meta; private readonly IList _points; private readonly IList _triangles; public MeshModel(IList points, IList triangles) { _points = points; _triangles = triangles; } public IList Points { get { return _points; } } public IList Triangles { get { return _triangles; } } public override string ToString() { return String.Format("<MeshModel({0}, {1})>", String.Join("|", Points.Select(x => x.ToString()).ToArray()), String.Join("|", Triangles.Select(x => x.ToString(CultureInfo.InvariantCulture)).ToArray())); } } }
c#
24
0.561786
109
24.342105
38
starcoderdata
static void Main(string[] args) { Int32 TargetPID = 0; string targetExe = null; // Load the parameter while ((args.Length != 1) || !Int32.TryParse(args[0], out TargetPID) || !File.Exists(args[0])) { if (TargetPID > 0) { break; } if (args.Length != 1 || !File.Exists(args[0])) { Console.WriteLine(); Console.WriteLine("Usage: FileMon %PID%"); Console.WriteLine(" or: FileMon PathToExecutable"); Console.WriteLine(); Console.Write("Please enter a process Id or path to executable: "); args = new string[] { Console.ReadLine() }; if (String.IsNullOrEmpty(args[0])) return; } else { targetExe = args[0]; break; } } try { RemoteHooking.IpcCreateServer<FileMonInterface>(ref ChannelName, WellKnownObjectMode.SingleCall); string injectionLibrary = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "FileMonInject.dll"); if (String.IsNullOrEmpty(targetExe)) { RemoteHooking.Inject( TargetPID, injectionLibrary, injectionLibrary, ChannelName); Console.WriteLine("Injected to process {0}", TargetPID); } else { RemoteHooking.CreateAndInject(targetExe, "", 0, InjectionOptions.DoNotRequireStrongName, injectionLibrary, injectionLibrary, out TargetPID, ChannelName); Console.WriteLine("Created and injected process {0}", TargetPID); } Console.WriteLine("<Press any key to exit>"); Console.ReadKey(); } catch (Exception ExtInfo) { Console.WriteLine("There was an error while connecting to target:\r\n{0}", ExtInfo.ToString()); Console.WriteLine("<Press any key to exit>"); Console.ReadKey(); } }
c#
21
0.472772
173
38.754098
61
inline
fn test_link() { // This tests that linking worked. If only "cargo build" is issued, it does // not guarantee that linking worked. With this test, "cargo test" only // passes if the apriltag library was succesfully linked. let td: *mut apriltag_sys::apriltag_detector = unsafe { apriltag_sys::apriltag_detector_create() }; unsafe { apriltag_sys::apriltag_detector_destroy(td) }; }
rust
8
0.691176
79
50.125
8
inline
package memory import ( "sync" "github.com/rodrigodiez/zorro/pkg/storage" ) type memory struct { mutex *sync.RWMutex k map[string]string v map[string]string metrics *storage.Metrics } func (m *memory) LoadOrStore(key string, value string) (actualValue string, loaded bool) { m.mutex.Lock() defer m.mutex.Unlock() actual, ok := m.k[key] if ok { m.incrLoadOps() return actual, true } m.k[key], m.v[value] = value, key m.incrStoreOps() return value, false } func (m *memory) Resolve(value string) (key string, ok bool) { m.mutex.RLock() defer m.mutex.RUnlock() key, ok = m.v[value] m.incrResolveOps() return key, ok } // New creates a new Storage that lives in memory. // // This type of storage is intended for testing and demonstration purposes only. // Although the implementation is safe for concurrent use, it is not persisted. func New() storage.Storage { return &memory{ mutex: &sync.RWMutex{}, k: make(map[string]string), v: make(map[string]string), } } func (m *memory) WithMetrics(metrics *storage.Metrics) storage.Storage { m.metrics = metrics return m } func (m *memory) Close() { } func (m *memory) incrStoreOps() { if m.metrics != nil && m.metrics.StoreOps != nil { m.metrics.StoreOps.Add(int64(1)) } } func (m *memory) incrLoadOps() { if m.metrics != nil && m.metrics.LoadOps != nil { m.metrics.LoadOps.Add(int64(1)) } } func (m *memory) incrResolveOps() { if m.metrics != nil && m.metrics.ResolveOps != nil { m.metrics.ResolveOps.Add(int64(1)) } }
go
13
0.670763
90
18.325
80
starcoderdata
package com.google.android.gms.samples.vision.ocrreader; import android.support.annotation.Nullable; import com.facebook.react.bridge.LifecycleEventListener; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.google.android.gms.samples.vision.ocrreader.ui.OcrReaderView; import com.google.android.gms.samples.vision.ocrreader.camera.CameraSourcePreview; import java.util.Collections; import java.util.HashMap; import java.util.Map; public class OcrReaderModule extends ReactContextBaseJavaModule implements LifecycleEventListener { private OcrReaderManager mOcrReaderManager; public OcrReaderModule(ReactApplicationContext reactContext, OcrReaderManager ocrReaderManager) { super(reactContext); reactContext.addLifecycleEventListener(this); mOcrReaderManager = ocrReaderManager; } /** * The name intended for React Native. */ @Override public String getName() { return "RCTOcrReaderModule"; } @Nullable @Override public Map<String, Object> getConstants() { return Collections.unmodifiableMap(new HashMap<String, Object>() { { put("FocusMode", getFocusModes()); put("CameraFillMode", getCameraFillModes()); } }); } private static Map<String, Integer> getFocusModes() { return Collections.unmodifiableMap(new HashMap<String, Integer>() { { put("AUTO", 0); put("TAP", 1); put("FIXED", 2); } }); } private static Map<String, Integer> getCameraFillModes() { return Collections.unmodifiableMap(new HashMap<String, Integer>() { { put("COVER", CameraSourcePreview.FILL_MODE_COVER); put("FIT", CameraSourcePreview.FILL_MODE_FIT); } }); } /* ---------------------------------------------- * ------------- Methods for JS ----------------- * ---------------------------------------------- */ @ReactMethod public void resume(Promise promise) { if (resume()) promise.resolve(null); else promise.reject("2", "Attempted to RESUME barcode scanner before scanner view was instantiated."); } @ReactMethod public void pause(Promise promise) { if (pause()) promise.resolve(null); else promise.reject("3", "Attempted to PAUSE barcode scanner before scanner view was instantiated."); } /* ---------------------------------------------- * ------------- Lifecycle events --------------- * ---------------------------------------------- */ @Override public void onHostResume() { resume(); } @Override public void onHostPause() { pause(); } @Override public void onHostDestroy() { release(); } /* ---------------------------------------------- * ------------- Utility methods ---------------- * ---------------------------------------------- */ private boolean start() { OcrReaderView view = mOcrReaderManager.getOcrReaderView(); if (view != null) { view.start(); } return view != null; } private boolean resume() { OcrReaderView view = mOcrReaderManager.getOcrReaderView(); if (view != null) { view.resume(); } return view != null; } private boolean pause() { OcrReaderView view = mOcrReaderManager.getOcrReaderView(); if (view != null) { view.pause(); } return view != null; } private boolean release() { OcrReaderView view = mOcrReaderManager.getOcrReaderView(); if (view != null) { view.release(); } return view != null; } }
java
14
0.603582
103
23.946667
150
starcoderdata
<?php namespace App\Console; use App\Http\Controllers\IhaController; use Carbon\Carbon; use Illuminate\Support\Facades\DB; use App\Console\Commands\DemoCron; use App\Models\Comments; use App\Models\Post; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; use Illuminate\Support\Str; use App\Models\Category; use App\Models\District; use http\Client\Response; use Illuminate\Http\Request; use Illuminate\Http\UploadedFile; use Storage; class Kernel extends ConsoleKernel { /** * The Artisan commands provided by your application. * * @var array */ protected $commands = [ // php artisan make:command NamazVakitleri --command=namaz:cron Commands\DemoCron::class, Commands\NamazVakitleri::class, Commands\Posttask::class, ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ protected function schedule(Schedule $schedule) { // $schedule->command('demo:cron')->everyMinute(); // $schedule->command('namaz:cron')->monthlyOn(15, '00:00'); $schedule->command('namaz:cron')->everyMinute(); $schedule->command('command:posttask')->everyMinute(); ///php artisan schedule:run ile tek sefer çalışıyor /// ile devamlı çalışıyor } /** * Register the commands for the application. * * @return void */ protected function commands() { $this->load(__DIR__ . '/Commands'); require base_path('routes/console.php'); } } /* */
php
12
0.660188
70
22.915493
71
starcoderdata
using gov.sandia.sld.common.utilities; using Xunit; namespace UnitTest { public class ThresholdShould { [Fact] public void ThresholdConstructsProperly() { Threshold t = new Threshold(50); Assert.Equal(50.0, t.Transition, 1); } [Fact] public void Threshold2ConstructsProperly() { Threshold2 t = new Threshold2(40, 50); Assert.Equal(40.0, t.Transition, 1); Assert.Equal(50.0, t.Transition2, 1); } [Fact] public void Threshold2HandlesBadOrderProperly() { // Make sure the thresholds are properly swapped Threshold2 t = new Threshold2(-200, -400); Assert.Equal(-400.0, t.Transition, 1); Assert.Equal(-200.0, t.Transition2, 1); } [Fact] public void PercentThresholdConstructsProperly() { PercentThreshold t = new PercentThreshold(80.0); Assert.Equal(80.0, t.Transition, 1); } [Fact] public void PercentThresholdHandlesMaxThresholdsProperly() { PercentThreshold t = new PercentThreshold(-1.0); Assert.Equal(0.0, t.Transition, 1); t = new PercentThreshold(101.0); Assert.Equal(100.0, t.Transition, 1); } [Fact] public void PercentThreshold2HandlesBadOrderProperly() { // Make sure the thresholds are properly swapped PercentThreshold2 t = new PercentThreshold2(90.0, 80.0); Assert.Equal(80.0, t.Transition, 1); Assert.Equal(90.0, t.Transition2, 1); } [Fact] public void PercentThreshold2HandlesMaxThresholdsProperly() { PercentThreshold2 mem_status = new PercentThreshold2(-1.0, 101.0); Assert.Equal(0.0, mem_status.Transition, 1); Assert.Equal(100.0, mem_status.Transition2, 1); } } }
c#
15
0.569383
78
27.521127
71
starcoderdata
import React from 'react'; const SongwritingPage = ({ active }) => ( <div className={`Songwriting ${active ? 'is-active' : ''}`}> ipsum dolor sit amet, consectetur adipiscing elit. Sed dictum accumsan dolor sed consequat. Nullam euismod lectus sit amet ante dictum, et consectetur ligula luctus. Curabitur sodales elit nec iaculis interdum. Vestibulum vulputate tortor quis neque porttitor, eu fringilla tortor malesuada. Donec eros libero, hendrerit vel ipsum vitae, tempor consectetur ante. ) export default SongwritingPage;
javascript
10
0.757624
379
50.916667
12
starcoderdata
#include "screens/room.h" #include #include #include "net/game.h" #include "net/tcp.h" #include "widget/loading.h" RoomScreen::RoomScreen(std::shared_ptr session, int difficulty, bool isOwner, int index) : isOwner(isOwner), session(session), names(), difficulty(difficulty), index(index) {} RoomScreen::~RoomScreen() {} void RoomScreen::onKeyDown(const Uint8* const keystate) { // Begin Game (only available if you are the room owner) if (isOwner && keystate[SDL_SCANCODE_RETURN] && !entering) { entering = true; auto loading = Global::get().widget.create auto& promise = Global::get().promise.add(); auto msg = net::gameStart(); promise.then(loading->show()) .then([=]() { return session->write(*msg); }) .then(loading->dismiss()); } } void RoomScreen::draw() const { lobbyBackground.draw(); // if owner, display enter (an asset) if (isOwner) enterNotification.draw(); // player list for (unsigned int i = 0; i < names.size(); i++) { auto name = names[i].substr(0, 8); if (i == static_cast<unsigned int>(index)) name += "(you)"; menuWriter.writeText(name, xstart, ystart + i * ystep, normalColor); } } void RoomScreen::update(Uint32 ticks) { (void)ticks; // do nothing when it's offline if (session->isOffline()) return; if (starting) return; net::message msg; bool ready = session->read(msg); if (!ready) return; auto type = msg["type"]; if (type == "state") { auto players = msg["players"]; std::replace(players.begin(), players.end(), ',', ' '); names.clear(); std::stringstream iss(players); std::string player; while (iss >> player) names.emplace_back(player); } else if (type == "start") { starting = true; auto loading = Global::get().widget.create auto& promise = Global::get().promise.add(); Global::get().mixer.transition.play(); promise.then(loading->show()) .sleep(1000) .then(loading->dismiss()) .then([=]() { auto& navigator = Global::get().navigator; navigator.push index, difficulty); return true; }) .then([&]() { entering = false; return true; }); } }
c++
20
0.601602
72
27.590361
83
starcoderdata
/* * The contents of this file are subject to the OpenMRS Public License * Version 1.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://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.mobile.activities.matchingpatients; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import org.openmrs.mobile.R; import org.openmrs.mobile.activities.ACBaseFragment; import org.openmrs.mobile.models.Patient; import org.openmrs.mobile.utilities.DateUtils; import org.openmrs.mobile.utilities.FontsUtil; import org.openmrs.mobile.utilities.ToastUtil; import java.util.List; public class MatchingPatientsFragment extends ACBaseFragment implements MatchingPatientsContract.View{ private Button registerNewPatientButton; private Button mergePatientsButton; private TextView givenName; private TextView middleName; private TextView familyName; private TextView gender; private TextView birthDate; private TextView address1; private TextView address2; private TextView city; private TextView state; private TextView country; private TextView postalCode; private RecyclerView mRecyclerView; private View view; public static MatchingPatientsFragment newInstance(){ return new MatchingPatientsFragment(); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_matching_patients, container, false); initFragmentFields(view); setListeners(); FontsUtil.setFont((ViewGroup) this.getActivity().findViewById(android.R.id.content)); return view; } private void setListeners() { registerNewPatientButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mPresenter.registerNewPatient(); } }); mergePatientsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mPresenter.mergePatients(); } }); } private void initFragmentFields(View root) { registerNewPatientButton = (Button) root.findViewById(R.id.registerNewPatientButton); mergePatientsButton = (Button) root.findViewById(R.id.mergePatientsButton); givenName = (TextView) root.findViewById(R.id.givenName); middleName = (TextView) root.findViewById(R.id.middleName); familyName = (TextView) root.findViewById(R.id.familyName); gender = (TextView) root.findViewById(R.id.gender); birthDate = (TextView) root.findViewById(R.id.birthDate); address1 = (TextView) root.findViewById(R.id.address1); address2 = (TextView) root.findViewById(R.id.address2); city = (TextView) root.findViewById(R.id.city); state = (TextView) root.findViewById(R.id.state); country = (TextView) root.findViewById(R.id.country); postalCode = (TextView) root.findViewById(R.id.postalCode); mRecyclerView = (RecyclerView) root.findViewById(R.id.recyclerView); } @Override public void showPatientsData(Patient patient, List matchingPatients) { setPatientInfo(patient); setMatchingPatients(patient, matchingPatients); } @Override public void enableMergeButton() { mergePatientsButton.setEnabled(true); } @Override public void disableMergeButton() { mergePatientsButton.setEnabled(false); } @Override public void notifyUser(int stringId) { ToastUtil.notify(getString(stringId)); } @Override public void finishActivity() { getActivity().finish(); } @Override public void showErrorToast(String message) { ToastUtil.error(message); } private void setMatchingPatients(Patient patient, List matchingPatients) { mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); mRecyclerView.setAdapter(new MergePatientsRecycleViewAdapter((getActivity()), mPresenter, matchingPatients, patient)); } private void setPatientInfo(Patient patient) { givenName.setText(patient.getPerson().getName().getGivenName()); middleName.setText(patient.getPerson().getName().getMiddleName()); familyName.setText(patient.getPerson().getName().getFamilyName()); if (("M").equals(patient.getPerson().getGender())) { gender.setText(getString(R.string.male)); } else { gender.setText(getString(R.string.female)); } birthDate.setText(DateUtils.convertTime(DateUtils.convertTime(patient.getPerson().getBirthdate()))); if (patient.getPerson().getAddress().getAddress1() != null) { address1.setText(patient.getPerson().getAddress().getAddress1()); } else { address1.setVisibility(View.GONE); view.findViewById(R.id.addr2Separator).setVisibility(View.GONE); view.findViewById(R.id.addr2Hint).setVisibility(View.GONE); } if (patient.getPerson().getAddress().getAddress2() != null) { address2.setText(patient.getPerson().getAddress().getAddress2()); } else { address2.setVisibility(View.GONE); view.findViewById(R.id.addr2Separator).setVisibility(View.GONE); view.findViewById(R.id.addr2Hint).setVisibility(View.GONE); } if (patient.getPerson().getAddress().getCityVillage() != null) { city.setText(patient.getPerson().getAddress().getCityVillage()); } else { city.setVisibility(View.GONE); view.findViewById(R.id.citySeparator).setVisibility(View.GONE); view.findViewById(R.id.cityHint).setVisibility(View.GONE); } if (patient.getPerson().getAddress().getStateProvince() != null) { state.setText(patient.getPerson().getAddress().getStateProvince()); } else { state.setVisibility(View.GONE); view.findViewById(R.id.stateSeparator).setVisibility(View.GONE); view.findViewById(R.id.stateHint).setVisibility(View.GONE); } if (patient.getPerson().getAddress().getCountry() != null) { country.setText(patient.getPerson().getAddress().getCountry()); } else { country.setVisibility(View.GONE); view.findViewById(R.id.countrySeparator).setVisibility(View.GONE); view.findViewById(R.id.countryHint).setVisibility(View.GONE); } if (patient.getPerson().getAddress().getPostalCode() != null) { postalCode.setText(patient.getPerson().getAddress().getPostalCode()); } else { postalCode.setVisibility(View.GONE); view.findViewById(R.id.postalCodeSeparator).setVisibility(View.GONE); view.findViewById(R.id.postalCodeHint).setVisibility(View.GONE); } } }
java
15
0.668395
138
39.621053
190
starcoderdata
@extends('apps.layout.master') @section('title','Purchase Item Invoice List') @section('content') <section id="form-action-layouts"> <?php $dataMenuAssigned=array(); $dataMenuAssigned=StaticDataController::dataMenuAssigned(); $userguideInit=StaticDataController::userguideInit(); //dd($dataMenuAssigned); ?> <div class="row"> <div class="col-md-12"> <div class="card"> <div class="card-header"> <h4 class="card-title" id="basic-layout-card-center"><i class="icon-filter_list"> Purchase Item Invoice Report Filter <a class="heading-elements-toggle"><i class="icon-ellipsis font-medium-3"> <div class="heading-elements"> <ul class="list-inline mb-0"> data-action="collapse"><i class="icon-minus4"> data-action="expand"><i class="icon-expand2"> <div class="card-body collapse in"> <div class="card-block"> <form method="post" action="{{url('purchase/item')}}"> {{csrf_field()}} <fieldset class="form-group"> <div class="row"> <div class="col-md-3"> Date <div class="input-group"> <span class="input-group-addon"><i class="icon-calendar3"> <input @if(!empty($start_date)) value="{{$start_date}}" @endif name="start_date" type="text" class="form-control DropDateWithformat" /> <div class="col-md-3"> Date <div class="input-group"> <span class="input-group-addon"><i class="icon-calendar3"> <input @if(!empty($end_date)) value="{{$end_date}}" @endif name="end_date" type="text" class="form-control DropDateWithformat" /> <div class="col-md-2"> Order ID <div class="input-group"> <input @if(!empty($order_no)) value="{{$order_no}}" @endif type="text" id="eventRegInput1" class="form-control border-primary" placeholder="Invoice ID" name="order_no"> <div class="col-md-3"> <div class="input-group"> <select name="vendor_id" class="select2 form-control"> <option value="">Select a vendor @if(isset($vendor)) @foreach($vendor as $cus) <option @if(!empty($vendor_id) && $vendor_id==$cus->id) selected="selected" @endif value="{{$cus->id}}">{{$cus->name}} @endforeach @endif <div class="col-md-12"> <div class="input-group" style="margin-top:32px;"> <button type="submit" class="btn btn-info btn-darken-1 mr-1" @if($userguideInit==1) data-step="2" data-intro="If you click this button then it will generate your report." @endif> <i class="icon-check2"> Generate Report <a href="javascript:void(0);" data-url="{{url('purchase/item/excel/report')}}" class="btn btn-info btn-darken-2 mr-1 change-action" @if($userguideInit==1) data-step="3" data-intro="If you click this button then it will generate excel file." @endif> <i class="icon-file-excel-o"> Generate Excel <a href="javascript:void(0);" data-url="{{url('purchase/item/pdf/report')}}" class="btn btn-info btn-darken-3 mr-1 change-action" @if($userguideInit==1) data-step="4" data-intro="If you click this button then it will generate pdf file." @endif> <i class="icon-file-pdf-o"> Generate PDF <a href="{{url('purchase/item')}}" style="margin-left: 5px;" class="btn btn-info btn-darken-4" @if($userguideInit==1) data-step="5" data-intro="if you want clear all information then click the reset button." @endif> <i class="icon-refresh"> Reset <a href="{{url('purchase/create')}}" style="margin-left: 5px;" class="btn btn-info btn-darken-4"> <i class="icon-plus"> Create new purchase invoice <!-- Both borders end--> <div class="row"> <div class="col-xs-12"> <div class="card"> <div class="card-header"> <h4 class="card-title"><i class="icon-stack"> Purchase Item Invoice List <a class="heading-elements-toggle"><i class="icon-ellipsis font-medium-3"> <div class="heading-elements"> <ul class="list-inline mb-0"> class="btn btn-info" href="{{url('purchase/create')}}"><i class="icon-plus"> Add New Purchase Invoice data-action="collapse"><i class="icon-minus4"> data-action="expand"><i class="icon-expand2"> <div class="card-body collapse in"> <div class="table-responsive" style="min-height: 360px;"> <table class="table table-striped table-bordered zero-configuration"> No Date Name Cost Price / Vendor @if(isset($dataTable)) @foreach($dataTable as $row) @endforeach @else <td colspan="9">No Record Found @endif <!-- Both borders end --> @endsection @include('apps.include.datatable',['JDataTable'=>1,'selectTwo'=>1,'dateDrop'=>1])
php
5
0.401717
259
49.206897
174
starcoderdata
#pragma once #define _USE_MATH_DEFINES 1 #include #include #include #include #include #include "../programs/vec.hpp" #define STBI_MSC_SECURE_CRT #define STB_IMAGE_IMPLEMENTATION #include "../lib/stb_image.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "../lib/stb_image_write.h" #include "../lib/HDRloader.h" // Struct used to keep GUI state struct App_State { // Default Constructor App_State() { context = Context::create(); // OptiX context W = H = 500; // image resolution samples = 500; // number of samples scene = 2; // counter to selection scene function model = 0; // model selection for mesh test scene frequency = 1; // update preview at every sample currentSample = 0; // always start at sample 0 showProgress = true; // display preview? RTX = true; // use RTX mode russian = true; // use Russian Roulette depth = 50; // max ray repth start = done = false; // hasn't started and it's not yet done fileType = 0; // PNG = 0, HDR = 1 fileName = "out"; // file name without extension } Context context; int W, H, samples, scene, currentSample, model, frequency, fileType, depth; bool done, start, showProgress, RTX, russian; Buffer accBuffer, displayBuffer; std::string fileName; }; // encapsulates PTX string program creation Program createProgram(const char file[], const std::string &name, Context &g_context) { Program program = g_context->createProgramFromPTXString(file, name); if (rtProgramValidate(program->get()) != RT_SUCCESS) { throw "Program " + name + " is not complete.\n"; } return program; } float rnd() { static std::mt19937 gen(0); static std::uniform_real_distribution dis(0.f, 1.f); return dis(gen); } struct Light_Sampler { std::vector sample, pdf; std::vector emissions; }; // returns smallest integer not less than a scalar or each vector component float saturate(float x) { return ffmax(0.f, ffmin(1.f, x)); } float Sign(float x) { if (x < 0.0f) return -1.0f; else if (x > 0.0f) return 1.0f; else return 0.0f; }
c++
10
0.609673
77
27.756098
82
starcoderdata
def test_get_signature_ufunc(): # Make sure that all get_signature can be applied to all numpy # ufuncs for name, func in np.__dict__.items(): if isinstance(func, np.ufunc): get_signature(func) sig = get_signature(np.trunc) assert len(sig.parameters) == 1 sig = get_signature(np.modf) assert len(sig.parameters) == 3
python
10
0.629428
66
27.307692
13
inline
module.exports = { "version": "1.0", "response": { "outputSpeech": { "type": "SSML", "ssml": " Sorry, I didn't get that. How long do you want the meeting to be? }, "shouldEndSession": false, "reprompt": { "outputSpeech": { "type": "SSML", "ssml": " How long do you want the meeting room for? } } }, "sessionAttributes": { "speechOutput": "Sorry, I didn't get that. How long do you want the meeting to be?", "STATE": "_TIMEMODE", "repromptSpeech": "How long do you want the meeting room for?" } }
javascript
12
0.563725
98
28.142857
21
starcoderdata
# Part of Odoo. See LICENSE file for full copyright and licensing details. from unittest.mock import patch from freezegun import freeze_time from odoo.fields import Command from odoo.tests import tagged from odoo.tools import mute_logger from odoo.addons.payment.tests.http_common import PaymentHttpCommon from odoo.addons.payment_asiapay import const from odoo.addons.payment_asiapay.tests.common import AsiaPayCommon @tagged('post_install', '-at_install') class TestPaymentTransaction(AsiaPayCommon, PaymentHttpCommon): @freeze_time('2011-11-02 12:00:21') # Freeze time for consistent singularization behavior. def test_reference_is_singularized(self): """ Test the singularization of reference prefixes. """ reference = self.env['payment.transaction']._compute_reference(self.asiapay.code) self.assertEqual(reference, 'tx-20111102120021') @freeze_time('2011-11-02 12:00:21') # Freeze time for consistent singularization behavior. def test_reference_is_computed_based_on_document_name(self): """ Test the computation of reference prefixes based on the provided invoice. """ self._skip_if_account_payment_is_not_installed() invoice = self.env['account.move'].create({}) reference = self.env['payment.transaction']._compute_reference( self.asiapay.code, invoice_ids=[Command.set([invoice.id])] ) self.assertEqual(reference, 'MISC/2011/11/0001-20111102120021') @freeze_time('2011-11-02 12:00:21') # Freeze time for consistent singularization behavior. def test_reference_is_stripped_at_max_length(self): """ Test that reference prefixes are stripped to have a length of at most 35 chars. """ reference = self.env['payment.transaction']._compute_reference( self.asiapay.code, prefix='this is a long reference of more than 35 characters' ) self.assertEqual(reference, 'this is a long refer-20111102120021') self.assertEqual(len(reference), 35) def test_no_item_missing_from_rendering_values(self): """ Test that the rendered values are conform to the transaction fields. """ tx = self._create_transaction(flow='redirect') with patch( 'odoo.addons.payment_asiapay.models.payment_provider.PaymentProvider' '._asiapay_calculate_signature', return_value='dummy_signature' ): rendering_values = tx._get_specific_rendering_values(None) self.assertDictEqual( rendering_values, { 'amount': tx.amount, 'api_url': tx.provider_id._asiapay_get_api_url(), 'currency_code': const.CURRENCY_MAPPING[tx.currency_id.name], 'language': const.LANGUAGE_CODES_MAPPING['en'], 'merchant_id': tx.provider_id.asiapay_merchant_id, 'mps_mode': 'SCP', 'payment_method': 'ALL', 'payment_type': 'N', 'reference': tx.reference, 'return_url': self._build_url('/payment/asiapay/return'), 'secure_hash': 'dummy_signature', } ) @mute_logger('odoo.addons.payment.models.payment_transaction') def test_no_input_missing_from_redirect_form(self): """ Test that no key is omitted from the rendering values. """ tx = self._create_transaction(flow='redirect') expected_input_keys = [ 'merchantId', 'amount', 'orderRef', 'currCode', 'mpsMode', 'successUrl', 'failUrl', 'cancelUrl', 'payType', 'lang', 'payMethod', 'secureHash', ] processing_values = tx._get_processing_values() form_info = self._extract_values_from_html_form(processing_values['redirect_form_html']) self.assertEqual(form_info['action'], tx.provider_id._asiapay_get_api_url()) self.assertEqual(form_info['method'], 'post') self.assertListEqual(list(form_info['inputs'].keys()), expected_input_keys) def test_processing_notification_data_confirms_transaction(self): """ Test that the transaction state is set to 'done' when the notification data indicate a successful payment. """ tx = self._create_transaction(flow='redirect') tx._process_notification_data(self.webhook_notification_data) self.assertEqual(tx.state, 'done')
python
17
0.631151
98
44.979798
99
research_code
static OS parse(String osName) { if (StringUtils.isBlank(osName)) { // null signals that the current OS is "unknown" return null; } osName = osName.toLowerCase(Locale.ENGLISH); if (osName.contains("aix")) { return AIX; } if (osName.contains("linux")) { return LINUX; } if (osName.contains("mac")) { return MAC; } if (osName.contains("sunos") || osName.contains("solaris")) { return SOLARIS; } if (osName.contains("win")) { return WINDOWS; } return ANY; }
java
9
0.528333
67
23.04
25
inline
using System; using System.Globalization; using Avalonia.Media; using Avalonia.Media.TextFormatting.Unicode; using Avalonia.Platform; using Avalonia.Utilities; using HarfBuzzSharp; using Buffer = HarfBuzzSharp.Buffer; namespace Avalonia.Direct2D1.Media { internal class TextShaperImpl : ITextShaperImpl { public GlyphRun ShapeText(ReadOnlySlice text, Typeface typeface, double fontRenderingEmSize, CultureInfo culture) { using (var buffer = new Buffer()) { FillBuffer(buffer, text); buffer.Language = new Language(culture ?? CultureInfo.CurrentCulture); buffer.GuessSegmentProperties(); var glyphTypeface = typeface.GlyphTypeface; var font = ((GlyphTypefaceImpl)glyphTypeface.PlatformImpl).Font; font.Shape(buffer); font.GetScale(out var scaleX, out _); var textScale = fontRenderingEmSize / scaleX; var bufferLength = buffer.Length; var glyphInfos = buffer.GetGlyphInfoSpan(); var glyphPositions = buffer.GetGlyphPositionSpan(); var glyphIndices = new ushort[bufferLength]; var clusters = new ushort[bufferLength]; double[] glyphAdvances = null; Vector[] glyphOffsets = null; for (var i = 0; i < bufferLength; i++) { glyphIndices[i] = (ushort)glyphInfos[i].Codepoint; clusters[i] = (ushort)glyphInfos[i].Cluster; if (!glyphTypeface.IsFixedPitch) { SetAdvance(glyphPositions, i, textScale, ref glyphAdvances); } SetOffset(glyphPositions, i, textScale, ref glyphOffsets); } return new GlyphRun(glyphTypeface, fontRenderingEmSize, new ReadOnlySlice new ReadOnlySlice new ReadOnlySlice text, new ReadOnlySlice } } private static void FillBuffer(Buffer buffer, ReadOnlySlice text) { buffer.ContentType = ContentType.Unicode; var i = 0; while (i < text.Length) { var codepoint = Codepoint.ReadAt(text, i, out var count); var cluster = (uint)(text.Start + i); if (codepoint.IsBreakChar) { if (i + 1 < text.Length) { var nextCodepoint = Codepoint.ReadAt(text, i + 1, out _); if (nextCodepoint == '\r' && codepoint == '\n' || nextCodepoint == '\n' && codepoint == '\r') { count++; buffer.Add('\u200C', cluster); buffer.Add('\u200D', cluster); } else { buffer.Add('\u200C', cluster); } } else { buffer.Add('\u200C', cluster); } } else { buffer.Add(codepoint, cluster); } i += count; } } private static void SetOffset(ReadOnlySpan glyphPositions, int index, double textScale, ref Vector[] offsetBuffer) { var position = glyphPositions[index]; if (position.XOffset == 0 && position.YOffset == 0) { return; } offsetBuffer ??= new Vector[glyphPositions.Length]; var offsetX = position.XOffset * textScale; var offsetY = position.YOffset * textScale; offsetBuffer[index] = new Vector(offsetX, offsetY); } private static void SetAdvance(ReadOnlySpan glyphPositions, int index, double textScale, ref double[] advanceBuffer) { advanceBuffer ??= new double[glyphPositions.Length]; // Depends on direction of layout // advanceBuffer[index] = buffer.GlyphPositions[index].YAdvance * textScale; advanceBuffer[index] = glyphPositions[index].XAdvance * textScale; } } }
c#
21
0.510061
127
31.335616
146
starcoderdata
// // Created by anghenfil on 23.02.18. // #ifndef SHITHUBDAEMON_LOG_HPP #define SHITHUBDAEMON_LOG_HPP #include #include "Levels.hpp" #include "Handler.hpp" #include namespace Log { class Log { public: static bool print(Levels, std::string&); static bool print(Levels, std::string&, std::exception&); static bool addHandler(Levels, Handler&); private: static std::vector trace; static std::vector debug; static std::vector info; static std::vector warn; static std::vector error; static std::vector critical; }; } #endif //SHITHUBDAEMON_LOG_HPP
c++
12
0.646438
65
21.969697
33
starcoderdata
<?php use App\Events\DragonActivated; use App\Events\WalletCreated; use App\Events\WalletUpdated; use App\Wallet; use Carbon\Carbon; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Hash; class RootUserSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { if (\App\User::find(1)) { return; } DB::beginTransaction(); $user = \App\User::firstOrCreate( [ 'email' => ' ], [ 'name' => 'root', 'password' => 'wallet_password' => 'frozen' => false, ] ); if (!$user->activated) { $dragon = $user->activatedDragon()->create( ['type' => \App\Dragon::TYPE_NORMAL, 'owner_id' => $user->id, 'activated_at' => Carbon::now()] ); event(new DragonActivated($dragon, $user)); } foreach ((new Wallet)->gems() as $gem) { $wallet = $user->wallets()->firstOrCreate( [ 'gem' => $gem, ], [ 'amount' => '0', ] ); event(new WalletCreated($wallet)); } DB::commit(); } }
php
18
0.469044
110
22.967742
62
starcoderdata
// // Translated by CS2J (http://www.cs2j.com): 2019-08-12 9:59:30 PM // package com.bazaarbot.agent; import com.bazaarbot.inventory.InventoryData; /** * The most fundamental agent class, and has as little implementation as possible. * In most cases you should start by extending Agent instead of this. * * @author larsiusprime */ public class AgentData { private String agentClassName; private double money; private InventoryData inventory; private String logicName; private AgentSimulation agentSimulation; private Integer lookBack; public AgentData(String agentClassName, double money, String logicName) { this.agentClassName = agentClassName; this.money = money; this.logicName = logicName; } public String getAgentClassName() { return agentClassName; } public void setAgentClassName(String agentClassName) { this.agentClassName = agentClassName; } public double getMoney() { return money; } public void setMoney(double money) { this.money = money; } public InventoryData getInventory() { return inventory; } public void setInventory(InventoryData inventory) { this.inventory = inventory; } public String getLogicName() { return logicName; } public void setLogicName(String logicName) { this.logicName = logicName; } public AgentSimulation getAgentSimulation() { return agentSimulation; } public void setAgentSimulation(AgentSimulation agentSimulation) { this.agentSimulation = agentSimulation; } public Integer getLookBack() { return lookBack; } public void setLookBack(Integer lookBack) { this.lookBack = lookBack; } }
java
8
0.673163
82
22.025641
78
starcoderdata
package com.strawberry.engine.rendering; import java.util.HashMap; import com.strawberry.engine.core.Vector3f; public class Material { private HashMap<String, Texture> _textureHash; private HashMap<String, Vector3f> _vectorHash; private HashMap<String, Float> _floatHash; public Material() { this._textureHash = new HashMap<String, Texture>(); this._vectorHash = new HashMap<String, Vector3f>(); this._floatHash = new HashMap<String, Float>(); } public void addTexture(String name, Texture texture) { this._textureHash.put(name, texture); } public Texture getTexture(String name) { Texture t = this._textureHash.get(name); if(t != null) return t; return Texture.loadTextureID("java.jpg"); } public void addVector(String name, Vector3f vector) { this._vectorHash.put(name, vector); } public Vector3f getVector(String name) { Vector3f v = this._vectorHash.get(name); if(v != null) return v; return Vector3f.ZERO; } public void addFloat(String name, Float f) { this._floatHash.put(name, f); } public float getFloat(String name) { Float f = this._floatHash.get(name); if(f != null) return f; return 0; } public void cleanUp() { this._floatHash.clear(); this._textureHash.clear(); this._vectorHash.clear(); } }
java
10
0.693138
95
21.362069
58
starcoderdata
require.config({ paths: { lookupTransformCreateView: "../app/lookup_editor/js/views/LookupTransformCreateView" } }); define([ 'lookupTransformCreateView', ], function( LookupTransformCreateView ) { describe('Lookup Transform Create View:', function(){ it('should find the transform for a collection', function(done) { var dom = $(' id="base"> var lookupTransformCreateView = new LookupTransformCreateView({ el: $('#base', dom) }); $.when(lookupTransformCreateView.getTransformForCollection('test_kv_store')).done(function(transform_name){ expect(transform_name).toBe('test_kv_store_lookup'); done(); }); }.bind(this)); it('should return null when attempting to find the transform for a non-existent collection', function(done){ var dom = $(' id="base"> var lookupTransformCreateView = new LookupTransformCreateView({ el: $('#base', dom) }); $.when(lookupTransformCreateView.getTransformForCollection('test_non_existent_kv_store')).done(function(transform_name){ expect(transform_name).toBe(null); done(); }); }.bind(this)); it('should load lookup transforms', function(done) { var dom = $(' id="base"> var lookupTransformCreateView = new LookupTransformCreateView({ el: $('#base', dom) }); $.when(lookupTransformCreateView.getTransforms()).done(function(transforms){ expect(transforms.models.length).toBeGreaterThan(0); done(); }); }.bind(this)); it('should get the fields for a transform', function(done){ var dom = $(' id="base"> var lookupTransformCreateView = new LookupTransformCreateView({ el: $('#base', dom) }); $.when(lookupTransformCreateView.getFieldsForLookup('test_kv_store')).done(function(fields){ expect(fields.length).toBe(3); done(); }); }.bind(this)); it('should return null when attempting to get fields for a non-existent collection', function(done) { var dom = $(' id="base"> var lookupTransformCreateView = new LookupTransformCreateView({ el: $('#base', dom) }); $.when(lookupTransformCreateView.getFieldsForLookup('test_non_existent_kv_store')).done(function(fields){ expect(fields).toBe(null); done(); }); }.bind(this)); }); });
javascript
26
0.555479
132
34.182927
82
starcoderdata
using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace VicoldUtility.ImageClip.Pages { /// /// CanvasPage.xaml 的交互逻辑 /// public partial class CanvasPage : Page { private bool mouseDown; private Point mouseXY; /// /// 坐标点 /// private List points; /// /// 直线 /// private List lines = null; /// /// 定位点 /// //private List anchorPoints = null; /// /// 是否鼠标为按下 /// private bool isMouseDown = false; /// /// 当前选中定位点 /// //private AnchorPoint curAnchorPoint = null; public CanvasPage() { InitializeComponent(); } #region 图片缩放 private void IMG1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { var img = sender as ContentControl; if (img == null) { return; } img.CaptureMouse(); mouseDown = true; mouseXY = e.GetPosition(img); } /// /// 鼠标按下时的事件,启用捕获鼠标位置并把坐标赋值给mouseXY. /// /// <param name="sender"> /// <param name="e"> private void IMG1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { var img = sender as ContentControl; if (img == null) { return; } img.ReleaseMouseCapture(); mouseDown = false; } /// /// 鼠标松开时的事件,停止捕获鼠标位置。 /// /// <param name="sender"> /// <param name="e"> private void IMG1_MouseMove(object sender, MouseEventArgs e) { var img = sender as ContentControl; if (img == null) { return; } if (mouseDown) { Domousemove(img, e); } } /// /// 鼠标移动时的事件,当鼠标按下并移动时发生 /// /// <param name=""> /// <param name=""> private void Domousemove(ContentControl img, MouseEventArgs e) { if (e.LeftButton != MouseButtonState.Pressed) { return; } var group = IMG.FindResource("Imageview") as TransformGroup; var transform = group.Children[1] as TranslateTransform; var position = e.GetPosition(img); transform.X -= mouseXY.X - position.X; transform.Y -= mouseXY.Y - position.Y; mouseXY = position; } /// /// group.Children中的第二个是移动的函数 /// 它根据X.Y的值来移动。并把当前鼠标位置赋值给mouseXY. /// /// <param name="sender"> /// <param name="e"> private void IMG1_MouseWheel(object sender, MouseWheelEventArgs e) { var img = sender as ContentControl; if (img == null) { return; } var point = e.GetPosition(img); var group = IMG.FindResource("Imageview") as TransformGroup; var delta = e.Delta * 0.001; DowheelZoom(group, point, delta); } /// /// 鼠标滑轮事件,得到坐标,放缩函数和滑轮指数,由于滑轮值变化较大所以*0.001. /// /// <param name="group"> /// <param name="point"> /// <param name="delta"> private void DowheelZoom(TransformGroup group, Point point, double delta) { var pointToContent = group.Inverse.Transform(point); var transform = group.Children[0] as ScaleTransform; if ((delta < 0 && transform.ScaleX + delta < 0.1) || (delta > 0 && transform.ScaleX + delta > 20)) { return; } transform.ScaleX += delta * transform.ScaleX; transform.ScaleY += delta * transform.ScaleY; var transform1 = group.Children[1] as TranslateTransform; transform1.X = -1 * ((pointToContent.X * transform.ScaleX) - point.X); transform1.Y = -1 * ((pointToContent.Y * transform.ScaleY) - point.Y); } #endregion //#region canvas //public void Init() //{ // //按x轴分类 // IEnumerable<IGrouping<double, Point>> pointXs = points.GroupBy(o => o.X); // //按y周分类 // IEnumerable<IGrouping<double, Point>> pointYs = points.GroupBy(o => o.Y); // //绘制竖线 // DrawXLine(pointXs); // //绘制横线 // DrawYLine(pointYs); // //设置定位点 // AddAnchorPoints(); // //绘制定位点并且添加事件 // foreach (AnchorPoint anchorPoint in anchorPoints) // { // Rectangle rec = anchorPoint.Draw(); // rec.MouseLeftButtonDown += new MouseButtonEventHandler(rec_MouseLeftButtonDown); // rec.MouseMove += new MouseEventHandler(rec_MouseMove); // canvas.Children.Add(rec); // } // //canvas添加事件 // canvas.MouseLeftButtonUp += new MouseButtonEventHandler(canvas_MouseLeftButtonUp); // canvas.MouseMove += new MouseEventHandler(canvas_MouseMove); // canvas.MouseLeave += new MouseEventHandler(canvas_MouseLeave); //} //public void Move(double x, double y) //{ // double offset = this.Width / 2; // this.retc.Margin = new Thickness(x - offset, y - offset, 0, 0); // this.X = x; // this.Y = y; //} //public Rectangle Draw() //{ // double offset = this.Width / 2; // Rectangle retc = new Rectangle() // { // Margin = new Thickness(this.X - offset, this.Y - offset, 0, 0), // Width = this.Width, // Height = this.Height, // Fill = Brushes.LightGoldenrodYellow, // Stroke = Brushes.Black, // StrokeThickness = 1, // DataContext = this.Key // }; // this.retc = retc; // return retc; //} //private void MoveLines(double x, double y) //{ // List moveLines = new List // moveLines = lines.Where(o => o.Y1 == curAnchorPoint.Y // || o.Y2 == curAnchorPoint.Y // || o.X1 == curAnchorPoint.X // || o.X2 == curAnchorPoint.X).ToList(); // foreach (Line line in moveLines) // { // if (line.Y1 == curAnchorPoint.Y) // { // line.Y1 = y; // } // if (line.Y2 == curAnchorPoint.Y) // { // line.Y2 = y; // } // if (line.X1 == curAnchorPoint.X) // { // line.X1 = x; // } // if (line.X2 == curAnchorPoint.X) // { // line.X2 = x; // } // } //} //private void MoveRefAnchorPoint(double x, double y, AnchorPoint movedAnchorPoint) //{ // foreach (AnchorPoint anchorPoint in anchorPoints) // { // if (anchorPoint.RefPoint.Length == 2) // { // if (anchorPoint.RefPoint[0].X == x && anchorPoint.RefPoint[0].Y == y) // { // anchorPoint.RefPoint[0].X = movedAnchorPoint.X; // anchorPoint.RefPoint[0].Y = movedAnchorPoint.Y; // } // else if (anchorPoint.RefPoint[1].X == x && anchorPoint.RefPoint[1].Y == y) // { // anchorPoint.RefPoint[1].X = movedAnchorPoint.X; // anchorPoint.RefPoint[1].Y = movedAnchorPoint.Y; // } // anchorPoint.X = (anchorPoint.RefPoint[0].X + anchorPoint.RefPoint[1].X) / 2; // anchorPoint.Y = (anchorPoint.RefPoint[0].Y + anchorPoint.RefPoint[1].Y) / 2; // anchorPoint.Move(); // } // } //} //#endregion } public enum AnchorPointType { /// /// 上下 /// NS, /// /// 左右 /// WE, /// /// 右上 /// NE, /// /// 左下 /// SW, /// /// 右下 /// NW, /// /// 左上 /// SE } }
c#
16
0.473869
110
31.064846
293
starcoderdata
 using ElectronicInvoice.Produce.Attributes; namespace ElectronicInvoice.Produce.Infrastructure { public enum InvoiceType { Barcode, QRCode } public enum OnlyWinningInvType { [Content(Name = "Y")] Y, [Content(Name = "N")] N } public enum CardType { [Content(Name = "3J0002")] PhoneBarCode } }
c#
11
0.562802
50
14.37037
27
starcoderdata
namespace Kilosim { /*! * The Viewer is used to display a Kilosim World. It is instantiated with a * pointer to a World, which will be displayed whenever the #draw method is * called. After constructing your Viewer, this is the only method you need to * call to use it. */ class Viewer { /*! @example example_viewer.cpp * Example usage of a Viewer to display a World in a simulation loop. */ private: //! Reference to the World that this Viewer draws World &m_world; //! Width of the display window (in pixels) const int m_window_width; //! Height of the display window (in pixels) int m_window_height; //! SFML window in which the world will be drawn sf::RenderWindow m_window; //! Texture of the World image (will be displayed as background) sf::Texture m_bg_texture; //! The background rectangle shape itself sf::RectangleShape m_background; //! Scaling ratio between world and window coordinates double m_scale; //! Texture used for drawing all the robots sf::RenderTexture m_robot_texture; //! Settings for SFML sf::ContextSettings m_settings; public: /*! * Create a Viewer with the pointer to the given world * * @param world Pointe_r to the World that will be displayed * @param window_width Width (in pixels) to draw the display window. Height * will be automatically determined from the aspect ratio of the World's * dimensions. */ Viewer(World &world, const int window_width = 1080); /*! * Draw everything in the world at the current state * * This will display all robots and the light pattern (if set; otherwise * black). It is frame rate limited to 144 FPS, which limits the overall rate * at which the simulation can run. If the window is closed, the simulation * will continue to run but the window will not reopen. */ void draw(); private: //! Draw a single robot onto the scene void draw_robot(Robot *robot); //! Add the current world time to the display void draw_time(); }; }
c
10
0.704885
79
30.857143
63
inline
import axios from 'axios'; const api= axios.create({ // baseURL:'http://192.168.2.6:3333' baseURL:'http://192.168.1.11:3333' }); export default api;
javascript
4
0.679144
39
19.888889
9
starcoderdata
@Test public void userAgentTest(CapturedOutput output) { new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(AzureAppConfigurationAutoConfiguration.class)) .withPropertyValues( "spring.cloud.azure.profile.tenant-id=sample", "spring.cloud.azure.credential.client-id=sample", "spring.cloud.azure.credential.client-secret=sample", "spring.cloud.azure.appconfiguration.enabled=true", "spring.cloud.azure.appconfiguration.endpoint=https://sample.azconfig.io", "spring.cloud.azure.appconfiguration.client.logging.level=headers", "spring.cloud.azure.appconfiguration.client.logging.allowed-header-names=User-Agent", "spring.cloud.azure.appconfiguration.retry.fixed.delay=1", "spring.cloud.azure.appconfiguration.retry.fixed.max-retries=0", "spring.cloud.azure.appconfiguration.retry.mode=fixed" ) .withBean(AzureGlobalProperties.class, AzureGlobalProperties::new) .run(context -> { assertThat(context).hasSingleBean(AzureAppConfigurationAutoConfiguration.class); assertThat(context).hasSingleBean(AzureAppConfigurationProperties.class); assertThat(context).hasSingleBean(ConfigurationClient.class); assertThat(context).hasSingleBean(ConfigurationAsyncClient.class); assertThat(context).hasSingleBean(ConfigurationClientBuilder.class); assertThat(context).hasSingleBean(ConfigurationClientBuilderFactory.class); ConfigurationClient configurationClient = context.getBean(ConfigurationClient.class); ConfigurationSetting configurationSetting = new ConfigurationSetting(); configurationSetting.setKey("key1"); try { configurationClient.getConfigurationSetting(configurationSetting); } catch (Exception exception) { // Eat it because we just want the log. } assertThat(output).contains(String.format("User-Agent:%s", AzureSpringIdentifier.AZURE_SPRING_APP_CONFIG)); }); }
java
14
0.656415
123
62.25
36
inline
namespace TootingMad.DataSources.LaCrosse { public enum RawDataType { U8, U16, U32, S8, S16, S32, S64, Bit, String, } }
c#
6
0.42439
42
12.666667
15
starcoderdata
package types_test import ( "testing" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" valtypes "github.com/tendermint/spn/pkg/types" "github.com/tendermint/spn/testutil/sample" "github.com/tendermint/spn/x/profile/types" ) const validatorKey = `{ "address": "B4AAC35ED4E14C09E530B10AF4DD604FAAC597C0", "pub_key": { "type": "tendermint/PubKeyEd25519", "value": " }, "priv_key": { "type": "tendermint/PrivKeyEd25519", "value": " } }` func TestMsgSetValidatorConsAddress_ValidateBasic(t *testing.T) { valKey, err := valtypes.LoadValidatorKey([]byte(validatorKey)) require.NoError(t, err) signature, err := valKey.Sign(0, "spn-1") require.NoError(t, err) tests := []struct { name string msg types.MsgSetValidatorConsAddress err error }{ { name: "invalid validator address", msg: types.MsgSetValidatorConsAddress{ ValidatorAddress: "invalid_address", ValidatorConsPubKey: valKey.PubKey.Bytes(), ValidatorKeyType: valKey.PubKey.Type(), Signature: signature, Nonce: 0, ChainID: "spn-1", }, err: sdkerrors.ErrInvalidAddress, }, { name: "invalid validator consensus key", msg: types.MsgSetValidatorConsAddress{ ValidatorAddress: sample.Address(), ValidatorConsPubKey: sample.Bytes(10), ValidatorKeyType: "invalid_key_type", Signature: signature, Nonce: 0, ChainID: "spn-1", }, err: types.ErrInvalidValidatorKey, }, { name: "invalid signature", msg: types.MsgSetValidatorConsAddress{ ValidatorAddress: sample.Address(), ValidatorConsPubKey: valKey.PubKey.Bytes(), ValidatorKeyType: valKey.PubKey.Type(), Signature: signature, Nonce: 99, ChainID: "invalid_chain_id", }, err: types.ErrInvalidValidatorSignature, }, { name: "valid message", msg: types.MsgSetValidatorConsAddress{ ValidatorAddress: sample.Address(), ValidatorConsPubKey: valKey.PubKey.Bytes(), ValidatorKeyType: valKey.PubKey.Type(), Signature: signature, Nonce: 0, ChainID: "spn-1", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := tt.msg.ValidateBasic() if tt.err != nil { require.ErrorIs(t, err, tt.err) return } require.NoError(t, err) }) } }
go
18
0.630732
65
25.446809
94
starcoderdata
package uk.co.jordanrobinson.tracktospeech.handlers; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.speech.tts.TextToSpeech; import android.util.Log; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.Iterator; import java.util.List; import java.util.Set; import uk.co.jordanrobinson.tracktospeech.MainActivity; import uk.co.jordanrobinson.tracktospeech.R; import static uk.co.jordanrobinson.tracktospeech.MainActivity.history; import static uk.co.jordanrobinson.tracktospeech.MainActivity.listView; public abstract class PlayerHandler { public static final String[] IDENTIFIERS = {}; private static final boolean DEBUG = true; public static List History; TextToSpeech tts; int initStatus; boolean playstate; String currentArtist = null; String currentTrack = null; PlayerHandler(TextToSpeech tts, int initStatus, boolean playstate, String currentArtist, String currentTrack) { this.tts = tts; this.initStatus = initStatus; this.playstate = playstate; this.currentArtist = currentArtist; this.currentTrack = currentTrack; } public void handle(Context context, Intent intent) { if (DEBUG) { Bundle bundle = intent.getExtras(); if (bundle != null) { Set keys = bundle.keySet(); Iterator it = keys.iterator(); Log.d("TrTS bundle output", intent.getAction()); Log.d("TrTS bundle output", "Dumping Intent start"); while (it.hasNext()) { String key = it.next(); Log.d("TrTS bundle output", "[" + key + "=" + bundle.get(key)+ "]"); } Log.d("TrTS bundle output", "Dumping Intent end"); } } } void updateHistory(Context context) { if (MainActivity.history.size() > 5) { MainActivity.history.remove(0); } ListView listView = MainActivity.listView; ArrayAdapter arrayAdapter = new ArrayAdapter<>( context, android.R.layout.simple_list_item_1, history); listView.setAdapter(arrayAdapter); listView.invalidate(); } }
java
17
0.60553
88
30.518987
79
starcoderdata
@Override public Flux<FeedResponse<T>> apply(Flux<OrderByRowResult<T>> source) { return source // .windows: creates an observable of observable where inner observable // emits max maxPageSize elements .window(maxPageSize).map(Flux::collectList) // flattens the observable<Observable<List<OrderByRowResult<T>>>> to // Observable<List<OrderByRowResult<T>>> .flatMap(resultListObs -> resultListObs, 1) // translates Observable<List<OrderByRowResult<T>>> to // Observable<FeedResponsePage<OrderByRowResult<T>>>> .map(orderByRowResults -> { // construct a page from result with request charge FeedResponse<OrderByRowResult<T>> feedResponse = BridgeInternal.createFeedResponse( orderByRowResults, headerResponse(tracker.getAndResetCharge())); if (!queryMetricMap.isEmpty()) { for (Map.Entry<String, QueryMetrics> entry : queryMetricMap.entrySet()) { BridgeInternal.putQueryMetricsIntoMap(feedResponse, entry.getKey(), entry.getValue()); } } return feedResponse; }) // Emit an empty page so the downstream observables know when there are no more // results. .concatWith(Flux.defer(() -> { return Flux.just(BridgeInternal.createFeedResponse(Utils.immutableListOf(), null)); })) // CREATE pairs from the stream to allow the observables downstream to "peek" // 1, 2, 3, null -> (null, 1), (1, 2), (2, 3), (3, null) .map(orderByRowResults -> { ImmutablePair<FeedResponse<OrderByRowResult<T>>, FeedResponse<OrderByRowResult<T>>> previousCurrent = new ImmutablePair<FeedResponse<OrderByRowResult<T>>, FeedResponse<OrderByRowResult<T>>>( this.previousPage, orderByRowResults); this.previousPage = orderByRowResults; return previousCurrent; }) // remove the (null, 1) .skip(1) // Add the continuation token based on the current and next page. .map(currentNext -> { FeedResponse<OrderByRowResult<T>> current = currentNext.left; FeedResponse<OrderByRowResult<T>> next = currentNext.right; FeedResponse<OrderByRowResult<T>> page; if (next.getResults().size() == 0) { // No more pages no send current page with null continuation token page = current; page = this.addOrderByContinuationToken(page, null); } else { // Give the first page but use the first value in the next page to generate the // continuation token page = current; List<OrderByRowResult<T>> results = next.getResults(); OrderByRowResult<T> firstElementInNextPage = results.get(0); String orderByContinuationToken = this.orderByContinuationTokenCallback .apply(firstElementInNextPage); page = this.addOrderByContinuationToken(page, orderByContinuationToken); } return page; }).map(feedOfOrderByRowResults -> { // FeedResponse<OrderByRowResult<T>> to FeedResponse<T> List<T> unwrappedResults = new ArrayList<T>(); for (OrderByRowResult<T> orderByRowResult : feedOfOrderByRowResults.getResults()) { unwrappedResults.add(orderByRowResult.getPayload()); } return BridgeInternal.createFeedResponseWithQueryMetrics(unwrappedResults, feedOfOrderByRowResults.getResponseHeaders(), BridgeInternal.queryMetricsFromFeedResponse(feedOfOrderByRowResults), ModelBridgeInternal.getQueryPlanDiagnosticsContext(feedOfOrderByRowResults)); }).switchIfEmpty(Flux.defer(() -> { // create an empty page if there is no result return Flux.just(BridgeInternal.createFeedResponseWithQueryMetrics(Utils.immutableListOf(), headerResponse(tracker.getAndResetCharge()), queryMetricMap, null)); })); }
java
23
0.498574
214
61.619048
84
inline
void XLogFlush(XLogRecPtr record) { XLogRecPtr WriteRqstPtr; XLogwrtRqst WriteRqst; /* * During REDO, we are reading not writing WAL. Therefore, instead of * trying to flush the WAL, we should update minRecoveryPoint instead. We * test XLogInsertAllowed(), not InRecovery, because we need checkpointer * to act this way too, and because when it tries to write the * end-of-recovery checkpoint, it should indeed flush. */ if (!XLogInsertAllowed()) { UpdateMinRecoveryPoint(record, false); return; } /* Quick exit if already known flushed */ if (record <= LogwrtResult.Flush) return; #ifdef WAL_DEBUG if (XLOG_DEBUG) elog(LOG, "xlog flush request %X/%X; write %X/%X; flush %X/%X", (uint32) (record >> 32), (uint32) record, (uint32) (LogwrtResult.Write >> 32), (uint32) LogwrtResult.Write, (uint32) (LogwrtResult.Flush >> 32), (uint32) LogwrtResult.Flush); #endif START_CRIT_SECTION(); /* * Since fsync is usually a horribly expensive operation, we try to * piggyback as much data as we can on each fsync: if we see any more data * entered into the xlog buffer, we'll write and fsync that too, so that * the final value of LogwrtResult.Flush is as large as possible. This * gives us some chance of avoiding another fsync immediately after. */ /* initialize to given target; may increase below */ WriteRqstPtr = record; /* * Now wait until we get the write lock, or someone else does the flush * for us. */ for (;;) { XLogRecPtr insertpos; /* read LogwrtResult and update local state */ SpinLockAcquire(&XLogCtl->info_lck); if (WriteRqstPtr < XLogCtl->LogwrtRqst.Write) WriteRqstPtr = XLogCtl->LogwrtRqst.Write; LogwrtResult = XLogCtl->LogwrtResult; SpinLockRelease(&XLogCtl->info_lck); /* done already? */ if (record <= LogwrtResult.Flush) break; /* * Before actually performing the write, wait for all in-flight * insertions to the pages we're about to write to finish. */ insertpos = WaitXLogInsertionsToFinish(WriteRqstPtr); /* * Try to get the write lock. If we can't get it immediately, wait * until it's released, and recheck if we still need to do the flush * or if the backend that held the lock did it for us already. This * helps to maintain a good rate of group committing when the system * is bottlenecked by the speed of fsyncing. */ if (!LWLockAcquireOrWait(WALWriteLock, LW_EXCLUSIVE)) { /* * The lock is now free, but we didn't acquire it yet. Before we * do, loop back to check if someone else flushed the record for * us already. */ continue; } /* Got the lock; recheck whether request is satisfied */ LogwrtResult = XLogCtl->LogwrtResult; if (record <= LogwrtResult.Flush) { LWLockRelease(WALWriteLock); break; } /* * Sleep before flush! By adding a delay here, we may give further * backends the opportunity to join the backlog of group commit * followers; this can significantly improve transaction throughput, * at the risk of increasing transaction latency. * * We do not sleep if enableFsync is not turned on, nor if there are * fewer than CommitSiblings other backends with active transactions. */ if (CommitDelay > 0 && enableFsync && MinimumActiveBackends(CommitSiblings)) { pg_usleep(CommitDelay); /* * Re-check how far we can now flush the WAL. It's generally not * safe to call WaitXLogInsertionsToFinish while holding * WALWriteLock, because an in-progress insertion might need to * also grab WALWriteLock to make progress. But we know that all * the insertions up to insertpos have already finished, because * that's what the earlier WaitXLogInsertionsToFinish() returned. * We're only calling it again to allow insertpos to be moved * further forward, not to actually wait for anyone. */ insertpos = WaitXLogInsertionsToFinish(insertpos); } /* try to write/flush later additions to XLOG as well */ WriteRqst.Write = insertpos; WriteRqst.Flush = insertpos; XLogWrite(WriteRqst, false); LWLockRelease(WALWriteLock); /* done */ break; } END_CRIT_SECTION(); /* wake up walsenders now that we've released heavily contended locks */ WalSndWakeupProcessRequests(); /* * If we still haven't flushed to the request point then we have a * problem; most likely, the requested flush point is past end of XLOG. * This has been seen to occur when a disk page has a corrupted LSN. * * Formerly we treated this as a PANIC condition, but that hurts the * system's robustness rather than helping it: we do not want to take down * the whole system due to corruption on one data page. In particular, if * the bad page is encountered again during recovery then we would be * unable to restart the database at all! (This scenario actually * happened in the field several times with 7.1 releases.) As of 8.4, bad * LSNs encountered during recovery are UpdateMinRecoveryPoint's problem; * the only time we can reach here during recovery is while flushing the * end-of-recovery checkpoint record, and we don't expect that to have a * bad LSN. * * Note that for calls from xact.c, the ERROR will be promoted to PANIC * since xact.c calls this routine inside a critical section. However, * calls from bufmgr.c are not within critical sections and so we will not * force a restart for a bad LSN on a data page. */ if (LogwrtResult.Flush < record) elog(ERROR, "xlog flush request %X/%X is not satisfied --- flushed only to %X/%X", (uint32) (record >> 32), (uint32) record, (uint32) (LogwrtResult.Flush >> 32), (uint32) LogwrtResult.Flush); }
c++
12
0.709763
75
33.670732
164
inline
package org.jboss.eap.qe.microprofile.jwt.testapp; public class Endpoints { public static final String SECURED_ENDPOINT = "secured-endpoint"; public static final String UNSECURED_ENDPOINT = "unsecured-endpoint"; public static final String RBAC_ENDPOINT = "rbac-endpoint"; public static final String SESSION_SCOPED_ENDPOINT = "session-scoped-endpoint"; }
java
8
0.75969
83
37.7
10
starcoderdata
package tools; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import models.ModelBase; import play.libs.Json; import java.util.List; /** * Created by sissoko on 06/04/2016. */ public class Utils { /** * * @param list * @param * @return */ public static <T extends ModelBase> ArrayNode convert(List list) { ArrayNode node = Json.newArray(); for(T t : list) { node.add(t.toJson()); } return node; } }
java
12
0.604015
73
18.571429
28
starcoderdata
//------------------------------------------------------------------------------ // // Этот код создан программой. // Исполняемая версия:4.0.30319.42000 // // Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае // повторной генерации кода. // //------------------------------------------------------------------------------ namespace NewPlatform.ClickHouseDataService.Tests { using System; using System.Xml; using ICSSoft.STORMNET; // *** Start programmer edit section *** (Using statements) // *** End programmer edit section *** (Using statements) /// /// Cabbage part2. /// // *** Start programmer edit section *** (CabbagePart2 CustomAttributes) // *** End programmer edit section *** (CabbagePart2 CustomAttributes) [AutoAltered()] [Caption("Cabbage part2")] [AccessType(ICSSoft.STORMNET.AccessType.none)] [View("CabbagePart2E", new string[] { "PartName as \'Part name\'"})] public class CabbagePart2 : ICSSoft.STORMNET.DataObject { private string fPartName; private NewPlatform.ClickHouseDataService.Tests.Cabbage2 fCabbage; // *** Start programmer edit section *** (CabbagePart2 CustomMembers) // *** End programmer edit section *** (CabbagePart2 CustomMembers) /// /// PartName. /// // *** Start programmer edit section *** (CabbagePart2.PartName CustomAttributes) // *** End programmer edit section *** (CabbagePart2.PartName CustomAttributes) [StrLen(255)] public virtual string PartName { get { // *** Start programmer edit section *** (CabbagePart2.PartName Get start) // *** End programmer edit section *** (CabbagePart2.PartName Get start) string result = this.fPartName; // *** Start programmer edit section *** (CabbagePart2.PartName Get end) // *** End programmer edit section *** (CabbagePart2.PartName Get end) return result; } set { // *** Start programmer edit section *** (CabbagePart2.PartName Set start) // *** End programmer edit section *** (CabbagePart2.PartName Set start) this.fPartName = value; // *** Start programmer edit section *** (CabbagePart2.PartName Set end) // *** End programmer edit section *** (CabbagePart2.PartName Set end) } } /// /// мастеровая ссылка на шапку NewPlatform.ClickHouseDataService.Tests.Cabbage2. /// // *** Start programmer edit section *** (CabbagePart2.Cabbage CustomAttributes) // *** End programmer edit section *** (CabbagePart2.Cabbage CustomAttributes) [Agregator()] [NotNull()] [PropertyStorage(new string[] { "Cabbage"})] public virtual NewPlatform.ClickHouseDataService.Tests.Cabbage2 Cabbage { get { // *** Start programmer edit section *** (CabbagePart2.Cabbage Get start) // *** End programmer edit section *** (CabbagePart2.Cabbage Get start) NewPlatform.ClickHouseDataService.Tests.Cabbage2 result = this.fCabbage; // *** Start programmer edit section *** (CabbagePart2.Cabbage Get end) // *** End programmer edit section *** (CabbagePart2.Cabbage Get end) return result; } set { // *** Start programmer edit section *** (CabbagePart2.Cabbage Set start) // *** End programmer edit section *** (CabbagePart2.Cabbage Set start) this.fCabbage = value; // *** Start programmer edit section *** (CabbagePart2.Cabbage Set end) // *** End programmer edit section *** (CabbagePart2.Cabbage Set end) } } /// /// Class views container. /// public class Views { /// /// "CabbagePart2E" view. /// public static ICSSoft.STORMNET.View CabbagePart2E { get { return ICSSoft.STORMNET.Information.GetView("CabbagePart2E", typeof(NewPlatform.ClickHouseDataService.Tests.CabbagePart2)); } } } } /// /// Detail array of CabbagePart2. /// // *** Start programmer edit section *** (DetailArrayDetailArrayOfCabbagePart2 CustomAttributes) // *** End programmer edit section *** (DetailArrayDetailArrayOfCabbagePart2 CustomAttributes) public class DetailArrayOfCabbagePart2 : ICSSoft.STORMNET.DetailArray { // *** Start programmer edit section *** (NewPlatform.ClickHouseDataService.Tests.DetailArrayOfCabbagePart2 members) // *** End programmer edit section *** (NewPlatform.ClickHouseDataService.Tests.DetailArrayOfCabbagePart2 members) /// /// Construct detail array. /// /// /// Returns object with type CabbagePart2 by index. /// /// /// Adds object with type CabbagePart2. /// public DetailArrayOfCabbagePart2(NewPlatform.ClickHouseDataService.Tests.Cabbage2 fCabbage2) : base(typeof(CabbagePart2), ((ICSSoft.STORMNET.DataObject)(fCabbage2))) { } public NewPlatform.ClickHouseDataService.Tests.CabbagePart2 this[int index] { get { return ((NewPlatform.ClickHouseDataService.Tests.CabbagePart2)(this.ItemByIndex(index))); } } public virtual void Add(NewPlatform.ClickHouseDataService.Tests.CabbagePart2 dataobject) { this.AddObject(((ICSSoft.STORMNET.DataObject)(dataobject))); } } }
c#
12
0.558688
143
35.281609
174
starcoderdata
// Copyright 2016, // All rights reserved. // // Author: ( // // The Polyline Class Tests using gtest #include "PolylineTest.h" TEST_F(PolylineTest, TestEncodeDecode) { static const int buffer_size = 10; static const int num_coords = 1; static const int precision = 5; char encoded[buffer_size] = {0}; GPSCoordinate gps_coordinates[num_coords]; gps_coordinates[0].set_coordinates(41.75368, -87.97330); Polyline polyline(precision); polyline.encode(gps_coordinates, num_coords, encoded); GPSCoordinate decoded_coordinates[10]; polyline.decode(encoded, decoded_coordinates); EXPECT_FLOAT_EQ(gps_coordinates[0].latitude(), decoded_coordinates[0].latitude()); EXPECT_FLOAT_EQ(gps_coordinates[0].longitude(), decoded_coordinates[0].longitude()); } // Encoded string generated from https://developers.google.com/maps/documentation/utilities/polylineutility TEST_F(PolylineTest, TestDecodeFromGoogleMapAPI) { char *encoded = (char*)"zh_pChhmfE"; GPSCoordinate decoded_coordinates[5]; Polyline polyline; polyline.decode(encoded, decoded_coordinates); EXPECT_FLOAT_EQ(-23.75838, decoded_coordinates[0].latitude()); EXPECT_FLOAT_EQ(-32.67733, decoded_coordinates[0].longitude()); } TEST_F(PolylineTest, TestEncodeDecodeLowPrecision) { static const int buffer_size = 10; static const int num_coords = 1; static const int precision = 3; char encoded[buffer_size] = {0}; GPSCoordinate gps_coordinates[num_coords]; gps_coordinates[0].set_coordinates(41.75368, -87.97330); Polyline polyline(precision); polyline.encode(gps_coordinates, num_coords, encoded); GPSCoordinate decoded_coordinates[5]; polyline.decode(encoded, decoded_coordinates); EXPECT_FLOAT_EQ(41.753, decoded_coordinates[0].latitude()); EXPECT_FLOAT_EQ(-87.973, decoded_coordinates[0].longitude()); } TEST_F(PolylineTest, TestDecode) { static const int buffer_size = 10; static const int num_coords = 1; char encoded[buffer_size] = {0}; GPSCoordinate gps_coordinates[num_coords]; gps_coordinates[0].set_coordinates(64.12345, -12.91827); Polyline polyline; polyline.encode(gps_coordinates, num_coords, encoded); GPSCoordinate decoded_coordinates[5]; polyline.decode(encoded, decoded_coordinates); EXPECT_FLOAT_EQ(64.12345, decoded_coordinates[0].latitude()); EXPECT_FLOAT_EQ(-12.91827, decoded_coordinates[0].longitude()); } // Encoded string generated from https://developers.google.com/maps/documentation/utilities/polylineutility TEST_F(PolylineTest, TripleDecode) { static const int precision = 5; Polyline polyline(precision); int buffer_size = 5; GPSCoordinate decoded_coordinates[buffer_size]; static char* encoded = (char*)"_nq~F|}bvOtnGx{DppBq|H"; int num_decoded_coords = polyline.decode(encoded, decoded_coordinates); EXPECT_TRUE(num_decoded_coords <= buffer_size); EXPECT_FLOAT_EQ(41.87376, decoded_coordinates[0].latitude()); EXPECT_FLOAT_EQ(-87.67471, decoded_coordinates[0].longitude()); EXPECT_FLOAT_EQ(41.83029, decoded_coordinates[1].latitude()); EXPECT_FLOAT_EQ(-87.70492, decoded_coordinates[1].longitude()); EXPECT_FLOAT_EQ(41.81212, decoded_coordinates[2].latitude()); EXPECT_FLOAT_EQ(-87.65411, decoded_coordinates[2].longitude()); } TEST_F(PolylineTest, TripleEncodeDecode) { static const int buffer_size = 32; static const int num_coords = 3; char encoded[buffer_size] = {0}; Polyline polyline; GPSCoordinate gps_coordinates[num_coords]; gps_coordinates[0].set_coordinates(41.87376, -87.67471); gps_coordinates[1].set_coordinates(41.83029, -87.70492); gps_coordinates[2].set_coordinates(41.81212, -87.65411); polyline.encode(gps_coordinates, num_coords, encoded); GPSCoordinate decoded_coordinates[3]; polyline.decode(encoded, decoded_coordinates); EXPECT_FLOAT_EQ(41.87376, decoded_coordinates[0].latitude()); EXPECT_FLOAT_EQ(-87.67471, decoded_coordinates[0].longitude()); EXPECT_FLOAT_EQ(41.83029, decoded_coordinates[1].latitude()); EXPECT_FLOAT_EQ(-87.70492, decoded_coordinates[1].longitude()); EXPECT_FLOAT_EQ(41.81212, decoded_coordinates[2].latitude()); EXPECT_FLOAT_EQ(-87.65411, decoded_coordinates[2].longitude()); }
c++
10
0.737568
107
32.102362
127
starcoderdata
package com.mxn.soul.flowingdrawer.main; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; /** * Created by yc on 2016/5/17. */ public class fileStorage{ //private final static String FROMPATH =""; //private final static String TOPATH = Environment.getExternalStorageDirectory().getPath(); public int copy(String fromFile, String toFile) { //要复制的文件目录 File[] currentFiles; File root = new File(fromFile); //如同判断SD卡是否存在或者文件是否存在 //如果不存在则 return出去 if(!root.exists()) { return -1; } //如果存在则获取当前目录下的全部文件 填充数组 currentFiles = root.listFiles(); //目标目录 File targetDir = new File(toFile); //创建目录 if(!targetDir.exists()) { targetDir.mkdirs(); } //遍历要复制该目录下的全部文件 for(int i= 0;i<currentFiles.length;i++) { if(currentFiles[i].isDirectory())//如果当前项为子目录 进行递归 { copy(currentFiles[i].getPath() + "/", toFile + currentFiles[i].getName() + "/"); }else//如果当前项为文件则进行文件拷贝 { CopySdcardFile(currentFiles[i].getPath(), toFile + currentFiles[i].getName()); } } return 0; } //文件拷贝 //要复制的目录下的所有非子目录(文件夹)文件拷贝 public int CopySdcardFile(String fromFile, String toFile) { try { InputStream fosfrom = new FileInputStream(fromFile); OutputStream fosto = new FileOutputStream(toFile); byte bt[] = new byte[1024]; int c; while ((c = fosfrom.read(bt)) > 0) { fosto.write(bt, 0, c); } fosfrom.close(); fosto.close(); return 0; } catch (Exception ex) { return -1; } } }
java
16
0.53171
100
23.6375
80
starcoderdata
import pytest import pandas as pd from shmapy.input import ( _read_user_input, _read_coordinate_file, _extract_coordinates, state_to_abbreviation, ) @pytest.mark.parametrize( "filename,chart_type", [ ("tests/data/demo_input1.csv", "vbar"), ("tests/data/demo_input2.csv", "vbar"), ("tests/data/demo_input3.csv", "vbar"), ("tests/data/demo_input4.csv", "vbar"), ("tests/data/demo_input5.csv", "categorical"), ], ) def test_read_user_input(filename, chart_type): assert isinstance( _read_user_input(filename, chart_type=chart_type), pd.core.frame.DataFrame )
python
10
0.635821
82
23.814815
27
starcoderdata
<?php include_once('5_11_c.php'); $c_id=$_GET['c_id']; $a=new ada; $b= $a->del('admina')->where('c_id','=',$c_id)->querya(); if($b){ echo "删除成功"; header("refresh:2;url='5_11_d.php'"); } ?>
php
9
0.5
58
19.1
10
starcoderdata
""" Decision-making based on profit/cost setting """ #import numpy as np def bayesian_targeting_policy(tau_pred, contact_cost, offer_accept_prob, offer_cost, value=None): """ Applied the Bayesian optimal decision framework to make a targeting decision. The decision to target is made when the expected profit increase from targeting is strictly larger than the expected cost of targeting. tau_pred : array-like Estimated treatment effect for each observations. Typically the effect on the expected profit. If tau_pred is the treatment effect on conversion, 'value' needs to be specified. contact_cost : float or array-like Static cost that realizes independent of outcome offer_cost : float or array-like Cost that realizes when the offer is accepted value : float or array-like, default: None Value of the observations in cases where tau_pred is the change in acceptance probability (binary outcome ITE) """ if value: tau_pred = tau_pred * value return (tau_pred > (offer_accept_prob * offer_cost - contact_cost)).astype('int')
python
11
0.717972
100
36.466667
30
starcoderdata
// Require Express const express = require("express"); const app = express(); // Use Heroku Port, OR port 5005, cause I'm crazy const PORT = process.env.PORT || 5005 // require the Api and client routes const apiRoutes = require("./routes/apiRoutes"); const clientRoutes = require("./routes/clientRoutes"); // Required to make sure the html can be read app.use(express.urlencoded({ extended: true })); app.use(express.json()); //NEED THIS TO BE ABLE TO USE THE JS AND CSS!!!! app.use(express.static("public")) // Middleware for where the routes go and giving them variables app.use("/api", apiRoutes); app.use("/", clientRoutes); // let the user know that the local host is working and at what port! app.listen(PORT, () => console.log(`listening at http://localhost:${PORT}`));
javascript
9
0.712821
77
36.190476
21
starcoderdata
#include <bits/stdc++.h> using namespace std; //全ての約数リストO(√n) vector<int> allDivisors(int x) { int sx = (int) sqrt(x); vector<int> v; for (int n = 1; n <= sx; n++) { if (x % n == 0) { int m = x / n; v.push_back(n); if (n != m) v.push_back(m); } } sort(v.begin(), v.end()); return v; } //最大公約数 //ベクトルの中で最大の数を取り、その約数を他のベクトルの要素でも割れるかを各自チェック //O(nm+√k) m:約数の数, k:最大数の値 int greatestCommonFactor(vector<int> v) { sort(v.begin(), v.end()); int maxval = v[v.size() - 1]; vector<int> divisors = allDivisors(maxval); int n = divisors.size(); int gcf = 1; for (int i = 0; i < n; i++) { int cf = divisors[n - 1 - i]; int counter = 0; for (int val : v) { if (val % cf != 0) break; counter++; } if (counter == v.size()) { gcf = cf; break; } } return gcf; } int main() { int N, X; cin >> N >> X; vector<int> x; for (int i = 0; i < N; i++) { int z; cin >> z; x.push_back(abs(z - X)); } int gcf = greatestCommonFactor(x); cout << gcf << endl; return 0; }
c++
11
0.539604
44
15.306452
62
codenet
/* * RHQ Management Platform * Copyright (C) 2005-2008 Red Hat, Inc. * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, version 2, as * published by the Free Software Foundation, and/or the GNU Lesser * General Public License, version 2.1, also as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License and the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU General Public License * and the GNU Lesser General Public License along with this program; * if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.rhq.core.domain.resource; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlTransient; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Represents some error that has occurred in or is associated with a {@link Resource}. * * @author * @author */ @Entity @NamedQueries( { @NamedQuery(name = ResourceError.QUERY_DELETE_BY_RESOURCES, query = "DELETE From ResourceError re WHERE re.resource.id IN ( :resourceIds )"), @NamedQuery(name = ResourceError.QUERY_FIND_BY_RESOURCE_ID, query = "SELECT re FROM ResourceError re WHERE re.resource.id = :resourceId"), @NamedQuery(name = ResourceError.QUERY_FIND_BY_RESOURCE_ID_AND_ERROR_TYPE, query = "SELECT re FROM ResourceError re WHERE re.resource.id = :resourceId AND re.errorType = :errorType") }) @SequenceGenerator(allocationSize = org.rhq.core.domain.util.Constants.ALLOCATION_SIZE, name = "RHQ_RESOURCE_ERROR_SEQ", sequenceName = "RHQ_RESOURCE_ERROR_ID_SEQ") @Table(name = "RHQ_RESOURCE_ERROR") @XmlAccessorType(XmlAccessType.PROPERTY) public class ResourceError implements Serializable { private static final long serialVersionUID = 1L; public static final String QUERY_DELETE_BY_RESOURCES = "ResourceError.deleteByResources"; public static final String QUERY_FIND_BY_RESOURCE_ID = "ResourceError.findByResource"; public static final String QUERY_FIND_BY_RESOURCE_ID_AND_ERROR_TYPE = "ResourceError.findByResourceAndErrorType"; private static final int MAX_SUMMARY_LENGTH = 1000; @Column(name = "ID", nullable = false) @GeneratedValue(strategy = GenerationType.AUTO, generator = "RHQ_RESOURCE_ERROR_SEQ") @Id private int id; @Column(name = "TIME_OCCURRED", nullable = false) private long timeOccurred; @JoinColumn(name = "RESOURCE_ID", nullable = false) @ManyToOne @XmlTransient private Resource resource; @Column(name = "ERROR_TYPE", nullable = false) @Enumerated(EnumType.STRING) private ResourceErrorType errorType; @Column(name = "SUMMARY", nullable = false, length = ResourceError.MAX_SUMMARY_LENGTH) private String summary; @Column(name = "DETAIL", nullable = true) private String detail; protected ResourceError() { } /** * Constructor for {@link ResourceError}. * * @param resource the resource that is associated with the error that occurred * @param errorType identifies this kind of error this represents * @param summary a summary of the error * @param detail a detailed description of the error - typically a stack trace; may be null * @param timeOccurred the epoch time when the error occurred */ public ResourceError(@NotNull Resource resource, @NotNull ResourceErrorType errorType, @NotNull String summary, @Nullable String detail, long timeOccurred) { setResource(resource); setErrorType(errorType); setSummary(summary); setDetail(detail); setTimeOccurred(timeOccurred); } public int getId() { return id; } public void setId(int id) { this.id = id; } public Resource getResource() { return resource; } public void setResource(Resource resource) { this.resource = resource; } public ResourceErrorType getErrorType() { return errorType; } public void setErrorType(ResourceErrorType errorType) { this.errorType = errorType; } public String getSummary() { return summary; } public void setSummary(String summary) { if (summary == null) { summary = "An error occurred."; } else if (summary.length() > MAX_SUMMARY_LENGTH) { summary = summary.substring(0, MAX_SUMMARY_LENGTH - 3) + "..."; } this.summary = summary; } @Nullable public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } public long getTimeOccurred() { return timeOccurred; } public void setTimeOccurred(long timeOccurred) { this.timeOccurred = timeOccurred; } @Override public String toString() { StringBuilder str = new StringBuilder("ResourceError: "); str.append("id=[").append(id); str.append("], time-occurred=[").append(new Date(timeOccurred)); str.append("], error-type=[").append(errorType); str.append("], resource=[").append(resource); str.append("], summary=[").append(summary); str.append("], detail=[").append(detail); str.append("]"); return str.toString(); } }
java
14
0.702383
189
34.285714
182
starcoderdata
<?php declare(strict_types=1); namespace Shopware\Core\Framework\Test\App\Manifest; use PHPUnit\Framework\TestCase; use Shopware\Core\Framework\App\Manifest\Manifest; class ManifestTest extends TestCase { public function testCreateFromXml(): void { $manifest = Manifest::createFromXmlFile(__DIR__ . '/_fixtures/test/manifest.xml'); static::assertEquals(__DIR__ . '/_fixtures/test', $manifest->getPath()); } public function testSetPath(): void { $manifest = Manifest::createFromXmlFile(__DIR__ . '/_fixtures/test/manifest.xml'); $manifest->setPath('test'); static::assertEquals('test', $manifest->getPath()); } }
php
12
0.688716
90
29.84
25
starcoderdata
#include #include #include #include "fmt/chrono.h" #include "fmt/color.h" #include "fmt/core.h" #include "fmt/os.h" #include "fmt/ranges.h" using namespace std; int32_t main(int32_t argc, char** argv) { std::string s = fmt::format("The answer is {:d}.\n", 42); printf("%s", s.c_str()); s = fmt::format("I'd rather be {1} than {0}.\n", "right", "happy"); printf("%s", s.c_str()); fmt::print("Default format: {} {}\n", 42s, 100ms); fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s); std::vector v = {1, 2, 3}; fmt::print("{}\n", v); auto out = fmt::output_file("guide.txt"); out.print("Don't {}", "Panic"); fmt::print(fg(fmt::color::crimson) | fmt::emphasis::bold, "Hello, {}!\n", "world"); fmt::print(fg(fmt::color::floral_white) | bg(fmt::color::slate_gray) | fmt::emphasis::underline, "Hello, {}!\n", "world"); fmt::print(fg(fmt::color::steel_blue) | fmt::emphasis::italic, "Hello, {}!\n", "world"); return 0; }
c++
12
0.599613
124
28.542857
35
starcoderdata
def update_mode_drivers(self, state, report=True): # state is 0 (Disabled) if state == "0": self.setDriver("CLIMD", 0, report) self.setDriver("CLIHCS", 0, report) # state is 1 (Enabled) elif state == "1": self.setDriver("CLIMD", 1, report) self.setDriver("CLIHCS", 0, report) # state is 2 (Heating) elif state == "2": self.setDriver("CLIMD", 1, report) self.setDriver("CLIHCS", 1, report)
python
10
0.505703
50
31
16
inline
using System.Collections; using System.Collections.Generic; using System.Linq; namespace Collections.Extensions.ToPyString { class DictionaryEntryPyStringConverter : BasePyStringConverter { internal DictionaryEntryPyStringConverter(DictionaryEntry source, IEnumerable sourceContainers, string prefix) : base(source, sourceContainers, prefix) { } public override string GetConvertedValue() { var newSourceContainers = SourceContainers.Append(Source); var keyConverter = PyStringConverterFactory.Create(Source.Key, newSourceContainers); var valueConverter = PyStringConverterFactory.Create(Source.Value, newSourceContainers); var key = keyConverter.GetConvertedValue(); var value = valueConverter.GetConvertedValue(); return $"{Prefix}{key}: {value}"; } } }
c#
15
0.708669
126
35.740741
27
starcoderdata
import numpy as np from inferelator.utils import Validator as check from inferelator import utils from inferelator.regression import base_regression from inferelator.distributed.inferelator_mp import MPControl from sklearn.base import BaseEstimator from inferelator.regression.base_regression import _MultitaskRegressionWorkflowMixin import copy import inspect def sklearn_gene(x, y, model, min_coef=None, **kwargs): """ Use a scikit-learn model for regression :param x: Feature array :type x: np.ndarray [N x K] :param y: Response array :type y: np.ndarray [N x 1] :param model: Instance of a scikit BaseEstimator-derived model :type model: BaseEstimator :param min_coef: A minimum coefficient value to include in the model. Any values smaller will be set to 0. :type min_coef: numeric :return: A dict of results for this gene :rtype: dict """ assert check.argument_type(x, np.ndarray) assert check.argument_type(y, np.ndarray) assert check.argument_is_subclass(model, BaseEstimator) (N, K) = x.shape # Fit the model model.fit(x, y, **kwargs) # Get all model coefficients [K, ] try: coefs = model.coef_ except AttributeError: coefs = model.estimator_.coef_ # Set coefficients below threshold to 0 if min_coef is not None: coefs[np.abs(coefs) < min_coef] = 0. # Threshold coefficients coef_nonzero = coefs != 0 # Create a boolean array where coefficients are nonzero [K, ] # If there are non-zero coefficients, redo the linear regression with them alone # And calculate beta_resc if coef_nonzero.sum() > 0: x = x[:, coef_nonzero] utils.make_array_2d(y) betas = base_regression.recalculate_betas_from_selected(x, y) betas_resc = base_regression.predict_error_reduction(x, y, betas) return dict(pp=coef_nonzero, betas=betas, betas_resc=betas_resc) else: return dict(pp=np.repeat(True, K).tolist(), betas=np.zeros(K), betas_resc=np.zeros(K)) class SKLearnRegression(base_regression.BaseRegression): def __init__(self, x, y, model, random_state=None, **kwargs): self.params = kwargs if random_state is not None: self.params["random_state"] = random_state self.min_coef = self.params.pop("min_coef", None) self.model = model(**self.params) super(SKLearnRegression, self).__init__(x, y) def regress(self): """ Execute Elastic Net :return: list Returns a list of regression results that base_regression's pileup_data can process """ if MPControl.is_dask(): from inferelator.distributed.dask_functions import sklearn_regress_dask return sklearn_regress_dask(self.X, self.Y, self.model, self.G, self.genes, self.min_coef) def regression_maker(j): level = 0 if j % 100 == 0 else 2 utils.Debug.allprint(base_regression.PROGRESS_STR.format(gn=self.genes[j], i=j, total=self.G), level=level) data = sklearn_gene(self.X.values, utils.scale_vector(self.Y.get_gene_data(j, force_dense=True, flatten=True)), copy.copy(self.model), min_coef=self.min_coef) data['ind'] = j return data return MPControl.map(regression_maker, range(self.G), tell_children=False) class SKLearnWorkflowMixin(base_regression._RegressionWorkflowMixin): """ Use any scikit-learn regression module """ _sklearn_model = None _sklearn_model_params = None _sklearn_add_random_state = False def __init__(self, *args, **kwargs): self._sklearn_model_params = {} super(SKLearnWorkflowMixin, self).__init__(*args, **kwargs) def set_regression_parameters(self, model=None, add_random_state=None, **kwargs): """ Set parameters to use a sklearn model for regression :param model: A scikit-learn model class :type model: BaseEstimator subclass :param add_random_state: Flag to include workflow random seed as "random_state" in the model :type add_random_state: bool :param kwargs: Any arguments which should be passed to the scikit-learn model class instantiation :type kwargs: any """ if model is not None and not inspect.isclass(model): raise ValueError("Pass an uninstantiated scikit-learn model (i.e. LinearRegression, not LinearRegression()") self._set_with_warning("_sklearn_model", model) self._set_without_warning("_sklearn_add_random_state", add_random_state) self._sklearn_model_params.update(kwargs) def run_bootstrap(self, bootstrap): x = self.design.get_bootstrap(bootstrap) y = self.response.get_bootstrap(bootstrap) utils.Debug.vprint('Calculating betas using SKLearn model {m}'.format(m=self._sklearn_model.__name__), level=0) return SKLearnRegression(x, y, self._sklearn_model, random_state=self.random_seed if self._sklearn_add_random_state else None, **self._sklearn_model_params).run() class SKLearnByTaskMixin(_MultitaskRegressionWorkflowMixin, SKLearnWorkflowMixin): """ This runs BBSR regression on tasks defined by the AMUSR regression (MTL) workflow """ def run_bootstrap(self, bootstrap_idx): betas, betas_resc = [], [] # Select the appropriate bootstrap from each task and stash the data into X and Y for k in range(self._n_tasks): x = self._task_design[k].get_bootstrap(self._task_bootstraps[k][bootstrap_idx]) y = self._task_response[k].get_bootstrap(self._task_bootstraps[k][bootstrap_idx]) utils.Debug.vprint('Calculating task {k} using {n}'.format(k=k, n=self._sklearn_model.__name__), level=0) t_beta, t_br = SKLearnRegression(x, y, self._sklearn_model, random_state=self.random_seed if self._sklearn_add_random_state else None, **self._sklearn_model_params).run() betas.append(t_beta) betas_resc.append(t_br) return betas, betas_resc
python
16
0.61671
120
37.810651
169
starcoderdata
mraa_result_t mraa_mock_i2c_write_word_data_replace(mraa_i2c_context dev, const uint16_t data, const uint8_t command) { if (dev->addr == dev->mock_dev_addr) { if ((command + 1) < dev->mock_dev_data_len) { // Let's say the device is big-endian dev->mock_dev_data[command] = (data & 0xFF00) >> 8; dev->mock_dev_data[command + 1] = data & 0x00FF; return MRAA_SUCCESS; } else { syslog(LOG_ERR, "i2c%i: write_word_data: Command/register number is too big, max is 0x%X", dev->busnum, dev->mock_dev_data_len - 2); return MRAA_ERROR_UNSPECIFIED; } } else { // Not our mock device return MRAA_ERROR_UNSPECIFIED; } }
c
13
0.546875
103
37.45
20
inline
<?php namespace App\Controllers; use App\Models\Entry; use Hashids\Hashids; use Illuminate\Http\Request; class Pages extends Controller { public function index() { return view('pages.index'); } public function share($id, Request $request) { $hashids = new Hashids(); $mongoid = $hashids->decodeHex($id); if (count($mongoid) < 1) { abort(404); } $entry = Entry::find($mongoid); if ($entry === null) { abort(404); } $url = $request->root().'/'.$id; $image = $request->root().'/image/meta/'.$id.'.jpg'; $title = str_replace('{{title}}', $entry->title, config('share')['title']); $pinterest_description = str_replace('{{title}}', $entry->title, config('share')['pinterest_description']); $description = str_replace('{{title}}', $entry->title, config('share')['description']); $twitter_description = str_replace('{{title}}', $entry->title, config('share')['twitter_description']); return view('pages.index', [ 'pinterest_description' => $twitter_description, 'twitter_description' => $twitter_description, 'description' => $description, 'title' => $title, 'image' => $image, 'url' => $url, 'share' => config()->get('share'), ]); } public function dl($id) { return view('pages.dl', ['id' => $id]); } public function ig($id) { return view('pages.dl', ['id' => $id, 'ig' => true]); } public function guide() { return view('pages.guide'); } public function tandc() { return view('pages.tandc'); } }
php
15
0.578046
111
21.514286
70
starcoderdata
'use strict'; const config = require('config'); const jwt = require('jsonwebtoken'); module.exports = () => function* validateToken(next) { // set unauthorised by default let isAuthorised = false; // allow token in body, query string, or headers const token = (this.request.body && this.request.body.accessToken) || (this.params && this.params.accessToken) || this.cookies.get('authToken') || this.header['X-Access-Token']; if (token) { try { // decode JWT const secretKey = config.get('jwtSecretKey'); yield jwt.verify(token, secretKey); isAuthorised = true; } catch(err) { // if error in decoding return 400 BAD REQUEST // to tell the client to clear their token this.cookies.set('token', ''); } } this.state.isAuthorised = isAuthorised; yield next; };
javascript
13
0.621421
73
28.46875
32
starcoderdata
/* * This header is generated by classdump-dyld 1.5 * on Wednesday, October 27, 2021 at 3:22:25 PM Mountain Standard Time * Operating System: Version 13.5.1 (Build 17F80) * Image Source: /System/Library/PrivateFrameworks/HealthUI.framework/HealthUI * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Updated by */ @class NSString, UIImage, UIColor, HKFillStyle; @interface HKDisplayCategory : NSObject { /*^block*/id _keyColor; long long _categoryID; NSString* _categoryName; NSString* _displayName; NSString* _largeListIconName; NSString* _listIconName; NSString* _healthDataIconName; NSString* _shareIconName; } @property (nonatomic,readonly) long long categoryID; //@synthesize categoryID=_categoryID - In the implementation block @property (nonatomic,readonly) NSString * categoryName; //@synthesize categoryName=_categoryName - In the implementation block @property (nonatomic,readonly) NSString * displayName; //@synthesize displayName=_displayName - In the implementation block @property (nonatomic,readonly) NSString * largeListIconName; //@synthesize largeListIconName=_largeListIconName - In the implementation block @property (nonatomic,readonly) NSString * listIconName; //@synthesize listIconName=_listIconName - In the implementation block @property (nonatomic,readonly) NSString * healthDataIconName; //@synthesize healthDataIconName=_healthDataIconName - In the implementation block @property (nonatomic,readonly) NSString * shareIconName; //@synthesize shareIconName=_shareIconName - In the implementation block @property (nonatomic,readonly) UIImage * largeListIcon; @property (nonatomic,readonly) UIImage * listIcon; @property (nonatomic,readonly) UIImage * healthDataIcon; @property (nonatomic,readonly) UIImage * shareIcon; @property (nonatomic,readonly) BOOL isMeCategory; @property (nonatomic,readonly) BOOL isTopLevelCategory; @property (nonatomic,readonly) UIColor * color; @property (nonatomic,readonly) HKFillStyle * fillStyle; +(id)topLevelCategoryIdentifiers; -(id)init; -(BOOL)isEqual:(id)arg1 ; -(id)initWithDictionary:(id)arg1 ; -(NSString *)displayName; -(UIColor *)color; -(NSString *)categoryName; -(long long)categoryID; -(HKFillStyle *)fillStyle; -(UIImage *)listIcon; -(UIImage *)largeListIcon; -(BOOL)isTopLevelCategory; -(UIImage *)healthDataIcon; -(UIImage *)shareIcon; -(BOOL)isMeCategory; -(NSString *)largeListIconName; -(NSString *)listIconName; -(NSString *)healthDataIconName; -(NSString *)shareIconName; @end
c
6
0.706306
157
45.25
60
starcoderdata