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
import {EventEmitter} from "events"; import SearchDispatcher from "../dispatchers/SearchDispatcher"; class SearchStore extends EventEmitter{ constructor(){ super(); this.results = []; this.trends = []; } getTrends(){ return this.trends; } getResults(){ return this.results; } search(args){ //fetch config var options = { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ keywords: args.keywords, url: args.url }) }; //call NodeJS API for web scraping fetch('/api/scrape', options) .then(resp => resp.json()) .then(data => { // code for handling the data from the API console.log("fetch succesful, data:", data); let positions = ""; if (data && data.length > 0) { for (let i = 0; i < data.length; i++) { if (i > 0) { positions += ", " + data[i].position; } else positions += data[i].position; } } this.trends.push({ id: Date.now() + "", //rowId for table date: new Date().toLocaleString(), positions: positions, url: args.url, keywords: args.keywords }) //console.debug("this.trends:",this.trends); this.results = data; this.emit("Search_Complete"); }).catch(function (err) { // if the server returns any errors console.error(err); }); } handleActions(action){ console.log("SearchStore received an action:", action); switch(action.type){ case "SEARCH":{ this.search(action.args) } } } } const searchStore = new SearchStore; SearchDispatcher.register(searchStore.handleActions.bind(searchStore)); export default searchStore;
javascript
23
0.439076
71
29.922078
77
starcoderdata
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2017-03-15 09:27 from __future__ import unicode_literals from django.db import migrations, models sql_forward = """\ UPDATE snoop_document SET digested_at = snoop_digest.updated_at FROM snoop_digest WHERE snoop_document.id = snoop_digest.id """ sql_reverse = """\ UPDATE snoop_digest SET updated_at = snoop_document.digested_at FROM snoop_document WHERE snoop_digest.id = snoop_document.id """ class Migration(migrations.Migration): dependencies = [ ('snoop', '0010_auto_20161121_2007'), ] operations = [ migrations.AddField( model_name='document', name='digested_at', field=models.DateTimeField(blank=True, null=True), ), migrations.AlterIndexTogether( name='document', index_together=set([('collection', 'digested_at')]), ), migrations.RunSQL(sql_forward, sql_reverse), migrations.RemoveField( model_name='digest', name='updated_at', ), ]
python
14
0.610564
64
23.282609
46
starcoderdata
// ******************************************* /* Method5: selection.text(value) If a value is specified, sets the text content to the specified value on all selected elements, replacing any existing child elements. If the value is a constant, then all elements are given the same text content If the value is a function, it is evaluated for each selected element, in order, being passed the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]).The function’s return value is then used to set each element’s text content. A null value will clear the content. If a value is not specified, returns the text content for the first (non-null) element in the selection. This is generally useful only if you know the selection contains exactly one element. */ // ******************************************* // Case0: Select h1 and get the text of the element and then set the text value of the element using .text() let h1Ele = d3.select('h1'); console.log(h1Ele.text()); h1Ele.text('Text'); console.log(h1Ele.text()); h1Ele.text(null); // removes the text content h1Ele.text('Text'); // Case1: Select all the paras and set the text; try setting text on the div and notice that all child elements will be deleted const paras = d3.selectAll('p'); paras.text('D3'); const divParas = d3.select('.paras').text('Removed'); // Case2: Select all the circles and set the text const svgCircles = d3.select('.circles') .attr('width', '400') .attr('height', '400'); const circles = d3.selectAll('circle'); circles.filter((d, i, n) => { const d3Obj = d3.select(n[i]); d3Obj.attr('cx', `${100 + (i * 100)}`) .attr('cy', `${100 + (i * 100)}`) .attr('r', 70); }); circles.text('SVG Circle Element'); // Does not work, text cannot be added inside SVG elements unless the element is // Case3: Select all the texts and set the text content const content = ['D3', 'Is', 'Amazing!']; const svgTexts = d3.select('.texts') .attr('width', '300') .attr('height', '100'); const texts = d3.selectAll('text'); texts.text(function (d, i) { const d3Obj = d3.select(this); d3Obj.attr('x', '5') .attr('y', `${30 + i * 30}`) .style('fill', 'red'); return content[i]; });
javascript
18
0.661484
332
39.927273
55
starcoderdata
package ananymous_InnerClass; public abstract class AbstractClass { public abstract void bb(); }
java
5
0.776596
77
19
9
starcoderdata
/** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.master.normalizer; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HBaseIOException; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.RegionInfo; import org.apache.yetus.audience.InterfaceAudience; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Implementation of MergeNormalizer Logic in use: * * all regions of a given table * avg size S of each region (by total size of store files reported in RegionLoad) * regions R1 and its neighbour R2 are merged, if R1 + R2 &lt; S, and all such regions are * returned to be merged * no action is performed * * * Considering the split policy takes care of splitting region we also want a way to merge when * regions are too small. It is little different than what * {@link org.apache.hadoop.hbase.master.normalizer.SimpleRegionNormalizer} does. Instead of doing * splits and merge both to achieve average region size in cluster for a table. We only merge * regions(older than defined age) and rely on Split policy for region splits. The goal of this * normalizer is to merge small regions to make size of regions close to average size (which is * either average size or depends on either target region size or count in that order). Consider * region with size 1,2,3,4,10,10,10,5,4,3. If minimum merge age is set to 0 days this algorithm * will find the average size as 7.2 assuming we haven't provided target region count or size. Now * we will find all those adjacent region which if merged doesn't exceed the average size. so we * will merge 1-2, 3-4, 4,3 in our first run. To get best results from this normalizer theoretically * we should set target region size between 0.5 to 0.75 of configured maximum file size. If we set * min merge age as 3 we create plan as above and see if we have a plan which has both regions as * new(age less than 3) we discard such plans and we consider the regions even if one of the region * is old enough to be merged. * */ @InterfaceAudience.Private public class MergeNormalizer extends AbstractRegionNormalizer { private static final Logger LOG = LoggerFactory.getLogger(MergeNormalizer.class); private int minRegionCount; private int minRegionAge; private static long[] skippedCount = new long[NormalizationPlan.PlanType.values().length]; public MergeNormalizer() { Configuration conf = HBaseConfiguration.create(); minRegionCount = conf.getInt("hbase.normalizer.min.region.count", 3); minRegionAge = conf.getInt("hbase.normalizer.min.region.merge.age", 3); } @Override public void planSkipped(RegionInfo hri, NormalizationPlan.PlanType type) { skippedCount[type.ordinal()]++; } @Override public long getSkippedCount(NormalizationPlan.PlanType type) { return skippedCount[type.ordinal()]; } @Override public List computePlanForTable(TableName table) throws HBaseIOException { List plans = new ArrayList<>(); if (!shouldNormalize(table)) { return null; } // at least one of the two regions should be older than MIN_REGION_AGE days List normalizationPlans = getMergeNormalizationPlan(table); for (NormalizationPlan plan : normalizationPlans) { if (plan instanceof MergeNormalizationPlan) { RegionInfo hri = ((MergeNormalizationPlan) plan).getFirstRegion(); RegionInfo hri2 = ((MergeNormalizationPlan) plan).getSecondRegion(); if (isOldEnoughToMerge(hri) || isOldEnoughToMerge(hri2)) { plans.add(plan); } else { LOG.debug("Skipping region {} and {} as they are both new", hri.getEncodedName(), hri2.getEncodedName()); } } } if (plans.isEmpty()) { LOG.debug("No normalization needed, regions look good for table: {}", table); return null; } return plans; } private boolean isOldEnoughToMerge(RegionInfo hri) { Timestamp currentTime = new Timestamp(System.currentTimeMillis()); Timestamp hriTime = new Timestamp(hri.getRegionId()); boolean isOld = new Timestamp(hriTime.getTime() + TimeUnit.DAYS.toMillis(minRegionAge)) .before(currentTime); return isOld; } private boolean shouldNormalize(TableName table) { boolean normalize = false; if (table == null || table.isSystemTable()) { LOG.debug("Normalization of system table {} isn't allowed", table); } else if (!isMergeEnabled()) { LOG.debug("Merge disabled for table: {}", table); } else { List tableRegions = masterServices.getAssignmentManager().getRegionStates().getRegionsOfTable(table); if (tableRegions == null || tableRegions.size() < minRegionCount) { int nrRegions = tableRegions == null ? 0 : tableRegions.size(); LOG.debug( "Table {} has {} regions, required min number of regions for normalizer to run is {} , " + "not running normalizer", table, nrRegions, minRegionCount); } else { normalize = true; } } return normalize; } }
java
16
0.720802
100
41.930556
144
starcoderdata
package me.qcarver.ballsack; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import processing.core.PApplet; import processing.event.KeyEvent; /** * * @author Quinn */ public class Visualization extends PApplet implements ActionListener { int grayValue = 128; Circle currentCircle; List circles; void settings() { } @Override public void setup() { //need to pass the Processing context to apps that use it Circle.setPApplet(this); //Typical Processing setup stuff, but no sizing, our frame sets this background(grayValue); noFill(); ellipseMode(RADIUS); } public void addCircle(Circle addMe) { //if this is the first time we have used our list.. allocate for it if (circles == null) { circles = new CopyOnWriteArrayList } circles.add(addMe); } public void dropXml(String filename) { XmlVisualization xmlViz = new XmlVisualization(filename); Circle docCircle = xmlViz.getCircle(); docCircle.update(width / 2, height / 2); addCircle(docCircle); } public void draw() { background(grayValue); if (circles != null) { for (Circle circle : circles) { circle.draw(); } } if ((currentCircle != null) && (currentCircle.makeCircle)) { //draw the circle we are currently dragging out currentCircle.draw(); } } @Override public void keyPressed(KeyEvent event) { if (event.getKey() == '\b'){ if (circles != null){ circles.clear(); background(grayValue); } } } public void mousePressed() { currentCircle = new Circle(mouseX, mouseY); } public void mouseDragged() { currentCircle.makeCircle = true; currentCircle.radius = dist(currentCircle.centerX, currentCircle.centerY, mouseX, mouseY); } public void mouseReleased() { //if mouse was released after dragging makeCircle will be true if (currentCircle.makeCircle == true) { //if this is the first time we have used our list.. allocate for it if (circles == null) { circles = new CopyOnWriteArrayList } //check and process for containing circles if (condense() == false) { //archive the currentCircle circles.add(currentCircle); } //make way for a new current circle currentCircle.makeCircle = false; currentCircle = null; } } //if there are circles with this circle condense them all together public boolean condense() { List containedCircles = null; float newCenterX = 0, newCenterY = 0; for (Circle circle : circles) { if (contains(currentCircle, circle)) { if (containedCircles == null) { containedCircles = new ArrayList } //keep summations of x and y positions to use in average later newCenterX += circle.centerX; newCenterY += circle.centerY; containedCircles.add(circle); } } if (containedCircles != null) { currentCircle.update( //change the new circles position to be the average newCenterX / containedCircles.size(), newCenterY / containedCircles.size()); Sack sack = new Sack(currentCircle, containedCircles); circles.removeAll(containedCircles); circles.add(sack); } return (containedCircles != null); } public boolean contains(Circle container, Circle containee) { return (dist(container.centerX, container.centerY, containee.centerX, containee.centerY) <= container.radius); } @Override public void actionPerformed(ActionEvent e) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
java
16
0.582825
135
29.944056
143
starcoderdata
// TODO: Add support for running on MSB-first platforms #include #include #include #include #include #include #include #include "types.h" static bool UOFlowDetected = false; const bool EmulateBuggyCodec = true; #include "pcfx-adpcm.inc" typedef struct { uint32 sector __attribute__((packed)); } song_pointer_t; static const int NumSongs = 36; song_pointer_t songs[NumSongs]; int main(int argc, char *argv[]) { FILE *fp; if(argc < 2) { printf("Usage: %s derlangrisser.bin\n", argv[0]); return(-1); } if(!(fp = fopen(argv[1], "rb"))) { printf("Couldn't open input file!\n"); return(-1); } if(fseek(fp, 0x2A7D6E0, SEEK_SET) == -1) { printf("%m\n"); return(-1); } if(fread(songs, sizeof(song_pointer_t), NumSongs, fp) != (size_t)NumSongs) { printf("%m\n"); return(-1); } for(int i = 0; i < NumSongs; i++) songs[i].sector = (songs[i].sector >> 11) + 0x4ae0 - 225; for(int i = 0; i < NumSongs; i++) { uint8 raw_mono[2048]; int32 count; // = songs[i + 1].sector - songs[i].sector; char wavpath[256]; SF_INFO sfi; SNDFILE *sf; if(i == (NumSongs - 1)) // Last song is a dummy song in Der Langrisser FX break; else count = songs[i + 1].sector - songs[i].sector; printf("%08x:%04x\n", songs[i].sector, count); snprintf(wavpath, 256, "dlfx-%d.wav", i); sfi.samplerate = ((double)1789772.727272727272 * 12 * 2) / 1365; sfi.channels = 1; sfi.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16; if(!(sf = sf_open(wavpath, SFM_WRITE, &sfi))) { printf("Error opening output file \"%s\".\n", wavpath); return(-1); } ResetADPCM(0); ResetADPCM(1); if(fseek(fp, 2352 * songs[i].sector + 12 + 3 + 1, SEEK_SET) == -1) { printf("%m\n"); return(-1); } while(count > 0) { int16 out_buffer[2048 * 2]; if(fread(raw_mono, 1, 2048, fp) != 2048) { printf("%m\n"); return(-1); } for(int i = 0; i < 2048 * 2; i++) { out_buffer[i] = DecodeADPCMNibble(0, (raw_mono[i >> 1] >> ((i & 1) * 4)) & 0xF); } if(sf_write_short(sf, out_buffer, 2048 * 2) != 2048 * 2) { puts(sf_strerror(sf)); return(-1); } count--; fseek(fp, 2352 - 2048, SEEK_CUR); } sf_close(sf); } fclose(fp); puts("DONE."); }
c++
20
0.585075
84
18.065041
123
starcoderdata
import { ajax } from "core"; export class MainService { /* static getUser(request) { return ajax("GET", "http://192.168.127.12:3200/api/user/check", request); } */ static getUser(request) { return ajax("GET", "/api/user/check", {}, request, undefined, true); } static login(request) { return ajax("POST", "/api/user/login", {}, request); } }
javascript
10
0.577608
81
25.2
15
starcoderdata
package com.duowan.sonic; import android.app.Activity; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioRecord; import android.media.AudioTrack; import android.media.MediaRecorder; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.Toast; public class MainActivity extends Activity { // 音频获取源 private int audioSource = MediaRecorder.AudioSource.MIC; // 设置音频采样率,44100是目前的标准,但是某些设备仍然支持22050,16000,11025 private static int sampleRateInHz = 44100; // 设置音频的录制的声道CHANNEL_IN_STEREO为双声道,CHANNEL_CONFIGURATION_MONO为单声道 private static int channelConfig = AudioFormat.CHANNEL_IN_MONO; private static int CHANNEL_COUNT = 1; // 音频数据格式:PCM 16位每个样本。保证设备支持。PCM 8位每个样本。不一定能得到设备支持。 private static int audioFormat = AudioFormat.ENCODING_PCM_16BIT; private static int BYTES_PER_FRAME = 2; // short==16bit==2byte // 缓冲区字节大小 private static int DEFAULT_BUFFER_SIZE = 4096 * CHANNEL_COUNT * BYTES_PER_FRAME; private int inNumberFrames = 0; private int bufferSizeInBytes = 0; private AudioRecord audioRecord; private boolean isRecording = false; private boolean isListening = false; public MainActivity() { Log.i("MainActivity", "Constructor"); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SonicGenerator.preLoad(); SonicListener.preLoad(); createAudioRecord(); } @Override protected void onDestroy() { isListening = false; stopRecord(); close(); SonicListener.releaseFFTMgr(); super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } private void createAudioRecord() { try { // 获得缓冲区字节大小 bufferSizeInBytes = AudioRecord.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat); if (bufferSizeInBytes < DEFAULT_BUFFER_SIZE) bufferSizeInBytes = DEFAULT_BUFFER_SIZE; // 创建AudioRecord对象 audioRecord = new AudioRecord(audioSource, sampleRateInHz, channelConfig, audioFormat, bufferSizeInBytes); if (audioRecord.getState() == AudioRecord.STATE_INITIALIZED) { Log.d("Recorder", "Audio recorder initialised successed"); inNumberFrames = bufferSizeInBytes / BYTES_PER_FRAME / CHANNEL_COUNT; SonicListener.initFFTMgr(inNumberFrames); startRecord(); } else { Log.d("Recorder", "Audio recorder initialised failed"); } } catch (IllegalArgumentException e) { Log.d("Recorder", "Exception"); } } public void onClickGenerate(View v) { String hash = "nk104a5dj8"; int buffer_len = SonicGenerator.getWaveLenByByte(); byte[] buffer = new byte[buffer_len]; SonicGenerator.genWaveData(hash, buffer); playShortAudioFileViaAudioTrack(buffer); Log.d("Click", "Generate"); } public void onClickStartListening(View v) { isListening = true; Log.d("Click", "StartListening"); } public void onClickStopListening(View v) { isListening = false; Log.d("Click", "StopListening"); } private void playShortAudioFileViaAudioTrack(byte[] byteData) { // Set and push to audio track.. int iMinBufferSize = android.media.AudioTrack.getMinBufferSize(sampleRateInHz, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT); AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRateInHz, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, iMinBufferSize, AudioTrack.MODE_STREAM); at.play(); at.write(byteData, 0, byteData.length); at.stop(); at.release(); at = null; } private void startRecord() { if (isRecording) return; audioRecord.startRecording(); isRecording = true; new Thread(new AudioRecordThread()).start(); new Thread(new AudioAnalysisThread()).start(); } private void stopRecord() { if (audioRecord != null) { isRecording = false; audioRecord.stop(); } } private void close() { if (audioRecord != null) { isRecording = false; audioRecord.stop(); audioRecord.release(); audioRecord = null; } } class AudioRecordThread implements Runnable { @Override public void run() { performThru(); } } private void performThru() { byte[] audiodata = new byte[bufferSizeInBytes]; int readsize = 0; while (isRecording == true) { readsize = audioRecord.read(audiodata, 0, bufferSizeInBytes); if (AudioRecord.ERROR_INVALID_OPERATION != readsize) { /* int result = */ SonicListener.grabAudioData( inNumberFrames, CHANNEL_COUNT, readsize, audiodata); //Log.d("performThru", String.format("result = %d", result)); } } } class AudioAnalysisThread implements Runnable { @Override public void run() { // 20Hz long timeInterval = (long)((1 / 20.) * 1000); while(true) { try { Thread.sleep(timeInterval); } catch (InterruptedException e) { e.printStackTrace(); } computeWave(); } } } private void computeWave() { if (!isListening) return; byte[] result_code = new byte[10]; if (!SonicListener.computeWave(result_code)) { return; } String msg = new String(result_code); Log.d("computeWave", msg); showToast(msg); } public void showToast(final String msg) { new Handler(Looper.getMainLooper()).post( new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show(); } }); } }
java
18
0.614535
110
26.871795
234
starcoderdata
def load_special_property(self, property): """Function to load the special property files related to IonizationEnergies and OxidationStates. Parameters ---------- property : str Property whose values need to be loaded. Returns ------- values : array-like A 2-D numpy array containing the property values for all the elements. Raises ------ IOError If property table doesn't exist. """ # Property file name. file = self.abs_path + property + ".table" # Initialize the list. tmp_values = [] try: prop_file = open(file, 'r') except IOError: print ("File {} doesn't exist!!! Please make sure you " \ "specify the correct file name".format(file)) sys.exit(1) else: for line in prop_file.readlines(): words = line.strip().split() tmp_list = [] for word in words: tmp_list.append(float(word)) tmp_values.append(tmp_list) prop_file.close() values = np.zeros(len(tmp_values), dtype=object) for i in range(len(tmp_values)): values[i] = np.asarray(tmp_values[i], dtype=float) return values
python
15
0.509761
72
29.086957
46
inline
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Xigadee { [AttributeUsage(AttributeTargets.Field)] public class ConfigSettingKeyAttribute:Attribute { public ConfigSettingKeyAttribute(string category = null) { Category = category; } public string Category { get; } } [AttributeUsage(AttributeTargets.Method)] public class ConfigSettingAttribute: Attribute { public ConfigSettingAttribute(string category = null) { Category = category; } public string Category { get; } } }
c#
10
0.664306
64
21.774194
31
starcoderdata
using System.Collections.Generic; using System.Security.Claims; using XingZen.Domain.Model; namespace XingZen.Domain.Services { public interface IStoreService { Store CreateStore(string name, ClaimsPrincipal owner); IList StoresByUser(ClaimsPrincipal owner); } }
c#
8
0.745819
62
22.076923
13
starcoderdata
// // Created by stone on 2019-05-10. // Copyright (c) 2019 stone. All rights reserved. // #import @interface TwoViewController : UIViewController @property (nonatomic, strong) RACSubject *delegateSignal; @end
c
4
0.741228
57
19.818182
11
starcoderdata
//HEADERFILE #ifndef RESTART_SIM_H #define RESTART_SUM_H #include #include #include #include #include #include #include
c
3
0.738397
37
17.230769
13
starcoderdata
<?php function lpp_f_admin_scripts_add() { // Adding scripts for admin view only $screen = get_current_screen(); if($screen->post_type === 'landingpage_f') { wp_enqueue_script('jquery'); wp_enqueue_media(); wp_enqueue_style( 'wp-color-picker'); wp_enqueue_script('lpp_script_s',plugins_url('js/image-upload.js',__FILE__),array( 'jquery' )); wp_enqueue_script('lpp_script_fonts',plugins_url('js/g-font-family.js',__FILE__),array( 'jquery' )); wp_enqueue_script( 'media-upload' ); wp_enqueue_script( 'my-script-handle', plugins_url('/js/lpp_color_picker.js', __FILE__ ), array( 'wp-color-picker' ), false, true ); wp_enqueue_script( 'lpp_wp-color-picker-alpha', plugins_url('/js/alpha-picker.js', __FILE__ ), array( 'wp-color-picker' ), '1.2', false ); } } add_action('admin_enqueue_scripts', 'lpp_f_admin_scripts_add'); ?>
php
13
0.665153
142
35.75
24
starcoderdata
public KinematicSteeringOutput GetSteering() { KinematicSteeringOutput steering = new KinematicSteeringOutput(); // determine new velocity steering.velocity = target.position - character.position; steering.velocity.Normalize(); steering.velocity *= maxSpeed; steering.rotation = Angle.WithDeg(0); return steering; }
c#
10
0.766467
67
24.769231
13
inline
void dbPhyDeleteJoint ( int iJoint ) { // delete a single joint in a scene if ( PhysX::pScene == NULL ) return; // go through all objects for ( DWORD dwJoint = 0; dwJoint < PhysX::pJointList.size ( ); dwJoint++ ) { // see if we have a match if ( PhysX::pJointList [ dwJoint ]->iID == iJoint ) { // get a pointer to our object PhysX::sPhysXJoint* pJoint = PhysX::pJointList [ dwJoint ]; if ( pJoint->pJoint ) { /* if ( pJoint->type == PhysX::eFixedJoint ) { delete pJoint->pFixedDesc; pJoint->pFixedDesc = NULL; pJoint->pFixedJoint->setBreakable ( 0.0f, 0.0f ); PhysX::pScene->releaseJoint ( *pJoint->pFixedJoint ); pJoint->pFixedJoint = NULL; } */ // release the joint PhysX::pScene->releaseJoint ( *pJoint->pJoint ); // erase the item in the list PhysX::pJointList.erase ( PhysX::pJointList.begin ( ) + dwJoint ); // clear up the memory delete pJoint; pJoint = NULL; } // break out break; } } }
c++
16
0.599607
75
20.702128
47
inline
/* SPDX-License-Identifier: Apache 2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.openmetadata.accessservices.governanceengine.server.handlers; import org.apache.commons.collections4.CollectionUtils; import org.odpi.openmetadata.accessservices.governanceengine.api.model.Context; import org.odpi.openmetadata.accessservices.governanceengine.api.model.GovernanceClassification; import org.odpi.openmetadata.accessservices.governanceengine.api.model.GovernedAsset; import org.odpi.openmetadata.accessservices.governanceengine.api.model.SoftwareServerCapability; import org.odpi.openmetadata.accessservices.governanceengine.server.processor.ContextBuilder; import org.odpi.openmetadata.commonservices.ffdc.InvalidParameterHandler; import org.odpi.openmetadata.commonservices.repositoryhandler.RepositoryErrorHandler; import org.odpi.openmetadata.commonservices.repositoryhandler.RepositoryHandler; import org.odpi.openmetadata.frameworks.connectors.ffdc.InvalidParameterException; import org.odpi.openmetadata.frameworks.connectors.ffdc.PropertyServerException; import org.odpi.openmetadata.frameworks.connectors.ffdc.UserNotAuthorizedException; import org.odpi.openmetadata.metadatasecurity.server.OpenMetadataServerSecurityVerifier; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.instances.*; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.typedefs.TypeDef; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.repositoryconnector.OMRSRepositoryHelper; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import static org.odpi.openmetadata.accessservices.governanceengine.server.util.Constants.*; /** * ConnectionHandler retrieves Connection objects from the property handlers. It runs handlers-side in the AssetConsumer * OMAS and retrieves Connections through the OMRSRepositoryConnector. */ public class GovernedAssetHandler { private final String serviceName; private final String serverName; private final RepositoryHandler repositoryHandler; private final OMRSRepositoryHelper repositoryHelper; private final InvalidParameterHandler invalidParameterHandler; private final RepositoryErrorHandler errorHandler; private OpenMetadataServerSecurityVerifier securityVerifier = new OpenMetadataServerSecurityVerifier(); private List supportedZones; private ContextBuilder contextBuilder; /** * Construct the handler information needed to interact with the repository services * * @param serviceName name of this service * @param serverName name of the local server * @param invalidParameterHandler handler for managing parameter errors * @param repositoryHandler manages calls to the repository services * @param repositoryHelper provides utilities for manipulating the repository services objects * @param errorHandler provides utilities for manipulating the repository services * @param supportedZones setting of the supported zones for the handler **/ public GovernedAssetHandler(String serviceName, String serverName, InvalidParameterHandler invalidParameterHandler, RepositoryHandler repositoryHandler, OMRSRepositoryHelper repositoryHelper, RepositoryErrorHandler errorHandler, List supportedZones) { this.serviceName = serviceName; this.serverName = serverName; this.invalidParameterHandler = invalidParameterHandler; this.repositoryHelper = repositoryHelper; this.repositoryHandler = repositoryHandler; this.errorHandler = errorHandler; this.supportedZones = supportedZones; contextBuilder = new ContextBuilder(serverName, repositoryHandler, repositoryHelper); } public void setSecurityVerifier(OpenMetadataServerSecurityVerifier securityVerifier) { this.securityVerifier = securityVerifier; } /** * Returns the list of governed assets with associated tags * * @param userId - String - userId of user making request. * @param entityTypes - types to start query offset. * @return List of Governed Access */ public List getGovernedAssets(String userId, List entityTypes, Integer offset, Integer pageSize) throws UserNotAuthorizedException, PropertyServerException, InvalidParameterException { String methodName = "getGovernedAssets"; invalidParameterHandler.validateUserId(userId, methodName); List response = new ArrayList<>(); if (CollectionUtils.isEmpty(entityTypes)) { response = repositoryHandler.getEntitiesForClassificationType(userId, null, SECURITY_TAG, offset, pageSize, methodName); } else { for (String typeName : entityTypes) { TypeDef typeDefByName = repositoryHelper.getTypeDefByName(userId, typeName); if (typeDefByName != null && typeDefByName.getGUID() != null) { response.addAll(repositoryHandler.getEntitiesForClassificationType(userId, typeDefByName.getGUID(), SECURITY_TAG, offset, pageSize, methodName)); } } } return convertGovernedAssets(userId, response); } public GovernedAsset getGovernedAsset(String userId, String assedID) throws InvalidParameterException, PropertyServerException, UserNotAuthorizedException { String methodName = "getGovernedAsset"; invalidParameterHandler.validateUserId(userId, methodName); EntityDetail entityDetailsByGUID = getEntityDetailsByGUID(userId, assedID, null); if (containsGovernedClassification(entityDetailsByGUID)) { return convertGovernedAsset(userId, entityDetailsByGUID); } return null; } public boolean containsGovernedClassification(EntityDetail entityDetail) { if (CollectionUtils.isEmpty(entityDetail.getClassifications())) { return false; } for (Classification classification : entityDetail.getClassifications()) { if (classification.getType() != null && classification.getType().getTypeDefName() != null && isGovernedClassification(classification.getType().getTypeDefName())) { return true; } } return false; } public boolean isSchemaElement(InstanceType entityType) { if (entityType == null) { return false; } return repositoryHelper.isTypeOf(serverName, entityType.getTypeDefName(), SCHEMA_ATTRIBUTE); } public String createSoftwareServerCapability(String userId, SoftwareServerCapability softwareServerCapability) throws UserNotAuthorizedException, PropertyServerException, org.odpi.openmetadata.commonservices.ffdc.exceptions.InvalidParameterException { String methodName = "createSoftwareServerCapability"; invalidParameterHandler.validateUserId(userId, methodName); InstanceProperties initialProperties = getSoftwareServerCapabilityProperties(softwareServerCapability); return repositoryHandler.createEntity(userId, SOFTWARE_SERVER_CAPABILITY_GUID, SOFTWARE_SERVER_CAPABILITY, initialProperties, Collections.emptyList(), InstanceStatus.ACTIVE, methodName); } public SoftwareServerCapability getSoftwareServerCapabilityByGUID(String userId, String guid) throws InvalidParameterException, PropertyServerException, UserNotAuthorizedException { String methodName = "getSoftwareServerCapabilityByGUID"; invalidParameterHandler.validateUserId(userId, methodName); EntityDetail entityDetailsByGUID = getEntityDetailsByGUID(userId, guid, SOFTWARE_SERVER_CAPABILITY); if (entityDetailsByGUID == null) { return null; } return convertSoftwareServerCapability(entityDetailsByGUID); } public GovernedAsset convertGovernedAsset(String userID, EntityDetail entity) throws InvalidParameterException, PropertyServerException, UserNotAuthorizedException { String methodName = "convertGovernedAsset"; GovernedAsset governedAsset = new GovernedAsset(); governedAsset.setGuid(entity.getGUID()); governedAsset.setType(entity.getType().getTypeDefName()); governedAsset.setFullQualifiedName(repositoryHelper.getStringProperty(serverName, QUALIFIED_NAME, entity.getProperties(), methodName)); governedAsset.setName(repositoryHelper.getStringProperty(serverName, DISPLAY_NAME, entity.getProperties(), methodName)); governedAsset.setContext(buildContext(userID, entity)); if (entity.getClassifications() != null && !entity.getClassifications().isEmpty()) { governedAsset.setAssignedGovernanceClassification(getGovernanceClassification(entity.getClassifications())); } return governedAsset; } private GovernanceClassification getGovernanceClassification(List allClassifications) { Optional classification = filterGovernedClassification(allClassifications); return classification.map(this::getGovernanceClassification).orElse(null); } private GovernanceClassification getGovernanceClassification(Classification classification) { String methodName = "getInstanceProperties"; GovernanceClassification governanceClassification = new GovernanceClassification(); governanceClassification.setName(classification.getName()); InstanceProperties properties = classification.getProperties(); if (properties != null) { governanceClassification.setSecurityLabels( repositoryHelper.getStringArrayProperty(serverName, SECURITY_LABELS, properties, methodName)); governanceClassification.setSecurityProperties( repositoryHelper.getStringMapFromProperty(serverName, SECURITY_PROPERTIES, properties, methodName)); } return governanceClassification; } private Optional filterGovernedClassification(List classifications) { return classifications.stream().filter(c -> isGovernedClassification(c.getType().getTypeDefName())).findAny(); } private boolean isGovernedClassification(String classificationName) { return SECURITY_TAG.equals(classificationName); } private List convertGovernedAssets(String userID, List entityDetails) throws InvalidParameterException, PropertyServerException, UserNotAuthorizedException { if (CollectionUtils.isEmpty(entityDetails)) { return Collections.emptyList(); } List result = new ArrayList<>(); for (EntityDetail entityDetail : entityDetails) { result.add(convertGovernedAsset(userID, entityDetail)); } return result; } private Context buildContext(String userID, EntityDetail entity) throws InvalidParameterException, PropertyServerException, UserNotAuthorizedException { switch (entity.getType().getTypeDefName()) { case RELATIONAL_COLUMN: return contextBuilder.buildContextForColumn(userID, entity.getGUID()); case RELATIONAL_TABLE: return contextBuilder.buildContextForTable(userID, entity.getGUID()); default: return null; } } private EntityDetail getEntityDetailsByGUID(String userId, String guid, String entityType) throws PropertyServerException, UserNotAuthorizedException, InvalidParameterException { String methodName = "getEntityDetailsByGUID"; return repositoryHandler.getEntityByGUID(userId, guid, "guid", entityType, methodName); } private SoftwareServerCapability convertSoftwareServerCapability(EntityDetail entityDetail) { InstanceProperties properties = entityDetail.getProperties(); SoftwareServerCapability softwareServerCapability = new SoftwareServerCapability(); softwareServerCapability.setGUID(entityDetail.getGUID()); softwareServerCapability.setOpenTypeGUID(entityDetail.getType().getTypeDefName()); softwareServerCapability.setName(getStringProperty(properties, NAME, repositoryHelper)); softwareServerCapability.setDescription(getStringProperty(properties, DESCRIPTION, repositoryHelper)); softwareServerCapability.setType(getStringProperty(properties, TYPE, repositoryHelper)); softwareServerCapability.setPatchLevel(getStringProperty(properties, PATCH_LEVEL, repositoryHelper)); softwareServerCapability.setVersion(getStringProperty(properties, VERSION, repositoryHelper)); softwareServerCapability.setSource(getStringProperty(properties, SOURCE, repositoryHelper)); return softwareServerCapability; } private InstanceProperties getSoftwareServerCapabilityProperties(SoftwareServerCapability softwareServerCapability) { InstanceProperties properties = new InstanceProperties(); addStringProperty(softwareServerCapability.getName(), NAME, properties, repositoryHelper); addStringProperty(softwareServerCapability.getDescription(), DESCRIPTION, properties, repositoryHelper); addStringProperty(softwareServerCapability.getType(), TYPE, properties, repositoryHelper); addStringProperty(softwareServerCapability.getVersion(), VERSION, properties, repositoryHelper); addStringProperty(softwareServerCapability.getPatchLevel(), PATCH_LEVEL, properties, repositoryHelper); addStringProperty(softwareServerCapability.getSource(), SOURCE, properties, repositoryHelper); return properties; } private void addStringProperty(String propertyValue, String propertyName, InstanceProperties properties, OMRSRepositoryHelper repositoryHelper) { String methodName = "addStringProperty"; if (propertyValue != null) { repositoryHelper.addStringPropertyToInstance(serverName, properties, propertyName, propertyValue, methodName); } } private String getStringProperty(InstanceProperties properties, String propertyName, OMRSRepositoryHelper repositoryHelper) { return repositoryHelper.getStringProperty(serverName, propertyName, properties, "getStringProperty"); } }
java
18
0.748426
255
49.084746
295
starcoderdata
void InputManager::Update(sf::Window &window) { //The old current state is now the new previous state mPreviousKeyState.swap(mCurrentKeyState); //Iterate through each game key and get the corresponding SFML Key code that is mapped to that game key. for (int k = 0; k < GK_COUNT; ++k) { sf::Keyboard::Key key = mKeyMap[static_cast<GameKey>(k)]; mCurrentKeyState[key] = sf::Keyboard::isKeyPressed(key); } //Set the mouse position relative to the window mMousePos.x = (float)sf::Mouse::getPosition(window).x; mMousePos.y = (float)sf::Mouse::getPosition(window).y; if (mMousePos.x < 0 || mMousePos.x >= window.getSize().x || mMousePos.y < 0 || mMousePos.y >= window.getSize().y) { mMousePos.x = -1.0f; mMousePos.y = -1.0f; } }
c++
13
0.697297
116
45.3125
16
inline
def test_topology_geom(self): p1 = PathFactory.create(geom=LineString((0, 0), (2, 2))) p2 = PathFactory.create(geom=LineString((2, 2), (2, 0))) p3 = PathFactory.create(geom=LineString((2, 0), (4, 0))) # Type Point t = TopologyFactory.create(paths=[(p1, 0.5, 0.5)]) self.assertEqual(t.geom, Point((1, 1), srid=settings.SRID)) # 50% of path p1, 100% of path p2 t = TopologyFactory.create(paths=[(p1, 0.5, 1), p2]) self.assertEqual(t.geom, LineString((1, 1), (2, 2), (2, 0), srid=settings.SRID)) # 100% of path p2 and p3, with offset of 1 t = TopologyFactory.create(offset=1, paths=[p2, p3]) self.assertEqual(t.geom, LineString((3, 2), (3, 1), (4, 1), srid=settings.SRID)) # Change offset, geometry is computed again t.offset = 0.5 t.save() self.assertEqual(t.geom, LineString((2.5, 2), (2.5, 0.5), (4, 0.5), srid=settings.SRID))
python
11
0.574113
96
44.666667
21
inline
import numpy as np from content.helper.constant import Key, CUBE_MOVE, MOVE_ANGLE from content.analyzers.location_analyzer import CubieLocationAnalyzer # noinspection PyProtectedMember class TestCubieLocationAnalyzer: analyzer = CubieLocationAnalyzer( cube_side_length=3, track_item_location=0 ) def test_get_all_basic_key(self): assert self.analyzer._get_basic_key() == [ Key(move=move, angle=90, index=1) for move in CUBE_MOVE ] def test_check_effective_key(self): assert self.analyzer._check_effective_key( key=Key(move="left", angle=90, index=1) ) def test_get_effective_key(self): assert self.analyzer._get_effective_key() == [ Key(move=move, angle=90, index=1) for move in ["left", "top", "back"] ] def test_get_all_effective_key(self): assert self.analyzer._get_all_effective_key() == [ Key(move=move, angle=angle, index=1) for move in ["left", "top", "back"] for angle in MOVE_ANGLE ] def test_get_location(self): assert self.analyzer._get_location( key=Key(move="left", angle=90, index=1)) == 37 def test_get_all_location(self): np.testing.assert_array_equal( self.analyzer.get_all_location(), [1, 37, 145, 215, 10, 35, 28, 136, 179, 82] ) def test_location_tracker(self): # Set up analyzer and the key to perform checking. analyzer = CubieLocationAnalyzer( cube_side_length=3, track_item_location=0 ) keys = [ Key(move="left", angle=90, index=1), Key(move="top", angle=90, index=1), Key(move="down", angle=90, index=1) ] np.testing.assert_array_equal( analyzer.location_tracker(keys=keys), [0, 37, 110, 183] )
python
14
0.58746
69
31.724138
58
starcoderdata
const Discord = require("discord.js"); exports.run = async (client, msg) => { const radio = { "franceinfo": "http://roo8ohho.cdn.dvmr.fr/live/franceinfo-midfi.mp3", "nrj": "http://192.168.127.12/fr/30001/mp3_128.mp3?origine=fluxradios", "rtl2": "http://streaming.radio.rtl2.fr/rtl2-1-48-192", "skyrock": "http://icecast.skyrock.net/s/natio_mp3_128k?tvr_name=tunein16&tvr_section1=128mp3", "rtl": "http://streaming.radio.rtl.fr/rtl-1-48-192", "rfm": "http://rfm-live-mp3-128.scdn.arkena.com/rfm.mp3", "bfm": "http://chai5she.cdn.dvmr.fr/bfmbusiness" } if (!msg.guild.voiceConnection) { if (!msg.member.voiceChannel) return msg.channel.send(':x: | Vous devez être dans un salon-vocal !') } let args = msg.content.split(" ").slice(1).join(" ").toLowerCase(); if (!args) return msg.channel.send(':x: | Vous devez choisir une radio. Liste des radios: **franceinfo**, **nrj**, **rtl2**, **skyrock**, **rtl**, **rfm**, **bfm**') if(!radio[args]) return msg.channel.send(':x: | Radio invalide. Liste des radios: **franceinfo**, **nrj**, **rtl2**, **skyrock**, **rtl**, **rfm**, **bfm**') msg.member.voiceChannel.join().then(connection => { require('http').get(radio[args], (res) => { connection.playStream(res); let embed = new Discord.RichEmbed() .setAuthor(args) .setColor(0xFF0000) .addField("Radio", args) .addField("Lien", radio[args]) .setFooter(msg.author.tag); msg.channel.send("**Radio en écoute**", embed); }); }); } exports.conf = { enabled: true, guildOnly: false, aliases: ["radio"], permLevel: 0 }; exports.help = { name : "radio", usage: "radio <nom de radio>", description: "Donner l'ordre au bot d'écouter la radio" }
javascript
21
0.574779
171
31.684211
57
starcoderdata
void setupResults(GPRReg destA, GPRReg destB) { GPRReg srcA = GPRInfo::returnValueGPR; GPRReg srcB = GPRInfo::returnValueGPR2; if (destA == InvalidGPRReg) move(srcB, destB); else if (destB == InvalidGPRReg) move(srcA, destA); else if (srcB != destA) { // Handle the easy cases - two simple moves. move(srcA, destA); move(srcB, destB); } else if (srcA != destB) { // Handle the non-swap case - just put srcB in place first. move(srcB, destB); move(srcA, destA); } else swap(destA, destB); }
c
14
0.522659
71
32.15
20
inline
func (packet *Packet) unmarshal(b []byte) (err error) { reader := bytes.NewReader(b) var first32 uint32 err = binary.Read(reader, binary.BigEndian, &first32) if err != nil { return err } // Unmarshal first 32 bits packet.Version = uint8(first32 >> 30) packet.Padding = (first32 >> 29 & 1) > 0 packet.Extension = (first32 >> 28 & 1) > 0 CSRCCount := first32 >> 24 & 15 packet.Marker = (first32 >> 23 & 1) > 0 packet.PayloadType = uint8(first32 >> 16 & 127) packet.SequenceNumber = uint16(first32 & 65535) // Unmarshal timestamp err = binary.Read(reader, binary.BigEndian, &packet.Timestamp) if err != nil { return err } // Unmrashal SSRC err = binary.Read(reader, binary.BigEndian, &packet.SSRC) if err != nil { return err } // Unmarshal CSRC list packet.CSRCList = make([]uint32, CSRCCount) for i := 0; i < int(CSRCCount); i++ { err = binary.Read(reader, binary.BigEndian, &packet.CSRCList[i]) if err != nil { return err } } // Unmarshal payload packet.Payload = packet.buf[:reader.Len()] reader.Read(packet.Payload) return nil }
go
12
0.663889
66
23.022222
45
inline
using System; using System.Collections.Generic; using Newtonsoft.Json; namespace MediaWikiNET.Models { /// /// see at https://en.wikipedia.org/w/api.php /// public abstract class Request { /// /// Output as a dict /// public virtual Dictionary<string, string> ToDictionary() { var json = JsonConvert.SerializeObject(this); return JsonConvert.DeserializeObject<Dictionary<string, string>>(json); } } }
c#
15
0.623509
83
25.681818
22
starcoderdata
import pytest from mcanitexgen.animation import generator from mcanitexgen.animation.parser import Action, Duration class InvalidCustomAction(Action): pass @pytest.mark.parametrize("action", [None, InvalidCustomAction(Duration(10))]) def test_unknown_action_type(action): with pytest.raises(TypeError, match="Unknown Action type.*"): generator.append_action_to_animation(action, 0, 0, None)
python
11
0.774266
77
28.533333
15
starcoderdata
//Web dependencies const express = require('express'); const helmet = require('helmet'); const app = express(); const port = process.env.PORT || 8080; app.set('json spaces', 2); app.use(helmet()); // Core dependencies const core = require('./utils/core'); // Routers const accountRouter = require('./routers/account'); const assetRouter = require('./routers/asset'); app.use(accountRouter); app.use(assetRouter); app.get('*', (req, res) => { res.status(404).json({ error: { code: res.statusCode, message: 'Valid service parameter must be provided.', } }) }); app.listen(port, () => { console.info(`Server is listening at port ${port}`); core.initiate(); });
javascript
10
0.625171
65
21.181818
33
starcoderdata
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.rlcommunity.rlglue.codec.taskspec; import java.util.StringTokenizer; /** * * @author */ public class TaskSpecVersionOnly extends TaskSpecDelegate { private String version = "unknown"; /** * Parse a task spec string. * @param taskSpecString */ public TaskSpecVersionOnly(String taskSpecString) { String tmpToken; //Default token is space, works for me. StringTokenizer T = new StringTokenizer(taskSpecString); tmpToken = T.nextToken(); if (!tmpToken.equals("VERSION")) { throw new IllegalArgumentException("Expected VERSION token. This task spec doesn't look like a fourth generation task spec."); } version = T.nextToken(); } /** * @see org.rlcommunity.rlglue.codec.taskspec.TaskSpec#getVersionString() */ @Override public String getVersionString() { return version; } }
java
11
0.650476
140
24
42
starcoderdata
<?php echo Notice::inline(Yii::t('core', 'Fields with <span class="required">* are required.')); ?> <div class="row"> <div class="col-sm-6"> <div class="row"> <div class="col-sm-4"> <div class="form-group <?php echo $model->hasErrors('genre') ? 'has-error' : '' ?>"> <?php echo $form->bsLabelFx0($model, 'genre', array('label' => Yii::t('cv', 'Type'))); ?> <div class=""> <?php echo $form->bsEnumDropDownList($model, 'genre'); ?> <?php echo $form->bsError($model, 'genre'); ?> <div class="col-sm-8"> <div class="form-group <?php echo $model->hasErrors('title') ? 'has-error' : '' ?>"> <?php echo $form->bsLabelFx0($model, 'title'); ?> <div class=""> <?php echo $form->bsTextField($model, 'title'); ?> <?php echo $form->bsError($model, 'title'); ?> <div class="form-group <?php echo $model->hasErrors('organization_name') ? 'has-error' : '' ?>"> <?php echo $form->bsLabelFx0($model, 'organization_name'); ?> <div class=""> <?php echo $form->bsTextField($model, 'organization_name'); ?> <?php echo $form->bsError($model, 'organization_name'); ?> <div class="form-group <?php echo $model->hasErrors('full_address') ? 'has-error' : '' ?>"> <?php echo $form->bsLabelFx0($model, 'full_address'); ?> <div class=""> <?php echo $form->bsTextArea($model, 'full_address', array('rows' => 2)); ?> <span class="help-block"><?php echo Yii::t('cv', "Don't worry, we will not display your full address to public. Only the city, state and country are show.") ?> <?php echo $form->bsError($model, 'full_address'); ?> <div class="row nopadding"> <div class="col col-sm-6 nopadding"> <div class="form-group <?php echo $model->hasErrors('year_start') ? 'has-error' : '' ?>"> <?php echo $form->bsLabelFx0($model, 'year_start'); ?> <div class=""> <?php echo $form->bsDropDownList($model, 'year_start', ysUtil::generateArrayRange(date('Y'), 1900, '2d'), array('empty' => 'Please Select'), array('class' => 'form-control', 'prompt' => 'Select Year')); ?> <?php echo $form->bsError($model, 'year_start'); ?> <div class="col col-sm-6" style="padding-right:0"> <div class="form-group <?php echo $model->hasErrors('month_start') ? 'has-error' : '' ?>"> <?php echo $form->bsLabelFx0($model, 'month_start'); ?> <div class=""> <?php echo $form->bsEnumDropDownList($model, 'month_start'); ?> <?php echo $form->bsError($model, 'month_start'); ?> <div class="row nopadding"> <div class="col col-sm-6 nopadding"> <div class="form-group <?php echo $model->hasErrors('year_end') ? 'has-error' : '' ?>"> <?php echo $form->bsLabelFx0($model, 'year_end'); ?> <div class=""> <?php echo $form->bsDropDownList($model, 'year_end', ysUtil::generateArrayRange(date('Y'), 1900, '2d'), array('empty' => 'Please Select'), array('class' => 'form-control', 'prompt' => 'Select Year')); ?> <?php echo $form->bsError($model, 'year_end'); ?> <div class="col col-sm-6" style="padding-right:0"> <div class="form-group <?php echo $model->hasErrors('month_end') ? 'has-error' : '' ?>"> <?php echo $form->bsLabelFx0($model, 'month_end'); ?> <div class=""> <?php echo $form->bsEnumDropDownList($model, 'month_end'); ?> <?php echo $form->bsError($model, 'month_end'); ?> <div class="col-sm-6"> <div class="form-group <?php echo $model->hasErrors('text_short_description') ? 'has-error' : '' ?>"> <?php echo $form->bsLabelFx0($model, 'text_short_description'); ?> <div class=""> <?php echo $form->bsTextArea($model, 'text_short_description', array('rows' => 16)); ?> <?php echo $form->bsError($model, 'text_short_description'); ?>
php
12
0.554672
225
41.814433
97
starcoderdata
# -*- coding: utf-8 -*- import re from pyjosa.exceptions import NotHangleException, JongsungInstantiationException from pyjosa import START_HANGLE, J_INDEX class Jongsung: """ 글자가 한글인지 체크 및 종성이 있는지 체크하는 클래스 """ # Class attribute _START_HANGLE = START_HANGLE # 44032 _J_IDX = J_INDEX # 28 # we will not instantiate this class because it's not really needed. def __init__(self): raise JongsungInstantiationException @staticmethod def is_hangle(string: str) -> bool: """ 입력받은 문자열의 마지막 글자가 한글인지 체크하는 정적 메서드 :param string: 처리하고자 하는 단어(문자열) :return: 마지막 글자가 한글일경우 True, 한글이 아닐경우 False """ last_char = string[-1] if re.match('.*[ㄱ-ㅎㅏ-ㅣ가-힣]+.*', last_char) is None: return False return True @classmethod def has_jongsung(cls, string: str) -> bool: """ 입력받은 문자열의 마지막 글자가 한글인 경우, 해당 글자가 종성이 있는지 없는지 확인하는 클래스 메서드 :param string: 입력받은 문자열 :return: 종성이 있을경우 True """ if not cls.is_hangle(string): raise NotHangleException last_char = string[-1] if (ord(last_char) - cls._START_HANGLE) % cls._J_IDX > 0: return True return False
python
13
0.584064
80
27.522727
44
starcoderdata
void RenameTempToPerm() { char szTemp[MAX_PATH]; char szPerm[MAX_PATH]; uint32_t dwIndex = 0; while (GetTempSaveNames(dwIndex, szTemp)) { [[maybe_unused]] bool result = GetPermSaveNames(dwIndex, szPerm); // DO NOT PUT DIRECTLY INTO ASSERT! assert(result); dwIndex++; if (mpqapi_has_file(szTemp)) { if (mpqapi_has_file(szPerm)) mpqapi_remove_hash_entry(szPerm); mpqapi_rename(szTemp, szPerm); } } assert(!GetPermSaveNames(dwIndex, szPerm)); }
c++
11
0.672165
103
25.055556
18
inline
#!/usr/bin/env python import os import sys import time import logging import logging.handlers import cPickle import random import requests from pyvirtualdisplay import Display from selenium import webdriver from selenium.webdriver.common.keys import Keys logging.basicConfig(level=logging.INFO, format='[%(levelname)s] %(asctime)-15s %(pathname)s:%(lineno)d - %(message)s') handler = logging.handlers.SysLogHandler(address='/dev/log') log = logging.getLogger(__name__) log.addHandler(handler) COOKIES_FILENAME = os.path.join(os.path.dirname(__file__), '.cookies.pkl') def login_with_credentials(browser): log.info('Entering username') username = browser.find_element_by_name('username') username.send_keys(os.environ['USERNAME']) # browser.save_screenshot('uname.png') log.info('Entering password') password = browser.find_element_by_name('password') password.send_keys(os.environ['PASSWORD']) password.submit() # log.info('Save screenshot with home') time.sleep(10) # browser.save_screenshot('home.png') log.info('Saving cookies into file %s', COOKIES_FILENAME) cPickle.dump(browser.get_cookies() , open(COOKIES_FILENAME, 'wb')) def login_with_cookies(browser): cookies = cPickle.load(open(COOKIES_FILENAME, 'rb')) for cookie in cookies: browser.add_cookie(cookie) def like_one_post(browser, img): """ Given an opened post, finds the like button, clicks on it and presses the right arrow in order to navigate to the next page :return: url of just liked image """ url = None try: like = browser.find_element_by_css_selector('.coreSpriteHeartOpen') like.click() url = browser.current_url except: log.error('Image was already liked or some other error: %s', browser.current_url) # browser.save_screenshot(str(time.time()) + '.png') img.send_keys(Keys.ARROW_RIGHT) return url def select_random_hashtag(): """ Returns a random hashtag from the latest posts or travel if none was found """ r = requests.get('https://api.instagram.com/v1/users/self/media/recent?access_token={}'.format(os.environ['ACCESS_TOKEN'])) if r.status_code == 200: data = r.json() tags = set() for media in data.get('data'): tags.update(media.get('tags')) return random.choice(list(tags)) return 'travel' def main(): # select random hashtag from latest posts hashtag = select_random_hashtag() log.info('Hashtag #%s was selected', hashtag) display = Display(visible=0, size=(1024, 768)) display.start() browser = webdriver.Firefox() log.info('Begin. Opening instagram.com') browser.get('https://instagram.com') if os.path.isfile(COOKIES_FILENAME): # load cookies log.info('Loading cookies and redirecting to instagram explore page') login_with_cookies(browser) else: log.info('Login with username and password') login_with_credentials(browser) # navigate to hashtag page, and wait 5s to load browser.get('https://www.instagram.com/explore/tags/{}/'.format(hashtag)) log.info('Navigated to #%s', hashtag) time.sleep(5) # find first post img = browser.find_element_by_css_selector('article a') img.click() log.info('Found first image') # find first 3-9 photos to like for i in xrange(1, random.randint(4, 10)): # wait somewere between 5-10 sec time.sleep(random.randint(5, 11)) # like the current active post, and move to the other url = like_one_post(browser, img) log.info('Liked image #%s, url: %s', i, url) # log.info('Saving screenshot') # browser.save_screenshot('home.png') log.info('Done!') browser.quit() display.stop() if __name__ == '__main__': main()
python
13
0.663489
127
28.625954
131
starcoderdata
#ifndef UTIL_HXX #define UTIL_HXX #include #include #include #include #include #include "strwrap.hxx" #include "vecwrap.hxx" class Exception { public: Exception(std::string&& new_message); const std::string& what(); private: const std::string message; }; enum class CLMode { WholeFile, Params }; enum class RWMode { Read, Write }; struct ReadWriteAction { ReadWriteAction(RWMode new_mode, std::string new_section_name, std::string new_name, std::string new_value); RWMode mode; std::string section_name; std::string parameter_name; std::string parameter_value; }; class FileReader { public: FileReader(const std::string& file_name); VectorWrapper lines(); ~FileReader(); FileReader& reset(); private: std::ifstream file; }; class FileWriter { public: FileWriter(const std::string& file_name); FileWriter& trunc_mode(); FileWriter& write_line(std::string write_me); FileWriter& close(); private: std::ofstream file; std::string name; }; #endif
c++
10
0.61841
116
18.916667
60
starcoderdata
#include "catch.hpp" #ifdef VECPP_TEST_SINGLE_HEADER #include "vecpp/vecpp_single.h" #else #include "vecpp/vecpp.h" #endif using Catch::Matchers::WithinAbs; TEST_CASE("Matrix transpose", "[mat]") { using Mat2 = vecpp::Mat<int, 2, 2>; REQUIRE(transpose(Mat2{1, 2, 3, 4}) == Mat2{1, 3, 2, 4}); static_assert(transpose(Mat2{1, 2, 3, 4}) == Mat2{1, 3, 2, 4}); } TEST_CASE("Large matrix determinant", "[mat]") { using Mat3 = vecpp::Mat<float, 3, 3>; using Mat4 = vecpp::Mat<float, 4, 4>; using Mat5 = vecpp::Mat<float, 5, 5>; // clang-format off Mat3 mat3 = { 1.0f, 5.0f, 1.0f, 4.0f, 0.0f, 0.0f, 3.0f, 1.0f, 2.0f }; Mat4 mat4 = { 0.0f, 3.0f, 5.0f, 1.0f, 1.0f, 5.0f, 1.0f, 0.0f, 4.0f, 0.0f, 0.0f, 2.0f, 3.0f, 1.0f, 2.0f, 0.0f }; Mat5 mat5 = { 1.0f, 0.0f, 3.0f, 5.0f, 1.0f, 0.0f, 1.0f, 5.0f, 1.0f, 0.0f, 0.0f, 4.0f, 0.0f, 0.0f, 2.0f, 2.0f, 3.0f, 1.0f, 2.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f}; // clang-format on REQUIRE_THAT(determinant(mat3), WithinAbs(-36.0f, 0.001f)); REQUIRE_THAT(determinant(mat4), WithinAbs(170.0f, 0.001f)); REQUIRE_THAT(determinant(mat5), WithinAbs(230.0f, 0.001f)); }
c++
10
0.567114
65
23.326531
49
starcoderdata
const express = require('express'); const router = express.Router();; const db = require('../models/landingPageModel'); // get featured projects router.get('/projects', function (req, res) { db.getPopularProjects() .then(project => { if (project) { res.status(200).json(project); } else { res.status(404).json({ error: 'Projects not found.' }); } }) .catch(err => { res.status(500).json(err); }); }); router.get('/makers', function (req, res) { db.getPopularMakers() .then(maker => { if (maker) { res.status(200).json(maker); } else { res.status(404).json({ error: 'Makers not found.' }); } }) .catch(err => { res.status(500).json(err); }); }); router.get('/reviewers', function (req, res) { db.getPopularReviewers() .then(reviewer => { if (reviewer) { res.status(200).json(reviewer); } else { res.status(404).json({ error: 'Reviewers not found.' }); } }) .catch(err => { res.status(500).json(err); }); }); module.exports = router;
javascript
18
0.545455
64
21.46
50
starcoderdata
public int closeTableEntries(List<Entry> entries) { // close entries by referencing head int nextDeletedObjectNumber = 0; assert entries != null; Entry entry; for (int i = entries.size() - 1; i >= 0; i--) { entry = entries.get(i); if (entry.isDeleted()) { entry.setNextDeletedObjectNumber(nextDeletedObjectNumber); nextDeletedObjectNumber = entry.getReference().getObjectNumber(); } } return nextDeletedObjectNumber; }
java
12
0.580586
81
38.071429
14
inline
package com.example.webfluxexample; import java.time.Duration; import java.util.Objects; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.fasterxml.jackson.annotation.JsonProperty; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @RestController public class HelloController { @GetMapping("/hello") public Mono getHello() { // curl -v localhost:8080/hello return Mono.just("Hello, world!"); } @GetMapping("/hello2") public Mono getHello2() { // curl -v localhost:8080/hello2 return Mono.just(new Hello("Hello, JSON!!")); } @GetMapping("/hello3") public Flux getHello3() { // curl -v localhost:8080/hello3 return Flux.range(1, 10) .map(i -> new Hello("Hello, Flux!!!" + i)); } @GetMapping("/hello4") public Flux getHello4() { // https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-codecs-streaming // JSON Streaming // curl -v localhost:8080/hello4 -H "Accept: application/stream+json" // SSE // curl -v localhost:8080/hello4 -H "Accept: text/event-stream" return Flux.range(1, 10) .map(i -> new Hello("Hello, HTTP Streaming!!!" + i)) .delayElements(Duration.ofSeconds(1)); } @GetMapping("/hello5") public Flux getHello5(@RequestParam final String name) { // curl -v "localhost:8080/hello5?name=world" return Flux.just(new Hello("Hello, " + name + "!!!")); } public static final class Hello { private final String text; public Hello(@JsonProperty("text") final String text) { this.text = Objects.requireNonNull(text); } public String getText() { return text; } @Override public int hashCode() { return Objects.hash(text); } @Override public boolean equals(final Object obj) { if (obj == this) { return true; } else if (obj == null) { return false; } else if (obj.getClass() != getClass()) { return false; } final Hello other = getClass().cast(obj); return text.equals(other.text); } } }
java
14
0.593428
123
28.717647
85
starcoderdata
import logging import pytest from pykube.exceptions import HTTPError from pytest_helm_charts.giantswarm_app_platform.app_catalog import AppCatalogFactoryFunc from pytest_helm_charts.giantswarm_app_platform.apps.http_testing import StormforgerLoadAppFactoryFunc logger = logging.getLogger(__name__) def test_app_catalog_factory_fixture(app_catalog_factory: AppCatalogFactoryFunc): """This example shows how to use [app_catalog_factory](pytest_helm_charts.giantswarm_app_platform.fixtures.app_app_catalog_factory) fixture to create a new AppCatalog CR in the Kubernetes API. You have to define an app catalog before you can install and use applications coming from that catalog. """ catalog_name = "test-dynamic" catalog_url = "https://test-dynamic.com" catalog = app_catalog_factory(catalog_name, catalog_url) assert catalog.metadata["name"] == catalog_name assert catalog.obj["spec"]["title"] == catalog_name assert catalog.obj["spec"]["storage"]["type"] == "helm" assert catalog.obj["spec"]["storage"]["URL"] == catalog_url @pytest.mark.xfail(raises=HTTPError) def test_app_catalog_bad_name(app_catalog_factory: AppCatalogFactoryFunc): """This example is the same as [test_test_app_catalog_factory_fixture](test_app_catalog_factory_fixture) but raises an Exception, as 'test_dynamic' is not a correct name in Kubernetes API. Be careful and check for Kubernetes API restrictions as well. In this case, a DNS-compatible name is required. """ catalog_name = "test_dynamic" catalog_url = "https://test-dynamic.com/" catalog = app_catalog_factory(catalog_name, catalog_url) assert catalog.metadata["name"] == catalog_name def test_app_factory_fixture(stormforger_load_app_factory: StormforgerLoadAppFactoryFunc): """Instead of using the [app_factory](pytest_helm_charts.giantswarm_app_platform.fixtures.app_factory) fixture directly to create a new app here, we test the specific case of using it to create [stormforger_load_app_factory](pytest_helm_charts.giantswarm_app_platforms.apps.http_testing.stormforger_load_app_factory), which works exactly by using the [app_factory](pytest_helm_charts.giantswarm_app_platform.fixtures.app_factory) fixture. """ configured_app = stormforger_load_app_factory(1, "loadtest.app", None) assert configured_app.app.name == "loadtest-app" assert configured_app.app.metadata["name"] == "loadtest-app" assert "app-operator.giantswarm.io/version" in configured_app.app.metadata["labels"] assert configured_app.app.obj["kind"] == "App"
python
9
0.747157
127
50.72549
51
starcoderdata
input = """ -p(1) | f. p(X) :- not -p(X), number(X). number(X) :- X!=0. %#int(X), X!=0. :- f. """ output = """ -p(1) | f. p(X) :- not -p(X), number(X). number(X) :- X!=0. %#int(X), X!=0. :- f. """
python
7
0.435294
41
13.294118
17
starcoderdata
package com.bohutskyi.logtailer; import com.bohutskyi.logtailer.ui.MainFrameUi; import com.jcraft.jsch.JSch; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.EnableAsync; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingDeque; /** * @author */ @EnableAsync @SpringBootApplication @EnableAutoConfiguration public class Application { @Bean public BlockingQueue logUiQueue() { return new LinkedBlockingDeque } @Bean public BlockingQueue logFileQueue() { return new LinkedBlockingDeque } @Bean public MainFrameUi mainFrameUi() { return new MainFrameUi(); } @Bean public JSch jsch() { return new JSch(); } public static void main(String[] args) { new SpringApplicationBuilder(Application.class).headless(false).run(args); } }
java
11
0.744472
82
25.543478
46
starcoderdata
#!env python import chess.pgn, urllib.request, urllib.parse, urllib.error, boto, time, json import sys def write_batch(pgn_string, inputs_bucket, batch_name, batch_num): games_key = '% % (batch_name, batch_num) results_key = '% % (batch_name, batch_num) key = inputs_bucket.new_key(games_key) key.set_contents_from_string(pgn_string) key.close() config = {'pgn_key': games_key, 'depth': 15, 'result_key': results_key} config_key = '% % (batch_name, batch_num) key = config_bucket.new_key(config_key) key.set_contents_from_string(json.dumps(config)) key.close() print("Wrote batch #%d" % batch_num) conn = boto.connect_s3() inputs_bucket = conn.get_bucket('bc-runinputs') config_bucket = conn.get_bucket('bc-runconfigs') batch_size = 60 game_num = 0 batch_name = time.strftime('%Y%m%d-%H%M%S') print("Batch is named %s" % batch_name) urlfd = urllib.request.urlopen(sys.argv[1]) exporter = chess.pgn.StringExporter() game = chess.pgn.read_game(urlfd) while game is not None: if 'FICSGamesDBGameNo' in game.headers: game.headers['BCID'] = 'FICS.%s' % game.headers['FICSGamesDBGameNo'] else: game.headers['BCID'] = 'Kaggle.%s' % game.headers['Event'] game.export(exporter, headers=True, variations=False, comments=False) game_num = game_num + 1 if game_num % batch_size == 0: batch_num = game_num / batch_size - 1 write_batch(str(exporter), inputs_bucket, batch_name, batch_num) exporter = chess.pgn.StringExporter() game = chess.pgn.read_game(urlfd) # if we have some games unwritten in this batch, write them out if game_num % batch_size != 0: batch_num = game_num / batch_size write_batch(str(exporter), inputs_bucket, batch_name, batch_num)
python
11
0.633938
78
32.072727
55
starcoderdata
def voice_combiner(iterable): """ Renders samples from voices and maintains a voice pool """ t = 0.0 stopping = False voice_pool = [] voice_time, voice_list = next(iterable) while True: # add new voices to the pool while t >= voice_time: voice_pool.extend(voice_list) try: voice_time, voice_list = next(iterable) except StopIteration: voice_time = float("inf") stopping = True # pull samples from voices and mix them sample = 0.0 pending_removal = [] for voice in voice_pool: try: sample += next(voice) except StopIteration: # voice has stopped, remove it from the pool pending_removal.append(voice) # clean up pool for voice in pending_removal: voice_pool.remove(voice) # stop yielding if we're done if stopping and len(voice_pool) == 0: raise StopIteration yield sample t += 1000.0 / 44100.0
python
15
0.516725
66
27.947368
38
inline
package gitignore import "path/filepath" type pathMatcher interface { match(path string) bool } type simpleMatcher struct { path string } func (m simpleMatcher) match(path string) bool { return m.path == path } type filepathMatcher struct { path string } func (m filepathMatcher) match(path string) bool { match, _ := filepath.Match(m.path, path) return match }
go
8
0.730769
50
14.6
25
starcoderdata
package com.danix43.javaSerialLogger; public class Launcher { public static void main(String[] args) { LoggerV2 arduino = new LoggerV2(); } }
java
9
0.688776
41
14.416667
12
starcoderdata
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_RENDERER_HOST_PEPPER_PEPPER_NETWORK_MONITOR_HOST_H_ #define CONTENT_BROWSER_RENDERER_HOST_PEPPER_PEPPER_NETWORK_MONITOR_HOST_H_ #include "base/compiler_specific.h" #include "base/memory/weak_ptr.h" #include "content/common/content_export.h" #include "net/base/net_util.h" #include "net/base/network_change_notifier.h" #include "ppapi/host/host_message_context.h" #include "ppapi/host/resource_host.h" namespace content { class BrowserPpapiHostImpl; // The host for PPB_NetworkMonitor. This class lives on the IO thread. class CONTENT_EXPORT PepperNetworkMonitorHost : public ppapi::host::ResourceHost, public net::NetworkChangeNotifier::IPAddressObserver { public: PepperNetworkMonitorHost( BrowserPpapiHostImpl* host, PP_Instance instance, PP_Resource resource); virtual ~PepperNetworkMonitorHost(); // net::NetworkChangeNotifier::IPAddressObserver interface. virtual void OnIPAddressChanged() OVERRIDE; private: void OnPermissionCheckResult(bool can_use_network_monitor); void GetAndSendNetworkList(); void SendNetworkList(scoped_ptr list); ppapi::host::ReplyMessageContext reply_context_; base::WeakPtrFactory weak_factory_; DISALLOW_COPY_AND_ASSIGN(PepperNetworkMonitorHost); }; } // namespace content #endif // CONTENT_BROWSER_RENDERER_HOST_PEPPER_PEPPER_NETWORK_MONITOR_HOST_H_
c
12
0.774497
78
30.84
50
starcoderdata
protected void perform() { // this is a comment buildSimplePlayground_from_library_PlaygroundDefinition_routine(); trace("Playground is ready."); searchForMark_routine(); trace("Found a mark!"); }
java
7
0.688073
70
30.285714
7
inline
// Copyright (C) 2012 GlavSoft LLC. // All rights reserved. // //------------------------------------------------------------------------- // This file is part of the TightVNC software. Please visit our Web site: // // http://www.tightvnc.com/ // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. //------------------------------------------------------------------------- // #include "CapsContainer.h" #include "thread/AutoLock.h" CapsContainer::CapsContainer() { } CapsContainer::~CapsContainer() { } void CapsContainer::add(UINT32 code, const char *vendor, const char *name, const StringStorage desc) { // Fill in an RfbCapabilityInfo structure and pass it to the overloaded // function. RfbCapabilityInfo capinfo; capinfo.code = code; memcpy(capinfo.vendorSignature, vendor, RfbCapabilityInfo::vendorSigSize); memcpy(capinfo.nameSignature, name, RfbCapabilityInfo::nameSigSize); add(&capinfo, desc); } void CapsContainer::add(const RfbCapabilityInfo *capinfo, const StringStorage desc) { AutoLock al(&m_mapLock); infoMap[capinfo->code] = *capinfo; enableMap[capinfo->code] = false; descMap[capinfo->code] = desc; } bool CapsContainer::isAdded(UINT32 code) const { AutoLock al(&m_mapLock); return isKnown(code); } bool CapsContainer::getInfo(UINT32 code, RfbCapabilityInfo *capinfo) { AutoLock al(&m_mapLock); if (isKnown(code)) { *capinfo = infoMap[code]; return true; } return false; } StringStorage CapsContainer::getDescription(UINT32 code) const { AutoLock al(&m_mapLock); return (isKnown(code)) ? descMap.find(code)->second : StringStorage(); } bool CapsContainer::enable(const RfbCapabilityInfo *capinfo) { AutoLock al(&m_mapLock); if (!isKnown(capinfo->code)) { return false; } const RfbCapabilityInfo *known = &(infoMap[capinfo->code]); if (memcmp(known->vendorSignature, capinfo->vendorSignature, RfbCapabilityInfo::vendorSigSize) != 0 || memcmp(known->nameSignature, capinfo->nameSignature, RfbCapabilityInfo::nameSigSize) != 0 ) { enableMap[capinfo->code] = false; return false; } enableMap[capinfo->code] = true; m_plist.push_back(capinfo->code); return true; } bool CapsContainer::isEnabled(UINT32 code) const { AutoLock al(&m_mapLock); return (isKnown(code)) ? enableMap.find(code)->second : false; } size_t CapsContainer::numEnabled() const { AutoLock al(&m_mapLock); return m_plist.size(); } UINT32 CapsContainer::getByOrder(size_t idx) { AutoLock al(&m_mapLock); return (idx < m_plist.size()) ? m_plist[idx] : 0; } void CapsContainer::getEnabledCapabilities(std::vector &codes) const { AutoLock al(&m_mapLock); codes = m_plist; } bool CapsContainer::isKnown(UINT32 code) const { return (descMap.find(code) != descMap.end()); }
c++
10
0.670904
76
26.022901
131
starcoderdata
def update_inventory(): """ write inventory file """ branchs = get_all_pro() inventory_info = "" for branch in branchs: inventory_info = inventory_info + "[" + branch + "]\r\n" hosts = get_hosts(branch) for i in hosts: inventory_info = inventory_info + i[0] + " ansible_ssh_host=" + i[1] + "\r\n" inventory_info = inventory_info + "\r\n" # write file with open(ansible_inventory_file, 'w') as outfile: outfile.write(inventory_info) return True
python
14
0.578244
89
34
15
inline
using System.Collections.Generic; using NuGet; using ripple.Model; namespace ripple.Nuget { public interface IRemoteNuget { string Name { get; } SemanticVersion Version { get; } INugetFile DownloadTo(Solution solution, string directory); string Filename { get; } IEnumerable Dependencies(); } public static class RemoteNugetExtensions { public static bool IsUpdateFor(this IRemoteNuget nuget, Dependency dependency) { var version = dependency.SemanticVersion(); if (version == null) return false; return nuget.Version > version; } public static bool IsUpdateFor(this IRemoteNuget nuget, INugetFile dependency) { return nuget.Version > dependency.Version; } public static Dependency ToDependency(this IRemoteNuget nuget, UpdateMode mode = UpdateMode.Float) { return new Dependency(nuget.Name, nuget.Version.ToString(), mode); } } }
c#
14
0.62037
106
27.243243
37
starcoderdata
def __init__(self, report_list, *args, **kwds): """ Initialization. The parameters added to Dialog are: :param report_list: list of html_str, text_str, image from invariant_state """ super(ReportDialog, self).__init__(report_list, *args, **kwds) # title self.SetTitle("Report: Fitting") # number of images of plot self.nimages = len(self.report_list[2]) if self.report_list[2] is not None: # put image path in the report string if len(self.report_list[2]) == 1: self.report_html = self.report_list[0] % \ "memory:img_fit0.png" elif len(self.report_list[2]) == 2: self.report_html = self.report_list[0] % \ ("memory:img_fit0.png", "memory:img_fit1.png") # allows up to three images else: self.report_html = self.report_list[0] % \ ("memory:img_fit0.png", "memory:img_fit1.png", "memory:img_fit2.png") else: self.report_html = self.report_list[0] # layout self._setup_layout()
python
13
0.461249
70
38.117647
34
inline
@Test public void shouldLoadFromMeetUpWithFallBackTest() { //replace original meetup.url property to force fallback System.setProperty("meetup.url", "127.0.0.1"); List<Group> groupList = groupService.loadFromMeetUp(); assertTrue(groupList.isEmpty()); }
java
8
0.681507
64
40.857143
7
inline
//go:generate go run ../../gen/model_response/main.go -package ssl -source model.go -destination model_response_generated.go //go:generate go run ../../gen/model_paginated/main.go -package ssl -source model.go -destination model_paginated_generated.go package ssl import ( "github.com/ukfast/sdk-go/pkg/connection" ) type CertificateStatus string func (s CertificateStatus) String() string { return string(s) } const ( CertificateStatusCompleted CertificateStatus = "Completed" CertificateStatusProcessing CertificateStatus = "Processing" CertificateStatusExpired CertificateStatus = "Expired" CertificateStatusExpiring CertificateStatus = "Expiring" CertificateStatusPendingInstall CertificateStatus = "Pending Install" ) // Certificate represents an SSL certificate // +genie:model_response // +genie:model_paginated type Certificate struct { ID int `json:"id"` Name string `json:"name"` Status CertificateStatus `json:"status"` CommonName string `json:"common_name"` AlternativeNames []string `json:"alternative_names"` ValidDays int `json:"valid_days"` OrderedDate connection.DateTime `json:"ordered_date"` RenewalDate connection.DateTime `json:"renewal_date"` } // CertificateContent represents the content of an SSL certificate // +genie:model_response type CertificateContent struct { Server string `json:"server"` Intermediate string `json:"intermediate"` } // CertificatePrivateKey represents an SSL certificate private key // +genie:model_response type CertificatePrivateKey struct { Key string `json:"key"` } // CertificateValidation represents the results of certificate validation // +genie:model_response type CertificateValidation struct { Domains []string `json:"domains"` ExpiresAt connection.DateTime `json:"expires_at"` } type RecommendationLevel string func (s RecommendationLevel) String() string { return string(s) } const ( RecommendationLevelLow RecommendationLevel = "low" RecommendationLevelMedium RecommendationLevel = "medium" RecommendationLevelHigh RecommendationLevel = "high" ) // Recommendations represents SSL recommendations // +genie:model_response type Recommendations struct { Level RecommendationLevel `json:"level"` Messages []string `json:"messages"` } // Report represents an SSL report // +genie:model_response type Report struct { Certificate struct { Name string `json:"name"` ValidFrom connection.DateTime `json:"valid_from"` ValidTo connection.DateTime `json:"valid_to"` Issuer string `json:"issuer"` SerialNumber string `json:"serial_number"` SignatureAlgorithm string `json:"signature_algorithm"` CoversDomain bool `json:"covers_domain"` DomainsSecured []string `json:"domains_secured"` MultiDomain bool `json:"multi_domain"` Wildcard bool `json:"wildcard"` Expiring bool `json:"expiring"` Expired bool `json:"expired"` SecureSha bool `json:"secure_sha"` } `json:"certificate"` Server struct { IP string `json:"ip"` Hostname string `json:"hostname"` Port string `json:"port"` CurrentTime connection.DateTime `json:"current_time"` ServertTime connection.DateTime `json:"server_time"` Software string `json:"software"` OpenSSLVersion string `json:"openssl_version"` SSLVersions struct { TLS struct { _1 bool `json:"1"` _1_1 bool `json:"1.1"` _1_2 bool `json:"1.2"` } `json:"tls"` SSL struct { _2 bool `json:"2"` _3 bool `json:"3"` } `json:"ssl"` } `json:"ssl_versions"` } `json:"server"` Vulnerabilities struct { Heartbleed bool `json:"heartbleed"` Poodle bool `json:"poodle"` } `json:"vulnerabilities"` Findings []string `json:"findings"` Chain struct { Certificates []struct { Name string `json:"name"` ValidFrom connection.DateTime `json:"valid_from"` ValidTo connection.DateTime `json:"valid_to"` Issuer string `json:"issuer"` SerialNumber string `json:"serial_number"` SignatureAlgorithm string `json:"signature_algorithm"` ChainIntact bool `json:"chain_intact"` CertificateType string `json:"certificate_type"` } `json:"certificates"` } `json:"chain"` ChainIntact bool `json:"chain_intact"` }
go
15
0.633645
126
35.203008
133
starcoderdata
private Cache createCacheWithSecurityManagerTakingExpectedCreds() { expectedAuthProperties = new Properties(); expectedAuthProperties.setProperty(ResourceConstants.USER_NAME, TEST_USERNAME); expectedAuthProperties.setProperty(ResourceConstants.PASSWORD, TEST_PASSWORD); SimpleSecurityManager securityManager = new SimpleSecurityManager("this is a secret string or something.", expectedAuthProperties); Properties properties = new Properties(); CacheFactory cacheFactory = new CacheFactory(properties); cacheFactory.set(ConfigurationProperties.MCAST_PORT, "0"); // sometimes it isn't due to other // tests. cacheFactory.set(ConfigurationProperties.USE_CLUSTER_CONFIGURATION, "false"); cacheFactory.set(ConfigurationProperties.ENABLE_CLUSTER_CONFIGURATION, "false"); cacheFactory.setSecurityManager(securityManager); return cacheFactory.create(); }
java
8
0.785006
99
49.444444
18
inline
define({ "viewer": { "common": { "close": "סגור", "focusMainstage": "שלח פוקוס של המקלדת למדיה", "expandImage": "הרחב תמונה" }, "a11y": { "skipToContent": "דלג לתוכן", "headerAria": "כותרת של הסיפור", "panelAria": "תוכן הסיפור", "mainStageAria": "המדיה של רשומת הסיפור הנוכחי", "logoLinkAria": "קישור ללוגו", "toTop": "עבור לרשומה הראשונה", "focusContent": "חזור לתוכן", "navAria": "רשומות סיפור", "toEntryAria": "עבור לרשומה ‎%ENTRY_NUMBER%‎‏: ‎%ENTRY_TITLE%‎", "entryAria": "רשומה ‎%ENTRY_NUMBER%‎‏: ‎%ENTRY_TITLE%‎", "loadingAria": "תוכן הסיפור נמצא בטעינה", "skipBelowContent": "דלג מתחת לתוכן זה", "skipBelowVideo": "דלג מתחת לסרטון זה", "skipAboveContent": "דלג מעל תוכן זה", "skipAboveVideo": "דלג מעל סרטון זה", "moreEntries": "רשומות נוספות" }, "loading": { "long": "הסיפור מבצע אתחול", "long2": "תודה על ההמתנה", "failButton": "טען מחדש את הסיפור" }, "signin": { "title": "נדרש אימות", "explainViewer": "אנא התחבר עם חשבון ב- %PORTAL_LINK% כדי לגשת לסיפור.", "explainBuilder": "אנא התחבר עם חשבון ב- %PORTAL_LINK% כדי להגדיר את הסיפור." }, "errors": { "boxTitle": "אירעה שגיאה", "invalidConfig": "תצורה לא חוקית", "invalidConfigNoApp": "מזהה אפליקציית המיפוי באינטרנט לא צוין ב-index.html.", "invalidConfigNoAppDev": "לא צוין בפרמטרי ה-URL מזהה של אפליקציית מיפוי אינטרנט‏ (‎?appid‎‎=‎). במצב פיתוח, המערכת מתעלמת מתצורת ה-appid ב-index.html.", "unspecifiedConfigOwner": "לא הוגדר בעלים מורשה.", "invalidConfigOwner": "הבעלים של הסיפור אינו מורשה.", "createMap": "לא ניתן ליצור מפה", "invalidApp": "%TPL_NAME% אינו קיים או אינו נגיש.", "appLoadingFail": "משהו השתבש, %TPL_NAME% לא נטען באופן תקין.", "notConfiguredDesktop": "הסיפור עדיין אינו מוגדר.", "notConfiguredMobile": "אשף הבנייה של %TPL_NAME% אינו נתמך בגודל תצוגה זה. אם ניתן, שנה את גודל הדפדפן שלך כדי לגשת לאשף הבנייה או בנה את הסיפור שלך בהתקן עם מסך גדול יותר.", "notConfiguredMobile2": "סובב את המכשיר שלך לכיוון לרוחב כדי להשתמש באשף הבנייה של %TPL_NAME%.", "notAuthorized": "אין לך הרשאה לגשת לסיפור זה", "notAuthorizedBuilder": "אינך מורשה להשתמש באשף הבנייה של %TPL_NAME%.", "noBuilderIE": "אשף הבנייה אינו נתמך ב-Internet Explorer לפני גרסה %VERSION%‏. %UPGRADE%", "noViewerIE": "סיפור זה אינו נתמך ב- Internet Explorer לפני גירסה %VERSION%‏.‏ %UPGRADE%", "noViewerIE2": "אתה מנסה להציג את הסיפור באמצעות דפדפן ישן שאינו נתמך. ייתכן כי חלק מהישויות לא יפעלו או שיתרחשו בעיות בלתי צפויות אחרות. מומלץ לשדרג ל-Internet Explorer 11 או להשתמש בדפדפן אחר, כגון Chrome.", "noViewerIE3": "בסוף שנת 2017, לא תוכל עוד לטעון את הסיפור בדפדפן זה. משלב זה ואילך תצטרך להשתמש בדפדפן נתמך כדי להציג את הסיפור.", "upgradeBrowser": "<a href='http://browsehappy.com/' target='_blank'>עדכן את הדפדפן שלך "mapLoadingFail": "משהו השתבש, המפה לא נטענה באופן תקין.", "signOut": "התנתק", "attention": "שים לב!" }, "mainStage": { "back": "חזור", "errorDeleted": "קישור זה אינו פעיל (המקטע נמחק)", "errorNotPublished": "קישור זה אינו פעיל (המקטע לא פורסם)" }, "panel": { "collapse": "כווץ חלונית", "expand": "הרחב חלונית" }, "mobileInfo": { "legend": "מקרא", "description": "תיאור", "lblLegendMobileError": "מצטערים, המקרא אינו זמין. טען מחדש את הסיפור.", "lblLegendMobileErrorExplain": "המקרא אינו זמין כשמסובבים את המכשיר למצב תצוגה לאורך לאחר שהסיפור נטען." }, "mobileFooter": { "swipeInvite": "החלק כדי לנווט בסיפור", "lblNext": "הבא", "lblEnd": "הגעת לסוף הסיפור" }, "headerFromCommon": { "storymapsText": "מפת סיפור", "builderButton": "ערוך", "facebookTooltip": "שתף בפייסבוק", "twitterTooltip": "שתף בטוויטר", "bitlyTooltip": "קבל קישור קצר", "templateTitle": "קבע כותרת לתבנית", "templateSubtitle": "קבע כותרת משנה לתבנית", "share": "שתף", "checking": "בודק את תוכן הסיפור שלך", "fix": "תקן בעיות בסיפור שלך", "noerrors": "לא זוהו בעיות", "tooltipAutoplayDisabled": "זה לא זמין במצב ניגון אוטומטי", "notshared": "הסיפור לא משותף" }, "mapFromCommon": { "overview": "מפת התמצאות", "legend": "מקרא", "home": "התמקד לדף הבית" }, "shareFromCommon": { "copy": "העתק", "copied": "הועתק", "open": "פתח", "embed": "הטמע בדף אינטרנט", "embedExplain": "השתמש בקוד ה- HTML הבא כדי להטמיע את הסיפור בדף אינטרנט.", "size": "גודל (רוחב/גובה):", "autoplayLabel": "מצב ניגון אוטומטי", "autoplayExplain1": "מצב ניגון אוטומטי יתקדם בסיפור שלך במרווחים קבועים. מצב זה אידיאלי עבור צג תצוגה בקיוסק או צג ציבורי, אבל שים לב שבמצבים אחרים, הוא עשוי להפוך את הסיפור לקשה יותר לקריאה. ישות זו אינה נתמכת בתצוגות קטנות.", "autoplayExplain2": "כאשר מצב זה פעיל, קיימים פקדים להפעלה/הפסקה של הסיפור ולהתאמת מהירות הניווט.", "linksupdated": "הקישורים התעדכנו!" }, "locatorFromCommon": { "error": "מיקום לא זמין" } } });
javascript
11
0.623264
233
43.698276
116
starcoderdata
/*! * @author: (https://jan-wolf.de) * @license: 2016 */ (function ( $ ) { "use strict"; // Initialize. $(document).ready(function() { var prefix = 'jw_lightcontactform_'; $('.' + prefix + 'autoresponder_commander').on('change', function(){ $('.' + prefix + 'autoresponder_complier').prop('disabled', !$('.' + prefix + 'autoresponder_commander').is(':checked')); }); }); })(jQuery);
javascript
23
0.572668
124
25.176471
17
starcoderdata
import React from 'react' const Avatar = props => ( <img className="avatar" src={props.src} alt="avatar" /> ) Avatar.defaultProps = { src: 'logo.png' } export default Avatar
javascript
9
0.668508
57
15.454545
11
starcoderdata
package leetcode.tool; /** * @author 17hao * @since 2019-04-07 */ public class LinkedListTool { /** * generate a linked list by given array * * @return the head of linked list */ public static ListNode generateList(int[] array) { ListNode dummyHead = new ListNode(Integer.MIN_VALUE); ListNode cur = dummyHead; for (int value : array) { cur.next = new ListNode(value); cur = cur.next; } return dummyHead.next; } /** * print linked list */ public static void printList(ListNode head) { while (head != null) { System.out.print(head.val + "->"); head = head.next; } System.out.print("null\n"); } }
java
12
0.557196
61
22.911765
34
starcoderdata
package org.ksoap2.serialization; import java.io.IOException; import java.math.BigDecimal; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlSerializer; public class MarshalFloat implements Marshal { static Class class$java$lang$Double; static Class class$java$lang$Float; static Class class$java$math$BigDecimal; static Class class$(String paramString) { try { paramString = Class.forName(paramString); return paramString; } catch (ClassNotFoundException paramString) { throw new NoClassDefFoundError(paramString.getMessage()); } } public Object readInstance(XmlPullParser paramXmlPullParser, String paramString1, String paramString2, PropertyInfo paramPropertyInfo) throws IOException, XmlPullParserException { paramXmlPullParser = paramXmlPullParser.nextText(); if (paramString2.equals("float")) { return new Float(paramXmlPullParser); } if (paramString2.equals("double")) { return new Double(paramXmlPullParser); } if (paramString2.equals("decimal")) { return new BigDecimal(paramXmlPullParser); } throw new RuntimeException("float, double, or decimal expected"); } public void register(SoapSerializationEnvelope paramSoapSerializationEnvelope) { String str = paramSoapSerializationEnvelope.xsd; Class localClass; if (class$java$lang$Float == null) { localClass = class$("java.lang.Float"); class$java$lang$Float = localClass; paramSoapSerializationEnvelope.addMapping(str, "float", localClass, this); str = paramSoapSerializationEnvelope.xsd; if (class$java$lang$Double != null) { break label98; } localClass = class$("java.lang.Double"); class$java$lang$Double = localClass; label51: paramSoapSerializationEnvelope.addMapping(str, "double", localClass, this); str = paramSoapSerializationEnvelope.xsd; if (class$java$math$BigDecimal != null) { break label105; } localClass = class$("java.math.BigDecimal"); class$java$math$BigDecimal = localClass; } for (;;) { paramSoapSerializationEnvelope.addMapping(str, "decimal", localClass, this); return; localClass = class$java$lang$Float; break; label98: localClass = class$java$lang$Double; break label51; label105: localClass = class$java$math$BigDecimal; } } public void writeInstance(XmlSerializer paramXmlSerializer, Object paramObject) throws IOException { paramXmlSerializer.text(paramObject.toString()); } } /* Location: /Users/gaoht/Downloads/zirom/classes4-dex2jar.jar!/org/ksoap2/serialization/MarshalFloat.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
java
13
0.695941
136
29.414894
94
starcoderdata
package com.gupao.edu.vip.lion.test.spi; import com.google.common.collect.Lists; import com.gupao.edu.vip.lion.api.service.BaseService; import com.gupao.edu.vip.lion.api.service.Listener; import com.gupao.edu.vip.lion.api.srd.*; import com.gupao.edu.vip.lion.tools.Jsons; import com.gupao.edu.vip.lion.tools.log.Logs; import java.util.List; /** */ public final class FileSrd extends BaseService implements ServiceRegistry, ServiceDiscovery { public static final FileSrd I = new FileSrd(); @Override public void start(Listener listener) { if (isRunning()) { listener.onSuccess(); } else { super.start(listener); } } @Override public void stop(Listener listener) { if (isRunning()) { super.stop(listener); } else { listener.onSuccess(); } } @Override public void init() { Logs.Console.warn("你正在使用的ServiceRegistry和ServiceDiscovery只能用于源码测试,生产环境请使用zookeeper."); } @Override public void register(ServiceNode node) { FileCacheManger.I.hset(node.serviceName(), node.nodeId(), Jsons.toJson(node)); } @Override public void deregister(ServiceNode node) { FileCacheManger.I.hdel(node.serviceName(), node.nodeId()); } @Override public List lookup(String path) { return Lists.newArrayList(FileCacheManger.I.hgetAll(path, CommonServiceNode.class).values()); } @Override public void subscribe(String path, ServiceListener listener) { } @Override public void unsubscribe(String path, ServiceListener listener) { } }
java
12
0.661836
101
24.090909
66
starcoderdata
public static Tensor compute_weighted_loss(Tensor losses, Tensor sample_weight = null, string reduction = null, string name = null) { if (sample_weight == null) sample_weight = losses.dtype == TF_DataType.TF_DOUBLE ? tf.constant(1.0) : tf.constant(1.0f); var weighted_losses = scale_losses_by_sample_weight(losses, sample_weight); // Apply reduction function to the individual weighted losses. var loss = reduce_weighted_loss(weighted_losses, reduction); // Convert the result back to the input type. // loss = math_ops.cast(loss, losses.dtype); return loss; }
c#
11
0.622781
131
60.545455
11
inline
package aac.impl.filter; import aac.BorderTreatmentStrategy; import aac.PGM; /** * Este filtro, quando aplicado às bordas da imagem, irá ignorar os pixels que o * filtro não casar na imagem. (a parte do filtro que cai fora da imagem) */ public class IgnoreBorderFilter implements BorderTreatmentStrategy { public void apply(PGM image, int[][] filter, int pivotX, int pivotY) { int[][] newBitmap = new int[image.getWidth()][image.getHeight()]; for (int y = 0; y < image.getHeight(); y++) { for (int x = 0; x < image.getWidth(); x++) { int value = 0; int div = 0; for (int filterY = 0; filterY < filter.length; filterY++) { for (int filterX = 0; filterX < filter[filterY].length; filterX++) { int posX = x + (filterX - pivotX); int posY = y + (filterY - pivotY); if (posX >= 0 && posX < image.getWidth() && posY >= 0 && posY < image.getHeight()) { value += image.getPixel(posX, posY) * filter[filterX][filterY]; div++; } } } newBitmap[x][y] = value / div; } } for (int y = 0; y < image.getHeight(); y++) { for (int x = 0; x < image.getWidth(); x++) { image.setPixel(x, y, newBitmap[x][y]); } } } }
java
21
0.576527
80
23.25
52
starcoderdata
def main(path, label): ''' Driver function, call this with a path to the data, and label you wish to use for the files. ''' #paths obs_data = '/Users/niemi/Desktop/Research/IDL/obs/' behroozi = obs_data + 'behroozi/mhmstar.dat' #read data from path g, gdust, prop, h = read_data(path) #plots fstar_plot(behroozi, g, prop, h, output = 'fstar.pdf') massfunc_plot(h, prop, obs_data) gasfrac_sam_cent(h, prop) ssfr_wrapper(h, prop, label) massmet_star(h, g, prop, obs_data, label) mhb(h, prop, obs_data, label)
python
8
0.625219
58
30.777778
18
inline
package controllers; import java.util.List; import annotations.Catch; import models.StockItem; import play.mvc.Controller; import play.mvc.Result; import play.mvc.With; import views.html.*; @Catch public class Product extends Controller{ public Result index() { return redirect(routes.Product.list(1)); } public Result list(int page) { return TODO; } public Result details(long ean) { return TODO; } public Result edit(long ean) { return TODO; } public Result save(long ean) { return TODO; } // public Result list(Long warehouseId) { // List stockItems = StockItem.find() // .where() // .eq("warehouse_id", warehouseId) // .findList(); // if(request().accepts("text/plain")) { // return ok(StringUtils.join(stockItems, "\n")); // } // return ok(product.render(stockItems)); // } }
java
10
0.686298
51
19.8
40
starcoderdata
from pbl import * ''' Top tracks by favorite artists ''' if __name__ == '__main__': fav_artists = ['nightwish', 'within temptation', 'epica', 'after forever'] all = Shuffler(Alternate([ArtistTopTracks(a) for a in fav_artists])) all = PlaylistSave(all, 'top gothic metal', 'plamere') show_source(all)
python
12
0.659401
78
29.583333
12
starcoderdata
using System.ComponentModel; using DevExpress.ExpressApp.Model; using Xpand.ExpressApp.Logic; using Xpand.ExpressApp.Logic.TypeConverters; namespace Xpand.ExpressApp.ModelArtifactState.ObjectViews.Logic { public sealed class ObjectViewRuleAttribute : LogicRuleAttribute, IObjectViewRule { public ObjectViewRuleAttribute(string id, string normalCriteria, string emptyCriteria, string objectView) : base(id, normalCriteria, emptyCriteria) { ObjectView = objectView; } public string ObjectView { get; set; } [TypeConverter(typeof(StringToModelViewConverter))] IModelObjectView IObjectViewRule.ObjectView { get; set; } } }
c#
11
0.745125
113
38.888889
18
starcoderdata
var UserModel = require('../model/schema').UserModel; var exists = function(name) { var p = new Promise(function(resolve, reject) { var query = UserModel.where({ 'name': name }); query.findOne(function(err, data) { if (err) reject(err); resolve(data); }) }) return p; } var save = function(user) { var p = new Promise(function(resolve, reject) { try { var u = new UserModel(user); u.save(function(err, rs, num) { if (err || num != 1) reject(err); resolve('ok'); }); } catch (e) { reject(e); } }); return p; } var findOne = function(conditions) { var p = new Promise(function(resolve, reject) { var query = UserModel.find(conditions); query.exec(function(err, docs) { if (err) { reject(err); } else { resolve(docs); } }); }); return p; } var update = function(conditions,set) { var p = new Promise(function(resolve, reject) { var query = UserModel.update(conditions,set); query.exec(function(err, docs) { if (err) { reject(err); } else { resolve(docs); } }); }); return p; } module.exports = { exists, save, findOne, update }
javascript
19
0.476849
54
20.939394
66
starcoderdata
import React from 'react'; export default (props) => { return ( <div style={props.styles.signUpContainer}> <form onSubmit={props.signup}> <input key="name" name="name" placeholder="name" style={props.styles.formControl} required /> <input key="displayName" name="displayName" placeholder="display name" maxLength="8" style={props.styles.formControl} required /> <input key="email" name="email" type="email" placeholder="email" style={props.styles.formControl} required /> <input key="password" name="password" type="password" placeholder="password" style={props.styles.formControl} required /> <button style={props.styles.loginButton} type="submit">Sign Up ); };
javascript
14
0.447611
79
22.392157
51
starcoderdata
<?php namespace app\common\service; use app\common\model\Notices; use app\common\model\UserAward; class Award { public static function registerAward($registerId,$referrerId) { //推荐人奖励 $referrerAward = self::awardUser($referrerId,10,'推荐成功','推荐成功'); //注册人奖励 $registerAward = self::awardUser($registerId,20,'注册奖励','注册成功'); } public static function awardUser($userId, $amount, $remark, $noticeContent) { $userAward = new UserAward( [ 'user_id' => $userId, 'amount' => $amount, 'status' => 1, 'remark' => $remark, ] ); $userAward->save(); //新增奖励通知 $notice = new Notices( [ 'type' => 1, 'user_id' => $userId, 'title' => '奖励通知', 'content' => '亲,您' . $noticeContent . ',您得到' . $amount . '个USDT的奖励已到账,祝您生活愉快', ] ); $notice->save(); //修改用户余额 Helper::changeUserBalance($userId, $amount, 3, $remark); } }
php
17
0.484134
94
23.533333
45
starcoderdata
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The main program for organizing the buildtool. This module is reponsible for determining the configuration then acquiring and dispatching commands. Commands are introduced into modules, and modules are explciitly plugged into the command_modules[] list in main() where they will be initialized and their commands registered into the registry. From there this module will be able to process arguments and dispatch commands. """ import argparse import datetime import logging import sys import yaml from buildtool.git import GitRunner from buildtool.metrics import MetricsManager from buildtool.util import ( add_parser_argument, maybe_log_exception) STANDARD_LOG_LEVELS = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR } def init_standard_parser(parser, defaults): """Init argparser with command-independent options. Args: parser: [argparse.Parser] defaults: [dict] Default value overrides keyed by option name. """ parser.add_argument( 'components', nargs='*', default=defaults.get('components', None), help='Restrict commands to these components or repository names') add_parser_argument( parser, 'default_args_file', defaults, None, help='path to YAML file containing default command-line options') add_parser_argument( parser, 'log_level', defaults, 'info', choices=STANDARD_LOG_LEVELS.keys(), help='Set the logging level') add_parser_argument( parser, 'root_path', defaults, 'build_source', help='Path to directory to put source code to build in.') add_parser_argument( parser, 'scratch_dir', defaults, 'scratch', help='Directory to write working files.') add_parser_argument( parser, 'logs_dir', defaults, None, help='Override director to write logfiles.' ' The default is add_parser_argument( parser, 'build_number', defaults, '{:%Y%m%d%H%M%S}'.format(datetime.datetime.utcnow()), help='Build number is used when generating artifacts.') add_parser_argument( parser, 'one_at_a_time', defaults, False, action='store_true', help='Do not perform applicable concurrency, for debugging.') def __load_defaults_from_path(path, visited=None): """Helper function for loading defaults from yaml file.""" visited = visited or [] if path in visited: raise ValueError('Circular "default_args_file" dependency in %s' % path) visited.append(path) with open(path, 'r') as f: defaults = yaml.load(f) # Allow these files to be recursive # So that there can be some overall default file # that is then overwridden by another file where # the override file references the default one # and the CLI argument points to the override file. base_defaults_file = defaults.get('default_args_file') if base_defaults_file: base_defaults = __load_defaults_from_path(base_defaults_file) base_defaults.update(defaults) # base is lower precedence. defaults = base_defaults # defaults is what we want to return. return defaults def preprocess_args(args): """Preprocess the args to determine the defaults to use. This recognizes the --default_args_file override and, if present loads them. Returns: args, defaults Where: args are remaining arguments (with--default_args_file removed defaults are overriden defaults from the default_args_file, if present. """ parser = argparse.ArgumentParser(add_help=False) parser.add_argument('--default_args_file', default=None) options, args = parser.parse_known_args(args) if not options.default_args_file: defaults = {} else: defaults = __load_defaults_from_path(options.default_args_file) defaults['default_args_file'] = options.default_args_file return args, defaults def make_registry(command_modules, parser, defaults): """Creates a command registry, adding command arguments to the parser. Args: command_modules: [list of modules] The modules that have commands to register. Each module should have a function register_commands(registry, subparsers, defaults) that will register CommandFactory instances into the registry. parser: [ArgumentParser] The parser to add commands to This adds a 'command' subparser to capture the requested command choice. defaults: [dict] Default values to specify when adding arguments. """ registry = {} subparsers = parser.add_subparsers(title='command', dest='command') for module in command_modules: module.register_commands(registry, subparsers, defaults) return registry def init_options_and_registry(args, command_modules): """Register command modules and determine options from commandline. These are coupled together for implementation simplicity. Conceptually they are unrelated but they share implementation details that can be encapsulated by combining them this way. Args: args: [list of command-line arguments] command_modules: See make_registry. Returns: options, registry Where: options: [Namespace] From parsed args. registry: [dict] of ( """ args, defaults = preprocess_args(args) parser = argparse.ArgumentParser(prog='buildtool.sh') init_standard_parser(parser, defaults) MetricsManager.init_argument_parser(parser, defaults) registry = make_registry(command_modules, parser, defaults) return parser.parse_args(args), registry def main(): """The main command dispatcher.""" GitRunner.stash_and_clear_auth_env_vars() import buildtool.source_commands import buildtool.build_commands import buildtool.bom_commands import buildtool.changelog_commands import buildtool.apidocs_commands import buildtool.image_commands command_modules = [ buildtool.source_commands, buildtool.build_commands, buildtool.bom_commands, buildtool.changelog_commands, buildtool.apidocs_commands, buildtool.image_commands ] options, command_registry = init_options_and_registry( sys.argv[1:], command_modules) logging.basicConfig( format='%(levelname).1s %(asctime)s.%(msecs)03d' ' [%(threadName)s.%(process)d] %(message)s', datefmt='%H:%M:%S', level=STANDARD_LOG_LEVELS[options.log_level]) logging.debug( 'Running with options:\n %s', '\n '.join(yaml.dump(vars(options), default_flow_style=False) .split('\n'))) factory = command_registry.get(options.command) if not factory: logging.error('Unknown command "%s"', options.command) return -1 MetricsManager.startup_metrics(options) try: command = factory.make_command(options) command() finally: MetricsManager.shutdown_metrics() return 0 def dump_threads(): """Dump current threads to facilitate debugging possible deadlock. A process did not exit when log file suggested it was. Maybe there was a background thread it was joining on. If so, this might give a clue should it happen again. """ import threading threads = [] for thread in threading.enumerate(): threads.append(' name={name} daemon={d} alive={a} id={id}'.format( name=thread.name, d=thread.daemon, a=thread.is_alive(), id=thread.ident)) logging.info('The following threads still running:\n%s', '\n'.join(threads)) if __name__ == '__main__': # pylint: disable=broad-except try: retcode = main() dump_threads() sys.exit(retcode) except Exception as ex: sys.stdout.flush() maybe_log_exception('main()', ex, action_msg='Terminating') logging.error("FAILED") dump_threads() sys.exit(-1)
python
14
0.708358
79
31.321705
258
starcoderdata
/******************************************************************************* * Copyright (C) 2021 Intel Corporation * * SPDX-License-Identifier: MIT ******************************************************************************/ #include namespace dml::testing { data_storage::data_storage(const uint32_t size, const uint32_t alignment): base(size, allocator_t{get_aligned_memory_resource(alignment)}) { } } // namespace dml::testing
c++
11
0.470942
80
32.266667
15
starcoderdata
<?php $prefscontents = file_get_contents("../../server/prefs.json"); // carga de forma plana el contenido de las preferencias $prefs = json_decode($prefscontents, true); // transforma el contenido plano en json a una array en forma de objeto include_once("sys/setupDone.php"); include_once("sys/checkDatabase.php");
php
7
0.751445
119
48.571429
7
starcoderdata
#pragma once #include #include #ifdef USE_JXX #define JXXAPI extern #else #define JXXAPI __declspec(dllexport) #endif #ifdef GENERATING_DOCUMENTATION #undef JXXAPI #define JXXAPI #endif using JxxCharPtr = const char*; using JxxNamePtr = JxxCharPtr; using JxxCount = size_t; using JxxFunction = JsNativeFunction; using JxxUInt = uint32_t; using JxxBool = bool; using JxxErrorCode = int; using JxxRefCount = uint32_t; using JxxClassId = void*; class JxxRuntime; enum _JxxConpect { eoJsrt, eoFile = 0x01000000, eoPath = 0x02000000, eoMemory = 0x03000000, eoPivotalData = 0x04000000, eoModule = 0x050000000, }; enum _JxxErrorCode { ecNone = 0, ecNotExists = 1, ecHasExisted = 2, ecUnmatch = 3, ecMissPivotalData = 4, ecBadFormat = 5, ecIoRead = 6, ecIoWrite = 7, ecNotEnough = 8, JxxNoError = 0, JxxErrorHasExisted = 1, JxxErrorNotExists = 2, JxxErrorNotUnmatch = 3, JxxErrorMissPivotalData = 4, JxxErrorJsrtError = 0x10000000, }; enum JxxRuntimeStage { INIT_STAGE = 0, RUNNING_STAGE = 1, }; /** * @brief * * @param attr * @param jts * @return JxxRuntime* */ JXXAPI JxxRuntime* JxxCreateRuntime(JsRuntimeAttributes attr, JsThreadServiceCallback jts); /** * @brief * * @return JxxRuntime* */ JXXAPI JxxRuntime* JxxGetCurrentRuntime(); /** * @brief * * @param runtime * @return JsContextRef */ JXXAPI JsContextRef JxxCreateContext(JxxRuntime* runtime = nullptr); JXXAPI JsValueRef JxxAllocString(JxxCharPtr ptr, size_t len = 0); JXXAPI JsPropertyIdRef JxxAllocPropertyId(JxxCharPtr ptr, size_t len = 0); JXXAPI JsValueRef JxxQueryProto(JxxCharPtr ptr); JXXAPI JsValueRef JxxRegisterProto(JxxCharPtr ptr, JsValueRef proto); JXXAPI JsValueRef JxxAllocSymbol(JxxCharPtr ptr); JXXAPI JsValueRef JxxRunScript(JsValueRef code, JsValueRef uri); JXXAPI JsValueRef JxxJsonParse(JsValueRef code); JXXAPI JsValueRef JxxJsonStringify(JsValueRef target); JXXAPI JsValueRef JxxReadFileContent(JxxCharPtr path, bool binary_mode = false); struct JxxParents { size_t Count; JxxClassId* ClassIDs; }; struct JxxExport { JxxNamePtr Name; JxxFunction Callee; }; struct JxxExports { JxxCount Count; const JxxExport* Entries; }; struct JxxClassDefinition { JxxClassId ClassId; JxxNamePtr UncName; JxxExports Methods; JxxExports Functions; JxxParents Parents; }; template <typename CXX> JXXAPI JxxClassDefinition JXX_DEFINITION_OF_() { static const JxxClassDefinition out = { (JxxClassId)& JXX_DEFINITION_OF_ CXX::__JS_UNCNAME__, CXX::__JS_METHODS__(), CXX::__JS_FUNCTIONS__(), CXX::__JS_PARENTS__() }; return out; } #define jxx_clsid_of_(X) ((JXX_DEFINITION_OF_ #define jxx_clsdef_of_(X) (jxx_clsid_of_(X)()) enum JxxMixinOptions { MIXIN_METHOD = 1, // class method MIXIN_FUNCTION = 2, // class static function }; #define DEFINE_CLASS_NAME(name) static inline JxxNamePtr __JS_UNCNAME__ = #name; #define NO_CLASS_NAME() static inline JxxNamePtr __JS_UNCNAME__ = nullptr; /** * @brief IJxxObject interface. All native object assigned to JS object must be inherit from this. * At the same time, the dynamic type convertion(like RTTI) depends on it. * @see IJxxObject::QueryClass * */ class IJxxObject { public: NO_CLASS_NAME(); static JxxExports __JS_METHODS__() { return {}; }; static JxxExports __JS_FUNCTIONS__() { return {}; }; static JxxParents __JS_PARENTS__() { return {}; }; public: virtual ~IJxxObject() {}; virtual JxxRefCount AddRef() = 0; virtual JxxRefCount Release() = 0; virtual void* QueryClass(JxxClassId clsid) { if (clsid == &JXX_DEFINITION_OF_ return this; return nullptr; } }; /** * @brief * * @param clsid * @return JxxClassDefinition */ JXXAPI JxxClassDefinition JxxQueryClass(JxxClassId clsid); /** * @brief * * @param object * @param clsid * @param MixinOptions * @return JXXAPI JxxMixinObject */ JXXAPI int JxxMixinObject(JsValueRef object, JxxClassId clsid, int MixinOptions); /** * @brief The shared pointer of IJxxObject * * @tparam JxxObject_ Any class inherit from IJxxObject */ template <typename JxxObject_> class JxxObjectPtr { protected: JxxObject_* nake_ = nullptr; public: JxxObject_* get() const { return nake_; } JxxObjectPtr() = default; JxxObjectPtr(JxxObject_* ptr) { reset(ptr, true); } JxxObjectPtr(const JxxObjectPtr& r) { reset(r.get(), true); } JxxObjectPtr(JxxObjectPtr&& r) { nake_ = r.detach(); } template <typename K> JxxObjectPtr(const JxxObjectPtr r) { reset(r); } template <typename K> JxxObjectPtr(JxxObjectPtr r) { reset(r); } ~JxxObjectPtr() { reset(); } ////////////////////////////////////////////////// JxxObjectPtr& attach(JxxObject_* ptr) { return reset(ptr, false); } JxxObject_* detach() { return std::exchange(nake_, nullptr); } JxxObjectPtr& reset() { auto old = std::exchange(nake_, nullptr); if (old) old->Release(); return *this; } JxxObjectPtr& reset(JxxObject_* ptr, bool ref) { auto old = std::exchange(nake_, ptr); if (ptr && ref) ptr->AddRef(); if (old) old->Release(); return *this; } template <typename K> JxxObjectPtr& reset(K* ptr, bool ref) { JxxObject_* np = query_cast(ptr); return reset(np, ref); } template <typename K> JxxObjectPtr& reset(const JxxObjectPtr ptr) { JxxObject_* np = query_cast(ptr.get()); return reset(np, true); } template <typename K> JxxObjectPtr& reset(JxxObjectPtr ptr) { JxxObject_* np = query_cast(ptr.get()); if (np) ptr.detach(); return reset(np, false); } ////////////////////////////////////////////////// JxxObject_* operator->() { return nake_; } const JxxObject_* operator->() const { return nake_; } ////////////////////////////////////////////////// operator bool() const { return nake_ != nullptr; } // operator JxxObject_* () { return nake_; } };
c
10
0.639608
98
23.983936
249
starcoderdata
/* * This header is generated by classdump-dyld 1.0 * on Sunday, June 7, 2020 at 11:12:36 AM Mountain Standard Time * Operating System: Version 13.4.5 (Build 17L562) * Image Source: /System/Library/Frameworks/Metal.framework/Metal * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by */ #import @class MTLIOAccelDevice; @interface MTLIOAccelDeviceShmem : NSObject { MTLIOAccelDeviceShmemPrivate* _priv; MTLIOAccelDevice* _device; unsigned _shmemID; unsigned _shmemSize; void* _virtualAddress; BOOL purgeable; } @property (readonly) void* virtualAddress; //@synthesize virtualAddress=_virtualAddress - In the implementation block @property (readonly) unsigned shmemID; //@synthesize shmemID=_shmemID - In the implementation block @property (readonly) unsigned shmemSize; //@synthesize shmemSize=_shmemSize - In the implementation block -(void)dealloc; -(void*)virtualAddress; -(id)initWithDevice:(id)arg1 shmemSize:(unsigned)arg2 ; -(unsigned)shmemID; -(unsigned)shmemSize; @end
c
6
0.741364
130
32.205882
34
starcoderdata
from PyQt4 import QtCore, QtGui import time from Realtime_Server import Databaze_2 import MySQLdb try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class DETAIL(object): def setupUi(self, MainWindow,clas): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.setFixedSize(210, 320) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.bg = QtGui.QLabel(self.centralwidget) self.bg.setGeometry(QtCore.QRect(0, 0, 210, 320)) self.bg.setText(_fromUtf8("")) self.bg.setPixmap(QtGui.QPixmap(_fromUtf8("teacherBackground_2"))) self.bg.setObjectName(_fromUtf8("bg")) self.verticalLayoutWidget = QtGui.QWidget(self.centralwidget) self.verticalLayoutWidget.setGeometry(QtCore.QRect(20, 50, 170, 200)) self.verticalLayoutWidget.setObjectName(_fromUtf8("verticalLayoutWidget")) self.verticalLayout = QtGui.QVBoxLayout(self.verticalLayoutWidget) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.la2 = QtGui.QLabel(self.centralwidget) self.la2.setGeometry(QtCore.QRect(20, 20, 250, 30)) self.la2.setObjectName(_fromUtf8("textEdit")) self.la2.setText("FRA "+ str(clas)) self.la2.setStyleSheet("color: white;font-size: 15pt") self.CLASSPROFILE = QtGui.QPushButton(self.verticalLayoutWidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.CLASSPROFILE.sizePolicy().hasHeightForWidth()) self.CLASSPROFILE.setSizePolicy(sizePolicy) self.CLASSPROFILE.setObjectName(_fromUtf8("CLASSPROFILE")) self.verticalLayout.addWidget(self.CLASSPROFILE) self.STUDENTPROFILE = QtGui.QPushButton(self.verticalLayoutWidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.STUDENTPROFILE.sizePolicy().hasHeightForWidth()) self.STUDENTPROFILE.setSizePolicy(sizePolicy) self.STUDENTPROFILE.setObjectName(_fromUtf8("STUDENTPROFILE")) self.verticalLayout.addWidget(self.STUDENTPROFILE) self.SHOWQUESTION = QtGui.QPushButton(self.verticalLayoutWidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.SHOWQUESTION.sizePolicy().hasHeightForWidth()) self.SHOWQUESTION.setSizePolicy(sizePolicy) self.SHOWQUESTION.setObjectName(_fromUtf8("SHOWQUESTION")) self.verticalLayout.addWidget(self.SHOWQUESTION) self.StatRealTimeUnderstand = QtGui.QProgressBar(self.verticalLayoutWidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.StatRealTimeUnderstand.sizePolicy().hasHeightForWidth()) self.StatRealTimeUnderstand.setSizePolicy(sizePolicy) self.StatRealTimeUnderstand.setProperty("value", 24) self.StatRealTimeUnderstand.setObjectName(_fromUtf8("StatRealTimeUnderstand")) self.StatRealTimeUnderstand.setValue(0) self.verticalLayout.addWidget(self.StatRealTimeUnderstand) self.back1 = QtGui.QPushButton(self.centralwidget) self.back1.setGeometry(QtCore.QRect(100, 270, 80, 20)) self.back1.setObjectName(_fromUtf8("BACK")) self.label = QtGui.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(60, 220, 71, 21)) font = QtGui.QFont() font.setPointSize(10) self.label.setFont(font) self.label.setObjectName(_fromUtf8("label")) self.label.setStyleSheet("color: gray;font-size: 10pt") self.amount = QtGui.QLabel(self.centralwidget) self.amount.setGeometry(QtCore.QRect(120, 240, 150, 15)) font = QtGui.QFont() font.setPointSize(10) self.amount.setFont(font) self.amount.setObjectName(_fromUtf8("amount")) self.amount.setStyleSheet("color: black;font-size: 8pt") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 356, 21)) self.menubar.setObjectName(_fromUtf8("menubar")) MainWindow.setMenuBar(self.menubar) self.statusbar = QtGui.QStatusBar(MainWindow) self.statusbar.setObjectName(_fromUtf8("statusbar")) MainWindow.setStatusBar(self.statusbar) self.CLASSPROFILE.setStyleSheet("background-color: green;color: white;font-size: 11pt;border: white") self.STUDENTPROFILE.setStyleSheet("background-color: green;color: white;font-size: 11pt;border: white") self.SHOWQUESTION.setStyleSheet("background-color: green;color: white;font-size: 11pt;border: white") self.back1.setStyleSheet("background-color: green;color: white;font-size: 11pt;border: white") datetime = time.asctime( time.localtime(time.time())) #Tue Nov 08 12:41:18 2016 datetime = datetime[20:24]+"-"+str(self.monthToNum(datetime[4:7]))+"-"+datetime[8:10]+" "+datetime[11:19] database2 = Databaze_2() l2 = database2.Oneshot(t=datetime[:10],sid=clas,time=float(datetime[11:19][:5].replace(":","."))) self.StatRealTimeUnderstand.setValue(l2[2]) self.amount.setText(_translate("MainWindow", "amount "+str(l2[0])+" / "+str(int(l2[0]+l2[1])), None)) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def monthToNum(self,shortMonth): return{'Jan' : 1,'Feb' : 2,'Mar' : 3,'Apr' : 4,'May' : 5,'Jun' : 6, 'Jul' : 7,'Aug' : 8,'Sep' : 9, 'Oct' : 10,'Nov' : 11,'Dec' : 12}[shortMonth] def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None)) self.CLASSPROFILE.setText(_translate("MainWindow", "Class Statistic", None)) self.STUDENTPROFILE.setText(_translate("MainWindow", "Student Profile", None)) self.SHOWQUESTION.setText(_translate("MainWindow", "Question", None)) self.back1.setText(_translate("MainWindow", "Back", None)) self.label.setText(_translate("MainWindow", "Understand", None)) if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) MainWindow = QtGui.QMainWindow() ui = DETAIL() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
python
18
0.689345
152
49.753521
142
starcoderdata
#include "modules/signaling_module.h" namespace net_blocks { signaling_module signaling_module::instance; void signaling_module::init_module(void) { framework::instance.register_module(this); // Field to communicate to with the reliable delivery module net_packet.add_member("is_signaling", new generic_integer_member 0); } module::hook_status signaling_module::hook_establish(builder::dyn_var c, builder::dyn_var h, builder::dyn_var<unsigned int> a, builder::dyn_var<unsigned int> sa) { if (!use_signaling_packet) { conn_layout.get(c, "callback_f")(QUEUE_EVENT_ESTABLISHED, c); } else { } return module::hook_status::HOOK_CONTINUE; } module::hook_status signaling_module::hook_ingress(packet_t) { return module::hook_status::HOOK_CONTINUE; } }
c++
12
0.730083
104
28
29
starcoderdata
using static System.Math; // ReSharper disable UnusedType.Global // ReSharper disable NotAccessedField.Local // ReSharper disable InconsistentNaming namespace MathCore.DSP.Fourier { /// фильтр Фурье public class ElementaryFilter { /// значение private double _ReValue; /// значение private double _ImValue; /// выборки private readonly int _N; /// спектральных компонент в спектре #pragma warning disable IDE0052 // Удалить непрочитанные закрытые члены private readonly int _M; #pragma warning restore IDE0052 // Удалить непрочитанные закрытые члены /// фазы private readonly double _dPhi; /// отсчёта private int _SamplesIndex; /// фильтра public Complex Value => new(_ReValue / _N, _ImValue / _N); /// нового элементарного фильтра преобразования Фурье /// <param name="N">Размер выборки /// <param name="M">Размер спектра public ElementaryFilter(int N, int M) { _M = M; _N = N; _dPhi = M * Consts.pi2 / N; } /// фильтра (сброс состояния) public void Initialize() { _ReValue = 0; _ImValue = 0; _SamplesIndex = 0; } /// очередного значения /// <param name="value">Значение обрабатываемого отсчёта public Complex Process(double value) { var arg = _dPhi * _SamplesIndex++; _ReValue += Cos(arg) * value; _ImValue += Sin(arg) * value; return Value; } } }
c#
13
0.607407
94
33.322034
59
starcoderdata
package charond import ( "context" "database/sql" "fmt" "net/url" "time" "github.com/piotrkowalczuk/charon" "github.com/piotrkowalczuk/charon/internal/model" "github.com/piotrkowalczuk/charon/internal/password" "github.com/piotrkowalczuk/mnemosyne/mnemosynerpc" "go.uber.org/zap" "google.golang.org/grpc" ) func initPostgres(address string, test bool, logger *zap.Logger) (*sql.DB, error) { db, err := sql.Open("postgres", address) if err != nil { return nil, fmt.Errorf("connection failure: %s", err.Error()) } if err = db.Ping(); err != nil { cancel := time.NewTimer(10 * time.Second) attempts := 1 PingLoop: for { select { case <-time.After(1 * time.Second): if err := db.Ping(); err != nil { attempts++ continue PingLoop } break PingLoop case <-cancel.C: return nil, fmt.Errorf("postgres connection failed after %d attempts", attempts) } } } if test { if err = teardownDatabase(db); err != nil { return nil, err } logger.Info("database has been cleared upfront") } if err = setupDatabase(db); err != nil { return nil, err } u, err := url.Parse(address) if err != nil { return nil, err } username := "" if u.User != nil { username = u.User.Username() } logger.Info("postgres connection has been established", zap.String("host", u.Host), zap.String("username", username)) return db, nil } func initMnemosyne(address string, logger *zap.Logger, opts []grpc.DialOption) (mnemosynerpc.SessionManagerClient, *grpc.ClientConn) { if address == "" { logger.Error("missing mnemosyne address") } conn, err := grpc.Dial(address, opts...) if err != nil { logger.Error("mnemosyne dial falilure", zap.Error(err), zap.String("address", address)) } logger.Info("rpc connection to mnemosyne has been established", zap.String("address", address)) return mnemosynerpc.NewSessionManagerClient(conn), conn } func initHasher(cost int, logger *zap.Logger) password.Hasher { bh, err := password.NewBCryptHasher(cost) if err != nil { logger.Fatal("hasher initialization failure", zap.Error(err)) } return bh } func initPermissionRegistry(r model.PermissionProvider, permissions charon.Permissions, logger *zap.Logger) (pr model.PermissionRegistry) { pr = model.NewPermissionRegistry(r) created, untouched, removed, err := pr.Register(context.TODO(), permissions) if err != nil { logger.Fatal("permission registry initialization failure", zap.Error(err)) } logger.Info("charon permissions has been registered", zap.Int64("created", created), zap.Int64("untouched", untouched), zap.Int64("removed", removed)) return }
go
16
0.698311
151
25.65
100
starcoderdata
@Override // documentation inherited protected void modelLoaded (Model model) { // in the game, we can lock the bounds and transforms of props // because we know they won't move super.modelLoaded(model); if (!_editorMode) { updateWorldVectors(); model.lockInstance(); } else if (Boolean.parseBoolean( model.getProperties().getProperty("editor_handle"))) { // the prop requires a handle to manipulate it in the editor Box handle = new Box("handle", new Vector3f(), 0.5f, 0.5f, 0.5f); handle.setModelBound(new BoundingBox()); handle.updateModelBound(); handle.setLightCombineMode(LightState.OFF); attachChild(handle); handle.updateRenderState(); } }
java
12
0.593712
77
40.4
20
inline
var profile = (function(){ var testResourceRe = /^bootstrap\/tests\//; var ignore = function(filename, mid){ var list = { "bootstrap/.gitignore" : true }; return (mid in list) || /^bootstrap\/vendor\//.test(mid); }; var test = function(filename, mid){ var list = { "bootstrap/tests" : true, "bootstrap/experimental": true }; return (mid in list) || testResourceRe.test(mid); }; var copyOnly = function(filename, mid){ var list = { "bootstrap/bootstrap.profile" : true, "bootstrap/package.json" : true, "bootstrap/LICENSE" : true, "bootstrap/README.md" : true }; return (mid in list) || /(png|jpg|jpeg|gif|tiff)$/.test(filename); }; var miniExclude = function(filename, mid){ var list = { "bootstrap/LICENCE" : true, "bootstrap/README.md" : true }; return (mid in list); }; return { resourceTags:{ ignore: function(filename, mid){ return ignore(filename, mid); }, test: function(filename, mid){ return test(filename, mid); }, copyOnly: function(filename, mid){ return copyOnly(filename, mid); }, miniExclude: function(filename, mid){ return miniExclude(filename, mid); }, amd: function(filename, mid){ return !test(filename, mid) && !copyOnly(filename, mid) && !ignore(filename, mid) && (/\.js$/).test(filename); } } }; })();
javascript
21
0.494528
129
27.235294
68
starcoderdata
void setup_test(void) { interrupt_init(); soft_timer_init(); // Purposely start close to the rollover _test_soft_timer_set_counter(UINT32_MAX - 2000); }
c
7
0.689441
50
22.142857
7
inline
export default class WhiteCard { constructor(id, text) { this.id = id; this.text = text; this.color = "white"; } } export function parseWhiteCardList(json) { let cards = []; for (let c of json) { cards.push(new WhiteCard(c.id, c.text)); } return cards; }
javascript
12
0.618375
44
17.933333
15
starcoderdata
using System.Collections.Generic; using Newtonsoft.Json; namespace NeteaseCloudMusic.Global.Model { /// /// 代表歌手的Model /// public class Artist { public long Id { get; set; } /// /// 代表歌手名 /// public string Name { get;set; } /// /// 歌手图片 /// [JsonIgnore] public string ArtistImage { get;set; } /// /// 歌手图片,遗留的就不改了 /// public string PicUrl { get { return ArtistImage; } set { ArtistImage = value; } } public List HotMusics { get; set; } /// /// mv数量 /// public int MvCount { get; set; } /// /// 音乐数量 /// public int MusicCount { get; set; } /// /// 专辑数量 /// public int AlbumCount { get; set; } /// /// 热度 /// public int HotScore { get; set; } /// /// 如果歌手有账户,对应账户id /// public long AccountId { get; set; } } }
c#
12
0.453818
60
21.916667
60
starcoderdata
def fill_in_the_blank_sized( dataset, size_bins=(1, 2, 4, 8, 16, 32, 64, 128, 256, 512), text_key='text', label='fill: '): """Fill in the blank preprocessor that labels blank with a binned size. The actual blank size is sampled uniformly from the inclusive range of the min and max bin. The blank is then filled in with the closest bin size to the actual blank size. Args: dataset: a tf.data.Dataset, the dataset to preprocess. size_bins: a list, a list of blank sizes to select from when labelling the blank. text_key: a string, the key for the text feature to preprocess in the dataset examples. label: a string, the label to prepend to the inputs. Returns: a tf.data.Dataset """ bins = sorted(size_bins) def my_fn(x): """Apply transformation.""" words = x['words'] n_words = tf.size(words) blank_size = tf.random.uniform( [], minval=bins[0], maxval=tf.math.minimum(n_words, bins[-1]), dtype=tf.dtypes.int32) bin_delta = tf.math.abs(bins - blank_size) bin_ = tf.gather(bins, tf.argmin(bin_delta)) blank_start = tf.random.uniform( [], minval=0, maxval=tf.math.maximum(0, n_words-blank_size) + 1, dtype=tf.dtypes.int32) pre_blank = tf.strings.reduce_join(words[0:blank_start], separator=' ') post_blank = tf.strings.reduce_join( words[blank_start+blank_size:], separator=' ') blank = tf.strings.format('_{}_', bin_) # We strip to handle cases where blank is at beginning or end. input_ = tf.strings.strip( tf.strings.join([pre_blank, blank, post_blank], ' ')) input_ = tf.strings.join([label, input_]) target = tf.strings.reduce_join( words[blank_start:blank_start+blank_size], separator=' ') return { 'inputs': tf.strings.strip(input_), 'targets': tf.strings.strip(target)} dataset = _split_text_to_words(dataset, text_key, min_num_words=2) # Filter out examples with fewer words than the minimum. dataset = dataset.filter(lambda x: tf.size(x['words']) >= bins[0]) dataset = dataset.map(my_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE) return dataset
python
14
0.652554
80
37.821429
56
inline
#include "main-widget.h" #include "desktop-view.h" #include MainWidget::MainWidget(QWidget *parent) : QMainWindow(parent), mDesktopView (new DesktopView(this)) { setContentsMargins(0, 0, 0, 0); mModel = new QFileSystemModel(this); setCentralWidget(mDesktopView); mDesktopView->setModel(mModel); mDesktopView->setRootIndex(mModel->setRootPath("/home/dingjing/")); }
c++
9
0.733496
99
28.214286
14
starcoderdata
def metrics(self, metric_names=None): """ Provides access to task metrics. Endpoint: [GET] /jobs/:jobid/vertices/:vertexid/metrics Returns ------- dict Task metrics. """ if metric_names is None: metric_names = self.metric_names() params = {"get": ",".join(metric_names)} query_result = _execute_rest_request( url=f"{self.prefix_url}/metrics", params=params ) result = {} for elem in query_result: metric_name = elem.pop("id") result[metric_name] = elem["value"] return result
python
11
0.518462
63
27.304348
23
inline
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class CardUserInfo(object): def __init__(self): self._user_uni_id = None self._user_uni_id_type = None @property def user_uni_id(self): return self._user_uni_id @user_uni_id.setter def user_uni_id(self, value): self._user_uni_id = value @property def user_uni_id_type(self): return self._user_uni_id_type @user_uni_id_type.setter def user_uni_id_type(self, value): self._user_uni_id_type = value def to_alipay_dict(self): params = dict() if self.user_uni_id: if hasattr(self.user_uni_id, 'to_alipay_dict'): params['user_uni_id'] = self.user_uni_id.to_alipay_dict() else: params['user_uni_id'] = self.user_uni_id if self.user_uni_id_type: if hasattr(self.user_uni_id_type, 'to_alipay_dict'): params['user_uni_id_type'] = self.user_uni_id_type.to_alipay_dict() else: params['user_uni_id_type'] = self.user_uni_id_type return params @staticmethod def from_alipay_dict(d): if not d: return None o = CardUserInfo() if 'user_uni_id' in d: o.user_uni_id = d['user_uni_id'] if 'user_uni_id_type' in d: o.user_uni_id_type = d['user_uni_id_type'] return o
python
14
0.550842
83
26
55
starcoderdata
@{ Layout = null; } <!DOCTYPE html> <html lang="ru"> <meta name="viewport" content="width=device-width" /> English <link rel="stylesheet" href="../../css/language/lang.css" asp-append-version="true"> <link rel="stylesheet" href="../../css/base.css" asp-append-version="true"> @await Html.PartialAsync("_CssHeaderPartial") @await Html.PartialAsync("_CssLanguagePartial") @await Html.PartialAsync("_HeaderPartial") <div class="levels"> @await Html.PartialAsync("_LevelPartial", null, new ViewDataDictionary(ViewData) { { "level", "A1" }, { "themes", Model } }) @await Html.PartialAsync("_LevelPartial", null, new ViewDataDictionary(ViewData) { { "level", "A2" }, { "themes", Model } }) @await Html.PartialAsync("_LevelPartial", null, new ViewDataDictionary(ViewData) { { "level", "B1" }, { "themes", Model } }) @await Html.PartialAsync("_LevelPartial", null, new ViewDataDictionary(ViewData) { { "level", "B2" }, { "themes", Model } })
c#
24
0.636955
132
42.08
25
starcoderdata
/* * Copyright (c) 2012 eXtensible Catalog Organization. * * This program is free software; you can redistribute it and/or modify it * under the terms of the MIT/X11 license. The text of the license can be * found at http://www.opensource.org/licenses/mit-license.php. */ package org.oclc.circill.toolkit.common.ncip; import org.oclc.circill.toolkit.common.base.ProtocolVersion; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; /** * Default NCIP {@link ProtocolVersion}. */ public class DefaultNCIPVersion implements ProtocolVersion { protected static final Map<String, DefaultNCIPVersion> VERSIONS_BY_ATTRIBUTE = new HashMap<>(); protected String versionAttribute; protected DefaultNCIPVersion canonicalVersion; /** * Construct an uninitialized instance. */ public DefaultNCIPVersion() { // Do nothing } /** * Construct an instance with provided version attribute and canonical version attribute. * @param versionAttribute the version attribute * @param canonicalVersion the canonical version attribute */ public DefaultNCIPVersion(final String versionAttribute, final DefaultNCIPVersion canonicalVersion) { this.versionAttribute = versionAttribute; this.canonicalVersion = canonicalVersion; synchronized (DefaultNCIPVersion.class) { if (!VERSIONS_BY_ATTRIBUTE.containsKey(this.versionAttribute)) { VERSIONS_BY_ATTRIBUTE.put(this.versionAttribute, this); } } } /** * Construct an instance with provided version attribute and a null canonical version attribute. * @param versionAttribute the version attribute */ public DefaultNCIPVersion(final String versionAttribute) { this(versionAttribute, null); } public static final DefaultNCIPVersion VERSION_1_0 = new DefaultNCIPVersion("http://www.niso.org/ncip/v1_0/imp1/dtd/ncip_v1_0.dtd"); public static final DefaultNCIPVersion VERSION_1_01 = new DefaultNCIPVersion("http://www.niso.org/ncip/v1_01/imp1/dtd/ncip_v1_01.dtd"); public static final DefaultNCIPVersion VERSION_2_0 = new DefaultNCIPVersion("http://www.niso.org/schemas/ncip/v2_0/imp1/xsd/ncip_v2_0.xsd"); public static final DefaultNCIPVersion VERSION_2_01 = new DefaultNCIPVersion("http://www.niso.org/schemas/ncip/v2_0/imp1/xsd/ncip_v2_01.xsd"); public static final DefaultNCIPVersion VERSION_2_02 = new DefaultNCIPVersion("http://www.niso.org/schemas/ncip/v2_0/imp1/xsd/ncip_v2_02.xsd"); public String getVersionAttribute() { return this.versionAttribute; } public DefaultNCIPVersion getCanonicalVersion() { return this.canonicalVersion; } /** * Find the {@link DefaultNCIPVersion} instance for the provided version attribute value. * @param versionAttribute the value of the attribute on the message * @return the {@link DefaultNCIPVersion} */ public static DefaultNCIPVersion findByVersionAttribute(final String versionAttribute) { return VERSIONS_BY_ATTRIBUTE.get(versionAttribute); } /** * Generic toString() implementation. * * @return String */ @Override public String toString() { return ToStringBuilder.reflectionToString(this); } @Override public boolean equals(final Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } final DefaultNCIPVersion rhs = (DefaultNCIPVersion) obj; return new EqualsBuilder().append(versionAttribute, rhs.versionAttribute).append(canonicalVersion, rhs.canonicalVersion).isEquals(); } @Override public int hashCode() { final int result = new HashCodeBuilder(1018898499, 1938329131).append(versionAttribute).append(canonicalVersion).toHashCode(); return result; } }
java
13
0.699138
146
32.96748
123
starcoderdata
/*Track class represents a music track, only MP3 and WAV is supported */ using System; namespace GamingMusicPlayer.MusicPlayer { public class Track : ICloneable { private string path; private string artist; //can be null private double bpm; //can be null private double spectrIrr; //can be null private int length; //in ms private string error_msg; public short[] Data { get { return readDataFromFile(); } } public double ZCR { get; set; } public double SpectralIrregularity { get { return spectrIrr; } set { this.spectrIrr = value; } } public double BPM { get { return bpm; } set { this.bpm = value; } } public string Path { get { return path; } set { this.path = value; if (!fixLength()) { this.length = -1; } validateFileFormat_throws(); } } public string Artist { get { var tfile = TagLib.File.Create(path); string artist = tfile.Tag.FirstPerformer; if (artist == null) artist = ""; return artist; } set { this.artist = value; } } public string Album { get { var tfile = TagLib.File.Create(path); string album = tfile.Tag.Album; if (album == null) album = ""; return album; } } public string Name { get { string[] slashTokens = path.Split('\\'); if (slashTokens.Length == 0) return ""; string name = ""; string[] dotTokens = slashTokens[slashTokens.Length - 1].Split('.'); if (dotTokens.Length > 0) { for(int i=0; i < dotTokens.Length - 1; i++) { name += dotTokens[i]; if (i != dotTokens.Length - 2) name += "."; } } return name; } } public string ErrorMsg { get { return error_msg; } } public int Length { get { return this.length; } } public string Format { get { string[] tokens = path.Split('.'); string fileType = "NA"; if (tokens.Length > 0) { fileType = tokens[tokens.Length - 1]; } fileType = fileType.ToUpper(); return fileType; } } public Track(string path) { Random rng = new Random(); this.path = path; this.artist = null; this.bpm = -1; this.ZCR = -1; this.spectrIrr = -1; this.error_msg = "no error"; if (!fixLength()) { this.length = -1; } validateFileFormat_throws(); } private Track(Track t) { if (t.artist == null) this.artist = null; else this.artist = (string)t.artist.Clone(); this.bpm = t.bpm; this.ZCR = t.ZCR; this.spectrIrr = t.spectrIrr; this.path = (string)t.path.Clone(); this.length = t.length; } public object Clone() { return new Track(this); } private bool fixLength() { this.length = MusicFileInfo.getLength(path); if (length < 0) { if (this.Format.Equals("MP3")) { try { this.length = (int)new NAudio.Wave.Mp3FileReader(path).TotalTime.TotalMilliseconds; } catch (Exception e) { this.length = 0; } } else if (this.Format.Equals("WAV")) { try { this.length = (int)new NAudio.Wave.WaveFileReader(path).TotalTime.TotalMilliseconds; } catch (Exception e) { this.length = 0; } } if (this.length < 0) { error_msg = MusicFileInfo.error_msg; return false; } } return true; } private void validateFileFormat_throws()//throws exception if file type is not supported { if (!MusicFileInfo.isCorrectFormat(path)) { error_msg = MusicFileInfo.error_msg; throw new FileFormatNotSupported(error_msg); } } private short[] readDataFromFile() { short[] data = null; NAudio.Wave.WaveStream reader = null; if (this.Format.Equals("MP3")) { reader = new NAudio.Wave.Mp3FileReader(this.Path); } else if (this.Format.Equals("WAV")) { reader = new NAudio.Wave.WaveFileReader(this.Path); } if (reader != null) { byte[] buffer = new byte[reader.Length]; int read = reader.Read(buffer, 0, buffer.Length); data = new short[read / sizeof(short)]; Buffer.BlockCopy(buffer, 0, data, 0, read); } return data; } } }
c#
22
0.389019
108
24.882591
247
starcoderdata
#include "splines.hpp" #include #include #include #include "macros.hpp" using namespace splines; size_t splines::num_knots(size_t order, size_t num_break_points) { return num_break_points + 2*(order-1); } size_t splines::num_basis(size_t order, size_t num_break_points) { return num_break_points + order - 2; } void splines::gen_knots_ref(size_t order, const std::vector & break_points, std::vector & knots) { size_t deg = order-1; size_t K = num_knots(order, break_points.size()); knots.resize(K); // repeat end points for ( size_t j = 0; j < order-1; ++j ) { knots[j] = break_points.front(); knots[K-1-j] = break_points.back(); } // copy middle std::copy(break_points.begin(), break_points.end(), knots.begin()+deg); } void splines::gen_unif_knots_ref(size_t order, size_t num_break_points, double a, double b, std::vector & knots) { size_t deg = order-1; size_t K = num_break_points + 2*deg; knots.resize(K); // repeat end points for ( size_t j = 0; j < order-1; ++j ) { knots[j] = a; knots[K-1-j] = b; } double h = (b-a) / (num_break_points - 1); for ( size_t j = 0; j < num_break_points; ++j ) { knots[deg+j] = a + h*j; } } double splines::omega(double x, size_t i, size_t ord, const std::vector & knots) { double a = knots[i]; double b = knots[i+ord-1]; if ( a < b ) { return (x-a)/(b-a); } else { return 0.0; } } double splines::basis(double x, size_t i, size_t ord, const std::vector & knots) { if ( ord == 1 ) { double a = knots[i]; double b = knots[i+1]; if ( a <= x && x < b ) { return 1.0; } else { return 0.0; } } else { double om0 = omega(x, i, ord, knots); double om1 = omega(x, i+1, ord, knots); double B0 = basis(x, i, ord-1, knots); double B1 = basis(x, i+1, ord-1, knots); return om0 * B0 + (1-om1) * B1; } } double splines::spline(double x, size_t ord, const std::vector & knots, const std::vector & weights) { double y = 0.0; for ( size_t i = 0; i < weights.size(); ++i ) { y += basis(x, i, ord, knots) * weights[i]; } return y; } double Spline::operator()(double x) const { return spline(x, order, knots, weights); } Spline splines::import_spline(std::string filename) { Spline spl; size_t num_break_points; std::ifstream file(filename.c_str()); // read order if ( file.good() ) { std::string order_str; std::getline(file, order_str); std::stringstream(order_str) >> spl.order; } else { throw std::runtime_error("unable to read order from spline file"); } // function to read a vector auto read_vec = [](const std::string & line) -> std::vector { std::vector vec; std::stringstream ss(line); std::string word; while ( ss.good() ) { std::getline(ss, word, ' '); vec.push_back(atof(word.c_str())); } return vec; }; // read break points if ( file.good() ) { std::string bp_line; std::getline(file, bp_line); std::vector break_points = read_vec(bp_line); num_break_points = break_points.size(); gen_knots_ref(spl.order, break_points, spl.knots); } else { throw std::runtime_error("unable to read break points from spline file"); } // read weights if ( file.good() ) { std::string w_line; std::getline(file, w_line); spl.weights = read_vec(w_line); } else { throw std::runtime_error("unable to read weights from spline file"); } // check that the number of weights is correct if ( spl.weights.size() != num_basis(spl.order, num_break_points) ) { throw std::runtime_error("incompatible order, weihts and break points"); } return spl; } /// methods for piecewise linear function inline double linfun(double x, double x0, double x1, double y0, double y1) { return y0 + (y1-y0)/(x1-x0) * (x-x0); } double PiecewiseLinFunc::operator()(double x) const { size_t n = break_points.size(); if ( n < 2 || n != values_break_points.size() ) { std::logic_error("invalid definition of piecewise linear function" + RIGHT_HERE); } double x0, x1, y0, y1; if ( x < break_points.front() ) { // extrapolate y0 = values_break_points[0]; y1 = values_break_points[1]; x0 = break_points[0]; x1 = break_points[1]; return linfun(x, x0, x1, y0, y1); } // else interpolate // find interval for ( size_t i = 1; i < n; ++i ) { if ( x < break_points[i] ) { y0 = values_break_points[i-1]; y1 = values_break_points[i]; x0 = break_points[i-1]; x1 = break_points[i]; return linfun(x, x0, x1, y0, y1); } } // else, x >= all breakpoints: extrapolate! y0 = values_break_points[n-2]; y1 = values_break_points[n-1]; x0 = break_points[n-2]; x1 = break_points[n-1]; return linfun(x, x0, x1, y0, y1); } PiecewiseLinFunc splines::import_piecewise_lin_fun(std::string filename) { std::ifstream file(filename.c_str()); // call more general function for istream input return import_piecewise_lin_fun(file); } std::list splines::import_multiple_piecewise_lin_funs(std::string filename) { std::ifstream file(filename.c_str()); std::list funlist; while ( file.good() ) { try { PiecewiseLinFunc fun = import_piecewise_lin_fun(file); funlist.push_back(fun); } catch ( std::runtime_error & e ) { // ignore error } } return funlist; } PiecewiseLinFunc splines::import_piecewise_lin_fun(std::istream & in) { PiecewiseLinFunc fun; // function to read a vector auto read_vec = [](const std::string & line) -> std::vector { std::vector vec; std::stringstream ss(line); std::string word; while ( ss.good() ) { std::getline(ss, word, ' '); vec.push_back(atof(word.c_str())); } return vec; }; // read break points if ( in.good() ) { std::string bp_line; std::getline(in, bp_line); fun.break_points = read_vec(bp_line); } else { throw std::runtime_error("unable to read break points from spline file"); } // read weights if ( in.good() ) { std::string val_line; std::getline(in, val_line); fun.values_break_points = read_vec(val_line); } else { throw std::runtime_error("unable to read weights from spline file"); } // check that the number of weights is correct if ( fun.values_break_points.size() != fun.break_points.size() ) { throw std::runtime_error("incompatible order, weihts and break points"); } return fun; }
c++
16
0.613506
95
27.843478
230
starcoderdata
function calculateMMSA(numbers) { var min, max, sum, average, i, length, index, temp, j, firstNum, secondNum; sum = 0; length = numbers.length; for (i = 0; i < length; i += 1) { for (index = i + 1; index < length; index += 1) { if (+numbers[i] > +numbers[index]) { temp = numbers[i]; numbers[i] = numbers[index]; numbers[index] = temp; } } } for (i = 0; i < length; i += 1) { sum += +numbers[i]; } min = +numbers[0]; max = +numbers[numbers.length - 1]; average = +(sum / length); console.log('min=' + min.toFixed(2)); console.log('max=' + max.toFixed(2)); console.log('sum=' + sum.toFixed(2)); console.log('avg=' + average.toFixed(2)); } function calculateMMSAOptimized(numbers) { var min, max, sum, average, i, length, min = +(Math.min(...numbers)); max = +(Math.max(...numbers)); sum = 0; length = numbers.length; for (i = 0; i < length; i += 1) { sum += +numbers[i]; } average = +(sum / length); console.log('min=' + min.toFixed(2)); console.log('max=' + max.toFixed(2)); console.log('sum=' + sum.toFixed(2)); console.log('avg=' + average.toFixed(2)); }
javascript
12
0.571429
51
19.392857
56
starcoderdata
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by // #import "NSObject.h" @class NSMutableSet, TCXmlTextWriterProvider; __attribute__((visibility("hidden"))) @interface TCXmlStreamWriter : NSObject { TCXmlTextWriterProvider *mTextWriterProvider; unsigned int mCurrentDepth; BOOL mContentAddedToTopElement; NSMutableSet *mAddedIds; } + (BOOL)writeAnchorTargetToStream:(struct _xmlTextWriter *)arg1 name:(id)arg2; + (BOOL)writeDtdToStream:(struct _xmlTextWriter *)arg1 name:(id)arg2 pubid:(id)arg3 sysid:(id)arg4 subset:(id)arg5; + (BOOL)writeNamespaceToStream:(struct _xmlTextWriter *)arg1 prefix:(id)arg2 uri:(const char *)arg3; + (BOOL)writeAttributeToStream:(struct _xmlTextWriter *)arg1 name:(id)arg2 content:(id)arg3 prefix:(id)arg4 ns:(const char *)arg5; + (BOOL)writePlainAttributeToStream:(struct _xmlTextWriter *)arg1 name:(id)arg2 content:(id)arg3; + (BOOL)writeStringToStream:(struct _xmlTextWriter *)arg1 text:(id)arg2; + (BOOL)endElementInStream:(struct _xmlTextWriter *)arg1; + (BOOL)startElementInStream:(struct _xmlTextWriter *)arg1 name:(id)arg2 prefix:(id)arg3 ns:(const char *)arg4; + (BOOL)startPlainElementInStream:(struct _xmlTextWriter *)arg1 name:(id)arg2; + (void)resetElementIds; + (id)newXmlStreamWriterWithZipEntryName:(id)arg1 outputStream:(id)arg2 isCompressed:(BOOL)arg3; - (void).cxx_destruct; - (BOOL)writeAnchorTarget:(id)arg1; - (BOOL)writeDtd:(id)arg1 pubid:(id)arg2 sysid:(id)arg3 subset:(id)arg4; - (BOOL)writeNamespace:(id)arg1 uri:(const char *)arg2; - (BOOL)writeElementId:(id)arg1; - (BOOL)writePlainAttribute:(id)arg1 doubleContent:(double)arg2; - (BOOL)writePlainAttribute:(id)arg1 enumContent:(int)arg2 map:(id)arg3; - (BOOL)writePlainAttribute:(id)arg1 boolContent:(BOOL)arg2; - (BOOL)writePlainAttribute:(id)arg1 intContent:(long long)arg2; - (BOOL)writePlainAttribute:(id)arg1 content:(id)arg2; - (BOOL)writeAttribute:(id)arg1 doubleContent:(double)arg2 prefix:(id)arg3 ns:(const char *)arg4; - (BOOL)writeAttribute:(id)arg1 enumContent:(int)arg2 map:(id)arg3 prefix:(id)arg4 ns:(const char *)arg5; - (BOOL)writeAttribute:(id)arg1 boolContent:(BOOL)arg2 prefix:(id)arg3 ns:(const char *)arg4; - (BOOL)writeAttribute:(id)arg1 intContent:(long long)arg2 prefix:(id)arg3 ns:(const char *)arg4; - (BOOL)writeAttribute:(id)arg1 content:(id)arg2 prefix:(id)arg3 ns:(const char *)arg4; - (BOOL)endElementsToDepth:(unsigned int)arg1; - (unsigned int)currentDepth; - (BOOL)writeString:(id)arg1; - (BOOL)endElement; - (BOOL)startPlainElement:(id)arg1; - (BOOL)startElement:(id)arg1 prefix:(id)arg2 ns:(const char *)arg3; - (BOOL)contentAddedToTopElement; - (struct _xmlTextWriter *)textWriter; - (id)textWriterProvider; - (BOOL)tearDown; - (BOOL)setUp; - (BOOL)isWriting; - (void)dealloc; - (id)initWithTextWriterProvider:(id)arg1; @end
c
7
0.748522
130
45.370968
62
starcoderdata
<?php namespace app\admin\model\terminal; use app\admin\model\SystemAdmin; use app\common\model\TimeModel; class Brand extends TimeModel { protected $name = "terminal_brand"; protected $deleteTime = false; //关联品牌 public function agent() { return $this->belongsToMany(SystemAdmin::class, 'agent_brand', 'agent_id', 'brand_id'); } //写入后 public static function onAfterWrite($model) { $res = SystemAdmin::select()->toArray(); $model->agent()->sync(array_column($res, 'id')); } }
php
13
0.639719
95
18.655172
29
starcoderdata
package main import ( "encoding/hex" "fmt" "os" "github.com/go-git/go-billy/v5/osfs" "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing/cache" "github.com/go-git/go-git/v5/storage/filesystem" ) func GitOpenWithCustomWorktreeDir(gitDir, worktreeDir string) (*git.Repository, error) { worktreeFilesystem := osfs.New(worktreeDir) storage := filesystem.NewStorage(osfs.New(gitDir), cache.NewObjectLRUDefault()) return git.Open(storage, worktreeFilesystem) } func newHash(s string) (plumbing.Hash, error) { var h plumbing.Hash b, err := hex.DecodeString(s) if err != nil { return h, err } copy(h[:], b) return h, nil } func do(gitDir, workTreeDir, commit string) error { if repository, err := GitOpenWithCustomWorktreeDir(gitDir, workTreeDir); err != nil { return fmt.Errorf("plain open %s failed: %s", workTreeDir, err) } else { hash, err := newHash(commit) if err != nil { return fmt.Errorf("bad commit %q hash: %s", commit, err) } commit, err := repository.CommitObject(hash) if err != nil { return fmt.Errorf("commit object fetch failed: %s", err) } fmt.Printf("-- Commit -> %v\n", commit) } return nil } func main() { if err := do(os.Args[1], os.Args[2], os.Args[3]); err != nil { fmt.Fprintf(os.Stderr, "ERROR: %s\n", err) os.Exit(1) } }
go
12
0.674282
88
22.396552
58
starcoderdata
using System.Diagnostics; using System.Windows; using System.Windows.Controls; namespace DotNetProjects.WPF.Converters.ExtensionMethods { /// /// Extensions to set and get a ListBox's first visible item. /// /// Author: (www.dominikschmidt.net) /// public static class ListBoxExtension { /// /// Sets the first visible item (i.e., scrolls to make /// given item the first visible). /// /// <param name="listBox">The ListBox /// <param name="item">The item to be the first visible public static void SetFirstVisibleItem(this ListBox listBox, object item) { PerformScroll(listBox, item); } /// /// Gets the first visible item. /// /// <param name="listBox">The ListBox /// first visible item or null of there are no items public static object GetFirstVisibleItem(this ListBox listBox) { return listBox.Items.Count > 0 ? listBox.Items[listBox.GetPanelOffset()] : null; } /// /// Gets horizontal or vertical offset (depending on panel orientation). /// /// <param name="listBox">The ListBox /// offset or 0 if no VirtualizingStackPanel was found private static int GetPanelOffset(this ListBox listBox) { VirtualizingStackPanel panel = listBox.GetPanel(); if (panel != null) return (int)((panel.Orientation == Orientation.Horizontal) ? panel.HorizontalOffset : panel.VerticalOffset); else return 0; } /// /// Sets horizontal or vertical offset depending on panel orientation. /// /// <param name="listBox">The ListBox /// <param name="offset">The offset private static void SetPanelOffset(this ListBox listBox, int offset) { VirtualizingStackPanel panel = listBox.GetPanel(); if (panel != null) { if (panel.Orientation == Orientation.Horizontal) panel.SetHorizontalOffset(offset); else panel.SetVerticalOffset(offset); } } /// /// Retrieves the ListBox's items panel as VirtualizingStackPanel. /// /// <param name="listBox">The ListBox /// item panel or null if no VirtualizingStackPanel was found public static VirtualizingStackPanel GetPanel(this ListBox listBox) { VirtualizingStackPanel panel = UIHelpers.TryFindChild if (panel == null) Debug.WriteLine("No VirtualizingStackPanel found for ListBox."); return panel; } /// /// Brings requested item into view as first visible item. /// /// <param name="listBox">The ListBox /// <param name="item">The requested item private static void PerformScroll(ListBox listBox, object item) { // get container for requested item DependencyObject container = listBox.ItemContainerGenerator.ContainerFromItem(item); // container does not exist yet (for example because it is not yet in view) if (container == null) { // scroll item into view... listBox.ScrollIntoView(item); // ...and get its container container = listBox.ItemContainerGenerator.ContainerFromItem(item); } // double-check that container was retrieved if (container != null) { // make sure that item is not only in view, // but that it is indeed the first item visible int index = listBox.ItemContainerGenerator.IndexFromContainer(container); // if panel offset is not equal to index, the // item is in view, but not as first item if (listBox.GetPanelOffset() != index) listBox.SetPanelOffset(index); } } } }
c#
16
0.577499
124
38.219298
114
starcoderdata
#ifndef __INHERITEDIMAGE_H__ #define __INHERITEDIMAGE_H__ #include "Image.h" class InheritedImage : public Image { public: InheritedImage(); InheritedImage(SDL_Rect& position, iPoint positionOffset, bool draggable); InheritedImage(SDL_Rect& position, iPoint positionOffset, SDL_Rect &image_section, bool draggable); InheritedImage(SDL_Rect& position, iPoint positionOffset, p2SString &path, bool draggable); ~InheritedImage(); bool PreUpdate(); bool PostUpdate(); bool Draw(); }; #endif
c
8
0.754902
100
23.333333
21
starcoderdata
<?php namespace app\components\behaviour; use yii\db\Expression; /** * Created by PhpStorm. * User: Rikipm * Date: 13.06.2019 * Time: 15:26 * * Its modified TimestampBehaviour that created for use with date-type columns (timestamp, datetime etc). Standart TimestampBehaviour can work only with int columns if you dont specify value */ class TimestampBehavior extends \yii\behaviors\TimestampBehavior { function __construct(array $config = []) { parent::__construct($config); $this->value = new Expression('NOW()'); } }
php
11
0.695341
190
22.291667
24
starcoderdata
using UnityEngine; using UnityEngine.UI; /// /// Implementation of Managers in POWERGAMESTUDIO namspace /// namespace PowerGameStudio.Systems.Dialogue { public class PGS_DialogueManager : MonoBehaviour { #region Variables private static PGS_DialogueManager _instance; public static PGS_DialogueManager Instance { get { if (_instance == null) { Debug.LogError("PGS_DialogueManager is null."); } return _instance; } } [SerializeField] private GameObject _dilogueCam = null; [SerializeField] private GameObject _dialoguePanel = null; [SerializeField] private Text _dialogueText = null; private PGS_Dialogue _activeDialogue; private bool _engageNPC; private int _currentMessage = 0; #endregion #region Builtin Methods private void Awake() { _instance = this; } private void Update() { if (_engageNPC) { _dilogueCam.SetActive(true); _dialoguePanel.SetActive(true); _dialogueText.text = _activeDialogue.messages[_currentMessage]; } } #endregion #region --Public Custom Methods-- public void Next() { _currentMessage++; //if current message is grater than or equal to the lenght if(_currentMessage >= _activeDialogue.messages.Length) { //close all panels _dilogueCam.SetActive(false); _dialoguePanel.SetActive(false); _activeDialogue = null; _engageNPC = false; _currentMessage = 0; return; } _dialogueText.text = _activeDialogue.messages[_currentMessage]; } public void ActiveNPC(PGS_Dialogue npcDialogue,bool canTalk) { _activeDialogue = npcDialogue; _engageNPC = canTalk; } #endregion } }
c#
16
0.526862
79
27.037975
79
starcoderdata
import numpy import cv2 from keras.utils import np_utils from keras.models import model_from_json from keras.models import Sequential from keras.layers import Convolution2D, MaxPooling2D, Dense, Dropout, Activation, Flatten # load json and create model json_file = open('model.json', 'r') loaded_model_json = json_file.read() json_file.close() model = model_from_json(loaded_model_json) # load weights into new model model.load_weights("model.h5") print("Loaded model from disk") cap = cv2.VideoCapture(1) ret = cap.set(3,640) # WIDTH ret = cap.set(4,360) # Height ret = cap.set(5,60) # FPS Frame rate print('Warming the camera') for k in range(10): ret, frame = cap.read() cv2.imshow('raw',frame) cv2.waitKey(33) print('Main Loop') for k in range(1000): ret, frame = cap.read() im=frame[116:244, 256:384] cv2.imshow('raw',im) cv2.waitKey(100) img = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) img = cv2.GaussianBlur(img, (7,7), 3) img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2) ret, edge = cv2.threshold(img, 25, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU) cv2.imshow('Edge',edge) cv2.waitKey(100) #print(img.shape) x=edge.reshape(1,128,128,1) #print(x.shape) y=model.predict(x) #print(y) z=numpy.argmax(y.reshape(6)) print(z) cap.release() cv2.destroyAllWindows()
python
9
0.703216
101
23.017544
57
starcoderdata
using Discord; using Discord.Interactions; namespace HexacowBot.Core.DiscordBot.Modules.GameServerHost; public sealed partial class GameServerHostModule { [RequireOwner(Group = "ServerManagerPermission")] [RequireRole("Game Server Manager", Group = "ServerManagerPermission")] [SlashCommand("scale", "Scales server to a specified size.")] public async Task ServerScaleAsync() { await DeferAsync(ephemeral: true); var sizeOptions = new List foreach (var size in GameServerHost.AllowedSizes) { var description = $"vCpus: {size.Vcpus} | RAM: {size.Memory} | Monthly: ${size.PriceMonthly} | Hourly: ${size.PriceHourly}"; var sizeOption = new SelectMenuOptionBuilder() .WithLabel(size.Slug) .WithValue(size.Slug) .WithDescription(description); sizeOptions.Add(sizeOption); } var slugSelectMenu = new SelectMenuBuilder() .WithCustomId("server-scale-select") .WithOptions(sizeOptions); var slugSelectComponent = new ComponentBuilder() .WithSelectMenu(slugSelectMenu) .Build(); await FollowupAsync("Please select a size to scale to.", ephemeral: false, components: slugSelectComponent); } [ComponentInteraction("server-scale-select", ignoreGroupNames: true)] public async Task ServerScaleSelectAsync(string[] selectedSlugs) { await DeferAsync(ephemeral: true); await SetCustomStatus("Scaling"); var selectedSlug = selectedSlugs.First(); await Context.Interaction.ModifyOriginalResponseAsync(message => { message.Content = $"Selected {selectedSlug}"; message.Components = new ComponentBuilder().Build(); }); var size = await GameServerHost.GetServerSizeAsync(selectedSlug); var initialMessage = await ReplyAsync( $"Attempting to scale the server __**{GameServerHost.ServerName}**__ to size {size!.Slug}."); MessagesToDelete.Add(initialMessage); var serverActionResult = await GameServerHost.ScaleServerAsync(size); await GameServerStatusHelper.SetServerStatus(Context.Client, GameServerHost); if (serverActionResult.Success) { Logger.Log(serverActionResult.Severity, serverActionResult.Message); var response = new StringBuilder(); response.AppendLine($"✅\t{serverActionResult.Message} {GetElapsedFriendly(serverActionResult.elapsedTime)}"); response.AppendLine("```"); response.AppendLine($"{"vCpus".PadRight(15, ' ')} {size.Vcpus}"); response.AppendLine($"{"Memory".PadRight(15, ' ')} {(size.Memory / 1024)}GB"); response.AppendLine($"{"Price Hourly".PadRight(15, ' ')} ${size.PriceHourly}"); response.AppendLine($"{"Price Monthly".PadRight(15, ' ')} ${size.PriceMonthly}"); response.AppendLine("```"); await FollowupAsync(response.ToString(), ephemeral: false); } else { Logger.Log(serverActionResult.Severity, serverActionResult.Message); await FollowupAsync($"❌\t{serverActionResult.Message} {GetElapsedFriendly(serverActionResult.elapsedTime)}", ephemeral: false); } } }
c#
20
0.742839
130
33.516854
89
starcoderdata