language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
TypeScript
UTF-8
3,536
3.546875
4
[]
no_license
'use strict'; let microChipNumber = 0; class AnimalShelter { animals: Animal [] = []; budget: number = 50; adopters: string [] = []; rescue(newAnimal: Animal) { this.animals.push(newAnimal); return this.animals.length; } heal() { let healedAnimals: number = 0; for (let i: number = 0; i < this.animals.length; i++) { if (!this.animals[i].isHealthy && this.animals[i].healCost <= this.budget){ //-0.5 this.animals[i].heal(); healedAnimals = 1; } else { healedAnimals = 0; } break; } return healedAnimals; } addAdopter(newAdopter: string) { this.adopters.push(newAdopter); } findNewOwner () { //Nézni kell hogy adoptabe-e -0,5 let randomNum2: number = generateRandomNumber(0,this.adopters.length); let healthyAnimals: any [] = []; for (let i:number = 0; i < this.animals.length; i++) { if (this.animals[i].isHealthy === true) { healthyAnimals.push(this.animals[i]); } } let randomNum1: number = generateRandomNumber(0,healthyAnimals.length); if (healthyAnimals[randomNum1] && this.adopters[randomNum2]) { for (let i:number = 0; i < this.animals.length; i++) { if ( healthyAnimals[randomNum1].microChip === this.animals[i].microChip) { this.animals.splice(i,1); } } this.adopters.splice(randomNum2,1); }; }; earnDonation(donationAmount: number) { return this.budget += donationAmount; } toString () { //-0,5 let retVal:string =`Budget: ${this.budget}, there are ${this.animals.length} animal(s) and ${this.adopters.length} potential adopter(s).\n`; for(let i:number = 0; i<this.animals.length;i++) { retVal += this.animals[i].toString() + "\n"; } return retVal; } } class Animal { name: string; isHealthy: boolean; healCost: number; microChip: number; //How the fuck am I supposed to do that? constructor(newName: string, newMicroChip: number = microChipNumber++) { this.name = newName; this.microChip = newMicroChip; } heal() { this.isHealthy = true; } isAdoptable() { return this.isHealthy; } toString() { if (this.isHealthy) { return `${this.name} is healthy and adoptable.` } else { return `${this.name} is not healthy (healing cost is ${this.healCost} EUR) and not adoptable.` } } } class Cat extends Animal { constructor (newName: string = "Cat") { super(newName); } healCost: number = generateRandomNumber(0, 6); } class Dog extends Animal { constructor (newName: string = "Dog") { super(newName); } healCost: number = generateRandomNumber(1, 8); } class Parrot extends Animal { constructor (newName: string = "Parrot") { super(newName); } healCost: number = generateRandomNumber(4, 10); } //This function will generate the random healing cost numbers export function generateRandomNumber(min_value: number, max_value: number) { let newNumber: number = 0; newNumber = Math.random() * (max_value - min_value) + min_value; return Math.floor(newNumber); } let animalShelter = new AnimalShelter(); animalShelter.rescue(new Cat()); animalShelter.rescue(new Dog("Furkesz")); animalShelter.rescue(new Parrot()); console.log(animalShelter.toString()); animalShelter.heal(); console.log(animalShelter.toString()); animalShelter.addAdopter("Kond"); console.log(animalShelter.toString()); animalShelter.findNewOwner(); animalShelter.earnDonation(30); console.log(animalShelter.toString());
C++
UTF-8
2,455
2.625
3
[]
no_license
#include "bltpch.h" #include "Font.h" #include "BoltLib/Profiling/Profiling.h" namespace Bolt { Font::Font(const FilePath& fontFile, float fontSize, int textureWidth, int textureHeight) : Texture2D(textureWidth, textureHeight, PixelFormat::R, { PixelWrap::Clamp, PixelFilter::Linear, PixelFilter::Linear, false }), m_FontSize(fontSize) { BLT_PROFILE_FUNCTION(); BLT_ASSERT(Filesystem::FileExists(fontFile), "Unable to find font file " + fontFile.Path()); m_TextureAtlas = std::unique_ptr<texture_atlas_t, std::function<void(texture_atlas_t*)>>(texture_atlas_new(m_Width, m_Height, 1), [](texture_atlas_t* ptr) { texture_atlas_delete(ptr); }); m_TextureFont = std::unique_ptr<texture_font_t, std::function<void(texture_font_t*)>>(texture_font_new_from_file(m_TextureAtlas.get(), m_FontSize, fontFile.Path().c_str()), [](texture_font_t* ptr) { texture_font_delete(ptr); }); texture_font_load_glyphs(m_TextureFont.get(), "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-=+';:,.<>?/`~|\\!@#$%^&*()_\"[]{}"); m_TextureAtlas->id = m_Id; GL_CALL(glTexSubImage2D((GLenum)Target(), 0, 0, 0, Width(), Height(), GL_RED, GL_UNSIGNED_BYTE, m_TextureAtlas->data)); } float Font::FontSize() const { return m_FontSize; } std::vector<Font::FontCharacter> Font::GetCharacters(const std::string& str) const { BLT_PROFILE_FUNCTION(); std::vector<FontCharacter> result; for (int i = 0; i < str.size(); i++) { char c = str[i]; texture_glyph_t* glyph = texture_font_get_glyph(m_TextureFont.get(), &c); float kerning = 0; if (i != 0) { char prevC = str[i - 1]; kerning = texture_glyph_get_kerning(glyph, &prevC); } FontCharacter chr = { { glyph->s0, glyph->t1, glyph->s1, glyph->t0 }, (uint32_t)glyph->width, (uint32_t)glyph->height, glyph->advance_x, glyph->advance_y, (float)glyph->offset_x, (float)glyph->offset_y, kerning }; result.push_back(chr); } return result; } Vector2f Font::SizeOfText(const std::string& text) const { BLT_PROFILE_FUNCTION(); std::vector<Font::FontCharacter> characters = GetCharacters(text); Vector2f size = std::accumulate(characters.begin(), characters.end(), Vector2f(), [](const Vector2f& current, const Font::FontCharacter& chr) { Vector2f result; result.y = current.y; if (chr.Height > current.y) { result.y = chr.Height; } result.x = current.x + chr.AdvanceX + chr.Kerning; return result; }); return size; } }
Java
UTF-8
5,933
2.03125
2
[]
no_license
package com.appsimples.mutti.interusp_android.Atualizar; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import com.appsimples.mutti.interusp_android.Manager.EditLocal; import com.appsimples.mutti.interusp_android.Model.Locais; import com.appsimples.mutti.interusp_android.R; import com.appsimples.mutti.interusp_android.Utils.Constants; import com.appsimples.mutti.interusp_android.Utils.StatusBarColor; import java.util.ArrayList; import java.util.Arrays; public class AtualizarLocal extends AppCompatActivity { Context context = this; Activity activity = this; String _id; private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { activity.finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_atualizar_local); boolean novo_lugar = getIntent().getBooleanExtra("novo_lugar", false); final ImageView icon = (ImageView) findViewById(R.id.icon_lugar); final EditText nome = (EditText) findViewById(R.id.lugar_nome_edt); final EditText descricao = (EditText) findViewById(R.id.lugar_descricao_edt); final EditText url = (EditText) findViewById(R.id.lugar_foto_edt); final EditText latitude = (EditText) findViewById(R.id.lugar_latitude_edt); final EditText longitude = (EditText) findViewById(R.id.lugar_longitude_edt); Button atualizar = (Button) findViewById(R.id.lugar_atualizar); ArrayList list = new ArrayList(); list.addAll(Arrays.asList(getResources().getStringArray(R.array.tipo_locais1))); final Spinner tipo_lugar = (Spinner) findViewById(R.id.lugar_spinner); ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, list); adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); tipo_lugar.setAdapter(adapter3); if (!novo_lugar) { final Locais local = getIntent().getParcelableExtra("locais"); _id = local.getId(); double[] coordenadas = local.getCoordenadas(); setIcon(local.getTipo(), icon); nome.setText(local.getNome()); descricao.setText(local.getDescricao()); url.setText(local.getFoto()); latitude.setText(String.valueOf(coordenadas[1])); longitude.setText(String.valueOf(coordenadas[0])); tipo_lugar.setSelection(local.getTipo() - 1); } atualizar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int tipo = tipo_lugar.getSelectedItemPosition() + 1; double[] coordenadas = new double[2]; if(latitude.getText().length()>0&&longitude.getText().length()>0) { coordenadas[0] = Double.parseDouble(latitude.getText().toString()); coordenadas[1] = Double.parseDouble(longitude.getText().toString()); Locais local = new Locais(nome.getText().toString(), descricao.getText().toString(), url.getText().toString(), coordenadas, tipo); local.setId(_id); EditLocal editLocal = new EditLocal(context); editLocal.EditLocal(local); } } }); //ACTION BAR StatusBarColor.setColorStatusBar(activity, "#000033"); TextView action_title = (TextView) findViewById(R.id.txtActionBar); if (novo_lugar) { action_title.setText("Atualiza Local"); } else { action_title.setText("Adicionar Local"); } final ImageView back_button = (ImageView) findViewById(R.id.btnVoltar); back_button.setVisibility(View.VISIBLE); back_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { activity.finish(); } }); } @Override protected void onResume() { super.onResume(); activity.registerReceiver(receiver, new IntentFilter(Constants.kGetLocaisDone)); } @Override public void onStop() { super.onStop(); activity.unregisterReceiver(receiver); } public void setIcon(int id, ImageView icon) { switch (id) { case 1: icon.setImageResource(R.drawable.info_ginasios); break; case 2: icon.setImageResource(R.drawable.info_tenda); break; case 3: icon.setImageResource(R.drawable.info_baladas); break; case 4: icon.setImageResource(R.drawable.info_onibus); break; case 5: icon.setImageResource(R.drawable.info_alojamento); break; case 6: icon.setImageResource(R.drawable.info_hospital); break; case 7: icon.setImageResource(R.drawable.info_delegacia); break; case 8: icon.setImageResource(R.drawable.info_restaurantes); break; default: icon.setImageResource(R.drawable.tabicon_azul_mapa); break; } } }
Java
UTF-8
875
3.921875
4
[]
no_license
package Lec20; public class Max_Sub_Array_Sum { public static void main(String[] args) { // TODO Auto-generated method stub int[] arr = { -2, -3, -1, -8, -13, -9 }; System.out.println(max_sum(arr)); System.out.println(max_sum1(arr)); } // O(N^3) public static int max_sum(int[] arr) { int ans = Integer.MIN_VALUE; for (int i = 0; i < arr.length; i++) { for (int j = i; j < arr.length; j++) { int sum = 0; for (int k = i; k <= j; k++) { // System.out.print(arr[k] + " "); sum += arr[k]; } // System.out.println(); ans = Math.max(ans, sum); } } return ans; } // O(n^2) public static int max_sum1(int[] arr) { int ans = Integer.MIN_VALUE; for (int i = 0; i < arr.length; i++) { int sum = 0; for (int j = i; j < arr.length; j++) { sum += arr[j]; ans = Math.max(ans, sum); } } return ans; } }
C
WINDOWS-1250
504
2.96875
3
[]
no_license
#include<stdio.h> int main(void){ int a,b; int ans; scanf("%d",&a); scanf("%d",&b); ans=(a-1)*(b-1); printf("%d\n",ans); return 0; } ./Main.c: In function main: ./Main.c:6:5: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result] scanf("%d",&a); ^ ./Main.c:7:5: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result] scanf("%d",&b); ^
Java
UTF-8
1,299
2.25
2
[]
no_license
package com.stackroute.findmeclinic.bookingappointment.model; import java.util.Date; public class Notification { private String notification_id; private String doctorId; private String patientId; private String content; private Date notifgenDate; public String getDoctorId() { return doctorId; } public void setDoctorId(String doctorId) { this.doctorId = doctorId; } public String getPatientId() { return patientId; } public void setPatientId(String patientId) { this.patientId = patientId; } public String getNotification_id() { return notification_id; } public void setNotification_id(String notification_id) { this.notification_id = notification_id; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getNotifgenDate() { return notifgenDate; } public void setNotifgenDate(Date notifgenDate) { this.notifgenDate = notifgenDate; } @Override public String toString() { return "Notification [notification_id=" + notification_id + ", doctorId=" + doctorId + ", patientId=" + patientId + ", content=" + content + ", notifgenDate=" + notifgenDate + "]"; } }
Java
UTF-8
348
1.609375
2
[]
no_license
package com.wipro.SpringBootDemoJul8; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootDemoJul8Application { public static void main(String[] args) { SpringApplication.run(SpringBootDemoJul8Application.class, args); } }
Java
UTF-8
2,599
2.40625
2
[ "Apache-2.0" ]
permissive
/** * Copyright (C) 2018 Jeebiz (http://jeebiz.net). * All Rights Reserved. */ package io.hiwepy.admin.authz.rbac0.utils; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.springframework.biz.utils.StringUtils; import org.springframework.util.CollectionUtils; import com.google.common.collect.Lists; public class AuthzPermsUtils { /** * 对提交的权限标记进行去重处理 * @param originPerms : 原始权限标记集合 * @return 解析和去重后的标记集合 */ public static List<String> distinct(Set<String> originPerms){ List<String> perms = Lists.newArrayList(); if(!CollectionUtils.isEmpty(originPerms)) { return distinct(originPerms.stream().collect(Collectors.toList())); } return perms; } /** * 对提交的权限标记进行去重处理 * @param originPerms : 原始权限标记集合 * @return 解析和去重后的标记集合 */ public static List<String> distinct(List<String> originPerms){ List<String> perms = Lists.newArrayList(); if(!CollectionUtils.isEmpty(originPerms)) { // 进行数据处理 originPerms = originPerms.stream().filter(p -> StringUtils.hasText(p) && p.split(":").length > 0).collect(Collectors.toList()); // 权限标记处理,这里的每个元素可能是多个标记的组合 for(String perm : originPerms) { perm = StringUtils.trimAllWhitespace(perm); if(StringUtils.hasText(perm)) { Collections.addAll(perms, StringUtils.tokenizeToStringArray(perm)); } } // 组合最终的标记 return perms.stream().distinct().sorted().collect(Collectors.toList()); } return perms; } /** * 获取授权标记增量集合 * @param perms :此次提交的授权标记 * @param oldperms : 已经授权标记 * @return */ public static List<String> increment(List<String> perms, List<String> oldperms){ if(CollectionUtils.isEmpty(perms) || CollectionUtils.isEmpty(oldperms)) { return Lists.newArrayList(); } return perms.stream() .filter(perm -> !oldperms.contains(perm)) .collect(Collectors.toList()); } /** * 获取授权标记减量集合 * @param perms :此次提交的授权标记 * @param oldperms : 已经授权标记 * @return */ public static List<String> decrement(List<String> perms, List<String> oldperms){ if(CollectionUtils.isEmpty(oldperms)) { return Lists.newArrayList(perms); } return oldperms.stream() .filter(perm -> !perms.contains(perm)) .collect(Collectors.toList()); } }
Java
UTF-8
6,579
2.21875
2
[ "MIT" ]
permissive
package domain; public class CompanyBuilder { private String buildertemplate; private String buildershort_description; private String builderindustry_category; private String buildercik; private String builderstock_exchange; private String builderbusiness_address; private int buildersic; private String builderceo; private String builderinc_country; private Security[] buildersecurities; private String builderlei; private String builderhq_country; private String buildercompany_url; private String builderhq_state; private String builderindustry_group; private String builderlegal_name; private String buildersector; private String builderhq_address2; private String builderticker; private String builderhq_address1; private String builderlong_description; private String builderhq_address_city; private String buildermailing_address; private String builderinc_state; private boolean builderstandardized_active; private String builderentity_legal_form; private String buildername; private String builderhq_address_postal_code; private String builderentity_status; private int builderemployees; private String builderbusiness_phone_no; public CompanyBuilder template(String template) { this.buildertemplate = template; return this; } public CompanyBuilder short_description(String short_description) { this.buildershort_description = short_description; return this; } public CompanyBuilder industry_category(String industry_category) { this.builderindustry_category = industry_category; return this; } public CompanyBuilder cik(String cik) { this.buildercik = cik; return this; } public CompanyBuilder stock_exchange(String stock_exchange) { this.builderstock_exchange = stock_exchange; return this; } public CompanyBuilder business_address(String business_address) { this.builderbusiness_address = business_address; return this; } public CompanyBuilder sic(int sic) { this.buildersic = sic; return this; } public CompanyBuilder ceo(String ceo) { this.builderceo = ceo; return this; } public CompanyBuilder inc_country(String inc_country) { this.builderinc_country = inc_country; return this; } public CompanyBuilder securities(Security[] securities) { this.buildersecurities = securities; return this; } public CompanyBuilder lei(String lei) { this.builderlei = lei; return this; } public CompanyBuilder hq_country(String hq_country) { this.builderhq_country = hq_country; return this; } public CompanyBuilder company_url(String company_url) { this.buildercompany_url = company_url; return this; } public CompanyBuilder hq_state(String hq_state) { this.builderhq_state = hq_state; return this; } public CompanyBuilder industry_group(String industry_group) { this.builderindustry_group = industry_group; return this; } public CompanyBuilder legal_name(String legal_name) { this.builderlegal_name = legal_name; return this; } public CompanyBuilder sector(String sector) { this.buildersector = sector; return this; } public CompanyBuilder hq_address2(String hq_address2) { this.builderhq_address2 = hq_address2; return this; } public CompanyBuilder ticker(String ticker) { this.builderticker = ticker; return this; } public CompanyBuilder hq_address1(String hq_address1) { this.builderhq_address1 = hq_address1; return this; } public CompanyBuilder long_description(String long_description) { this.builderlong_description = long_description; return this; } public CompanyBuilder hq_address_city(String hq_address_city) { this.builderhq_address_city = hq_address_city; return this; } public CompanyBuilder mailing_address(String mailing_address) { this.buildermailing_address = mailing_address; return this; } public CompanyBuilder inc_state(String inc_state) { this.builderinc_state = inc_state; return this; } public CompanyBuilder standardized_active(boolean standardized_active) { this.builderstandardized_active = standardized_active; return this; } public CompanyBuilder entity_legal_form(String entity_legal_form) { this.builderentity_legal_form = entity_legal_form; return this; } public CompanyBuilder name(String name) { this.buildername = name; return this; } public CompanyBuilder hq_address_postal_code(String hq_address_postal_code) { this.builderhq_address_postal_code = hq_address_postal_code; return this; } public CompanyBuilder entity_status(String entity_status) { this.builderentity_status = entity_status; return this; } public CompanyBuilder employees(int employees) { this.builderemployees = employees; return this; } public CompanyBuilder business_phone_no(String business_phone_no) { this.builderbusiness_phone_no = business_phone_no; return this; } public Company build(){ return new Company( this.buildertemplate, this.buildershort_description, this.builderindustry_category, this.buildercik, this.builderstock_exchange, this.builderbusiness_address, this.buildersic, this.builderceo, this.builderinc_country, this.buildersecurities, this.builderlei, this.builderhq_country, this.buildercompany_url, this.builderhq_state, this.builderindustry_group, this.builderlegal_name, this.buildersector, this.builderhq_address2, this.builderticker, this.builderhq_address1, this.builderlong_description, this.builderhq_address_city, this.buildermailing_address, this.builderinc_state, this.builderstandardized_active, this.builderentity_legal_form, this.buildername, this.builderhq_address_postal_code, this.builderentity_status, this.builderemployees, this.builderbusiness_phone_no ); } }
JavaScript
UTF-8
1,776
2.875
3
[ "MIT" ]
permissive
'use strict'; const EventEmitter = require('events'); class CmdError extends Error { constructor(msg) { super(); this.errorMsg = msg; } } // Mutex class to control read/write access to discord-distances/imgcache/ class Lock extends EventEmitter { constructor(socket) { super(); this._socket = socket; // Socket descriptor to backend.py this._locked = false; this._socket.on('unlock', () => { this.unlock(); }).on('lock', () => { this.lock(); }); } async attempt(func, args) { // If lock is active, call the function on unlock // Otherwise, just call the function if (this._locked) { this.once('unlock', () => { return func(...args); }); } else { return func(...args); } } async attemptCmd(func, args, message) { // Same as attempt but assumes func is a cmdObj.execute // And notifies command caller that the bot is currently locked if (this._locked) { this.once('unlock', () => { return func(...args); }); message.channel.send('Currently busy. Will serve result shortly...'); } else { return func(...args); } } async lock() { this._locked = true; this.emit('lock'); console.log("[MUTEX] Locked"); } async unlock() { this._locked = false; this.emit('unlock'); console.log("[MUTEX] Unlocked"); } get locked() { return this._locked; } } module.exports = { CmdError: CmdError, Lock: Lock };
Java
UTF-8
2,294
3.515625
4
[]
no_license
package model; /** * Created by danielchu on 12/30/16. */ import model.pieces.IPiece; import model.pieces.PieceInfo; import model.players.Team; /** * Interface for the model for a game of chess. */ public interface IChessGameModel { /** * Makes the piece move from its original location to the target location, if the move is valid. * Also returns a piece that was taken as a result of this move. Returns null if none. * * @param fromCol piece's original column * @param fromRow piece's original row * @param targetCol target column * @param targetRow target row * @return the piece that was taken as a result of this move - if none were taken, returns null. * @throws IllegalArgumentException if this move is not valid */ IPiece movePiece(int fromCol, int fromRow, int targetCol, int targetRow) throws IllegalArgumentException; /** * Checks if this move would be invalid due to a check or other criteria specific to the game. * * @param fromCol piece's original column * @param fromRow piece's original row * @param targetCol target column * @param targetRow target row * @return if making that move will cause the game to be in an invalid state */ boolean willCauseInvalidStateFromCheck(int fromCol, int fromRow, int targetCol, int targetRow); /** * Tells us the status of the game. * * @return the code representing if the game has been won yet, and if so, by who. */ GameStatusCode getGameStatus(); /** * Gets the player whose turn it currently is. * * @return the Team of the current player */ Team whosTurn(); /** * Gets a 2d array representing the location of all pieces in this game. The first array is the * column, the second row. So [3][5] would be col 3 row 5. * * @return the 2d array representing this game */ PieceInfo[][] getBoard(); /** * Undos the last move. */ void undoLastMove(); /** * Restarts the game. */ void restartGame(); /** * Checks if there is a piece on the given cell. * * @param cell the cell to check * @return true if there is a piece, false otherwise */ boolean hasPieceOnCell(String cell); /** * Gets the name of this game mode. */ String getGameModeName(); }
C
UTF-8
3,198
2.9375
3
[]
no_license
#include<stdio.h> #include<string.h> #include<stdlib.h> struct FT { char nonT,set[20]; }; int i,j; typedef struct FT FIRST_FOLLOW_SET; FIRST_FOLLOW_SET first[10],follow[10]; char Parser_Table[2][3][10]; char *strrev(char *str) { int i=strlen(str)-1,j=0; char ch; while(i>j) { ch=str[i]; str[i]=str[j]; str[j]=ch; i--; j++; } return(str); } char terminal_list[3] = {"ab$"}; char stack[50]; int top = -1; int getFollowIndex(char x) { for(i=0;i<2;i++) if(follow[i].nonT==x) break; return(i); } int getTerminalIndex(char x) { for(i=0;i<strlen(terminal_list);i++) if(terminal_list[i]==x) break; return(i); } void push(char x) { stack[++top]=x; } void pop() { stack[top]='\0'; top--; } void check_input(char expr[30]) { int row,col; char prod[20],*token,ch,StackTop,temp[2],rprod[20]; temp[1]='\0'; for(i=0;expr[i]!='$';) { ch = expr[i]; StackTop = stack[top]; temp[0] = StackTop; if((strstr(terminal_list,temp)!=NULL)|| StackTop == '$') { if(strstr(terminal_list,temp)!=NULL) { pop(); i++; } else { printf("\nError in the stack symbol , Not Mentioned "); printf("\n%s Not Accepted",expr); return; } } else { if(strstr(terminal_list,temp)==NULL) { row = getFollowIndex(StackTop); col = getTerminalIndex(ch); strcpy(prod,Parser_Table[row][col]); printf("\nM[%d,%d] M[%c,%c] = %s",row,col,StackTop,ch,prod); if(strstr(prod,"err")!=NULL) { printf("\nError : No Entry in the Table"); printf("\n%s Not Accepted",expr); return; } else { strcpy(rprod,strrev(prod)); token = strtok(rprod,">"); if(strstr(rprod,"#")!=NULL) { pop(); } else { pop(); for(j=0;j<strlen(token);j++) { push(token[j]); } } } } } } if(expr[i]==stack[top]) printf("\nch = %c StackTop = %c %s is Accepted ",expr[i],stack[top],expr); else printf("\nch = %c StackTop = %c %s is Not Accepted ",expr[i],stack[top],expr); } void init() { stack[0] = '\0'; top = -1; } int main() { char production[10][20],inputString[30],t,T; int ch; for(i=0;i<2;i++) { printf("\nEnter the %d production ",i); gets(production[i]); fflush(stdin); } printf("\nThe productions entered are - "); for (i=0;i<2;i++) { printf("\n%s",production[i]); } printf("\n--First Set--\n"); for(i=0;i<2;i++) { first[i].nonT = production[i][0]; printf("\nEnter First(%c) : ",first[i].nonT); gets(first[i].set); fflush(stdin); } printf("\n--Follow Set--\n"); for(i=0;i<2;i++) { follow[i].nonT = first[i].nonT; printf("\nEnter Follow(%c) : ",follow[i].nonT); gets(follow[i].set); fflush(stdin); } printf("\nIf no entry , enter 'err' in the table "); for(i=0;i<2;i++) for(j=0;j<3;j++) { T = first[i].nonT; t = terminal_list[j]; printf("\nM[%d,%d] M[%c,%c] = ",i,j,T,t); gets(Parser_Table[i][j]); fflush(stdin); } init(); push('$'); push(production[0][0]); printf("\nStack %s",stack); printf("\nEnter the input : "); gets(inputString); strcat(inputString,"$"); printf("\nInput String %s ",inputString); check_input(inputString); printf("\n"); }
Go
UTF-8
2,351
3.03125
3
[ "MIT" ]
permissive
package gocfcrypt import ( "bytes" "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/base64" "encoding/hex" "io" "io/ioutil" "log" "strings" ) func Base64Decode(key []byte) []byte { decoded, _ := base64.StdEncoding.DecodeString(strings.TrimSpace(string(key))) return decoded } func ReadFile(filePath string) []byte { body, err := ioutil.ReadFile(filePath) if err != nil { log.Fatalf("unable to read file: %v", err) } return body } func PKCS7Padding(ciphertext []byte, blockSize int) []byte { padding := blockSize - len(ciphertext)%blockSize padtext := bytes.Repeat([]byte{byte(padding)}, padding) return append(ciphertext, padtext...) } func PKCS7UnPadding(origData []byte) []byte { length := len(origData) unpadding := int(origData[length-1]) return origData[:(length - unpadding)] } func EncryptAesCBC(rawData, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { panic(err) } blockSize := block.BlockSize() rawData = PKCS7Padding(rawData, blockSize) cipherText := make([]byte, blockSize+len(rawData)) iv := cipherText[:blockSize] if _, err := io.ReadFull(rand.Reader, iv); err != nil { panic(err) } mode := cipher.NewCBCEncrypter(block, iv) mode.CryptBlocks(cipherText[blockSize:], rawData) return cipherText, nil } func DecryptAesCBC(encryptData, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { panic(err) } blockSize := block.BlockSize() if len(encryptData) < blockSize { panic("ciphertext too short") } iv := encryptData[:blockSize] encryptData = encryptData[blockSize:] if len(encryptData)%blockSize != 0 { panic("ciphertext is not a multiple of the block size") } mode := cipher.NewCBCDecrypter(block, iv) mode.CryptBlocks(encryptData, encryptData) encryptData = PKCS7UnPadding(encryptData) return encryptData, nil } func Encrypt(rawData, key []byte) (string, error) { data, err := EncryptAesCBC(rawData, key) if err != nil { return "", err } return strings.ToUpper(hex.EncodeToString(data)), nil } func Decrypt(rawData string, key []byte) (string, error) { //data, err := base64.StdEncoding.DecodeString(rawData) data, err := hex.DecodeString(rawData) if err != nil { return "", err } dnData, err := DecryptAesCBC(data, key) if err != nil { return "", err } return string(dnData), nil }
Java
UTF-8
1,319
2.15625
2
[]
no_license
package vn.luvina.startup.security.services; import java.util.Optional; import org.springframework.http.HttpStatus; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import lombok.RequiredArgsConstructor; import vn.luvina.startup.enums.UserStatus; import vn.luvina.startup.exception.ServiceRuntimeException; import vn.luvina.startup.model.User; import vn.luvina.startup.repository.UserRepository; import vn.luvina.startup.util.StartupMessages; @Service @RequiredArgsConstructor public class UserDetailsServiceImpl implements UserDetailsService { private final UserRepository userRepository; @Override public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { Optional<User> user = userRepository.findByEmail(email); if (user.isPresent()) { if (user.get().getStatus().toLowerCase().equals(UserStatus.BLOCKED.toString().toLowerCase())) { throw new ServiceRuntimeException(HttpStatus.FORBIDDEN, StartupMessages.ERR_AUTH_006); } return UserDetailsImpl.build(user.get()); } throw new UsernameNotFoundException(email); } }
C#
UTF-8
463
2.671875
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; namespace TimecardRepository.Interfaces { /// <summary> /// Enforces CRUD methods. /// </summary> /// <typeparam name="T"></typeparam> public interface IDataRepository<T> { T Add(T inputObject); List<T> GetAll(); bool Update(T inputObject); bool Remove(T inputObject); IEnumerable<T> Query(); } }
Java
UTF-8
440
2.671875
3
[]
no_license
import java.util.regex.Pattern; public enum Lexeme { VAR(Pattern.compile("^[a-z]+$")), ASSIGN_OP(Pattern.compile("^=$")), DIGIT(Pattern.compile("^0|[1-9][0-9]*")), OP(Pattern.compile("^\\+|\\-|\\*|\\/$")), WS(Pattern.compile("^\\s+")); private Pattern pattern; Lexeme(Pattern pattern) { this.pattern = pattern; } public Pattern getPattern() { return pattern; } }
Shell
UTF-8
1,132
2.5625
3
[ "Apache-2.0" ]
permissive
#!/bin/bash BASEDIR="$(dirname $0)" # paths are valid for mml7 # select images #ls /data/inpainting/work/data/train | shuf | head -2000 | xargs -n1 -I{} cp {} /data/inpainting/mask_analysis/src # generate masks #"$BASEDIR/../gen_debug_mask_dataset.py" \ # "$BASEDIR/../../configs/debug_mask_gen.yaml" \ # "/data/inpainting/mask_analysis/src" \ # "/data/inpainting/mask_analysis/generated" # predict #"$BASEDIR/../predict.py" \ # model.path="simple_pix2pix2_gap_sdpl_novgg_large_b18_ffc075_batch8x15/saved_checkpoint/r.suvorov_2021-04-30_14-41-12_train_simple_pix2pix2_gap_sdpl_novgg_large_b18_ffc075_batch8x15_epoch22-step-574999" \ # indir="/data/inpainting/mask_analysis/generated" \ # outdir="/data/inpainting/mask_analysis/predicted" \ # dataset.img_suffix=.jpg \ # +out_ext=.jpg # analyze good and bad samples "$BASEDIR/../analyze_errors.py" \ --only-report \ --n-jobs 8 \ "$BASEDIR/../../configs/analyze_mask_errors.yaml" \ "/data/inpainting/mask_analysis/small/generated" \ "/data/inpainting/mask_analysis/small/predicted" \ "/data/inpainting/mask_analysis/small/report"
Java
UTF-8
375
1.6875
2
[]
no_license
package edu.brown.cs.atari_vision.ale.burlap; import burlap.mdp.core.oo.state.generic.GenericOOState; import org.bytedeco.javacpp.opencv_core.*; /** * Created by MelRod on 3/18/16. */ public class BlankALEState extends GenericOOState { public Mat screen; public BlankALEState() {} public BlankALEState(Mat screen) { this.screen = screen; } }
Java
UTF-8
40,699
1.578125
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.contacts; import com.android.contacts.BackScrollManager.ScrollableHeader; import com.android.contacts.calllog.CallDetailHistoryAdapter; import com.android.contacts.calllog.CallTypeHelper; import com.android.contacts.calllog.ContactInfo; import com.android.contacts.calllog.ContactInfoHelper; import com.android.contacts.calllog.PhoneNumberHelper; import com.android.contacts.format.FormatUtils; import com.android.contacts.util.AsyncTaskExecutor; import com.android.contacts.util.AsyncTaskExecutors; import com.android.contacts.util.ClipboardUtils; import com.android.contacts.util.Constants; import com.android.contacts.voicemail.VoicemailPlaybackFragment; import com.android.contacts.voicemail.VoicemailStatusHelper; import com.android.contacts.voicemail.VoicemailStatusHelper.StatusMessage; import com.android.contacts.voicemail.VoicemailStatusHelperImpl; import android.app.ActionBar; import android.app.Activity; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.provider.CallLog; import android.provider.CallLog.Calls; import android.provider.Contacts.Intents.Insert; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.Contacts; import android.provider.VoicemailContract.Voicemails; import android.telephony.PhoneNumberUtils; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Log; import android.view.ActionMode; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.List; /** * Displays the details of a specific call log entry. * <p> * This activity can be either started with the URI of a single call log entry, or with the * {@link #EXTRA_CALL_LOG_IDS} extra to specify a group of call log entries. */ public class CallDetailActivity extends Activity implements ProximitySensorAware { private static final String TAG = "CallDetail"; /** The time to wait before enabling the blank the screen due to the proximity sensor. */ private static final long PROXIMITY_BLANK_DELAY_MILLIS = 100; /** The time to wait before disabling the blank the screen due to the proximity sensor. */ private static final long PROXIMITY_UNBLANK_DELAY_MILLIS = 500; /** The enumeration of {@link AsyncTask} objects used in this class. */ public enum Tasks { MARK_VOICEMAIL_READ, DELETE_VOICEMAIL_AND_FINISH, REMOVE_FROM_CALL_LOG_AND_FINISH, UPDATE_PHONE_CALL_DETAILS, } /** A long array extra containing ids of call log entries to display. */ public static final String EXTRA_CALL_LOG_IDS = "EXTRA_CALL_LOG_IDS"; /** If we are started with a voicemail, we'll find the uri to play with this extra. */ public static final String EXTRA_VOICEMAIL_URI = "EXTRA_VOICEMAIL_URI"; /** If we should immediately start playback of the voicemail, this extra will be set to true. */ public static final String EXTRA_VOICEMAIL_START_PLAYBACK = "EXTRA_VOICEMAIL_START_PLAYBACK"; /** If the activity was triggered from a notification. */ public static final String EXTRA_FROM_NOTIFICATION = "EXTRA_FROM_NOTIFICATION"; private CallTypeHelper mCallTypeHelper; private PhoneNumberHelper mPhoneNumberHelper; private PhoneCallDetailsHelper mPhoneCallDetailsHelper; private TextView mHeaderTextView; private View mHeaderOverlayView; private ImageView mMainActionView; private ImageButton mMainActionPushLayerView; private ImageView mContactBackgroundView; private AsyncTaskExecutor mAsyncTaskExecutor; private ContactInfoHelper mContactInfoHelper; private String mNumber = null; private String mDefaultCountryIso; /* package */ LayoutInflater mInflater; /* package */ Resources mResources; /** Helper to load contact photos. */ private ContactPhotoManager mContactPhotoManager; /** Helper to make async queries to content resolver. */ private CallDetailActivityQueryHandler mAsyncQueryHandler; /** Helper to get voicemail status messages. */ private VoicemailStatusHelper mVoicemailStatusHelper; // Views related to voicemail status message. private View mStatusMessageView; private TextView mStatusMessageText; private TextView mStatusMessageAction; /** Whether we should show "edit number before call" in the options menu. */ private boolean mHasEditNumberBeforeCallOption; /** Whether we should show "trash" in the options menu. */ private boolean mHasTrashOption; /** Whether we should show "remove from call log" in the options menu. */ private boolean mHasRemoveFromCallLogOption; private ProximitySensorManager mProximitySensorManager; private final ProximitySensorListener mProximitySensorListener = new ProximitySensorListener(); /** * The action mode used when the phone number is selected. This will be non-null only when the * phone number is selected. */ private ActionMode mPhoneNumberActionMode; private CharSequence mPhoneNumberLabelToCopy; private CharSequence mPhoneNumberToCopy; /** Listener to changes in the proximity sensor state. */ private class ProximitySensorListener implements ProximitySensorManager.Listener { /** Used to show a blank view and hide the action bar. */ private final Runnable mBlankRunnable = new Runnable() { @Override public void run() { View blankView = findViewById(R.id.blank); blankView.setVisibility(View.VISIBLE); getActionBar().hide(); } }; /** Used to remove the blank view and show the action bar. */ private final Runnable mUnblankRunnable = new Runnable() { @Override public void run() { View blankView = findViewById(R.id.blank); blankView.setVisibility(View.GONE); getActionBar().show(); } }; @Override public synchronized void onNear() { clearPendingRequests(); postDelayed(mBlankRunnable, PROXIMITY_BLANK_DELAY_MILLIS); } @Override public synchronized void onFar() { clearPendingRequests(); postDelayed(mUnblankRunnable, PROXIMITY_UNBLANK_DELAY_MILLIS); } /** Removed any delayed requests that may be pending. */ public synchronized void clearPendingRequests() { View blankView = findViewById(R.id.blank); blankView.removeCallbacks(mBlankRunnable); blankView.removeCallbacks(mUnblankRunnable); } /** Post a {@link Runnable} with a delay on the main thread. */ private synchronized void postDelayed(Runnable runnable, long delayMillis) { // Post these instead of executing immediately so that: // - They are guaranteed to be executed on the main thread. // - If the sensor values changes rapidly for some time, the UI will not be // updated immediately. View blankView = findViewById(R.id.blank); blankView.postDelayed(runnable, delayMillis); } } static final String[] CALL_LOG_PROJECTION = new String[] { CallLog.Calls.DATE, CallLog.Calls.DURATION, CallLog.Calls.NUMBER, CallLog.Calls.TYPE, CallLog.Calls.COUNTRY_ISO, CallLog.Calls.GEOCODED_LOCATION, }; static final int DATE_COLUMN_INDEX = 0; static final int DURATION_COLUMN_INDEX = 1; static final int NUMBER_COLUMN_INDEX = 2; static final int CALL_TYPE_COLUMN_INDEX = 3; static final int COUNTRY_ISO_COLUMN_INDEX = 4; static final int GEOCODED_LOCATION_COLUMN_INDEX = 5; private final View.OnClickListener mPrimaryActionListener = new View.OnClickListener() { @Override public void onClick(View view) { if (finishPhoneNumerSelectedActionModeIfShown()) { return; } startActivity(((ViewEntry) view.getTag()).primaryIntent); } }; private final View.OnClickListener mSecondaryActionListener = new View.OnClickListener() { @Override public void onClick(View view) { if (finishPhoneNumerSelectedActionModeIfShown()) { return; } startActivity(((ViewEntry) view.getTag()).secondaryIntent); } }; private final View.OnLongClickListener mPrimaryLongClickListener = new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (finishPhoneNumerSelectedActionModeIfShown()) { return true; } startPhoneNumberSelectedActionMode(v); return true; } }; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.call_detail); mAsyncTaskExecutor = AsyncTaskExecutors.createThreadPoolExecutor(); mInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); mResources = getResources(); mCallTypeHelper = new CallTypeHelper(getResources()); mPhoneNumberHelper = new PhoneNumberHelper(mResources); mPhoneCallDetailsHelper = new PhoneCallDetailsHelper(mResources, mCallTypeHelper, mPhoneNumberHelper); mVoicemailStatusHelper = new VoicemailStatusHelperImpl(); mAsyncQueryHandler = new CallDetailActivityQueryHandler(this); mHeaderTextView = (TextView) findViewById(R.id.header_text); mHeaderOverlayView = findViewById(R.id.photo_text_bar); mStatusMessageView = findViewById(R.id.voicemail_status); mStatusMessageText = (TextView) findViewById(R.id.voicemail_status_message); mStatusMessageAction = (TextView) findViewById(R.id.voicemail_status_action); mMainActionView = (ImageView) findViewById(R.id.main_action); mMainActionPushLayerView = (ImageButton) findViewById(R.id.main_action_push_layer); mContactBackgroundView = (ImageView) findViewById(R.id.contact_background); mDefaultCountryIso = ContactsUtils.getCurrentCountryIso(this); mContactPhotoManager = ContactPhotoManager.getInstance(this); mProximitySensorManager = new ProximitySensorManager(this, mProximitySensorListener); mContactInfoHelper = new ContactInfoHelper(this, ContactsUtils.getCurrentCountryIso(this)); configureActionBar(); optionallyHandleVoicemail(); if (getIntent().getBooleanExtra(EXTRA_FROM_NOTIFICATION, false)) { closeSystemDialogs(); } } @Override public void onResume() { super.onResume(); updateData(getCallLogEntryUris()); } /** * Handle voicemail playback or hide voicemail ui. * <p> * If the Intent used to start this Activity contains the suitable extras, then start voicemail * playback. If it doesn't, then hide the voicemail ui. */ private void optionallyHandleVoicemail() { View voicemailContainer = findViewById(R.id.voicemail_container); if (hasVoicemail()) { // Has voicemail: add the voicemail fragment. Add suitable arguments to set the uri // to play and optionally start the playback. // Do a query to fetch the voicemail status messages. VoicemailPlaybackFragment playbackFragment = new VoicemailPlaybackFragment(); Bundle fragmentArguments = new Bundle(); fragmentArguments.putParcelable(EXTRA_VOICEMAIL_URI, getVoicemailUri()); if (getIntent().getBooleanExtra(EXTRA_VOICEMAIL_START_PLAYBACK, false)) { fragmentArguments.putBoolean(EXTRA_VOICEMAIL_START_PLAYBACK, true); } playbackFragment.setArguments(fragmentArguments); voicemailContainer.setVisibility(View.VISIBLE); getFragmentManager().beginTransaction() .add(R.id.voicemail_container, playbackFragment).commitAllowingStateLoss(); mAsyncQueryHandler.startVoicemailStatusQuery(getVoicemailUri()); markVoicemailAsRead(getVoicemailUri()); } else { // No voicemail uri: hide the status view. mStatusMessageView.setVisibility(View.GONE); voicemailContainer.setVisibility(View.GONE); } } private boolean hasVoicemail() { return getVoicemailUri() != null; } private Uri getVoicemailUri() { return getIntent().getParcelableExtra(EXTRA_VOICEMAIL_URI); } private void markVoicemailAsRead(final Uri voicemailUri) { mAsyncTaskExecutor.submit(Tasks.MARK_VOICEMAIL_READ, new AsyncTask<Void, Void, Void>() { @Override public Void doInBackground(Void... params) { ContentValues values = new ContentValues(); values.put(Voicemails.IS_READ, true); getContentResolver().update(voicemailUri, values, Voicemails.IS_READ + " = 0", null); return null; } }); } /** * Returns the list of URIs to show. * <p> * There are two ways the URIs can be provided to the activity: as the data on the intent, or as * a list of ids in the call log added as an extra on the URI. * <p> * If both are available, the data on the intent takes precedence. */ private Uri[] getCallLogEntryUris() { Uri uri = getIntent().getData(); if (uri != null) { // If there is a data on the intent, it takes precedence over the extra. return new Uri[]{ uri }; } long[] ids = getIntent().getLongArrayExtra(EXTRA_CALL_LOG_IDS); Uri[] uris = new Uri[ids.length]; for (int index = 0; index < ids.length; ++index) { uris[index] = ContentUris.withAppendedId(Calls.CONTENT_URI_WITH_VOICEMAIL, ids[index]); } return uris; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_CALL: { // Make sure phone isn't already busy before starting direct call TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); if (tm.getCallState() == TelephonyManager.CALL_STATE_IDLE) { startActivity(ContactsUtils.getCallIntent( Uri.fromParts(Constants.SCHEME_TEL, mNumber, null))); return true; } } } return super.onKeyDown(keyCode, event); } /** * Update user interface with details of given call. * * @param callUris URIs into {@link CallLog.Calls} of the calls to be displayed */ private void updateData(final Uri... callUris) { class UpdateContactDetailsTask extends AsyncTask<Void, Void, PhoneCallDetails[]> { @Override public PhoneCallDetails[] doInBackground(Void... params) { // TODO: All phone calls correspond to the same person, so we can make a single // lookup. final int numCalls = callUris.length; PhoneCallDetails[] details = new PhoneCallDetails[numCalls]; try { for (int index = 0; index < numCalls; ++index) { details[index] = getPhoneCallDetailsForUri(callUris[index]); } return details; } catch (IllegalArgumentException e) { // Something went wrong reading in our primary data. Log.w(TAG, "invalid URI starting call details", e); return null; } } @Override public void onPostExecute(PhoneCallDetails[] details) { if (details == null) { // Somewhere went wrong: we're going to bail out and show error to users. Toast.makeText(CallDetailActivity.this, R.string.toast_call_detail_error, Toast.LENGTH_SHORT).show(); finish(); return; } // We know that all calls are from the same number and the same contact, so pick the // first. PhoneCallDetails firstDetails = details[0]; mNumber = firstDetails.number.toString(); final Uri contactUri = firstDetails.contactUri; final Uri photoUri = firstDetails.photoUri; // Set the details header, based on the first phone call. mPhoneCallDetailsHelper.setCallDetailsHeader(mHeaderTextView, firstDetails); // Cache the details about the phone number. final boolean canPlaceCallsTo = mPhoneNumberHelper.canPlaceCallsTo(mNumber); final boolean isVoicemailNumber = mPhoneNumberHelper.isVoicemailNumber(mNumber); final boolean isSipNumber = mPhoneNumberHelper.isSipNumber(mNumber); // Let user view contact details if they exist, otherwise add option to create new // contact from this number. final Intent mainActionIntent; final int mainActionIcon; final String mainActionDescription; final CharSequence nameOrNumber; if (!TextUtils.isEmpty(firstDetails.name)) { nameOrNumber = firstDetails.name; } else { nameOrNumber = firstDetails.number; } if (contactUri != null) { mainActionIntent = new Intent(Intent.ACTION_VIEW, contactUri); // This will launch People's detail contact screen, so we probably want to // treat it as a separate People task. mainActionIntent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); mainActionIcon = R.drawable.ic_contacts_holo_dark; mainActionDescription = getString(R.string.description_view_contact, nameOrNumber); } else if (isVoicemailNumber) { mainActionIntent = null; mainActionIcon = 0; mainActionDescription = null; } else if (isSipNumber) { // TODO: This item is currently disabled for SIP addresses, because // the Insert.PHONE extra only works correctly for PSTN numbers. // // To fix this for SIP addresses, we need to: // - define ContactsContract.Intents.Insert.SIP_ADDRESS, and use it here if // the current number is a SIP address // - update the contacts UI code to handle Insert.SIP_ADDRESS by // updating the SipAddress field // and then we can remove the "!isSipNumber" check above. mainActionIntent = null; mainActionIcon = 0; mainActionDescription = null; } else if (canPlaceCallsTo) { mainActionIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT); mainActionIntent.setType(Contacts.CONTENT_ITEM_TYPE); mainActionIntent.putExtra(Insert.PHONE, mNumber); mainActionIcon = R.drawable.ic_add_contact_holo_dark; mainActionDescription = getString(R.string.description_add_contact); } else { // If we cannot call the number, when we probably cannot add it as a contact either. // This is usually the case of private, unknown, or payphone numbers. mainActionIntent = null; mainActionIcon = 0; mainActionDescription = null; } if (mainActionIntent == null) { mMainActionView.setVisibility(View.INVISIBLE); mMainActionPushLayerView.setVisibility(View.GONE); mHeaderTextView.setVisibility(View.INVISIBLE); mHeaderOverlayView.setVisibility(View.INVISIBLE); } else { mMainActionView.setVisibility(View.VISIBLE); mMainActionView.setImageResource(mainActionIcon); mMainActionPushLayerView.setVisibility(View.VISIBLE); mMainActionPushLayerView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(mainActionIntent); } }); mMainActionPushLayerView.setContentDescription(mainActionDescription); mHeaderTextView.setVisibility(View.VISIBLE); mHeaderOverlayView.setVisibility(View.VISIBLE); } // This action allows to call the number that places the call. if (canPlaceCallsTo) { final CharSequence displayNumber = mPhoneNumberHelper.getDisplayNumber( firstDetails.number, firstDetails.formattedNumber); ViewEntry entry = new ViewEntry( getString(R.string.menu_callNumber, FormatUtils.forceLeftToRight(displayNumber)), ContactsUtils.getCallIntent(mNumber), getString(R.string.description_call, nameOrNumber)); // Only show a label if the number is shown and it is not a SIP address. if (!TextUtils.isEmpty(firstDetails.name) && !TextUtils.isEmpty(firstDetails.number) && !PhoneNumberUtils.isUriNumber(firstDetails.number.toString())) { entry.label = Phone.getTypeLabel(mResources, firstDetails.numberType, firstDetails.numberLabel); } // The secondary action allows to send an SMS to the number that placed the // call. if (mPhoneNumberHelper.canSendSmsTo(mNumber)) { entry.setSecondaryAction( R.drawable.ic_text_holo_dark, new Intent(Intent.ACTION_SENDTO, Uri.fromParts("sms", mNumber, null)), getString(R.string.description_send_text_message, nameOrNumber)); } configureCallButton(entry); mPhoneNumberToCopy = displayNumber; mPhoneNumberLabelToCopy = entry.label; } else { disableCallButton(); mPhoneNumberToCopy = null; mPhoneNumberLabelToCopy = null; } mHasEditNumberBeforeCallOption = canPlaceCallsTo && !isSipNumber && !isVoicemailNumber; mHasTrashOption = hasVoicemail(); mHasRemoveFromCallLogOption = !hasVoicemail(); invalidateOptionsMenu(); ListView historyList = (ListView) findViewById(R.id.history); historyList.setAdapter( new CallDetailHistoryAdapter(CallDetailActivity.this, mInflater, mCallTypeHelper, details, hasVoicemail(), canPlaceCallsTo, findViewById(R.id.controls))); BackScrollManager.bind( new ScrollableHeader() { private View mControls = findViewById(R.id.controls); private View mPhoto = findViewById(R.id.contact_background_sizer); private View mHeader = findViewById(R.id.photo_text_bar); private View mSeparator = findViewById(R.id.blue_separator); @Override public void setOffset(int offset) { mControls.setY(-offset); } @Override public int getMaximumScrollableHeaderOffset() { // We can scroll the photo out, but we should keep the header if // present. if (mHeader.getVisibility() == View.VISIBLE) { return mPhoto.getHeight() - mHeader.getHeight(); } else { // If the header is not present, we should also scroll out the // separator line. return mPhoto.getHeight() + mSeparator.getHeight(); } } }, historyList); loadContactPhotos(photoUri); findViewById(R.id.call_detail).setVisibility(View.VISIBLE); } } mAsyncTaskExecutor.submit(Tasks.UPDATE_PHONE_CALL_DETAILS, new UpdateContactDetailsTask()); } /** Return the phone call details for a given call log URI. */ private PhoneCallDetails getPhoneCallDetailsForUri(Uri callUri) { ContentResolver resolver = getContentResolver(); Cursor callCursor = resolver.query(callUri, CALL_LOG_PROJECTION, null, null, null); try { if (callCursor == null || !callCursor.moveToFirst()) { throw new IllegalArgumentException("Cannot find content: " + callUri); } // Read call log specifics. String number = callCursor.getString(NUMBER_COLUMN_INDEX); long date = callCursor.getLong(DATE_COLUMN_INDEX); long duration = callCursor.getLong(DURATION_COLUMN_INDEX); int callType = callCursor.getInt(CALL_TYPE_COLUMN_INDEX); String countryIso = callCursor.getString(COUNTRY_ISO_COLUMN_INDEX); final String geocode = callCursor.getString(GEOCODED_LOCATION_COLUMN_INDEX); if (TextUtils.isEmpty(countryIso)) { countryIso = mDefaultCountryIso; } // Formatted phone number. final CharSequence formattedNumber; // Read contact specifics. final CharSequence nameText; final int numberType; final CharSequence numberLabel; final Uri photoUri; final Uri lookupUri; // If this is not a regular number, there is no point in looking it up in the contacts. ContactInfo info = mPhoneNumberHelper.canPlaceCallsTo(number) && !mPhoneNumberHelper.isVoicemailNumber(number) ? mContactInfoHelper.lookupNumber(number, countryIso) : null; if (info == null) { formattedNumber = mPhoneNumberHelper.getDisplayNumber(number, null); nameText = ""; numberType = 0; numberLabel = ""; photoUri = null; lookupUri = null; } else { formattedNumber = info.formattedNumber; nameText = info.name; numberType = info.type; numberLabel = info.label; photoUri = info.photoUri; lookupUri = info.lookupUri; } return new PhoneCallDetails(number, formattedNumber, countryIso, geocode, new int[]{ callType }, date, duration, nameText, numberType, numberLabel, lookupUri, photoUri); } finally { if (callCursor != null) { callCursor.close(); } } } /** Load the contact photos and places them in the corresponding views. */ private void loadContactPhotos(Uri photoUri) { mContactPhotoManager.loadPhoto(mContactBackgroundView, photoUri, mContactBackgroundView.getWidth(), true); } static final class ViewEntry { public final String text; public final Intent primaryIntent; /** The description for accessibility of the primary action. */ public final String primaryDescription; public CharSequence label = null; /** Icon for the secondary action. */ public int secondaryIcon = 0; /** Intent for the secondary action. If not null, an icon must be defined. */ public Intent secondaryIntent = null; /** The description for accessibility of the secondary action. */ public String secondaryDescription = null; public ViewEntry(String text, Intent intent, String description) { this.text = text; primaryIntent = intent; primaryDescription = description; } public void setSecondaryAction(int icon, Intent intent, String description) { secondaryIcon = icon; secondaryIntent = intent; secondaryDescription = description; } } /** Disables the call button area, e.g., for private numbers. */ private void disableCallButton() { findViewById(R.id.call_and_sms).setVisibility(View.GONE); } /** Configures the call button area using the given entry. */ private void configureCallButton(ViewEntry entry) { View convertView = findViewById(R.id.call_and_sms); convertView.setVisibility(View.VISIBLE); ImageView icon = (ImageView) convertView.findViewById(R.id.call_and_sms_icon); View divider = convertView.findViewById(R.id.call_and_sms_divider); TextView text = (TextView) convertView.findViewById(R.id.call_and_sms_text); View mainAction = convertView.findViewById(R.id.call_and_sms_main_action); mainAction.setOnClickListener(mPrimaryActionListener); mainAction.setTag(entry); mainAction.setContentDescription(entry.primaryDescription); mainAction.setOnLongClickListener(mPrimaryLongClickListener); if (entry.secondaryIntent != null) { icon.setOnClickListener(mSecondaryActionListener); icon.setImageResource(entry.secondaryIcon); icon.setVisibility(View.VISIBLE); icon.setTag(entry); icon.setContentDescription(entry.secondaryDescription); divider.setVisibility(View.VISIBLE); } else { icon.setVisibility(View.GONE); divider.setVisibility(View.GONE); } text.setText(entry.text); TextView label = (TextView) convertView.findViewById(R.id.call_and_sms_label); if (TextUtils.isEmpty(entry.label)) { label.setVisibility(View.GONE); } else { label.setText(entry.label); label.setVisibility(View.VISIBLE); } } protected void updateVoicemailStatusMessage(Cursor statusCursor) { if (statusCursor == null) { mStatusMessageView.setVisibility(View.GONE); return; } final StatusMessage message = getStatusMessage(statusCursor); if (message == null || !message.showInCallDetails()) { mStatusMessageView.setVisibility(View.GONE); return; } mStatusMessageView.setVisibility(View.VISIBLE); mStatusMessageText.setText(message.callDetailsMessageId); if (message.actionMessageId != -1) { mStatusMessageAction.setText(message.actionMessageId); } if (message.actionUri != null) { mStatusMessageAction.setClickable(true); mStatusMessageAction.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Intent.ACTION_VIEW, message.actionUri)); } }); } else { mStatusMessageAction.setClickable(false); } } private StatusMessage getStatusMessage(Cursor statusCursor) { List<StatusMessage> messages = mVoicemailStatusHelper.getStatusMessages(statusCursor); if (messages.size() == 0) { return null; } // There can only be a single status message per source package, so num of messages can // at most be 1. if (messages.size() > 1) { Log.w(TAG, String.format("Expected 1, found (%d) num of status messages." + " Will use the first one.", messages.size())); } return messages.get(0); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.call_details_options, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onPrepareOptionsMenu(Menu menu) { // This action deletes all elements in the group from the call log. // We don't have this action for voicemails, because you can just use the trash button. menu.findItem(R.id.menu_remove_from_call_log).setVisible(mHasRemoveFromCallLogOption); menu.findItem(R.id.menu_edit_number_before_call).setVisible(mHasEditNumberBeforeCallOption); menu.findItem(R.id.menu_trash).setVisible(mHasTrashOption); return super.onPrepareOptionsMenu(menu); } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case android.R.id.home: { onHomeSelected(); return true; } // All the options menu items are handled by onMenu... methods. default: throw new IllegalArgumentException(); } } public void onMenuRemoveFromCallLog(MenuItem menuItem) { final StringBuilder callIds = new StringBuilder(); for (Uri callUri : getCallLogEntryUris()) { if (callIds.length() != 0) { callIds.append(","); } callIds.append(ContentUris.parseId(callUri)); } mAsyncTaskExecutor.submit(Tasks.REMOVE_FROM_CALL_LOG_AND_FINISH, new AsyncTask<Void, Void, Void>() { @Override public Void doInBackground(Void... params) { getContentResolver().delete(Calls.CONTENT_URI_WITH_VOICEMAIL, Calls._ID + " IN (" + callIds + ")", null); return null; } @Override public void onPostExecute(Void result) { finish(); } }); } public void onMenuEditNumberBeforeCall(MenuItem menuItem) { startActivity(new Intent(Intent.ACTION_DIAL, ContactsUtils.getCallUri(mNumber))); } public void onMenuTrashVoicemail(MenuItem menuItem) { final Uri voicemailUri = getVoicemailUri(); mAsyncTaskExecutor.submit(Tasks.DELETE_VOICEMAIL_AND_FINISH, new AsyncTask<Void, Void, Void>() { @Override public Void doInBackground(Void... params) { getContentResolver().delete(voicemailUri, null, null); return null; } @Override public void onPostExecute(Void result) { finish(); } }); } private void configureActionBar() { ActionBar actionBar = getActionBar(); if (actionBar != null) { actionBar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME); } } /** Invoked when the user presses the home button in the action bar. */ private void onHomeSelected() { Intent intent = new Intent(Intent.ACTION_VIEW, Calls.CONTENT_URI); // This will open the call log even if the detail view has been opened directly. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); } @Override protected void onPause() { // Immediately stop the proximity sensor. disableProximitySensor(false); mProximitySensorListener.clearPendingRequests(); super.onPause(); } @Override public void enableProximitySensor() { mProximitySensorManager.enable(); } @Override public void disableProximitySensor(boolean waitForFarState) { mProximitySensorManager.disable(waitForFarState); } /** * If the phone number is selected, unselect it and return {@code true}. * Otherwise, just {@code false}. */ private boolean finishPhoneNumerSelectedActionModeIfShown() { if (mPhoneNumberActionMode == null) return false; mPhoneNumberActionMode.finish(); return true; } private void startPhoneNumberSelectedActionMode(View targetView) { mPhoneNumberActionMode = startActionMode(new PhoneNumberActionModeCallback(targetView)); } private void closeSystemDialogs() { sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); } private class PhoneNumberActionModeCallback implements ActionMode.Callback { private final View mTargetView; private final Drawable mOriginalViewBackground; public PhoneNumberActionModeCallback(View targetView) { mTargetView = targetView; // Highlight the phone number view. Remember the old background, and put a new one. mOriginalViewBackground = mTargetView.getBackground(); mTargetView.setBackgroundColor(getResources().getColor(R.color.item_selected)); } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { if (TextUtils.isEmpty(mPhoneNumberToCopy)) return false; getMenuInflater().inflate(R.menu.call_details_cab, menu); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return true; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { case R.id.copy_phone_number: ClipboardUtils.copyText(CallDetailActivity.this, mPhoneNumberLabelToCopy, mPhoneNumberToCopy, true); mode.finish(); // Close the CAB return true; } return false; } @Override public void onDestroyActionMode(ActionMode mode) { mPhoneNumberActionMode = null; // Restore the view background. mTargetView.setBackground(mOriginalViewBackground); } } }
Java
UTF-8
1,774
2.484375
2
[ "BSD-2-Clause", "Apache-2.0" ]
permissive
package org.oddjob.schedules; import org.junit.Test; import java.text.ParseException; import java.util.Calendar; import java.util.TimeZone; import org.oddjob.OjTestCase; import org.oddjob.arooa.utils.DateHelper; /** * */ public class DateUtilsTest extends OjTestCase { /* * Test for Date startOfDay(Date) */ @Test public void testStartOfDayDate() throws ParseException { assertEquals( DateHelper.parseDate("2003-07-11"), DateUtils.startOfDay(DateHelper.parseDateTime( "2003-07-11 12:27"), TimeZone.getDefault())); } /* * Test for Date endOfDay(Date) */ @Test public void testEndOfDayDate() throws ParseException { assertEquals( DateHelper.parseDate("2003-07-12"), DateUtils.endOfDay(DateHelper.parseDateTime( "2003-07-11 12:27"), TimeZone.getDefault())); } /* * Test for int dayOfWeek(Date) */ @Test public void testDayOfWeekDate() throws ParseException { assertEquals(6, DateUtils.dayOfWeek( DateHelper.parseDateTime("2003-07-11 12:27"), TimeZone.getDefault())); } /* * Test for int dayOfMonth(Date) */ @Test public void testDayOfMonthDate() throws ParseException { assertEquals(11, DateUtils.dayOfMonth( DateHelper.parseDateTime("2003-07-11 12:27"), TimeZone.getDefault())); } @Test public void testCompareCalendars() throws ParseException { Calendar c1 = Calendar.getInstance(); c1.setTime(DateHelper.parseDateTime("2005-06-21 10:00")); Calendar c2 = Calendar.getInstance(); c2.setTime(DateHelper.parseDateTime("2005-06-21 12:00")); assertEquals(-1, DateUtils.compare(c1, c2)); assertEquals(1, DateUtils.compare(c2, c1)); assertEquals(0, DateUtils.compare(c1, c1)); } }
Markdown
UTF-8
4,882
2.953125
3
[]
no_license
--- title: 获取键值对 weight: 4 --- ## grib_get > 获取键值对 使用`grib_get`从一个或多个文件中获取一个或多个key值,与`grib_ls`类似。 默认情况下,如果有错误发生(例如没有找到key),`grib_get`则会运行失败,返回非0退出值。 - 适合在脚本中获取 GRIB 消息的键值。 - 可以强制`grib_get`在出错时不会运行失败。 支持获取所有的 MARS key 和特定名称空间中的所有 key。可以添加其他 key 到默认集合。 浮点类型数据的输出支持 C 风格的格式化描述。 可以用于寻找某个经纬度坐标点的最近邻点,与`grib_ls`工作方式相同。 ## 用法 ``` grib_get [options] grib_file grib_file ... ``` ## 选项 选项 | 含义 ---|--- -p key1,key2,... | Keys to get -P key1,key2,... | Additional keys to get with –m, -n -w key1=val1,key2!=val2,... | Where option -s key1=val1,key2=val2,... | Keys to set (temporary for printing) -m | Get all MARS keys -n namespace | Get all keys for namespace -l lat,lon[,MODE,FILE] | Value(s) nearest to lat-lon point -F format | Format for floating point values -f | Do not fail on error ... | ... ## 使用 where 选项 where 选项 -w 可以用于所有的 GRIB 工具,具有相同的格式。 约束条件可以表示为如下几种形式: - `key=value` - `key!=value` - `key=value1|value2|value3` 示例 ``` -w key1=value1,key2:i!=value2,key3:s=value3 ``` 只有满足所有约束条件的 GRIB 消息才会被处理 ``` # IS > grib_get–w level=100–p step file.grib1 … # NOT > grib_get–w level!=100–p step file.grib1“NOT” … # AND > grib_get–w level=100,step=3 –p step file.grib1 … # OR > grib_get–w level=100/200/300 –p step file.grib1 … ## 指定 key 的类型 ecCodes 的所有 key 都有默认类型,例如字符型(string),整型(integer),浮点型(float point)。 key 的类型可以用下面的方式指定: - `key` -> 原始类型 - `key:i` -> 整形 - `key:s` -> 字符型 - `key:d` -> 双精度浮点型 ``` $ grib_get -w count=1 -p centre:i,dataDate,shortName,paramId,typeOfLevel,level ne_gmf.gra.2017050100000.grb2 38 20170501 t 130 surface 0 ``` ### 示例 获取文件中第一个 GRIB 消息的 centre(使用字符型和整形) ```powershell $ grib_get -w count=1 -p centre ne_gmf.gra.2017050100000.grb2 babj $ grib_get -w count=1 -p centre:i ne_gmf.gra.2017050100000.grb2 38 ``` 如果有错误,`grib_get`会出错退出。 ```powershell $ grib_get -w count=1 -p mykey ne_gmf.gra.2017050100000.grb2 ECCODES ERROR : Key/value not found $ echo $? False ``` 获取所有的 MARS key,附加打印 shortName ``` $ grib_get -w count=1 -m ne_gmf.gra.2017050100000.grb2 20170501 0000 0 sfc 130 $ grib_get -w count=1 -m -P shortName ne_gmf.gra.2017050100000.grb2 t 20170501 0000 0 sfc 130 ``` `grib_get -m`是`grib_get -n mars`的简写。 获取所有属于 statistics 命名空间的 key ``` $.\grib_get -w count=1 -n statistics ne_gmf.gra.2017050100000.grb2 317.949 250.369 284.773 15.9011 -0.0924059 -1.26255 0 ``` ### 设置输出格式 浮点数的输出格式可以通过 -F 选项使用 C 风格的输出语法设置。 - `-F "%.4f"` - 小数格式,带4位小数(1.2345) - `-F "%.4e"` - 指数格式,带4位小数(1.2345E-03) ``` $ grib_get -w count=1 -p maximum -F "%.6f" ne_gmf.gra.2017050100000.grb2 317.949199 $ grib_get -w count=1 -p maximum -F "%.4e" ne_gmf.gra.2017050100000.grb2 3.1795e+02 ```` 默认格式是 `-F ".10e"`。 ### stepRange 和 stepUnits step 总是使用整型打印。 默认打印的 step 单位是小时。 获取其他单位的 `step`,需要使用`-s`选项设置 `stepUnits`。 ``` $ grib_get -w count=1 -p stepRange ne_gmf.gra.2017050100012.grb2 0-12 $ grib_get -w count=1 -p stepRange -s stepUnits=m ne_gmf.gra.2017050100012.grb2 0-720 ``` stepUnits 可以设置为 `s, m, h, 3h, 6h, 12h, D, M, Y, 10Y, 30Y, C` ### 使用`grib_get`寻找最近邻点 GRIB 场中某个经纬度坐标点的最近邻点可以用`grib_get`找到,与`grib_ls`工作方式相同。 寻找北京1000百帕的温度: ``` $ grib_get -w count=51 -l 39.92,116.46 ne_gmf.gra.2017050100012.grb2 295.684 294.634 294.064 295.044 $ grib_get -w count=51 -F "%.5f" -P stepRange -l 39.92,116.46 ne_gmf.gra.2017050100012.grb2 12 295.68381 294.63381 294.06381 295.04381 ``` 选择 GRIB 文件必须包含格点数据。 ### 获取某个格点的数据值 输出 GRIB 要素场中特定个点的数值可以使用`grib_get`的`-i`选项。 例如,使用`grib_ls`寻找最近邻的 index,再使用`grib_get`获取该点的一系列值。 ``` $ grib_get -i 2159 -p shortName,dummy:s ne_gmf.gra.2017050100012.grb2 acpcp 10 ncpcp 10.00806427 ``` `dummy:s`用于在 shortName 和 value 间强制输出一个空格。 非格点数据也会返回值。
JavaScript
UTF-8
3,280
2.75
3
[]
no_license
import Routes from '../routes'; import Ajax from '../ajax'; /** * Class used to make all api's request */ class ApiRequest { /** * Get all items asynchronously. If something went wrong with the request, it returns null, else it returns array of items * * @returns {Array|null} */ GetAllItems = async () => { let data = await Ajax.GetData(Routes.api.menuItems.all); if (data === undefined || data.statusCode < 200 || data.statusCode > 399) { this.LogError(data); return null; } return data.value; } /** * Get an item asynchronously. If something went wrong with the request, it returns null, else it returns the item * * @param {int} itemId Item's id * @returns {any|null} items */ GetItem = async (itemId) => { let data = await Ajax.GetData(Routes.api.menuItems.get(itemId)); if (data === undefined || data.statusCode < 200 || data.statusCode > 399) { this.LogError(data); return null; } return data.value; } /** * Create an order * * @param {any} data order's data * @returns {any|null} order's data or null if it failed */ MakeOrder = async (data) => { let response = await Ajax.PostData(Routes.api.orders.post, data); if (response === undefined || response.statusCode < 200 || response.statusCode > 399) { this.LogError(response); return null; } return response.value; } /** * Get all orders * * @returns {Array|null} */ GetAllOrders = async () => { let response = await Ajax.GetData(Routes.api.orders.all); if (response === undefined || response.statusCode < 200 || response.statusCode > 399) { this.LogError(response); return null; } return response.value; } /** * Update an order * * @returns {Array|null} */ UpdateOrder = async (data) => { let response = await Ajax.PutData(Routes.api.orders.put(data.id), data); if (response === undefined || response.statusCode < 200 || response.statusCode > 399) { this.LogError(response); return null; } return response.value; } /** * Delete an order * * @returns {Array|null} */ DeleteOrder = async (id) => { let response = await Ajax.DeleteData(Routes.api.orders.delete(id)); if (response === undefined || response.statusCode < 200 || response.statusCode > 399) { this.LogError(response); return null; } return response.value; } /** * Get all deliveryMen * * @returns {Array|null|Promise} */ GetAllDeliveryMen = async () => { let response = await Ajax.GetData(Routes.api.deliveryMan.all); if (response === undefined || response.statusCode < 200 || response.statusCode > 399) { this.LogError(response); return null; } return response.value; } LogError = (response) => { console.log((response || { value: { error: 'An error occured during the proccess' } }).value.error); } } export default ApiRequest;
Python
UTF-8
136
3.90625
4
[]
no_license
for i in range(1,10,1): for j in range(2,10,1): print("%d * %d = %3d"%(j,i,(i*j)), end= ' | ') print("\n")
Python
UTF-8
586
3.15625
3
[]
no_license
T=int(input()) res=[] def check(s,t): i,j=0,0 len1=len(s) len2=len(t) for i in range(0,len2): if t[i]!=t[0]: break i=i if i>0 else 1 if i>len1: return "No" for j in range(i): if s[j]!=t[0]: return "No" while j<len1: while i<len2: if t[i]==s[j]: break i+=1 j+=1 if i==len2 and j==len1: return "Yes" else: return 'No' for i in range(T): s=input() t=input() res.append(check(s,t)) for i in range(T): print(res[i])
Rust
UTF-8
7,981
2.765625
3
[]
no_license
use crate::jsonrpc::Client; use crate::{Coalition, Error}; use serde_json::Value; pub struct MenuEntry { client: Client, path: Value, } pub struct GroupMenuEntry { client: Client, group_id: usize, path: Value, } pub struct CoalitionMenuEntry { client: Client, coalition: Coalition, path: Value, } pub struct SubMenu<C> where for<'de> C: serde::Serialize + serde::Deserialize<'de>, { client: Client, path: Value, mark: std::marker::PhantomData<C>, } pub struct GroupSubMenu<C> where for<'de> C: serde::Serialize + serde::Deserialize<'de>, { client: Client, group_id: usize, path: Value, mark: std::marker::PhantomData<C>, } pub struct CoalitionSubMenu<C> where for<'de> C: serde::Serialize + serde::Deserialize<'de>, { client: Client, coalition: Coalition, path: Value, mark: std::marker::PhantomData<C>, } impl MenuEntry { pub fn remove(self) -> Result<(), Error> { remove_entry(&self.client, self.path) } } impl GroupMenuEntry { pub fn remove(self) -> Result<(), Error> { remove_group_entry(&self.client, self.group_id, self.path) } } impl CoalitionMenuEntry { pub fn remove(self) -> Result<(), Error> { remove_coalition_entry(&self.client, self.coalition, self.path) } } impl<C> SubMenu<C> where for<'de> C: serde::Serialize + serde::Deserialize<'de>, { pub fn add_submenu(&self, name: &str) -> Result<SubMenu<C>, Error> { add_submenu(&self.client, name, Some(&self.path)) } pub fn add_command(&self, name: &str, command: C) -> Result<MenuEntry, Error> { add_command(&self.client, name, Some(&self.path), command) } pub fn remove(self) -> Result<(), Error> { remove_entry(&self.client, self.path) } } impl<C> GroupSubMenu<C> where for<'de> C: serde::Serialize + serde::Deserialize<'de>, { pub fn add_submenu(&self, name: &str) -> Result<GroupSubMenu<C>, Error> { add_group_submenu(&self.client, self.group_id, name, Some(&self.path)) } pub fn add_command(&self, name: &str, command: C) -> Result<GroupMenuEntry, Error> { add_group_command(&self.client, self.group_id, name, Some(&self.path), command) } pub fn remove(self) -> Result<(), Error> { remove_group_entry(&self.client, self.group_id, self.path) } } impl<C> CoalitionSubMenu<C> where for<'de> C: serde::Serialize + serde::Deserialize<'de>, { pub fn add_submenu(&self, name: &str) -> Result<CoalitionSubMenu<C>, Error> { add_coalition_submenu(&self.client, self.coalition, name, Some(&self.path)) } pub fn add_command(&self, name: &str, command: C) -> Result<CoalitionMenuEntry, Error> { add_coalition_command( &self.client, self.coalition, name, Some(&self.path), command, ) } pub fn remove(self) -> Result<(), Error> { remove_coalition_entry(&self.client, self.coalition, self.path) } } pub(crate) fn add_submenu<C>( client: &Client, name: &str, parent: Option<&Value>, ) -> Result<SubMenu<C>, Error> where for<'de> C: serde::Serialize + serde::Deserialize<'de>, { #[derive(Serialize)] struct Params<'a> { name: &'a str, path: Option<&'a Value>, } let path: Value = client.request("addGroupSubMenu", Some(Params { name, path: parent }))?; Ok(SubMenu { client: client.clone(), path, mark: std::marker::PhantomData, }) } pub(crate) fn add_group_submenu<C>( client: &Client, group_id: usize, name: &str, parent: Option<&Value>, ) -> Result<GroupSubMenu<C>, Error> where for<'de> C: serde::Serialize + serde::Deserialize<'de>, { #[derive(Serialize)] struct Params<'a> { #[serde(rename = "groupID")] group_id: usize, name: &'a str, path: Option<&'a Value>, } let path: Value = client.request( "addGroupSubMenu", Some(Params { group_id, name, path: parent, }), )?; Ok(GroupSubMenu { client: client.clone(), group_id, path, mark: std::marker::PhantomData, }) } pub(crate) fn add_coalition_submenu<C>( client: &Client, coalition: Coalition, name: &str, parent: Option<&Value>, ) -> Result<CoalitionSubMenu<C>, Error> where for<'de> C: serde::Serialize + serde::Deserialize<'de>, { #[derive(Serialize)] struct Params<'a> { coalition: Coalition, name: &'a str, path: Option<&'a Value>, } let path: Value = client.request( "addCoalitionSubMenu", Some(Params { coalition, name, path: parent, }), )?; Ok(CoalitionSubMenu { client: client.clone(), coalition, path, mark: std::marker::PhantomData, }) } pub(crate) fn add_command<C>( client: &Client, name: &str, parent: Option<&Value>, command: C, ) -> Result<MenuEntry, Error> where for<'de> C: serde::Serialize + serde::Deserialize<'de>, { #[derive(Serialize)] struct Params<'a, C> where C: serde::Serialize, { name: &'a str, path: Option<&'a Value>, command: C, } let path: Value = client.request( "addCommand", Some(Params { name, path: parent, command, }), )?; Ok(MenuEntry { client: client.clone(), path, }) } pub(crate) fn add_group_command<C>( client: &Client, group_id: usize, name: &str, parent: Option<&Value>, command: C, ) -> Result<GroupMenuEntry, Error> where for<'de> C: serde::Serialize + serde::Deserialize<'de>, { #[derive(Serialize)] struct Params<'a, C> where C: serde::Serialize, { #[serde(rename = "groupID")] group_id: usize, name: &'a str, path: Option<&'a Value>, command: C, } let path: Value = client.request( "addGroupCommand", Some(Params { group_id, name, path: parent, command, }), )?; Ok(GroupMenuEntry { client: client.clone(), group_id, path, }) } pub(crate) fn add_coalition_command<C>( client: &Client, coalition: Coalition, name: &str, parent: Option<&Value>, command: C, ) -> Result<CoalitionMenuEntry, Error> where for<'de> C: serde::Serialize + serde::Deserialize<'de>, { #[derive(Serialize)] struct Params<'a, C> where C: serde::Serialize, { coalition: Coalition, name: &'a str, path: Option<&'a Value>, command: C, } let path: Value = client.request( "addCoalitionCommand", Some(Params { coalition, name, path: parent, command, }), )?; Ok(CoalitionMenuEntry { client: client.clone(), coalition, path, }) } pub(crate) fn remove_entry(client: &Client, path: Value) -> Result<(), Error> { #[derive(Serialize)] struct Params { path: Value, } client.notification("removeEntry", Some(Params { path })) } pub(crate) fn remove_group_entry( client: &Client, group_id: usize, path: Value, ) -> Result<(), Error> { #[derive(Serialize)] struct Params { #[serde(rename = "groupID")] group_id: usize, path: Value, } client.notification("removeGroupEntry", Some(Params { group_id, path })) } pub(crate) fn remove_coalition_entry( client: &Client, coalition: Coalition, path: Value, ) -> Result<(), Error> { #[derive(Serialize)] struct Params { coalition: Coalition, path: Value, } client.notification("removeGroupEntry", Some(Params { coalition, path })) }
C
UTF-8
1,446
3.546875
4
[ "GPL-1.0-or-later", "GPL-2.0-only", "MIT" ]
permissive
/* * Copyright (c) 2002, Intel Corporation. All rights reserved. * Created by: rolla.n.selbak REMOVE-THIS AT intel DOT com * This file is licensed under the GPL license. For the full content * of this license, see the COPYING file at the top level of this * source tree. * Test that pthread_create() creates a new thread with attributes specified * by 'attr', within a process. * * Steps: * 1. Create a thread using pthread_create() * 2. Cancel that thread with pthread_cancel() * 3. If that thread doesn't exist, then it pthread_cancel() will return * an error code. This would mean that pthread_create() did not create * a thread successfully. */ #include <pthread.h> #include <stdio.h> #include <unistd.h> #include "posixtest.h" void *a_thread_func() { sleep(10); /* Shouldn't reach here. If we do, then the pthread_cancel() * function did not succeed. */ perror("Could not send cancel request correctly\n"); pthread_exit(0); return NULL; } int main() { pthread_t new_th; if(pthread_create(&new_th, NULL, a_thread_func, NULL) < 0) { perror("Error creating thread\n"); return PTS_UNRESOLVED; } /* Try to cancel the newly created thread. If an error is returned, * then the thread wasn't created successfully. */ if(pthread_cancel(new_th) != 0) { printf("Test FAILED: A new thread wasn't created\n"); return PTS_FAIL; } printf("Test PASSED\n"); return PTS_PASS; }
Java
UTF-8
534
2.625
3
[]
no_license
package com.ledgerCo.dao; import com.ledgerCo.models.Borrower; import java.util.HashMap; public class BorrowerDao implements Dao<Borrower> { public HashMap<String, Borrower> borrowers = new HashMap<>(); @Override public Borrower get(String name) { return borrowers.getOrDefault(name, null); } @Override public HashMap<String, Borrower> getAll() { return borrowers; } @Override public void save(Borrower borrower) { borrowers.put(borrower.getName(), borrower); } }
JavaScript
UTF-8
1,786
2.75
3
[]
no_license
import React, { Component } from 'react'; import io from 'socket.io-client'; import axios from 'axios'; import './Messages.css'; const socket = io.connect('http://localhost:4000') export default class Messages extends Component { constructor(props) { super(props); this.state= { userId: null, messages: [], userInput: '' } } componentDidMount() { socket.on('message dispatched', this.updateMessages); socket.on('welcome', this.setUserId); axios.get('/test').then(res => { console.log(res); }) } handleInput(e) { this.setState({userInput: e.target.value}) } sendMessage() { this.setState({messages: [...this.state.messages, {message: this.state.userInput}]}) } render() { console.log(this.state.messages) const{ messages, userInput, userId } = this.state; console.log(messages) const messagesToDisplay = messages.map((e, i) => { const styles = e.user === userId ? { alignSelf: 'flex-end', backgroundColor: '#2d96fb', color: 'white'} : { alignSelf: 'flex-end', backgroundColor: '#e5e6ea'} return( <p key={i} style={styles}> {e.message} </p> ) }); return( <div className="Messages"> <div className="messages">{messagesToDisplay}</div> <div className="input"> <input value={userInput} onChange={(e) => this.handleInput(e)} onKeyPress={this.handleEnter} /> <button onClick={e => this.sendMessage()}>Send</button> </div> </div> ) } }
Ruby
UTF-8
679
3.078125
3
[]
no_license
def pi places = 1000 digitCt = 0 q_, r_, t_, k_, n_, l_ = 1, 0, 1, 1, 3, 3 dot = nil loop do if 4 * q_ + r_ - t_ < n_ * t_ then digitCt += 1 if places > 0 && digitCt - 1 > places then break end yield n_ if dot.nil? then yield '.' dot = '.' end nr = 10 * (r_ - n_ * t_) n_ = ((10 * (3 * q_ + r_)) / t_) - 10 * n_ q_ *= 10 r_ = nr else nr = (2 * q_ + r_) * l_ nn = (q_ * (7 * k_ + 2) + r_ * l_) / (t_ * l_) q_ *= k_ t_ *= l_ l_ += 2 k_ += 1 n_ = nn r_ = nr end end end pi {|digit| print digit; $stdout.flush} puts
PHP
UTF-8
3,308
2.515625
3
[]
no_license
<?php namespace App\Controller; use Cake\ORM\TableRegistry; use App\Controller\AppController; use App\Form\AddFighterForm; use Cake\Event\Event; use Cake\Auth\DefaultPasswordHasher; /** * Controller utilisateur * Toutes les fonctions relatives aux joueurs */ class PlayersController extends AppController { /** * Autorisation d'accès aux pages d'inscription et de déconnexion sans connexion */ public function beforeFilter(Event $event) { parent::beforeFilter($event); $this->Auth->allow(['add', 'logout','pwdrecovery']); } /** * Ajout d'un utilisateur */ public function add() { $user = $this->Players->newEntity(); if ($this->request->is('post')) { $user = $this->Players->patchEntity($user, $this->request->getData()); //Vérifier si l'adresse mail est déjà utilisée (= présente dans la table Players) $playersEmail = TableRegistry::get('Players'); $query = $playersEmail ->find() ->select(['email']) ->where(['email' => $user->email]); if($query-> count() != 0) { $this->Flash->error(__("Cette adresse mail est déjà utilisée")); } else{ //Ajouter le compte if ($this->Players->save($user)) { $this->Flash->success(__("L'utilisateur a été sauvegardé. Il est maintenant temps de créer votre premier combattant.")); return $this->redirect(['controller' => 'Arenas', 'action' => 'fighter']); } else{ $this->Flash->error(__("Impossible d'ajouter l'utilisateur.")); } } } $this->set('user', $user); } /** * Connexion */ public function login() { $this->loadModel('Fighters'); if ($this->request->is('post')) { $user = $this->Auth->identify(); if ($user) { $this->Auth->setUser($user); //Vérification des champs 'next_action_time' du joueur pour le bon fonctionnement des points d'action $ptmax=$this->viewVars['PT_ACTION_MAX']; $tpsrecup=$this->viewVars['TPS_RECUP']; $this->Fighters->checkFighters($this->Auth->user('id'), $ptmax, $tpsrecup); return $this->redirect($this->Auth->redirectUrl()); }else{ $this->Flash->error(__('Votre adresse mail ou mot de passe est incorrect, veuillez réessayer')); } } } /** * Déconnexion */ public function logout() { return $this->redirect($this->Auth->logout()); } public function pwdrecovery() { $this->loadModel('Players'); if($this->request->is('post')){ $email=$this->request->getData('email'); $password=$this->request->getData('password'); $hasher = new DefaultPasswordHasher(); $this->Players->updatePwd($email, $hasher->hash($password)); return $this->redirect(['controller' => 'Players', 'action' => 'login']); } } }
Java
UTF-8
1,385
3.21875
3
[]
no_license
package isu; import java.awt.Image; import java.util.*; import javax.swing.ImageIcon; public class DestWall { private Image inputWall; private ImageIcon wall; private int x; private int y; private int wallSize = 40; //Description: The constructor for the Destructible Wall class, it creates a new object with the other wall image //Parameters: the x and y coordinates of the top left corner of the wall //Return: N/A public DestWall(int x, int y) { inputWall = new ImageIcon("destWall.png").getImage().getScaledInstance(wallSize, wallSize, Image.SCALE_DEFAULT); wall = new ImageIcon(inputWall); this.x = x; this.y = y; } // getter methods public Image getDestWallImage () { return wall.getImage(); } public int getDestWally () { return y; } public int getDestWallx() { return x; } /* hashCode Method * description: overrides hashSet to sort by x and y values * returns: int */ @Override public int hashCode() { return Objects.hash(x, y); } /* equals Method * description: overrides equals to compare x and y values * returns: boolean */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } DestWall other = (DestWall) obj; return x == other.x && y == other.y; } }
Java
UTF-8
88
1.789063
2
[]
no_license
package com.janani.lambda; public interface Interface1 { void method1(String s); }
C++
UTF-8
3,183
2.609375
3
[ "Apache-2.0" ]
permissive
/** * This program tests serial Slightly Compressible solver with an * acoustic wave in 2D duct case. * A Gaussian pulse is used as the time dependent BC with max velocity * equal to 6cm/s. * This test takes about 770s. */ #include "mpi_scnsim.h" #include "parameters.h" #include "utilities.h" extern template class Fluid::MPI::SCnsIM<2>; extern template class Fluid::MPI::SCnsIM<3>; using namespace dealii; int main(int argc, char *argv[]) { using namespace dealii; try { Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1); std::string infile("parameters.prm"); if (argc > 1) { infile = argv[1]; } Parameters::AllParameters params(infile); double L = 4, H = 1; auto gaussian_pulse = [dt = params.time_step](const Point<2> &p, const unsigned int component, const double time) -> double { auto time_value = [](double t) { return 6.0 * exp(-0.5 * pow((t - 0.5e-4) / 0.15e-4, 2)); }; if (component == 0 && std::abs(p[0]) < 1e-10) { double previous_value = time < 2 * dt ? 0.0 : time_value(time - dt); return time_value(time) - previous_value; } return 0; }; if (params.dimension == 2) { parallel::distributed::Triangulation<2> tria(MPI_COMM_WORLD); dealii::GridGenerator::subdivided_hyper_rectangle( tria, {8, 2}, Point<2>(0, 0), Point<2>(L, H), true); Fluid::MPI::SCnsIM<2> flow(tria, params); flow.add_hard_coded_boundary_condition(0, gaussian_pulse); flow.run(); // After the computation the max velocity should be ~ // the peak of the Gaussian pulse (with dispersion). auto solution = flow.get_current_solution(); auto v = solution.block(0); double vmax = Utils::PETScVectorMax(v); double verror = std::abs(vmax - 5.93) / 5.93; AssertThrow(verror < 1e-3, ExcMessage("Maximum velocity is incorrect!")); } else { AssertThrow(false, ExcNotImplemented()); } } catch (std::exception &exc) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Exception on processing: " << std::endl << exc.what() << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; } catch (...) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Unknown exception!" << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; } return 0; }
Java
UTF-8
1,708
2.25
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2020. * Created by YoloSanta * Created On 10/22/20, 1:23 AM */ package net.hcriots.hcfactions.bosses.eggs; import cc.fyre.stark.util.ItemBuilder; import net.hcriots.hcfactions.Hulu; import org.bukkit.Bukkit; import org.bukkit.event.Listener; import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.List; /** * Created by InspectMC * Date: 7/20/2020 * Time: 8:52 PM */ public abstract class BossEggAbility implements Listener { public BossEggAbility() { Bukkit.getServer().getPluginManager().registerEvents(this, Hulu.getInstance()); } public abstract String getName(); public abstract ItemStack getMaterial(); public abstract String getDisplayName(); public abstract List<String> getLore(); public ItemStack getItemStack() { return ItemBuilder.of(this.getMaterial().getType()) .name(this.getDisplayName() == null ? this.getName() : this.getDisplayName()) .setLore(this.getLore() == null ? new ArrayList<>() : this.getLore()) .build(); } public boolean isSimilar(ItemStack itemStack) { if (itemStack == null || itemStack.getItemMeta() == null) { return false; } if (itemStack.getItemMeta().getDisplayName() == null) { return false; } if (itemStack.getItemMeta().getLore() == null || itemStack.getItemMeta().getLore().isEmpty()) { return false; } return itemStack.getType() == this.getMaterial().getType() && itemStack.getItemMeta().getDisplayName().equals(this.getDisplayName()) && itemStack.getItemMeta().getLore().equals(this.getLore()); } }
C++
UTF-8
1,390
3.109375
3
[]
no_license
#include "geometry/Sphere.h" bool Sphere::hit(const Ray& ray, double minDistance, double maxDistance, HitRecord& hitRecord) const { Vector3 sphereCenterToRayOrigin = ray.getOrigin() - this->center; double a = ray.getDirection().lengthSquared(); double simplifiedB = ray.getDirection().dotProduct(sphereCenterToRayOrigin); double c = sphereCenterToRayOrigin.lengthSquared() - this->radius * this->radius; double discriminant = simplifiedB * simplifiedB - a * c; if (discriminant > 0) { double discriminantRoot = std::sqrt(discriminant); double root = (-simplifiedB - discriminantRoot) / a; if (processHitInformation(ray, hitRecord, root, minDistance, maxDistance)) { return true; } else { root = (-simplifiedB + discriminantRoot) / a; return processHitInformation(ray, hitRecord, root, minDistance, maxDistance); } } return false; } bool Sphere::processHitInformation(const Ray& ray, HitRecord& hitRecord, double hitRayDistance, double minDistance, double maxDistance) const { if (hitRayDistance > minDistance && hitRayDistance < maxDistance) { hitRecord.hitRayDistance = hitRayDistance; hitRecord.hitPoint = ray.getPosition(hitRecord.hitRayDistance); Vector3 outwardNormal = (hitRecord.hitPoint - this->center) / this->radius; hitRecord.setFaceNormal(ray, outwardNormal); hitRecord.material = material; return true; } return false; }
Markdown
UTF-8
456
2.59375
3
[ "MIT" ]
permissive
# 💻 Sobre o desafio Neste desafio, coloquei em pratica o conceito de passagem de propriedades para componentes filhos, criação de interfaces separadas, etc. Principais conceitos - Passar propriedades e funções para componentes - Componentização - Compartilhamento de interfaces no typescript Screenshot ![desafio02](https://user-images.githubusercontent.com/18725901/118734532-fc7f7400-b814-11eb-88ac-d89e5691bea1.png) Entregue 🚀 🚀 🚀
Java
UTF-8
262
1.570313
2
[]
no_license
package com.adn.test.dao; import com.adn.test.entity.Examen; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface ExamenRepository extends JpaRepository<Examen, Long> { }
Java
UTF-8
155
1.820313
2
[]
no_license
package com.ntgtask.whattoweather.domain.repository; public interface WeatherDataSource { void getWeatherStatus(double latitude, double longitude); }
SQL
UTF-8
2,987
4.40625
4
[]
no_license
--Find all accounts and sales reps in the Midwest region. SELECT r.name AS region, s.name AS rep, a.name AS account FROM region AS r JOIN sales_reps AS s ON s.region_id = r.id JOIN accounts AS a ON a.sales_rep_id = s.id WHERE r.name = 'Midwest' ORDER BY a.name; --Find all accounts and sales reps in the Midwest region who have a sales rep starting with "S." SELECT r.name AS region, s.name AS rep, a.name AS account FROM region AS r JOIN sales_reps AS s ON s.region_id = r.id JOIN accounts AS a ON a.sales_rep_id = s.id WHERE r.name = 'Midwest' AND s.name LIKE 'S%' ORDER BY a.name; --Find all accounts and sales reps in the Midwest region who have a sales rep whose last name starts with "K." SELECT r.name AS region, s.name AS rep, a.name AS account FROM region AS r JOIN sales_reps AS s ON s.region_id = r.id JOIN accounts AS a ON a.sales_rep_id = s.id WHERE r.name = 'Midwest' AND s.name = '% K%' ORDER BY a.name; --Find all regions, account names, and unit prices (plus one cent to avoid zero division error) for orders of standard over 100 units. SELECT r.name AS region, a.name AS account, o.total_amt_usd/(o.total+0.01) AS unit_price FROM region AS r JOIN sales_reps AS s ON r.id = s.region_id JOIN accounts AS a ON s.id = a.sales_rep_id JOIN orders AS o ON a.id = o.account_id WHERE o.standard_qty > 100; --Find all regions, account names, and unit prices (plus one cent to avoid zero division error) for orders of standard over 100 units and poster over 50 units. Start with the smallest orders. SELECT r.name AS region, a.name AS account, o.total_amt_usd/(o.total+0.01) AS unit_price FROM region AS r JOIN sales_reps AS s ON r.id = s.region_id JOIN accounts AS a ON s.id = a.sales_rep_id JOIN orders AS o ON a.id = o.account_id WHERE o.standard_qty > 100 AND poster_qty > 50 ORDER BY o.total_amt_usd; --Find all regions, account names, and unit prices (plus one cent to avoid zero division error) for orders of standard over 100 units and poster over 50 units. Start with the largest orders. SELECT r.name AS region, a.name AS account, o.total_amt_usd/(o.total+0.01) AS unit_price FROM region AS r JOIN sales_reps AS s ON r.id = s.region_id JOIN accounts AS a ON s.id = a.sales_rep_id JOIN orders AS o ON a.id = o.account_id WHERE o.standard_qty > 100 AND poster_qty > 50 ORDER BY o.total_amt_usd DESC; --Find all distinct channels for account #1001. SELECT DISTINCT a.name, w.channel FROM accounts AS a JOIN web_events AS w ON a.id = w.account_id WHERE a.id = 1001; --Find all account names, total sales quantity, and total sales dollars for the year 2015, starting with the last sale. SELECT w.occurred_at, a.name, o.total, o.total_amt_usd FROM accounts AS a JOIN web_events AS w ON a.id = w.account_id JOIN orders AS o ON a.id = o.account_id WHERE o.occurred_at BETWEEN '2015-01-01' AND '2016-01-01' ORDER BY o.occurred_at DESC;
C++
UTF-8
10,955
2.6875
3
[]
no_license
//2020/08/27 TomokiHirayama //Aug 28, 2020 Masahiro Furukawa modified // //this program is calcurating Inverse Kinematics(IK) //and save angle data into .csv file // #include <stdio.h> #include <stdlib.h> #include <math.h> #include <iostream> #include <string> #include "QueryPerformanceTimer.h" #include "mbed_Serial_binary.h" #include "Deg_List.h" //=================================================Function Definition======================================================= //======PI===== #define PI 3.14159265358979 //degree struct struct deg { double j1; double j2; double j3; }; //position struct struct Pos { double x; double y; double z; }; //arm's parameter(mm) double a_1 = 26.50; double a_2 = 120.03; double a_3 = 19.92; double d_4 = 123.08; //decide scale double scale; //xy->movespace=0 yz->movespace=1 zx->movespace=2 int movespace; // degree list // defined in "Deg_List.h" Deg_List dl; // binary communication // defined in "mbed_Serial_binary.h" #define NUM_OF_HEADER 2 #define NUM_OF_BUF 26 Com_Binary com; unsigned char sbuf[4 * 6 + NUM_OF_HEADER]; // global timer // defined in "QueryPerformanceTimer.h" QueryPerformanceTimer qpTime; //radian to degree double rad2deg(double rad) { return rad / PI * 180.0; } //degree to radian double deg2rad(double deg) { return deg / 180.0 * PI; } //Cos,Sin double C(double a) { return cos(a); } double S(double a) { return sin(a); } //===========================================Kinematics : Calcurate Hand position from J1J2J3================ double cal_fpx(deg J) { double J1 = deg2rad(J.j1); double J2 = deg2rad(J.j2); double J3 = deg2rad(J.j3); return (a_1 - a_2 * S(J2) - a_3 * S(J3) + d_4 * C(J3)) * C(J1); } double cal_fpy(deg J) { double J1 = deg2rad(J.j1); double J2 = deg2rad(J.j2); double J3 = deg2rad(J.j3); return (a_1 - a_2 * S(J2) - a_3 * S(J3) + d_4 * C(J3)) * S(J1); } double cal_fpz(deg J) { double J1 = deg2rad(J.j1); double J2 = deg2rad(J.j2); double J3 = deg2rad(J.j3); return a_2 * C(J2) + a_3 * C(J3) + d_4 * S(J3); } //===========================================Inverse Kinematics : Calcurate J1J2J3 from Hand position ================ double cal_J1(Pos pos) { double px = pos.x; double py = pos.y; double J1 = rad2deg(atan2(py, px)); return J1; } double cal_J2(Pos pos,deg J) { double J1 = deg2rad(J.j1); double J3 = deg2rad(J.j3); double px = pos.x; double py = pos.y; double pz = pos.z; double tmpA = -1 * a_1 + px * C(J1) + py * S(J1); double J2_1 = -1 * rad2deg(-1 * acos(-1 * (a_3 * C(J3) + d_4 * S(J3) - pz) / a_2));//+360; double J2_2 = -1 * rad2deg(acos(-1 * (a_3 * C(J3) + d_4 * S(J3) - pz) / a_2)); //check //printf("J2_1,J2_2=%lf , %lf\n", J2_1, J2_2); //if (J2_1 > 180.0) { J2_1 = J2_1 - 180.0; } //else if (J2_1 < -180.0) { J2_1 = J2_1 + 360; } //if (J2_2 > 180.0) { J2_2 = J2_2 - 180.0; } //else if (J2_2 < -180.0) { J2_2 = J2_2 + 360; } //printf("J2_1,J2_2=%lf , %lf\n", J2_1, J2_2); //Conditional Branch if ((J2_1 >= -150.0 && J2_1 <= -80.0) && (J2_2 < -150.0 || J2_2 > -80.0)) { return J2_1; } else if ((J2_2 >= -150.0 && J2_2 <= -80.0) && (J2_1 < -150.0 || J2_1 > -80.0)) { return J2_2; } else if ((J2_1 >= -150.0 && J2_1 <= -80.0) && (J2_2 >= -150.0 && J2_2 <= -80.0)) { //return EOF; <- //zenkai tukatta atai to onaji atai wo return suru, kai no rireki //if (/*zennkai no J2 */) // ; return J2_1; } else if ((J2_1 < -150.0 || J2_1 > -80.0) && (J2_2 < -150.0 || J2_2 > -80.0)) { return EOF; } // return J2_1; } double cal_J3(Pos pos,deg J) { double J1 = deg2rad(J.j1); double px = pos.x; double py = pos.y; double pz = pos.z; double tmpA = -1 * a_1 + px * C(J1) + py * S(J1); double bunbo = tmpA * tmpA + 2 * tmpA * d_4 - a_2 * a_2 + a_3 * a_3 + 2 * a_3 * pz + d_4 * d_4 + pz * pz; double ruto = -1 * tmpA * tmpA * tmpA * tmpA + 2 * tmpA * tmpA * a_2 * a_2 + 2 * tmpA * tmpA * a_3 * a_3 + 2 * tmpA * tmpA * d_4 * d_4 - 2 * tmpA * tmpA * pz * pz - a_2 * a_2 * a_2 * a_2 + 2 * a_2 * a_2 * a_3 * a_3 + 2 * a_2 * a_2 * d_4 * d_4 + 2 * a_2 * a_2 * pz * pz - a_3 * a_3 * a_3 * a_3 - 2 * a_3 * a_3 * d_4 * d_4 + 2 * a_3 * a_3 * pz * pz - d_4 * d_4 * d_4 * d_4 + 2 * d_4 * d_4 * pz * pz - pz * pz * pz * pz; //printf("ruto=%lf\n", ruto); double J3_1 = rad2deg(2 * atan2(-2 * tmpA * a_3 + 2 * d_4 * pz + sqrt(ruto), bunbo)); double J3_2 = rad2deg(-2 * atan2(2 * tmpA * a_3 - 2 * d_4 * pz + sqrt(ruto), bunbo)); //printf("ruto:%lf\n", a_3 * a_3 + d_4 * d_4 - pz * pz + 2 * pz - 1); //double J3_1 = rad2deg( 2 * atan2(d_4 - sqrt(a_3 * a_3 + d_4 * d_4 - pz * pz + 2 * pz - 1), a_3 + pz - 1)); //double J3_2 = rad2deg(-2 * atan2(d_4 + sqrt(a_3 * a_3 + d_4 * d_4 - pz * pz + 2 * pz - 1), a_3 + pz - 1)); // //printf("J3_1,J3_2=[%lf,%lf]\n", J3_1, J3_2); if (J3_1 > 180.0) { J3_1 = J3_1 - 180.0; } else if (J3_1 < -180.0) { J3_1 = J3_1 + 360; } if (J3_2 > 180.0) { J3_2 = J3_2 - 180.0; } else if (J3_2 < -180.0) { J3_2 = J3_2 + 360; } //printf("J3_1,J3_2=[%lf,%lf]\n", J3_1, J3_2); if ((J3_1 <= 90 && J3_1 >= -15) && (J3_2 > 90 || J3_2 < -15)) { return J3_1; } else if ((J3_2 <= 90 && J3_2 >= -15) && (J3_1 > -90 || J3_1 < -15)) { return J3_2; } else if ((J3_1 > 90 || J3_1 < -15) && (J3_2 > 90 || J3_2 < -15)) { return EOF; } else if ((J3_1 <= 90 || J3_1 >= -15) && (J3_2 <= 90 || J3_2 >= -15)) { return EOF; } } //define Frist Place deg iniJ() { deg J; J.j1 = 0.0; J.j2 = -120.0; J.j3 = 30.0; return J; } //=====================calculate Now Position======================= Pos cal_nowpos(Pos csvpos, Pos firstpos,double scale) { Pos pos; pos.x = firstpos.x + csvpos.x * scale; pos.y = firstpos.y + csvpos.y * scale; pos.z = firstpos.z + csvpos.z * scale; return pos; } //==========================Kinematics Set============================== Pos cal_kin(deg J) { Pos xyz; xyz.x = cal_fpx(J); xyz.y = cal_fpy(J); xyz.z = cal_fpz(J); return xyz; } //==========================Inverse Kinematics Set============================ deg cal_invkin(Pos pos) { deg J; J.j1 = cal_J1(pos); J.j3 = cal_J3(pos,J); J.j2 = cal_J2(pos,J); return J; } // void read_cal_J123(FILE* fp1,FILE* fp2) { deg master_J,posJ,csvJ;//,into csv Pos FirstPos,csvPos,nowPos; //calculate FirstPlace master_J = iniJ(); FirstPos = cal_kin(master_J); //scan for (int i = 0; i < 2458; i++) { //Decide which plane to turn if (movespace == 0) { fscanf_s(fp1, "%lf,%lf\n", &csvPos.x, &csvPos.y); csvPos.z = 0.0; } else if (movespace == 1) { fscanf_s(fp1, "%lf,%lf\n", &csvPos.y, &csvPos.z); csvPos.x = 0.0; } else { fscanf_s(fp1, "%lf,%lf\n", &csvPos.z, &csvPos.x); csvPos.y = 0.0; } //calculate Now Position nowPos = cal_nowpos(csvPos, FirstPos, scale); //calculate Inverse Kinematics posJ= cal_invkin(nowPos); //calculate the difference between angles input to the servo csvJ.j1 = posJ.j1 - master_J.j1; csvJ.j2 = posJ.j2 - master_J.j2; csvJ.j3 = posJ.j3 - master_J.j3; //Writing. fprintf(fp2, "%lf,%lf,%lf\n", csvJ.j1, csvJ.j2, csvJ.j3); // store angle list dl.add(csvJ.j1, csvJ.j2, csvJ.j3); } } void realtime_angle_sending() { int ret; double j1, j2, j3; unsigned char sbuf[4 * 6 + NUM_OF_HEADER]; printf("\n\n ... realtime_angle_sending ...\n\n"); // initialize pointer as zero dl.setStart(); // header sbuf[0] = '*'; sbuf[1] = '+'; // angular sequence trail do { // refer angular sequence ret = dl.getNext(&j1, &j2, &j3); // make byte list com.float2byte(&sbuf[0 + NUM_OF_HEADER], (float)j1); com.float2byte(&sbuf[4 + NUM_OF_HEADER], (float)j2); com.float2byte(&sbuf[8 + NUM_OF_HEADER], (float)j3); com.float2byte(&sbuf[12 + NUM_OF_HEADER], 0.0f); com.float2byte(&sbuf[16 + NUM_OF_HEADER], 0.0f); com.float2byte(&sbuf[20 + NUM_OF_HEADER], 0.0f); // send via serial port com.send_bytes(sbuf, NUM_OF_BUF); // constant time loop qpTime.wait(); } while (ret != -1); } //create savename std::string setname(int i) { std::string root = ".csv"; std::string name = "deg123data_scale_"; std::string space,scalesize; // Order of names created... 1/4xy,yz,zx 1/8xy,yz,zx 1/16xy,yz,zx // by using "if" ,"%",and "/" if (i % 3 == 0) { space = "xy"; movespace = 0; } else if (i % 3 == 1) { space = "yz"; movespace = 1; } else { space = "zx"; movespace = 2; } if (i / 3 == 0) { scalesize = "1_4"; scale = 0.25; } else if (i / 3 == 1) { scalesize = "1_8"; scale = 0.125; } else { scalesize = "1_16"; scale = 0.0625; } std::string savename = name + scalesize + space + root; //std::cout << savename << std::endl; //printf("%sn", savename.c_str()); return savename; } int main(void) { // timer qpTime.setFps(60); qpTime.wait(); FILE* fp1,*fp2; errno_t error_fp; const char* filename = "sweep.csv"; for (int i = 0; i < 9; i++) { // angle list to realize realtime angle sending dl.init(); printf("%d\n", i); error_fp = fopen_s(&fp1, filename, "r"); if (fp1==NULL) { printf("fp1 error!"); exit(0); } else { printf("fp1 open OK\n"); //create savename std::string tmp = setname(i); const char* savename = tmp.c_str(); printf("savename %s\n", savename); error_fp = fopen_s(&fp2, savename, "w"); if (fp2 == NULL) { printf("fp2 error!"); exit(0); } else { printf("fp2 Open OK\n"); //header fprintf(fp2, "J1,J2,J3\n"); printf("header writing OK\n"); read_cal_J123(fp1, fp2); printf("read_cal_J123 OK\n"); fclose(fp1); fclose(fp2); //free(fp2); } } // start realtime angle sending realtime_angle_sending(); } return 0; }
Java
UTF-8
1,942
3.046875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package programa.primeira.fase; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * * @author Camille */ public class NovoClass { public static void main(String[] args) throws FileNotFoundException, IOException { List<String> produtos = new ArrayList<>(); File banco = new File("C:\\Users\\Camille\\Documents\\NetBeansProjects\\Cadastro\\src\\java\\banco\\banco"); FileReader converteParaBufferedLer = new FileReader(banco); BufferedReader ler = new BufferedReader(converteParaBufferedLer); while (ler.ready()) { String linha = ler.readLine(); String idForm = linha.substring(0, 4); produtos.add(linha); } ler.close(); converteParaBufferedLer.close(); // int i = 0; // // while (i < produtos.size()) { // // System.out.println(produtos.get(i)); // // String s = produtos.get(i).substring(0, 4); // // System.out.println(s); // // if (s.equals("3111")) { // System.out.println("ex: "+produtos.get(i)); // produtos.remove(produtos.get(i)); // // } // if (!produtos.contains("3111")) { // i++; // } // // } System.out.println("--------lista---------"); for (int i = 0; i < produtos.size(); i++) { System.out.println(produtos.get(i)); } } }
Java
UTF-8
1,404
1.742188
2
[]
no_license
package CurrentUser.Model; public class CurrentUserBean { public String areaname; public String departmentname; public String officename; public String assetdaesang; public String assetreceive; public String noassetdaesang; public String noassetreceive; public String getOfficename() { return officename; } public void setOfficename(String officename) { this.officename = officename; } public String getAreaname() { return areaname; } public void setAreaname(String areaname) { this.areaname = areaname; } public String getDepartmentname() { return departmentname; } public void setDepartmentname(String departmentname) { this.departmentname = departmentname; } public String getAssetdaesang() { return assetdaesang; } public void setAssetdaesang(String assetdaesang) { this.assetdaesang = assetdaesang; } public String getAssetreceive() { return assetreceive; } public void setAssetreceive(String assetreceive) { this.assetreceive = assetreceive; } public String getNoassetdaesang() { return noassetdaesang; } public void setNoassetdaesang(String noassetdaesang) { this.noassetdaesang = noassetdaesang; } public String getNoassetreceive() { return noassetreceive; } public void setNoassetreceive(String noassetreceive) { this.noassetreceive = noassetreceive; } }
Markdown
UTF-8
1,112
2.9375
3
[]
no_license
Ramayana ============= **Introduction:** Book about Ramayana ( One of the two great epics of Hinduism ) ascribed by Valmiki The Ramayana consists of 24,000 verses in seven books (kāṇḍas) and 500 cantos (sargas) Ramayana tells the story of Rama (an avatar of the Hindu supreme-god Vishnu), whose wife Sita is abducted by Ravana, the king of Lanka (current day Sri Lanka). Thematically, the Ramayana explores human values and the concept of dharma. The seven kandas (books or maybe chapters or phases) of Ramayana are as follows: - Bāla Kāṇḍa (Book of childhood) - Ayodhya Kāṇḍa (Book of ayodhya)3 - Araṇya Kāṇḍa (Book of the forest) - Kishkindha Kāṇḍa (Book of the monkey kingdom) - Sundara Kāṇḍa (Book of beauty) - Yuddha Kāṇḍa (Book of war, also known as Lanka Kanda) - Uttara Kāṇḍa (Last book) **Development** I/we would like to create a portable version of epic Ramayana in any format (html,pdf,word etc) to preserve one of the best books ever written in hindu mythology. We would appreciate if anyone could provide good resources to start.
TypeScript
UTF-8
6,426
3.25
3
[ "MIT" ]
permissive
import diff_match_patch, { DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL, Diff, } from 'diff-match-patch' const clc = require('cli-color') const SkippedLinesMarker = `\n---` /** * Compares code using Google's diff_match_patch and displays the results in the console. * @param codeA * @param codeB * @param lineBuff the number of lines to display before and after each change. */ export const diffCode = (codeA: string, codeB: string, lineBuff: number) => { // @ts-ignore const dmp = new diff_match_patch() const diff = dmp.diff_main(codeA, codeB) dmp.diff_cleanupSemantic(diff) const linesB = countLines(codeB) + 1 diff_pretty(diff, linesB, lineBuff) } /** * Convert a diff array into human-readable for the console * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples. * @param lines number of a lines in the second contract B * @param lineBuff number of a lines to output before and after the change */ const diff_pretty = (diffs: Diff[], lines: number, lineBuff = 2) => { const linePad = lines.toString().length let output = '' let diffIndex = 0 let lineCount = 1 const firstLineNumber = '1'.padStart(linePad) + ' ' for (const diff of diffs) { diffIndex++ const initialLineNumber = diffIndex <= 1 ? firstLineNumber : '' const op = diff[0] // Operation (insert, delete, equal) const text: string = diff[1] // Text of change. switch (op) { case DIFF_INSERT: // If first diff then we need to add the first line number const linesInserted = addLineNumbers(text, lineCount, linePad) output += initialLineNumber + clc.green(linesInserted) lineCount += countLines(text) break case DIFF_DELETE: // zero start line means blank line numbers are used const linesDeleted = addLineNumbers(text, 0, linePad) output += initialLineNumber + clc.red(linesDeleted) break case DIFF_EQUAL: const eolPositions = findEOLPositions(text) // If no changes yet if (diffIndex <= 1) { output += lastLines(text, eolPositions, lineBuff, linePad) } // if no more changes else if (diffIndex === diffs.length) { output += firstLines( text, eolPositions, lineBuff, lineCount, linePad, ) } else { // else the first n lines and last n lines output += firstAndLastLines( text, eolPositions, lineBuff, lineCount, linePad, ) } lineCount += eolPositions.length break } } output += '\n' console.log(output) } /** * Used when there is no more changes left */ const firstLines = ( text: string, eolPositions: number[], lineBuff: number, lineStart: number, linePad: number, ): string => { const lines = text.slice(0, eolPositions[lineBuff]) return addLineNumbers(lines, lineStart, linePad) } /** * Used before the first change */ const lastLines = ( text: string, eolPositions: number[], lineBuff: number, linePad: number, ): string => { const eolFrom = eolPositions.length - (lineBuff + 1) let lines = text let lineCount = 1 if (eolFrom >= 0) { lines = eolFrom >= 0 ? text.slice(eolPositions[eolFrom] + 1) : text lineCount = eolFrom + 2 } const firstLineNumber = lineCount.toString().padStart(linePad) + ' ' return firstLineNumber + addLineNumbers(lines, lineCount, linePad) } /** * Used between changes to show the lines after the last change and before the next change. * @param text * @param eolPositions * @param lineBuff * @param lineStart * @param linePad */ const firstAndLastLines = ( text: string, eolPositions: number[], lineBuff: number, lineStart: number, linePad: number, ): string => { if (eolPositions.length <= 2 * lineBuff) { return addLineNumbers(text, lineStart, linePad) } const endFirstLines = eolPositions[lineBuff] const eolFrom = eolPositions.length - (lineBuff + 1) const startLastLines = eolPositions[eolFrom] if (startLastLines <= endFirstLines) { return addLineNumbers(text, lineStart, linePad) } // Lines after the previous change let lines = text.slice(0, endFirstLines) let output = addLineNumbers(lines, lineStart, linePad) output += SkippedLinesMarker // Lines before the next change lines = text.slice(startLastLines) const lineCount = lineStart + eolFrom output += addLineNumbers(lines, lineCount, linePad) return output } /** * Gets the positions of the end of lines in the string * @param text */ const findEOLPositions = (text: string): number[] => { const eolPositions: number[] = [] text.split('').forEach((c, i) => { if (c === '\n') { eolPositions.push(i) } }) return eolPositions } /** * Counts the number of carriage returns in a string * @param text */ const countLines = (text: string): number => (text.match(/\n/g) || '').length /** * Adds left padded line numbers to each line. * @param text with the lines of code * @param lineStart the line number of the first line in the text. If zero, then no lines numbers are added. * @param linePad the width of the largest number which may not be in the text */ const addLineNumbers = ( text: string, lineStart: number, linePad: number, ): string => { let lineCount = lineStart let textWithLineNumbers = '' text.split('').forEach((c, i) => { if (c === '\n') { if (lineStart > 0) { textWithLineNumbers += `\n${(++lineCount) .toString() .padStart(linePad)} ` } else { textWithLineNumbers += `\n${' '.repeat(linePad)} ` } } else { textWithLineNumbers += c } }) return textWithLineNumbers }
Java
UTF-8
1,941
2.296875
2
[]
no_license
package com.brand.entity; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.Length; @Entity @Table(name = "master_devices") public class MasterDevice implements Serializable { private static final long serialVersionUID = -295290316133064573L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Long id; @Column(name = "serial_number", unique = true, nullable = false) private String serialNumber; @Column(name = "device_name") private String name; @Column(name = "address_IPv4") private String addressIPv4; @Size(max = 10, message = "maximum_10_elements") @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true) private List<Device> devices = new ArrayList<>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getSerialNumber() { return serialNumber; } public void setSerialNumber(String serialNumber) { this.serialNumber = serialNumber; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddressIPv4() { return addressIPv4; } public void setAddressIPv4(String addressIPv4) { this.addressIPv4 = addressIPv4; } public List<Device> getDevices() { return devices; } public void setDevices(List<Device> devices) { this.devices = devices; } }
Java
UTF-8
1,446
3.40625
3
[]
no_license
package com.company.lab10; import java.util.concurrent.ThreadLocalRandom; public class RaceCarRunnable extends Car implements Runnable{ private int passed; private int distance; private boolean isFinish; public int getPassed(){ return passed; } public int getDistance(){ return distance; } public RaceCarRunnable(String n, int s,int d) { super(n, s); distance=d; } public double getRandomSpeed(){ return ThreadLocalRandom.current().nextInt(getMaxSpeed()/2, getMaxSpeed()); // return getMaxSpeed()/2+(Math.random()*getMaxSpeed()/2); } public static void main(String[] args) { RaceCarRunnable raceCar=new RaceCarRunnable("Mers",250,200); // System.out.println(raceCar.getName()+"=>speed :"+getRandomSpeed()+"; progress :"+getPassed()+"/"+getDistance()); // raceCar.getPassed(); Thread car = new Thread(raceCar); car.start(); } @Override public void run() { while (!isFinish) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } double carSpeed=getRandomSpeed(); passed+=carSpeed*1000/3600; if (passed>=distance){ isFinish=true; } System.out.println(getName()+"=>speed :"+getRandomSpeed()+"; progress :"+passed+"/"+getDistance()); } } }
Python
UTF-8
7,157
2.828125
3
[]
no_license
from dronekit import connect, VehicleMode, LocationGlobal, LocationGlobalRelative from pymavlink import mavutil # Needed for command message definitions import time import math # Connect to the Vehicle connection_string = '/dev/ttyAMA0' print 'Connecting to vehicle on: %s' % connection_string vehicle = connect(connection_string, wait_ready=True, baud=57600) def arm_and_takeoff(aTargetAltitude): """ Arms vehicle and fly to aTargetAltitude. """ print "Basic pre-arm checks" # Don't let the user try to arm until autopilot is ready while not vehicle.is_armable: print " Waiting for vehicle to initialise..." time.sleep(1) print "Arming motors" # Copter should arm in GUIDED mode vehicle.mode = VehicleMode("GUIDED") vehicle.armed = True while not vehicle.armed: print " Waiting for arming..." time.sleep(1) print "Taking off!" vehicle.simple_takeoff(aTargetAltitude) # Take off to target altitude # Wait until the vehicle reaches a safe height before processing the goto (otherwise the command # after Vehicle.simple_takeoff will execute immediately). while True: print " Altitude: ", vehicle.location.global_relative_frame.alt if vehicle.location.global_relative_frame.alt>=aTargetAltitude*0.95: #Trigger just below target alt. print "Reached target altitude" break time.sleep(1) def condition_yaw(heading, relative=False): """ Send MAV_CMD_CONDITION_YAW message to point vehicle at a specified heading (in degrees). This method sets an absolute heading by default, but you can set the `relative` parameter to `True` to set yaw relative to the current yaw heading. By default the yaw of the vehicle will follow the direction of travel. After setting the yaw using this function there is no way to return to the default yaw "follow direction of travel" behaviour (https://github.com/diydrones/ardupilot/issues/2427) For more information see: http://copter.ardupilot.com/wiki/common-mavlink-mission-command-messages-mav_cmd/#mav_cmd_condition_yaw """ if relative: is_relative = 1 #yaw relative to direction of travel else: is_relative = 0 #yaw is an absolute angle # create the CONDITION_YAW command using command_long_encode() msg = vehicle.message_factory.command_long_encode( 0, 0, # target system, target component mavutil.mavlink.MAV_CMD_CONDITION_YAW, #command 0, #confirmation heading, # param 1, yaw in degrees 0, # param 2, yaw speed deg/s 1, # param 3, direction -1 ccw, 1 cw is_relative, # param 4, relative offset 1, absolute angle 0 0, 0, 0) # param 5 ~ 7 not used # send command to vehicle vehicle.send_mavlink(msg) """ Functions that move the vehicle by specifying the velocity components in each direction. The two functions use different MAVLink commands. The main difference is that depending on the frame used, the NED velocity can be relative to the vehicle orientation. The methods include: * send_ned_velocity - Sets velocity components using SET_POSITION_TARGET_LOCAL_NED command * send_global_velocity - Sets velocity components using SET_POSITION_TARGET_GLOBAL_INT command """ def send_ned_velocity(velocity_x, velocity_y, velocity_z, duration): """ Move vehicle in direction based on specified velocity vectors and for the specified duration. This uses the SET_POSITION_TARGET_LOCAL_NED command with a type mask enabling only velocity components (http://dev.ardupilot.com/wiki/copter-commands-in-guided-mode/#set_position_target_local_ned). Note that from AC3.3 the message should be re-sent every second (after about 3 seconds with no message the velocity will drop back to zero). In AC3.2.1 and earlier the specified velocity persists until it is canceled. The code below should work on either version (sending the message multiple times does not cause problems). See the above link for information on the type_mask (0=enable, 1=ignore). At time of writing, acceleration and yaw bits are ignored. """ msg = vehicle.message_factory.set_position_target_local_ned_encode( 0, # time_boot_ms (not used) 0, 0, # target system, target component mavutil.mavlink.MAV_FRAME_LOCAL_NED, # frame 0b0000111111000111, # type_mask (only speeds enabled) 0, 0, 0, # x, y, z positions (not used) velocity_x, velocity_y, velocity_z, # x, y, z velocity in m/s 0, 0, 0, # x, y, z acceleration (not supported yet, ignored in GCS_Mavlink) 0, 0) # yaw, yaw_rate (not supported yet, ignored in GCS_Mavlink) # send command to vehicle on 1 Hz cycle for x in range(0,duration): vehicle.send_mavlink(msg) time.sleep(1) def send_global_velocity(velocity_x, velocity_y, velocity_z, duration): """ Move vehicle in direction based on specified velocity vectors. This uses the SET_POSITION_TARGET_GLOBAL_INT command with type mask enabling only velocity components (http://dev.ardupilot.com/wiki/copter-commands-in-guided-mode/#set_position_target_global_int). Note that from AC3.3 the message should be re-sent every second (after about 3 seconds with no message the velocity will drop back to zero). In AC3.2.1 and earlier the specified velocity persists until it is canceled. The code below should work on either version (sending the message multiple times does not cause problems). See the above link for information on the type_mask (0=enable, 1=ignore). At time of writing, acceleration and yaw bits are ignored. """ msg = vehicle.message_factory.set_position_target_global_int_encode( 0, # time_boot_ms (not used) 0, 0, # target system, target component mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT_INT, # frame 0b0000111111000111, # type_mask (only speeds enabled) 0, # lat_int - X Position in WGS84 frame in 1e7 * meters 0, # lon_int - Y Position in WGS84 frame in 1e7 * meters 0, # alt - Altitude in meters in AMSL altitude(not WGS84 if absolute or relative) # altitude above terrain if GLOBAL_TERRAIN_ALT_INT velocity_x, # X velocity in NED frame in m/s velocity_y, # Y velocity in NED frame in m/s velocity_z, # Z velocity in NED frame in m/s 0, 0, 0, # afx, afy, afz acceleration (not supported yet, ignored in GCS_Mavlink) 0, 0) # yaw, yaw_rate (not supported yet, ignored in GCS_Mavlink) # send command to vehicle on 1 Hz cycle for x in range(0,duration): vehicle.send_mavlink(msg) time.sleep(1) #Arm and take of to altitude of 2 meters so we can still grab it in case we need to. arm_and_takeoff(3) time.sleep(10) """ The example is completing. LAND at current location. """ print("Setting LAND mode...") vehicle.mode = VehicleMode("LAND") #Close vehicle object before exiting script print "Close vehicle object" vehicle.close() print("Completed")
C#
UTF-8
4,618
3.375
3
[]
no_license
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using CustomListClassProject; namespace CustomUnitTestProject1 { [TestClass] public class UnitTest1 { [TestMethod] public void Add_AddItemToEmptyList_ItemGoesToIndexZero() { //Arange CustomList<int> testList = new CustomList<int>(); int value = 4; int expected = 4; int actual; //Act testList.Add(value); actual = testList[0]; //Assert Assert.AreEqual(expected, actual); } [TestMethod] public void Add_AddItemToEmptyList_CountIncrements() { //Arrange CustomList<string> testList = new CustomList<string>(); int expected = 1; int actual; //Act testList.Add("Bold"); actual = testList.Count; //Assert Assert.AreEqual(expected, actual); } [TestMethod] public void Add_AddItemToListWithItemsAlreadyInIt_NewItemGoesTOLastIndex() { //Arrange CustomList<bool> testList = new CustomList<bool>(); bool expected = true; bool actual; testList.Add(false); testList.Add(true); testList.Add(false); testList.Add(false); testList.Add(true); //Act testList.Add(true); actual = testList[4]; //Assert Assert.AreEqual(expected, actual); } [TestMethod] public void Add_AddMultipleItemsToList_CheckItemCount() { //Arrange CustomList<int> testList = new CustomList<int>(); int expected = 4; int actual; testList.Add(1); testList.Add(2); testList.Add(3); //Act testList.Add(4); actual = testList.count; //Assert Assert.AreEqual(expected, actual); } [TestMethod] public void Add_AddItemsToExceedList_CheckToSeeIfCapacityIncreases() { //Arrange CustomList<string> testList = new CustomList<string>(); int expected = 8; int actual; testList.Add("Eagles"); testList.Add("Packers"); testList.Add("Bears"); testList.Add("Vikings"); //Act testList.Add("Cowboys"); actual = testList.capacity; //Assert Assert.AreEqual(expected, actual); } [TestMethod] public void Remove_RemoveItemFromList_RemoveItemFromIndexThree() { //Arrange CustomList<int> testList = new CustomList<int>(); int expected = 3; int actual; testList.Add(1); testList.Add(2); testList.Add(3); testList.Add(4); //Act testList.Remove(1); actual = testList[2]; //Assert Assert.AreEqual(expected, actual); } [TestMethod] public void Remove_RemoveItemFromList_CountIncrements() { //Arrange CustomList<string> testList = new CustomList<string>(); int expected = 1; int actual; testList.Add("Time"); testList.Add("Bold"); //Act testList.Remove("Bold"); actual = testList.count; //Asseert Assert.AreEqual(expected, actual); } [TestMethod] public void Remove_RemoveItemThatDoesNotExistInList_CountShouldNotChange() { //Arrange CustomList<int> testList = new CustomList<int>(); int expected = 4; int actual; testList.Add(4); testList.Add(5); testList.Add(6); testList.Add(7); //Act testList.Remove(8); actual = testList.count; //Assert Assert.AreEqual(expected, actual); } [TestMethod] public void Remove_RemoveFirstIndex_CheckCount() { } [TestMethod] public void TestZip() { //Arrange CustomList<string> left = new CustomList<string>() {"one","two","three","four" }; CustomList<int> right = new CustomList<int>() {1,2,3,4 }; } } }
JavaScript
UTF-8
786
2.59375
3
[]
no_license
function reducer(state = { sales: [], currentChart: { chart: 'retailSales', description: 'RETAIL SALES', color: 'blue' } },action) { switch (action.type) { case "SET_SUMMARY": return ({ ...state, summary: { ...action.payload } }) case "SET_TAGS": return ({ ...state, tags: action.payload.tags }) case "SET_SALES": return ({ ...state, sales: action.payload.sales }) case "SET_CURRENT_CHART": return ({ ...state, currentChart: { chart: action.payload.chart, description: action.payload.description, color: action.payload.color } }) default: return state; } } export default reducer;
Shell
UTF-8
653
3.09375
3
[]
no_license
#------------------------------------------------------------- # bash aliases #------------------------------------------------------------- alias df='df -kTh' alias lr='ll -R' # Recursive ls. alias tree='tree -Csuh' # Nice alternative to 'recursive ls' ... alias ..='cd ..' # Pretty-print of some PATH variables: alias path='echo -e ${PATH//:/\\n}' alias ldlibpath='echo -e ${LD_LIBRARY_PATH//:/\\n}' alias modulepath='echo -e ${MODULEPATH//:/\\n}' # Git commands alias s='git status' # Search history by pressing up (backward) and down (forward) arrow #bind '"\e[A": history-search-backward' #bind '"\e[B": history-search-forward'
C#
UTF-8
6,986
2.6875
3
[]
no_license
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MonoTetris2; namespace Game1 { // TODO: Make this intantiate once and just change what block is the current one. public class BlockController { private bool _active = true; private int _count; private const int FallSpeed = 1; private int _fallSpeed; static public float TotalCountDuration = 1.0f; static public float CurrentCountDuration = TotalCountDuration; private float _countDuration = CurrentCountDuration; private float _currentTime; private bool _keyHasBeenPressed; private Texture2D sprite; private ActiveBlock _currentBlockPattern; // There needs to be a singular static grid to check things on. public BlockController(Texture2D sprite, ActiveBlock currentBlockPattern) { this.sprite = sprite; _count = 0; _currentBlockPattern = currentBlockPattern; } public bool SetNewBlock(ActiveBlock newBlock) { foreach (var ele in newBlock.GetPos()) { if (IsValidMove(ele)) continue; return false; } _currentBlockPattern = newBlock; _count = 0; _active = true; return true; } public List<Vector2> GetPos() { return _currentBlockPattern.GetPos(); } public Color GetColor() { return _currentBlockPattern.GetColor(); } private bool IsValidMove(Vector2 toCheck) { if (toCheck.X >= MonoTetris2.Game1.WindowBounds.Right || toCheck.X < MonoTetris2.Game1.WindowBounds.Left || toCheck.Y + sprite.Height > MonoTetris2.Game1.WindowBounds.Bottom) return false; foreach (List<Block> list in MonoTetris2.Game1.grid) { if (list.Count > 0) { // If the block isn't in the same row then don't bother checking it if ((int)list[0].GetPos().Y != (int)toCheck.Y) continue; } foreach (Block blk in list) { if (toCheck == blk.GetPos()) return false; } } return true; } public void Move(Vector2 toMove) { foreach (var ele in _currentBlockPattern.GetPos()) { if (IsValidMove(ele + toMove)) continue; if (!(_currentTime < _countDuration)) _count++; return; } _count = 0; for(int i = 0; i < _currentBlockPattern.GetPos().Count; i++) { _currentBlockPattern.GetPos()[i] += toMove; } } // Draws the active block public void Draw(SpriteBatch spriteBatch, Texture2D sprite) { _currentBlockPattern.Draw(spriteBatch, sprite); } public void Update(GameTime gameTime) { if (Keyboard.GetState().IsKeyDown(Keys.Down)) { if (!_keyHasBeenPressed) { _keyHasBeenPressed = true; _currentTime = 0; } _fallSpeed = 6; } else { _countDuration = CurrentCountDuration; } if (Keyboard.GetState().IsKeyDown(Keys.X)) { if (!_keyHasBeenPressed) { _keyHasBeenPressed = true; _currentTime = 0; } _fallSpeed = 200; } else { _countDuration = CurrentCountDuration; } if (Keyboard.GetState().IsKeyDown(Keys.Right) && !_keyHasBeenPressed) { Move(new Vector2(sprite.Width, 0)); _keyHasBeenPressed = true; } else if (Keyboard.GetState().IsKeyDown(Keys.Left) && !_keyHasBeenPressed) { Move(new Vector2(-sprite.Width, 0)); _keyHasBeenPressed = true; } else if (Keyboard.GetState().IsKeyDown(Keys.Up) && !_keyHasBeenPressed) { List<Vector2> rotations = _currentBlockPattern.Rotate(); List<Vector2> kickbacks = new List<Vector2> { new Vector2(0, 0), new Vector2(0, -sprite.Height), new Vector2(sprite.Width, 0), new Vector2(-sprite.Width, 0), new Vector2(sprite.Width * 2, 0), new Vector2(-sprite.Width * 2, 0) }; // Tries rotating the block in place and if not possible tries one place to the left, to the right // etc (the kickbacks list) until it finds a valid place or not. foreach (Vector2 kickback in kickbacks) { List<Vector2> validRotation = new List<Vector2>(); foreach (Vector2 rotation in rotations) { if (IsValidMove(rotation + kickback)) { validRotation.Add(rotation + kickback); } else { break; } } if (validRotation.Count == 4) { _currentBlockPattern.SetPos(validRotation); _keyHasBeenPressed = true; return; } } } if (Keyboard.GetState().IsKeyUp(Keys.Left) && Keyboard.GetState().IsKeyUp(Keys.Right) && Keyboard.GetState().IsKeyUp(Keys.Up) && Keyboard.GetState().IsKeyUp(Keys.Down) && Keyboard.GetState().IsKeyUp(Keys.X)) { _keyHasBeenPressed = false; _fallSpeed = FallSpeed; } _countDuration = CurrentCountDuration / _fallSpeed; _currentTime += (float)gameTime.ElapsedGameTime.TotalSeconds; //Time passed since last Update() if (!(_currentTime > _countDuration)) return; Move(new Vector2(0f, sprite.Height)); _active = _count < 2; _currentTime -= _countDuration; } public bool IsActive() { return _active; } } }
Shell
UTF-8
870
2.515625
3
[]
no_license
# $Id: PKGBUILD 35938 2009-04-18 11:42:35Z andrea $ # Maintainer: Jason Chu <jason@archlinux.org> pkgname=pacbuild pkgver=0.4 pkgrel=2 pkgdesc="A distributed build management system" arch=(i586 i686 x86_64) url="http://groups.google.com/group/pacbuild" license=("GPL") depends=('snarf' 'python-sqlobject' 'python-pysqlite') backup=('etc/appleConfig.py' 'etc/strawberryConfig.py' 'etc/mkchroot.conf') source=(ftp://ftp.archlinux.org/other/pacbuild/$pkgname-$pkgver.tar.gz) md5sums=('ad467a286046882ddc0a79b9e7c1b60e') sha1sums=('1af9f97dc57fb273747a44bc96502c417b83121a') build() { cd $srcdir/$pkgname-$pkgver python setup.py install --root $pkgdir || return 1 touch $pkgdir/etc/appleConfig.pyc touch $pkgdir/etc/strawberryConfig.pyc install -d $pkgdir/etc/rc.d install -m 755 apple.rcd $pkgdir/etc/rc.d/apple install -m 755 strawberry.rcd $pkgdir/etc/rc.d/strawberry }
JavaScript
UTF-8
1,443
3.1875
3
[]
no_license
// We use testing features to run quick tests across our applications to make sure everything is working fine // The framework we are using for this course is called Jest, and is designed by Facebook to work with React very well // We are going to install Jest, but it is not the kind of thing that we need to import into our project // It is more like live-server or webpack where we use it from the command line // Since we installed it locally it exists in package.json, and we are going to create a script for it that we can run to use it // To use it, we need to create test files in our project where we can define our test cases // Inside the source folder, we create a test folder to hold our test files // The syntax we use in naming our files inside of the test folder needs to include .test.js on the end // For our test, we create a function // Then we call a method provided by Jest called test() // The first argument for test() is a string explaining what we are testing and what we want to see the code do // The second argument for test() is an arrow function with our test cases for our code inside // We also get access to things provided by Jest, such as functions in the library that allows us to make assertions about our code // For expect(), we pass in the value we want to make an assertion about, then we add on a method from Jest // A common one is toBe, which checks if the first value equals whatever is passed in
Python
UTF-8
422
2.546875
3
[ "MIT" ]
permissive
import unittest import api.photo2song as p2s class TestPhoto2Song(unittest.TestCase): def test_photo_to_song(self): image_urls = [ "https://oxfordportal.blob.core.windows.net/vision/Thumbnail/1.jpg", "https://oxfordportal.blob.core.windows.net/vision/Thumbnail/4.jpg" ] result = p2s.convert(image_urls) self.assertTrue("mood" in result) print(result)
JavaScript
UTF-8
1,657
2.71875
3
[]
no_license
import {QUESTION_ADD,QUESTION_DELETE,QUESTION_GETALL,QUESTION_GETALL_SUCCESS,QUESTION_GETALL_FAILURE,QUESTION_UPDATE} from '../actions/actionTypes' const initialState = { Questions : [ ], loading : false } const reducer = (state = initialState, action) => { switch(action.type){ case QUESTION_ADD: return { ...state, Questions : [...state.Questions,action.question] } case QUESTION_DELETE: let QuestionTotal = state.Questions.filter( (Question) => { return !(Question._id === action.id ) }) return { ...state, Questions : QuestionTotal } case QUESTION_GETALL: console.log('123',action) return { ...state, loading :true, } case QUESTION_GETALL_SUCCESS: console.log('123',action) return { ...state, Questions : action.question, loading :false } case QUESTION_GETALL_FAILURE: console.log('123',action) return { ...state, loading : false, } case QUESTION_UPDATE: let QuestionAll = state.Questions.map( (Question) => { if(Question._id === action.id ){ return action.question; } return Question; }) return { ...state, Questions : QuestionAll } } return state; }; export default reducer;
Markdown
UTF-8
3,214
2.984375
3
[]
no_license
# 93: Viết code như thể bạn phải hỗ trợ nó đến hết đời Bạn có thể hỏi 97 người liệu lập trình viên nên biết gì và làm gì, và bạn sẽ nhận được 97 câu trả lời khác nhau. Điều này có thể vừa áp đảo vừa đáng sợ. Mọi lời khuyên đều tốt, mọi nguyên tắc đều hợp lý, và mọi câu chuyện đều hấp dẫn, nhưng bạn nên bắt đầu từ đâu? Quan trọng hơn, một khi bạn bắt đầu, làm thế nào để theo kịp những thực tiễn tốt nhất bạn đã học được và biến chúng thành một phần không thể thiếu trong quá trình thực hành lập trình của bạn? Tôi nghĩ câu trả lời nằm trong suy nghĩ của bạn hoặc, rõ ràng hơn, trong thái độ của bạn. Nếu bạn không quan tâm đến nhà phát triển, tester, quản lý, người tiếp thị và bán hàng cũng như người dùng, thì bạn sẽ không bị thúc đẩy sử dụng Phát triển dựa trên thử nghiệm hoặc viết comment rõ ràng trong code của bạn. Tôi nghĩ có một cách đơn giản để điều chỉnh thái độ của bạn và tạo động lực để cung cấp sản phẩm với chất lượng tốt nhất: Viết code như thể bạn phải hỗ trợ nó cho đến hết cuộc đời. Nếu bạn chấp nhận khái niệm này, những điều tuyệt vời sẽ đến. Nếu bạn chấp nhận rằng bất kỳ nhà tuyển dụng nào - cả trong quá khứ lẫn hiện tại có quyền gọi cho bạn vào lúc nửa đêm, yêu cầu bạn giải thích các lựa chọn bạn đã thực hiện khi viết phương pháp fooBar, bạn sẽ dần cải thiện để trở thành một lập trình viên chuyên nghiệp. Bạn sẽ tự nhiên nghĩ ra những phương thức và biến tốt hơn. Bạn sẽ tránh được việc viết những code dài hàng trăm dòng. Bạn sẽ tìm kiếm, tìm hiểu và sử dụng design pattern. Bạn sẽ viết comment, kiểm tra và tái cấu trúc liên tục code của bạn. Hỗ trợ tất cả code bạn từng viết cho đến hết đời cũng là một nỗ lực có thể mở rộng. Do đó, bạn không có lựa chọn nào khác ngoài việc trở nên tốt hơn, thông minh hơn và hiệu quả hơn. Những code bạn viết nhiều năm trước vẫn ảnh hưởng đến sự nghiệp của bạn, dù bạn có thích hay không. Bạn để lại dấu vết về kiến thức, thái độ, sự kiên trì, tính chuyên nghiệp, mức độ cam kết và mức độ thích thú trên mọi phương pháp, class hay module bạn thiết kế và viết. Mọi người sẽ hình thành ý kiến về bạn dựa trên những code mà họ thấy. Nếu những ý kiến đó tiêu cực, bạn sẽ nhận được ít hơn từ sự nghiệp của bạn hơn bạn mong muốn. Hãy chăm chút sự nghiệp của bạn, của khách hàng và của người dùng với mọi dòng code- viết code như thể bạn phải hỗ trợ nó cho đến giây phút cuối cùng của cuộc đời mình.
Java
UTF-8
293
2.671875
3
[]
no_license
package fanorona.Logic; public class Player { // white or black public long state; public Player(long state) { this.state = state; } /** * Copy constructor. */ public Player(Player p) { this.state = p.state; } }
PHP
UTF-8
923
2.671875
3
[ "BSD-3-Clause", "MIT" ]
permissive
<?php namespace Illuminate\Mail\Transport; use Swift_Mime_SimpleMessage; use GuzzleHttp\ClientInterface; class MailgunTransport extends Transport { /** * Guzzle client instance. * * @var \GuzzleHttp\ClientInterface */ protected $client; /** * The Mailgun API key. * * @var string */ protected $key; /** * The Mailgun domain. * * @var string */ protected $domain; /** * The Mailgun API end-point. * * @var string */ protected $url; /** * Create a new Mailgun transport instance. * * @param \GuzzleHttp\ClientInterface $client * @param string $key * @param string $domain * @return void */ public function __construct(ClientInterface $client, $key, $domain) { $this->key = $key; $this->client = $client; $this->setDomain($domain)
Java
UTF-8
3,956
2.40625
2
[]
no_license
package com.newlec.web; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @WebServlet("/calc2") public class Calc2 extends HttpServlet{ @Override protected void service(HttpServletRequest req , HttpServletResponse res) throws ServletException, IOException { ServletContext application = req.getServletContext(); HttpSession session = req.getSession(); //쿠키읽기 Cookie[] cookies = req.getCookies(); //브라우저에서 받아온 쿠키정보(배열) System.out.println("파라미터들:"+ req.getParameterNames()); System.out.println("쿠키길이는 " + cookies.length); System.out.println(Arrays.toString(cookies)); System.out.println(JsonUtil.toString(cookies[0])); System.out.println(JsonUtil.toString(cookies[0].getName())); //System.out.println(cookies[0]); //System.out.println(cookies[0]); String ck = req.getHeader("Cookie"); System.out.println("쿠키헤더는"+ck); res.setCharacterEncoding("UTF-8"); res.setContentType("text/html; charset=UTF-8"); PrintWriter out = res.getWriter(); // int v = Integer.parseInt(req.getParameter("v")); //현재값 // System.out.println(v); // String op = req.getParameter("operator"); // System.out.println("현재op는 "+op); // // //계산 // if(op.equals("=")) { // // int x= 0; // int result = 0; // String operator = ""; //int x = (Integer) application.getAttribute("value"); //저장되있는 값 //int x = (Integer) session.getAttribute("value"); //저장되있는 값 //String operator = (String) application.getAttribute("op"); //저장되있는 연산 //String operator = (String) session.getAttribute("op"); // for(Cookie c : cookies) { // if(c.getName().equals("value")) { // x= Integer.parseInt(c.getValue()); // int aaaa = Integer.parseInt(c.getValue()); // System.out.println("aaaa:"+ aaaa); // System.out.println("x는 "+ x); // break; // } // } // PrintWriter script = res.getWriter(); // script.println("<script>"); // script.println("location.href = 'main.jsp'"); // script.println("</script>"); // // for(Cookie c : cookies) { // System.out.println(c.getValue()); // if(c.getName().equals("op")) { // System.out.println("op는"+c.getValue()); // operator = c.getValue(); // System.out.println("operator는 "+operator); // break; // } // // } // // int y = v; //현재 값 // System.out.println("y는:" + y); // // // if(operator.equals("+")) { // result = x+y; // res.getWriter().printf("결과: %d",result); // // }else{ // result=x-y; // res.getWriter().printf("결과: %d",result); // } // // //값을 저장 // }else { // //session.setAttribute("value", v); // //session.setAttribute("op", op); // // Cookie valueCookie = new Cookie("value", String.valueOf(v)); //쿠키는 반드시 문자열로만 저장되어야 한다. // Cookie opCookie = new Cookie("op", op); // valueCookie.setPath("/calc2"); // valueCookie.setMaxAge(24*60*60); // opCookie.setPath("/calc2"); // // res.addCookie(valueCookie); //response header에 전해진다. // res.addCookie(opCookie); // PrintWriter script = res.getWriter(); // script.println("<script>"); // script.println("location.href = 'calc2.html'"); // script.println("</script>"); //res.sendRedirect("calc2.html"); // } //int v = 0; //초기값 설정 } }
C++
UTF-8
843
3.203125
3
[]
no_license
#include <iostream> #include <vector> #include <memory> #include "electronic_device.h" int main() { std::vector<std::unique_ptr<ElectronicDevice>> electronic_devices(4); electronic_devices[0] = std::make_unique<TV>(); electronic_devices[1] = std::make_unique<Laptop>(); electronic_devices[2] = std::make_unique<VideoGameConsole>(); electronic_devices[3] = std::make_unique<Laptop>(); PriceVisitor price_visitor {}; PowerConsumptionVisitor power_consumption_visitor {}; std::cout << "Visiting the devices one by one...\n"; for (auto& device : electronic_devices) { device->accept(price_visitor); device->accept(power_consumption_visitor); } std::cout << "Here's a summary the visitors got:\n"; price_visitor.summary(); power_consumption_visitor.summary(); return 0; }
PHP
UTF-8
1,512
2.671875
3
[]
no_license
<?php /** * Class file for XiFinancialsTypeGetIncomeStatementRangeResponse * @date 08/07/2012 */ /** * Class XiFinancialsTypeGetIncomeStatementRangeResponse * @date 08/07/2012 */ class XiFinancialsTypeGetIncomeStatementRangeResponse extends XiFinancialsWsdlClass { /** * The GetIncomeStatementRangeResult * Meta informations : * - minOccurs : 0 * - maxOccurs : 1 * @var XiFinancialsTypeArrayOfIncomeStatement */ public $GetIncomeStatementRangeResult; /** * Constructor * @param XiFinancialsTypeArrayOfIncomeStatement GetIncomeStatementRangeResult * @return XiFinancialsTypeGetIncomeStatementRangeResponse */ public function __construct($_GetIncomeStatementRangeResult = null) { parent::__construct(array('GetIncomeStatementRangeResult'=>new XiFinancialsTypeArrayOfIncomeStatement($_GetIncomeStatementRangeResult))); } /** * Set GetIncomeStatementRangeResult * @param ArrayOfIncomeStatement GetIncomeStatementRangeResult * @return ArrayOfIncomeStatement */ public function setGetIncomeStatementRangeResult($_GetIncomeStatementRangeResult) { return ($this->GetIncomeStatementRangeResult = $_GetIncomeStatementRangeResult); } /** * Get GetIncomeStatementRangeResult * @return XiFinancialsTypeArrayOfIncomeStatement */ public function getGetIncomeStatementRangeResult() { return $this->GetIncomeStatementRangeResult; } /** * Method returning the class name * @return string __CLASS__ */ public function __toString() { return __CLASS__; } } ?>
Python
UTF-8
1,010
3.640625
4
[]
no_license
import csv def extraire(fichier): """Extrait d’un fichier texte annuaire avec du type prenom, tel la liste des prenoms et celle des numéros de telephone""" f = open(fichier,'r') prenom,tel = [],[] #initialisation des listes de prenoms et de numeros for ligne in f for ligne in f: p,n =ligne.rstrip().split(',') prenom.append(p) tel.append(n) return prenom, tel def recherche_sequentielle(clef,liste1,liste2): i = 0 m = len(liste1) while i < m: if liste1[i] == clef: return (clef, liste2[i]) i += 1 else: return None l1, l2 = extraire('annuaire.csv') print(l1, l2) #search by alphonse print(recherche_sequentielle('Alphonse', l1, l2)) #search by Zeid print(recherche_sequentielle('Zeid', l1, l2)) #search by any thing excluding names list print(recherche_sequentielle('best', l1, l2)) #search by phone number print(recherche_sequentielle('215-325-3042', l2, l1))
Java
UTF-8
1,861
2.546875
3
[]
no_license
package cn.zjnktion.middleware.zson.serializer; import cn.zjnktion.middleware.zson.Context; import cn.zjnktion.middleware.zson.writer.ZsonWriter; import java.io.IOException; import java.util.Iterator; import java.util.Map; /** * @author zjnktion */ public class MapSerializer implements ZsonSerializer { public static final MapSerializer INSTANCE = new MapSerializer(); private MapSerializer() { } public void serialize(ZsonWriter writer, Object obj) throws IOException { if (obj == null) { writer.writeNull(); } else { writer.write('{'); Map map = (Map) obj; if (map != null && !map.isEmpty()) { Iterator<Map.Entry> iterator = map.entrySet().iterator(); int i = 0; while (iterator.hasNext()) { Map.Entry entry = iterator.next(); if (i > 0) { writer.write(','); } Object key = entry.getKey(); if (key == null) { writer.writeNull(); } else { ZsonSerializer serializer = Context.getSerializer(key.getClass()); serializer.serialize(writer, key); } writer.write(':'); Object value = entry.getValue(); if (value == null) { writer.writeNull(); } else { ZsonSerializer serializer = Context.getSerializer(value.getClass()); serializer.serialize(writer, value); } i++; } } writer.write('}'); } } }
C++
UTF-8
491
2.546875
3
[]
no_license
#ifndef TRLANGUAGE_H #define TRLANGUAGE_H #include <string> #include <ostream> #include "tnode.h" #include "wordstructure.h" class WordTree : public WordStructure { private: TNode m_Tree; void add_word(TNode & node, const std::string & word, uint32_t pos); public: WordTree() : WordStructure() {} TNode & root() { return m_Tree; } const TNode & root() const { return m_Tree; } void add(const std::string & word) override; void clear() override; }; #endif
PHP
UTF-8
112
3.59375
4
[]
no_license
<?php function cube($num) { return $num * $num * $num; } $cubeResult = cube(4); echo $cubeResult;
Markdown
UTF-8
2,400
2.9375
3
[]
no_license
# 2월21일 ### #2.8 express의 router > index.js 파일을 app.js > > init.js 파일생성 > > app.js 파일에서 post부분 삭제 - init.js에 어플리케이션 호출 시작 > app있는것을 init에 호출 > > - export default app; > > > 누군가가 내파일을 불러올때(import) app object를 주겠다라는 의미. - router에대한것. roots 감싸기 - ##### Module(모듈) > 코드를 공유할 수 있다. 다른파일에서 코드를 가져다가 사용할 수 있다. - ##### express의 router란? > route들의 복잡함을 쪼개주는데 사용할 수 있다. > > router는 많은 route들이 담긴 파일이다. - router.js 파일생성 - ##### .use 의미 > 누군가가 /user 경로에 접속하면 이 router 전체를 사용하겠다라는 의미 - #### request(요청) , response(응답) --- ### #2.9 MVC pattern - ##### MVC(Model, View, Control) > **modle** : data > > **view** : how does the data look = template > > **control** : tha looks for the data - pattern > 일종의 structure(구조) - url에 해당하는 router를 사용하고 실행하는 함수가 controller가 됨 = mvc패턴 - ##### sperate > 분리하다 - export default는 파일로 export한다는거임 - valuable > 변수 - ##### Global router > /join, /login, /home 등등을 다룸 > > 유일하게 독점적으로 url을 다루는 방법이다. --- ### #2.10 - routes.js 파일 생성 > 하나의 소스를 쓰고싶기에 만듬 > > URL들을 작성 > > 어디에든 이 URL을 불러다 씀 - url만들기 --- ### #2.11 - controllers 폴더생성 > video 컨트롤러와 user 컨트롤러를 만듬 > > 컨트롤러는 어떤 일이 어떻게 발생하는지에 관한 로직이다. > > - userController.js > > > join > > > > login > > > > jologoutin > > - videoController.js > > > home > > > > search - 대개 프로젝트에 있는 각 모덱마다 컨트롤러를 만들게된다. - 함수부분 라우터랑 쪼개기 - ##### arrow function > **implicit return(임시적 리턴)** 이 있다. > > arrow = () => true; > > > ture를 리턴한다는 뜻 > > arrow = () => { > > ​ return true; > > } > > > 대괄호{} 를 적어주면 암시적 성격을 잃게 되어서 return을 적어줘야한다. --- 2. >
Java
UTF-8
1,090
2.75
3
[ "Apache-2.0" ]
permissive
package com.contaazul.challenge.mars.model; import com.contaazul.challenge.mars.model.enums.OrientationEnum; /** * * @author Wesklei Migliorini */ public class Robot { private static final long serialVersionUID = -340875071855645838L; private int xCoord; private int yCoord; private OrientationEnum orientationEnum; public Robot() { xCoord = 0; yCoord = 0; orientationEnum = OrientationEnum.NORTH; } public int getxCoord() { return xCoord; } public void setxCoord(int xCoord) { this.xCoord = xCoord; } public int getyCoord() { return yCoord; } public void setyCoord(int yCoord) { this.yCoord = yCoord; } public OrientationEnum getOrientationEnum() { return orientationEnum; } public void setOrientationEnum(OrientationEnum orientationEnum) { this.orientationEnum = orientationEnum; } @Override public String toString() { return "(" + xCoord + "," + yCoord +"," + orientationEnum.getOrientationValue() + ")"; } }
JavaScript
UTF-8
1,802
2.671875
3
[ "MIT" ]
permissive
const express = require('express') const router = express.Router() const User = require('../models/user') /** Route to get all users. */ // GET localhost:3000/users/ router.get('/', (req, res) => { User.find().then((users) => { return res.json({users}) }) .catch((err) => { throw err.message }); }) /** Route to get one user by id. */ // GET localhost:3000/users/:userId router.get('/:userId', (req, res) => { User.findOne({_id: req.params.userId}) .then(result => { res.json(result) }).catch(err => { throw err.message }) }) /** Route to add a new user to the database. */ router.post('/', (req, res) => { // POST localhost:3000/users/ let user = new User(req.body) user.save().then(userResult => { return res.json({user: userResult}) }).catch((err) => { throw err.message }) }) /** Route to update an existing user. */ // PUT localhost:3000/users/:userId router.put('/:userId', (req, res) => { User.findByIdAndUpdate(req.params.userId, req.body).then(() => { return User.findOne({_id: req.params.userId}) }).then((user) => { return res.json({user}) }).catch((err) => { throw err.message }) }) /** Route to delete a user. */ // DELETE localhost:3000/users/:userId router.delete('/:userId', (req, res) => { User.findByIdAndDelete(req.params.userId).then((result) => { if (result === null) { return res.json({message: 'User does not exist.'}) } return res.json({ 'message': 'Successfully deleted.', '_id': req.params.userId }) }) .catch((err) => { throw err.message }) }) module.exports = router
Java
UTF-8
1,132
2.09375
2
[]
no_license
package io.starskyoio.dbstore.common.constants; /** * 定义数据存储服务URL地址 */ public interface Paths { /** * 插入URL */ String INSERT_PATH = "/api/dbstore/add/v1"; /** * 修改URL */ String UPDATE_PATH = "/api/dbstore/mod/v1"; /** * 删除URL */ String DELETE_PATH = "/api/dbstore/del/v1"; /** * 查询单条记录URL */ String DETAIL_PATH = "/api/dbstore/detail/v1"; /** * 查询列表记录URL */ String LIST_PATH = "/api/dbstore/list/v1"; /** * 查询分页记录URL */ String PAGE_PATH = "/api/dbstore/page/v1"; /** * 执行更新SQL URL */ String EXECUTE_UPDATE_PATH = "/api/dbstore/executeUpdate/v1"; /** * 执行查询单条记录SQL URL */ String EXECUTE_FOR_MAP_PATH = "/api/dbstore/executeForMap/v1"; /** * 执行查询多条记录SQL URL */ String EXECUTE_FOR_LIST_PATH = "/api/dbstore/executeForList/v1"; /** * 执行查询分页记录SQL URL */ String EXECUTE_FOR_PAGE_PATH = "/api/dbstore/executeForPage/v1"; }
Java
UTF-8
793
2.453125
2
[]
no_license
package RoombaTest; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.Scalar; import org.opencv.imgproc.Imgproc; public class ColorDetector { public ColorDetector(){ } public Mat detect_blue(Mat img){ System.loadLibrary(Core.NATIVE_LIBRARY_NAME); Mat im = img;// 入力画像の取得 Mat im2 = img;// 入力画像の取得 Mat hsv = new Mat(); Imgproc.cvtColor(im, hsv, Imgproc.COLOR_RGBA2BGR);//From RGBA to BGR Imgproc.cvtColor(im, hsv, Imgproc.COLOR_BGR2HSV);//From BGR to HSV. HSVは色抽出に向いている Core.inRange(hsv, new Scalar(0, 100, 30), new Scalar(5, 255, 255), im2);//指定した画素値の範囲内にある領域をマスク画像で取得する. ノイズ除去後の画像を保存する. return im2; } }
Python
UTF-8
4,094
2.890625
3
[]
no_license
# cancer.npy를 가지고 tensorflow 코딩을 하시오 # test와 train 분리할 것 # dropout, get_variable, multi layer 등 배운 것을 모두 사용할 것 import tensorflow as tf import numpy as np import random tf.set_random_seed(777) x_data = np.load("./data/cancer_x.npy", allow_pickle = True) y_data = np.load("./data/cancer_y.npy", allow_pickle = True) # print(x_data.shape) # (569, 30) # print(y_data.shape) # (569, ) # print(x_data) y_data = y_data.reshape(y_data.shape[0], 1) # print(y_data.shape) from sklearn.preprocessing import StandardScaler, MinMaxScaler scaler = MinMaxScaler() scaler.fit(x_data) x_data = scaler.transform(x_data) # print(x_data[:10]) from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split( x_data, y_data, test_size=0.2) # print(x_train.shape) # (455, 30) # print(x_test.shape) # (114, 30) # print(y_train.shape) # (455, 1) # print(y_test.shape) # (114, 1) # print(y_train[:10]) keep_prob = tf.placeholder(tf.float32) # nb_classes = 2 # 0,1 X = tf.placeholder(tf.float32, shape=[None, 30]) Y = tf.placeholder(tf.float32, shape=[None, 1]) # Y_one_hot = tf.one_hot(Y, nb_classes) # print("one_hot:", Y_one_hot) # Y_one_hot = tf.reshape(Y_one_hot, [-1, nb_classes]) # print("reshape one_hot:", Y_one_hot) ''' # one_hot: Tensor("one_hot:0", shape=(?, 3), dtype=float32) # reshape one_hot: Tensor("Reshape:0", shape=(?, 3), dtype=float32) ''' # W1 = tf.get_variable("W1", shape=[30, 50], initializer=tf.contrib.layers.xavier_initializer()) # b1 = tf.Variable(tf.random_normal([50])) # layer1 = tf.nn.relu(tf.matmul(X, W1) + b1) # layer1 = tf.nn.dropout(layer1, keep_prob=keep_prob) # W2 = tf.get_variable("W2", shape=[50, 50], initializer=tf.contrib.layers.xavier_initializer()) # b2 = tf.Variable(tf.random_normal([50])) # layer2 = tf.nn.relu(tf.matmul(layer1, W2) + b2) # layer2 = tf.nn.dropout(layer2, keep_prob=keep_prob) W3 = tf.get_variable("W3", shape=[30, 1], initializer=tf.contrib.layers.xavier_initializer()) b3 = tf.Variable(tf.random_normal([1])) hypothesis = tf.sigmoid(tf.matmul(X, W3) + b3) cost = -tf.reduce_mean(Y * tf.log(hypothesis) + (1 - Y) * tf.log(1 - hypothesis)) train = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost) # train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost) prediction = tf.argmax(hypothesis, 1) correct_prediction = tf.equal(prediction, tf.argmax(y_test, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # num_epochs = 15 # batch_size = 100 # Launch graph with tf.Session() as sess: # Initialize TensorFlow variables sess.run(tf.global_variables_initializer()) for step in range(2001): _, cost_val, acc_val = sess.run([train, cost, accuracy], feed_dict={X: x_train, Y: y_train, keep_prob:0.7}) if step % 100 == 0: print("Step: {:5}\tCost: {:.3f}\tAcc: {:.2%}".format(step, cost_val, acc_val)) # Let's see if we can predict pred = sess.run(prediction, feed_dict={X: x_test, keep_prob: 1}) # y_data: (N, 1) = flatten => (N, ) matches pred.shape for p, y in zip(pred, y_test.flatten()): print("[{}] Prediction: {} True Y: {}".format(p == int(y), p, int(y))) # Calculate the accuracy print("Accuracy: ", sess.run(accuracy, feed_dict={X: x_test, Y: y_test, keep_prob: 1})) ''' sess = tf.Session() pred = sess.run([hypothesis], feed_dict={X: x_test, keep_prob: 1}) pred = np.array(pred) # 원본데이터와 형식 통일 y_test = y_test.reshape((-1,)) # flatten pred = pred.reshape((-1,)) # RMSE 구하기 from sklearn.metrics import mean_squared_error def RMSE(y_data, pred): # y_test, y_predict의 차이를 비교하기 위한 함수 return np.sqrt(mean_squared_error(y_test, pred)) # np.sqrt 제곱근씌우기 print("RMSE : ", RMSE(y_test, pred)) # R2(결정계수) 구하기 from sklearn.metrics import r2_score r2_y_predict = r2_score(y_test, pred) print("R2 : ", r2_y_predict) sess.close() '''
TypeScript
UTF-8
1,380
3.171875
3
[]
no_license
class GameUtil{ /**基于矩形的碰撞检测*/ public static hitTest(obj1:egret.DisplayObject,obj2:egret.DisplayObject):boolean { var rect1:egret.Rectangle = obj1.getBounds(); var rect2:egret.Rectangle = obj2.getBounds(); rect1.x = obj1.x - obj1.width/2; rect1.y = obj1.y - obj1.height/2; rect2.x = obj2.x; rect2.y = obj2.y; //console.log(obj1.x,obj1.y) //console.log(rect1.width,rect1.height,rect2.width,rect2.height); //console.log(rect1.x,rect1.y,rect2.x,rect2.y); return rect1.intersects(rect2); } /**圆形碰撞检测 */ public static hitTest2(obj1:egret.DisplayObject,obj2:egret.DisplayObject):boolean { var rect1:egret.Rectangle = obj1.getBounds(); var rect2:egret.Rectangle = obj2.getBounds(); rect1.x = obj1.x - obj1.width/2; rect1.y = obj1.y - obj1.height/2; rect2.x = obj2.x - obj2.width/2; rect2.y = obj2.y - obj2.height/2; //console.log(obj1.x,obj1.y) //console.log(rect1.width,rect1.height,rect2.width,rect2.height); //console.log(rect1.x,rect1.y,rect2.x,rect2.y); return rect1.intersects(rect2); } }
Java
UTF-8
610
1.976563
2
[]
no_license
package com.zconly.pianocourse.event; import com.zconly.pianocourse.bean.CouponBean; /** * @Description: 选择优惠券 * @Author: dengbin * @CreateDate: 2020/3/24 20:55 * @UpdateUser: dengbin * @UpdateDate: 2020/3/24 20:55 * @UpdateRemark: 更新说明 */ public class SelectCouponEvent { private CouponBean couponBean; public SelectCouponEvent(CouponBean couponBean) { this.couponBean = couponBean; } public CouponBean getCouponBean() { return couponBean; } public void setCouponBean(CouponBean couponBean) { this.couponBean = couponBean; } }
Python
UTF-8
3,231
2.546875
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- # Copyright (c) 2016 Jeremy Low # License: MIT try: from urlparse import * except ImportError: from cgi import parse_qsl, parse_qs pass try: import oauth2 as Oauth from twitter import Twitter import twitter import json import sys import os from time import sleep except ImportError as whoops: print("Sorry, one of the required packages did not import properly. try running pip install with the package name", str(whoops)) # sleep(8) # display error message so they can gather the needed info, can add in logging, and log it to a file. # sys.exit(1) # because of error with importing, set exit status as 1 because of an error. # screen.background('White') # can be changed to a background picture with screen.bgpic('') #os.system('clear') print('Please be aware, none of this information will be shared with anyone,\n' 'this is to help you unblock your access to twitter.\n' 'AND WILL ONLY BE USED FOR THAT PURPOSE.\n') # switched to TextInput, to solve an error generated by turtles default Floating point number. CONSUMER_KEY = str(input('Please enter in your Consumer Key:\n->')) CONSUMER_SECRET = str(input('Please enter in your Consumer Secret Key:\n->')) ACCESS_KEY = str(input('Please enter in your Access Key:\n->')) ACCESS_SECRET = str(input('Please enter in your Access Secret Key:\n->')) # debugging purposes. print(CONSUMER_KEY) print(CONSUMER_SECRET) print(ACCESS_KEY) print(ACCESS_SECRET) # convert to int, see if that cleans up some of this and makes it passable to OAuth. #CONSUMER_KEY = int(CONSUMER_KEY) #CONSUMER_SECRET = int(CONSUMER_SECRET) #ACCESS_KEY = int(ACCESS_KEY) #ACCESS_SECRET = int(ACCESS_SECRET) # debugging purposes. print(CONSUMER_KEY) print(CONSUMER_SECRET) print(ACCESS_KEY) print(ACCESS_SECRET) # inside this call, im not exactly sure if they can be passed as a string, or as an int, so i figured for ease of use, # set as string and if it fails handle as necessary. api = Twitter(auth=Oauth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET, tweet_mode='extended', sleep_on_rate_limit=True)) def get_blocks(filename): with open(filename, 'w+') as f: blocks = api.GetBlocksIDs() f.write(json.dumps(blocks)) return True def unblock(blocklist): with open(blocklist, 'r') as f: blocks = json.loads(f.read()) while blocks: block = str(blocks.pop()) try: result = api.DestroyBlock(user_id=block) if result: with open('successfully_unblocked.txt', 'a+') as unblocked_list: unblocked_list.write(block + '\n') except Exception as e: with open('errors.txt', 'a+') as error_log: error_log.write(repr(e) + '\n') with open('faied_to_unblock.txt', 'a+') as fail_list: fail_list.write(block + '\n') continue with open(blocklist, 'w+') as f: f.write(json.dumps(blocks)) if __name__ == '__main__': if get_blocks('blocklist.json'): unblock('blocklist.json')
JavaScript
UTF-8
390
3
3
[ "MIT" ]
permissive
function Scoreboard() { this.initialize(); } Scoreboard.prototype = new Text(); Scoreboard.prototype.initialize = function() { this.color = "#fff"; this.font = "bold 24px Arial"; this.text = 'SCORE: 0'; this.x = 10; this.y = 25; this.name = 'scoreboard'; game.stage.addChild(this); }; Scoreboard.prototype.onTick = function() { this.text = 'SCORE: ' + game.score; };
C#
UTF-8
1,224
3.15625
3
[]
no_license
using Module_6_Task_6.Entities; using System; using System.Collections.Generic; using System.Text; namespace Module_6_Task_6.Attacks { public class SpearAttack : Entities.Attack { public SpearAttack(Log log) : base(log) { } public override void Do(Unit target) { bool isMiss = _checkMiss(target); bool isTrueStrike = _checkTryeStrike(); _addToLog($"{_attacker.Name} strikes {target.Name}"); if (!isMiss || isTrueStrike) { int damage = _rand.Next(_attacker.DamageLow, _attacker.DamageMax); _addToLog($"{damage}DMG"); if (!isTrueStrike) { _addToLog($"{target.Armor} blocked"); damage -= target.Armor; } else { _addToLog($"The spear {_attacker.Name} went through the protection!"); } target.TakeDamage(damage); if (target.CheckAlive()) { _addToLog($"{target.Name}({target.Health}HP)"); } } } } }
TypeScript
UTF-8
969
2.953125
3
[]
no_license
import moment from 'moment-timezone'; interface SEARCHKEYVALUE { '$gte': string; '$lte': string; } export interface UPDATEKEYVALUE { update: SEARCHKEYVALUE; } export class VODateTime { private timestamp: string; public static of(timestamp: string): VODateTime { return new VODateTime(timestamp); } private constructor(timestamp: string){ this.timestamp = timestamp; } public extractYearDate(): string { const formatting = moment(this.timestamp).format('YYYY-MM-DD'); return formatting; } public toKeyValue(): UPDATEKEYVALUE { const start: string = moment(this.timestamp).toISOString(); const end: string= moment(this.timestamp).add(1, 'days').toISOString(); const kv: UPDATEKEYVALUE = { update: { '$gte': start, '$lte': end } }; console.log(kv); return kv; } public toISODate(): string { const iso: string = moment(this.timestamp).toISOString(); return iso; } }
Python
UTF-8
208
2.921875
3
[]
no_license
def fun(a): return(len(a)) x=map(fun,('apple','grapes','orange')) print(x) print(list(x)) def fun(a,b): return a,-,+b x=map(fun,('apple','grapes','banana'),('red','green','yellow')) print(x) print(list(x))
PHP
UTF-8
1,645
2.671875
3
[]
no_license
<?php require_once('./db.inc.php'); $con = mysqli_connect("$db_hostname","$db_username","$db_password", "$db_database"); //check connection if (mysqli_connect_errno()) { echo "Failed to connect MySQL: " . mysqli_connect_errno(); exit(); } // Getting user data from the form $fullname = mysqli_real_escape_string($con, $_POST['name']); $phone = mysqli_real_escape_string($con, $_POST['phone']); $email = mysqli_real_escape_string($con, $_POST['email']); $subject = mysqli_real_escape_string($con, $_POST['subject']); $message = mysqli_real_escape_string($con, $_POST['message']); echo "Thank you for your message! we will keep in touch <3"; // sending maing /* $content="From: $fullname \n Email: $email \n Message: $message"; $recipient = "info@complexgraphicx.co.za"; $mailheader = "From: $email \r\n"; mail($recipient, $subject, $content, $mailheader) or die("Error! cant send mail please call us"); */ // echo "Thank you mail sent"; //sending to database $sqli = "INSERT INTO clients (fullname,phone,email,subject,message) VALUES ('?','?','?','?','?')"; $stmt = mysqli_stmt_init($con); if(!mysqli_stmt_prepare ($stmt,$sqli)){ echo "SQLI error "; } else { mysqli_stmt_bind_param($stmt,"sisss", $fullname,$phone,$email,$subject,$message); mysqli_stmt_execute($stmt); } mysqli_query($con,$sqli); ?>
Java
UTF-8
7,894
3.015625
3
[]
no_license
package UI; import line.Line; import line.Timetable; import line.comparator.LineNameComparator; import line.comparator.VehicleDepartureComparator; import line.vehicle.Vehicle; import station.Station; import ticket.Ticket; import java.util.*; /** Listázással kapcsolatos inteface metódusok */ public abstract class listUI { public static final int EXIT = 0; public static final int LINES = 1; public static final int STATIONS = 2; public static final int TRAINS = 3; public static final int ROUTE = 4; public static final int TIMETABLE = 5; /** Az összes listázható opció */ public static final String[] MENU_LIST_ALL = new String[]{ "Vissza", "Vonalak", "Állomások", "Vonatok (egy vonalon)", "Vonal útvonala", "Vonat menetrendje" }; /** * Kilistázza az összes megadott állomást, az állomások neve szerint rendezve. * @param stationsCollection kilistázandó állomások * @param showIndex ha {@code true}, mutatja az állomás neve előtt annak indexét is.<br> * <b>Az indexet +1-el mutatja</b>, hogy legyen lehetőség a vissza implementálására is! * @param sorted ha {@code true}, akkor sorba rendezi az állomásokat név szerint * @return a név szerint rendezett állomások listáját */ public static ArrayList<Station> listStations(Collection<Station> stationsCollection, boolean showIndex, boolean sorted){ ArrayList<Station> stations = new ArrayList<>(stationsCollection); if(sorted) Collections.sort(stations); for (int i = 0; i < stations.size(); i++) { if(showIndex) System.out.print(i+1 + ". "); System.out.println(stations.get(i)); } return stations; } /** * Kilistázza az összes megadott vonalat, a megadott comparátorral. * @param lineCollection kilistázandó vonalak * @param showIndex ha {@code true}, mutatja a vonal neve előtt annak indexét is.<br> * <b>Az indexet +1-el mutatja</b>, hogy legyen lehetőség a vissza implementálására is! * @return a rendezett vonalak listáját */ public static ArrayList<Line> listLines(Collection<Line> lineCollection, Comparator<Line> comparator, boolean showIndex){ ArrayList<Line> lines = new ArrayList<>(lineCollection); lines.sort(comparator); for (int i = 0; i < lines.size(); i++) { if(showIndex) System.out.print(i+1 + ". "); System.out.println(lines.get(i)); } return lines; } /** * Kilistázza a megadott vonal összes járművének az indulási idejét * és állomását, indulási idő szerint sorba rendezve. * @param showIndex ha {@code true}, mutatja a vonal neve előtt annak indexét is.<br> * <b>Az indexet +1-el mutatja</b>, hogy legyen lehetőség a vissza implementálására is! * @return a sorba rendezett vonatok listáját. */ public static ArrayList<Vehicle> listVehicles(Line line, boolean showIndex, boolean displayFreeSeat){ Station start_normal = line.getRoute()[0]; Station start_reverse = line.getRoute()[line.getRoute().length-1]; ArrayList<Vehicle> vehicles = new ArrayList<>(line.getVehicles()); vehicles.sort(new VehicleDepartureComparator()); int i = 0; for (Vehicle vehicle : vehicles){ if(showIndex) System.out.print(i+1 + ". "); System.out.print((vehicle.isLineReversed() == Timetable.DIRECTION_NORMAL ? start_normal : start_reverse) + ":\t\t" + vehicle.getDepartureTime() + "\tkésés: " + vehicle.getDelay() + "p"); if(displayFreeSeat) System.out.print("\t" + vehicle.getTotalFreeSeatCount() + " szabad szék"); System.out.println(); i++; } return vehicles; } /** * Kilistázza az összes megadott jegyet, ár szerint rendezve. * @param tickets kiírandó jegyek * @param showIndex ha {@code true}, mutatja a vonal neve előtt annak indexét is.<br> * <b>Az indexet +1-el mutatja</b>, hogy legyen lehetőség a vissza implementálására is! * @return az ár szerint sorba rendezett jegyeket */ public static ArrayList<Ticket> listTickets(Collection<Ticket> tickets, boolean showIndex){ ArrayList<Ticket> sortedTickets = new ArrayList<>(tickets); Collections.sort(sortedTickets); for (int i = 0; i < sortedTickets.size(); i++) { if(showIndex) System.out.print(i + 1 + ". "); System.out.println(sortedTickets.get(i)); } return sortedTickets; } /** * Kér a felhasználótól egy vonalat a megadott vonalak közül. * @param lines választható vonalak * @return választott vonal */ public static Line selectLine(Collection<Line> lines){ if(lines.size() == 0){ System.out.println("Nincs 1 kiírható vonal se."); standardUIMessage.ok(); return null; } ArrayList<Line> listedLines = listLines(lines, new LineNameComparator(), true); System.out.print("Vonal sorszáma: "); int selectedLine = Main.getInt()-1; if(selectedLine < 0 || selectedLine >= listedLines.size()) return null; return listedLines.get(selectedLine); } /** * Kiválaszt a megadott vonal összes járműje közül 1-et. * @param line A megadott vonal, ahol a járműt keresi * @param displayFreeSeat ha {@code true}, kiírja a szabad székek számát is. * @return a kiválasztott jármű, vagy {@code null}, ha nem sikerült kiválasztani */ public static Vehicle selectVehicle(Line line, boolean displayFreeSeat){ if(line.getVehicles().size() == 0){ System.out.println("Nincs 1 jármű se ezen a vonalon."); standardUIMessage.ok(); return null; } ArrayList<Vehicle> vehicles = listVehicles(line, true, displayFreeSeat); System.out.print("Jármű sorszáma: "); int selectedTrain = Main.getInt()-1; if(selectedTrain < 0 || selectedTrain >= vehicles.size()) return null; return vehicles.get(selectedTrain); } /** * Kér a felhasználótól az összes állomás közül 1-et. * @param stations A választható állomások * @return a kiválasztott állomás, vagy {@code null}, ha nem sikerült kiválasztani */ public static Station selectStation(Collection<Station> stations){ if(stations.size() == 0){ System.out.println("Nincs 1 kiválasztható állomás se."); standardUIMessage.ok(); return null; } ArrayList<Station> orderedStations = listStations(stations, true, true); System.out.print("Állomás sorszáma: "); int selectedStation = Main.getInt()-1; if(selectedStation < 0 || selectedStation >= orderedStations.size()) return null; return orderedStations.get(selectedStation); } /** * Kiválaszt a megadott jegyek közül 1-et. * @param tickets Választható jegyek * @return a kiválasztott jegy, vagy {@code null}, ha nem sikerült kiválasztani */ public static Ticket selectTicket(Collection<Ticket> tickets){ if(tickets.size() == 0){ System.out.println("Nincs 1 kiválasztható jegy se."); standardUIMessage.ok(); return null; } ArrayList<Ticket> orderedTickets = listTickets(tickets, true); System.out.print("Jegy sorszáma: "); int selectedTicket = Main.getInt()-1; if(selectedTicket < 0 || selectedTicket >= orderedTickets.size()) return null; return orderedTickets.get(selectedTicket); } }
C++
UTF-8
192
2.546875
3
[]
no_license
#include <iostream> #include <thread> int main() { for (auto i=0; i<20; ++i) { if (i%3 == 0) { std::cout << i << std::endl; } } }
Swift
UTF-8
3,737
2.640625
3
[ "MIT" ]
permissive
// // PresentPhotoFromInternetViewController.swift // Tinkoff Chat // // Created by Даниил on 11.05.17. // Copyright © 2017 Даниил. All rights reserved. // import UIKit protocol IPresentaionPhotoFormInternetDelegate { func setNewImage(imageToShow: UIImage) } class PresentPhotoFromInternetViewController: UIViewController { @IBOutlet weak var phpotCollectionView: UICollectionView! let photoModel = PhotoModel(photoService: PhotoService()) var dataSource = [PhotoApiModel]() let bounds = UIScreen.main.bounds var iamgeToSend: UIImage? var delegate: IPresentaionPhotoFormInternetDelegate? override func viewDidLoad() { super.viewDidLoad() phpotCollectionView.allowsMultipleSelection = false photoModel.fetchPhotos(completionHandler: { [unowned self] _ in self.dataSource = self.photoModel.photosToShow DispatchQueue.main.async { self.phpotCollectionView.reloadData() } }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func sendPhotoToPreviousController(_ sender: Any) { delegate?.setNewImage(imageToShow: iamgeToSend!) _ = self.navigationController?.popViewController(animated: true) // If you are presenting this controller then you need to dismiss self.dismiss(animated: true) } } extension PresentPhotoFromInternetViewController: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSource.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "sampleCell", for: indexPath) as! photoCollectionViewCell let photos = dataSource[indexPath.row] let photosUrl = URL(string: photos.url) let backgroundQueue = DispatchQueue(label: "backgroundQueue", qos: .background, attributes: .concurrent, autoreleaseFrequency: .inherit, target: nil) //cell.photoImageView.image = UIImage(named: "samplePhoto") backgroundQueue.async { if let imageData = try? Data(contentsOf: photosUrl!) { DispatchQueue.main.async { cell.photoImageView.image = UIImage(data: imageData) } } } return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) as! photoCollectionViewCell print("Cell is selected") iamgeToSend = cell.photoImageView.image cell.selectedView.backgroundColor = UIColor.green } func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) as! photoCollectionViewCell print("Cell is selected") cell.selectedView.backgroundColor = UIColor.clear } } extension PresentPhotoFromInternetViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: bounds.width/3.5, height: bounds.width/3.5) } }
C++
UTF-8
5,698
2.6875
3
[ "MIT" ]
permissive
// ====================================================================== /*! * \file NFmiPreProcessor.h * \brief Interface of class NFmiPreProcessor */ // ====================================================================== #pragma once #include "NFmiCommentStripper.h" #include <map> #include <string> //! Undocumented class NFmiPreProcessor : public NFmiCommentStripper { public: NFmiPreProcessor(const NFmiPreProcessor& theStripper); NFmiPreProcessor(bool stripPound = false, bool stripDoubleSlash = true, bool stripSlashAst = true, bool stripSlashAstNested = true, bool stripEndOfLineSpaces = true); NFmiPreProcessor(const std::string& theFileName, bool stripPound = false, bool stripDoubleSlash = true, bool stripSlashAst = true, bool stripSlashAstNested = true, bool stripEndOfLineSpaces = true); bool CompleteFileName(std::string& theFileName); using NFmiCommentStripper::Strip; bool Strip(); bool StripDoubleEnds(const std::string& theBeginDirective, const std::string& theEndDirective, const std::string& theEndDirective2); bool StripConditionally(bool theCondValue, const std::string& theConditionalBeginDirective, const std::string& theConditionalNotBeginDirective = "", const std::string& theConditionalEndDirective = "#endif", const std::string& theConditionalElseDirective = "#else"); bool IncludeFiles(const std::string& theIncludeDirective = "#Include", const std::string& theIncludePath = "", const std::string& theIncludeExtension = "inc"); bool SetIncluding(const std::string& theIncludeDirective = "#Include", const std::string& theIncludePath = "", const std::string& theIncludeExtension = "inc"); bool SetDefine(const std::string& theDefineDirective = "#define", bool useReplace = false); bool SetConditionalStripping(bool theCondValue, const std::string& theConditionalBeginDirective, const std::string& theConditionalNotBeginDirective = "", const std::string& theConditionalEndDirective = "#endif", const std::string& theConditionalElseDirective = "#else"); bool SetReplaceMap(const std::map<std::string, std::string>& theMap); bool AddReplaceString(const std::string fromString, const std::string toString); int NumOfReplacesDone() const; bool NoFilesIncluded(); void SetNumOfIncludes(int newValue) { itsCurNumOfIncludes = newValue; } bool ReplaceAll(); private: bool StripConditionally(); bool Replace(); bool Include(); bool Define(); bool StripNestedConditionally(std::vector<unsigned long> theBeginPositions, std::vector<unsigned long> theEndPositions, bool theCond); bool IncludeFile(const std::string& theFileName, std::string& theFileContentsToInclude); bool IsConditional() const; bool IsInclude() const; bool IsReplace() const; bool IsDefine() const; std::string itsDefineDirective; std::string itsIncludeDirective; std::string itsIncludePath; std::string itsIncludeExtension; std::string itsConditionalBeginDirective; std::string itsConditionalNotBeginDirective; std::string itsConditionalEndDirective; std::string itsConditionalElseDirective; std::map<std::string, std::string> itsReplaceMap; int itsNumOfReplacesDone; bool fConditionValue; bool fNoFilesIncluded; bool fUseReplace; int itsCurNumOfIncludes; // estää mm. rekursiivisen includen käädon ohjelmassa }; // class NFmiPreProcessor // ---------------------------------------------------------------------- /*! * \return Undocumented */ // ---------------------------------------------------------------------- inline int NFmiPreProcessor::NumOfReplacesDone() const { return itsNumOfReplacesDone; } // ---------------------------------------------------------------------- /*! * \return Undocumented * \todo This should be const */ // ---------------------------------------------------------------------- inline bool NFmiPreProcessor::NoFilesIncluded() { return fNoFilesIncluded; } // ---------------------------------------------------------------------- /*! * \return True, if a #define directive has been defined */ // ---------------------------------------------------------------------- inline bool NFmiPreProcessor::IsDefine() const { return !itsDefineDirective.empty(); } // ---------------------------------------------------------------------- /*! * \return Undocumented */ // ---------------------------------------------------------------------- inline bool NFmiPreProcessor::IsConditional() const { return !itsConditionalBeginDirective.empty(); } // ---------------------------------------------------------------------- /*! * \return Undocumented */ // ---------------------------------------------------------------------- inline bool NFmiPreProcessor::IsReplace() const { return !itsReplaceMap.empty(); } // ---------------------------------------------------------------------- /*! * \return Undocumented */ // ---------------------------------------------------------------------- inline bool NFmiPreProcessor::IsInclude() const { return !itsIncludeDirective.empty(); } // ======================================================================
TypeScript
UTF-8
3,476
2.71875
3
[]
no_license
import { createSlice } from "@reduxjs/toolkit"; import { CellRow, gameSelectors } from "."; import { CellState } from "@/components/Cell"; import { GameSettings } from "@/components/SettingsPanel"; export const getRandomField = (settings: GameSettings) => { const { columnCount, rowCount, fillingPercent } = settings; const result: CellRow[] = []; const cellsCount = columnCount * rowCount; const maxAliveCount = (cellsCount / 100) * fillingPercent; let aliveCount = 0; for (let y = 0; y < rowCount; y++) { const rowCells: CellState[] = []; for (let x = 0; x < columnCount; x++) { let cellState = CellState.dead; if (Math.round(Math.random() * 100) <= fillingPercent) { aliveCount++; if (aliveCount <= maxAliveCount) { cellState = CellState.alive; } } rowCells.push(cellState); } result.push({ cells: rowCells }); } return result; }; export const initSettingsState: GameSettings = { height: 600, width: 600, rowCount: 18, columnCount: 18, fillingPercent: 40, frequency: 4, }; export interface GameState { settings: GameSettings; isPlaying: boolean; isSettingsVisible: boolean; userpic: string; field: CellRow[]; history: CellRow[][]; currentHistoryStep: number; } export const initGameState: GameState = { settings: initSettingsState, isPlaying: false, isSettingsVisible: false, userpic: "", field: getRandomField(initSettingsState), history: [], currentHistoryStep: -1 }; const makeCellAliveField = ( oldField: CellRow[], colIndex: number, rowIndex: number ) => { if (oldField[rowIndex].cells[colIndex] !== CellState.alive) { const newRows = [...oldField]; const rowCells = [...newRows[rowIndex].cells]; rowCells[colIndex] = CellState.alive; newRows[rowIndex] = { cells: rowCells }; return newRows; } return oldField; }; const gameSlice = createSlice({ name: "game", initialState: initGameState, reducers: { playGame(state) { state.isPlaying = true; state.history = [state.field]; state.currentHistoryStep = 0; }, stopGame(state) { state.isPlaying = false; }, setIsSettingsVisible(state, action) { state.isSettingsVisible = action.payload; }, reset(state) { state.field = getRandomField(state.settings); state.history = [state.field]; state.currentHistoryStep = 0; }, setUserpic(state, action) { state.userpic = action.payload; }, setSettings(state, action) { state.settings = action.payload; state.field = getRandomField(action.payload); state.history = [state.field]; state.currentHistoryStep = 0; }, setField(state, action) { state.field = action.payload; state.history.push(state.field); state.currentHistoryStep++; }, makeCellAlive(state, action) { state.field = makeCellAliveField( state.field, action.payload.colIndex, action.payload.rowIndex ); state.history.push(state.field); state.currentHistoryStep++; }, nextStep(state) { if (gameSelectors.hasNextStep(state)) { state.currentHistoryStep++; state.field = state.history[state.currentHistoryStep]; } }, prevStep(state) { if (gameSelectors.hasPrevStep(state)) { state.currentHistoryStep--; state.field = state.history[state.currentHistoryStep]; } }, }, }); export const { setSettings, playGame, stopGame, setIsSettingsVisible, reset, setUserpic, setField, makeCellAlive, nextStep, prevStep, } = gameSlice.actions; export const gameReducer = gameSlice.reducer;
Java
UTF-8
1,480
2.296875
2
[]
no_license
package com.tmt.kontroll.ui.page.configuration.impl.event; import java.lang.annotation.Annotation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.tmt.kontroll.ui.page.configuration.PageSegmentConfigurator; import com.tmt.kontroll.ui.page.configuration.annotations.context.PageConfig; import com.tmt.kontroll.ui.page.configuration.annotations.context.PageContext; import com.tmt.kontroll.ui.page.configuration.annotations.event.Event; import com.tmt.kontroll.ui.page.configuration.helpers.handlers.EventConfigurationHandler; import com.tmt.kontroll.ui.page.segments.PageSegment; /** * <p> * Configures {@link PageSegment}s annotated with {@link PageConfig} according to the * configuration of {link Event} annotations present. * </p> * * @author SergDerbst * */ @Component public class EventConfigurator extends PageSegmentConfigurator { @Autowired EventConfigurationHandler eventHandler; @Override protected Class<? extends Annotation> getAnnotationType() { return Event.class; } @Override public void configure(final PageSegment segment) { final PageConfig config = segment.getClass().getAnnotation(PageConfig.class); for (final Event event : config.events()) { this.eventHandler.handle(event, segment); } for (final PageContext context : config.contexts()) { for (final Event event : context.events()) { this.eventHandler.handle(event, segment); } } } }
Java
UTF-8
535
1.921875
2
[]
no_license
package com.s.homepage.impl; import com.s.entity.Positions; import com.s.homepage.mapper.PositionsMapper; import com.s.interfac.PositionsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class PositionsServiceImpl implements PositionsService { @Autowired private PositionsMapper positionsMapper; @Override public Positions getPositionsId(String positionsName) { return positionsMapper.getPositionsId(positionsName); } }
Java
UTF-8
10,084
2.109375
2
[ "MIT" ]
permissive
/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockito.internal.creation; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.junit.Test; import org.mockito.Mock; import org.mockito.exceptions.base.MockitoException; import org.mockito.internal.debugging.VerboseMockInvocationLogger; import org.mockito.listeners.InvocationListener; import org.mockito.listeners.StubbingLookupListener; import org.mockitoutil.TestBase; public class MockSettingsImplTest extends TestBase { private MockSettingsImpl<?> mockSettingsImpl = new MockSettingsImpl<Object>(); @Mock private InvocationListener invocationListener; @Mock private StubbingLookupListener stubbingLookupListener; @Test @SuppressWarnings("unchecked") public void shouldNotAllowSettingNullInterface() { assertThatThrownBy( () -> { mockSettingsImpl.extraInterfaces(List.class, null); }) .isInstanceOf(MockitoException.class) .hasMessageContaining("extraInterfaces() does not accept null parameters."); } @Test @SuppressWarnings("unchecked") public void shouldNotAllowNonInterfaces() { assertThatThrownBy( () -> { mockSettingsImpl.extraInterfaces(List.class, LinkedList.class); }) .isInstanceOf(MockitoException.class) .hasMessageContainingAll( "extraInterfaces() accepts only interfaces", "You passed following type: LinkedList which is not an interface."); } @Test @SuppressWarnings("unchecked") public void shouldNotAllowUsingTheSameInterfaceAsExtra() { assertThatThrownBy( () -> { mockSettingsImpl.extraInterfaces(List.class, LinkedList.class); }) .isInstanceOf(MockitoException.class) .hasMessageContainingAll( "extraInterfaces() accepts only interfaces.", "You passed following type: LinkedList which is not an interface."); } @Test @SuppressWarnings("unchecked") public void shouldNotAllowEmptyExtraInterfaces() { assertThatThrownBy( () -> { mockSettingsImpl.extraInterfaces(); }) .isInstanceOf(MockitoException.class) .hasMessageContaining("extraInterfaces() requires at least one interface."); } @Test @SuppressWarnings("unchecked") public void shouldNotAllowNullArrayOfExtraInterfaces() { assertThatThrownBy( () -> { mockSettingsImpl.extraInterfaces((Class<?>[]) null); }) .isInstanceOf(MockitoException.class) .hasMessageContaining("extraInterfaces() requires at least one interface."); } @Test @SuppressWarnings("unchecked") public void shouldAllowMultipleInterfaces() { // when mockSettingsImpl.extraInterfaces(List.class, Set.class); // then assertThat(mockSettingsImpl.getExtraInterfaces().size()).isEqualTo(2); assertThat(mockSettingsImpl.getExtraInterfaces()).contains(List.class); assertThat(mockSettingsImpl.getExtraInterfaces()).contains(Set.class); } @Test public void shouldSetMockToBeSerializable() { // when mockSettingsImpl.serializable(); // then assertThat(mockSettingsImpl.isSerializable()).isTrue(); } @Test public void shouldKnowIfIsSerializable() { // given assertThat(mockSettingsImpl.isSerializable()).isFalse(); // when mockSettingsImpl.serializable(); // then assertThat(mockSettingsImpl.isSerializable()).isTrue(); } @Test public void shouldAddVerboseLoggingListener() { // given assertThat(mockSettingsImpl.hasInvocationListeners()).isFalse(); // when mockSettingsImpl.verboseLogging(); // then assertThat(mockSettingsImpl.getInvocationListeners()) .extracting("class") .contains(VerboseMockInvocationLogger.class); } @Test public void shouldAddVerboseLoggingListenerOnlyOnce() { // given assertThat(mockSettingsImpl.hasInvocationListeners()).isFalse(); // when mockSettingsImpl.verboseLogging().verboseLogging(); // then assertThat(mockSettingsImpl.getInvocationListeners()).hasSize(1); } @Test @SuppressWarnings("unchecked") public void shouldAddInvocationListener() { // given assertThat(mockSettingsImpl.hasInvocationListeners()).isFalse(); // when mockSettingsImpl.invocationListeners(invocationListener); // then assertThat(mockSettingsImpl.getInvocationListeners()).contains(invocationListener); } @Test @SuppressWarnings("unchecked") public void canAddDuplicateInvocationListeners_ItsNotOurBusinessThere() { // given assertThat(mockSettingsImpl.hasInvocationListeners()).isFalse(); // when mockSettingsImpl .invocationListeners(invocationListener, invocationListener) .invocationListeners(invocationListener); // then assertThat(mockSettingsImpl.getInvocationListeners()) .containsSequence(invocationListener, invocationListener, invocationListener); } @Test public void validates_listeners() { assertThatThrownBy( () -> mockSettingsImpl.addListeners( new Object[] {}, new LinkedList<Object>(), "myListeners")) .hasMessageContaining("myListeners() requires at least one listener"); assertThatThrownBy( () -> mockSettingsImpl.addListeners( null, new LinkedList<Object>(), "myListeners")) .hasMessageContaining("myListeners() does not accept null vararg array"); assertThatThrownBy( () -> mockSettingsImpl.addListeners( new Object[] {null}, new LinkedList<Object>(), "myListeners")) .hasMessageContaining("myListeners() does not accept null listeners"); } @Test public void validates_stubbing_lookup_listeners() { assertThatThrownBy( () -> mockSettingsImpl.stubbingLookupListeners( new StubbingLookupListener[] {})) .hasMessageContaining("stubbingLookupListeners() requires at least one listener"); assertThatThrownBy(() -> mockSettingsImpl.stubbingLookupListeners(null)) .hasMessageContaining( "stubbingLookupListeners() does not accept null vararg array"); assertThatThrownBy( () -> mockSettingsImpl.stubbingLookupListeners( new StubbingLookupListener[] {null})) .hasMessageContaining("stubbingLookupListeners() does not accept null listeners"); } @Test public void validates_invocation_listeners() { assertThatThrownBy(() -> mockSettingsImpl.invocationListeners(new InvocationListener[] {})) .hasMessageContaining("invocationListeners() requires at least one listener"); assertThatThrownBy(() -> mockSettingsImpl.invocationListeners(null)) .hasMessageContaining("invocationListeners() does not accept null vararg array"); assertThatThrownBy( () -> mockSettingsImpl.invocationListeners(new InvocationListener[] {null})) .hasMessageContaining("invocationListeners() does not accept null listeners"); } @Test public void addListeners_has_empty_listeners_by_default() { assertThat(mockSettingsImpl.getInvocationListeners()).isEmpty(); assertThat(mockSettingsImpl.getStubbingLookupListeners()).isEmpty(); } @Test public void addListeners_shouldAddMockObjectListeners() { // when mockSettingsImpl.invocationListeners(invocationListener); mockSettingsImpl.stubbingLookupListeners(stubbingLookupListener); // then assertThat(mockSettingsImpl.getInvocationListeners()).contains(invocationListener); assertThat(mockSettingsImpl.getStubbingLookupListeners()).contains(stubbingLookupListener); } @Test public void addListeners_canAddDuplicateMockObjectListeners_ItsNotOurBusinessThere() { // when mockSettingsImpl .stubbingLookupListeners(stubbingLookupListener) .stubbingLookupListeners(stubbingLookupListener) .invocationListeners(invocationListener) .invocationListeners(invocationListener); // then assertThat(mockSettingsImpl.getInvocationListeners()) .containsSequence(invocationListener, invocationListener); assertThat(mockSettingsImpl.getStubbingLookupListeners()) .containsSequence(stubbingLookupListener, stubbingLookupListener); } @Test public void validates_strictness() { assertThatThrownBy(() -> mockSettingsImpl.strictness(null)) .hasMessageContaining("strictness() does not accept null parameter"); } }
Java
UTF-8
3,901
3.28125
3
[]
no_license
package com.example.bms.Test; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.*; import java.net.Socket; import java.util.Scanner; /** * 用户聊天界面及数据处理器 * @create 2021-01-23 13:14 */ public class ClientHandle extends JFrame implements ActionListener, KeyListener, Runnable{ private JTextArea jta; //文本域 private JScrollPane jsp; //滚动条 private JPanel jp; //面板 private JTextField jtf; //文本框 private JButton jb; //按钮 private PrintStream ps = null; //输出流 private Socket socket; // 用户端口 private String userName; // 用户名 //构造方法 public ClientHandle(String userName, Socket socket) { this.userName = userName; this.socket = socket; this.init(); // 初始化 } /** * 初始化 */ public void init() { //初始化组件 jta = new JTextArea(); //文本域,需要将文本域添加到滚动条中,实现滚动效果 jsp = new JScrollPane(jta); //滚动条 jp = new JPanel(); //面板 jtf = new JTextField(15);//文本框大小 jb = new JButton("发送");//按钮名称 // 将文本框与按钮添加到面板中 jp.add(jtf); jp.add(jb); // 将滚动条和面板添加到窗体中 this.add(jsp, BorderLayout.CENTER); this.add(jp,BorderLayout.SOUTH); //设置 标题、大小、位置、关闭、是否可见 this.setTitle(userName + " 聊天框");//标题 this.setSize(400,400);// 宽,高 this.setLocation(700,300);// 水平 垂直 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//窗体关闭 程序退出 this.setVisible(true);//是否可见 //给"发送"按钮绑定一个监听点击事件 jb.addActionListener(this);//让当前对象监听 //给文本框绑定一个键盘点击事件 jtf.addKeyListener(this); } @Override public void run() { Scanner scanner = null; try { while (true) { scanner = new Scanner(socket.getInputStream()); // 获取接收服务器信息的扫描器 while (scanner.hasNext()) { jta.append(scanner.next() + System.lineSeparator()); // 将受到的信息显示出来,换行 } } } catch(IOException e) { e.printStackTrace(); } finally { if (scanner != null) { scanner.close(); } } } @Override public void actionPerformed(ActionEvent event) { // 点击发送按钮时发送会话框中的内容 //发送数据到socket通道中 sendDataToServer(); } @Override public void keyPressed(KeyEvent e) { // 键盘按下回车键时将会话框中的内容发送出去 if(e.getKeyCode() == KeyEvent.VK_ENTER) { //发送数据到socket通道中 sendDataToServer(); } } @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { } //将数据发送给Server服务端 private void sendDataToServer(){ String text = jtf.getText(); // 获取文本框中发送的内容 jta.append("我:" + text + "\n"); // 在自己的聊天界面中显示 try { // 发送数据 ps = new PrintStream(socket.getOutputStream()); ps.println(text); ps.flush(); // 清空自己当前的会话框 jtf.setText(""); } catch (IOException el) { el.printStackTrace(); } } }
Markdown
UTF-8
1,033
3.28125
3
[ "MIT" ]
permissive
--- layout: post title: "[Basic] K largest elements" date: 2018-01-17 11:30:00 +0900 categories: Algorithm --- Given an array, print k largest elements from the array. The output elements should be printed in decreasing order. Input: The first line of input contains an integer T denoting the number of test cases. The first line of each test case is N and k, N is the size of array and K is the largest elements to be returned. The second line of each test case contains N input C[i]. Output: Print the k largest element in descending order. Constraints: 1 ≤ T ≤ 100<br> 1 ≤ N ≤ 100<br> K ≤ N<br> 1 ≤ C[i] ≤ 1000 Example: Input: 2<br> 5 2<br> 12 5 787 1 23<br> 7 3<br> 1 23 12 9 30 2 50 Output:<br> 787 23<br> 50 30 23 ```python t = int(input()) for i in range(t): answer = [] n = list(map(int, input().split())) arr = list(map(int, input().split())) for j in range(int(n[1])): answer.append(max(arr)) arr.remove(max(arr)) print(" ".join(str(i) for i in answer)) ```
Python
UTF-8
15,820
2.75
3
[]
no_license
# computes trajectories on a Dedalus Chebyshev (z) / Fourier (x,y) grid from mpi4py import MPI import numpy as np import math as ma import matplotlib.pyplot as plt import scipy from scipy.fftpack import fft, dct from decimal import Decimal from scipy.stats import chi2 from scipy import signal import matplotlib.patches as mpatches from matplotlib.colors import colorConverter as cc from scipy.fftpack import fft, fftshift import matplotlib.patches as mpatches from matplotlib.colors import colorConverter as cc from mpl_toolkits.mplot3d import Axes3D figure_path = './figures' # make the trajectory calculation into a function # velocity fields must # want a function that takes the x0,y0,z0 (which may be more than one # point) and a known velocity field and outputs the trajectories into # data files. # ============================================================================= # functions def weights(z,x,m): # From Bengt Fornbergs (1998) SIAM Review paper. # Input Parameters # z location where approximations are to be accurate, # x(0:nd) grid point locations, found in x(0:n) # n one less than total number of grid points; n must # not exceed the parameter nd below, # nd dimension of x- and c-arrays in calling program # x(0:nd) and c(0:nd,0:m), respectively, # m highest derivative for which weights are sought, # Output Parameter # c(0:nd,0:m) weights at grid locations x(0:n) for derivatives # of order 0:m, found in c(0:n,0:m) # dimension x(0:nd),c(0:nd,0:m) n = np.shape(x)[0]-1 c = np.zeros([n+1,m+1]) c1 = 1.0 c4 = x[0]-z for k in range(0,m+1): for j in range(0,n+1): c[j,k] = 0.0 c[0,0] = 1.0 for i in range(0,n+1): mn = min(i,m) c2 = 1.0 c5 = c4 c4 = x[i]-z for j in range(0,i): c3 = x[i]-x[j] c2 = c2*c3 if (j == i-1): for k in range(mn,0,-1): c[i,k] = c1*(k*c[i-1,k-1]-c5*c[i-1,k])/c2 c[i,0] = -c1*c5*c[i-1,0]/c2 for k in range(mn,0,-1): c[j,k] = (c4*c[j,k]-k*c[j,k-1])/c3 c[j,0] = c4*c[j,0]/c3 c1 = c2 return c def fornberg1d( xl , x , u , N , m ): # Input: the grid, the location to interpolate to, values to interpolate # Output: the interpolated variable at the specified location. # N = an even number of indices for the stencil # m = order of the derivative to be interpolated (0 = just interpolation) Nx = np.shape(u)[0] # u must be shape = [Nx,1] #print(Nx) # ensure u is shape = [Nx,1] v = np.zeros([Nx,1]) for j in range(0,Nx): v[j] = u[j] u = v # find the nearest N grid points to xl on x: dist = np.zeros([Nx]) for j in range(0,Nx): dist[j] = np.sqrt( (x[j] - xl)**2. ) minloc = np.where(dist == np.amin(dist))[0][0] # add near-boundary option for stencil here!!! xint = x[minloc-int(N/2)+1:minloc+int(N/2)+1] # the nearest N grid points to xl # now interpolate with the Fornberg scheme c = np.transpose(weights(xl,xint,N)) uint = np.dot( c[m,:] , u[minloc-int(N/2)+1:minloc+int(N/2)+1,0] ) return uint def fornberg3d( xl , x , yl , y , zl , z , u , N , m ): # Input: the grid, the location to interpolate to, values to interpolate # Output: the interpolated variable at the specified location. # N = an even number of indices for the stencil # m = order of the derivative to be interpolated (0 = just interpolation) #print(np.shape(u)) Ny = np.shape(u)[0] Nx = np.shape(u)[1] Nz = np.shape(u)[2] # interpolate in x: ux = np.zeros([Ny,Nz]) for i in range(0,Ny): for j in range(0,Nz): ux[i,j] = fornberg1d( xl , x , u[i,:,j] , N , m ) # interpolate in y: uy = np.zeros([Nz]) for j in range(0,Nz): uy[j] = fornberg1d( yl , y , ux[:,j] , N , m ) # interpolate in z: uz = fornberg1d( zl , z , uy , N , m ) return uz # interpolated to (xl,yl,zl) def trajectory( xn , x , yn , y , zn , z , un , u , vn , v , wn , w , N , m , t , dt , Nt , figure_path ): # input: # xn,yn,zn = trajectory locations (initialized with x0,y0,z0 at time t[0] = 0), shape = [Nt] # un,vn,wn = initial velocities, to be rewritten as the scheme advances, shape = [1] # x,y,z,u,v,w = grid points & velocity fields, shape = # N = number of points in interp stencil, Fornberg algorithm constant # m = order of derivative (0th = interpolation) Fornberg algorithm constant # dt = time step (must be constant) # t = time # Nt = length of time vector for j in range(0,Nt-1): print(j) # update Lagrangian locations using the previous steps' location and velocity field: xn[j+1] = dt*un + xn[j] # un is at time t[j] yn[j+1] = dt*vn + yn[j] zn[j+1] = dt*wn + zn[j] # interpolate the velocites at time t[j+1] to the locations at time t[j+1] un = fornberg3d( xn[j+1] , x , yn[j+1] , y , zn[j+1] , z , u[j+1,:,:,:] , N , m ) vn = fornberg3d( xn[j+1] , x , yn[j+1] , y , zn[j+1] , z , v[j+1,:,:,:] , N , m ) wn = fornberg3d( xn[j+1] , x , yn[j+1] , y , zn[j+1] , z , w[j+1,:,:,:] , N , m ) # plot: plot_num = '%i' %j if j < 10: plotname = figure_path +'/00000' + plot_num +'.png' elif j < 100: plotname = figure_path +'/0000' + plot_num +'.png' elif j < 1000: plotname = figure_path +'/000' + plot_num +'.png' elif j < 10000: plotname = figure_path +'/00' + plot_num +'.png' elif j < 100000: plotname = figure_path +'/0' + plot_num +'.png' elif j < 1000000: plotname = figure_path +'/' + plot_num +'.png' #plottitle = 'trajectory, (x0,y0,z0)=(%.2f,%.2f,%.2f)' %(x0,y0,z0) plottitle = 't = %.1f s' %(t[j]) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot(xn[0:j+1],yn[0:j+1], zn[0:j+1], color='b') #, marker='o') ax.set_xlabel("x") ax.set_ylabel("y") ax.set_zlabel("z") plt.axis([-2.8,-2.64,-0.01,0.035]) plt.title(plottitle); plt.savefig(plotname,format="png"); plt.close(fig); return xn,yn,zn def trajectories_parallel( xn , x , yn , y , zn , z , un , u , vn , v , wn , w , N , m , t , dt , Nt , Ns , n , counts , displs , n2 , counts2 , displs2 ): # broadcast N,m? # Broadcast the grid and (known) u,v,w fields: comm.Bcast(x, root=0) comm.Bcast(y, root=0) comm.Bcast(z, root=0) comm.Bcast(u, root=0) comm.Bcast(v, root=0) comm.Bcast(w, root=0) #comm.Bcast(N, root=0) # number of stencil points for Fornberg algorithm #comm.Bcast(m, root=0) # order of derivative for Fornberg algorithm # initialize chunks: if rank == 0: xnc = np.zeros([int(n/Nt),Nt]) # shape = Nchunk, Nt ync = np.zeros([int(n/Nt),Nt]) znc = np.zeros([int(n/Nt),Nt]) unc = np.zeros([int(n2)]) vnc = np.zeros([int(n2)]) wnc = np.zeros([int(n2)]) #print(int(n/Nt),int(n2)) else: xnc = np.empty([int(n/Nt),Nt], dtype=np.float64 ) # shape = Nchunk, Nt ync = np.empty([int(n/Nt),Nt], dtype=np.float64 ) znc = np.empty([int(n/Nt),Nt], dtype=np.float64 ) unc = np.empty([int(n2)], dtype=np.float64 ) vnc = np.empty([int(n2)], dtype=np.float64 ) wnc = np.empty([int(n2)], dtype=np.float64 ) comm.Bcast(xnc, root=0) comm.Bcast(ync, root=0) comm.Bcast(znc, root=0) comm.Bcast(unc, root=0) comm.Bcast(vnc, root=0) comm.Bcast(wnc, root=0) # scatter variables comm.Scatterv([ xn , counts , displs , MPI.DOUBLE ], xnc, root = 0) comm.Scatterv([ yn , counts , displs , MPI.DOUBLE ], ync, root = 0) comm.Scatterv([ zn , counts , displs , MPI.DOUBLE ], znc, root = 0) comm.Scatterv([ un , counts2 , displs2 , MPI.DOUBLE ], unc, root = 0) comm.Scatterv([ vn , counts2 , displs2 , MPI.DOUBLE ], vnc, root = 0) comm.Scatterv([ wn , counts2 , displs2 , MPI.DOUBLE ], wnc, root = 0) # compute: for p in range(0,nprocs): # divide the computation into chunks, per processor if rank == p: #print('rank = %i' %p) for j in range(0,Nt-1): # loop over time if rank == 0: print('step = %i' %(j+1)) for i in range(0,int(Ns/nprocs)): # loop over points xnc[i,j+1] = dt*unc[i] + xnc[i,j] ync[i,j+1] = dt*vnc[i] + ync[i,j] znc[i,j+1] = dt*wnc[i] + znc[i,j] #if rank == 0: # print('point = %i' %i) #print(u[j+1,:,:,:]) #print(N,m) #print(np.shape(xnc),Nt,Ns) unc[i] = fornberg3d( xnc[i,j+1] , x , ync[i,j+1] , y , znc[i,j+1] , z , u[j+1,:,:,:] , N , m ) vnc[i] = fornberg3d( xnc[i,j+1] , x , ync[i,j+1] , y , znc[i,j+1] , z , v[j+1,:,:,:] , N , m ) wnc[i] = fornberg3d( xnc[i,j+1] , x , ync[i,j+1] , y , znc[i,j+1] , z , w[j+1,:,:,:] , N , m ) # gather xn,yn,zn values into x,y,z: if rank == 0: x0 = np.zeros([Ns,Nt], dtype=np.float64) y0 = np.zeros([Ns,Nt], dtype=np.float64) z0 = np.zeros([Ns,Nt], dtype=np.float64) else: x0 = None y0 = None z0 = None comm.Gatherv(xnc, [x0, counts, displs, MPI.DOUBLE], root = 0) comm.Gatherv(ync, [y0, counts, displs, MPI.DOUBLE], root = 0) comm.Gatherv(znc, [z0, counts, displs, MPI.DOUBLE], root = 0) return x0,y0,z0 # ============================================================================= comm = MPI.COMM_WORLD nprocs = comm.Get_size() rank = comm.Get_rank() # [0,1,2,...,nprocs-1] # ============================================================================= # grid Lx, Ly, H = (6., 6., 20.) Nx = 128 Ny = 128 Nz = 16 # computational domain (identical to how dedalus builds) dx = Lx/Nx; x = np.linspace(0.0, dx*Nx-dx, num=Nx) - Lx/2. dy = Ly/Ny; y = np.linspace(0.0, dy*Ny-dy, num=Ny) - Ly/2. z = -np.cos(((np.linspace(1., Nz, num=Nz))*2.-1.)/(2.*Nz)*np.pi)*H/2.+H/2. X,Y,Z = np.meshgrid(x,y,z) # shape = Ny, Nx, Nz dt = 1. # s Tfinal = 8. #100. Nt = int(Tfinal/dt) t = np.linspace(0.0, Tfinal-dt, num=Nt) # ============================================================================= # initial velocities at one point # Fornberg (1998) algorithm constraints N = 4 # four point stencil m = 0 # zeroth derivative # input known velocity fields (entire array, corresponds to the analytical solution): u0 = 0.001 # m/s v0 = 0.001 # m/s k = 2.*np.pi/Lx*10. # wavenumber in x c = 2.*np.pi/(10*Tfinal) Xk = np.tile( X[...,None],Nt ) T = np.tile(np.tile(np.tile(t[...,None],Ny)[...,None],Nx)[...,None],Nz) #print(sum(sum(sum(X-Xk[:,:,:,0])))) u = np.ones(np.shape(T))*u0 # shape = Nt, Ny, Nx, Nz w = np.zeros(np.shape(T)) v = np.zeros([Nt, Ny, Nx, Nz]) for j in range(0,Nt): v[j,:,:,:] = v0*np.cos(k*(Xk[:,:,:,j]-c*T[j,:,:,:])) # shape = Nt, Ny, Nx, Nz # initial locations and velocities at those locations: (x0c,y0c,z0c) = (X[64,32,5],Y[64,32,5],Z[64,32,5]) # shape = Ny, Nx, Nz r = 0.05 # m, radius tht = np.arange(0.,384,24.)*np.pi/180. # Ns points C0 = 2.*np.pi*r # m, true circumference at t=0 Ns = np.shape(tht)[0] n = int(Ns*Nt/nprocs) # number of elements in a space-time chunk counts = np.ones([nprocs])*n # array describing how many elements to send to each process displs = np.linspace(0,Ns*Nt-n,nprocs,dtype=int) # array describing the displacements where each segment begins n2 = int(Ns/nprocs) # number of elements in a space chunk counts2 = np.ones([nprocs])*n2 # array describing how many elements to send to each process displs2 = np.linspace(0,Ns-n2,nprocs,dtype=int) # array describing the displacements where each segment begins #if rank == 0: #print(Nt) #print(Ns) #print(int(Ns/nprocs)) #print(n) #print(counts) #print(displs) #print(n2) #print(counts2) #print(displs2) # 1) scatter chunks of xn,yn,zn,un,vn,zn: if rank == 0: xn = np.zeros([Ns,Nt]) yn = np.zeros([Ns,Nt]) zn = np.zeros([Ns,Nt]) un = np.zeros([Ns]) vn = np.zeros([Ns]) wn = np.zeros([Ns]) #print(np.shape(xn)) else: xn = None yn = None zn = None un = None vn = None wn = None # broadcast: if rank == 0: xnc = np.zeros([int(n/Nt),Nt]) # shape = Nchunk, Nt ync = np.zeros([int(n/Nt),Nt]) znc = np.zeros([int(n/Nt),Nt]) unc = np.zeros([int(n2)]) vnc = np.zeros([int(n2)]) wnc = np.zeros([int(n2)]) else: xnc = np.empty([int(n/Nt),Nt], dtype=np.float64 ) # shape = Nchunk, Nt ync = np.empty([int(n/Nt),Nt], dtype=np.float64 ) znc = np.empty([int(n/Nt),Nt], dtype=np.float64 ) unc = np.empty([int(n2)], dtype=np.float64 ) vnc = np.empty([int(n2)], dtype=np.float64 ) wnc = np.empty([int(n2)], dtype=np.float64 ) comm.Bcast(xnc, root=0) comm.Bcast(ync, root=0) comm.Bcast(znc, root=0) comm.Bcast(unc, root=0) comm.Bcast(vnc, root=0) comm.Bcast(wnc, root=0) #if rank == 3: # print(np.shape(xnc)) comm.Scatterv([ xn , counts , displs , MPI.DOUBLE ], xnc, root = 0) # scattering zeros... comm.Scatterv([ yn , counts , displs , MPI.DOUBLE ], ync, root = 0) comm.Scatterv([ zn , counts , displs , MPI.DOUBLE ], znc, root = 0) comm.Scatterv([ un , counts2 , displs2 , MPI.DOUBLE ], unc, root = 0) comm.Scatterv([ vn , counts2 , displs2 , MPI.DOUBLE ], vnc, root = 0) comm.Scatterv([ wn , counts2 , displs2 , MPI.DOUBLE ], wnc, root = 0) #if rank == 0: # print(np.shape(xnc),Nt,Ns) # 2) compute new xn,yn,zn,un,vn,zn values in chunks: for p in range(0,nprocs): if rank == p: for i in range(0,int(Ns/nprocs)): #print(i+p*int(Ns/nprocs)) xnc[i,0] = x0c + r*np.cos(tht[i+p*int(Ns/nprocs)]) ync[i,0] = y0c + r*np.sin(tht[i+p*int(Ns/nprocs)]) #0,i znc[i,0] = z0c + tht[i]*0. unc[i] = fornberg3d( xnc[i,0] , x , ync[i,0] , y , znc[i,0] , z , u[0,:,:,:] , N , m ) vnc[i] = fornberg3d( xnc[i,0] , x , ync[i,0] , y , znc[i,0] , z , v[0,:,:,:] , N , m ) wnc[i] = fornberg3d( xnc[i,0] , x , ync[i,0] , y , znc[i,0] , z , w[0,:,:,:] , N , m ) #print(xnc[:,0]) #print(np.shape(w[0,:,:,:])) # 3) gather xn,yn,zn,un,vn,zn values: if rank == 0: x0 = np.zeros([Ns,Nt], dtype=np.float64) y0 = np.zeros([Ns,Nt], dtype=np.float64) z0 = np.zeros([Ns,Nt], dtype=np.float64) u0 = np.zeros([Ns], dtype=np.float64) v0 = np.zeros([Ns], dtype=np.float64) w0 = np.zeros([Ns], dtype=np.float64) #print(np.shape(x)) else: x0 = None y0 = None z0 = None u0 = None v0 = None w0 = None comm.Gatherv(xnc, [x0, counts, displs, MPI.DOUBLE], root = 0) comm.Gatherv(ync, [y0, counts, displs, MPI.DOUBLE], root = 0) comm.Gatherv(znc, [z0, counts, displs, MPI.DOUBLE], root = 0) comm.Gatherv(unc, [u0, counts2, displs2, MPI.DOUBLE], root = 0) comm.Gatherv(vnc, [v0, counts2, displs2, MPI.DOUBLE], root = 0) comm.Gatherv(wnc, [w0, counts2, displs2, MPI.DOUBLE], root = 0) # 4) plot: if rank == 0: # initial velocities are ok: print(u0) print(v0) print(w0) # plot the circle: #print(x[:,0]) #print(np.nonzero(x)) plotname = figure_path +'/circle.png' plottitle = '(x0,y0,z0)=(%.2f,%.2f,%.2f)' %(x0c,y0c,z0c) fig = plt.figure() plt.plot(x0[:,0],y0[:,0],'b'); #0,: plt.xlabel('x'); #plt.legend(loc=1); plt.ylabel('y'); plt.axis('tight') #[5.,15.,-1.5e-9,1.5e-9]) plt.title(plottitle); plt.savefig(plotname,format='png'); plt.close(fig); # now add parallel trajectories code: (xf,yf,zf) = trajectories_parallel( x0 , x , y0 , y , z0 , z , u0 , u , v0 , v , w0 , w , N , m , t , dt , Nt , Ns , n , counts , displs , n2 , counts2 , displs2 ) if rank == 0: print(xf[:,7]) print(yf[:,7]) print(zf[:,7]) """ # plot: plot_num = '%i' %j if j < 10: plotname = figure_path +'/00000' + plot_num +'.png' elif j < 100: plotname = figure_path +'/0000' + plot_num +'.png' elif j < 1000: plotname = figure_path +'/000' + plot_num +'.png' elif j < 10000: plotname = figure_path +'/00' + plot_num +'.png' elif j < 100000: plotname = figure_path +'/0' + plot_num +'.png' elif j < 1000000: plotname = figure_path +'/' + plot_num +'.png' #plottitle = 'trajectory, (x0,y0,z0)=(%.2f,%.2f,%.2f)' %(x0,y0,z0) plottitle = 't = %.1f s' %(t[j]) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot(xn[j,:],yn[j,:], zn[j,:], color='b') #, marker='o') ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') plt.axis([-1.7,0.3,-0.25,0.25]) plt.title(plottitle); plt.savefig(plotname,format='png'); plt.close(fig); """
C++
UTF-8
772
3.84375
4
[ "MIT" ]
permissive
// Program demonstrating binary search in a sorted array (ascending order) #include<iostream> using namespace std; int binarySearch(int A[],int i,int start,int end){ if(start > end) return -1; int mid = (start+end)/2; int ans; if(A[mid] == i){ ans = mid; return ans; } if(A[mid] > i){ end = mid-1; binarySearch(A,i,start,end); } if(A[mid] < i){ start = mid+1; binarySearch(A,i,start,end); } } int main(){ int size,i,ans; cout<<"Enter size of sorted array\n"; cin>>size; int A[size]; cout<<"Enter the elements in ascending order\n"; for(i=0;i<size;i++) cin>>A[i]; cout<<"Enter the element to be searched for\n"; cin>>i; ans = binarySearch(A,i,0,size-1); if(ans != -1) cout<<"Element found!\n"; else cout<<"Element not found!\n"; return 0; }
Python
UTF-8
1,173
3.21875
3
[]
no_license
a="101" def countOnes(A): empty = [] a = list(A) if a.count("1") == len(a): return empty b = [] max_nums = a.count("1") location = [1, 1] for i in range(len(a)): for j in range(i, len(a)): b = a.copy() if i == j: b[i] = str(1 - int(b[i])) else: for k in range(i, j + 1): b[k] = str(1 - int(b[k])) # b[j] = 1 - (b[j]) if b.count("1") > max_nums: location = [i + 1, j + 1] max_nums = b.count("1") # print(b,location,b.count("1"),max_nums) # print(f"({i},{j}) array-{b}, bcount-{b.count(1)}, max-val-{max_nums}, {location}") return location def countOnes_kadane(A): a = [1 if i == '0' else -1 for i in A] curr_sum=0 max_sum=0 res = [] start=0 for i in range(len(A)): curr_sum += a[i] if curr_sum > max_sum and curr_sum >=0: max_sum=curr_sum res = [start+1, i+1] else: start +=1 curr_sum=0 return res #print(countOnes(a)) print(countOnes_kadane(a))
Markdown
UTF-8
5,810
2.859375
3
[ "Apache-2.0" ]
permissive
# El pulpo de raza loba ## Índice 1. [Desarrollo en Entorno Cliente](#cliente) - [Arquitectura de la aplicación y tecnologías utilizadas](#arquitectura) - [Diagrama de componentes](#diagrama) - [Clockify](#clockify) 2. [Despliegue de la Aplicación Web](#despliegue) 3. [Diseño de Interfaces](#interfaces) - [Diseño de la interfaz](#diseñoInt) - [Css GRID y Css Flexbox](#css) - [Tipografía utilizada](#tipografia) - [Paleta de colores](#colores) 4. [Información](#información) ## 1. Desarrollo en Entorno Cliente<a id="cliente"></a> ### 1.1 Arquitectura de la aplicación y tecnologías utilizadas<a id="arquitectura"></a> ![Arquitectura](https://github.com/ocelot269/Pop-proyect/blob/master/Front/img/arquitectura.jpg) ### 1.2 Diagrama de componentes<a id="diagrama"></a> ![Diagrama](https://github.com/ocelot269/Pop-proyect/blob/master/Front/img/diagrama.jpg) ### 1.3 Clockify<a id="clockify"></a> ![Clockify](https://github.com/ocelot269/Pop-proyect/blob/master/Front/img/clockify.JPG) ## 2. Despliegue de la Aplicación Web<a id="despliegue"></a> La documentación se podrá encontrar aqui: https://docs.google.com/document/d/1zNieCK8W2y5TGMrqelVzl2OGJVB7lNgssOU4jdh1PEQ/edit?usp=sharing ## 3. Diseño de Interfaces<a id="interfaces"></a> ### 3.1. Diseño de la interfaz<a id="diseñoInt"></a> #### 3.1.1. Explicación del diseño de las diferentes interfaces (Escritorio, móvil, tablet...) ---- El diseño principal está creado con Grid. En tamaño escritorio tenemos una estructura de 3 o 4 partes. En la página principal y la de correlaciones, tenemos la parte del Navbar y el Footer. En el centro encontramos dos columnas, una con el contenido principal de la página y otra que es el Newsletter. En la página del diario solo encontramos 3 partes, Navbar y Footer, igual que las otras dos comentadas. En cambio solo hay una columna central, la cual contiene el diario completo. En formato móvil y tablet, es una estructura de 1, y se alinean, uno abajo de la otra las diferentes partes comentadas anteriormente. #### 3.1.2. Cambios que ocurren cuando el usuario cambia de una interfaz a otra ---- Cuando el Usuario pasa de una interfaz a otra podrá observar como poco a poco la web se va ajustando a la medida de su pantalla. Normalmente se le colocara en posición vertical cada elemento de la web. #### 3.1.3. Puntos de interrupción --- Los puntos de interrupción que se han utilizado en nuestra web es 600px y en un caso 500px. Se utiliza para pasar de escritorio a móvil o tablet. ### 3.2. Css GRID y Css Flexbox<a id="css"></a> Se ha creado una base fija con ***Grid***, ya que hemos considerado que es más sencillo y más practico a la hora de hacerlo responsive. Nuestra base fija consta de 3 partes, el *navbar* que se encuentra en la parte superior y ocupa todo. Luego encontramos la parte central, la cual dependiendo de la página en la que te encuentres, hay más partes o menos. En el index, por ejemplo, hay dos partes, la del contenido y la del sidebar, que tiene como contenido el Newsletter. En cambio, la del diario solo tiene el contenido, que ocupa toda la parte central. Finalmente encontramos el *footer*, el cual para situar cada parte ha sido utilizado ***flexbox***, por el hecho de que fuese más sencillo definir y colocar cada columna donde queríamos. También se ha hecho uso tanto de ***Grid*** como de ***Flexbox***, en la parte del diario. Ya que la fila donde se encuentran los nombres de los días esta creada con ***Grid***. Las filas, donde podemos ver los números, está creada con una estructura de ***Grid*** y dentro utilizamos ***Flexbox*** para poder situar cada día en su respectiva posición. Se ha creado la estructura con ***Grid*** porque al hacerlo en formato móvil o tablet, es más sencillo que con ***Flexbox***. En la gráfica se utiliza ***Flexbox***. ### 3.3. Tipografía utilizada<a id="tipografia"></a> Se han utilizado dos tipografías cogidas desde [Google Fonts](https://fonts.google.com/). Para el cuerpo utilizamos [Noto Sans](https://fonts.google.com/specimen/Noto+Sans). Queríamos utilizar una tipografía que fuese fácil de leer y que no quedase muy cargada la página. Decidimos decantarnos por esta porque vimos que era bastante normal, pero a la vez es divertida y fuera de lo habitual. Después para los títulos utilizamos [Fjalla One](https://fonts.google.com/specimen/Fjalla+One). Vimos que encajaba bastante bien con la que habíamos decidido para el cuerpo y que era diferente a las demás. También consideramos que resaltaba muy bien en título. ### 3.4. Paleta de colores<a id="colores"></a> Para ayudarnos con la paleta de colores, los hemos buscado desde [Paletton](http://paletton.com/) y nuestra paleta es [esta](http://paletton.com/#uid=13j0u0kpJkHh2t7lQovukgbE3aP). Hemos escogido estos colores porque pensamos que combinan bien con el estilo de página que hemos diseñado. Hemos utilizado #054B4E para el fondo del Navbar. Un color común para cuando un link está activo en el navbar (#267276). Y finalmente #42898C para los :hover. También hemos utilizado la misma paleta de color pero en tono pastel, para los colores de la gráfica. ## 4. Información<a id="información"></a> ***Nombres de los autores:*** Jose Antonio Zamora Andrés y Sandra Cabrera García ***La idea fundamental del proyecto pertenece a Marijn Haverbeke, nosotros solo hemos cambiado el nombre al personaje *** ***Curso:*** 2º Desarrollo de Aplicaciones Web ***Duración del proyecto:*** Desde 10/10/2019 hasta 10/12/2019 ***Proyecto:*** El pulpo de raza loba ***Descripción breve del proyecto:*** Construir una aplicación web para poder ver y registrar los eventos que le suceden cada día a Mariano, con la finalidad de averiguar cuales de ellos provocan que se transforme en pulpo.
C++
UTF-8
360
3.234375
3
[]
no_license
#include<iostream> using namespace std; class Sample { private: static int x, y, z; Sample() { cout<<"Constructor Called"<<endl; } public: static void show() { Sample o1; cout<<"X="<<x<<endl; cout<<"Y="<<y<<endl; cout<<"Z="<<z<<endl; } }; int Sample::x= 10; int Sample::y= 20; int Sample::z= 30; int main() { Sample::show(); }
Go
UTF-8
665
3
3
[]
no_license
package templates import ( "testing" "github.com/stretchr/testify/assert" ) func TestFunctionCall(t *testing.T) { template := `0x{{ printf "%02x" . }}` assert.Equal(t, "0x41", renderTemplate(template, 65)) } func TestPipeline(t *testing.T) { template := `0x{{ . | printf "%02x" }}` assert.Equal(t, "0x41", renderTemplate(template, 65)) } func TestLongPipeline(t *testing.T) { template := `{{ . | printf "%02x" | printf "0x%s" }}` assert.Equal(t, "0x41", renderTemplate(template, 65)) } func TestChainingMixedWithPipeline(t *testing.T) { template := `{{ printf "0x%s" ( . | printf "%02x" ) }}` assert.Equal(t, "0x41", renderTemplate(template, 65)) }
Python
UTF-8
253
3.03125
3
[]
no_license
# coding=utf-8 def comp(array1, array2): if (not isinstance(array1, list) or not isinstance(array2, list)): return False array1 = [x ** 2 for x in array1] array1.sort() array2.sort() return array1 == array2
Python
UTF-8
708
3.265625
3
[]
no_license
1) N = int(input()) data = list(input().split()) x,y = 1, 1 #L,R,U,D 순서 dx = [0, 0, -1, 1] dy = [-1, 1, 0, 0] a = ['L', 'R', 'U', 'D'] for plan in data: for i in range(len(a)): if plan == a[i]: x += dx[i] y += dy[i] if x < 1: x = 1 elif x > N: x = N elif y < 1: y = 1 elif y > N: y = N print(x, y) 2) N = int(input()) data = list(input().split()) x,y = 1, 1 #L,R,U,D 순서 dx = [0, 0, -1, 1] dy = [-1, 1, 0, 0] a = ['L', 'R', 'U', 'D'] for plan in data: for i in range(len(a)): if plan == a[i]: nx = x + dx[i] ny = y + dy[i] if nx < 1 or ny < 1 or nx > N or ny > N: continue x, y = nx, ny print(nx, ny)
Python
UTF-8
1,620
2.515625
3
[]
no_license
from flask import Flask, jsonify, request from flask_cors import CORS, cross_origin import pandas as pd from sklearn.preprocessing import OneHotEncoder, StandardScaler from sklearn.compose import make_column_transformer import joblib dataset_path = './50_Startups.csv' model_path = './model.sav' app = Flask(__name__) CORS(app, resources={r'/*': {'origins': '*'}}) @app.route('/') @cross_origin() def index(): return jsonify({'message': 'Welcome to the Shark Prediction Service'}), 200 @app.route('/predict', methods=['POST']) @cross_origin() def predictSalary(): data = request.get_json() if 'R&D Spend' not in data or 'Administration Spend' not in data or 'Marketing Spend' not in data or 'State' not in data: return jsonify({'Error': 'Bad Request'}), 400 else: rd_spend = data.get('R&D Spend') administration_spend = data.get('Administration Spend') marketing_spend = data.get('Marketing Spend') state = data.get('State') loaded_model = joblib.load(model_path) dataset = pd.read_csv(dataset_path) independent_variables = dataset.iloc[:, :-1].values # model input is R&D Spend independent_variables[1,0] = rd_spend onehotencoder = make_column_transformer((StandardScaler(), [0, 1, 2]), (OneHotEncoder(), [3])) independent_variables = onehotencoder.fit_transform(independent_variables) y_pred = loaded_model.predict([[1, independent_variables[1,0]]]) return jsonify({'predicted_startup_annual_profit': y_pred[0]}), 200 if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
C++
UTF-8
1,091
2.515625
3
[]
no_license
#ifndef NETCONNECTDIALOG_H #define NETCONNECTDIALOG_H #include <QLabel> #include <QDialog> #include <QLineEdit> #include <QEventLoop> #include <QPushButton> class inputDialog : public QDialog { Q_OBJECT public: inputDialog(QWidget *parent = nullptr); ~inputDialog(); static inputDialog* getInstance(QWidget *parent = nullptr) { if (!_instance) { _instance = new inputDialog; } return _instance; } void setText(QString yes, QString no, QString text); QString getEditText(){return wordEdit->text();} int exec(); bool isRunning(); void exit(bool result); private: static inputDialog* _instance; QLabel *nameLabel; QLineEdit *wordEdit; QPushButton yBtn; QPushButton nBtn; QEventLoop* m_eventLoop; bool m_chooseResult; protected: void closeEvent(QCloseEvent *); private slots: void slot_onApplicationFocusChanged(QWidget *, QWidget *); void slot_onYesClicked(); void slot_onNoClicked(); }; #endif // NETCONNECTDIALOG_H
C
UTF-8
3,177
2.59375
3
[ "BSD-2-Clause" ]
permissive
/* * This file is part of udisks-glue. * * © 2011 Fernando Tarlá Cardoso Lemos * * Refer to the LICENSE file for licensing information. * */ #include <assert.h> #include <glib.h> #include "property_cache.h" #include "props.h" typedef struct { enum { CACHE_VALUE_TYPE_BOOL, CACHE_VALUE_TYPE_STRING, CACHE_VALUE_TYPE_STRINGV } type; union { int bool_value; gchar *string_value; gchar **stringv_value; } values; } cache_value; struct property_cache_ { GHashTable *entries; }; static cache_value *cache_value_create_bool(int val) { cache_value *value = g_malloc0(sizeof(cache_value)); value->type = CACHE_VALUE_TYPE_BOOL; value->values.bool_value = val; return value; } static cache_value *cache_value_create_string(gchar *val) { cache_value *value = g_malloc0(sizeof(cache_value)); value->type = CACHE_VALUE_TYPE_STRING; value->values.string_value = val; return value; } static cache_value *cache_value_create_stringv(gchar **val) { cache_value *value = g_malloc0(sizeof(cache_value)); value->type = CACHE_VALUE_TYPE_STRING; value->values.stringv_value = val; return value; } static void cache_value_free(cache_value *value) { switch (value->type) { case CACHE_VALUE_TYPE_BOOL: break; case CACHE_VALUE_TYPE_STRING: g_free(value->values.string_value); break; case CACHE_VALUE_TYPE_STRINGV: g_strfreev(value->values.stringv_value); break; default: assert(0); break; } g_free(value); } property_cache *property_cache_create() { property_cache *cache = g_malloc(sizeof(property_cache)); cache->entries = g_hash_table_new_full(&g_str_hash, &g_str_equal, &g_free, (GDestroyNotify)&cache_value_free); return cache; } void property_cache_free(property_cache *cache) { g_hash_table_destroy(cache->entries); g_free(cache); } int get_bool_property_cached(property_cache *cache, DBusGProxy *proxy, const char *name, const char *interface) { cache_value *value = g_hash_table_lookup(cache->entries, name); if (value) return value->values.bool_value; int res = get_bool_property(proxy, name, interface); if (res != BOOL_PROP_ERROR) g_hash_table_insert(cache->entries, g_strdup(name), cache_value_create_bool(res)); return res; } gchar *get_string_property_cached(property_cache *cache, DBusGProxy *proxy, const char *name, const char *interface) { cache_value *value = g_hash_table_lookup(cache->entries, name); if (value) return value->values.string_value; gchar *res = get_string_property(proxy, name, interface); if (res) g_hash_table_insert(cache->entries, g_strdup(name), cache_value_create_string(res)); return res; } gchar **get_stringv_property_cached(property_cache *cache, DBusGProxy *proxy, const char *name, const char *interface) { cache_value *value = g_hash_table_lookup(cache->entries, name); if (value) return value->values.stringv_value; gchar **res = get_stringv_property(proxy, name, interface); if (res) g_hash_table_insert(cache->entries, g_strdup(name), cache_value_create_stringv(res)); return res; }