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
def _set_meta_info(self): """Identify environment in report if non-production.""" self._report_data['environment'] = f'{self._get_environment()}'.lstrip() self._report_data['meta_account_id'] = self._account_id if self._account_name: self._report_data['meta_account_name'] = self._account_name # Get source ??? # Appears in the Description section of the PDF Document Properties as Title. self._report_data['meta_title'] = ReportMeta.reports[self._report_key]['metaTitle'].upper() # Appears in the Description section of the PDF Document Properties as Subject. if self._report_key == ReportTypes.SEARCH_DETAIL_REPORT: search_type: str = self._report_data['searchQuery']['type'] search_desc: str = TO_SEARCH_DESCRIPTION[search_type] criteria: str = '' if search_type == 'OWNER_NAME': criteria = self._report_data['searchQuery']['criteria']['ownerName']['last'] + ', ' criteria += self._report_data['searchQuery']['criteria']['ownerName']['first'] if 'middle' in self._report_data['searchQuery']['criteria']['ownerName']: criteria += ' ' + self._report_data['searchQuery']['criteria']['ownerName']['middle'] else: criteria = self._report_data['searchQuery']['criteria']['value'].upper() self._report_data['meta_subject'] = f'{search_desc} - "{criteria}"' self._report_data['footer_content'] = f'{search_desc} Search - "{criteria}"'
python
17
0.595704
105
62.36
25
inline
import React from 'react'; import PropTypes from 'prop-types'; import Divider from '@material-ui/core/Divider'; import List from '@material-ui/core/List'; import MuiDrawer from '@material-ui/core/Drawer'; import useStyles from './useStyles'; import ListItemLink from '../ListItemLink'; const Drawer = (props) => { const { open, setOpen } = props; const classes = useStyles(); return ( <MuiDrawer className={classes.drawer} open={open} onClick={() => setOpen(false)} classes={{ paper: classes.drawerPaper, }} > <div className={classes.drawerHeader} /> <Divider /> <ListItemLink to={process.env.ROUTE_TODO} primary="Todo" /> ); }; Drawer.defaultProps = { open: false, setOpen: () => {}, }; Drawer.propTypes = { open: PropTypes.bool, setOpen: PropTypes.func, }; export default Drawer;
javascript
9
0.641745
67
22.487805
41
starcoderdata
@Override public void onDisable() { if (discordInstalled) { // Unsubscribe from DiscordSRV messages DiscordSRV.api.unsubscribe(discordsrvListener); } }
java
8
0.603015
59
27.571429
7
inline
import React from 'react' import images from "../constants/images" import { Link } from 'gatsby' export function GetStartedSection() { return ( <div className="bg-red"> <div className="flex container px-10 relative"> <div className="hidden md:block absolute bottom-0"> <p className="font-40 text-red-2 font-second uppercase absolute" style={{ marginLeft: "70%", marginTop: "35%" }}>LOLA <img src={images.IMG_LOLA} className=" object-fill relative bottom-0" style={{ marginTop: -35 }} /> <div className="w-0 md:w-2/5"> <div className="py-10 pl-0 md:pl-16 mx-auto md:mx-0"> <p className="font-64 text-white z-20 leading-none relative">READY FOR RESULTS? <p className="font-80 text-black z-10 leading-none relative mb-4 uppercase font-bold" style={{ marginTop: -28 }}>let’s get started <div className="flex"> <img className="object-none mr-2" src={images.IC_CHECKBOX} /> <span className="text-white font-27 my-auto">Pay Per Results PR <div className="flex"> <img className="object-none mr-2" src={images.IC_CHECKBOX} /> <span className="text-white font-27 my-auto">50+ Pick ‘N’ Mix Marketing Services <div className="flex"> <img className="object-none mr-2" src={images.IC_CHECKBOX} /> <span className="text-white font-27 my-auto">Low Fees <div className="flex mb-4"> <img className="object-none mr-2" src={images.IC_CHECKBOX} /> <span className="text-white font-27 my-auto">No Contracts <button className="button-green px-8">Let&apos;s begin ); } export function DownloadOrderSection() { return ( <div className="bg-red"> <div className="container flex px-12 md:px-24 justify-between"> <img src={images.IMG_NICK} className="hidden md:block object-none relative bottom-0" style={{ marginTop: -100 }} /> <form className="leading-none py-20 px-0 md:px-10 mx-auto md:mx-0 w-full md:w-2/3"> <p className="uppercase font-58 text-white"> SAMPLE ORDERS & PRICE LISTS <p className="font-40 font-second text-black relative mb-6" style={{ marginTop: -12 }}> Download our ordering guide <input className="form-input rounded-none w-full appearance-none px-8 py-4 text-black placeholder-black font-34 mb-4" placeholder="Enter your email address" type="email" required /> <button className="button-yellow px-10 py-5 mx-auto">Download ); } export function GuaranteeSection() { return ( <div className="container px-12 md:px-24 py-10 bg-white flex flex-col md:flex-row"> <div className="w-full md:w-1/2 leading-none mt-10"> <p className="uppercase font-58 text-black z-20 relative">Guarantee <p className="uppercase font-54 text-red z-10 relative font-medium font-second" style={{ marginTop: -16 }}>100% Satisfaction <div className="flex flex-col md:flex-row mt-16 justify-between"> <img src={images.IC_GURANTEE} className="object-none" /> <span className="text-black font-20 mr-10 mt-4 md:mt-0 w-full md:w-1/2 leading-snug"> We want you to feel confident in every purchase you make with us, which is why we are offering a 100% satisfaction guarantee. If for any reason you are not satisfied with our product, contact our support within 30 days of receiving your report and we’ll work with you to make it right! <div className="w-full md:w-1/2 mx-auto"> <img src={images.IMG_TESTIMONIAL_G} className="object-fill mx-auto" /> ); } export function PopularServiceSection() { return ( <div className="container px-12 md:px-24 py-10 bg-white flex flex-col md:flex-row"> <div className="w-full md:w-1/3 leading-none mt-10 mb-8"> <p className="uppercase font-58 text-red z-20 relative">POPULAR SERVICES <p className="uppercase font-40 text-black z-10 relative mb-8 font-medium font-second" style={{ marginTop: -16 }}>how we can help <Link to="/services" className="button-yellow px-12 mx-auto"> BROWSE ALL SERVICES <div className="w-full md:w-2/3 grid grid-cols-1 md:grid-cols-3 col-gap-4 row-gap-6 mb-4"> <div className="bg-white shadow-md py-4 relative"> <div className="absolute bottom-0 flex justify-center w-full" style={{ marginBottom: -20 }}> <button className="bg-red font-22 py-px px-4 text-white">VIEW <img src={images.IMG_PR} className="object-fill mb-1 mx-auto" /> <p className="text-center font-34">Press Releases <div className="bg-white shadow-md py-4 relative"> <div className="absolute bottom-0 flex justify-center w-full" style={{ marginBottom: -20 }}> <button className="bg-red font-22 py-px px-4 text-white">VIEW <img src={images.IMG_PR} className="object-fill mb-1 mx-auto" /> <p className="text-center font-34">Press Releases <div className="bg-white shadow-md py-4 relative"> <div className="absolute bottom-0 flex justify-center w-full" style={{ marginBottom: -20 }}> <button className="bg-red font-22 py-px px-4 text-white">VIEW <img src={images.IMG_PR} className="object-fill mb-1 mx-auto" /> <p className="text-center font-34">Press Releases ); }
javascript
16
0.530464
309
54.459677
124
starcoderdata
<?php /** * Controller para gestionar las licencias */ class LicenciasController extends AppController { public function before_filter() { View::template('admin'); $valido = New Administrador; if(!$valido->logged()){ Redirect::to("administrador/index/entrar"); } else{ $this->admin = Session::get('nombre', 'administrador'); if(!$this->acl->is_allowed($this->userRol, $this->controller_name, $this->action_name)){ //Flash::error("Acceso negado"); //return false; Redirect::to('administrador'); } } } public function index() { //Index de vista de index } public function listar_licencias() { $licencia["data"] = (New Licences)->getLicenciasActivas(); $this->data = $licencia; View::select(NULL, 'json'); } } ?>
php
16
0.630337
94
20.190476
42
starcoderdata
<!DOCTYPE html> <html lang="en"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" id="theme_link" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/4.3.1/materia/bootstrap.min.css"/> <link rel="stylesheet" href="navbar-fixed-right.min.css"> <link rel="stylesheet" href="navbar-fixed-left.min.css"> <link rel="stylesheet" href="docs.css"> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/3.6.0/mdb.min.js" > <!-- Font Awesome --> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" rel="stylesheet" /> <!-- Google Fonts --> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" rel="stylesheet" /> <!-- MDB --> <link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/3.6.0/mdb.min.css" rel="stylesheet" /> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="<?php echo base_url('pelayanan'); ?>">pelayanan <button class="navbar-toggler" type="button" data-mdb-toggle="collapse" data-mdb-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <i class="fas fa-bars"> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav"> <a class="nav-link active" aria-current="page" href="<?php echo base_url('antrian'); ?>">Ambil Antrian <a class="nav-link" href="<?php echo base_url('antrianno'); ?>">Nomor Antrian <a class="nav-link" href="<?php echo base_url('loketpanggil'); ?>">Loket Antrian <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true"></a > <div class="container"> <div class="jumbotron"> <h1 class="display-4"> dengan FrameWork Codeigniter 4 Tugas Ujian Akhir Semester 4 Pemograman Web
php
6
0.503432
108
34.987654
81
starcoderdata
<?php declare(strict_types=1); namespace Ray\Di; use ReflectionClass; use ReflectionMethod; use ReflectionParameter; interface InjectionPointInterface { /** * Return parameter reflection */ public function getParameter(): ReflectionParameter; /** * Return method reflection */ public function getMethod(): ReflectionMethod; /** * Return class reflection * * @psalm-return ReflectionClass * @phpstan-return ReflectionClass */ public function getClass(): ReflectionClass; /** * Return Qualifier annotations * * @return array */ public function getQualifiers(): array; }
php
6
0.655761
56
17.5
38
starcoderdata
from django import template from datetime import datetime from django.utils.timezone import localtime register = template.Library() @register.filter def data_format_y_m_d(value): if not isinstance(value, datetime): return value return localtime(value).strftime("%Y-%m-%d") @register.filter def data_format_y_m_d_h_m_s(value): if not isinstance(value, datetime): return value return localtime(value).strftime("%Y/%m/%d %H:%M:%S")
python
9
0.704741
57
24.833333
18
starcoderdata
using BepuUtilities.Collections; using BepuUtilities.Memory; using BepuPhysics; using BepuPhysics.Constraints; using System.Numerics; using BepuUtilities; namespace DemoRenderer.Constraints { struct CenterDistanceLimitLineExtractor : IConstraintLineExtractor { public int LinesPerConstraint => 5; public unsafe void ExtractLines(ref CenterDistanceLimitPrestepData prestepBundle, int setIndex, int* bodyIndices, Bodies bodies, ref Vector3 tint, ref QuickList lines) { //Could do bundles of constraints at a time, but eh. ref var poseA = ref bodies.Sets[setIndex].SolverStates[bodyIndices[0]].Motion.Pose; ref var poseB = ref bodies.Sets[setIndex].SolverStates[bodyIndices[1]].Motion.Pose; var minimumDistance = GatherScatter.GetFirst(ref prestepBundle.MinimumDistance); var maximumDistance = GatherScatter.GetFirst(ref prestepBundle.MaximumDistance); var color = new Vector3(0.2f, 0.2f, 1f) * tint; var packedColor = Helpers.PackColor(color); var backgroundColor = new Vector3(0f, 0f, 1f) * tint; lines.AllocateUnsafely() = new LineInstance(poseA.Position, poseA.Position, packedColor, 0); lines.AllocateUnsafely() = new LineInstance(poseB.Position, poseB.Position, packedColor, 0); var offset = poseB.Position - poseA.Position; var length = offset.Length(); var direction = length < 1e-9f ? new Vector3(1, 0, 0) : offset / length; var errorColor = new Vector3(1, 0, 0) * tint; var packedErrorColor = Helpers.PackColor(errorColor); var packedFarColor = Helpers.PackColor(color * 0.5f); var packedNearColor = Helpers.PackColor(color * 0.25f); var minimumPoint = poseA.Position + direction * minimumDistance; if (length >= minimumDistance && length <= maximumDistance) { //Create a darker bar to signify the minimum limit. lines.AllocateUnsafely() = new LineInstance(poseA.Position, minimumPoint, packedNearColor, 0); lines.AllocateUnsafely() = new LineInstance(minimumPoint, poseB.Position, packedFarColor, 0); lines.AllocateUnsafely() = new LineInstance(new Vector3(float.MinValue), new Vector3(float.MinValue), 0, 0); } else if (length < minimumDistance) { //Too close; draw an error line extending beyond the connecting line. lines.AllocateUnsafely() = new LineInstance(poseA.Position, poseB.Position, packedNearColor, 0); lines.AllocateUnsafely() = new LineInstance(poseB.Position, poseA.Position + direction * minimumDistance, packedErrorColor, 0); lines.AllocateUnsafely() = new LineInstance(new Vector3(float.MinValue), new Vector3(float.MinValue), 0, 0); } else { //Too far; draw an error line that extends from the desired endpoint to the current endpoint. var targetEnd = poseA.Position + direction * maximumDistance; lines.AllocateUnsafely() = new LineInstance(poseA.Position, minimumPoint, packedNearColor, 0); lines.AllocateUnsafely() = new LineInstance(minimumPoint, targetEnd, packedFarColor, 0); lines.AllocateUnsafely() = new LineInstance(targetEnd, poseB.Position, packedErrorColor, 0); } } } }
c#
21
0.657496
143
56.451613
62
starcoderdata
package com.zzw.coolweather; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.zzw.coolweather.gson.Forecast; import com.zzw.coolweather.gson.Weather; import com.zzw.coolweather.services.AutoUpdateService; import com.zzw.coolweather.util.HttpUtil; import com.zzw.coolweather.util.Utilty; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; /** * Created by dly. */ public class WeatherActivity extends AppCompatActivity { private ScrollView weatherlayout; private TextView titleCityName,titleUpadeTime; private TextView nowdegress,nowWeatherInfo; private LinearLayout forecastLayout; private TextView aqiText,pm25Text; private TextView comfortText,carWashText,sportText; private SharedPreferences preferences; //背景图 private ImageView bingPicImage; //该控件可使ScrollView刷新数据 public SwipeRefreshLayout refreshLayout; private String mWeatherId; // private Button homeButton; public DrawerLayout drawerLayout; @Override public void onCreate(Bundle savedInstanceStatee) { super.onCreate (savedInstanceStatee); setContentView (R.layout.activity_weather); /* if (Build.VERSION.SDK_INT>=21){ View decorView=getWindow ().getDecorView (); decorView.setSystemUiVisibility (View.SYSTEM_UI_FLAG_FULLSCREEN|View.SYSTEM_UI_FLAG_LAYOUT_STABLE); getWindow ().setStatusBarColor (Color.TRANSPARENT); }*/ //控件初始化 weatherlayout=findViewById (R.id.weather_layout); titleCityName=findViewById (R.id.title_city); titleUpadeTime=findViewById (R.id.title_time); nowdegress=findViewById (R.id.degree_text); nowWeatherInfo=findViewById (R.id.weather_info_text); forecastLayout=findViewById (R.id.forecast_layout); aqiText=findViewById (R.id.aqi_text); pm25Text=findViewById (R.id.pm25_text); comfortText=findViewById (R.id.comfort_text); carWashText=findViewById (R.id.car_wash_text); sportText=findViewById (R.id.sport_text); refreshLayout=findViewById (R.id.swipe_refresh); refreshLayout.setColorSchemeResources (R.color.colorPrimary); bingPicImage=findViewById (R.id.bing_pic_image); //初始化home按钮和drawerLayout homeButton=findViewById (R.id.back_button); drawerLayout=findViewById (R.id.drawer_layout); homeButton.setOnClickListener (new View.OnClickListener () { @Override public void onClick(View v) { drawerLayout.openDrawer (GravityCompat.START); } }); preferences= PreferenceManager.getDefaultSharedPreferences (this); //加载背景图片 String bing_pic = preferences.getString ("bing_pic", null); if (bing_pic!=null){ Glide.with (this).load (bing_pic).into (bingPicImage); }else { loadBingPic(); } //加载天气详情 String weatherString = preferences.getString ("weather", null); if (weatherString!=null){ Weather weather = Utilty.handleWeatherResponse (weatherString); mWeatherId=weather.basic.weatherId; showWeatherInfo (weather); }else { //无缓存去服务器查询 String weatherId=getIntent ().getStringExtra ("weatherId"); mWeatherId=weatherId; weatherlayout.setVisibility (View.INVISIBLE); requestWeather(weatherId); } //设置滑动监听 refreshLayout.setOnRefreshListener (new SwipeRefreshLayout.OnRefreshListener () { @Override public void onRefresh() { requestWeather (mWeatherId); } }); } private void loadBingPic() { String requestBingPic="http://guolin.tech/api/bing_pic"; HttpUtil.sendOkHttpRequest (requestBingPic, new Callback () { @Override public void onFailure(Call call, IOException e) { e.printStackTrace (); } @Override public void onResponse(Call call, Response response) throws IOException { final String bingpic=response.body ().string (); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences (WeatherActivity.this); SharedPreferences.Editor editor = preferences.edit (); editor.putString ("bing_pic",bingpic); editor.apply (); runOnUiThread (new Runnable () { @Override public void run() { Glide.with (WeatherActivity.this).load (bingpic).into (bingPicImage); } }); } }); } public void requestWeather(final String weatherId) { String weatherUrl="http://guolin.tech/api/weather?cityid="+weatherId+"&key= HttpUtil.sendOkHttpRequest (weatherUrl, new Callback () { @Override public void onFailure(Call call, IOException e) { runOnUiThread (new Runnable () { @Override public void run() { Toast.makeText (WeatherActivity.this,"网络请求失败",Toast.LENGTH_SHORT).show (); refreshLayout.setRefreshing (false); } }); } @Override public void onResponse(Call call, Response response) throws IOException { final String weatherString=response.body ().string (); final Weather weather = Utilty.handleWeatherResponse (weatherString); runOnUiThread (new Runnable () { @Override public void run() { if (weather!=null&&"ok".equals (weather.status)){ SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences (WeatherActivity.this).edit (); editor.putString ("weather",weatherString); editor.apply (); showWeatherInfo(weather); }else { Toast.makeText (WeatherActivity.this,"获取数据失败",Toast.LENGTH_SHORT).show (); } refreshLayout.setRefreshing (false); } }); } }); loadBingPic (); } private void showWeatherInfo(Weather weather) { String cityName=weather.basic.cityName; String updateTime=weather.basic.update.updateTime.split (" ")[1]; titleCityName.setText (cityName); titleUpadeTime.setText (updateTime); String degress=weather.now.tmperature+"°C"; String weatherInfo=weather.now.more.info; nowWeatherInfo.setText (weatherInfo); nowdegress.setText (degress); forecastLayout.removeAllViews (); for (Forecast forecast:weather.forecastList) { View view = LayoutInflater.from (WeatherActivity.this).inflate (R.layout.forecast_item, forecastLayout, false); TextView dataText = view.findViewById (R.id.date_text); TextView infoText = view.findViewById (R.id.info_text); TextView maxText = view.findViewById (R.id.max_text); TextView minText = view.findViewById (R.id.min_text); dataText.setText (forecast.data); infoText.setText (forecast.more.info); maxText.setText (forecast.temperature.max); minText.setText (forecast.temperature.min); forecastLayout.addView (view); } if (weather.aqi!=null){ String aqi=weather.aqi.city.aqi; String pm25=weather.aqi.city.pm25; aqiText.setText (aqi); pm25Text.setText (pm25); } comfortText.setText ("舒适度:"+weather.suggestion.comFort.info); carWashText.setText ("洗车指数:"+weather.suggestion.carWash.info); sportText.setText ("运动指数:"+weather.suggestion.sport.info); weatherlayout.setVisibility (View.VISIBLE); //启动服务 Intent intent=new Intent (this, AutoUpdateService.class); startService (intent); } }
java
27
0.625
139
39.144796
221
starcoderdata
# noinspection PyPackageRequirements import pytest from euler_python.hardest import * def test_problem_331(answer): output = p331.problem_331() expected_output = answer['Problem 331'] assert output == expected_output
python
7
0.734694
43
19.416667
12
starcoderdata
#!/usr/bin/env python from wand.image import Image from wand.drawing import Drawing from wand.color import Color # http://www.imagemagick.org/Usage/draw/ # original imagemagick command: # Point 'paints' the color pixel # convert -size 10x6 xc:skyblue -fill black \ # -draw 'point 3,2' -scale 100x60 draw_point.gif # # Color Point 'replaces' the color pixel # convert -size 10x6 xc:skyblue -fill black \ # -draw 'color 6,3 point' -scale 100x60 draw_color_point.gif with Image(width=10, height=6, background=Color('skyblue')) as img: with Drawing() as draw: draw.point(3, 2) draw(img) img.resize(100, 60, 'point') img.save(filename='sample01a.png') with Image(width=10, height=6, background=Color('skyblue')) as img: with Drawing() as draw: draw.point(6, 3) draw(img) img.resize(100, 60, 'point') img.save(filename='sample01b.png')
python
11
0.659436
72
30.793103
29
starcoderdata
/* * The MIT License (MIT) * * Copyright (c) 2015 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.erikandcolleen.gacookieparser; import java.util.Collections; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; /** * Traffic Sources (__utmz) * * This cookie stores the type of referral used by the visitor to reach your site, * whether via a direct method, a referring link, a website search, or a campaign * such as an ad or an email link. It is used to calculate search engine traffic, * ad campaigns and page navigation within your own site. The cookie is updated with * each page view to your site. * * @author <a href="https://github.com/ebeeson"> */ public class GATrafficSourcesData extends GADataBase { public static final String COOKIE_NAME = "__utmz"; private final Date currentSessionStart; private final Integer sessionCount; private final Integer campaignNumber; private final CampaignData campaignData; public GATrafficSourcesData(String cookieValue) { super(cookieValue, 5); this.currentSessionStart = getDate(1); this.sessionCount = getInteger(2); this.campaignNumber = getInteger(3); this.campaignData = new CampaignData(getString(4)); } /** * Timestamp for the current session. */ public Date getCurrentSessionStart() { return currentSessionStart; } /** * Number of sessions started. */ public Integer getSessionCount() { return sessionCount; } public Integer getCampaignNumber() { return campaignNumber; } public CampaignData getCampaignData() { return campaignData; } public static class CampaignData { private final String source; private final String name; private final String medium; private final String term; private final String content; private final Map<String, String> additionalData; private CampaignData(String campaignData) { Map<String, String> map = new LinkedHashMap<String, String>(); for(String field : campaignData.split("\\|")) { String[] pair = field.split("=", 2); if(pair.length == 2) { map.put(pair[0], pair[1]); } } this.source = map.remove("utmcsr"); this.name = map.remove("utmccn"); this.medium = map.remove("utmcmd"); this.term = map.remove("utmctr"); this.content = map.remove("utmcct"); this.additionalData = map.isEmpty() ? null : Collections.unmodifiableMap(map); } public String getSource() { return source; } public String getName() { return name; } public String getMedium() { return medium; } public String getTerm() { return term; } public String getContent() { return content; } public Map<String, String> getAdditionalData() { return additionalData; } public String toString() { final StringBuilder sb = new StringBuilder("CampaignData{"); sb.append("source='").append(source).append('\''); sb.append(", name='").append(name).append('\''); sb.append(", medium='").append(medium).append('\''); sb.append(", term='").append(term).append('\''); sb.append(", content='").append(content).append('\''); sb.append(", additionalData=").append(additionalData); sb.append('}'); return sb.toString(); } } public String toString() { final StringBuilder sb = new StringBuilder("GATrafficSourcesData{"); sb.append("domain='").append(getDomain()).append('\''); sb.append(", currentSessionStart=").append(currentSessionStart); sb.append(", sessionCount=").append(sessionCount); sb.append(", campaignNumber=").append(campaignNumber); sb.append(", campaignData=").append(campaignData); sb.append('}'); return sb.toString(); } }
java
15
0.710231
84
29.262821
156
starcoderdata
void initialcall(void){ // tau=0.45; numbhum=4000; ringpar=10; standpar=1; w=10; convar=1; torvar=0, swapmax=500*numbhum; roundrep=10; testmode=0; std::cout << " Welcome to Schelling 1D full-history"<< " version 2.0, a program by Barmpalias, Elwes and Lewis-Pye.\n\n";//Initial Input Calls // std::cout << " Yes/No answers are given by 1/0\n"; std::cout << " Time is measured in seconds (s), milliseconds (ms) or microseconds (mus)\n"; // std::cout << " Default values are: convention on, max swaps n*1000, report every 5*n, and no test mode\n\n"; std::cout << " Graphical output controls:\n\n";//Initial Input Calls std::cout << " - Press q for quitting\n"; std::cout << " - Press f for fullscreen\n\n"; std::cout << " User input:\n\n"; std::cout << " - Give me the number of humans: "; std::cin >> numbhum; std::cout << " - Give me the neighbourhood radius w: "; std::cin >> w; std::cout << " - Give me the tolerance parameter tau: "; std::cin >> tau; std::cout << " - Give me pixel dimension: "; std::cin >> pixdim; // std::cout << " - Display binary?: "; std::cin >> dispz; convar=1; swapmax=100*numbhum; roundrep= 10000; testmode=0; seedvar = (unsigned int)time (NULL); srand (seedvar); std::cout<< "\n\n Random seed is "<< seedvar;}
c++
9
0.599411
129
66.95
20
inline
#include /* Surface to store current scribbles */ static cairo_surface_t *surface = NULL; static void clear_surface (void) { cairo_t *cr; cr = cairo_create (surface); cairo_set_source_rgb (cr, 1, 1, 1); cairo_paint (cr); cairo_destroy (cr); } /* Create a new surface of the appropriate size to store our scribbles */ static void resize_cb (GtkWidget *widget, int width, int height, gpointer data) { if (surface) { cairo_surface_destroy (surface); surface = NULL; } if (gtk_native_get_surface (gtk_widget_get_native (widget))) { surface = gdk_surface_create_similar_surface (gtk_native_get_surface (gtk_widget_get_native (widget)), CAIRO_CONTENT_COLOR, gtk_widget_get_width (widget), gtk_widget_get_height (widget)); /* Initialize the surface to white */ clear_surface (); } } /* Redraw the screen from the surface. Note that the draw * callback receives a ready-to-be-used cairo_t that is already * clipped to only draw the exposed areas of the widget */ static void draw_cb (GtkDrawingArea *drawing_area, cairo_t *cr, int width, int height, gpointer data) { cairo_set_source_surface (cr, surface, 0, 0); cairo_paint (cr); } /* Draw a rectangle on the surface at the given position */ static void draw_brush (GtkWidget *widget, double x, double y) { cairo_t *cr; /* Paint to the surface, where we store our state */ cr = cairo_create (surface); cairo_rectangle (cr, x - 3, y - 3, 6, 6); cairo_fill (cr); cairo_destroy (cr); /* Now invalidate the drawing area. */ gtk_widget_queue_draw (widget); } static double start_x; static double start_y; static void drag_begin (GtkGestureDrag *gesture, double x, double y, GtkWidget *area) { start_x = x; start_y = y; draw_brush (area, x, y); } static void drag_update (GtkGestureDrag *gesture, double x, double y, GtkWidget *area) { draw_brush (area, start_x + x, start_y + y); } static void drag_end (GtkGestureDrag *gesture, double x, double y, GtkWidget *area) { draw_brush (area, start_x + x, start_y + y); } static void pressed (GtkGestureClick *gesture, int n_press, double x, double y, GtkWidget *area) { clear_surface (); gtk_widget_queue_draw (area); } static void close_window (void) { if (surface) cairo_surface_destroy (surface); } static void activate (GtkApplication *app, gpointer user_data) { GtkWidget *window; GtkWidget *drawing_area; GtkGesture *drag; GtkGesture *press; window = gtk_application_window_new (app); gtk_window_set_title (GTK_WINDOW (window), "Drawing Area"); g_signal_connect (window, "destroy", G_CALLBACK (close_window), NULL); drawing_area = gtk_drawing_area_new (); /* set a minimum size */ gtk_widget_set_size_request (drawing_area, 100, 100); gtk_window_set_child (GTK_WINDOW (window), drawing_area); gtk_drawing_area_set_draw_func (GTK_DRAWING_AREA (drawing_area), draw_cb, NULL, NULL); g_signal_connect_after (drawing_area, "resize", G_CALLBACK (resize_cb), NULL); drag = gtk_gesture_drag_new (); gtk_gesture_single_set_button (GTK_GESTURE_SINGLE (drag), GDK_BUTTON_PRIMARY); gtk_widget_add_controller (drawing_area, GTK_EVENT_CONTROLLER (drag)); g_signal_connect (drag, "drag-begin", G_CALLBACK (drag_begin), drawing_area); g_signal_connect (drag, "drag-update", G_CALLBACK (drag_update), drawing_area); g_signal_connect (drag, "drag-end", G_CALLBACK (drag_end), drawing_area); press = gtk_gesture_click_new (); gtk_gesture_single_set_button (GTK_GESTURE_SINGLE (press), GDK_BUTTON_SECONDARY); gtk_widget_add_controller (drawing_area, GTK_EVENT_CONTROLLER (press)); g_signal_connect (press, "pressed", G_CALLBACK (pressed), drawing_area); gtk_widget_show (window); } int main (int argc, char **argv) { GtkApplication *app; int status; app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE); g_signal_connect (app, "activate", G_CALLBACK (activate), NULL); status = g_application_run (G_APPLICATION (app), argc, argv); g_object_unref (app); return status; }
c
13
0.600602
108
24.420765
183
starcoderdata
//*************************************************** //* This file was generated by JSharp //*************************************************** namespace java.lang { public abstract partial class VirtualMachineError : Error { public VirtualMachineError(){} public VirtualMachineError(String prm1){} } }
c#
6
0.51938
61
31.25
12
starcoderdata
const { ipcMain } = require('electron'); const logger = require('../../logger'); const { encryptRC4, decryptRC4, encryptAES256, decryptAES256 } = require('../utils/utils-crypto'); // encryptRC4 ipcMain.on('sync-encryptRC4', (event, key, str) => { logger.debug('encryptRC4 req:', str) event.returnValue = encryptRC4(key, str); }); // decryptRC4 ipcMain.on('sync-decryptRC4', (event, key, cipherStr) => { logger.debug('decryptRC4 req:', cipherStr) event.returnValue = decryptRC4(key, cipherStr) }); // encryptAES256 ipcMain.on('sync-encryptAES256', (event, key, str) => { logger.debug('encryptAES256 req:', key, str) event.returnValue = encryptAES256(skey, strtr) }); // decryptAES256 ipcMain.on('sync-decryptAES256', (event, key, cipherStr) => { logger.debug('decryptAES256 req:', key, cipherStr) event.returnValue = decryptAES256() });
javascript
10
0.688297
98
26.870968
31
starcoderdata
package place import ( "bufio" "encoding/json" "errors" "fmt" "image" "image/color" "io" "net/http" ) const ( infoURL = "https://www.reddit.com/api/place/pixel.json" bmpURL = "https://www.reddit.com/api/place/board-bitmap" ) func GetPixel(x, y int) (*Info, error) { query := fmt.Sprintf("?x=%d&y=%d", x, y) res, err := http.Get(infoURL + query) if err != nil { return nil, err } if res.StatusCode != http.StatusOK { return nil, errors.New(res.Status) } defer res.Body.Close() var inf Info if err := json.NewDecoder(res.Body).Decode(&inf); err != nil { return nil, err } return &inf, nil } type Info struct { Username string `json:"user_name"` Timestamp float64 `json:"timestamp"` Tile } type Tile struct { Y int `json:"y"` X int `json:"x"` Color paletteIndex `json:"color"` } type paletteIndex int func (i paletteIndex) Color() color.Color { return DefaultColorPalette[i] } func GetBitmap() (image.Image, error) { res, err := http.Get(bmpURL) if err != nil { return nil, err } if res.StatusCode != http.StatusOK { return nil, errors.New(res.Status) } defer res.Body.Close() img := image.NewPaletted(image.Rect(0, 0, 1000, 1000), DefaultColorPalette) r := bufio.NewReader(res.Body) var whatIsThis [4]byte r.Read(whatIsThis[:]) for i := 0; i < len(img.Pix); i += 2 { pix, err := r.ReadByte() if err != nil { if err == io.EOF { break } return nil, err } img.Pix[i] = pix >> 4 img.Pix[i+1] = pix & 15 } return img, nil } var DefaultColorPalette = color.Palette{ color.RGBA{0xFF, 0xFF, 0xFF, 0xFF}, color.RGBA{0xE4, 0xE4, 0xE4, 0xFF}, color.RGBA{0x88, 0x88, 0x88, 0xFF}, color.RGBA{0x22, 0x22, 0x22, 0xFF}, color.RGBA{0xFF, 0xA7, 0xD1, 0xFF}, color.RGBA{0xE5, 0x00, 0x00, 0xFF}, color.RGBA{0xE5, 0x95, 0x00, 0xFF}, color.RGBA{0xA0, 0x6A, 0x42, 0xFF}, color.RGBA{0xE5, 0xD9, 0x00, 0xFF}, color.RGBA{0x94, 0xE0, 0x44, 0xFF}, color.RGBA{0x02, 0xBE, 0x01, 0xFF}, color.RGBA{0x00, 0xD3, 0xDD, 0xFF}, color.RGBA{0x00, 0x83, 0xC7, 0xFF}, color.RGBA{0x00, 0x00, 0xEA, 0xFF}, color.RGBA{0xCF, 0x6E, 0xE4, 0xFF}, color.RGBA{0x82, 0x00, 0x80, 0xFF}, }
go
11
0.637939
76
18.40708
113
starcoderdata
public void testWaitForUntilUnlockedReachesTimeout() throws Exception { VirtualMachineDto locked = new VirtualMachineDto(); locked.setState(VirtualMachineState.LOCKED); server.enqueue(new MockResponse().addHeader("Content-type", VirtualMachineDto.SHORT_MEDIA_TYPE_JSON).setBody(json.write(locked))); server.play(); VirtualMachineDto dto = new VirtualMachineDto(); RESTLink link = new RESTLink("edit", "/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1"); link.setType(VirtualMachineDto.SHORT_MEDIA_TYPE_JSON); dto.addLink(link); try { newApiClient().getClient().waitUntilUnlocked(dto, 100, 50, TimeUnit.MILLISECONDS); fail("Test should have failed without having reached the desired status in the given timeout"); } catch (Exception ex) { // Expected exception. Ignore it to verify the recorded requests assertEquals(ex.getMessage(), "Virtual machine did not reach the desired state in the configured timeout"); } // Verify that only one request was made before the method timed out assertEquals(server.getRequestCount(), 1); // Verify the request RecordedRequest request = server.takeRequest(); assertRequest(request, "GET", dto.getEditLink().getHref()); assertAccept(request, VirtualMachineDto.SHORT_MEDIA_TYPE_JSON, SingleResourceTransportDto.API_VERSION); }
java
11
0.652618
107
41.351351
37
inline
<?php /** * 任务树帮助类 * * @author * @copyright ©2003-2103 phpwind.com * @license http://www.windframework.com * @version $Id: PwTaskTreeHelper.php 4670 2012-02-23 01:41:42Z xiaoxia.xuxx $ * @package service.task.srv.helper */ class PwTaskTreeHelper { /** * 获得一颗有序的任务树 * * @param array $tasks * @return array */ public static function getTaskTree($tasks) { foreach ($tasks as $id => &$v) { if ($id === 'root') continue; if ($v['pre_task'] == 0) { $tasks['root']['items'][$id] = &$v; } else { if (!isset($tasks[$v['pre_task']])) continue; $tasks[$v['pre_task']]['items'][$id] = &$v; } } return $tasks; } /** * 根据$id删除所有此id的后置任务 * * @param array $taskTree 此$id的任务树 * @param int $id */ public static function clearAllNextNode($taskTree, &$toClear, $id) { if (isset($taskTree['items']) && !empty($taskTree['items'])) { foreach ($taskTree['items'] as $item) { unset($toClear[$item['id']]); self::clearAllNextNode($item, $toClear, $id); } } } /** * 将树展示出来 * * @param array $tree * @param array $accepts 为空则不做过滤操作,否则要判断节点id是否在accept中 * @param string $split * @return array */ public static function cookTree($tree, $accepts = array(), $split = '|- ') { static $result = array(); foreach ($tree as $k => $v) { if (!empty($accepts) && !in_array($k, $accepts)) continue; $result[$k] = $split . $v['title']; if (isset($v['items'])) { self::cookTree($v['items'], $accepts, '&nbsp;&nbsp;&nbsp;' . $split); } } return $result; } } ?>
php
19
0.574536
78
21.666667
69
starcoderdata
@Test // Tests removing non-existing key public void testRemoveNonExisting() { SkipList sl = new SkipList(2, 2, 5); assertFalse("Remove should return false when Object does not exist", sl.remove(4)); sl.insert(4); assertTrue("Object should be removable", sl.remove(4)); assertFalse("Remove should return false when it has already been removed", sl.remove(4)); }
java
8
0.697436
93
31.583333
12
inline
import os import logging as log import logging.config import yaml import http.client httpclient_logger = log.getLogger('http.client') # Load logging configuration def setup_logging(path='./logging.yaml'): if not os.path.exists('logs'): os.makedirs('logs') try: with open(path, 'r') as stream: config = yaml.safe_load(stream.read()) logging.config.dictConfig(config) log.debug('Completed logging configuration') except Exception as ex: print('Error in loggin configuration, so using default config') print(ex) log.basicConfig(filename='logs/bemo.log',\ format='%(asctime)s - [%(levelname)7s] - %(name)s - %(message)s',\ level=log.DEBUG,\ encoding='utf8') log.debug('[Default] Completed logging configuration') httpclient_logging_patch() # Http client logging def httpclient_logging_patch(level=log.DEBUG): '''Enable HTTPConnection debug logging to the logging framework''' def httpclient_log(*args): httpclient_logger.log(level, ' '.join(args)) # mask the print() built-in in the http.client module to use # logging instead http.client.print = httpclient_log # enable debugging http.client.HTTPConnection.debuglevel = 1
python
13
0.702333
72
27.906977
43
starcoderdata
<?php namespace LazyAnts\Bundle\FrontBundle\Controller; use LazyAnts\Bundle\FrontBundle\Entity\Game; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\DomCrawler\Crawler; use Symfony\Component\HttpFoundation\Request; class MainController extends Controller { public function indexAction() { $teams = $this->getDoctrine()->getRepository('LazyAntsFrontBundle:Team') ->findAll(); return $this->render('LazyAntsFrontBundle:Main:index.html.twig', array('teams' => $teams)); } public function teamAction($name) { $request = Request::createFromGlobals(); $team = $this->getDoctrine()->getRepository('LazyAntsFrontBundle:Team') ->findOneByName($name); $search = $request->query->get('search'); if ($request->isMethod('GET') && !is_null($search)) { $home_games = $this->getDoctrine()->getRepository('LazyAntsFrontBundle:Game')->searchAwayTeamByWord($name, $search); } else { $home_games = $team->getHomeGames(); } return $this->render('LazyAntsFrontBundle:Main:team.html.twig', array('team' => $team,'games' => $home_games)); } }
php
14
0.647764
128
30.3
40
starcoderdata
import React from "react"; import { Link } from "react-router-dom"; function CategoryItem({ img_1, img_2, img_3, title, price, path }) { return ( <div className="card" style={{ width: "19rem" }}> <div className="image__categories"> <img src={img_1} className="card-img-top left__img" alt="..." /> <div className="right__side__img"> <img src={img_2} className="mt-1 right__top__img" alt="..." /> <img src={img_3} className="mt-1 right__bottom__img" alt="..." /> <div className="card-body"> <h5 className="card-title">{title} <p className="card-text text-muted">Starting from ${price} <Link to={path} className="btn btn-default"> VIEW PRODUCTS ); } export default CategoryItem;
javascript
12
0.568985
75
32.730769
26
starcoderdata
Studio 2010/Projects/bjarneStroustrupC++PartI/object_oriented_examples/Chapter10Exercise3.h /* TITLE Read file & calculate statistics Chapter10Exercise3.h Bjarne Stroustrup "Programming: Principles and Practice Using C++" COMMENT Objective: Write a function that reads a file containing data in the format (hour, temp) and calculates mean and median temperatures. Input: - Output: - Author: Date: 08.04.2015 */ bool is_valid_input(int h ,double t); struct Reading { Reading() : hour(0), temperature(0) { } Reading(int h, double t) : hour(h), temperature(t) { if (!is_valid_input(h, t)) { throw std::invalid_argument("Reading::Invalid initialization value!\n"); } } int hour; double temperature; }; //----------------------------------------------------------------------------------------------------------- // Overloaded operators /* operator>> Populates an objec Reading. Input format (hour, temperature), where hour: [0, 23] and temperature: [-273.15, 1.4e32]. */ std::istream& operator >> (std::istream& is, Reading& r) { char par1, comma, par2; int h; double t; // extract data is >> par1 >> h >> comma >> t >> par2; // check stream state if (!is) { return is; } // check input validity if (par1 != '(' || comma != ',' || par2 != ')') { is.clear(std::ios_base::failbit); return is; } r = Reading(h, t); return is; } //----------------------------------------------------------------------------------------------------------- /* operator<< Prints the data mebers of an object Reading. Output format: (hour, date). */ std::ostream& operator<< (std::ostream& os, Reading& r) { return os <<'('<< r.hour <<','<< r.temperature <<')'; } //----------------------------------------------------------------------------------------------------------- // Helper functions /* Function: is_valid_input(h, t); It checks whether the constructor is initialized with valid value. */ bool is_valid_input(int h, double t) { // 24 - hour format const int lower_bound = 0; const int upper_bound = 23; if (h < lower_bound || h > upper_bound) { return false; } // theoretical range in Ceslius const double absolute_zero = -273.15; const double planck_temperature = 1.4e32; if (t < absolute_zero || t > planck_temperature) { return false; } return true; } //----------------------------------------------------------------------------------------------------------- /* Function: void fill_vector(std::istream& is, std::vector v) */ void fill_vector(std::istream& is, std::vector v) { // read line by line std::string input; while (getline(is, input)) { std::stringstream ss(input); Reading r; if (ss >> r) { v.emplace_back(r); } else { std::cerr <<"Wrong input format!\n"; } } } //----------------------------------------------------------------------------------------------------------- /* Function: vector_mean(std::vector r) It returns the mean of the temperatures stored in the vector. */ double vector_mean(std::vector v) { double sum = 0; for (size_t i = 0; i < v.size(); ++i) { sum += v[i].temperature; } return sum / v.size(); } //----------------------------------------------------------------------------------------------------------- /* Function: vector_median(std::vector v) It returns the median of the temperatures stored in the vector. */ double vector_median(std::vector v) { std::vector temperatures; for (size_t i = 0; i < v.size(); ++i) { temperatures.push_back(v[i].temperature); } sort(temperatures.begin(), temperatures.end()); if (temperatures.size() % 2 == 0) { return (temperatures[temperatures.size() / 2 - 1] + temperatures[temperatures.size() / 2]) / 2; } else { return temperatures[temperatures.size() / 2]; } }
c
14
0.530488
109
20.275676
185
starcoderdata
import matplotlib.pyplot as plt import numpy as np import pandas as pd import wbml.metric import wbml.out import wbml.plot from wbml.data.eeg import load from wbml.experiment import WorkingDirectory from gpar import GPARRegressor if __name__ == "__main__": wbml.out.report_time = True wd = WorkingDirectory("_experiments", "eeg") _, train, test = load() x = np.array(train.index) y = np.array(train) # Fit and predict GPAR. model = GPARRegressor( scale=0.02, linear=False, nonlinear=True, nonlinear_scale=1.0, noise=0.01, impute=True, replace=False, normalise_y=True, ) model.fit(x, y) means, lowers, uppers = model.predict( x, num_samples=200, credible_bounds=True, latent=True ) # Report SMSE. pred = pd.DataFrame(means, index=train.index, columns=train.columns) smse = wbml.metric.smse(pred, test) wbml.out.kv("SMSEs", smse.dropna()) wbml.out.kv("Average SMSEs", smse.mean()) # Name of output to plot. name = "F2" # Plot the result. plt.figure(figsize=(12, 1.75)) wbml.plot.tex() p = list(train.columns).index(name) plt.plot(x, means[:, p], style="pred") plt.fill_between(x, lowers[:, p], uppers[:, p], style="pred") plt.scatter(x, y[:, p], style="train") plt.scatter(test[name].index, test[name], style="test") plt.xlabel("Time (second)") plt.xlim(0.4, 1) plt.ylabel(f"{name} (volt)") wbml.plot.tweak(legend=False) plt.tight_layout() plt.savefig(wd.file("eeg.pdf"))
python
10
0.619286
72
24.758065
62
starcoderdata
@Override public void initialize(URL location, ResourceBundle resources) { try { //System.out.println(); // creating connection by creating object DB db = new DB(); // import from txt file importToDB txtImport = new importToDB(); // All Properties displaypropertiesfromDB(); // Filters displayFilters(); // Add New Property } catch (Exception e) { e.printStackTrace(); } }
java
9
0.434439
69
21.642857
28
inline
using FluentAssertions; using NUnit.Framework; namespace NamingAndCommenting { [TestFixture] public class CalculatorTests { private Calculator calculator; [SetUp] public void Setup() { calculator = new Calculator(); } [Test] public void should_return_0_discount_when_no_product_is_bought() { var discount = calculator.Calc(0, 10); discount.Should().Be(0); } [Test] public void should_return_0_discount_when_one_product_with_price_5d_is_bought() { var discount = calculator.Calc(1, 5d); discount.Should().Be(0); } [Test] public void should_return_10d_discount_when_6_products_with_price_5d_are_bought() { var discount = calculator.Calc(6, 5d); discount.Should().Be(10d); } [Test] public void should_return_5d_discount_when_5_products_with_price_5d_are_bought() { var discount = calculator.Calc(5, 5d); discount.Should().Be(5d); } [Test] public void should_return_30d_discount_when_12_products_with_price_5d_are_bought() { var discount = calculator.Calc(12, 5d); discount.Should().Be(30d); } } }
c#
14
0.555715
90
25.245283
53
starcoderdata
/**************************************************************************** * arch/arm/src/lpc43xx/hardware/lpc43_spi.h * * 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. * ****************************************************************************/ #ifndef __ARCH_ARM_SRC_LPC43XX_HARDWARE_LPC43_SPI_H #define __ARCH_ARM_SRC_LPC43XX_HARDWARE_LPC43_SPI_H /**************************************************************************** * Included Files ****************************************************************************/ #include /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /* Register offsets *********************************************************/ #define LPC43_SPI_CR_OFFSET 0x0000 /* Control Register */ #define LPC43_SPI_SR_OFFSET 0x0004 /* SPI Status Register */ #define LPC43_SPI_DR_OFFSET 0x0008 /* SPI Data Register */ #define LPC43_SPI_CCR_OFFSET 0x000c /* SPI Clock Counter Register */ #define LPC43_SPI_TCR_OFFSET 0x0010 /* SPI Test Control Register */ #define LPC43_SPI_TSR_OFFSET 0x0014 /* SPI Test Status Register */ #define LPC43_SPI_INT_OFFSET 0x001c /* SPI Interrupt Register */ /* Register addresses *******************************************************/ #define LPC43_SPI_CR (LPC43_SPI_BASE+LPC43_SPI_CR_OFFSET) #define LPC43_SPI_SR (LPC43_SPI_BASE+LPC43_SPI_SR_OFFSET) #define LPC43_SPI_DR (LPC43_SPI_BASE+LPC43_SPI_DR_OFFSET) #define LPC43_SPI_CCR (LPC43_SPI_BASE+LPC43_SPI_CCR_OFFSET) #define LPC43_TCR_CCR (LPC43_SPI_BASE+LPC43_SPI_TCR_OFFSET) #define LPC43_TSR_CCR (LPC43_SPI_BASE+LPC43_SPI_TSR_OFFSET) #define LPC43_SPI_INT (LPC43_SPI_BASE+LPC43_SPI_INT_OFFSET) /* Register bit definitions *************************************************/ /* Control Register */ /* Bits 0-1: Reserved */ #define SPI_CR_BITENABLE (1 << 2) /* Bit 2: Enable word size selected by BITS */ #define SPI_CR_CPHA (1 << 3) /* Bit 3: Clock phase control */ #define SPI_CR_CPOL (1 << 4) /* Bit 4: Clock polarity control */ #define SPI_CR_MSTR (1 << 5) /* Bit 5: Master mode select */ #define SPI_CR_LSBF (1 << 6) /* Bit 6: SPI data is transferred LSB first */ #define SPI_CR_SPIE (1 << 7) /* Bit 7: Serial peripheral interrupt enable */ #define SPI_CR_BITS_SHIFT (8) /* Bits 8-11: Number of bits per word (BITENABLE==1) */ #define SPI_CR_BITS_MASK (15 << SPI_CR_BITS_SHIFT) # define SPI_CR_BITS_8BITS (8 << SPI_CR_BITS_SHIFT) /* 8 bits per transfer */ # define SPI_CR_BITS_9BITS (9 << SPI_CR_BITS_SHIFT) /* 9 bits per transfer */ # define SPI_CR_BITS_10BITS (10 << SPI_CR_BITS_SHIFT) /* 10 bits per transfer */ # define SPI_CR_BITS_11BITS (11 << SPI_CR_BITS_SHIFT) /* 11 bits per transfer */ # define SPI_CR_BITS_12BITS (12 << SPI_CR_BITS_SHIFT) /* 12 bits per transfer */ # define SPI_CR_BITS_13BITS (13 << SPI_CR_BITS_SHIFT) /* 13 bits per transfer */ # define SPI_CR_BITS_14BITS (14 << SPI_CR_BITS_SHIFT) /* 14 bits per transfer */ # define SPI_CR_BITS_15BITS (15 << SPI_CR_BITS_SHIFT) /* 15 bits per transfer */ # define SPI_CR_BITS_16BITS (0 << SPI_CR_BITS_SHIFT) /* 16 bits per transfer */ /* Bits 12-31: Reserved */ /* SPI Status Register */ /* Bits 0-2: Reserved */ #define SPI_SR_ABRT (1 << 3) /* Bit 3: Slave abort */ #define SPI_SR_MODF (1 << 4) /* Bit 4: Mode fault */ #define SPI_SR_ROVR (1 << 5) /* Bit 5: Read overrun */ #define SPI_SR_WCOL (1 << 6) /* Bit 6: Write collision */ #define SPI_SR_SPIF (1 << 7) /* Bit 7: SPI transfer complete */ /* Bits 8-31: Reserved */ /* SPI Data Register */ #define SPI_DR_MASK (0xff) /* Bits 0-15: SPI Bi-directional data port */ #define SPI_DR_MASKWIDE (0xffff) /* Bits 0-15: If SPI_CR_BITENABLE != 0 */ /* Bits 8-31: Reserved */ /* SPI Clock Counter Register */ #define SPI_CCR_MASK (0xff) /* Bits 0-7: SPI Clock counter setting */ /* Bits 8-31: Reserved */ /* SPI Test Control Register */ /* Bit 0: Reserved */ #define SPI_TCR_TEST_SHIFT (1) /* Bits 1-7: SPI test mode */ #define SPI_TCR_TEST_MASK (0x7f << SPI_TCR_TEST_SHIFT) /* Bits 8-31: Reserved */ /* SPI Test Status Register */ /* Bits 0-2: Reserved */ #define SPI_TSR_ABRT (1 << 3) /* Bit 3: Slave abort */ #define SPI_TSR_MODF (1 << 4) /* Bit 4: Mode fault */ #define SPI_TSR_ROVR (1 << 5) /* Bit 5: Read overrun */ #define SPI_TSR_WCOL (1 << 6) /* Bit 6: Write collision */ #define SPI_TSR_SPIF (1 << 7) /* Bit 7: SPI transfer complete */ /* Bits 8-31: Reserved */ /* SPI Interrupt Register */ #define SPI_INT_SPIF (1 << 0) /* SPI interrupt */ /* Bits 1-31: Reserved */ /**************************************************************************** * Public Types ****************************************************************************/ /**************************************************************************** * Public Data ****************************************************************************/ /**************************************************************************** * Public Functions Prototypes ****************************************************************************/ #endif /* __ARCH_ARM_SRC_LPC43XX_HARDWARE_LPC43_SPI_H */
c
8
0.497243
94
48.711111
135
starcoderdata
def _cache_controller(view_func): @wraps(view_func) def _cache_controlled(request, *args, **kw): response = view_func(request, *args, **kw) if hasattr(response, 'has_header'): # check if response is httpresponse patch_cache_control(response, **kwargs) return response return _cache_controlled
python
12
0.596206
84
45.25
8
inline
package fakeservicebroker import ( "bytes" "encoding/json" "io" "net/http" . "github.com/onsi/gomega" ) func (f *FakeServiceBroker) configure() { req, err := http.NewRequest("POST", f.URL("/config"), f.configJSON()) Expect(err).ToNot(HaveOccurred()) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") resp, err := http.DefaultClient.Do(req) Expect(err).ToNot(HaveOccurred()) Expect(resp.StatusCode).To(Equal(http.StatusOK)) defer resp.Body.Close() } func (f *FakeServiceBroker) configJSON() io.Reader { f.behaviors.Catalog = syncResponse(). withBody(map[string]interface{}{ "services": f.Services, }) config := configuration{Behaviors: f.behaviors} data, err := json.Marshal(config) Expect(err).NotTo(HaveOccurred()) return bytes.NewReader(data) } func asyncResponse() responseMock { return responseMock{ SleepSeconds: 0, Status: http.StatusAccepted, Body: map[string]interface{}{}, } } func syncResponse() responseMock { return responseMock{ SleepSeconds: 0, Status: http.StatusOK, Body: map[string]interface{}{}, } } func (r responseMock) asyncOnly() responseMock { var nillableTrue = new(bool) *nillableTrue = true r.AsyncOnly = nillableTrue return r } func (r responseMock) withBody(body map[string]interface{}) responseMock { r.Body = body return r } func (r responseMock) withStatus(status int) responseMock { r.Status = status return r } type configuration struct { Behaviors behaviors `json:"behaviors"` } type behaviors struct { Catalog responseMock `json:"catalog"` Provision map[string]responseMock `json:"provision"` Bind map[string]responseMock `json:"bind"` Fetch map[string]map[string]responseMock `json:"fetch"` Update map[string]responseMock `json:"update"` Deprovision map[string]responseMock `json:"deprovision"` Unbind map[string]responseMock `json:"unbind"` FetchServiceBinding map[string]responseMock `json:"fetch_service_binding"` } type service struct { Name string `json:"name"` ID string `json:"id"` Description string `json:"description"` Bindable bool `json:"bindable"` InstancesRetrievable bool `json:"instances_retrievable"` BindingsRetrievable bool `json:"bindings_retrievable"` Plans []plan `json:"plans"` Requires []string `json:"requires"` Metadata metadata `json:"metadata"` } func (s service) PlanNames() []string { var planNames []string for _, plan := range s.Plans { planNames = append(planNames, plan.Name) } return planNames } type plan struct { Name string `json:"name"` ID string `json:"id"` Description string `json:"description"` MaintenanceInfo *maintenanceInfo `json:"maintenance_info,omitempty"` } func (p *plan) SetMaintenanceInfoVersion(version string) { p.MaintenanceInfo.Version = version } func (p *plan) RemoveMaintenanceInfo() { p.MaintenanceInfo = nil } type maintenanceInfo struct { Version string `json:"version"` } type responseMock struct { SleepSeconds int `json:"sleep_seconds"` Status int `json:"status"` Body map[string]interface{} `json:"body"` AsyncOnly *bool `json:"async_only,omitempty"` } type metadata struct { Shareable bool `json:"shareable"` DocumentationURL string `json:"documentationUrl"` }
go
12
0.641799
86
26.413534
133
starcoderdata
<?php namespace Goodwong\DatabaseQueryLog; use DB; use Log; use Illuminate\Support\ServiceProvider; class QueryLogServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { // log database query if (config('app.debug', false)) { $this->logDatabaseQuery(); } } /** * log database query sql * * @return void */ private function logDatabaseQuery() { DB::listen(function($query) { $cost = sprintf('%5.2fms', $query->time); Log::info( " -- time {$cost} -- + -- sql {$query->sql} -- + -- bindings", $query->bindings ); }); } /** * Register any application services. * * @return void */ public function register() { // } }
php
18
0.5154
78
18.098039
51
starcoderdata
void CertificateReloader::tryLoad(const Poco::Util::AbstractConfiguration & config) { /// If at least one of the files is modified - recreate std::string new_cert_path = config.getString("openSSL.server.certificateFile", ""); std::string new_key_path = config.getString("openSSL.server.privateKeyFile", ""); /// For empty paths (that means, that user doesn't want to use certificates) /// no processing required if (new_cert_path.empty() || new_key_path.empty()) { LOG_INFO(log, "One of paths is empty. Cannot apply new configuration for certificates. Fill all paths and try again."); } else { bool cert_file_changed = cert_file.changeIfModified(std::move(new_cert_path), log); bool key_file_changed = key_file.changeIfModified(std::move(new_key_path), log); if (cert_file_changed || key_file_changed) { LOG_DEBUG(log, "Reloading certificate ({}) and key ({}).", cert_file.path, key_file.path); data.set(std::make_unique<const Data>(cert_file.path, key_file.path)); LOG_INFO(log, "Reloaded certificate ({}) and key ({}).", cert_file.path, key_file.path); } /// If callback is not set yet try { if (init_was_not_made) init(); } catch (...) { init_was_not_made = true; LOG_ERROR(log, fmt::runtime(getCurrentExceptionMessage(false))); } } }
c++
17
0.598782
127
36.923077
39
inline
package io.onedev.server.web.component.beaneditmodal; import java.io.Serializable; import java.util.Collection; import java.util.HashSet; import javax.annotation.Nullable; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import io.onedev.server.web.component.modal.ModalPanel; @SuppressWarnings("serial") public abstract class BeanEditModalPanel extends ModalPanel { private final Serializable bean; private final Collection propertyNames; private final boolean exclude; private final String title; public BeanEditModalPanel(AjaxRequestTarget target, Serializable bean) { this(target, bean, new HashSet<>(), true, null); } public BeanEditModalPanel(AjaxRequestTarget target, Serializable bean, Collection propertyNames, boolean exclude, @Nullable String title) { super(target); this.bean = bean; this.propertyNames = propertyNames; this.exclude = exclude; this.title = title; } @Override protected Component newContent(String id) { return new BeanEditContentPanel(id) { @Override protected void onSave(AjaxRequestTarget target, Serializable bean) { BeanEditModalPanel.this.onSave(target, bean); } @Override protected void onCancel(AjaxRequestTarget target) { close(); } @Override protected Serializable getBean() { return bean; } @Override protected Collection getPropertyNames() { return propertyNames; } @Override protected boolean isExclude() { return exclude; } @Override protected String getTitle() { return title; } }; } protected abstract void onSave(AjaxRequestTarget target, Serializable bean); }
java
11
0.706718
79
21.487179
78
starcoderdata
# -*- coding: utf-8 -*- from __future__ import print_function, division """ Graph classification """ # Python modules import torch import glob import numpy as np import time import os import argparse # Own modules from options import Options from Logger import LogMetric from utils import load_checkpoint, knn_accuracy, mean_average_precision from models import models, realdistance from data.load_data import load_data import dgl __author__ = " __email__ = " def test(data_loader, gallery_loader, distance, cuda): batch_time = LogMetric.AverageMeter() acc = LogMetric.AverageMeter() meanap = LogMetric.AverageMeter() end = time.time() distance.eval() dist_matrix = [] start = time.time() with torch.no_grad(): g_gallery = [] target_gallery = [] for j, (g, target) in enumerate(gallery_loader): if cuda: g.to(torch.device('cuda')) g.gdata['std'] = g.gdata['std'].cuda() target_gallery.append(target) g_gallery.append(g) target_gallery = np.array(np.concatenate(target_gallery)) gdata = list(map(lambda g: g.gdata['std'], g_gallery)) g_gallery = dgl.batch(g_gallery) g_gallery.gdata = {'std': torch.cat(gdata)} target_query = [] for i, (g, target) in enumerate(data_loader): # Prepare input data if cuda: g.to(torch.device('cuda')) g.gdata['std'] = g.gdata['std'].cuda() # Output d = distance(g, g_gallery, mode='retrieval') dist_matrix.append(d) target_query.append(target) dist_matrix = torch.stack(dist_matrix) target_query = np.array(np.concatenate(target_query)) target_combined_query = np.unique(target_query) combined_dist_matrix = torch.zeros(target_combined_query.shape[0], dist_matrix.shape[1]) for i, kw in enumerate(target_combined_query): ind = kw == target_query combined_dist_matrix[i] = dist_matrix[ind].min(0).values # K-NN classifier acc.update(knn_accuracy(combined_dist_matrix, target_gallery, target_combined_query, k=5, dataset=data_loader.dataset.dataset)) # mAP retrieval meanap.update(mean_average_precision(combined_dist_matrix, target_gallery, target_combined_query)) batch_time.update(time.time()-start) print('* Test Acc {acc.avg:.3f}; mAP {meanap.avg: .3f}; Time x Test {b_time.avg:.3f}' .format(acc=acc, meanap=meanap, b_time=batch_time)) return acc, meanap def main(): print('Prepare data') train_loader, valid_loader, valid_gallery_loader, test_loader, test_gallery_loader, in_size = load_data(args.dataset, args.data_path, batch_size=args.batch_size, prefetch=args.prefetch, set_partition=args.set_partition) distance = realdistance.HausdorffEditDistance(alpha=args.alpha, beta=args.beta, tau_n=args.tau_n, tau_e=args.tau_e) print('Check CUDA') if args.cuda and args.ngpu > 1: distance = torch.nn.DataParallel(distance, device_ids=list(range(args.ngpu))) if args.cuda: distance = distance.cuda() print('***Test***') test(test_loader, test_gallery_loader, distance, args.cuda) if __name__ == '__main__': # Parse options parser = argparse.ArgumentParser(description='Train a Metric Learning Graph Neural Network', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # Positional arguments parser.add_argument('dataset', type=str, choices=['iam', 'histograph-gw', 'histograph-ak'], help='Dataset.') parser.add_argument('data_path', type=str, help='Dataset root path.') # Model parameters parser.add_argument('--set_partition', type=str, help='Dataset set partition (Only histograph-gw otherwise it is ignored).', default='cv1') parser.add_argument('--batch_size', '-bz', type=int, default=64, help='Batch Size.') parser.add_argument('--tau_n', type=float, default=4, help='Batch Size.') parser.add_argument('--tau_e', type=float, default=16, help='Batch Size.') parser.add_argument('--alpha', type=float, default=0.5, help='Batch Size.') parser.add_argument('--beta', type=float, default=0.1, help='Batch Size.') # Optimization options parser.add_argument('--prefetch', type=int, default=4, help='Number of workers to load data.') parser.add_argument('--ngpu', type=int, default=1, help='0 = CPU, 1 = CUDA, 1 < DataParallel') # i/o args = parser.parse_args() # Check cuda & Set random seed args.cuda = args.ngpu > 0 and torch.cuda.is_available() main()
python
15
0.646391
223
35.476563
128
starcoderdata
"use strict"; const inheritFrom = require("../utils").inheritFrom; // https://html.spec.whatwg.org/multipage/webappapis.html#errorevent // Currently installed via level2/events.js; that is not ideal, but necessary for now. const message = Symbol("ErrorEvent message"); const filename = Symbol("ErrorEvent filename"); const lineno = Symbol("ErrorEvent lineno"); const colno = Symbol("ErrorEvent colno"); const error = Symbol("ErrorEvent error"); module.exports = function (core) { core.ErrorEvent = function ErrorEvent(type, eventInitDict) { core.Event.apply(this, arguments); this[message] = eventInitDict && "message" in eventInitDict ? String(eventInitDict.message) : ""; this[filename] = eventInitDict && "filename" in eventInitDict ? String(eventInitDict.filename) : ""; this[lineno] = eventInitDict && "lineno" in eventInitDict ? +eventInitDict.lineno : 0; this[colno] = eventInitDict && "colno" in eventInitDict ? +eventInitDict.colno : 0; this[error] = eventInitDict && "error" in eventInitDict ? eventInitDict.error : null; }; inheritFrom(core.Event, core.ErrorEvent, { get message() { return this[message]; }, get filename() { return this[filename]; }, get lineno() { return this[lineno]; }, get colno() { return this[colno]; }, get error() { return this[error]; } }); }; module.exports.setErrorEventValues = function (e, values) { e[message] = values.message; e[filename] = values.filename; e[lineno] = values.lineno; e[colno] = values.colno; e[error] = values.error; };
javascript
9
0.683028
104
32.156863
51
starcoderdata
@Override @Test public void getEnclosingScope_Standard_ReturnsScopePassedInConstructor() { // different behaviour - returns always null // yet, does not really violate the Liskov Substitution Principle // since it returns the enclosing scope (which is always null for a GlobalNamespaceScope) IScope enclosingScope = mock(IScope.class); AScope scope = createScope(mock(IScopeHelper.class), "foo", enclosingScope); IScope result = scope.getEnclosingScope(); assertNull(result); }
java
10
0.698905
97
38.214286
14
inline
package classes; /** * * - equals() * for defining equivalence relation (reflexive, transitive, symmetric) * must be consistent until object is modified * used when search inside collection (e.g. contains, remove ...) * tells whether you have found exact match * default implementation in Object class use operator '=' * * - hashCode() * must return consistent integer value for object during application execution * used when inserting object into hashtable, hashmap or hashset * tells which bucket to look in * default implementation in Object class provides memory address * * - Note * if override one of them, then necessary to override the other one too * if override, both must be public * same set of fields should be used to compute both * If a.equals(b), then a.hashCode() and b.hashCode() must be same * same hashcode for two objects doesn't guarantee one equals to other */ public class EqualsAndHashCode { String name; int versionId; @Override public boolean equals(Object obj) { if (obj instanceof EqualsAndHashCode) return this.name.equals(((EqualsAndHashCode)obj).name) && this.versionId == ((EqualsAndHashCode)obj).versionId; return false; } @Override public int hashCode() { return name.hashCode() + versionId * 19; } }
java
13
0.735513
79
31.047619
42
starcoderdata
package it.bububear.plutus.themis.service; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.LinkedList; import java.util.List; import org.junit.jupiter.api.Test; import it.bububear.plutus.themis.model.CartProduct; import it.bububear.plutus.themis.test.utils.TestCaseUtils; class CartServiceInMemoryTest { CartServiceInMemory cartServiceInMemory = new CartServiceInMemory(); @Test void test001AddProductToCart() { int id = 1; CartProduct cartProduct = TestCaseUtils.createCartProduct(id); cartServiceInMemory.addProductToCart(cartProduct); CartProduct cartProductFromMap = cartServiceInMemory.cartProductsMap.get(id); assertEquals(cartProduct, cartProductFromMap); } @Test void test002GetProducts() { List listOfCartProducts = new LinkedList<>(); CartProduct cartProduct = TestCaseUtils.createCartProduct(1); listOfCartProducts.add(cartProduct); cartServiceInMemory.addProductToCart(cartProduct); CartProduct cartProductFromList = cartServiceInMemory.getProducts().iterator().next(); assertEquals(cartProduct, cartProductFromList); } }
java
9
0.813644
88
31.486486
37
starcoderdata
# This is a minimalis wrapper around just a few Windows API calls. # It more or less mimics a few of the same functions in pywin32's win32gui, # but does not require anything but the built-in ctypes module. import ctypes from ctypes import wintypes user32 = ctypes.windll.user32 #----------------------------------------------------------------------- _EnumWindows_callback = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM) user32.EnumWindows.argtypes = [_EnumWindows_callback, wintypes.LPARAM] user32.GetWindowTextLengthW.argtypes = [wintypes.HWND] user32.GetWindowTextW.argtypes = [wintypes.HWND, wintypes.LPWSTR, ctypes.c_int] user32.ShowWindow.argtypes = [wintypes.HWND, ctypes.c_int] SW_SHOWMAXIMIZED = 3 SW_SHOWMINIMIZED = 2 SW_SHOWMINNOACTIVE = 7 SW_MAXIMIZE = 3 SW_MINIMIZE = 6 SW_RESTORE = 9 class RECT(ctypes.Structure): _fields_ = [ ('left', wintypes.LONG), ("top", wintypes.LONG), ("right", wintypes.LONG), ("bottom", wintypes.LONG), ] user32.GetWindowRect.argtypes = [wintypes.HWND, wintypes.POINTER(RECT)] user32.SetWindowPos.argtypes = [wintypes.HWND, wintypes.HWND, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_uint] HWND_TOP = 0 class POINT(ctypes.Structure): _fields_ = [ ("x", wintypes.LONG), ("y", wintypes.LONG), ] class WINDOWPLACEMENT(ctypes.Structure): _fields_ = [ ("length", ctypes.c_uint), ("flags", ctypes.c_uint), ("showCmd", ctypes.c_uint), ("ptMinPosition", POINT), ("ptMaxPosition", POINT), ("rcNormalPosition", RECT), ] def __getitem__(self, index): if index == 0: return self.length if index == 1: return self.flags if index == 2: return self.showCmd if index == 3: return self.ptMinPosition if index == 4: return self.ptMaxPosition if index == 5: return self.rcNormalPosition raise IndexError user32.GetWindowPlacement.argtypes = [wintypes.HWND, wintypes.POINTER(WINDOWPLACEMENT)] #----------------------------------------------------------------------- def EnumWindows(callback): if not user32.EnumWindows(_EnumWindows_callback(callback), 42): raise ctypes.WinError() def GetWindowText(hwnd): length = user32.GetWindowTextLengthW(hwnd) + 1 buffer = ctypes.create_unicode_buffer(length) user32.GetWindowTextW(hwnd, buffer, length) title = str(buffer.value) return title def GetWindowRect(hwnd): rect = RECT() user32.GetWindowRect(hwnd, ctypes.byref(rect)) return (rect.left, rect.top, rect.right, rect.bottom) def SetWindowPos(hwnd, after_hwnd, x, y, w, h, flags): user32.SetWindowPos(hwnd, after_hwnd, x, y, w, h, flags) def ShowWindow(hwnd, show_type): user32.ShowWindow(hwnd, show_type) def GetWindowPlacement(hwnd): wp = WINDOWPLACEMENT() wp.length = ctypes.sizeof(wp) user32.GetWindowPlacement(hwnd, ctypes.byref(wp)) return wp
python
9
0.628247
132
31.478261
92
starcoderdata
<?php namespace DataTables\Tests; use DataTables\Request as DataTableRequest; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Request; class RequestTest extends TestCase { public function testPaginationWithoutParams() { $data = []; $request = new DataTableRequest(Request::create('localhost', 'GET', $data)); $this->assertEquals(0, $request->getOffset()); $this->assertEquals(DataTableRequest::DEFAULT_LIMIT, $request->getLimit()); $this->assertEquals(1, $request->getPage()); } public function testPageNumber() { $data = [ 'start' => 40, 'length' => 10 ]; $request = new DataTableRequest(Request::create('localhost', 'GET', $data)); $this->assertEquals(5, $request->getPage()); } public function testSearch() { $data = [ 'search' => [ 'regex' => false, 'value' => 'TEST!' ] ]; $request = new DataTableRequest(Request::create('localhost', 'GET', $data)); $this->assertEquals('TEST!', $request->getParams()->get('search')); } public function testSort() { $data = [ 'columns' => [ [ 'data' => 'id', 'name' => 'The ID', ], ], 'order' => [ [ 'column' => 0, 'dir' => 'natural', ], ], ]; $request = new DataTableRequest(Request::create('localhost', 'GET', $data)); $this->assertEquals('The ID', $request->getSort()->getCol()); $this->assertEquals('asc', $request->getSort()->getDir()); } public function testSortWithFallback() { $data = [ 'columns' => [ [ 'data' => 'id', 'name' => 'The ID', ], [ 'data' => 'name', 'name' => null, ], ], 'order' => [ [ 'column' => 1, 'dir' => 'natural', ], ], ]; $request = new DataTableRequest(Request::create('localhost', 'GET', $data)); $this->assertEquals('name', $request->getSort()->getCol()); $this->assertEquals('asc', $request->getSort()->getDir()); } }
php
14
0.445316
84
25.030612
98
starcoderdata
const fs = require('fs'); const util = require('util'); const spawnPromise = require('./spawnPromise'); const { describeRepositories, createRepository, } = require('./ecr'); const { NGINX_REPOSITORY_NAME, } = require('./constants'); const writeFilePromise = util.promisify(fs.writeFile); const deleteFilePromise = util.promisify(fs.unlink); const buildAndPush = ({ awsAccountID, awsRegion, WONQA_DIR, subDomain, imageRepositoryPath, } = {}) => new Promise((resolve, reject) => { if (imageRepositoryPath) { spawnPromise('bash', [`${WONQA_DIR}/bin/nginx_ssl.sh`], { WONQA_DIR, imageRepositoryPath, subDomain, }) .then(() => resolve()) .catch(err => reject(err)); } else { // ensure default ECR wonqa-nginx ECR repo exists or create it describeRepositories({ awsRegion }) .then((repositories = []) => { const wonqaNginxExists = repositories .some(({ repositoryArn }) => repositoryArn.includes(NGINX_REPOSITORY_NAME)); return !wonqaNginxExists ? createRepository({ awsRegion, repositoryName: NGINX_REPOSITORY_NAME }) : Promise.resolve(); }) .then(() => { const imageRepository = `${awsAccountID}.dkr.ecr.${awsRegion}.amazonaws.com/${NGINX_REPOSITORY_NAME}`; return spawnPromise('bash', [`${WONQA_DIR}/bin/nginx_ssl.sh`], { WONQA_DIR, imageRepositoryPath: imageRepository, subDomain, }); }) .then(() => resolve()) .catch(err => reject(err)); } }); const writeConfFile = ({ WONQA_DIR, servers, configurationPath, }) => new Promise((resolve, reject) => { let config; if (configurationPath) { config = fs.readFileSync(configurationPath); } else { const serverConfig = (port, serverName) => ` server { ${serverName ? (`listen 443 ssl; \n server_name ${serverName}.*;`) : 'listen 443 ssl default_server;'} location / { proxy_pass http://localhost:${port}/; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $http_host; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } }`; const s = servers.map(({ port, serverName }) => serverConfig(port, serverName)); config = ` http { ssl_certificate /etc/ssl/fullchain1.pem; ssl_certificate_key /etc/ssl/privkey1.pem; map $http_upgrade $connection_upgrade { default upgrade; '' close; } ${s.toString().replace(new RegExp('},', 'g'), '}\n')} } events { accept_mutex on; worker_connections 1024; } `; } writeFilePromise(`${WONQA_DIR}/nginx/ecs-nginx.conf`, config) .then((buf = '') => resolve(buf.toString())) .catch(err => reject(err)); }); const deleteConfFile = ({ WONQA_DIR }) => new Promise((resolve, reject) => { deleteFilePromise(`${WONQA_DIR}/nginx/ecs-nginx.conf`) .then(() => resolve()) .catch(err => reject(err)); }); module.exports = { buildAndPush, writeConfFile, deleteConfFile, };
javascript
20
0.617408
110
26.773913
115
starcoderdata
package br.com.technologies.venom.medalertapp.models; import android.os.Parcel; import android.os.Parcelable; public class MedicamentoDetalhe implements Parcelable { private String gtin; private String nome; private String laboratorio; private String imagemCaixa; private String imagemCodigoBarras; private Double precoMin; private Double precoMed; private Double precoMax; private Integer idProduto; private String registro; private String bula; private String criacao; private String modificacao; private String status; public String getGtin() { return gtin; } public void setGtin(String gtin) { this.gtin = gtin; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getLaboratorio() { return laboratorio; } public void setLaboratorio(String laboratorio) { this.laboratorio = laboratorio; } public String getImagemCaixa() { return imagemCaixa; } public void setImagemCaixa(String imagemCaixa) { this.imagemCaixa = imagemCaixa; } public String getImagemCodigoBarras() { return imagemCodigoBarras; } public void setImagemCodigoBarras(String imagemCodigoBarras) { this.imagemCodigoBarras = imagemCodigoBarras; } public Double getPrecoMin() { return precoMin; } public void setPrecoMin(Double precoMin) { this.precoMin = precoMin; } public Double getPrecoMed() { return precoMed; } public void setPrecoMed(Double precoMed) { this.precoMed = precoMed; } public Double getPrecoMax() { return precoMax; } public void setPrecoMax(Double precoMax) { this.precoMax = precoMax; } public Integer getIdProduto() { return idProduto; } public void setIdProduto(Integer idProduto) { this.idProduto = idProduto; } public String getRegistro() { return registro; } public void setRegistro(String registro) { this.registro = registro; } public String getBula() { return bula; } public void setBula(String bula) { this.bula = bula; } public String getCriacao() { return criacao; } public void setCriacao(String criacao) { this.criacao = criacao; } public String getModificacao() { return modificacao; } public void setModificacao(String modificacao) { this.modificacao = modificacao; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public MedicamentoDetalhe() { } public MedicamentoDetalhe(String gtin, String nome, String laboratorio, String imagemCaixa, String imagemCodigoBarras, Double precoMin, Double precoMed, Double precoMax, Integer idProduto, String registro, String bula, String criacao, String modificacao, String status) { this.gtin = gtin; this.nome = nome; this.laboratorio = laboratorio; this.imagemCaixa = imagemCaixa; this.imagemCodigoBarras = imagemCodigoBarras; this.precoMin = precoMin; this.precoMed = precoMed; this.precoMax = precoMax; this.idProduto = idProduto; this.registro = registro; this.bula = bula; this.criacao = criacao; this.modificacao = modificacao; this.status = status; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.gtin); dest.writeString(this.nome); dest.writeString(this.laboratorio); dest.writeString(this.imagemCaixa); dest.writeString(this.imagemCodigoBarras); dest.writeValue(this.precoMin); dest.writeValue(this.precoMed); dest.writeValue(this.precoMax); dest.writeValue(this.idProduto); dest.writeString(this.registro); dest.writeString(this.bula); dest.writeString(this.criacao); dest.writeString(this.modificacao); dest.writeString(this.status); } protected MedicamentoDetalhe(Parcel in) { this.gtin = in.readString(); this.nome = in.readString(); this.laboratorio = in.readString(); this.imagemCaixa = in.readString(); this.imagemCodigoBarras = in.readString(); this.precoMin = (Double) in.readValue(Double.class.getClassLoader()); this.precoMed = (Double) in.readValue(Double.class.getClassLoader()); this.precoMax = (Double) in.readValue(Double.class.getClassLoader()); this.idProduto = (Integer) in.readValue(Integer.class.getClassLoader()); this.registro = in.readString(); this.bula = in.readString(); this.criacao = in.readString(); this.modificacao = in.readString(); this.status = in.readString(); } public static final Parcelable.Creator CREATOR = new Parcelable.Creator { @Override public MedicamentoDetalhe createFromParcel(Parcel source) { return new MedicamentoDetalhe(source); } @Override public MedicamentoDetalhe[] newArray(int size) { return new MedicamentoDetalhe[size]; } }; }
java
12
0.632379
119
25.746411
209
starcoderdata
#include <bits/stdc++.h> #define mod 1000000007 using namespace std; int exp_log(int b, int exp) { int prod = 1; while (exp) { if (exp % 2) prod = (1LL * prod * b) % mod; exp /= 2; b = (1LL * b * b) % mod; } return prod; } int combinari(int n, int k) { int p1 = 1, p2 = 1, p3 = 1; for (int i = 1; i <= n; ++i) p1 = (1LL * p1 * i) % mod; for (int i = 1; i <= n - k; ++i) p2 = (1LL * p2 * i) % mod; for (int i = 1; i <= k; ++i) p3 = (1LL * p3 * i) % mod; p2 = exp_log(p2, mod - 2); p3 = exp_log(p3, mod - 2); return ((1LL * p1 * p2) % mod * 1LL * p3) % mod; } int main() { int x, y, nr1 = 0, s_inversa = 0, rez = 0; cin >> x >> y; nr1 = x; int nr_termeni = nr1; s_inversa = 2 * nr1; while (nr1 >= 0) { if (s_inversa == y) { rez = 1LL * (1LL * rez + 1LL * combinari(nr_termeni, nr1)) % mod; } nr1 -= 2; nr_termeni--; s_inversa -= 3; } cout << rez; return 0; }
c++
16
0.432909
77
21.195652
46
codenet
process.env.NODE_ENV = process.env.NODE_ENV || 'development' process.env.PORT = process.env.PORT || 3000 process.env.DATABASE_URL = process.env.NODE_ENV === 'production' ? 'mongodb+srv://heroku_w0tg51xf:[email protected]/heroku_w0tg51xf?retryWrites=true&w=majority' : 'mongodb://127.0.0.1:27017/givhub'
javascript
7
0.738506
133
48.714286
7
starcoderdata
package com.google.android.gms.internal.firebase_remote_config; import java.io.IOException; public interface zzs extends zzcm { long getLength() throws IOException; String getType(); boolean zzn(); }
java
11
0.76087
140
28.75
12
starcoderdata
import React from "react" import * as Yup from "yup" import { Formik } from "formik" import signupStyles from "../styles/Signup.module.css" import styles from "../styles/Hero.module.css" const signInValidationSchema = Yup.object().shape({ betaEmail: Yup.string() .label("Email") .email("Please enter a valid email") .required("Please enter an email") }); const IOSSignup = () => { return ( <div className={signupStyles.container}> <div className={signupStyles.formContainer}> <div className={signupStyles.title}>Get the app early! <Formik initialValues={{ betaEmail: '' }} validationSchema={signInValidationSchema} > {({ values, errors, touched, handleChange, handleBlur, dirty, isValid }) => ( <form name="beta-signup-ios" method="POST" data-netlify="true" className={styles.form} action="/" > <div className={styles.inputContainer}> <div className={styles.inputField}> <input id="betaEmail" type="email" name="betaEmail" onChange={handleChange} onBlur={handleBlur} value={values.betaEmail} placeholder="Email (required)" aria-required="true" /> <label htmlFor="betaEmail">Email (required) { (errors.betaEmail && touched.betaEmail) && <div className={styles.error} style={ (errors.betaEmail && touched.betaEmail) ? {} : { display: 'none' }}> {errors.betaEmail} } <input type="hidden" name="form-name" value="beta-signup-ios" /> <div className={styles.buttonContainer}> { !(isValid && dirty) && <div className={styles.buttonDisabled} /> } <div className={styles.buttonShadow} /> <input type="submit" value="Sign Up" disabled={!(isValid && dirty)} /> )} ) } export default IOSSignup
javascript
23
0.502108
121
30.64
75
starcoderdata
using System.Net.Http; namespace ShareFile.Api.Client.Events { public delegate EventHandlerResponse ExceptionCallback(HttpResponseMessage responseMessage, int retryCount); }
c#
6
0.835391
112
33.714286
7
starcoderdata
#ifndef MAZE_H #define TREE_H typedef struct mazepos { int step; struct mazepos * north; struct mazepos * south; struct mazepos * east; struct mazepos * west; } Maze; typedef struct mazeroot { Maze * root; } Start; void printer(Start * sPos); void freeMaze(Start * sPos); Start * convert(char * filename); void stepCounter(Start * sPos); #endif
c
8
0.707042
33
15.136364
22
starcoderdata
<?php declare(strict_types=1); namespace NBPFetch\ExchangeRateTable; use NBPFetch\ApiCaller\AbstractApiCallerSingleOrCollection; use UnexpectedValueException; /** * Class ApiCaller * @package NBPFetch\ExchangeRateTable */ class ApiCaller extends AbstractApiCallerSingleOrCollection { /** * @var string API_SUBSET API Subset that returns exchange rate table data. */ private const API_SUBSET = "exchangerates/tables/"; /** * Returns a single exchange rate table from given URL. * @param string $path * @return ExchangeRateTable * @throws UnexpectedValueException */ public function getSingle(string $path): ExchangeRateTable { $fetchedExchangeRateTables = $this->getFromNBPAPI(self::API_SUBSET . $path); return $this->createExchangeRateTable($fetchedExchangeRateTables[0]); } /** * Returns a set of exchange rate tables from given URL. * @param string $path * @return ExchangeRateTableCollection * @throws UnexpectedValueException */ public function getCollection(string $path): ExchangeRateTableCollection { $fetchedExchangeRateTables = $this->getFromNBPAPI(self::API_SUBSET . $path); return $this->createExchangeRateTableCollection($fetchedExchangeRateTables); } /** * Creates an ExchangeRateTable object from fetched array. * @param array $fetchedExchangeRateTable * @return ExchangeRateTable */ private function createExchangeRateTable(array $fetchedExchangeRateTable): ExchangeRateTable { $exchangeRateCollection = new ExchangeRateCollection(); foreach ($fetchedExchangeRateTable["rates"] as $exchangeRate) { $exchangeRateCollection[] = new ExchangeRate($exchangeRate["code"], (string) $exchangeRate["mid"]); } return new ExchangeRateTable( $fetchedExchangeRateTable["table"], $fetchedExchangeRateTable["no"], $fetchedExchangeRateTable["effectiveDate"], $exchangeRateCollection ); } /** * Creates an ExchangeRateTableCollection object from fetched array. * @param array $fetchedExchangeRateTables * @return ExchangeRateTableCollection */ private function createExchangeRateTableCollection(array $fetchedExchangeRateTables): ExchangeRateTableCollection { $exchangeRateTableCollection = new ExchangeRateTableCollection(); foreach ($fetchedExchangeRateTables as $fetchedExchangeRateTable) { $exchangeRateTableCollection[] = $this->createExchangeRateTable($fetchedExchangeRateTable); } return $exchangeRateTableCollection; } }
php
15
0.70227
117
33.448718
78
starcoderdata
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TravelCompany { class TravelCompany { static void Main(string[] args) { string command = string.Empty; Dictionary<string, Dictionary<string, int>> destinations = new Dictionary<string, Dictionary<string, int>>(); while (true) { command = Console.ReadLine(); if (command == "ready") { break; } string[] arr = command.Split(new char[] { ':', ',' }, StringSplitOptions.RemoveEmptyEntries); string city = arr[0]; if (!destinations.ContainsKey(city)) { destinations[city] = new Dictionary<string, int>(); } for (int y = 1; y < arr.Length; y++) { string[] transport = arr[y].Split(new char[] { '-' }); destinations[city][transport[0]] = int.Parse(transport[1]); } } while (true) { command = Console.ReadLine(); if (command == "travel time!") { break; } string[] destination = command.Split(' '); string city = destination[0]; int seats = int.Parse(destination[1]); foreach (var k in destinations.Keys) { if (k == city) { int sum = 0; foreach (KeyValuePair<string, int> item in destinations[k]) { sum += item.Value; } sum -= seats; if (sum >= 0) { Console.WriteLine($"{city} -> all {seats} accommodated"); } else { Console.WriteLine($"{city} -> all except {Math.Abs(sum)} accommodated"); } } } } } } }
c#
24
0.376618
121
27.511905
84
starcoderdata
package com.hs.gpxparser.type; /** * of GPS fix. Value comes from list: {'none'|'2d'|'3d'|'dgps'|'pps'} * * * = GPS had no fix. * = military signal used * * signify "the fix info is unknown", leave out fixType entirely. */ public class Fix { /** * Constant that defines 'none' Fix type */ public static Fix NONE = new Fix("none"); /** * Constant that defines '2d' Fix type */ public static Fix TWO_D = new Fix("2d"); /** * Constant that defines '3d' Fix type */ public static Fix THREE_D = new Fix("3d"); /** * Constant that defines 'dgps' Fix type */ public static Fix DGPS = new Fix("dgps"); //'none'|'2d'|'3d'|'dgps'|'pps' /** * Constant that defines 'pps' Fix type */ public static Fix PPS = new Fix("pps"); private String value; private Fix(String value) { this.value = value; } public static Fix returnType(String value) { if (NONE.getValue().equals(value)) { return NONE; } else if (TWO_D.getValue().equals(value)) { return TWO_D; } else if (THREE_D.getValue().equals(value)) { return THREE_D; } else if (DGPS.getValue().equals(value)) { return DGPS; } else if (PPS.getValue().equals(value)) { return PPS; } return null; } public String getValue() { return value; } public String toString() { return value; } }
java
14
0.537922
81
23.138462
65
starcoderdata
#pragma once #include #include #include #include #include #include #include #include namespace mbgl { namespace style { template <class T> class PaintProperty { public: using TransitionableType = Transitionable using UnevaluatedType = Transitioning using EvaluatorType = PropertyEvaluator using PossiblyEvaluatedType = T; using Type = T; static constexpr bool IsDataDriven = false; }; template <class T, class A, class U> class DataDrivenPaintProperty { public: using TransitionableType = Transitionable using UnevaluatedType = Transitioning using EvaluatorType = DataDrivenPropertyEvaluator using PossiblyEvaluatedType = PossiblyEvaluatedPropertyValue using Type = T; static constexpr bool IsDataDriven = true; using Attribute = A; using Uniform = U; }; template <class T> class CrossFadedPaintProperty { public: using TransitionableType = Transitionable using UnevaluatedType = Transitioning using EvaluatorType = CrossFadedPropertyEvaluator using PossiblyEvaluatedType = Faded using Type = T; static constexpr bool IsDataDriven = false; }; /* * Special-case paint property traits for heatmap-color and line-gradient, * needed because these values do not fit into the * Undefined | Value | {Camera,Source,Composite}Function taxonomy that applies * to all other paint properties. * * These traits are provided here--despite the fact that color ramps * is not used like other paint properties--to allow the parameter-pack-based * batch evaluation of paint properties to compile properly. */ class ColorRampProperty { public: using TransitionableType = Transitionable using UnevaluatedType = Transitioning using EvaluatorType = PropertyEvaluator using PossiblyEvaluatedType = Color; using Type = Color; static constexpr bool IsDataDriven = false; static Color defaultValue() { return {}; } }; } // namespace style } // namespace mbgl
c++
16
0.755861
78
31.986667
75
starcoderdata
#include "gdt.h" #include "../platform/ibm/phys_virt.h" #include extern "C" void gdt_flush_asm(uint32_t gdt_ptr); void Gdt::create_gdt() { gdt_pointer_.limit = (sizeof(GDTEntry) * 5) - 1; gdt_pointer_.base = ((uint32_t) &gdt_entries_); // Null segment gdt_set_entry(0, 0, 0, 0, 0); // Code segment gdt_set_entry(1, 0, 0xFFFFFFFF, 0x9A, 0xCF); // Data segment gdt_set_entry(2, 0, 0xFFFFFFFF, 0x92, 0xCF); // User mode code segment gdt_set_entry(3, 0, 0xFFFFFFFF, 0xFA, 0xCF); // User mode data segment gdt_set_entry(4, 0, 0xFFFFFFFF, 0xF2, 0xCF); gdt_flush(); } void Gdt::gdt_set_entry(int32_t idx, uint32_t base, uint32_t limit, uint8_t access, uint8_t granularity) { gdt_entries_[idx].base_low = static_cast & 0xFFFF); gdt_entries_[idx].base_middle = static_cast >> 16) & 0xFF); gdt_entries_[idx].base_high = static_cast >> 24) & 0xFF); gdt_entries_[idx].limit_low = static_cast & 0xFFFF); gdt_entries_[idx].granularity = static_cast >> 16) & 0x0F); gdt_entries_[idx].granularity |= granularity & 0xF0; gdt_entries_[idx].access = access; } void Gdt::gdt_flush() { gdt_flush_asm((uint32_t)&gdt_pointer_); }
c++
10
0.629744
106
29.023256
43
starcoderdata
import java.security.MessageDigest; import java.sql.*; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; import java.net.URI; import java.net.URISyntaxException; import java.util.Date; import static spark.Spark.*; import spark.QueryParamsMap; import spark.Session; import spark.template.freemarker.FreeMarkerEngine; import spark.ModelAndView; import static spark.Spark.get; import com.heroku.sdk.jdbc.DatabaseUrl; import spark.utils.StringUtils; public class Main { public static void main(String[] args) { port(Integer.valueOf(System.getenv("PORT"))); staticFileLocation("/public"); get("/hello", (req, res) -> "Hello World"); get("/", (request, response) -> { Map<String, Object> attributes = new HashMap<>(); User user = request.session().attribute("User"); if (user != null) { attributes.put("userName", user.getName()); } return new ModelAndView(attributes, "index.ftl"); }, new FreeMarkerEngine()); get("/db", (req, res) -> { Connection connection = null; Map<String, Object> attributes = new HashMap<>(); try { connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now())"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); ArrayList output = new ArrayList while (rs.next()) { output.add("Read from DB: " + rs.getTimestamp("tick")); } attributes.put("results", output); return new ModelAndView(attributes, "db.ftl"); } catch (Exception e) { attributes.put("message", "There was an error: " + e); return new ModelAndView(attributes, "error.ftl"); } finally { if (connection != null) try { connection.close(); } catch (SQLException e) { } } }, new FreeMarkerEngine()); post("/login", (request, response) -> { String email = request.queryMap().get("email").value(); String password = Map<String, Object> attributes = new HashMap<>(); Connection connection = null; try { connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS societies (\n" + "ID BIGSERIAL PRIMARY KEY,\n" + "name varchar(255),\n" + "email varchar(255),\n" + "password text);"); // stmt.executeUpdate("INSERT INTO " + // "societies (name, email, password) " + // "VALUES ('Some society', ' ' PreparedStatement pS = connection.prepareStatement("SELECT ID, name, email " + "FROM societies " + "WHERE email = ? AND password = ?"); pS.setString(1, email); pS.setString(2, password); ResultSet rs = pS.executeQuery(); User user = null; while (rs.next()) { user = new User(rs.getInt("ID"), rs.getString("email"), rs.getString("name")); } if (user != null) { request.session().attribute("User", user); attributes.put("successMessage", user.getName() + " login correctly !"); attributes.put("userName", user.getName()); } else { attributes.put("errorMessage", "Wrong email or password"); } return new ModelAndView(attributes, "index.ftl"); } catch (Exception e) { attributes.put("errorMessage", "There was an error: " + e); return new ModelAndView(attributes, "error.ftl"); } finally { if (connection != null) try { connection.close(); } catch (SQLException e) { } } }, new FreeMarkerEngine()); get("/findFreeTime", (request, response) -> { Map<String, Object> attributes = new HashMap<>(); User user = request.session().attribute("User"); if (user == null) { response.redirect("/"); return new ModelAndView(attributes, "error.ftl"); } attributes.put("userName", user.getName()); QueryParamsMap date = request.queryMap().get("date"); QueryParamsMap dateSubmit = request.queryMap().get("date_submit"); String dateS, dateSubmitS; Date dateD; if (date.hasValue() && dateSubmit.hasValue()) { dateS = date.value(); dateSubmitS = dateSubmit.value(); } else { dateS = new SimpleDateFormat("dd MMMM, yyyy").format(new java.util.Date()); dateSubmitS = new SimpleDateFormat("yyyy/MM/dd").format(new java.util.Date()); } dateD = new Date( Integer.parseInt(dateSubmitS.substring(0, 4)), Integer.parseInt(dateSubmitS.substring(5, 7)) - 1, Integer.parseInt(dateSubmitS.substring(8, 10)) ); ArrayList<TreeMap<Long, Integer>> events = null; try { DataParser.Main main = new DataParser.Main(); events = main.start(); } catch(Exception e) {} TreeMap<Long, Integer> eventsForDay = getEventsByDate(events, dateD); if (eventsForDay == null) { eventsForDay = new TreeMap<>(); } StringBuilder labels = new StringBuilder(); StringBuilder data = new StringBuilder(); try { for (Map.Entry<Long, Integer> event : eventsForDay.entrySet()) { Date eventDate = new Date(event.getKey()); labels.append("\""); if (eventDate.getHours() < 10) labels.append("0"); labels.append(eventDate.getHours()); labels.append(":"); labels.append(eventDate.getMinutes()); if (eventDate.getMinutes() == 0) labels.append("0"); labels.append("\""); labels.append(","); data.append(event.getValue()); data.append(", "); } } catch (Exception e) {} attributes.put("labels", labels.toString()); attributes.put("data", data.toString()); attributes.put("date", dateS); attributes.put("dateSubmit", dateSubmitS); attributes.put("activeMenu", ""); return new ModelAndView(attributes, "findFreeTime.ftl"); }, new FreeMarkerEngine()); // get("/signup", (request, response) -> { // Map<String, Object> attributes = new HashMap<>(); // attributes.put("message", "Hello World!"); // // return new ModelAndView(attributes, "index.ftl"); // }, new FreeMarkerEngine()); } private static TreeMap<Long, Integer> getEventsByDate(ArrayList<TreeMap<Long, Integer>> events, Date date) { for (TreeMap<Long, Integer> eventsForSingleDay : events) { Map.Entry<Long, Integer> event = eventsForSingleDay.firstEntry(); if (event != null) { Date eventDate = new Date(event.getKey()); if (eventDate.getYear() == date.getYear() && eventDate.getMonth() == date.getMonth() && eventDate.getDate() == date.getDate()) { return eventsForSingleDay; } } } return null; } private static String hashSha256(String toHash) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(toHash.getBytes()); byte byteData[] = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); } catch (Exception e) { } return ""; } }
java
21
0.619968
130
26.296703
273
starcoderdata
public void createPharmacyStaffBill() { Date startTime = new Date(); Map m = new HashMap(); m.put("bt", BillType.PharmacyPre); // m.put("class", PreBill.class); m.put("fd", getFromDate()); m.put("td", getToDate()); m.put("ins", getSessionController().getInstitution()); String sql; sql = "Select b from PreBill b where " + " b.createdAt between :fd and :td " + " and b.billType=:bt" + " and b.billedBill is null " + " and b.institution=:ins " + " and b.toStaff is not null " + " order by b.createdAt "; // // ////System.out.println("sql = " + sql); bills = getBillFacade().findBySQL(sql, m, TemporalType.TIMESTAMP); netTotalValue = 0.0; for (Bill b : bills) { netTotalValue += b.getNetTotal(); } commonController.printReportDetails(fromDate, toDate, startTime, "Pharmacy/Reports/Summeries/BHT issue/BHT issue - staff(/faces/pharmacy/pharmacy_report_staff_issue_bill.xhtml)"); }
java
12
0.529974
187
37.758621
29
inline
package cn.bitflash.vip.system.controller; import cn.bitflash.entities.UserEntity; import cn.bitflash.util.R; import cn.bitflash.util.SmsUtils; import cn.bitflash.vip.system.feign.SystemFeign; import io.swagger.annotations.Api; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.util.Random; @RestController @RequestMapping("/system") @Api(value = "短息Con",tags={"注册时发送短信验证"}) public class VerifyCode { @Autowired private SystemFeign systemFeign; @RequestMapping("getVerifyCode") public R sent(@RequestParam String mobile, @RequestParam String type, HttpServletResponse response) { response.addHeader("Access-Control-Allow-Origin", "*"); if (StringUtils.isBlank(mobile)) { return R.error(501, "手机号不能为空"); } UserEntity userEntity = systemFeign.selectUserEntityByMobile(mobile); String verifyCode = generateCode(); if (type.equals("reg")) { if (userEntity != null) { return R.error("用户已注册,请直接登录"); } return SmsUtils.smsApi(mobile, verifyCode, "贝壳", "SMS_135330146"); } // 找回密码 if (type.equals("findPwd")) { if (userEntity == null) { return R.error("手机号错误"); } return SmsUtils.smsApi(mobile, verifyCode, "贝壳", "SMS_136065023"); } return R.error("系统错误"); } private String generateCode() { return String.valueOf(new Random().nextInt(8999) + 1000); } }
java
13
0.672241
105
33.5
52
starcoderdata
'use strict'; /* global module */ var SELECTORS = Object.freeze({ main: '#thread-list', conversation: '.threadlist-item', smsConversation: '.threadlist-item[data-last-message-type="sms"]', mmsConversation: '.threadlist-item[data-last-message-type="mms"]', conversationTitle: '.threadlist-item-title', navigateToComposerHeaderButton: '#threads-composer-link' }); function InboxAccessor(client) { this.client = client; } InboxAccessor.prototype = { get firstConversation() { return this.client.helper.waitForElement(SELECTORS.conversation); }, get smsConversation() { return this.client.helper.waitForElement(SELECTORS.smsConversation); }, get mmsConversation() { return this.client.helper.waitForElement(SELECTORS.mmsConversation); }, get conversations() { return this.client.findElements(SELECTORS.conversation); }, get createNewMessageButton() { return this.client.helper.waitForElement( SELECTORS.navigateToComposerHeaderButton ); }, getConversationTitle: function(conversation) { return conversation.findElement(SELECTORS.conversationTitle); }, waitToAppear: function() { return this.client.helper.waitForElement(SELECTORS.main); }, // Temporary solution to keep the current tests running. // TODO: bug 1167103 navigateToComposer: function() { this.createNewMessageButton.tap(); } }; module.exports = InboxAccessor;
javascript
11
0.732782
72
24.473684
57
starcoderdata
// -*- c++ -*- #ifndef KEYBOARDPRESENTER_H #define KEYBOARDPRESENTER_H #include #include #include #include #include "keyboardcomm.h" #include "keyboardview.h" #include "layoutpresenter.h" #include "programspresenter.h" #include "triggerspresenter.h" #include "valuespresenter.h" class KeyboardModel; class KeyboardComm; class KeyboardPresenter : public QObject { Q_OBJECT Q_DISABLE_COPY(KeyboardPresenter) KeyboardComm::DeviceList mDevices; QSharedPointer mCurrentDevice; QScopedPointer mView; QSharedPointer mKeyboardModel; LayoutPresenter mLayoutPresenter; ProgramsPresenter mProgramsPresenter; TriggersPresenter mTriggersPresenter; ValuesPresenter mValuesPresenter; QList<QPair<QString, QWidget*> > createSubviewList(); public: KeyboardPresenter(); ~KeyboardPresenter(); signals: void modelChanged(const QSharedPointer void deviceChanged(const QSharedPointer public slots: void showAction(); void selectDeviceAction(int index); void updateDeviceListAction(); void uploadAction(); void downloadAction(); }; #endif
c
11
0.792631
57
20.611111
54
starcoderdata
from utils.log import init_logger LOG = init_logger('uart', 'warn') LOG_SEND = init_logger('send', 'debug') LOG_RECEIVE = init_logger('receive', 'debug') PATH_DEVICES = '/sys/bus/usb/devices/*-' PATH_USB_TTY = ':*/'
python
6
0.66055
45
26.25
8
starcoderdata
// const submitBtn = document.querySelector('#submit-btn'); // submitBtn.onclick = function(){ // const nameInput = document.querySelector('#name'); // const ageInput = document.querySelector('#age'); // const addressInput = document.querySelector('#address'); // const mobileInput = document.querySelector('#mobile'); // const name = nameInput.value; // const age = ageInput.value; // const address = addressInput.value; // const mobile = mobileInput.value; // nameInput.value = ""; // ageInput.value = ""; // addressInput.value = ""; // mobileInput.value = ""; // console.log(name); // fetch('http://localhost:5000/insert', { // headers: { // 'Content-type': 'application/json' // }, // method: 'POST', // body: JSON.stringify({name: name, age: age, address: address, mobile: mobile}) // }) // .then(response => response.json()) // .then(data => insertRowIntoTable(data['data'])); // } // function insertRowIntoTable(data){ // } var sendInfo = document.getElementById("submit-btn"); sendInfo.addEventListener("click", function(){ var request = XMLHttpRequest(); const username = document.getElementById("user-email"); const password = document.getElementById("user-password"); console.log(username, password); // request.open('POST', "http://localhost:5000/applicant/login", true); // request.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // request.send(`name=${username}&pass=${password}`); request.open("GET", "http://localhost:5000/applicant/login"); request.send(); })
javascript
9
0.634671
89
30.272727
55
starcoderdata
/* Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: */ #pragma once #include "util/name_generator.h" #include "util/rb_map.h" #include "util/name_map.h" #include "kernel/expr.h" namespace lean { /* inductive LocalDecl | cdecl (index : Nat) (name : Name) (userName : Name) (type : Expr) (bi : BinderInfo) | ldecl (index : Nat) (name : Name) (userName : Name) (type : Expr) (value : Expr) */ class local_decl : public object_ref { friend class local_ctx; friend class local_context; friend void initialize_local_ctx(); local_decl(unsigned idx, name const & n, name const & un, expr const & t, expr const & v); local_decl(local_decl const & d, expr const & t, expr const & v); local_decl(unsigned idx, name const & n, name const & un, expr const & t, binder_info bi); local_decl(local_decl const & d, expr const & t); public: local_decl(); local_decl(local_decl const & other):object_ref(other) {} local_decl(local_decl && other):object_ref(other) {} local_decl(obj_arg o):object_ref(o) {} local_decl(b_obj_arg o, bool):object_ref(o, true) {} local_decl & operator=(local_decl const & other) { object_ref::operator=(other); return *this; } local_decl & operator=(local_decl && other) { object_ref::operator=(other); return *this; } friend bool is_eqp(local_decl const & d1, local_decl const & d2) { return d1.raw() == d2.raw(); } unsigned get_idx() const { return static_cast<nat const &>(cnstr_get_ref(raw(), 0)).get_small_value(); } name const & get_name() const { return static_cast<name const &>(cnstr_get_ref(raw(), 1)); } name const & get_user_name() const { return static_cast<name const &>(cnstr_get_ref(raw(), 2)); } expr const & get_type() const { return static_cast<expr const &>(cnstr_get_ref(raw(), 3)); } optional get_value() const { if (cnstr_tag(raw()) == 0) return none_expr(); return some_expr(static_cast<expr const &>(cnstr_get_ref(raw(), 4))); } binder_info get_info() const; expr mk_ref() const; }; /* Plain local context object used by the kernel type checker. */ class local_ctx : public object_ref { protected: template<bool is_lambda> expr mk_binding(unsigned num, expr const * fvars, expr const & b) const; public: local_ctx(); explicit local_ctx(obj_arg o):object_ref(o) {} local_ctx(b_obj_arg o, bool):object_ref(o, true) {} local_ctx(local_ctx const & other):object_ref(other) {} local_ctx(local_ctx && other):object_ref(other) {} local_ctx & operator=(local_ctx const & other) { object_ref::operator=(other); return *this; } local_ctx & operator=(local_ctx && other) { object_ref::operator=(other); return *this; } bool empty() const; /* Low level `mk_local_decl` */ local_decl mk_local_decl(name const & n, name const & un, expr const & type, binder_info bi); /* Low level `mk_local_decl` */ local_decl mk_local_decl(name const & n, name const & un, expr const & type, expr const & value); expr mk_local_decl(name_generator & g, name const & un, expr const & type, binder_info bi = mk_binder_info()) { return mk_local_decl(g.next(), un, type, bi).mk_ref(); } expr mk_local_decl(name_generator & g, name const & un, expr const & type, expr const & value) { return mk_local_decl(g.next(), un, type, value).mk_ref(); } /** \brief Return the local declarations for the given reference. */ optional find_local_decl(name const & n) const; optional find_local_decl(expr const & e) const { return find_local_decl(fvar_name(e)); } local_decl get_local_decl(name const & n) const; local_decl get_local_decl(expr const & e) const { return get_local_decl(fvar_name(e)); } /* \brief Return type of the given free variable. \pre is_fvar(e) */ expr get_type(expr const & e) const { return get_local_decl(e).get_type(); } /** Return the free variable associated with the given name. \pre get_local_decl(n) */ expr get_local(name const & n) const; /** \brief Remove the given local decl. */ void clear(local_decl const & d); expr mk_lambda(unsigned num, expr const * fvars, expr const & e) const; expr mk_pi(unsigned num, expr const * fvars, expr const & e) const; expr mk_lambda(buffer const & fvars, expr const & e) const { return mk_lambda(fvars.size(), fvars.data(), e); } expr mk_pi(buffer const & fvars, expr const & e) const { return mk_pi(fvars.size(), fvars.data(), e); } expr mk_lambda(expr const & fvar, expr const & e) { return mk_lambda(1, &fvar, e); } expr mk_pi(expr const & fvar, expr const & e) { return mk_pi(1, &fvar, e); } expr mk_lambda(std::initializer_list const & fvars, expr const & e) { return mk_lambda(fvars.size(), fvars.begin(), e); } expr mk_pi(std::initializer_list const & fvars, expr const & e) { return mk_pi(fvars.size(), fvars.begin(), e); } }; void initialize_local_ctx(); void finalize_local_ctx(); }
c
14
0.647496
131
46.775701
107
starcoderdata
"""Модуль содержит примеры работы для класса Color""" from change_color.color import Color def check_on_examples(): """ Функция check_on_examples демонстрирует работу класса Colour на примерах """ first_color = Color('#01E305') print(f'{first_color} был преобразован к {first_color.lighten(10)}') second_color = Color('#15F47A') print(f'{second_color} был преобразован к {second_color.darken(50)},' f'а затем обратно к {second_color.lighten(50)}') black = Color('#000000') print(f'{black} был преобразован к {black.lighten(100)}') new_color = Color('#99CCFF') print(f'{new_color} был преобразован к {new_color.darken(50)}') third_color = Color('#45A1F0') print(f'{third_color} был преобразован к {third_color.darken(20)}') if __name__ == "__main__": check_on_examples()
python
11
0.659353
73
33.64
25
starcoderdata
#!/usr/bin/env python import sys, math, os, pexpect, commands # default values of input parameters: m = 1.0; b = 0.7; c = 5.0; func = 'y'; A = 5.0; w = 2*math.pi y0 = 0.2; tstop = 30.0; dt = 0.05; case = 'tmp1'; screenplot = 1 remote_host = 'magnum.uio.no' user = 'douglas' if not '-passwdfile' in sys.argv: import getpass password = getpass.getpass('Password on %s@%s: ' % (user, remote_host)) else: # get password from a secret and highly protected file on my laptop... f = open('/work/scripting/trunk/.pw_douglas', 'r') password = f.read().strip() f.close() # read variables from the command line, one by one: while len(sys.argv) > 1: option = sys.argv[1]; del sys.argv[1] if option == '-m': m = float(sys.argv[1]); del sys.argv[1] elif option == '-b': b = float(sys.argv[1]); del sys.argv[1] elif option == '-c': c = float(sys.argv[1]); del sys.argv[1] elif option == '-func': func = sys.argv[1]; del sys.argv[1] elif option == '-A': A = float(sys.argv[1]); del sys.argv[1] elif option == '-w': w = float(sys.argv[1]); del sys.argv[1] elif option == '-y0': y0 = float(sys.argv[1]); del sys.argv[1] elif option == '-tstop': tstop = float(sys.argv[1]); del sys.argv[1] elif option == '-dt': dt = float(sys.argv[1]); del sys.argv[1] elif option == '-noscreenplot': screenplot = 0 elif option == '-case': case = sys.argv[1]; del sys.argv[1] elif option == '-host': remote_host = sys.argv[1]; del sys.argv[1] elif option == '-user': user = sys.argv[1]; del sys.argv[1] else: print sys.argv[0],': invalid option',option sys.exit(1) # make input file to the program: f = open('%s.i' % case, 'w') # write a multi-line (triple-quoted) string with # variable interpolation: f.write(""" %(m)g %(b)g %(c)g %(func)s %(A)g %(w)g %(y0)g %(tstop)g %(dt)g """ % vars()) f.close() # generate script to be run on the remote machine: f = open('run_%s.py' % case, 'w') f.write("""\ #!/usr/bin/env python import os, shutil, sys d = '%(case)s' if os.path.isdir(d): shutil.rmtree(d) os.mkdir(d) os.rename('%(case)s.i', '%(case)s/%(case)s.i') # move .i file os.chdir(d) cmd = '../oscillator < %(case)s.i' import commands failure, output = commands.getstatusoutput(cmd) if failure: print 'running the oscillator code failed' print output; sys.exit(1) """ % vars()) f.close() # copy files to remote host: cmd = 'scp %(case)s.i run_%(case)s.py '\ '%(user)s@%(remote_host)s:tmp' % vars() print cmd # run application on remote host using pexpect to feed password etc. child = pexpect.spawn(cmd) child.expect('password:') child.sendline(password) print 'before:', child.before print 'after:', child.after child.expect(pexpect.EOF) # important; wait for end of scp session child.close() # can inspect the dialog that pexpect automates by printing # child.before and child.after, see pexpect documentation # run on remove host: cmd = 'ssh %(user)s@%(remote_host)s '\ '"cd tmp; python run_%(case)s.py"' % vars() print cmd child = pexpect.spawn(cmd) child.expect('password:') child.sendline(password) child.expect(pexpect.EOF) # important; wait for end of scp session # copy result file back to local host: cmd = 'scp %(user)s@%(remote_host)s:tmp/%(case)s/sim.dat .' % vars() print cmd child = pexpect.spawn(cmd) child.expect('password:') child.sendline(password) child.expect(pexpect.EOF) # important; wait for end of scp session import time; time.sleep(2) # sleep to make scp finish if not os.path.isfile('sim.dat'): print 'no result file sim.dat - script aborted...' # make file with gnuplot commands: f = open(case + '.gnuplot', 'w') f.write(""" set title '%s: m=%g b=%g c=%g f(y)=%s A=%g w=%g y0=%g dt=%g'; """ % (case,m,b,c,func,A,w,y0,dt)) if screenplot: f.write("plot 'sim.dat' title 'y(t)' with lines;\n") f.write(""" set size ratio 0.3 1.5, 1.0; # define the postscript output format: set term postscript eps monochrome dashed 'Times-Roman' 28; # output file containing the plot: set output '%s.ps'; # basic plot command plot 'sim.dat' title 'y(t)' with lines; # make a plot in PNG format: set term png small; set output '%s.png'; plot 'sim.dat' title 'y(t)' with lines; """ % (case,case)) f.close() # make plot on local host: cmd = 'gnuplot -geometry 800x200 -persist ' + case + '.gnuplot' failure, output = commands.getstatusoutput(cmd) if failure: print 'running gnuplot failed'; sys.exit(1) # clean up: import time; time.sleep(3) # let Gnuplot have some time for plotting... for file in ('run_%s.py' % case, '%s.i' % case, 'sim.dat'): print 'removing', file; os.remove(file)
python
12
0.609481
75
30.43871
155
starcoderdata
""" This file is used to run the experiment. Note that it should always be run from within the main project directory, since the structure of the package is designed with that expectation. """ if __name__ == '__main__': from expts.controllers import Controller Controller() #import profile #profile.run('Controller()')
python
6
0.711816
143
33.7
10
starcoderdata
/* * Copyright © 2019, SAS Institute Inc., Cary, NC, USA. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ /* usage: node myipd your-machine-fullname(ex: d1111111111.us.acme.com) */ let dns = require('dns'); let os = require('os'); let f = process.argv[2]; console.log(`server name = ${f}`); dns.resolve(f, (err, r) => { if (err) { console.log(err); } else { console.log(`Your ip is: ${r}`); } });
javascript
7
0.603376
76
21.619048
21
starcoderdata
<?php namespace app\modules\api\models; use Yii; use yii\db\Query; class ReportQueries { public static function getAdmissionStatus(){ $query = Yii::$app->db->createCommand("SELECT COUNT( `adm`.`transaction_number` ) AS `adm_count` , DATE_FORMAT( `adm`.`created_on` , '%Y-%c-%d' ) AS `adm_date` , `adm`.`last_status` AS `adm_status` FROM `admission` AS `adm` WHERE `adm`.`created_on` BETWEEN '2015-12-07 00:00:00' AND '2015-12-10 23:59:59' GROUP BY DATE_FORMAT( `adm`.`created_on` , '%Y-%c-%d' ) , `adm`.`last_status`"); $rows = $query->queryAll(); return $rows; } }
php
11
0.537911
113
29.391304
23
starcoderdata
public int createUploadInfoTable() { string[] insertStr = new string[30]; // truncate the table mainForm.commandString = "delete from tUploadInfo"; FbCommand sqlCmd = new FbCommand(mainForm.commandString, mainForm.bookConn); sqlCmd.ExecuteNonQuery(); // create insert strings insertStr[0] = "insert into tUploadInfo (ListingService, UID, Pwd, FTPAddr, FTPDir, FileFmt ) " + @"values('A1 Books','','','mkt.A1books.com','/data','Tab')"; insertStr[1] = "insert into tUploadInfo (ListingService, UID, Pwd, FTPAddr, FTPDir, FileFmt ) " + @"values('ABE','','','ftp.abebooks.com','','ABE')"; insertStr[2] = "insert into tUploadInfo (ListingService, UID, Pwd, FTPAddr, FTPDir, FileFmt ) " + @"values('Alibris','','','aus.alibris.com','/','HB')"; insertStr[3] = "insert into tUploadInfo (ListingService, UID, Pwd, FTPAddr, FTPDir, FileFmt ) " + @"values('Amazon','','','n/a','/','Tab')"; insertStr[4] = "insert into tUploadInfo (ListingService, UID, Pwd, FTPAddr, FTPDir, FileFmt ) " + @"values('Antiqbook','','','dusty.antiqbook.com','/','UIEE')"; insertStr[5] = "insert into tUploadInfo (ListingService, UID, Pwd, FTPAddr, FTPDir, FileFmt ) " + @"values('Barnes & Noble','','','sftp.barnesandnoble.com','/home/Listings/Inventory_to_Drop/','Tab')"; insertStr[6] = "insert into tUploadInfo (ListingService, UID, Pwd, FTPAddr, FTPDir, FileFmt ) " + @"values('Biblio','','','ftp.biblio.com','./','UIEE')"; insertStr[7] = "insert into tUploadInfo (ListingService, UID, Pwd, FTPAddr, FTPDir, FileFmt ) " + @"values('Biblion','','','217.158.127.116','./','UIEE')"; insertStr[8] = "insert into tUploadInfo (ListingService, UID, Pwd, FTPAddr, FTPDir, FileFmt ) " + @"values('Bibliophile','','','www.bookbase.com','/','UIEE')"; insertStr[9] = "insert into tUploadInfo (ListingService, UID, Pwd, FTPAddr, FTPDir, FileFmt ) " + @"values('Book Byte','','','ftp.bookbyte.com','/','UIEE')"; insertStr[10] = "insert into tUploadInfo (ListingService, UID, Pwd, FTPAddr, FTPDir, FileFmt ) " + @"values('Bonanza','','','ftp.bonanza.com','/','Tab')"; insertStr[11] = "insert into tUploadInfo (ListingService, UID, Pwd, FTPAddr, FTPDir, FileFmt ) " + @"values('ChooseBooks','','','ftp.choosebooks.com','/','UIEE')"; insertStr[12] = "insert into tUploadInfo (ListingService, UID, Pwd, FTPAddr, FTPDir, FileFmt ) " + @"values('Chrislands','','','ftp.chrislands.com','/','Tab')"; insertStr[13] = "insert into tUploadInfo (ListingService, UID, Pwd, FTPAddr, FTPDir, FileFmt ) " + @"values('Google','','','uploads.google.com','/','XML')"; insertStr[14] = "insert into tUploadInfo (ListingService, UID, Pwd, FTPAddr, FTPDir, FileFmt ) " + @"values('Half.com','','','n/a','/','CSV')"; insertStr[15] = "insert into tUploadInfo (ListingService, UID, Pwd, FTPAddr, FTPDir, FileFmt ) " + @"values('Papa Media','','','(internal)','(internal)','Tab')"; insertStr[16] = "insert into tUploadInfo (ListingService, UID, Pwd, FTPAddr, FTPDir, FileFmt ) " + @"values('Scribblemonger','','','ftp.scribblemonger.com','/','UIEE')"; insertStr[17] = "insert into tUploadInfo (ListingService, UID, Pwd, FTPAddr, FTPDir, FileFmt ) " + @"values('Tom Folio','','','204.246.14.212','/','UIEE')"; insertStr[18] = "insert into tUploadInfo (ListingService, UID, Pwd, FTPAddr, FTPDir, FileFmt ) " + @"values('Valore Books','','','ftp.valorebooks.com','/Inventory','CSV')"; insertStr[19] = "insert into tUploadInfo (ListingService, UID, Pwd, FTPAddr, FTPDir, FileFmt ) " + "values('Custom Site #1','','','','','')"; insertStr[20] = "insert into tUploadInfo (ListingService, UID, Pwd, FTPAddr, FTPDir, FileFmt ) " + "values('Custom Site #2','','','','','')"; insertStr[21] = "insert into tUploadInfo (ListingService, UID, Pwd, FTPAddr, FTPDir, FileFmt ) " + "values('Custom Site #3','','','','','')"; insertStr[22] = "insert into tUploadInfo (ListingService, UID, Pwd, FTPAddr, FTPDir, FileFmt ) " + "values('Custom Site #4','','','','','')"; if (bookConn.State == ConnectionState.Closed) bookConn.Open(); try { for (int i = 0; i < 23; i++) { // insert info for each of the listing services sqlCmd = new FbCommand(insertStr[i], bookConn); sqlCmd.ExecuteNonQuery(); } // NOTE: if all entries are not showing up in table, go to mainForm and search for "farkeled" //lbStatus.Items.Insert(0, "table tUploadInfo loaded successfully"); //lbStatus.Refresh(); } catch (Exception ex) { MessageBox.Show("error: " + ex.Message); } return 0; }
c#
16
0.535452
118
53.571429
98
inline
from enum import auto from ...utils.misc import StringEnum class Anchor(StringEnum): """ Anchor: The anchor position for text CENTER The text origin is centered on the layer item bounding box. UPPER_LEFT The text origin is on the upper left corner of the bounding box UPPER_RIGHT The text origin is on the upper right corner of the bounding box LOWER_LEFT The text origin is on the lower left corner of the bounding box LOWER_RIGHT The text origin is on the lower right corner of the bounding box """ CENTER = auto() UPPER_LEFT = auto() UPPER_RIGHT = auto() LOWER_LEFT = auto() LOWER_RIGHT = auto()
python
7
0.700152
80
28.863636
22
starcoderdata
/** * simple breadcrumb control using handlebars template * known limitations - if used server-side it won't attach clickhandlers */ var UIbreadcrumb = function(/* @var jQuery|null */ $existingContainer) { var that = this this.crumbs = [] this.clickHandlers = {} this.withJquery = (typeof jQuery !== 'undefined') this.options = { useSeparator : true, separatorHtml : null // default from template } if (typeof E2 !== 'undefined') { this.get_uid = E2.core.get_uid // used to attach onClick events at add/prepend time this._template = E2.views.partials.breadcrumb } else { var uid_c = 0 // server-side this.get_uid = function(){return ++uid_c} this._template = function(){return function(x){return (x)}} } if (this.withJquery && ($existingContainer instanceof jQuery)) { this.container = $existingContainer this._attach() } else { this.container = null // only produce html } Object.defineProperty(this, 'length', { get: function(){return that.crumbs.length} }) } UIbreadcrumb.prototype.getTemplateData = function() { return { options: this.options, crumbs: this.crumbs } } UIbreadcrumb.prototype.renderHtml = function() { return this._template(this.getTemplateData()) } UIbreadcrumb.prototype.render = function($container) { // optionally supply $container at last minute (client js only) if (this.withJquery) { if ($container instanceof jQuery) this.container = $container if (this.container) { this.container.html(this.renderHtml()) this._attach() return this.container } } else return this.renderHtml() } UIbreadcrumb.prototype._attach = function() { this.container.find('a').off('.breadcrumb') this.container.find('a').on('click.breadcrumb', this.clickHandler.bind(this)) } UIbreadcrumb.prototype.destroy = function() { if (this.withJquery && this.container) { this.container.find('a').off('.breadcrumb') this.container.html('') } this.clickHandlers = {} this.crumbs = [] this.container = null } /** * add a new crumb * @param text * @param link optional * @param onClick optional * @param uid optional */ UIbreadcrumb.prototype.add = function(text, link, onClick, uid) { this.crumbs.push( this._makeCrumb(text, link, onClick, uid) ) return this } UIbreadcrumb.prototype.prepend = function(text, link, onClick, uid) { this.crumbs.unshift( this._makeCrumb(text, link, onClick, uid) ) return this } UIbreadcrumb.prototype._makeCrumb = function(text, linkHref, onClick, uid) { uid = uid || ('bc'+this.get_uid()) linkHref = linkHref || '' if (typeof onClick === 'function') { this.clickHandlers[uid] = onClick if (linkHref === '') linkHref = '#' } return { uid: uid, link: linkHref, text: text } } UIbreadcrumb.prototype.clickHandler = function(e) { var domNode = e.currentTarget var $a = jQuery(domNode) var uid = $a.data('uid') if (uid && (typeof this.clickHandlers[uid] === 'function')) { this.clickHandlers[uid](domNode) e.preventDefault() e.stopPropagation() return false } else return true } if (typeof module !== 'undefined') module.exports = UIbreadcrumb
javascript
17
0.689633
118
24.467213
122
starcoderdata
<?php global $contextFile, $shaclDir, $generatedDir; $generatedDir="generated"; $contextFile="generated/context.json"; $shaclDir="generated/shacl"; function autonote(){echo "autogenerated...";} function init () {echo "**auto-generated from model/*.php via pre-commit hook. Edit in PHP in git and enable hook with `cd .git/hooks && ln -s ../../.githooks/pre-commit pre-commit`** "; } function table ($section, $sectionExampleURI, $owl, $shacl, $example, $context){ global $contextFile, $shaclDir; //merge dataid with distribution if($section=="distribution"){ $section="dataid"; } if ($shacl != "missing") { file_put_contents("$shaclDir/$section.shacl",$shacl .PHP_EOL .PHP_EOL,FILE_APPEND); } if ($context !== "missing" && $context !== "duplicate" ){ file_put_contents($contextFile,$context.",".PHP_EOL.PHP_EOL,FILE_APPEND); } //file_put_contents("$examplesDir/$section.example.jsonld",$example .PHP_EOL,FILE_APPEND); $mdString = render($owl,$shacl,$example,$context,$section,$sectionExampleURI); echo $mdString; } function render($owl,$shacl,$example,$context,$section,$sectionExampleURI){ // prepare context string $cstring=""; if(trim($context)!="duplicate"){ $cstring = "```javascript $context ``` ";} //prepare example string //TODO change URI $exstring= " \"@id\": \"$sectionExampleURI\", $example"; return " Example (JSON-LD): ```javascript { $exstring } ``` Spec (OWL, SHACL, JSON-LD Context) ```turtle $owl ``` ```turtle $shacl ``` ".$cstring.""; } ?>
php
13
0.667519
183
22
68
starcoderdata
using UniModules.UniGame.AddressableTools.Runtime.Extensions; using UniModules.UniGame.SerializableContext.Runtime.Addressables; namespace UniGame.UniNodes.GameFlow.Runtime.Commands { using System.Collections.Generic; using Cysharp.Threading.Tasks; using UniModules.UniCore.Runtime.DataFlow.Interfaces; using UniModules.UniGame.Core.Runtime.DataFlow.Interfaces; using UnityEngine; using UnityEngine.AddressableAssets; public class LoadAddressablesSourcesCommand<TSource, TResult> where TResult : class where TSource : Object { private readonly IReadOnlyList resources; private readonly List sources = new List public IReadOnlyList Sources => sources; public LoadAddressablesSourcesCommand(IReadOnlyList resources) { this.resources = resources; } public async UniTask Execute(ILifeTime lifeTime) { sources.Clear(); return await resources.LoadAssetsTaskAsync<TSource, TResult, AssetReference>(sources,lifeTime); } } }
c#
13
0.726904
107
33.305556
36
starcoderdata
$(document).ready(function() { $('#usersform').bootstrapValidator({ fields: { name: { validators: { notEmpty: { message: 'El nombre es obligatorio y no puede estar vacío' } } }, email: { validators: { notEmpty: { message: 'La dirección de correo electrónico es obligatoria y no puede estar vacía' }, emailAddress: { message: 'La entrada no es una dirección de correo electrónico válida' } } }, password: { validators: { notEmpty: { message: 'La contraseña es obligatoria y no puede estar vacía' }, stringLength: { min: 6, message: 'La contraseña debe tener al menos 6 caracteres' }, identical: { field: 'password_confirmation', message: 'La contraseña y su confirmación no son las mismas.' } } }, password_confirmation: { validators: { notEmpty: { message: 'Se requiere confirmación de contraseña y no puede estar vacía' }, identical: { field: 'password', message: 'La contraseña y su confirmación no son las mismas.' } } } } }); });
javascript
16
0.44832
92
29.98
50
starcoderdata
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2020 FIRST Team 2393. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.recharge; /** Hardware Mappings * * One place to find what's connected how */ public class RobotMap { // Power Distribution Panel // // 40 Amp connectors // 0 Drive motor 15 Drive motor // 1 Drive motor 14 Drive motor // 2 Hood 13 Shooter // 3 Telescope 12 Colorspin // // Below 40 Amp ports // 4 Intake Arm 11 Intake Arm // 5 Intake Roller 10 Conveyor Back // 6 Climb 9 Conveyor Horizontal // 7 Color LED 8 Camera LED // // PDP controller port -> RoboRIO // PDP PCM port -> PCM, compressor, solenoids // // PDP VRM port -> // VRM 12V, 2A // 1) Radiop // 2) must not be used // // VRM 12V, 500mA // 1) Prox sensor at end of conveyors // 2) Prox sensor in 'ejector' // // VRM 5V, 500mA // 1) // 2) // // VRM 5V, 2A // 1) Raspberry Pi power // 2) Color LED strip power // Talon CAN IDs ================================= // Drivetrain motors public final static int LEFT_MOTOR_MAIN = 4; public final static int RIGHT_MOTOR_MAIN = 3; public final static int LEFT_MOTOR_SLAVE = 2; public final static int RIGHT_MOTOR_SLAVE = 1; // Shooter Motors public final static int SHOOTER_SLAVE_MOTOR = 5; public final static int SHOOTER_MOTOR = 6; // Telescope-Climb Motor public final static int CLIMBER_MOTOR = 13; public final static int TELESCOPE_MOTOR = 7; // Motor port used for wheel-of-fortune on control panel public final static int CONTROL_PANEL_WHEEL = 8; // Intake Motors public final static int INTAKE_ROTATOR_SLAVE = 9; public final static int INTAKE_ROTATOR = 10; public final static int INTAKE_SPINNER = 11; // Conveyor Motors public final static int CONVEYOR_BOTTOM = 12; public final static int CONVEYOR_TOP = 14; // Digital IO Sensors public final static int SHOOTER_SENSOR_LOW_CONVEYOR = 0; public final static int SHOOTER_SENSOR_READY = 1; public final static int SHOOTER_SENSOR_EJECT = 2; // Limit switch that detects when intake is all the way 'up' public final static int INTAKE_HOME_SENSOR = 4; // PWM port for LED Strip public static final int LED_STRIP = 8; // PCM ports used for solenoids public static final int HOOD_ADJUST = 4; public static final int INTAKE_AGITATOR = 5; public static final int GEAR_SOLENOID = 6; public static final int CONTROL_PANEL_SOLENOID = 7; }
java
5
0.582308
80
31.333333
93
starcoderdata
from django.core.mail import send_mail from hermes.forms.models import Submission from hermes.forms.signals import submission_received from hermes.utils.email import render_email_body from .email import render_submission_body from .models import FormMailSettings def send_submission_to_email(submission: Submission, **kwargs) -> None: try: settings = FormMailSettings.objects.filter(form=submission.form).first() except FormMailSettings.DoesNotExist: return (subject, body) = render_submission_body(submission=submission) send_mail( subject=subject, message=body.plain, from_email=None, html_message=body.html, recipient_list=[settings.email_address], ) def connect_signals() -> None: submission_received.connect(send_submission_to_email)
python
13
0.726723
80
27.517241
29
starcoderdata
/** * Copyright 2018 Google LLC * * 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 * * https://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. */ Polymer({ is: 'tfma-line-chart-grid', properties: { /** * List of all metrics available for linecharts. * @type {!Array */ metrics: { type: Array, value: function() { return []; }, }, /** * A comma separated string of metrics to skip. * @type {string} */ blacklist: { type: String, value: '', }, /** * An array of selectable metrics. * @private {!Array */ selectableMetrics_: { type: Array, computed: 'computeSelectableMetrics_(metrics, blacklist)', observer: 'selectableMetricsChanged_', }, selectedMetric_: {type: String, observer: 'selectedMetricChanged_'}, /** * List of metrics that are shown as linecharts. * The user may add/remove a metric linechart. * @type {!Array */ selectedMetrics_: {type: Array}, /** * The line chart provider object. * @type {!tfma.LineChartProvider} */ provider: {type: Object}, /** * List of metrics that can be added to linecharts, i.e. all metrics * excluding the selected metrics. * @private {!Array */ addableMetrics_: {type: Array}, /** * Label in the add-series dropdown. * @private {string} */ addSeriesLabel_: {type: String, computed: 'computeAddSeriesLabel_(addableMetrics_)'}, }, observers: [ 'setAddableMetrics_(selectableMetrics_, selectedMetrics_)', // Since array mutation does not trigger the compute method above, set a // separate observer for mutation. 'updateAddableMetrics_(selectedMetrics_.splices)', ], /** * @param {?Object} selection Key value pairs in the selection object specify * the data point to highlight in the charts. If null, clear existing * selection. */ highlight: function(selection) { if (selection) { this.highlightSelection_(selection, false); } else { this.clearSelection_(false); } }, /** * Internal implementation of model selection. * @param {!Object} selection * @param {boolean} fireEvent Whether to fire a model selection event from the * component. * @private */ highlightSelection_: function(selection, fireEvent) { const targetModelId = selection[this.provider.getModelColumnName()]; const targetDataVersion = selection[this.provider.getDataColumnName()]; const rowMatchingModel = []; this.provider.getModelIds().forEach((modelId, index) => { if (modelId == targetModelId) { rowMatchingModel.push(index); } }); this.selectedMetrics_.forEach((metric) => { const row = rowMatchingModel.filter((rowId) => { const config = this.provider.getEvalConfig(rowId); return config && config.data == targetDataVersion; }); if (row.length == 1) { const chart = this.getChartForMetric_(metric); if (chart) { chart.select({row: row[0]}); } } }); if (fireEvent) { this.fire(tfma.Event.SELECT, selection); } }, /** * Internal implementation of clearing model selection. * @param {boolean} fireEvent Whether to fire a model selection event from the * component. * @private */ clearSelection_: function(fireEvent) { this.selectedMetrics_.forEach((metric) => { const chart = this.getChartForMetric_(metric); if (chart != null) { chart.clearSelection(); } }); if (fireEvent) { this.fire(tfma.Event.CLEAR_SELECTION); } }, /** * Closes a line chart. * @param {!Event} e * @private */ closeLineChart_: function(e) { const item = e['model']['item']; const index = item && this.selectedMetrics_.indexOf(item); if (index >= 0) { this.splice('selectedMetrics_', index, 1); } }, /** * Computes the chart data for the named metric. * @param {string} metric * @return {!Array */ computeChartData_: function(metric) { const lineChartData = this.provider.getLineChartData(metric); return [ [ {'label': this.provider.getDataColumnName(), 'type': 'number'}, {'role': 'annotation', 'type': 'string'}, {'role': 'annotationText', 'type': 'string'}, {'label': metric, 'type': 'number'} ]].concat(lineChartData ); }, /** * Computes the addable metrics, which are (all) metrics excluding the * selectedMetrics. * @param {!Array metrics * @param {!Array selectedMetrics * @private */ setAddableMetrics_: function(metrics, selectedMetrics) { this.addableMetrics_ = metrics.filter(metric => selectedMetrics.indexOf(metric) == -1); // Unselect since the list is of addable metrics is being changed. this.selectedMetric_ = ''; }, /** * Updates the addable metrics. * @private */ updateAddableMetrics_: function() { this.setAddableMetrics_(this.selectableMetrics_, this.selectedMetrics_); }, /** * Sets the add-series dropdown label message to a string reflecting the * number of remaining metrics that can be added. When all metrics are added, * the dropdown will not pop-out so it is necessary to have a hint presented. * @param {!Array addableMetrics_ * @return {string} The add series label. * @private */ computeAddSeriesLabel_: function(addableMetrics_) { return addableMetrics_.length ? 'Add metric series' : 'All metrics have been added'; }, /** * Observer for selectedMetric_ property. * @param {string} metric * @private */ selectedMetricChanged_: function(metric) { if (metric) { this.push('selectedMetrics_', metric); } }, /** * Determines selectable metrics by filtering out all blacklisted metrics from * available metrics. * @param {!Array metrics * @param {string} blacklist A comma separated string of metrics that should * be blacklisted. * @return {!Array */ computeSelectableMetrics_: function(metrics, blacklist) { const blacklisted = blacklist.split(','); return metrics.filter(metric => blacklisted.indexOf(metric) == -1); }, /** * Resets the selectedMetrics to the first available metric. This is expected * to only occur when the input data changes. * @private */ selectableMetricsChanged_: function() { // By default show the first available metric series. this.selectedMetrics_ = this.metrics.slice(0, 1); }, /** * Handler for select event from a line chart. * @param {!Event} e * @private */ onChartSelect_: function(e) { e.stopPropagation(); const config = this.provider.getEvalConfig(e.detail.point.row); if (config) { const selection = {}; selection[this.provider.getModelColumnName()] = config.model; selection[this.provider.getDataColumnName()] = config.data; this.highlightSelection_(selection, true); } }, /** * Handler for clear-selection event from any line chart. * @param {!Event} e * @private */ onChartClearSelection_: function(e) { e.stopPropagation(); this.clearSelection_(true); }, /** * @param {string} metric * @return {?Element} The chart for the named metric if availale. * @private */ getChartForMetric_: function(metric) { return this.$$('tfma-line-chart[metric="' + metric + '"]'); }, });
javascript
23
0.629684
89
27.251724
290
starcoderdata
func TestECBCipher(t *testing.T) { inPart := bytes.Replace( []byte( "df4797bef68491542a6963b58bac773d¤51afcde9f56a132096c0496cc95eb24b¤3¤3135556¤5¤"), []byte("¤"), []byte{164}, -1, ) tt := []struct { name string key []byte in []byte out string }{ { name: "Check Cipher output", key: []byte("jo6aey6haid2Teih"), in: []byte("abc"), out: "90a14c0c4d0104397e5590415b7be2db", // answer got from nodejs }, { name: "Check Cipher output", key: []byte("jo6aey6haid2Teih"), in: []byte("hellow World!"), out: "598ad60562de8421a8223645a44e733e", // asnwer got from nodejs }, { name: "Check Cipher output", key: []byte("jo6aey6haid2Teih"), in: inPart, out: finAnswer, // asnwer got from nodejs }, } for _, tc := range tt { t.Run(tc.name, func(t *testing.T) { input := Pad(tc.in) // Test the Pad function if len(input)%aes.BlockSize != 0 { t.Error("Input size is not multiple of block size") } block, err := aes.NewCipher(tc.key) ErrChecker(t, "Key Error", err) ciphertext := make([]byte, len(input)) mode := NewECBEncrypter(block) mode.CryptBlocks(ciphertext, input) Equals(t, fmt.Sprintf("%x", ciphertext), tc.out) }) } }
go
16
0.617932
85
22.826923
52
inline
package com.jkurapati.grocery.api.constants; import javax.inject.Singleton; @Singleton public class Constants { public String version() { return "0.01"; } }
java
5
0.748276
114
25.363636
11
starcoderdata
import React from 'react' import { Container, Heading } from '@chakra-ui/react' import { Section } from '../Section' import { Paragraph } from '../Paragraph' export function AboutMe() { return ( <Container display="flex" justifyContent="left" alignItems="center"> <Section delay={0.1}> <Heading as="h3" variant="section-title"> About me 18 years old, I&apos;m currently second year college student studying computer science, very passionate about coding in general, I find the idea of turning lines of code into very beautiful things very charming. And whenever possible, I also apply my passion for developing Side Projects with Node.js and Modern Javascript Library and Frameworks like React.js and Next.js. ) }
javascript
12
0.653718
79
36.541667
24
starcoderdata
package org.chronopolis.common.transfer; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.file.Path; import java.nio.file.Paths; /** * * Created by shake on 10/21/16. */ public class RSyncTransferTest { @Rule public final ExpectedException exception = ExpectedException.none(); private final Path local = Paths.get(""); @Test public void lastRemote() { String link = " RSyncTransfer xfer = new RSyncTransfer(link, local); String last = xfer.last(); Assert.assertEquals("folder", last); } @Test public void lastRemoteNoSlash() { String link = " RSyncTransfer xfer = new RSyncTransfer(link, local); String last = xfer.last(); Assert.assertEquals("folder", last); } @Test public void lastLocal() { String link = "/path/to/folder"; RSyncTransfer xfer = new RSyncTransfer(link, local); String last = xfer.last(); Assert.assertEquals("folder", last); } @Test public void lastLocalNoSlash() { String link = "folder"; RSyncTransfer xfer = new RSyncTransfer(link, local); String last = xfer.last(); Assert.assertEquals("folder", last); } @Test public void lastEmpty() { String link = ""; RSyncTransfer xfer = new RSyncTransfer(link, local); exception.expect(IllegalArgumentException.class); xfer.last(); } @Test public void lastRemoteEmpty() { String link = " RSyncTransfer xfer = new RSyncTransfer(link, local); exception.expect(IllegalArgumentException.class); xfer.last(); } @Test public void lastLocalEmpty() { String link = ""; RSyncTransfer xfer = new RSyncTransfer(link, local); exception.expect(IllegalArgumentException.class); xfer.last(); } @Test public void lastNull() { RSyncTransfer xfer = new RSyncTransfer(null, local); exception.expect(IllegalArgumentException.class); xfer.last(); } }
java
9
0.622727
72
23.730337
89
starcoderdata
def GP2D120Calibrate(self, calData, unitsG='adc', unitsR='mm'): """ Calibrate the GP2D120 sensor with the given real-world data to find the best fit slope m and y-intercept b values to the linearized function provided by Sharp: m*ADC + b = 1/(R + k), k = 4.2. Solving for the distance, the integer linear function is: R = m_prime / (ADC + b_prime) - k_prime where m_prime = int(1/m), b_prime = int(b/m) k_prime = int(k). Parameters: calData - list of calibration data points [(G1,R1), (G2,R2) ...] where Gn is the GP2D120() output and Rn is the distance. unitsG - units of GP2D120() output. Supported values are: 'adc' = Analog to Digital Converter bits (default) 'volts' = volts DC unitsR - units of distance R. Supported values are: 'mm' = millimeters (default) 'cm' = centimeters 'in' = inches Return Value: Returns m_prime, b_prime """ if not calData: raise ValueError("Parameter 'calData' not specified or is empty") if len(calData) < 2: raise ValueError("Parameter 'calData' must have at least 2 data points") if unitsG == 'adc': scaleG = None elif unitsG == 'volts': scaleG = KheCmdBase.KheAdcBpv # bits/volt else: raise ValueError("Parameter 'unitsG' value is unknown: %s" \ % (repr(unitsG))) if unitsR == 'mm': scaleR = None elif unitsR == 'cm': scaleR = 10.0 elif unitsR == 'in': scaleR = 25.4 else: raise ValueError("Parameter 'unitsR' value is unknown: %s" \ % (repr(unitsR))) # linearize data calLinData = [] for pt in calData: g = pt[0] if scaleG: g *= scaleG r = pt[1] if scaleR: r *= scaleR if r >= GP2D120DistMin and r <= GP2D120DistMax and \ g >= 0 and g <= KheCmdBase.KheAdcMax: calLinData += [(g, 1.0/(r + GP2D120_k))] if len(calLinData) < 2: raise ValueError( "Calibration data must have 2 or more data points in range") # new calibration data self.mCalData = calData self.mUnitsG = unitsG self.mUnitsR = unitsR # linear regression fit new coeficients m, b = self._Fit(calLinData) m_prime = int(1.0 / m) b_prime = int(b / m) return m_prime, b_prime
python
14
0.556722
78
37.123077
65
inline
package wusc.edu.pay.web.portal.action.merchant; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import wusc.edu.pay.common.enums.PublicStatusEnum; import wusc.edu.pay.common.page.PageParam; import wusc.edu.pay.common.utils.export.DataField; import wusc.edu.pay.common.utils.export.ExportDataSource; import wusc.edu.pay.common.utils.export.excel.ExcelDataExportor; import wusc.edu.pay.common.utils.export.excel.MODE; import wusc.edu.pay.common.utils.number.AmountUtil; import wusc.edu.pay.common.utils.validate.ValidateUtils; import wusc.edu.pay.common.web.annotation.Permission; import wusc.edu.pay.facade.account.entity.Account; import wusc.edu.pay.facade.account.entity.AccountHistory; import wusc.edu.pay.facade.account.enums.AccountStatusEnum; import wusc.edu.pay.facade.account.enums.AccountTradeTypeEnum; import wusc.edu.pay.facade.limit.entity.BizFunctionSwitch; import wusc.edu.pay.facade.limit.enums.LimitTrxTypeEnum; import wusc.edu.pay.facade.limit.service.BizFunctionSwitchFacade; import wusc.edu.pay.web.portal.base.MerchantLogonAction; /** * 账户 * * @author liliqiong * @date 2013-11-4 * @version 1.0 */ @Scope("prototype") public class AccountAction extends MerchantLogonAction { private static final long serialVersionUID = 1L; private static final Log LOG = LogFactory.getLog(AccountAction.class); @Autowired private BizFunctionSwitchFacade bizFunctionSwitchFacade; /** * 我的帐户 * * @return */ @SuppressWarnings("rawtypes") public String viewAccount() { // 1.判断该商户支持的业务 Integer transferStatus = 0;// 转账业务状态 Integer rechargeStatus = 0;// 充值业务状态 List bizs = bizFunctionSwitchFacade.getBizFunctionSwitchByMerchantNo(super.getCurrentUserInfo().getUserNo()); for (Iterator iterator = bizs.iterator(); iterator.hasNext();) { BizFunctionSwitch bizFunctionSwitch = (BizFunctionSwitch) iterator.next(); if (bizFunctionSwitch.getBizFunction().equals(LimitTrxTypeEnum.ACCOUNT_DEPOSIT.name())) {// rechargeStatus = 100; } if (bizFunctionSwitch.getBizFunction().equals(LimitTrxTypeEnum.ACCOUNT_TRANSFER.name())) {// transferStatus = 100; } } // 2.得到账户信息 Account account = getAccount(); // 3.获取积分 putData("loginScore", this.getScore().getLoginScore()); // 积分 // 4.查看公告(POS商户) /* * if (getCurrentUser().getUserType().intValue() == * AccountTypeEnum.POS.getValue()) { Map<String, Object> paramMap = new * HashMap<String, Object>(); paramMap.put("type", * ArticleTypeEnum.NOTICE.getValue()); paramMap.put("status", * PublicStatusEnum.ACTIVE.getValue()); paramMap.put("articleType", * AccountTypeEnum.POS.getValue()); pageBean = * articleFacade.listPage(getPageParam(), paramMap); pushData(pageBean); * } */ // 5.把页面中需要的参数放入request域中 putData("AccountStatusEnumList", AccountStatusEnum.values());// 账户状态 /* * 在可用账户余额显示时,要对余额精度进行处理,大于两位小数的不能四舍五入,而是直接舍弃两位以后的小数(如100.0098,显示时为100.0, * 不能显示为100.01,否则提现时会出问题) 注意,此用法也不能直接加要account实体的get方法中,否则有可能造成账户余额错误. */ putData("availableBalance", AmountUtil.roundDown(account.getAvailableBalance())); // 账户可用余额 putData("account", account);// 账户信息 putData("transferStatus", transferStatus);// 转账业务状态 putData("rechargeStatus", rechargeStatus);// 充值业务状态 putData("userInfo", getCurrentUserInfo()); putData("PublicStatusEnum", PublicStatusEnum.toMap()); return "viewAccount"; } /** * 财务明细查询 * * @return */ @Permission("Account:History:List") public String listAccountHistory() { // 1.获取页面查询参数 String beginDate = getString("beginDate"); String endDate = getString("endDate"); String trxType = getString("trxType");// 业务类型 String fundDirection = getString("fundDirection");// 资金变动方向 String requestNo = getString("requestNo"); // 回显示查询条件 super.pushData(this.getParamMap()); super.putData("trxTypeList", AccountTradeTypeEnum.toList()); super.pageBean = this.queryAccountHistoryListPage(getPageParam(), beginDate, endDate, fundDirection, requestNo, trxType); super.pushData(pageBean); return "listAccountHistory"; } /** * 导出EXCEL */ @Permission("Account:History:List") public void exportExcel() { try { final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String filename = "Account_" + sdf.format(new Date()); String fileName = filename + ".xls"; // 解决导出文件的文件名乱码问题 String name = new String(fileName.getBytes("ISO-8859-1"), "UTF-8"); this.getHttpResponse().setHeader("Content-disposition", "attachment; filename=" + name); OutputStream os = getHttpResponse().getOutputStream(); DataField[] dataFields = new DataField[6]; dataFields[0] = new DataField("序号", "no"); dataFields[1] = new DataField("交易日期", "createTime"); dataFields[2] = new DataField("交易流水号", "requestNo"); dataFields[3] = new DataField("交易金额", "amount"); dataFields[4] = new DataField("账户余额", "balance"); dataFields[5] = new DataField("交易类型", "trxType"); final String beginDate = getString("beginDate"); final String endDate = getString("endDate"); final String trxType = getString("trxType");// 业务类型 final String fundDirection = getString("fundDirection");// 资金变动方向 final String requestNo = getString("requestNo"); PageParam pageParam = new PageParam(1, 5000); pageBean = this.queryAccountHistoryListPage(pageParam, beginDate, endDate, fundDirection, requestNo, trxType); new ExcelDataExportor new ExportDataSource { // DecimalFormat df = new DecimalFormat("#0.00"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public List getData() { List list = pageBean.getRecordList(); List<Map<String, Object>> lists = new ArrayList<Map<String, Object>>(); if (list != null && !list.isEmpty()) { int temp = 0; for (int i = 0; i < list.size(); i++) { Map<String, Object> mapParam = new HashMap<String, Object>(); AccountHistory accountHistory = (AccountHistory) list.get(i); mapParam.put("no", ++temp); mapParam.put("createTime", ValidateUtils.isEmpty(accountHistory.getCreateTime()) ? "" : sdf.format(accountHistory.getCreateTime())); mapParam.put("requestNo", accountHistory.getRequestNo()); if (123 == accountHistory.getFundDirection()) { mapParam.put("amount", "+" + accountHistory.getAmount()); } else { mapParam.put("amount", "-" + accountHistory.getAmount()); } mapParam.put("balance", accountHistory.getBalance()); mapParam.put( "trxType", ValidateUtils.isEmpty(accountHistory.getTrxType()) ? "" : AccountTradeTypeEnum.getEnum( accountHistory.getTrxType()).getDesc()); lists.add(mapParam); } } return lists; } }, os, MODE.EXCEL).export(); } catch (UnsupportedEncodingException e) { LOG.error("exportExcel fail:", e); } catch (IOException e) { LOG.error("exportExcel fail:", e); } } }
java
26
0.697541
130
35.871921
203
starcoderdata
<?php declare(strict_types = 1); namespace CodelyTv\Mooc\VideoHighlight\Domain; use CodelyTv\Shared\Domain\ValueObject\StringValueObject; final class VideoHighlightMessage extends StringValueObject { }
php
6
0.815385
59
20.666667
12
starcoderdata
/* * Copyright 2020 Haulmont. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.jmix.ui.widget.client.responsivegridlayout; import com.google.gwt.json.client.JSONObject; import com.google.gwt.json.client.JSONParser; import com.google.gwt.user.client.ui.Widget; import com.vaadin.client.ComponentConnector; import com.vaadin.client.ConnectorHierarchyChangeEvent; import com.vaadin.client.communication.StateChangeEvent; import com.vaadin.client.ui.AbstractHasComponentsConnector; import com.vaadin.shared.ui.Connect; import io.jmix.ui.widget.JmixResponsiveGridLayout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; @Connect(JmixResponsiveGridLayout.class) public class JmixResponsiveGridLayoutConnector extends AbstractHasComponentsConnector { protected List containerStyles = new ArrayList<>(); protected boolean layoutUpdated; @Override public JmixResponsiveGridLayoutWidget getWidget() { return (JmixResponsiveGridLayoutWidget) super.getWidget(); } @Override public JmixResponsiveGridLayoutState getState() { return (JmixResponsiveGridLayoutState) super.getState(); } @Override protected void init() { super.init(); getWidget().client = getConnection(); } @Override public void onConnectorHierarchyChange(ConnectorHierarchyChangeEvent event) { JmixResponsiveGridLayoutWidget layout = getWidget(); updateWidgetLayout(); for (ComponentConnector child : getChildComponents()) { String location = getState().childLocations.get(child); try { getWidget().setWidget(child.getWidget(), location); } catch (final IllegalArgumentException e) { // If no location is found, this component is not visible getLogger().warn("Child not rendered as no slot with id '" + location + "' has been defined"); } } for (ComponentConnector oldChild : event.getOldChildren()) { if (oldChild.getParent() == this) { continue; } Widget oldChildWidget = oldChild.getWidget(); if (oldChildWidget.isAttached()) { layout.remove(oldChildWidget); } } } @Override public void updateCaption(ComponentConnector connector) { getWidget().updateCaption(connector); } @Override public void onStateChanged(StateChangeEvent stateChangeEvent) { super.onStateChanged(stateChangeEvent); if (stateChangeEvent.hasPropertyChanged("configuration")) { updateWidgetLayout(); } } protected void updateWidgetLayout() { if (layoutUpdated) { return; } JSONObject confObject = JSONParser.parseStrict(getState().configuration).isObject(); // Remove all old stylenames for (String oldStyle : containerStyles) { setWidgetStyleName(oldStyle, false); } containerStyles.clear(); if (confObject.containsKey("style")) { String containerStyle = confObject.get("style").isString().stringValue(); String[] newStyles = containerStyle.split(" "); for (String newStyle : newStyles) { setWidgetStyleName(newStyle, true); containerStyles.add(newStyle); } } getWidget().generateLayout(confObject); layoutUpdated = true; } private static Logger getLogger() { return LoggerFactory.getLogger(JmixResponsiveGridLayoutConnector.class); } }
java
16
0.675824
154
31.842105
133
starcoderdata
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using ScaffoldView.Models; namespace ScaffoldView.Data { public class ScaffoldViewContext : DbContext { public ScaffoldViewContext(DbContextOptions options) : base(options) { } public DbSet Account { get; set; } } }
c#
10
0.705479
81
22.105263
19
starcoderdata
package com.aditya.personal.algorithmproblems.leetCode; public class M_934_ShortestBridge { public int shortestBridge(int[][] A) { int[] island = findIsland(A); if (island == null) return -1; return findIncrement(A, island[0], island[1], 1); } private int[] findIsland(int[][] A) { for (int i = 0; i < A.length; i++) { for (int j = 0; j < A[i].length; j++) { if (A[i][j] != 1) continue; // upper bound if (i > 0 && A[i - 1][j] == 1) continue; // lower bound if (i < A.length - 1 && A[i + 1][j] == 1) continue; // left bound if (j > 0 && A[i][j - 1] == 1) continue; // right bound if (j < A[i].length - 1 && A[i][j + 1] == 1) continue; return new int[]{i, j}; } } return null; } private int findIncrement(int[][] matrix, int cRow, int cColumn, int inc) { // meaning inbound bottom & found land if (cRow + inc < matrix.length && matrix[cRow + inc][cColumn] == 1) return inc; // meaning inbound top & found land if (cRow - inc >= 0 && matrix[cRow - inc][cColumn] == 1) return inc; // meaning inbound right & found land if (cColumn + inc < matrix[cRow].length && matrix[cRow][cColumn + inc] == 1) return inc; // meaning inbound left & found land if (cColumn - inc >= 0 && matrix[cRow][cColumn - inc] == 1) return inc; if (cRow + inc + 1 >= matrix.length && cRow - inc - 1 < 0 && cColumn + inc + 1 >= matrix[cRow].length && cColumn - inc - 1 < 0) return 1000; // sink current matrix[cRow][cColumn] = 0; return findIncrement(matrix, cRow, cColumn, inc + 1); } public static void main(String[] args) { M_934_ShortestBridge instance = new M_934_ShortestBridge(); int[][] inp1 = new int[][]{{0, 1}, {1, 0}}; System.out.println(instance.shortestBridge(inp1)); /* [[1,1,1,1,1], [1,0,0,0,1], [1,0,0,0,1], [1,0,1,0,1], [1,0,0,0,1], [1,0,0,0,1], [1,1,1,1,1]] [[0,1], [1,0]] */ } }
java
16
0.445132
84
24.515789
95
starcoderdata
#pragma warning disable CC0061 // Asynchronous method can be terminated with the 'Async' keyword. using System; using System.IO; using System.Threading; using System.Threading.Tasks; using NUnit.Framework; using Tests.Helpers; namespace Tests.SystemTests.IOTests { [TestFixture] public static class StreamExtensionsTest { [Test] public static void ReadAsyncReads() { ReadAsyncReadsExtracted().Wait(); } [Test] public static void ReadAsyncThrowsOnCanceledToken() { var stream = new MemoryStream[1]; using (stream[0] = new MemoryStream(new byte[50])) { var tokenSource = new CancellationTokenSource[1]; using (tokenSource[0] = new CancellationTokenSource()) { tokenSource[0].Cancel(); var buffer = new byte[10]; AssertEx.AsyncThrows => stream[0].ReadAsync(buffer, 0, 10, tokenSource[0].Token)); } } } [Test] public static void WriteAsyncThrowsOnCanceledToken() { var stream = new MemoryStream[1]; using (stream[0] = new MemoryStream(new byte[50])) { var tokenSource = new CancellationTokenSource[1]; using (tokenSource[0] = new CancellationTokenSource()) { tokenSource[0].Cancel(); var buffer = new byte[10]; AssertEx.AsyncThrows => stream[0].ReadAsync(buffer, 0, 10, tokenSource[0].Token)); } } } private static async Task ReadAsyncReadsExtracted() { // ReSharper disable once UseAwaitUsing using (var stream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 })) { var buffer = new byte[10]; var x = await stream.ReadAsync(buffer, 0, 10).ConfigureAwait(false); Assert.AreEqual(10, x); AssertEx.CollectionEquals(buffer, new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }); } } } }
c#
23
0.535436
154
34.615385
65
starcoderdata
using System.Collections.Generic; using System.Linq; using BattleTech; using BattleTech.UI; using Harmony; using UnityEngine; using static Logger; public class Patches { [HarmonyPatch(typeof(CombatHUDWeaponPanel), "Update")] public class CombatHUDWeaponPanel_Update_Patch { private static bool energyState; private static bool ballisticState; private static bool missileState; private static bool supportState; private static bool closeRangeState; private static bool standardRangeState; private static bool longRangeState; private static bool veryLongRangeState; private static bool extremeRangeState; public static void Postfix(CombatHUDWeaponPanel __instance, List ___WeaponSlots, List ___sortedWeaponsList) { foreach (var weapon in ___sortedWeaponsList) { LogDebug($"{weapon.UIName}: {weapon.RangeDescription}"); } var hotkeyF1 = Input.GetKeyDown(KeyCode.F1); if (hotkeyF1) { switch (ballisticState) { case true: ___sortedWeaponsList.Where(w => w.Category == WeaponCategory.Ballistic).Do(w => w.DisableWeapon()); break; case false: ___sortedWeaponsList.Where(w => w.Category == WeaponCategory.Ballistic).Do(w => w.EnableWeapon()); break; } __instance.RefreshDisplayedWeapons(); ballisticState = !ballisticState; } var hotkeyF2 = Input.GetKeyDown(KeyCode.F2); if (hotkeyF2) { switch (energyState) { case true: ___sortedWeaponsList.Where(w => w.Category == WeaponCategory.Energy).Do(w => w.DisableWeapon()); break; case false: ___sortedWeaponsList.Where(w => w.Category == WeaponCategory.Energy).Do(w => w.EnableWeapon()); break; } __instance.RefreshDisplayedWeapons(); energyState = !energyState; } var hotkeyF3 = Input.GetKeyDown(KeyCode.F3); if (hotkeyF3) { switch (missileState) { case true: ___sortedWeaponsList.Where(w => w.Category == WeaponCategory.Missile).Do(w => w.DisableWeapon()); break; case false: ___sortedWeaponsList.Where(w => w.Category == WeaponCategory.Missile).Do(w => w.EnableWeapon()); break; } __instance.RefreshDisplayedWeapons(); missileState = !missileState; } var hotkeyF4 = Input.GetKeyDown(KeyCode.F4); if (hotkeyF4) { switch (supportState) { case true: ___sortedWeaponsList.Where(w => w.Category == WeaponCategory.AntiPersonnel).Do(w => w.DisableWeapon()); break; case false: ___sortedWeaponsList.Where(w => w.Category == WeaponCategory.AntiPersonnel).Do(w => w.EnableWeapon()); break; } __instance.RefreshDisplayedWeapons(); supportState = !supportState; } var hotkeyF5 = Core.ModSettings.enableRangeSettings && Input.GetKeyDown(KeyCode.F5); if (hotkeyF5) { switch (closeRangeState) { case true: ___sortedWeaponsList.Where(w => w.RangeDescription == "Close").Do(w => w.DisableWeapon()); break; case false: ___sortedWeaponsList.Where(w => w.RangeDescription == "Close").Do(w => w.EnableWeapon()); break; } __instance.RefreshDisplayedWeapons(); closeRangeState = !closeRangeState; } var hotkeyF6 = Core.ModSettings.enableRangeSettings && Input.GetKeyDown(KeyCode.F6); if (hotkeyF6) { switch (standardRangeState) { case true: ___sortedWeaponsList.Where(w => w.RangeDescription == "Standard").Do(w => w.DisableWeapon()); break; case false: ___sortedWeaponsList.Where(w => w.RangeDescription == "Standard").Do(w => w.EnableWeapon()); break; } __instance.RefreshDisplayedWeapons(); standardRangeState = !standardRangeState; } var hotkeyF7 = Core.ModSettings.enableRangeSettings && Input.GetKeyDown(KeyCode.F7); if (hotkeyF7) { switch (longRangeState) { case true: ___sortedWeaponsList.Where(w => w.RangeDescription == "Very Long").Do(w => w.DisableWeapon()); break; case false: ___sortedWeaponsList.Where(w => w.RangeDescription == "Very Long").Do(w => w.EnableWeapon()); break; } __instance.RefreshDisplayedWeapons(); longRangeState = !longRangeState; } var hotkeyF8 = Core.ModSettings.enableRangeSettings && Input.GetKeyDown(KeyCode.F8); if (hotkeyF8) { switch (veryLongRangeState) { case true: ___sortedWeaponsList.Where(w => w.RangeDescription == "Very Long").Do(w => w.DisableWeapon()); break; case false: ___sortedWeaponsList.Where(w => w.RangeDescription == "Very Long").Do(w => w.EnableWeapon()); break; } __instance.RefreshDisplayedWeapons(); veryLongRangeState = !veryLongRangeState; } var hotkeyF9 = Core.ModSettings.enableRangeSettings && Input.GetKeyDown(KeyCode.F9); if (hotkeyF9) { switch (extremeRangeState) { case true: ___sortedWeaponsList.Where(w => w.RangeDescription == "Extreme").Do(w => w.DisableWeapon()); break; case false: ___sortedWeaponsList.Where(w => w.RangeDescription == "Extreme").Do(w => w.EnableWeapon()); break; } __instance.RefreshDisplayedWeapons(); extremeRangeState = !extremeRangeState; } } } }
c#
21
0.482175
144
37.67027
185
starcoderdata
package com.bignerdranch.android.notifytest; import android.content.Context; import android.graphics.Color; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; 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.TextView; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class MainActivity extends AppCompatActivity { private List mItems; private TextAdapter mTextAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView); mItems = new ArrayList<>(Arrays.asList("#FF0000", "#00FF00", "#0000FF", "#FFFF00", "#00FFFF")); mTextAdapter = new TextAdapter(this, mItems, new View.OnClickListener() { @Override public void onClick(View v) { if (mItems.size() > 2) { mItems.add(1, "#FF00FF"); mTextAdapter.notifyItemInserted(1); mItems.subList(2, 6).clear(); mTextAdapter.notifyItemRangeRemoved(2, 4); } else { mItems.remove(1); mItems.addAll(Arrays.asList("#00FF00", "#0000FF", "#FFFF00", "#00FFFF")); mTextAdapter.notifyDataSetChanged(); } } }); recyclerView.setAdapter(mTextAdapter); recyclerView.setLayoutManager(new LinearLayoutManager(this)); } private class TextAdapter extends RecyclerView.Adapter { private LayoutInflater mLayoutInflater; private List mStringList; private View.OnClickListener mOnClickListener; public TextAdapter(Context context, List stringList, View.OnClickListener onClickListener) { mLayoutInflater = LayoutInflater.from(context);; mStringList = stringList; mOnClickListener = onClickListener; } @Override public TextAdapter.TextViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = mLayoutInflater.inflate(R.layout.text_item_view, parent, false); view.setOnClickListener(mOnClickListener); return new TextViewHolder(view); } @Override public void onBindViewHolder(TextAdapter.TextViewHolder holder, int position) { holder.bindText(mStringList.get(position)); } @Override public int getItemCount() { return mStringList.size(); } public class TextViewHolder extends RecyclerView.ViewHolder { private TextView mTextView; public TextViewHolder(View itemView) { super(itemView); mTextView = (TextView) itemView; } public void bindText(String text) { mTextView.setText(text); mTextView.setBackgroundColor(Color.parseColor(text)); } } } }
java
21
0.638763
108
33.705263
95
starcoderdata
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _Location = _interopRequireDefault(require("../controllers/Location")); var _validateRequestBody = require("../middlewares/validateRequestBody"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var createLocation = _Location.default.createLocation, updateLocation = _Location.default.updateLocation, fetchAllLocations = _Location.default.fetchAllLocations, fetchALocation = _Location.default.fetchALocation, deleteLocation = _Location.default.deleteLocation; var _default = function _default(app) { app.route('/api/v1/location').post(_validateRequestBody.validateLocationCreation, createLocation).get(fetchAllLocations); app.route('/api/v1/location/:id').put(_validateRequestBody.validateUpdateLocation, updateLocation).delete(deleteLocation).get(fetchALocation); }; exports.default = _default;
javascript
18
0.762626
144
37.115385
26
starcoderdata
// Copyright 2020 Hal@shurabaP. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package utau import ( "errors" "strconv" "strings" ) // Phoneme represents one piece of wave file that contains voice. type Phoneme struct { Filename string `json:"filename"` Alias string `json:"alias"` LeftBlank float64 `json:"left_blank"` Consonant float64 `json:"consonant"` RightBlank float64 `json:"right_blank"` PreUtterance float64 `json:"pre_utterance"` Overlap float64 `json:"overlap"` } // Phonemes represents a single oto.ini in UTAU library. type Phonemes []*Phoneme // NewPhonemesFromText creates Phonemes from a single oto.ini. func NewPhonemesFromText(t string) (*Phonemes, error) { res := Phonemes{} for _, l := range strings.Split(t, "\n") { p, err := NewPhonemeFromLine(l) if err != nil { // Log here if you want. continue } res = append(res, p) } return &res, nil } // NewPhonemeFromLine creates Phoneme from a single line in a single oto.ini. func NewPhonemeFromLine(l string) (*Phoneme, error) { es := strings.Split(l, ",") if len(es) != 6 { return nil, errors.New("The given line does not contain 6 elements; `" + l + "`") } if !strings.Contains(es[0], "=") { return nil, errors.New("The given line does not contain alias; `" + es[0] + "`") } fa := strings.Split(es[0], "=") if len(fa) != 2 { return nil, errors.New("The given line does not contain valid alias; `" + es[0] + "`") } r1, r2, r3, r4, r5, err := parse(es) if err != nil { return nil, err } return &Phoneme{ Filename: fa[0], Alias: fa[1], LeftBlank: r1, Consonant: r2, RightBlank: r3, PreUtterance: r4, Overlap: r5, }, nil } func parse(es []string) (float64, float64, float64, float64, float64, error) { r1, err := strconv.ParseFloat(es[1], 64) if err != nil { return 0, 0, 0, 0, 0, err } r2, err := strconv.ParseFloat(es[2], 64) if err != nil { return r1, 0, 0, 0, 0, err } r3, err := strconv.ParseFloat(es[3], 64) if err != nil { return r1, r2, 0, 0, 0, err } r4, err := strconv.ParseFloat(es[4], 64) if err != nil { return r1, r2, r3, 0, 0, err } r5, err := strconv.ParseFloat(es[5], 64) if err != nil { return r1, r2, r3, r4, 0, err } return r1, r2, r3, r4, r5, nil } type phonemesFactory interface { New(string) (*Phonemes, error) } type phonemesFactoryDefault struct { } func (pf phonemesFactoryDefault) New(filename string) (*Phonemes, error) { return NewPhonemesFromText(filename) } // PhonemesReader reads Phonemes from the file on file system. type PhonemesReader interface { Read(string) (*Phonemes, error) } // PhonemesReaderDefault is a default PhonemeReader. type PhonemesReaderDefault struct { fr fileReader pf phonemesFactory } // NewPhonemesReader create PhonemesReader that uses file system as its source. func NewPhonemesReader() PhonemesReader { return PhonemesReaderDefault{ fr: fileReaderDefault{}, pf: phonemesFactoryDefault{}, } } func (pr PhonemesReaderDefault) Read(filename string) (*Phonemes, error) { t, err := pr.fr.Read(filename) if err != nil { return nil, err } return pr.pf.New(t) }
go
12
0.664918
88
23.930769
130
starcoderdata
export const NODE_ENV = process.env.NEXT_PUBLIC_NODE_ENV || "development"; //NOTE(amine): feature flags export const ACTIVITY_FEATURE_FLAG = NODE_ENV === "development" || NODE_ENV === "staging"; // NOTE(jim): External servers export const URI_SHOVEL = process.env.NEXT_PUBLIC_URI_SHOVEL; export const URI_FIJI = process.env.NEXT_PUBLIC_URI_FIJI; export const URI_LENS = process.env.NEXT_PUBLIC_URI_LENS; //NOTE(amine): Extensions links export const EXTENSION_CHROME = process.env.NEXT_PUBLIC_EXTENSION_CHROME; export const EXTENSION_FIREFOX = process.env.NEXT_PUBLIC_EXTENSION_FIREFOX; export const EXTENSION_SAFARI = process.env.NEXT_PUBLIC_EXTENSION_SAFARI;
javascript
7
0.767722
90
46.357143
14
starcoderdata
using NUnit.Framework; namespace HFM.Proteins { [TestFixture] public class ProteinProductionTests { [Test] public void ProteinProduction_EqualsProteinProduction_ReturnsTrue() { // Arrange var production = new ProteinProduction(1.0, 2.0, 3.0, 4.0); var other = production; // Act var result = production.Equals(other); // Assert Assert.IsTrue(result); Assert.AreEqual(production.GetHashCode(), other.GetHashCode()); Assert.IsTrue(production == other); Assert.IsFalse(production != other); } [Test] public void ProteinProduction_EqualsProteinProduction_ReturnsFalse() { // Arrange var production = new ProteinProduction(1.0, 2.0, 3.0, 4.0); var other = new ProteinProduction(2.0, 3.0, 4.0, 5.0); // Act var result = production.Equals(other); // Assert Assert.IsFalse(result); Assert.AreNotEqual(production.GetHashCode(), other.GetHashCode()); Assert.IsFalse(production == other); Assert.IsTrue(production != other); } [Test] public void ProteinProduction_EqualsObject_ReturnsTrue() { // Arrange var production = new ProteinProduction(1.0, 2.0, 3.0, 4.0); object other = production; // Act var result = production.Equals(other); // Assert Assert.IsTrue(result); } [Test] public void ProteinProduction_EqualsObject_ReturnsFalse() { // Arrange var production = new ProteinProduction(1.0, 2.0, 3.0, 4.0); object other = new ProteinProduction(2.0, 3.0, 4.0, 5.0); // Act var result = production.Equals(other); // Assert Assert.IsFalse(result); } } }
c#
14
0.537773
78
30.936508
63
starcoderdata
package com.alexanders.retrotest.api.services; import com.alexanders.retrotest.app.ClientAbstract; /** * @author astolnikov: 03.07.2018 */ public class BaseClient extends ClientAbstract { public BaseClient() { super(new ClientBuilder()); } }
java
9
0.717514
77
23.357143
14
starcoderdata
std::vector<Move> Piece::get_moves(const bool in_check_moves) const { // All moves of piece, whether valid or not. std::vector<Move> candidate_moves = get_candidate_moves(in_check_moves); // All valid moves of piece. std::vector<Move> moves; for (const Move &move : candidate_moves) { // If move destination is not in board, do not add to valid moves. if (!m_board->contains(move.get_dest())) { continue; } // If piece captures own color piece, do not add to valid moves. if (m_board->piece_at(move.get_dest()) != nullptr && m_board->piece_at(move.get_dest())->get_color() == m_color) { continue; } // If move puts board in check for color, do not add to valid moves. if (!in_check_moves) { Board candidate_board(*m_board); candidate_board.piece_at(m_coordinate)->move(move); if (candidate_board.in_check(m_color)) { continue; } } moves.push_back(move); } return moves; }
c++
15
0.605133
74
29.71875
32
inline
static void generate_msg_sender_implement(std::size_t lvl) { s_outf_converter.pf(lvl, R"senderfillheader( /// @sender constructor sender::sender(size_t reserve_header_size) : m_buf(&m_lbuf[reserve_header_size + LWS_PRE]) , m_pcur(m_buf) , m_pend(m_lbuf + sizeof(m_lbuf)) , m_doc(new rapidjson::Document()) {} /// @sender destructor sender::~sender() { delete (rapidjson::Document*)m_doc; } /// @sender reset void sender::__reset(mid_t mid) { m_pcur = m_buf; ((rapidjson::Document*)m_doc)->SetObject(); rapidjson::Document & doc = *(rapidjson::Document *)m_doc; doc.AddMember(s_id, s_mid_to_str[(%s)mid], doc.GetAllocator()); } /// @sender serialize void sender::__serialize() { out_wrapper buf((char *)m_pcur); rapidjson::Writer<out_wrapper> writer(buf); ((rapidjson::Document *)m_doc)->Accept(writer); m_pcur = (uint8_t *)buf.pcur; } )senderfillheader", s_mid_under_type); s_outf_converter.pf(lvl, "\n"); for (const auto & itr: s_export_order) { /// @todo maybe not struct const rapidjson::Value & val = *itr; const char * type_name = val.FindMember("name")->value.GetString(); s_outf_converter.pf(lvl, "void sender::convert(std::string & dst, const struct %s & src)\n", type_name); s_outf_converter.pf(lvl, "{\n"); s_outf_converter.pf(lvl+1, "rapidjson::Document & doc = *(rapidjson::Document*)m_doc;\n"); s_outf_converter.pf(lvl+1, "out_string_wrapper buf(dst);\n"); s_outf_converter.pf(lvl+1, "rapidjson::PrettyWriter<out_string_wrapper> writer(buf);\n"); s_outf_converter.pf(lvl+1, "c2json(doc, src).Accept(writer);\n"); s_outf_converter.pf(lvl, "}\n\n"); } s_outf_converter.pf(lvl, "/// messages packer wrapper\n"); for (const auto & itr: s_msg_order) { /// @todo maybe not struct const rapidjson::Value & val = *itr; const char * type_name = val.FindMember("name")->value.GetString(); s_outf_converter.pf(lvl, "void sender::__pack(const struct %s & val)\n", type_name); s_outf_converter.pf(lvl, "{\n"); s_outf_converter.pf(lvl+1, "rapidjson::Document & doc = *(rapidjson::Document *)m_doc;\n"); s_outf_converter.pf(lvl+1, "doc.AddMember(s_data, c2json(doc, val), doc.GetAllocator());\n"); s_outf_converter.pf(lvl, "}\n\n"); } }
c++
15
0.661195
106
33.28125
64
inline
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) class Discount: def __init__(self, customer, price): self.customer = customer self.price = price def get_discount(self): if self.customer == 'fav': return self.price * 0.2 if self.customer == 'vip': return self.price * 0.4 def main(): customer1, price1 = 'fav', 100 assert Discount(customer1, price1).get_discount() == 20.0 customer2, price2 = 'vip', 100 assert Discount(customer2, price2).get_discount() == 40.0 if __name__ == '__main__': main()
python
10
0.587366
66
23
31
starcoderdata
package org.cbioportal.genome_nexus.web.mixin; import com.fasterxml.jackson.annotation.JsonInclude; import io.swagger.annotations.ApiModelProperty; import org.cbioportal.genome_nexus.model.GenomicLocation; import org.cbioportal.genome_nexus.model.Hotspot; import java.util.List; @JsonInclude(JsonInclude.Include.NON_NULL) public class AggregatedHotspotsMixin { @ApiModelProperty(value = "Genomic Location", required = true) private GenomicLocation genomicLocation; @ApiModelProperty(value = "HGVS notation", required = true) private String variant; @ApiModelProperty(value = "Hotspots", required = true) private List<Hotspot> hotspots; }
java
9
0.785607
66
30.761905
21
research_code
package tickrecorder; import com.fxcore2.*; import redis.clients.jedis.*; public class TickRecorder{ private static JedisPool redisPool = new JedisPool(Config.redisIP, Config.redisPort); public static void main(String[] args){ O2GSession session = FXCMConnect(Config.FXCMUsername, Config.FXCMPassword, Config.FXCMHostsURL, Config.connectionType); //printPrices(session); try{ O2GTableManager tableManager = session.getTableManager(); O2GOffersTable offersTable = (O2GOffersTable)tableManager.getTable(O2GTableType.OFFERS); ResponseListener responseListener = new ResponseListener(session); session.subscribeResponse(responseListener); subscribeToPriceUpdates(offersTable); setupRedis(session); }catch(java.lang.NullPointerException ex){ System.out.println("Unable to connect. Most likely the servers are down for maintenance. "); System.exit(0); } while(true){ try{ Thread.sleep(50); }catch(InterruptedException e){} } } public static O2GSession FXCMConnect(String username, String password, String url, String type){ O2GSession mSession = O2GTransport.createSession(); MySessionStatusListener statusListener = new MySessionStatusListener(); mSession.subscribeSessionStatus(statusListener); TableManagerListener managerListener = new TableManagerListener(); mSession.useTableManager(O2GTableManagerMode.YES, managerListener); mSession.login(username, password, url, type); while (!statusListener.isConnected() && !statusListener.hasError()) { try{ Thread.sleep(50); }catch(InterruptedException e){} } return mSession; } public static void printPrices(O2GSession loggedInSession){ O2GTableManager tableManager = loggedInSession.getTableManager(); O2GOffersTable offersTable = (O2GOffersTable)tableManager.getTable(O2GTableType.OFFERS); O2GTableIterator iterator = new O2GTableIterator(); O2GOfferTableRow offerTableRow = offersTable.getNextRow(iterator); while (offerTableRow!=null) { System.out.println("Instrument = " + offerTableRow.getInstrument() + "; Bid = " + offerTableRow.getBid() + "; Ask = " + offerTableRow.getAsk()); offerTableRow = offersTable.getNextRow(iterator); } } private static void subscribeToPriceUpdates(O2GOffersTable offersTable){ TableListener tableListener = new TableListener(); offersTable.subscribeUpdate(O2GTableUpdateType.UPDATE, tableListener); } private Jedis getClient(JedisPool pool){ Jedis jedis = null; return pool.getResource(); } private static void setupRedis(O2GSession session){ try(Jedis client = redisPool.getResource()) { redisPubsubListener redisListener = new redisPubsubListener(session); client.subscribe(redisListener, "priceRequests"); }catch(redis.clients.jedis.exceptions.JedisConnectionException ex){ setupRedis(session); } } public static void redisPublish(String channel, String message){ Jedis client = null; //System.out.println("Sending redis message on " + channel + ": " + message); try{ client = redisPool.getResource(); client.publish(channel, message); }catch(redis.clients.jedis.exceptions.JedisConnectionException ex){ //try again. redisPublish(channel, message); }finally{ if(client != null){ client.close(); } } } }
java
17
0.644778
156
37.29703
101
starcoderdata
def main(): import sys # to get command line args import argparse # to parse options for us and print a nice help message import subprocess, os, sys, time # Add some necessary extras to blender's neutered python # Add anything from any existing full-fledged Python installation # because we need google.protobuf !!! paths = os.environ['Path'] paths = paths.split(';') for path in paths: if path.find('Python')!=-1: if path.find('Blender')==-1: sPath=path.split('\\') if sPath[-2].find('Python')!=-1: pypath = os.path.join(path,'Lib','site-packages') sys.path.append(pypath) # Add the current path of THIS file this_path = os.path.dirname(os.path.realpath(__file__)) sys.path.append(this_path) from BlenderVisitor import BlenderVisitor # get the args passed to blender after "--", all of which are ignored by # blender so scripts may receive their own arguments argv = sys.argv if "--" not in argv: argv = [] # as if no args are passed else: argv = argv[argv.index("--") + 1:] # get all args after "--" # When --help or no args are given, print this help usage_text = ( "Run blender in background mode to load a scene and export to fus:" " blender --background MyScene.blend --python " + __file__ + " -- [options]" ) parser = argparse.ArgumentParser(description=usage_text) # Example utility, add some text and renders or saves it (with options) # Possible types are: string, int, long, choice, float and complex. parser.add_argument( "-o", "--out", dest="fus_file", metavar='FILE', help="Destination path for the generated .fus file", ) args = parser.parse_args(argv) # In this example we won't use the args # if not argv: # parser.print_help() # return fus_file = '' if not args.fus_file: if not bpy.data.filepath: fus_file = 'untitled.fus' else: fus_file = os.path.splitext(bpy.data.filepath)[0] + '.fus' else: fus_file = args.fus_file # Run the exporter roots = set() for obj in bpy.data.objects: parent = GetParents(obj) roots.add(parent) try: roots.remove(None) except: pass #set blender to object mode and deselect everything (prevents problems) if bpy.context.mode != 'OBJECT' and bpy.ops.object.mode_set.poll(): bpy.ops.object.mode_set(mode="OBJECT") bpy.ops.object.select_all(action='DESELECT') visitor = BlenderVisitor() visitor.DoApplyModifiers = True visitor.DoApplyScale = True visitor.DoRecalcOutside = True visitor.TraverseList(roots) # visitor.PrintFus() visitor.WriteFus(fus_file) print("Exported Blender scene to FUSEE file: " + fus_file)
python
16
0.607009
85
30.956522
92
inline