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
Java
UTF-8
2,591
2.34375
2
[]
no_license
package zhaohad.glpath.multiscreen.obj; import android.content.Context; import android.opengl.GLES30; import zhaohad.glpath.multiscreen.R; import zhaohad.glpath.multiscreen.gl.ShaderProgram; import zhaohad.glpath.multiscreen.gl.VertexBuffer; import zhaohad.glpath.multiscreen.util.ShaderUtils; public class Table { private static final int POSITION_COMPONENT_COUNT = 2; private static final int TEXTURE_COORDINATES_COMPONENT_COUNT = 2; private static final int STRIDE = (POSITION_COMPONENT_COUNT + TEXTURE_COORDINATES_COMPONENT_COUNT) * ShaderUtils.BYTES_PER_FLOAT; private static final float[] VERTEX_DATA = { // Order of coordinates: X, Y, S, T // Triangle Fan 0f, 0f, 0.5f, 0.5f, -0.5f, -0.8f, 0f, 0.9f, 0.5f, -0.8f, 1f, 0.9f, 0.5f, 0.8f, 1f, 0.1f, -0.5f, 0.8f, 0f, 0.1f, -0.5f, -0.8f, 0f, 0.9f }; private VertexBuffer mVertexBuffer; public TableProgram mTableProgram; public Table(Context context) { mVertexBuffer = new VertexBuffer(VERTEX_DATA); mTableProgram = new TableProgram(context, R.raw.texture_vertex_shader, R.raw.texture_fragment_shader); } private void bindData() { mVertexBuffer.setVertexAttrPointer(0, mTableProgram.maPosition, POSITION_COMPONENT_COUNT, STRIDE); mVertexBuffer.setVertexAttrPointer(POSITION_COMPONENT_COUNT, mTableProgram.maTextureCoordinates, TEXTURE_COORDINATES_COMPONENT_COUNT, STRIDE); } public void draw() { mTableProgram.useProgram(); bindData(); GLES30.glDrawArrays(GLES30.GL_TRIANGLE_FAN, 0, 6); } public class TableProgram extends ShaderProgram { private int maPosition; private int maTextureCoordinates; private int muTextureUnit; private int mTextureId; public TableProgram(Context context, int vertexResId, int fragResId) { super(context, vertexResId, fragResId); muTextureUnit = GLES30.glGetUniformLocation(mProgramId, "u_TextureUnit"); maPosition = GLES30.glGetAttribLocation(mProgramId, "a_Position"); maTextureCoordinates = GLES30.glGetAttribLocation(mProgramId, "a_TextureCoordinates"); mTextureId = ShaderUtils.loadTexture(context, R.drawable.air_hockey_surface); // 激活文理单元 GLES30.glActiveTexture(GLES30.GL_TEXTURE0); GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, mTextureId); GLES30.glUniform1i(muTextureUnit, 0); } } }
PHP
UTF-8
2,234
2.796875
3
[]
no_license
<?php namespace netForum\xWeb\Xml\Generated; class GetQuery { /** * @var string $szObjectName */ protected $szObjectName = null; /** * @var string $szColumnList */ protected $szColumnList = null; /** * @var string $szWhereClause */ protected $szWhereClause = null; /** * @var string $szOrderBy */ protected $szOrderBy = null; /** * @param string $szObjectName * @param string $szColumnList * @param string $szWhereClause * @param string $szOrderBy */ public function __construct($szObjectName, $szColumnList, $szWhereClause, $szOrderBy) { $this->szObjectName = $szObjectName; $this->szColumnList = $szColumnList; $this->szWhereClause = $szWhereClause; $this->szOrderBy = $szOrderBy; } /** * @return string */ public function getSzObjectName() { return $this->szObjectName; } /** * @param string $szObjectName * @return \netForum\xWeb\Xml\Generated\GetQuery */ public function setSzObjectName($szObjectName) { $this->szObjectName = $szObjectName; return $this; } /** * @return string */ public function getSzColumnList() { return $this->szColumnList; } /** * @param string $szColumnList * @return \netForum\xWeb\Xml\Generated\GetQuery */ public function setSzColumnList($szColumnList) { $this->szColumnList = $szColumnList; return $this; } /** * @return string */ public function getSzWhereClause() { return $this->szWhereClause; } /** * @param string $szWhereClause * @return \netForum\xWeb\Xml\Generated\GetQuery */ public function setSzWhereClause($szWhereClause) { $this->szWhereClause = $szWhereClause; return $this; } /** * @return string */ public function getSzOrderBy() { return $this->szOrderBy; } /** * @param string $szOrderBy * @return \netForum\xWeb\Xml\Generated\GetQuery */ public function setSzOrderBy($szOrderBy) { $this->szOrderBy = $szOrderBy; return $this; } }
Python
UTF-8
1,899
3.1875
3
[]
no_license
import time import tkinter as tk sudoku = [[],[],[],[],[],[],[],[],[]] backtracks=0 window=tk.Tk() t="" def isValid(row,col,n): for i in range(0,9): if sudoku[row][i]==n: return False for i in range(0,9): if sudoku[i][col]==n: return False sub_row=(row//3)*3 sub_col=(col//3)*3 for i in range(0,3): for j in range(0,3): if sudoku[sub_row+i][sub_col+j]==n: return False return True def makeSudoku(): matrix = input("Enter the puzzle: \n") #sudoku = [[],[],[],[],[],[],[],[],[]] for i in range(0,81): if i<9: sudoku[0].append(int(matrix[i])) elif i<18: sudoku[1].append(int(matrix[i])) elif i<27: sudoku[2].append(int(matrix[i])) elif i<36: sudoku[3].append(int(matrix[i])) elif i<45: sudoku[4].append(int(matrix[i])) elif i<54: sudoku[5].append(int(matrix[i])) elif i<63: sudoku[6].append(int(matrix[i])) elif i<72: sudoku[7].append(int(matrix[i])) elif i<81: sudoku[8].append(int(matrix[i])) print("\nGiven puzzle:-") for i in sudoku: print(i) def solve(): for x in range(9): for y in range(9): if sudoku[x][y]==0: for i in range(1,10): if isValid(x,y,i): sudoku[x][y]=i solve() sudoku[x][y]=0 return for i in sudoku: print(i) def main(): makeSudoku() print("\nSolution:-") t1 = time.time() solve() t2 = time.time() print("\ntime taken - ", round(t2 - t1, 2), "s\n") if __name__ == "__main__": while True: main() t = "" sudoku = [[], [], [], [], [], [], [], [], []]
Java
UTF-8
2,606
3.59375
4
[]
no_license
package butte.emily.casinoproject; import java.util.ArrayList; /** * Created by emilybutte on 10/12/16. */ public class Hand { ArrayList<Card> currentHand = new ArrayList<>(); public void clear() { currentHand.clear(); } public void addCard(Card card) { if(card == null) { throw new NullPointerException("Card can't be added to currentHand."); } currentHand.add(card); } public void removeCard(Card card) { currentHand.remove(card); } public void removeCard(int position) { if(position < 0 || position >= currentHand.size()) { throw new IllegalArgumentException("Position does not exist in currentHand:" + position); } currentHand.remove(position); } public int getCardCount() { return currentHand.size(); } public Card getCard(int position) { if(position < 0 || position >= currentHand.size()) { throw new IllegalArgumentException("Position does not exist in hand:" + position); } return currentHand.get(position); } public ArrayList<Card> sortBySuit() { ArrayList<Card> newHand = new ArrayList<Card>(); while (currentHand.size() > 0) { int position = 0; // Position of minimal card. Card card = currentHand.get(0); // Minimal card. for (int i = 1; i < currentHand.size(); i++) { Card c1 = currentHand.get(i); if (c1.getSuit() < card.getSuit() || (c1.getSuit() == card.getSuit() && c1.getValue() < card.getValue()) ) { position = i; card = c1; } } currentHand.remove(position); newHand.add(card); } currentHand = newHand; return newHand; } public ArrayList sortByValue() { ArrayList<Card> newHand = new ArrayList<Card>(); while (currentHand.size() > 0) { int position = 0; // Position of minimal card. Card card = currentHand.get(0); // Minimal card. for (int i = 1; i < currentHand.size(); i++) { Card c1 = currentHand.get(i); if ( c1.getValue() < card.getValue() || (c1.getValue() == card.getValue() && c1.getSuit() < card.getSuit()) ) { position = i; card = c1; } } currentHand.remove(position); newHand.add(card); } currentHand = newHand; return newHand; } }
C++
GB18030
795
3.046875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int num[100005]; int ex[100005]; int main(int argc, char *argv[]) { int index = 0; int a, b; bool flag = false;//Ƿг while(scanf("%d %d", &a, &b) != EOF) { index++; num[index] = a * b;//󵼺ϵ if(b != 0) { ex[index] = b - 1;//󵼺ָ-1 } else { ex[index] = 0;//ָ flag = true; break; } } if(flag)//޸±꣬󵼺0 { index--; } if(index) { for(int i = 1; i <= index; i++)//뵽indexΪֹ { printf("%d %d", num[i], ex[i]); if(i < index) { printf(" "); } } } else//󵼺index == 0޷д { printf("0 0"); } return 0; }
TypeScript
UTF-8
1,969
2.84375
3
[]
no_license
import moment from 'moment'; import { IssueType } from 'types/Issue'; export function TimeFromNow(date: Date): string { return moment(date).fromNow(); } export function IssueColor(type: IssueType): string { switch (type) { case IssueType.ISSUE: return '#28a745'; case IssueType.PR: return '#6f42c1'; } } export function LanguageColor(type: string): string { switch (type) { case 'Python': return '#3572A5'; case 'JavaScript': return '#f1e05a'; case 'C++': return '#f34b7d'; case 'HTML': return '#e34c26'; case 'CSS': return '#563d7c'; case 'Go': return '#00ADD8'; case 'Solidity': return '#AA6746'; case 'Clojure': return '#db5855'; case 'Haskell': return '#5e5086'; case 'Java': return '#b07219'; case 'Kotlin': return '#f18e33'; case 'Nim': return '#37775b'; case 'PHP': return '#4F5D95'; case 'Ruby': return '#701516'; case 'Scala': return '#c22d40'; case 'TypeScript': return '#2b7489'; case 'Shell': return '#89e051'; case 'Elixir': return '#6e4a7e'; case 'Rust': return '#dea584'; case 'Swift': return '#ffac45'; case 'Objective-C': return '#438eff'; case 'C': return '#555555'; case 'C#': return '#178600'; case 'PowerShell': return '#012456'; case 'YAML': return '#cb171e'; case 'Vue': return '#2c3e50'; } return '#ccc'; } export function ShortenAddress(address: string, substring: number = 5): string { if (!address) return ''; const begin = address.substring(0, substring + 2); const end = address.substring(address.length - substring, address.length); const formatted = `${begin}...${end}`; return formatted; } export function Percentage(share: number, total: number, precision: number = 2) { return ((share / total) * 100).toFixed(precision); }
C
UTF-8
757
3.46875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #define TAILLE 10 int rechercheDico(int *tab, int debut, int fin, int valeur){ int milieu = (debut + fin) / 2; printf("milieu = %d \n", milieu); if(debut == milieu){ if(tab[debut] == valeur) return milieu; else return -1; } if(valeur <= tab[milieu]){ rechercheDico(tab, debut, milieu, valeur); //printf("debut = %d \n milieu = %d", debut, milieu); } else rechercheDico(tab, milieu+1, fin, valeur); //printf("fin = %d \n milieu = %d", fin, milieu); } int main(void){ int tab[TAILLE] = { 1 , 3 , 6 , 9 , 10 , 15 , 16, 23, 25, 30}; int resultat; resultat = rechercheDico(tab, 0, TAILLE, 15); printf("resultat = %d \n", resultat); return 0; }
Markdown
UTF-8
799
2.921875
3
[]
no_license
# LetsTryInfix this branch describe about how to use infix function in kotlin # what is infix? infix merupakan salah satu spesial method yang disediakan pada bahasa pemrograman kotlin cara pembuatan method infix cukup mudah hanya buat seperti berikut : infix fun TipeObject.namaMethod(parameternyaApa){<br/> //do something here<br/> }<br/> jika memerlukan nilai balik maka akan seperti berikut : infix fun TipeObject.namaMethod(parameternyaApa) : NilaiBaliknyaApa{<br/> //do somethin here<br/> jangan lupa di return<br/> } dan saat penggunaannya hanya seperti berikut ini : <b>TipeObject namaMethod parameternyaApa</b><br/> contoh yang ada pada branch ini adalah : <br/> * method infix untuk memunculkan toast * method infix untuk intent * method infix untuk melakukan penambahan
Shell
UTF-8
989
2.90625
3
[]
no_license
#!/bin/sh FSLDIR=/opt/ni_tools/fsl . /opt/ni_tools/fsl/etc/fslconf/fsl.sh PATH=$FSLDIR/bin:$PATH export FSLDIR PATH #location of subject data DATA_ROOT=/Volumes/Phillips/P5/subj FEAT_TEMPLATE_PATH=/Volumes/Phillips/P5/scripts/design/template_L1_WM_delay_PPI_R1.fsf #your seed ROI reg="RBA40" ID="11358_20150129" #11363_20150310" #11359_20150203 11360_20150129 0" #"11333_20141017" #not run yet (run1 or run2) # for i in ${ID} do #go to designs directory cd /Volumes/Phillips/P5/scripts/design #replace original ID with the ID you want sed -e "s/10843_20151015/${i}/g" $FEAT_TEMPLATE_PATH > ${i}_L1_WM_delay_${reg}_PPI_R1.fsf #run analysis run 1 feat ${i}_L1_WM_delay_${reg}_PPI_R1.fsf #replace run 1 with run 2 sed -e "s/run1/run2/g" -e "s/wm1/wm2/g" -e "s/_1_5/_2_5/g" -e "s/workingmemory_1/workingmemory_2/g" ${i}_L1_WM_delay_${reg}_PPI_R1.fsf > ${i}_L1_WM_delay_${reg}_PPI_R2.fsf #run analysis run 2 feat ${i}_L1_WM_delay_${reg}_PPI_R2.fsf done
Java
UTF-8
2,621
1.945313
2
[]
no_license
package com.iesvirgendelcarmen.dam.peliculasapp; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import adaptador.ListaPeliculas; import detalle.DetallePeliculas; import modelos.Pelicula; import modelos.api.PeliculasAPI; /** * Created by matinal on 13/06/2018. */ public class Formulario extends AppCompatActivity { TextView tvnombre,tvdirector,tvgenero,tvsinopsis,tvid; EditText etnombre,etdirector,etgenero,etsinopsis,etid; Button botonAnnadir,irLista; private Pelicula pelicula; private List<Pelicula> listaPeliculas=new ArrayList<Pelicula>(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.formulario_peliculas); tvid=(TextView)findViewById(R.id.tvid); tvnombre=(TextView)findViewById(R.id.tvnombre); tvdirector=(TextView)findViewById(R.id.tvdirector); tvgenero=(TextView)findViewById(R.id.tvgenero); tvsinopsis=(TextView)findViewById(R.id.tvsinopsis); etid=(EditText) findViewById(R.id.etid); etnombre=(EditText) findViewById(R.id.etnombre); etdirector=(EditText) findViewById(R.id.etdirector); etgenero=(EditText) findViewById(R.id.etgenero); etsinopsis=(EditText) findViewById(R.id.etsinopsis); botonAnnadir=(Button)findViewById(R.id.botonAnnadir); irLista=(Button)findViewById(R.id.irLista); botonAnnadir.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addPelicula(); } }); irLista.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(getApplication(),MainActivity.class); startActivity(intent); } }); } private void addPelicula() { Pelicula pelicula = new Pelicula(Long.parseLong(etid.getText().toString()),etnombre.getText().toString(), etdirector.getText().toString(), etgenero.getText().toString(), etsinopsis.getText().toString()); PeliculasAPI api = new PeliculasAPI(); api.postPeliculas(pelicula, this); } }
Python
UTF-8
1,450
3.828125
4
[]
no_license
#String nama_depan = 'Arie' nama_belakang = 'Rafli' nama = nama_depan + " " + nama_belakang umur = 21 hobi = 'Lari' print('Biodata:\n', nama, "\n", umur, "\n", hobi) #Integer panjang = 10 lebar = 20 luas = panjang + lebar print(luas) #Booleran nama = 'shift' usia = 22 suda_menikah = False print('nama: ', nama) print('usia: ', usia) print('sudah menikah: ', suda_menikah) a, b, c = 100, "ASHIAP", 20 print('a: ',a) print('b: ',b) print('c: ',c) #Integer panjang = 10 lebar = 20 luas = panjang*lebar print(panjang, '*', lebar, "=", luas) print("Tipe data luas:", type(luas)) #Complex a1 = 20 + 14j b1 = 5 + 53j ab = a1+b1 print(ab) print('Type data ab:', type(ab)) #List List = ['Arie', 'Rafli', 'Katami'] print(List[1]) print(List[-1]) List[2] = "Kasep" print(List) List2 = [['Arie'], ['Rafli']] print(List2) #Tuple ini_variable = ('Arie', 'Rafli', 'Katami') print(ini_variable) contoh = tuple('Arie') print(contoh) tuple1 = (0,1,2,3,4) tuple2 = ("Saya", "Bahagia") tuple3 = (tuple1, tuple2) print(tuple3) #Slicing #L[start:stop:step] L = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] print(L[:10:-2]) L[1:9] = ['a', 'b', 'c', 'd'] print(L) x = [5, 6, 1, 4, 7, 3, 4, 4, 0, 9] x.sort() print(x) x.append(10) print(x) x.insert(2, [10,5]) print(x) del(x[3:4]) print(x) x.pop(1) print(x) x.remove([10,5]) print('ini adalah x terakhir:',x)
Python
UTF-8
175
3.28125
3
[]
no_license
n = int(input()) al = list(map(int, input().split())) cnt = 0 for i in range(n): tmp = al[i] if al[tmp-1] == i+1: cnt += 1 else: pass print(cnt//2)
Markdown
UTF-8
858
3.15625
3
[]
no_license
# Rework - Jason Fried ## Ignore the real world **_That would never work in the real world.” You hear it all the time when you tell people about a fresh idea._** "The real world isn’t a place, it’s an excuse. It’s a justification for not trying. It has nothing to do with you." ## Learn from mistakes is overrated **_Failure is not a prerequisite for success_** “You need to learn from your mistakes. What do you really learn from mistakes? You might learn what not to do again, but how valuable is that? You still don’t know what you should do next.” ## Planning is guessing **_Why don’t we just call plans what they really are: guesses_** "Start referring to your business plans as business guesses, your financial plans as financial guesses, and your strategic plans as strategic guesses. Now you can stop worrying about them as much"
C++
UTF-8
270
2.734375
3
[]
no_license
#include <iostream> class Point { private: int x; int y; public: Point(int pos_x, int pos_y); }; class Geometry { private: Point* point_array[100]; public: Geometry(Point **point_list); Geometry(); void AddPoint(const Point &point); void PrintDistance(); }
JavaScript
UTF-8
886
2.984375
3
[ "MIT" ]
permissive
function print(mat) { let { a, b, c, d } = mat console.log(` a: ${a.toFixed(2)} b: ${b.toFixed(2)} c: ${c.toFixed(2)} d: ${d.toFixed(2)} `) } function moveit() { let { cx: x0, cy: y0 } = or.rbox(svg) let { cx: x1, cy: y1 } = b1.rbox(svg) let { cx: x2, cy: y2 } = b2.rbox(svg) let m = new SVG.Matrix( (x1 - x0) / 50, (y1 - y0) / 50, (x2 - x0) / 50, (y2 - y0) / 50, x0, y0 ) let com = m.decompose() let g = new SVG.Matrix().compose(com) // Transform both of the items target.transform(m) mover.transform(g) console.log(com) print(m) print(g) } // Declare the two points let svg = SVG('svg') var or = SVG('#or').draggable(moveit) var b1 = SVG('#b1').draggable(moveit) var b2 = SVG('#b2').draggable(moveit) // Declare the squares let target = SVG('#true') let mover = SVG('#guess') let tester = SVG('#tester')
Java
UTF-8
881
2.078125
2
[ "Apache-2.0" ]
permissive
package com.eoi.marayarn; import com.eoi.marayarn.http.HandlerFactory; public interface ApplicationMasterPlugin { /** * name of plugin */ String name(); /** * return HandlerFactory for http handler * @return */ HandlerFactory handlerFactory(); /** * return an executor hook if need to inject the execution process of container * @return */ ExecutorHook getExecutorHook(); /** * dashboardId of grafana, GRAFANA_BASE_URL must be set as am's environment * @return */ default String grafanaDashboardId() { return null; } /** * start used to initialize plugin when application master, and will be called before any other * @param applicationMaster */ void start(MaraApplicationMaster applicationMaster); /** * stop plugin */ void stop(); }
Java
UTF-8
2,647
2.1875
2
[]
no_license
package com.example.springboot_quartz.testcase; import com.example.springboot_quartz.base.CaseBase; import com.example.springboot_quartz.model.po.MailPo; import com.example.springboot_quartz.resp.Result; import com.example.springboot_quartz.service.MailService; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.apache.http.client.HttpClient; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.File; import java.io.IOException; import java.util.Arrays; /** * created by ${user} on 2019/9/16 */ @Slf4j public class TestCase extends CaseBase implements Job { @Autowired RestTemplate restTemplate; @Autowired HttpClient httpClient; @Autowired MailService mailService; @Test public void test(){ /*ObjectMapper objectMapper = new ObjectMapper(); MailPo mailPo = null; try { mailPo = objectMapper.readValue(mailPoString, MailPo.class); } catch (IOException e) { e.printStackTrace(); } log.info("test==========================="); HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); requestHeaders.setContentType(MediaType.APPLICATION_JSON); HttpEntity<MailPo> httpEntity = new HttpEntity<>(mailPo,requestHeaders); String url = "http://localhost:8081/mail/sendSimple"; */ // ResponseEntity<String> resultResponseEntity = restTemplate.postForEntity(url, httpEntity, String.class); mailService.sendMailByJavaMail("测试",System.getProperty("user.dir")+ File.separator+"test-output"+File.separator+"html"+File.separator+"index.html"); // log.info(resultResponseEntity.getBody()); } @DataProvider(name = "data") public Object[][] dataProvider(){ //数据读取excel或者数据库 Object[][] mailString = {{"{\n" + " \"content\": \"测试\",\n" + " \"subject\": " + "}"}}; return mailString; } // public static void main(String[] args) { // log.info(System.getProperty("user.dir")+ File.separator+"test-output"+File.separator+"html"+"index.html"); // } @Override public void execute(JobExecutionContext context) throws JobExecutionException { } }
Java
UTF-8
2,225
2.6875
3
[]
no_license
package org.daisy.pipeline.job.impl.fuzzy; import org.daisy.common.fuzzy.InferenceEngine; import org.daisy.common.priority.PrioritizableRunnable; import org.daisy.common.priority.PriorityCalculator; import com.google.common.base.Supplier; import com.google.common.primitives.Doubles; /** * Computes its final priority from a set of priorities and * the time spent in the execution queue. This computation is calculated * using a fuzzy {@link InferenceEngine}. * */ public class FuzzyPriorityCalculator<T> implements PriorityCalculator<T>{ /** * Inference engine used to compute the final priority */ private final InferenceEngine inferenceEngine; /** * score given by the engine for the current runnable status */ private double score; private Supplier<double[]> crispsSupplier; private Supplier<T> prioritySourceSupplier; /** * @param inferenceEngine */ public FuzzyPriorityCalculator(InferenceEngine inferenceEngine, Supplier<double[]> crispsSupplier,Supplier<T> prioritySourceSupplier) { this.inferenceEngine = inferenceEngine; this.crispsSupplier=crispsSupplier; this.prioritySourceSupplier=prioritySourceSupplier; } /** * Returns the score of this FuzzyRunnable computed with InfereneceEngine */ @Override public double getPriority(PrioritizableRunnable<T> runnable) { //Lazy score calcualtion and caching if(runnable.isDirty()){ double[] crispValues=Doubles.concat(new double[]{runnable.getRelativeWaitingTime()},this.crispsSupplier.get()); this.score=-1*this.inferenceEngine.getScore(crispValues); runnable.markDirty(false); } return this.score; } /** * @return the crispsSupplier */ public Supplier<double[]> getCrispsSupplier() { return crispsSupplier; } @Override public T prioritySource() { return this.prioritySourceSupplier.get(); } }
Java
UTF-8
2,381
2.53125
3
[]
no_license
package iiAplication; import mario.order.OrderParser; import mario.xml.XMLParser; /*** * */ public class Tests extends Thread { private static final String LINES = "\n ---------------------------"; private static final String SUCCESS="() test successful!"; public Tests() { xmlTest(); /* try { UDPTest(); } catch (SocketException e) { e.printStackTrace(); } /* try { databaseTest(); } catch (SQLException e) { e.printStackTrace(); }*/ // requestStoresTest(); } private static void xmlTest() { System.out.println("Starting XML Test"); OrderParser order1 = new OrderParser("XMLFiles//command1.xml"); order1.printAll(); OrderParser order2 = new OrderParser("XMLFiles//command2.xml"); order2.printAll(); OrderParser order3 = new OrderParser("XMLFiles//command3.xml"); order3.printAll(); XMLParser test3 = new XMLParser("XMLFiles//command4.xml"); OrderParser order4 = new OrderParser("XMLFiles//command4.xml"); order4.printAll(); System.out.println(LINES); XMLParser test4 = new XMLParser("XMLFiles//command5.xml"); OrderParser order5 = new OrderParser("XMLFiles//command5.xml"); order5.printAll(); System.out.println(LINES); System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName()+SUCCESS); } /* public void UDPTest() throws SocketException { System.out.println("Starting mario.UDP test"); UDPHandler a=new UDPHandler(54321); a.start(); } public void databaseTest() throws SQLException{ System.out.println("Starting DB Test"); Database database = new Database(); database.query("SELECT * from \"II\".armazem"); database.closeConnection(); System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName()+SUCCESS); System.out.println(LINES); } public void requestStoresTest(){ Storage storage=new Storage(); storage.setQuantity("p9",2); storage.setQuantity("P3",5); storage.setQuantity("p5",90); String stores= storage.requestStores(); System.out.println(stores); UDPSend.sendUDP(stores,54321); } */ }
Java
UTF-8
1,090
2.65625
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 Servlets.AdminServlets; import AdminModule.Admin; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Talha Iqbal */ public class DeleteProductServlet extends HttpServlet { @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ res.setContentType("text/html"); Admin admin = (Admin) req.getSession().getAttribute("admin"); if(admin.deleteProduct(Integer.parseInt(req.getParameter("productId")))){ res.getWriter().print("Product deleted successfully!"); } else{ res.getWriter().print("An error occured while deleting the item"); } } }
C
UTF-8
3,679
3.3125
3
[ "BSD-2-Clause" ]
permissive
/* _test_memory2.c: test the correctness of upc_global_alloc function. Date created : September 19, 2002 Date modified : November 4, 2002 Function tested: upc_global_alloc Description: - Test the correctness of upc_global_alloc(). There are 2 parts in this test case. - 1st part: - All threads will perform global memory allocation, initialization, simultaneously. - Thread 0 performs error checking at end. - 2nd part: - Each thread initializes the elements in array b with value of the array a of its neighbour (MYTHREAD + 1). - Thread 0 performs error checking at end. - Thread 0 determines the success of this test case. Platform Tested No. Proc Date Tested Success UPC0 4 September 19, 2002 Yes UPC0 (all types) 4 October 29, 2002 Yes UPC0 (all types) 4 November 5, 2002 Yes CSE0 (all - D) 2,4,8,16 November 11, 2002 Partial CSE0 (double) 2,4,8,16 November 17, 2002 Yes LION (all types) 2,4,8,16,32 November 22, 2002 No UPC0 (all types) 2 December 3, 2002 Yes Bugs Found: [FIXED] [11/11/2002] Test case failed for DTYPE=double, n=16, S=16. [11/22/2002] On lionel, test case failed for DTYPE=all, n=2,4,8,16,32, S=16. MPI process rank 0 (n0, p4752) caught a SIGSEGV */ #include <upc.h> #include <stdio.h> //#define VERBOSE0 #define DTYPE int #define SIZE 16000 shared DTYPE * shared a[THREADS]; shared DTYPE * shared b[THREADS]; int main (void) { int i, j; int error1=0, error2=0, error=0; /* Allocate memory using global memory allocation */ a[MYTHREAD] = upc_global_alloc(SIZE, sizeof(DTYPE)); b[MYTHREAD] = upc_global_alloc(SIZE, sizeof(DTYPE)); /* Each thread initializes it's own array */ for (i = 0; i < SIZE; i++) { a[MYTHREAD][i] = (DTYPE)((DTYPE)(i) + (DTYPE)(MYTHREAD)); } #ifdef VERBOSE0 for (j =0; j < THREADS; j++) { if (MYTHREAD == j) for (i = 0; i < SIZE; i++) printf("<%d>[aff %d] a[%d][%d] = %d\n", MYTHREAD, upc_threadof(&a[j][i]), j, i, a[j][i]); upc_barrier; } #endif upc_barrier; if (MYTHREAD == 0) { for (j = 0; j < THREADS; j++) for (i = 0; i < SIZE; i++) if (a[j][i] != (DTYPE)((DTYPE)(i) + (DTYPE)(j))) error1 = 1; #ifdef VERBOSE0 if (error1) printf("Error: test_memory2.c (pt 1) failed! [th=%d, error1=%d]\n", THREADS, error1); else printf("Success: test_memory2.c (pt 1) passed! [th=%d, error1=%d]\n", THREADS, error1); #endif } upc_barrier; for(i = 0; i < SIZE; i++) { b[MYTHREAD][i] = a[(MYTHREAD+1)%THREADS][i]; } #ifdef VERBOSE_1 for (j =0; j < THREADS; j++) { if (MYTHREAD == j) for (i = 0; i < SIZE; i++) printf("<%d>[aff %d] b[%d][%d] = %d\n", MYTHREAD, upc_threadof(&b[j][i]), j, i, b[j][i]); upc_barrier; } #endif upc_barrier; if (MYTHREAD == 0) { for (j = 0; j < THREADS; j++) for (i = 0; i < SIZE; i++) if (b[j][i] != (DTYPE)((DTYPE)(i) + (DTYPE)((j + 1) % THREADS))) error2 = 1; #ifdef VERBOSE0 if (error2) printf("Error: test_memory2.c (pt 2) failed! [th=%d, error2=%d]\n", THREADS, error2); else printf("Success: test_memory2.c (pt 2) passed! [th=%d, error2=%d]\n", THREADS, error2); #endif error = error1 + error2; if (error) printf("Error: test_memory2.c failed! [th=%d, error=%d, DATA]\n", THREADS, error); else printf("Success: test_memory2.c passed! [th=%d, error=%d, DATA]\n", THREADS, error); } return (error); }
Java
UTF-8
2,559
2.15625
2
[]
no_license
package com.quadriyanney.aacc; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class DevelopersList extends AppCompatActivity { String json_string; JSONObject jsonObject; JSONArray jsonArray; DevAdapter devAdapter; ListView listView; Toolbar toolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.developers_list); listView = (ListView) findViewById(R.id.dev_list); toolbar = (Toolbar) findViewById(R.id.toolBar); setSupportActionBar(toolbar); toolbar.setTitle("Developers List"); devAdapter = new DevAdapter(this, R.layout.list_layout); listView.setAdapter(devAdapter); json_string = getIntent().getExtras().getString("json_data"); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { DeveloperInfo developerInfo = (DeveloperInfo) devAdapter.getItem(i); Intent intent = new Intent(DevelopersList.this, ProfileDisplay.class); assert developerInfo != null; intent.putExtra("username", developerInfo.getUsername()); intent.putExtra("url", developerInfo.getGit_url()); intent.putExtra("photo", developerInfo.getUser_photo()); startActivity(intent); } }); try { jsonObject = new JSONObject(json_string); jsonArray = jsonObject.getJSONArray("items"); int counter = 0; String username, user_photo, git_url; while (counter < jsonArray.length()){ JSONObject json = jsonArray.getJSONObject(counter); username = json.getString("login"); user_photo = json.getString("avatar_url"); git_url = json.getString("html_url"); DeveloperInfo info = new DeveloperInfo(username, user_photo, git_url); devAdapter.add(info); counter++; } } catch (JSONException e) { e.printStackTrace(); } } }
Java
UTF-8
1,959
2.25
2
[ "Apache-2.0" ]
permissive
package org.sagebionetworks.repo.model.dbo.dao.table; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.Date; import org.junit.jupiter.api.Test; import org.sagebionetworks.repo.model.dbo.persistence.table.DBOTableRowChange; import org.sagebionetworks.repo.model.table.TableChangeType; import org.sagebionetworks.repo.model.table.TableRowChange; /** * * @author jmhill * */ public class TableRowChangeUtilsTest { @Test public void testDTOandDBORoundTrip(){ TableRowChange dto = new TableRowChange(); dto.setId(123L); dto.setTableId("syn123"); dto.setRowVersion(12l); dto.setCreatedBy("456"); dto.setCreatedOn(new Date(101)); dto.setBucket("bucket"); dto.setKeyNew("newKey"); dto.setEtag("someEtag"); dto.setRowCount(999L); dto.setChangeType(TableChangeType.ROW); dto.setTransactionId(222L); dto.setHasFileRefs(false); // To DBO DBOTableRowChange dbo = TableRowChangeUtils.createDBOFromDTO(dto); assertNotNull(dbo); // Create a clone TableRowChange clone = TableRowChangeUtils.ceateDTOFromDBO(dbo); assertNotNull(clone); assertEquals(dto, clone); } @Test public void testDTOandDBORoundTripOptionalFields(){ TableRowChange dto = new TableRowChange(); dto.setId(123L); dto.setTableId("syn123"); dto.setRowVersion(12l); dto.setCreatedBy("456"); dto.setCreatedOn(new Date(101)); dto.setBucket("bucket"); dto.setKeyNew("newKey"); dto.setEtag("someEtag"); dto.setRowCount(999L); dto.setChangeType(TableChangeType.ROW); dto.setTransactionId(null); dto.setHasFileRefs(false); // To DBO DBOTableRowChange dbo = TableRowChangeUtils.createDBOFromDTO(dto); assertNotNull(dbo); // Create a clone TableRowChange clone = TableRowChangeUtils.ceateDTOFromDBO(dbo); assertNotNull(clone); assertEquals(dto, clone); } }
C
SHIFT_JIS
492
3.09375
3
[]
no_license
#include <stdio.h> void func1(); void func2(); // GLOBAL int data = 128; int main () { func1(); func2(); func2(); return 0; } void func1() { // [Jϐi֐̂ݗLj // sɏ auto int a = 1; printf("global %d local %d\n", data, a); } void func2() { // [Jϐi֐̂ݗLj // slێ static int b = 1; printf("global %d local %d\n", data, b); b++; }
Java
UTF-8
1,621
2.671875
3
[]
no_license
package com.database; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Program { private static Connection conn; private static String url = "jdbc:mysql://localhost:3306/data"; private static String user = "duxcms"; private static String password = "szpdOwRBK5g3"; private static String driver = "com.mysql.jdbc.Driver"; static { try { conn = DriverManager.getConnection(url,user,password); } catch (SQLException e) { e.printStackTrace(); } } public static void main(String[] args) throws UnsupportedEncodingException { try { Statement statement1,statement2 = null; ResultSet resultSet1,resultSet2 = null; statement1 = conn.createStatement(); statement2 = conn.createStatement(); resultSet1 = statement1.executeQuery("select * from quyu"); while(resultSet1.next()) { int id = resultSet1.getInt("id"); String name = resultSet1.getString("name").replace("省", "").replace("市", "").replace("区", "").replace("县", ""); int parent_id = resultSet1.getInt("parent_id"); String summary = resultSet1.getString("summary"); int level = resultSet1.getInt("level"); String insert = "insert into diming (id,name,parent_id,summary,level) values (" + id + ",'" + name + "'," + parent_id + ",'" + summary + "'," + level + ")"; statement2.execute(insert); System.out.println(insert); } } catch (SQLException e) { e.printStackTrace(); } } }
Go
UTF-8
148
3.296875
3
[]
no_license
package main import "fmt" func setSum(a, b int, c *int) { *c = a + b } func main() { var otvet int setSum(3, 4, &otvet) fmt.Println(otvet) }
C++
UTF-8
2,183
3
3
[]
no_license
#pragma once #include "CEntity.h" #include <fstream> #include <string> #include <list> #include <memory> #include <ctime> /** * @class CGameSaver * @brief CGameSaver saves entities to specified file and appends save index file * CGameSaver is ready to save tower (available) and enemies. Currently saving of enemies is not used. * (Because there is no way to save game during game phase). */ class CGameSaver { public: /** * @param[in] m_entities list of entities to be saved * @param[in] mapSize size of gameplan */ CGameSaver( const std::list< std::shared_ptr< CEntity > > & m_entities , const std::pair< int , int > & mapSize ); /** * @param[in] saveName * @param[in] mapPath * @param[in] HP * @param[in] score * @param[in] money * @brief saves entities to save file with HP, score and money * @return success - FILE_OKAY / else - FILE_ERROR (defined in game_constants.cpp) */ int Save( const std::string & saveName , const std::string & mapPath , int HP , int score , int money ); private: /** * @brief refreshes time (m_actTime) for save reasons */ void RefreshTime(); /** * @param[out] os outputstream (file here) * @brief saves entities */ void SaveEntities( std::ofstream & os ); /** * @param[out] os outputstream (file here) * @param[in] HP player health * @param[in] score player score * @param[in] money player money * @brief saves player's stats */ void SaveSizeAndStats( std::ofstream & os , int HP , int score , int money ); /** * @param[in] saveName name of the save file * @param[in] mapPath map on which was save game played * @brief appends save index file * @return success - FILE_OKAY / else - FILE_ERROR (defined in game_constants.cpp) */ int SaveToIndexer( const std::string & saveName , const std::string & mapPath ); /** list of entities to save */ const std::list< std::shared_ptr< CEntity > > & m_entities; const std::pair< int , int > & m_mapSize; /** time structure from ctime standart library */ std::tm * m_actTime; };
Python
UTF-8
154
3.265625
3
[]
no_license
tuple = [("Jon", 15), ("Ned", 45), ("Arya", 9), ("Catelyn", 44), ("Bran", 10)] for i in range(len(tuple)): if tuple[i][1] > 18: print(tuple[i][0])
Python
UTF-8
1,571
2.65625
3
[]
no_license
import pandas as pd import numpy as np import sklearn.preprocessing from sklearn.preprocessing import MinMaxScaler from sklearn.feature_selection import mutual_info_classif dataset = pd.read_csv('maline_fvt2.csv') #print(dataset.head) X = dataset.iloc[:, 1:105].values y = dataset.iloc[:,0].values #print(X) ##normalize scaler = MinMaxScaler() scaler.fit(X) MinMaxScaler(copy=True, feature_range=(0, 1)) X_normalized = scaler.transform(X) print(X_normalized.shape) ##feature selection(mutual info) scores=mutual_info_classif(X_normalized,y) print(scores) np.savetxt("mutual_info_hello.csv",scores, delimiter=",") ''' ################################## from skfeature.function.statistical_based import gini_index score = gini_index.gini_index(X, y) print(score) np.savetxt("gini_index2.csv",score, delimiter=",") score = gini_index.gini_index(X_normalized, y) print(score) ''' #sel.transform(X) #print(sel.scores_) #np.savetxt("deb.csv", sel.scores_, delimiter=",") ''' ####creating the table l=list(dataset.columns.values) l=l[1:157] score=sel.scores_ df = pd.DataFrame({'system_call': pd.Series(l, dtype=str), 'chi_score': pd.Series(score, dtype=float)}) columnsTitles=['system_call','chi_score'] df=df.reindex(columns=columnsTitles) df['Feature_Rank'] = df['chi_score'].rank(ascending=False) df=df.sort_values(by=['Feature_Rank']) df.to_csv("score4.csv",index=False) #print(sel.scores_) #np.savetxt("foo.csv", sel.scores_, delimiter=",") '''
Markdown
UTF-8
2,117
2.90625
3
[]
no_license
# Check list for QA process - [ ] Introduction To Project - [x] (*nshaver*) Does the document have an introduction? - [x] (*nshaver*) Is it formed corectly and properly described? - [x] (*nshaver*) Does it provide context? [ ] Spelling and Grammar? nshaver: need a comma after study in the intro - [ ] Code Section - [ ] Correctly commented? nshaver: Need to remove the commennt in the .rmd file, line 13, which shows my old working dir; also, the code in line 43 of the .rmd file was intended to be a comment, not active code - [x] (*nshaver*) *modular* style? - [ ] Is the code well written? nshaver: no, clean up code is not the latest rev, and thus it does not correctly remove the unranked rows - [ ] Does it compile in R? nshaver: no, the source statements from the .rmd do not find the correct code. it is looking in the wrong directory for the R code. it also can't write the csv files to the right directory. - [ ] Does it build with make? - [ ] Brief Explanation - [ ] Is it written well? - [ ] Spelling and Grammar? - [ ] Answers - [ ] Are the answers clear? - [x] Are the answers correct? nshaver: Q4 is not complete - [ ] Q5 is not the right version of the answer--cose is wrong and the answer should be 5. - [ ] Q1 is wrong as we need the correct version of cleanup_ED_GDP.R--the right version removes the unranked countries - [ ] Spelling and Grammar? - [ ] Conclusion - [ ] Does it summarize findings from the excercise in paragraph form? nshaver: its not done--it needs to provide a summary of the findings in question 3, 4 and 5 - [ ] Spelling and Grammar? - [ ] GitHub Items - [ ] Is it able to get from GitHub on a virgin machine and build? - [ ] Will it run on a Mac or PC without modifications? - [ ] Readme file nshaver: the current version is not correct, the correct version is in the history, though - [ ] spelling and grammar - [ ] session info captured - [ ] all key columns and units described - [ ] info of how to create the output is correct - [ ] describes project purpose, title, copyright info, folder organization
Markdown
UTF-8
925
3.296875
3
[]
no_license
# SampleFunctionApp Created for Aspire Training to introduce freshers to Azure functions (HTTP and Timer trigger). The solution contains two projects - i. Timer trigger function app: Logs the time this function is called based on the interval set. ii. Http trigger function app: Sample app to add two whole numbers which are given by the user in the query parameters. Feature requirement: Basic calculator application HTTP Method: POST Request Body: { "Num1": 10 "Num2": 20 "Operation": "ADD" } Num1 - int <br /> Num2 - int <br /> Operation - enum with members [ADD, SUB, MUL, DIV] <br /> Response: The {operation} of {num1} and {num2} is: {result} Note: Add validations to avoid incorrect operations like division by zero or an invalid operation input. <br /> Eg of valid operation input: ADD <br /> Eg of invalid operation input: add, addition, sum <br /> Branch syntax for raising a PR: calc/{alias}
C++
UTF-8
386
3
3
[]
no_license
#include <stdio.h> int main () { int marks ; printf("enter the marks:"); scanf("%d",&marks); if(marks>=85) { printf("Grade A"); } else if (marks>=70) { printf ("Grade B"); } else if( marks>=55) { printf("Grade C"); } else if (marks>=40) { printf("Grade D"); } else { printf ("Grade F"); } return 0; }
Java
UTF-8
2,338
2.5
2
[]
no_license
package com.filter; import java.io.IOException; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; import com.opensymphony.xwork2.util.ValueStack; @SuppressWarnings({"rawtypes","unused"}) public class IllegalCharacterInterceptor extends AbstractInterceptor { /** * */ private static final long serialVersionUID = 1L; @Override public String intercept(ActionInvocation invocation) throws Exception { // 通过核心调度器invocation来获得调度的Action上下文 ActionContext actionContext = invocation.getInvocationContext(); // 获取Action上下文的值栈 ValueStack stack = actionContext.getValueStack(); // 获取上下文的请求参数 Map valueTreeMap = actionContext.getParameters(); // 获得请求参数集合的迭代器 Iterator iterator = valueTreeMap.entrySet().iterator(); // 遍历组装请求参数 while (iterator.hasNext()) { // 获得迭代的键值对 Entry entry = (Entry) iterator.next(); // 获得键值对中的键值 String key = (String) entry.getKey(); // 原请求参数,因为有可能一键对多值所以这里用的String[] String[] oldValues = null; // 对参数值转换成String类型的 if (entry.getValue() instanceof String) { oldValues = new String[] { entry.getValue().toString() }; } else { oldValues = (String[]) entry.getValue(); } // 对请求参数过滤处理 if (oldValues.length > 0) { for (int i = 0; i < oldValues.length; i++) { oldValues[i] = FilterIllegalCharacter(oldValues[i] .toString()); } } } String result = null; try { // 调用下一个拦截器,如果拦截器不存在,则执行Action result = invocation.invoke(); } catch (Exception e) { e.printStackTrace(); } return result; } private String FilterIllegalCharacter(String str) throws IOException { // FileReader fr = new FileReader( // OaConstants.ILLEGAL_CHARACTER_FILE_PATH); // BufferedReader br = new BufferedReader(fr); // String line = ""; // while ((line = br.readLine()) != null) { // if (str.contains(line)) { // str = str.replaceAll(line, ""); // } // } return str; } }
Rust
UTF-8
3,106
2.859375
3
[]
no_license
use objc_foundation::NSObject; use super::{AvCaptureDeviceInput, AvCaptureVideoDataOutput}; /// You use an `AVCaptureSession` object to coordinate the flow of data from AV input /// devices to outputs. pub struct AvCaptureSession { obj: *mut NSObject, pub inputs: Vec<AvCaptureDeviceInput>, pub outputs: Vec<AvCaptureVideoDataOutput>, } impl AvCaptureSession { pub fn init() -> AvCaptureSession { use ffi::AVCaptureSession; let obj = unsafe { let obj: *mut NSObject = msg_send![&AVCaptureSession, alloc]; msg_send![obj, init] }; AvCaptureSession { obj, inputs: vec![], outputs: vec![], } } // TODO: pub fn canAddInput<I: AvCaptureInput>(input: I) -> bool /// Returns a Boolean value that indicates whether a given input can be added to the session. pub fn canAddInput(&self, input: &AvCaptureDeviceInput) -> bool { unsafe { msg_send![self.obj, canAddInput:input.obj] } } /// Adds a given input to the session. pub fn addInput(&mut self, input: AvCaptureDeviceInput) { let _: () = unsafe { msg_send![self.obj, addInput:input.obj] }; self.inputs.push(input); } // TODO: pub fn canAddOutput<O: AvCaptureOutput>(output: O) -> bool /// Returns a Boolean value that indicates whether a given output can be added to the session. pub fn canAddOutput(&self, output: &AvCaptureVideoDataOutput) -> bool { unsafe { msg_send![self.obj, canAddOutput:output.obj] } } /// Adds a given output to the session. /// /// # Arguments /// /// * `output` - An output to add to the session. pub fn addOutput(&mut self, output: AvCaptureVideoDataOutput) { let _: () = unsafe { msg_send![self.obj, addOutput:output.obj] }; self.outputs.push(output); } /// Indicates the start of a set of configuration changes to be made atomically. pub fn beginConfiguration(&self) { unsafe { msg_send![self.obj, beginConfiguration] } } /// Commits a set of configuration changes. pub fn commitConfiguration(&self) { unsafe { msg_send![self.obj, commitConfiguration] } } /// Tells the receiver to start running. /// /// This method is used to start the flow of data from the inputs to the outputs connected to /// the `AVCaptureSession` instance that is the receiver. This method is synchronous and blocks /// until the receiver has either completely started running or failed to start running. If /// an error occurs during this process and the receiver fails to start running, you receive /// an `AVCaptureSessionRuntimeError`. pub fn startRunning(&self) { unsafe { msg_send![self.obj, startRunning] } } /// Tells the receiver to stop running. /// /// This method is used to stop the flow of data from the inputs to the outputs connected to /// the `AVCaptureSession` instance that is the receiver. This method is synchronous and /// blocks until the receiver has completely stopped running. pub fn stopRunning(&self) { unsafe { msg_send![self.obj, stopRunning] } } } impl Drop for AvCaptureSession { fn drop(&mut self) { let _: () = unsafe { msg_send![self.obj, release] }; } }
PHP
UTF-8
3,778
2.59375
3
[ "MIT" ]
permissive
<?php namespace App\Libraries\Cells\Service\Business; use App\Libraries\Abstracts\Base\Cell as CellBase; use App\Exceptions\Business\ServiceExceptionCode; use App\Exceptions\Jwt\AuthExceptionCode; use App\Libraries\Instances\Router\Janitor; use App\Entities\Member\Auth as Member; use TokenAuth; use StorageSignature; /** * Final Class AuthCell. * * @package App\Libraries\Cells\Service\Business */ final class AuthCell extends CellBase { /** * Get the validation rules that apply to the arguments input. * * @return array */ protected function rules(): array { return [ 'type' => 'required', 'signature' => 'required|size:72', // Custom validation rules ]; } /** * Execute the cell handle. * * @return array * @throws \Exception */ protected function handle(): array { // You can use getInput function to get the value returned by validation rules // $this->getInput( Rules name ) try { $type = $this->getInput('type'); if (! Janitor::isAllowed(Janitor::getGuestClass($type), 'business')) { throw new ServiceExceptionCode(ServiceExceptionCode::UNAVAILABLE_SERVICE); } $signature = $this->getInput('signature'); if (($data = StorageSignature::get($signature)) && isset($data['mark'], $data['type'], $data['business'], $data['inviter_model'], $data['inviter_id'], $data['model'], $data['id']) && $data['mark'] === 'Business' && $data['type'] === 'login' && $data['business'] === $type) { StorageSignature::forget($signature); $janitorData = Janitor::getGuestData($type); $inviteable = (isset($janitorData['available_invite']) ? $janitorData['available_invite'] : false); if ($inviteable) { if (isset($data['inviter_model'][0]) && (! TokenAuth::getAuthGuard($data['inviter_model']) || $data['inviter_model'] !== Member::class)) { throw new ServiceExceptionCode(ServiceExceptionCode::INVITER_TYPE_NOT_SUPPORT); } if (isset($data['inviter_model'][0]) && !($inviter = app($data['inviter_model'])->find($data['inviter_id']))) { throw new ServiceExceptionCode(ServiceExceptionCode::INVALID_INVITER); } } if (! TokenAuth::getAuthGuard($data['model']) || $data['model'] !== Member::class) { throw new ServiceExceptionCode(ServiceExceptionCode::USER_TYPE_NOT_SUPPORT); } if (! $user = app($data['model'])->find($data['id'])) { throw new ServiceExceptionCode(ServiceExceptionCode::INVALID_USER); } /* Check auth user status */ $user->verifyHoldStatusOnFail(); /* User auth info */ $source = [ 'uid' => $user->uid, 'nickname' => (isset($user->nickname) ? $user->nickname : '') ]; /* Inviter uid */ if ($inviteable) { $source['inviter_uid'] = (isset($inviter->uid) ? $inviter->uid : ''); } /* Return success message */ return $this->success($source); } throw new ServiceExceptionCode(ServiceExceptionCode::INVALID_SIGNATURE); } catch (\Throwable $e) { /* Return failure message */ // return $this->failure([ // 'message' => $e->getMessage() // ]); /* Throw error */ throw $e; } } }
JavaScript
UTF-8
2,765
2.59375
3
[ "MIT" ]
permissive
/* */ (function(Buffer) { 'use strict'; function objectToString(o) { return Object.prototype.toString.call(o); } var util = { isArray: function(ar) { return Array.isArray(ar) || (typeof ar === 'object' && objectToString(ar) === '[object Array]'); }, isDate: function(d) { return typeof d === 'object' && objectToString(d) === '[object Date]'; }, isRegExp: function(re) { return typeof re === 'object' && objectToString(re) === '[object RegExp]'; }, getRegExpFlags: function(re) { var flags = ''; re.global && (flags += 'g'); re.ignoreCase && (flags += 'i'); re.multiline && (flags += 'm'); return flags; } }; if (typeof module === 'object') module.exports = clone; function clone(parent, circular, depth, prototype) { var allParents = []; var allChildren = []; var useBuffer = typeof Buffer != 'undefined'; if (typeof circular == 'undefined') circular = true; if (typeof depth == 'undefined') depth = Infinity; function _clone(parent, depth) { if (parent === null) return null; if (depth == 0) return parent; var child; var proto; if (typeof parent != 'object') { return parent; } if (util.isArray(parent)) { child = []; } else if (util.isRegExp(parent)) { child = new RegExp(parent.source, util.getRegExpFlags(parent)); if (parent.lastIndex) child.lastIndex = parent.lastIndex; } else if (util.isDate(parent)) { child = new Date(parent.getTime()); } else if (useBuffer && Buffer.isBuffer(parent)) { child = new Buffer(parent.length); parent.copy(child); return child; } else { if (typeof prototype == 'undefined') { proto = Object.getPrototypeOf(parent); child = Object.create(proto); } else { child = Object.create(prototype); proto = prototype; } } if (circular) { var index = allParents.indexOf(parent); if (index != -1) { return allChildren[index]; } allParents.push(parent); allChildren.push(child); } for (var i in parent) { var attrs; if (proto) { attrs = Object.getOwnPropertyDescriptor(proto, i); } if (attrs && attrs.set == null) { continue; } child[i] = _clone(parent[i], depth - 1); } return child; } return _clone(parent, depth); } clone.clonePrototype = function(parent) { if (parent === null) return null; var c = function() {}; c.prototype = parent; return new c(); }; })(require("buffer").Buffer);
JavaScript
UTF-8
1,535
2.59375
3
[]
no_license
service_id = param = window.location.search.substring(1); $.ajax({ url: 'lib/get-store.php', method: 'POST', data: {service_id:service_id}, cache: false, success: function(data){ $('.card-title').text(data[0]['product_title']); $('.price').text('Strating Price $'+data[0]['product_price']); $('.card-text').html(data[0]['product_details']); $('.card-img-top').attr('src', 'img/product-image/'+data[0]['product_image']);; } }); $.ajax({ url: 'lib/get-store.php', method: 'POST', data: {reviews:service_id}, cache: false, success: function(data){ //<p>Lorem</p> <small class="text-muted">Posted</small> <hr> review = ''; for(var i in data) { review += '<p>'+data[i]['review']+'</p> <small class="text-muted">Posted by '+data[i]['name']+' on '+data[i]['date']+'</small> <hr>' } review += '<a href="#leave_review" class="btn btn-success" see="0">Leave a Review</a>'; $('.reviews').html(review); } }); var options = { max_value: 5, step_size: 1, initial_value: 0, update_input_field_name: $("#rating_count"), } $(".rate").rate(options); $(".rate").rate("setFace", 5, '😊'); $(".rate").rate("setFace", 1, '😒'); $(document).on('click', '.btn-success', function(event) { event.preventDefault(); see = $(this).attr('see'); if (see == 0) { $('.leave_reviews').show(); $(this).attr('see', '1'); }else{ $('.leave_reviews').hide(); $(this).attr('see', '0'); } }); $('.submit_review').click(function(event) { $('.err_rev').text('Please Enter a Valid Order Number'); });
Python
UTF-8
365
2.875
3
[ "MIT" ]
permissive
import gym import numpy as np env = gym.make('LunarLander-v2') env.reset() train_steps = int(1e4) reward_per_ep = [] for _ in range(train_steps): _, r, _, _ = env.step(env.action_space.sample()) # take a random action reward_per_ep.append(r) env.close() average_reward_per_ep = np.mean(reward_per_ep) print(f"Average reward: {average_reward_per_ep}")
Java
UTF-8
5,007
1.851563
2
[ "Apache-2.0" ]
permissive
package com.example.creation.admin.restapi; import com.example.creation.admin.annotion.AuthorityVerify.AuthorityVerify; import com.example.creation.admin.annotion.AvoidRepeatableCommit.AvoidRepeatableCommit; import com.example.creation.admin.annotion.OperationLogger.OperationLogger; import com.example.creation.base.exception.ThrowableUtils; import com.example.creation.base.validator.group.Delete; import com.example.creation.base.validator.group.GetList; import com.example.creation.base.validator.group.Insert; import com.example.creation.base.validator.group.Update; import com.example.creation.utils.ResultUtil; import com.example.creation.xo.service.ArticleSortService; import com.example.creation.xo.vo.ArticleSortVO; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.List; /** * @author xmy * @date 2021/3/17 11:44 */ @RestController @RequestMapping("/articleSort") @Api(value = "文章分类相关接口", tags = {"文章分类相关接口"}) @Slf4j public class ArticleSortRestApi { @Resource private ArticleSortService articleSortService; @AuthorityVerify @ApiOperation(value = "获取文章分类列表", notes = "获取文章分类列表", response = String.class) @PostMapping("/getList") public String getList(@Validated({GetList.class}) @RequestBody ArticleSortVO articleSortVO, BindingResult result) { ThrowableUtils.checkParamArgument(result); log.info("获取文章分类列表"); return ResultUtil.successWithData(articleSortService.getPageList(articleSortVO)); } @AvoidRepeatableCommit @AuthorityVerify @OperationLogger(value = "增加文章分类") @ApiOperation(value = "增加文章分类", notes = "增加文章分类", response = String.class) @PostMapping("/add") public String add(@Validated({Insert.class}) @RequestBody ArticleSortVO articleSortVO, BindingResult result) { ThrowableUtils.checkParamArgument(result); log.info("增加文章分类"); return articleSortService.addArticleSort(articleSortVO); } @AuthorityVerify @OperationLogger(value = "编辑文章分类") @ApiOperation(value = "编辑文章分类", notes = "编辑文章分类", response = String.class) @PostMapping("/edit") public String edit(@Validated({Update.class}) @RequestBody ArticleSortVO articleSortVO, BindingResult result) { ThrowableUtils.checkParamArgument(result); log.info("编辑文章分类"); return articleSortService.editBlogSort(articleSortVO); } @AuthorityVerify @OperationLogger(value = "批量删除文章分类") @ApiOperation(value = "批量删除文章分类", notes = "批量删除文章分类", response = String.class) @PostMapping("/deleteBatch") public String delete(@Validated({Delete.class}) @RequestBody List<ArticleSortVO> articleSortVoList, BindingResult result) { ThrowableUtils.checkParamArgument(result); log.info("批量删除文章分类"); return articleSortService.deleteBatchBlogSort(articleSortVoList); } @AuthorityVerify @ApiOperation(value = "置顶分类", notes = "置顶分类", response = String.class) @PostMapping("/stick") public String stick(@Validated({Delete.class}) @RequestBody ArticleSortVO articleSortVO, BindingResult result) { ThrowableUtils.checkParamArgument(result); log.info("置顶分类"); return articleSortService.stickBlogSort(articleSortVO); } @AuthorityVerify @OperationLogger(value = "通过点击量排序文章分类") @ApiOperation(value = "通过点击量排序文章分类", notes = "通过点击量排序文章分类", response = String.class) @PostMapping("/blogArticleByClickCount") public String blogSortByClickCount() { log.info("通过点击量排序文章分类"); return articleSortService.blogSortByClickCount(); } /** * 通过引用量排序标签 * 引用量就是所有的文章中,有多少使用了该标签,如果使用的越多,该标签的引用量越大,那么排名越靠前 * * @return */ @AuthorityVerify @OperationLogger(value = "通过引用量排序文章分类") @ApiOperation(value = "通过引用量排序文章分类", notes = "通过引用量排序文章分类", response = String.class) @PostMapping("/blogSortByCite") public String blogSortByCite() { log.info("通过引用量排序文章分类"); return articleSortService.blogSortByCite(); } }
Markdown
UTF-8
1,584
3.03125
3
[ "MIT" ]
permissive
# Overview of TRiBot Forum Bumper (TFB) To be ran continuously, will log in to the specified forum account (in data/credentials file), and bump the specified threads. TRiBot has a 4 hour interval between forum bumps. ### Architecture - Language: [Python](https://www.python.org/) - Libraries / Modules: - [cloudflare-scrape](https://github.com/Anorov/cloudflare-scrape) - [pyotp](https://github.com/pyotp/pyotp) - [lxml](http://lxml.de/) - [Requests](http://docs.python-requests.org/en/master/) - [PyExecJS](https://pypi.python.org/pypi/PyExecJS) - [Node.js](https://nodejs.org/en/) ### Basic Logic Flow 1. Startup routine - Load forum credentials from file 2. Main cycle - Load forum threads to bump from file (loaded every cycle in case a change is made between cycles) - Log in to [TRiBot](http://www.tribot.org) forums - Bump each specified thread - Navigate to thread's page - Utilize bump feature - Sleep for specified cycle time (bump interval) ### Deployment 1. Install Python 2. Install cfscrape module 3. Install lxml module 4. Install Requests module 5. Install PyExecJS module 6. Install pyotp module 7. Install Node.js 8. Run! ### Usage 1. Create a file "credentials" in the project/data/ directory with the contents: - tribot username - tribot password - 2fa secret key 2. Create a file "threads" in the project/data/ folder with the link to each thread you want to bump. One thread per line! - http://www.tribot.org/forums/thread_one - http://www.tribot.org/forums/thread_two
Java
UTF-8
423
2.265625
2
[]
no_license
/** * Copyright 2014-2015, NetEase, Inc. All Rights Reserved. * * Date: 2017年5月12日 */ package com.example.demo; /** * Desc:TODO * * @author wei.zw * @since 2017年5月12日 下午8:32:15 * @version v 0.1 */ public class ForASMTestClass { private String name; private String value; public void display1() { System.out.println(name); System.out.println(value); } public void display2() { } }
Python
UTF-8
3,907
2.796875
3
[]
no_license
"""Implementation based on NEAT-Python neat-python/neat/population.py: https://github.com/CodeReclaimers/neat-python/blob/master/neat/population.py""" import neuroevolution.reporting as reporting from neuroevolution.utils import mean class CompleteExtinctionException(Exception): pass class Population: def __init__(self, config, initial_state=None): self.config = config self.reporters = reporting.ReporterSet() stagnation = config.stagnation_type(config.stagnation_config, self.reporters) self.reproduction = config.reproduction_type(config.reproduction_config, self.reporters, stagnation) if config.fitness_criterion == "max": self.fitness_criterion = max elif config.fitness_criterion == "min": self.fitness_criterion = min elif config.fitness_criterion == "mean": self.fitness_criterion = mean elif not config.no_fitness_termination: raise RuntimeError("Unexpected fitness_criterion: {0!r}".format(config.fitness_criterion)) if initial_state is None: self.population = self.reproduction.create_new(config.genome_type, config.genome_config, config.pop_size,) self.species = config.species_set_type(config.species_set_config, self.reporters) self.generation = 0 self.species.speciate(config, self.population, self.generation) else: self.population, self.species, self.generaton = initial_state self.best_genome = None def add_reporter(self, reporter): self.reporters.add(reporter) def remove_reporter(self, reporter): self.reporters.remove(reporter) def run(self, fitness_function, n=None): if self.config.no_fitness_termination and (n is None): raise RuntimeError("Cannot have no generational limit with no fitness termination.") k = 0 while n is None or k < n: k += 1 self.reporters.start_generation(self.generation) fitness_function(list(self.population.items()), self.config) best = None for g in self.population.values(): if g.fitness is None: raise RuntimeError("Fitness not assigned to genome {}".format(g.key)) if best is None or g.fitness > best.fitness: best = g self.reporters.post_evaluate(self.config, self.population, self.species, best) if self.best_genome is None or best.fitness > self.best_genome.fitness: self.best_genome = best if not self.config.no_fitness_termination: fv = self.fitness_criterion(g.fitness for g in self.population.values()) if fv >= self.config.fitness_threshold: self.reporters.found_solution(self.config, self.generation, best) break self.population = self.reproduction.reproduce(self.config, self.species, self.config.pop_size, self.generation) if not self.species.species: self.reporters.complete_extinction() if self.config.reset_on_extinction: self.population = self.reproduction.create_new(self.config.genome_type, self.config.genome_config, self.config.pop_size) else: raise CompleteExtinctionException() self.species.speciate(self.config, self.population, self.generation) self.reporters.end_generation(self.config, self.population, self.species) self.generation += 1 if self.config.no_fitness_termination: self.reporters.found_solution(self.config, self.generation, self.best_genome) return self.best_genome
Java
UTF-8
1,202
2.4375
2
[]
no_license
package monster.resp; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/respDemo05") public class respDemo05 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext servletContext = this.getServletContext(); String realPath = servletContext.getRealPath("/b.txt"); String realPath1 = servletContext.getRealPath("/WEB-INF/c.txt"); String realPath2 = servletContext.getRealPath("/WEB-INF/classes/a.txt"); response.getOutputStream().write((realPath+"\r\n").getBytes()); response.getOutputStream().write((realPath1+"\r\n").getBytes()); response.getOutputStream().write((realPath2+"\r\n").getBytes()); } }
Python
UTF-8
6,455
3.09375
3
[]
no_license
''' 功能:本程序能将target_file_path下的所有的纯数字的图片,通过确定图片号码num_fill_pic来除去人像,但target_file_path目录下 每张纯数字图片必须存在一张纯数字_predict目标分割图片与之对应,如原图为0.jpg,必须存在0_predict.jpg本程序才能正常运行。 ''' import cv2, os import numpy as np import time target_file_path = './result/test/' num_fill_pic = 10 # 用来填充的图片序号0-? image_width = 512 image_height = 512 g_rect = [0, 0, 0, 0] def is_number(s): try: float(s) return True except ValueError: pass try: import unicodedata unicodedata.numeric(s) return True except (TypeError, ValueError): pass def on_mouse(event, x, y, flags, param): # 鼠标点击交互函数 global img1, point1, point2, g_rect img2 = img1.copy() if event == cv2.EVENT_LBUTTONDOWN: # 左键点击,则在原图打点 print("1-EVENT_LBUTTONDOWN") point1 = (x, y) print("point1:", point1) cv2.circle(img2, point1, 8, (0, 255, 0), thickness=2) # cv2.circle(img2, point1, 8(这是圈的半径), (0, 255, 0), thickness=2(这是圈的粗细)) cv2.imshow('image', img2) elif event == cv2.EVENT_MOUSEMOVE and (flags & cv2.EVENT_FLAG_LBUTTON): # 按住左键拖曳,画框 print("2-EVENT_FLAG_LBUTTON") cv2.rectangle(img2, point1, (x, y), (255, 0, 0), thickness=2) cv2.imshow('image', img2) elif event == cv2.EVENT_LBUTTONUP: # 左键释放,显示 print("3-EVENT_LBUTTONUP") point2 = (x, y) cv2.rectangle(img2, point1, point2, (0, 0, 255), thickness=2) cv2.imshow('image', img2) print("point1:{0} point2:{1}".format(point1, point2)) if point1 != point2: min_x = min(point1[0], point2[0]) min_y = min(point1[1], point2[1]) width = abs(point1[0] - point2[0]) height = abs(point1[1] - point2[1]) g_rect = [min_x, min_y, width, height] cut_img1 = img1[min_y:min_y + height, min_x:min_x + width] # cv2.imshow('ROI', cut_img1) # 展示截取的图片 # 读取目录下所有图片,纯数字名字的图片放入images,带有predict字样的图片放入masks def read_pics(): images = np.zeros([1, image_height, image_width, 3], dtype=np.uint8) # 加上这个dtype=np.uint8太重要了,否则图片会显示很模糊,或是无法显示 masks = np.zeros([1, image_height, image_width, 3], dtype=np.uint8) pics = os.listdir(target_file_path) image_names = {} for k in pics: if is_number(k.split('.')[0]): image_names[int(k.split('.')[0])] = k # 为所有纯数字的原图片创建一个字典。 image_names_sorted = {} for i in sorted(image_names): # 将字典按key排序 image_names_sorted[i] = image_names[i] print(image_names_sorted) for k in image_names_sorted: # 读取文件,将原图放入images,目标分割图放入masks # print(k) img = cv2.imread('{0}\\{1}'.format(target_file_path, image_names_sorted[k].replace('.', '_predict.'))) img = img[np.newaxis, :] masks = np.vstack((masks, img)) img = cv2.imread('{0}\\{1}'.format(target_file_path, image_names_sorted[k])) img = img[np.newaxis, :] images = np.vstack((images, img)) masks = masks[1:] images = images[1:] # for k in images: # cv2.imshow('image', k) # while(True): # if cv2.waitKey(1000): # cv2.destroyAllWindows() # break return images,masks # 将像素值写入文件 # with open('./1.txt', 'w') as f: # for i in range(len(images[0])): # for j in range(len(images[0][0])): # f.write('{}'.format(images[1][i][j])) # f.write('\n') # 填入多张图片的平均像素值 def fill_pics(images, masks): global img1 img1 = images[num_fill_pic].copy() # copy给保存截图交互用 for i in range(len(masks[0])): # 多张图片的平均像素填充mask for j in range(len(masks[0][0])): # print('images[1][i][j][:] :', images[1][i][j][:]) if all(masks[num_fill_pic][i][j][:] >= [240, 240, 240]): # all用来比较numpy数组里的每个值是否符合,如果当前mask的像素为白色,即是mask空白处 a = np.empty(shape=[1, 3], dtype=np.uint8) for k in range(len(masks)): if all(masks[k][i][j][:] < [240, 240, 240]): # 如果当前像素处于不被分割出来的区域,也就是mask里的黑区域,就放入a中求平均像素,之后覆盖到mask中 a = np.vstack((a, images[k][i][j][:])) # 采用np.vstack可以实现动态增加numpy的功能 a = a[1:] a = [np.mean(a[:, 0]).astype(np.uint8), np.mean(a[:, 1]).astype(np.uint8),np.mean(a[:, 2]).astype(np.uint8)] # 求多张图片的平均像素 # input('breakpoint') images[num_fill_pic][i][j][:] = a cv2.namedWindow("image") cv2.setMouseCallback("image", on_mouse) cv2.imshow("image", img1) while(True): try: if cv2.waitKey(100) & 0xff == ord('q'): break except Exception: cv2.destroyWindow("image") break # g_rect = [min_x, min_y, width, height] global g_rect print('g_rect', g_rect) min_x, min_y, width, height = g_rect[0], g_rect[1], g_rect[2], g_rect[3] images[num_fill_pic, min_y:min_y + height, min_x:min_x + width] = img1[min_y:min_y + height, min_x:min_x + width] # images[1,:,:,:] = np.ones([512,512,3], dtype=np.uint8)*255 # 将图片设置为白色 cv2.imwrite('{0}\\{1}'.format(target_file_path, '{0}_filled_image.jpg'.format(num_fill_pic)), images[num_fill_pic]) cv2.imshow('fill in image{0}'.format(num_fill_pic), images[num_fill_pic]) while(True): if cv2.waitKey(3500): cv2.destroyAllWindows() break if __name__ == '__main__': startTime = time.time() # 开始时刻 images, masks = read_pics() # 读取图片 fill_pics(images, masks) # 填充图片 endTime = time.time() # 结束时刻 print('time using:{0:.2f}s'.format(endTime-startTime)) # 10张图片平均像素来填10张图片,用时19.17s
Markdown
UTF-8
11,183
2.921875
3
[]
no_license
Chapter 6: curriculum: Art/Architecture --------------------------------------- [Art/Architecture](../category/curriculum/artarchitecture/index.html) --------------------------------------------------------------------- Oscar Niemeyer ============== One of the most depressing aspects of travel is finding that the world often looks the same in many different places. The towers of downtown Tokyo are indistinguishable from those of Frankfurt or Seattle. Thats no coincidence. Modern architecture was founded on the idea that buildings should logically look the same everywhere. The early figures of Modernism were united in their bitter opposition to any kind of regionalism, which they saw as reactionary, folkloric and plain mediocre. If bicycles, telephones and planes (all harbingers of the new age) werent going to be done up in a local style, why should buildings? Down with chalets, wigwams and gargoyles. <span class="s1">The Brazilian architect Oscar Niemeyer began his career as an orthodox modern architect, subscribing thoroughly to this universalist credo. He was born in Rio de Janeiro in 1907 and developed a passion for architecture in his early teens. When he went to study at the National School of Fine Arts, he fell in with a group that venerated the great European Modernist architects, especially Le Corbusier who had insisted with particular vehemence on making sure buildings made no concession whatever to the culture in which they were located.</span> <span class="s1">Niemeyers professional ambitions were realised when, in 1936, Le Corbusier was commissioned to come to Rio to design the new Ministry of Education and Health. Niemeyer was invited to join the team of Brazilian architects charged with helping the European to realise his scheme on this large and prestigious building.</span> [![philippou.2010.04.21](http://i1.wp.com/www.thebookoflife.org/wp-content/uploads/2014/11/philippou.2010.04.21.jpg?resize=635%2C436)](http://i0.wp.com/www.thebookoflife.org/wp-content/uploads/2014/11/philippou.2010.04.21.jpg) <span class="s1">While working with him, Niemeyer retained the utmost respect for Le Corbusier, but at the same time, he couldnt help but observe how blind his guest was to the particularities of Brazilian culture and climate. With what would become his legendary charm, Niemeyer managed to persuade Le Corbusier to abandon some of his more hard-edged universalist intentions for the building and to make some concessions to local conditions. Under his influence, the buildings windows acquired louvres against the sun and, most spectacularly of all, Niemeyer persuaded Le Corbusier to commission an enormous traditional Portuguese piece of tile work, done up with abstract motifs, for the public areas on the ground floor.</span> [![Gustavo\_Capanema\_Palace\_Rio\_de\_Janeiro\_Brazil\_main\_entrance\_2004](http://i1.wp.com/www.thebookoflife.org/wp-content/uploads/2014/11/Gustavo_Capanema_Palace_Rio_de_Janeiro_Brazil_main_entrance_2004.jpg?resize=635%2C349)](http://i2.wp.com/www.thebookoflife.org/wp-content/uploads/2014/11/Gustavo_Capanema_Palace_Rio_de_Janeiro_Brazil_main_entrance_2004.jpg) <span class="s1">Emboldened by his success with the building, Niemeyer felt ready to break free from European Modernism. He is to be celebrated for being perhaps the first architect anywhere in the world to practice a regional kind of Modernism: in his case, a Brazilian-infused modernism.</span> <span class="s1">His first wholly original work was completed in 1943 (when he was 36), and was commissioned by the local mayor of Belo Horizonte, the future president of Brazil, Juscelino Kubitschek. It was a building complex that included a casino, a restaurant, a dance hall, a yacht club and most famously, a place of worship, now known as the Church of Saint Francis of Assisi, in Belo Horizonte. </span> <span class="s1">Though the local clergy hated it (Archbishop Antonio dos Santos Cabral called it a devils bomb shelter unfit for religious purposes), it was quickly recognised as a masterpiece. </span> ![](http://i1.wp.com/imageweb-cdn.magnoliasoft.net/bridgeman/supersize/stf372067.jpg?resize=600%2C403) <span class="s1">The complex had no straight lines on any plane, for Niemeyer now judged these to be European and (it was the heyday of Fascism) appallingly authoritarian. Architecture had in theory been liberated from oppressive structural conventions by the invention of reinforced concrete and Niemeyer proposed that one should use the new freedom in more creative ways.</span> <span class="s1">Niemeyer was henceforth to include curves in all his buildings, and saw them in a nationalistic light as being particularly Brazilian in nature. It is not the right angle that attracts me, nor the straight line, hard and inflexible, created by man, he said. What attracts me is the free and sensual curvethe curve that I find in the mountains of my country, in the sinuous course of its rivers and in the bodies of its beautiful women. The latter point is telling. Niemeyer was deeply responsive to female beauty throughout his life. He was famous around Rio for his affairs, many with people dramatically younger than he was. At 92, he acquired a girlfriend who had just turned 25. </span> <span class="s1">As in the Ministry of Health, the Pampulha Church had tiles across it. They reminded viewers that Brazil could be both modern and recall its heritage that a church might nod towards the forms of a futuristic airplane hanger, and yet could at the same time accommodate a depiction of Saint Francis and some (distinctly charming) chickens. </span> ![002](http://i2.wp.com/www.thebookoflife.org/wp-content/uploads/2014/09/002.jpg) <span class="s1">The sensuality that Niemeyer enjoyed in his life also came to infuse many of his buildings. His Casa das Canoas (1951) repositions sensuality as part of a sophisticated, mature life. Instead of suggesting that it might be the special province of the young, the carefree, the louche or the pretty, he creates a home where one imagines you can be an accountant or work in the Ministry of Infrastructure (be a responsible, hard working person much concerned with technical and administrative problems) and relish your body. You can have a conversation that stretches your mind and also be gently exploring the back of your lovers knee; or you might kiss in the warm shadows before taking a conference call about worrying regional sales projections.</span> The house is a bit like a confident and encouraging friend who makes reassuring murmurs at the right time. One could imagine a couple feeling safe enough in this house to be sexually adventurous in a way that felt impossible for years in their normal home. [![5696218302\_befc49d6c0\_z](http://i0.wp.com/www.thebookoflife.org/wp-content/uploads/2014/11/5696218302_befc49d6c0_z.jpg?resize=635%2C395)](http://i0.wp.com/www.thebookoflife.org/wp-content/uploads/2014/11/5696218302_befc49d6c0_z.jpg) <span class="s1">Niemeyers most audacious attempt to use architecture to define Brazilian identity came with his designs for the new capital, Brasilia. In 1956, Kubitschek asked Niemeyer to help create a wholly planned city in the centre of the country, free from the corruption of the old capital in Rio. Niemeyer drew up the National Congress, a cathedral, a cultural complex, many ministries and commercial and residential buildings. The atmosphere was dignified, hopeful, and in touch with the native environment. Apartment buildings were lifted on stilts to allow vegetation to grow beneath them, maintaining a connection with the local ecology and tropical climate. </span> ![item16.rendition.slideshowVertical.the-architects-eye-lee-mindel-brasilia-brazil-16-national-congress-of-brazil-exterior](http://i0.wp.com/www.thebookoflife.org/wp-content/uploads/2014/09/item16.rendition.slideshowVertical.the-architects-eye-lee-mindel-brasilia-brazil-16-national-congress-of-brazil-exterior.jpg) <span class="s1">Of course, Niemeyers works depicted Brazil not as it was, but as he believed and hoped it might one day be. He knew that architecture can point hopefully and encouragingly in a good direction. Brazil is a country of frenetic economic activity, of rainforest and Amazonian villages, favelas, soccer, beaches and intense disagreement about political priorities ... none of which is apparent from contemplation of the National Congress in Brasilia. Instead the building imagines the Brazil of the future; it is a glass and reinforced concrete ideal for the country to develop towards. In the future, so the building argues, Brazil will be a place where rationality is powerful; where order and harmony reign; where elegance and serenity are normal. Calm, thoughtful people will labour carefully and think accurately about legislation; in offices in the towers, efficient secretaries will type up judicious briefing notes; the filing systems will be perfect nothing will get lost, overlooked, neglected or mislaid; negotiations will take place in an atmosphere of impersonal wisdom. The country will be perfectly managed. The building, therefore, could be seen as an essay in flattery. It hints that these desirable qualities are already to some extent possessed by the country and by its governing class. Ideals flatter us because we experience them not merely as intimations of a far distant future but also as descriptions of what we are like. We are used to thinking of flattery as bad but in fact it is rather helpful, for flattery encourages us to live up to the appealing image it presents. The child who is praised for his or her first modest attempts at humour, and called witty as a result, is being guided and helped to develop beyond what he or she actually happens to be right now. They grow into the person they have flatteringly been described as already being. This is important because the obstacle to our good development is not usually arrogance, but a lack of confidence.</span> ![o-arquiteto-oscar-niemeyer-participou-de-ensaio-da-beija-flor-de-nilc3b3polis-no-sambc3b3dromo-do-rio](http://i1.wp.com/www.thebookoflife.org/wp-content/uploads/2014/09/o-arquiteto-oscar-niemeyer-participou-de-ensaio-da-beija-flor-de-nilc3b3polis-no-sambc3b3dromo-do-rio.jpg) ##### <span class="s1">Niemeyer enjoys the beautiful dream of a Brazilian carnival in 2012, the year of his death. His then girlfriend was 42.</span> <span class="s1">Niemeyer was prolific until his very last years, teaching around the world, writing and designing sculptures and furniture. He died in 2012, when he was 104 years old. He was given a heros funeral and thousands joined the cortege. What his nation was honouring was an architect who had given it a workable yet ideal portrait of itself. He had enabled Brazil to break free from a sterile European modernism and to create buildings that better reflected the nations uniqueness. Niemeyer remains an example to all architects who aspire to put up buildings that remember the distinctiveness of their locales architects who may like their phones to be universal in design, but are as keen for their buildings to be culturally specific.</span> <span class="s1"> </span>
Markdown
UTF-8
2,593
3.125
3
[]
no_license
### 2장 기본 select #### 테이블의 구조 보기 ``` desc emp desc dept ``` #### 기본 Select하기 select * from 테이블명 ; ``` select * from emp; select * from dept; ``` #### system보기 ``` show user ``` #### emp 테이블에서 이름과 급여를 조회하세요. ``` select ename, sal from emp; ``` #### 사원의 이름과 월급, 월급을 200원 인상한다면 얼마가 될지 조회하세요. ``` select ename, sal, sal + 200 from emp; ``` #### 사원의 이름과 월급, 연봉을 조회하세요. 연봉은 급여*12 ``` select ename, sal, sal*12 from emp; ``` #### 사원의 이름과 월급, 연봉을 조회하세요. 연봉은 (급여 + comm) *12 ``` select ename, sal, comm, from emp; ``` 이 문장의 문제점 : 결과가 null이 나온다 NVL 함수를 사용해라 NVL( a, b ) => a가 널이면 b를 반환해라 ( a가 널이 아니면 a를) NVL ( comm, 0) => comm이 널이면 0를 반환해라 -- NULL : 의미가 없다. 아직 정해지지 않았다. 100 + null => null ``` select ename, sal, comm, (sal + NVL ( comm, 0 )) * 12 from emp; ``` #### column alias 사용해서 컬럼 헤딩을 변경하세요. ``` select ename, sal, comm, (sal + NVL ( comm, 0 )) * 12 Ann_Sal from emp; ``` #### column alias를 대소문자 구분해서 표시하고자 할때 " " 사용 ``` select ename, sal, comm, (sal + NVL ( comm, 0 )) * 12 Ann_Sal from emp; select ename, sal, comm, (sal + NVL ( comm, 0 )) * 12 "Ann_Sal" from emp; select ename AS emp_name, sal, comm, (sal + NVL ( comm, 0 )) * 12 AS "Ann Sal" from emp; ``` #### 연결연산자 : || ``` select ename, job , ename || job AS emp_detail from emp; ``` SMITH의 직무는 CLERK이다. 라고 추출하고 싶을때 ENAME || '의 직무는 '|| job || '이다.' -- 상수 : literal -- 문자 상수 , 날짜 상수 : '문자' '날짜' -- 숫자 상수 : 100 ``` select ENAME || '의 직무는 '|| job || '이다.' from emp; ``` -- DB에서 가져온 데이터가 아니고 상수(문자, 날짜, 숫자 literal) 만 display하고자 한다면 sys.dual 을 사용할 수 있다. sys.dual은 dual이라고 해도 된다. #### schema명.테이블명 ``` select * from sys.dual; select * from sys.dual; select * from dual; ``` 참고 ) select * from emp; -- 내가 소유한 테이블은 스키마명을 생략할 수 있다. hr.emp ==> emp #### user, sysdate 함수 user : 현재 접속한 유저명 sysdate : 현재 날짜와 시간 Ex ) round( 123.45 ) ==> 123
C++
GB18030
3,504
2.53125
3
[]
no_license
#pragma once #include <vector> class DialogPlus :public CDialogEx { DECLARE_DYNAMIC(DialogPlus) public: typedef enum { RENDER_COMMAND_BEGIN = WM_USER, //Ⱦʼ RENDER_SAVE_IMAGE, // ͼ RENDER_LOAD_IMAGE, // ͼ RENDER_EXIT, // ˳ RENDER_ZOOM_ORIGIN_IMAGE, // ͼԭʼߴ RENDER_ZOOM_FIT_IMAGE, // ͼӦ RENDER_ZOOM_IN_IMAGE, // Ŵͼ RENDER_ZOOM_OUT_IMAGE, // Сͼ RENDER_TOOLBAR_SHOW_HIDE, // /ʾ RENDER_PARAM_SHOW_HIDE, // ȾЧ /ʾ RENDER_DISPLAY_SHOW_HIDE, // ȾЧ /ʾ RENDER_SETTINGS_SHOW_HIDE, // Ⱦ /ʾ RENDER_STATUS_SHOW_HIDE, // ״̬ /ʾ RENDER_DEFAULT_LAYOUT, // ָĬϲ RENDER_SAVE_LAYOUT, // 沼 RENDER_LOAD_LAYOUT, // ָ RENDER_HELP, // RENDER_SAVE_SETTINGS, // RENDER_LOAD_SETTINGS, // ȡ RENDER_CHANGE_SETTINGS, // RENDER_BEGIN, // Ⱦʼ RENDER_STOP, // Ⱦֹͣ RENDER_DONE, // Ⱦֹͣ RENDER_SETTING_UPDATE, // Ⱦ RENDER_STATUS_UPDATE, // Ⱦ״̬ RENDER_IMAGE_UPDATE, // Ⱦ״̬ RENDER_COMMAND_END, //Ⱦ }CMD; typedef enum { update_process, //Ⱦ update_status_text, //Ⱦ״̬ update_image_scale, //ͼƬű }RenderStatus; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV ֧ DECLARE_MESSAGE_MAP() public: DialogPlus(); DialogPlus(UINT nIDTemplate, CWnd *pParent = NULL); DialogPlus(LPCTSTR lpszTemplateName, CWnd *pParentWnd = NULL); ~DialogPlus(void); ////////////////////////////////////////////////////////////////////////// // ܺ public: void SetBtnImage(int _btn_marco,int _res_marco); virtual void OnOK(); virtual void OnCancel(); CRect getOffset(const CRect& newRect,const CRect& oldRect); float get_edit_float(UINT editMacro); void set_edit_float(UINT editMacro,float val); bool checkMacro(UINT editMacro); bool get_check_bool(UINT checkMacro); void set_check_bool(UINT checkMacro,bool val); ////////////////////////////////////////////////////////////////////////// // public: //static HWND registerShareHwnd() { return m_shareHwnd; } static void registerShareHwnd(HWND val) { for (int i = 0; i < m_shareArr.size() ; i++) { if(m_shareArr.at(i) == val) { return; } } m_shareArr.push_back(val); } CString SaveImagePath() const { return m_saveImagePath; } void SaveImagePath(CString val) { m_saveImagePath = val; } /** 㸡롣*/ static float getAccuracy(float input,unsigned int accuracy = 3); static int getAccuracyInt(float input); static void Post(DialogPlus::CMD cmd,WPARAM wParam = NULL ,LPARAM lParam = NULL) { for (int i = 0; i < m_shareArr.size() ; i++) { ::PostMessage(m_shareArr.at(i),cmd,wParam,lParam); } } static void Send(DialogPlus::CMD cmd,WPARAM wParam = NULL ,LPARAM lParam = NULL) { for (int i = 0; i < m_shareArr.size() ; i++) { ::SendMessage(m_shareArr.at(i),cmd,wParam,lParam); } } static void setStatusText(CString text) { DialogPlus::Send(DialogPlus::RENDER_STATUS_UPDATE,DialogPlus::update_status_text,(LPARAM)(LPCTSTR)text); } private: static std::vector<HWND> m_shareArr; static CString m_saveImagePath; };
Java
UTF-8
682
3.015625
3
[]
no_license
package ca.mcmaster.oopdesign.visitor; /** * @author SeanForFun E-mail:xiaob6@mcmaster.ca * @date Jul 11, 2018 3:21:40 PM * @version 1.0 */ public class Boss implements AccountBillViewer { private double totalIncome; private double totalConsume; @Override public void view(ConsumerBill bill) { totalConsume += bill.getAmount(); } @Override public void view(IncomeBill bill) { this.totalIncome += bill.getAmount(); } public double getTotalConsume() { System.out.println("Boss: spend " + this.totalConsume + " dollars"); return totalConsume; } public double getTotalIncome() { System.out.println("Boss: get " + this.totalIncome + " dollars"); return totalIncome; } }
C++
UTF-8
2,593
2.796875
3
[]
no_license
//============================================================================ // Name : file_client.cpp // Author : Lars Mortensen // Version : 1.0 // Description : file_client in C++, Ansi-style //============================================================================ #include <iostream> #include <fstream> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <iknlib.h> #define BUFFERSIZE 1000 #define PORT 9000 using namespace std; void receiveFile(string fileName, int socketfd); int main(int argc, char *argv[]) { string ip = argv[1]; string filepath = argv[2]; //Define variables int sockfd; socklen_t clilen; char buffer[BUFFERSIZE]; struct sockaddr_in serv_addr; //Create socket sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) error("ERROR when opening socket"); auto server = gethostbyname(ip.c_str()); //bzero clears data bzero((char *) &serv_addr, sizeof(serv_addr)); //Initiate server IP serv_addr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(PORT); //Connect socket /* if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) error("ERROR on connect"); */ receiveFile(filepath, sockfd); } /** * Modtager filstørrelsen og udskriver meddelelsen: "Filen findes ikke" hvis størrelsen = 0 * ellers * Åbnes filen for at skrive de bytes som senere modtages fra serveren (HUSK kun selve filnavn) * Modtag og gem filen i blokke af 1000 bytes indtil alle bytes er modtaget. * Luk filen, samt input output streams * * @param fileName Det fulde filnavn incl. evt. stinavn * @param sockfd Stream for at skrive til/læse fra serveren */ void receiveFile(string fileName, int sockfd) { //Define variables char* fileNameChar = new char[fileName.length()+1]; strcpy(fileNameChar, fileName.c_str()); //Request file writeTextTCP(sockfd, fileNameChar); string extractedFileName = extractFileName(fileName.c_str()); //Read response from server ofstream fs(extractedFileName, ios_base::out); auto fileSize = getFileSizeTCP(sockfd); char* buf = new char[BUFFERSIZE]; //Receive file from server while(fileSize != fs.tellp()) { int bytesRead = read(sockfd, buf, BUFFERSIZE); fs.write(buf, bytesRead); } delete[] buf; }
Python
UTF-8
537
2.5625
3
[]
no_license
#!/usr/bin/env python #coding=utf-8 import time import demonhandler ################################################################## # Runs different tasks once in a hour. # ################################################################## while(True): print("Awoken!") # Refreshes access tokens which are about to get old. demonhandler.refreshTokens() # Fetches data for each user. demonhandler.fetchData() print("Sleepings...") time.sleep(3600)
PHP
UTF-8
352
2.71875
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace Multi\User\Role; class Parse { public function __invoke(string $role): Role { switch ($role) { case Collaborator::COLLABORATOR: return new Collaborator(); case Administrator::ADMINISTRATOR: return new Administrator(); } } }
Go
UTF-8
896
2.796875
3
[ "MIT" ]
permissive
// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package rand import ( "bytes" "compress/flate" "io" "testing" ) func TestRead(t *testing.T) { var n int = 4e6 if testing.Short() { n = 1e5 } b := make([]byte, n) n, err := io.ReadFull(Reader, b) //t.Fatalf("%d", len(b)) if n != len(b) || err != nil { t.Fatalf("ReadFull(buf) = %d, %s", n, err) } var z bytes.Buffer f, _ := flate.NewWriter(&z, 5) f.Write(b) f.Close() if z.Len() < len(b)*99/100 { t.Fatalf("Compressed %d -> %d", len(b), z.Len()) } } func TestReadEmpty(t *testing.T) { n, err := Reader.Read(make([]byte, 0)) if n != 0 || err != nil { t.Fatalf("Read(make([]byte, 0)) = %d, %v", n, err) } n, err = Reader.Read(nil) if n != 0 || err != nil { t.Fatalf("Read(nil) = %d, %v", n, err) } }
Markdown
UTF-8
500
2.96875
3
[]
no_license
### About Me Hello. I'm Shayna Conner. I'm a senior at Western Oregon University and this page is to showcase projects and assignments that I will complete as part of the Software Engineering series (CS 460, 461, and 462). --- ### Software Engineering Series Assignments * [CS 460 - Software Engineering I](CS460/README.md) * CS 461 - Software Engineering II - Coming soon! * CS 462 - Software Engineering III - Coming soon! --- ### Contact Me * Email: sconner15@wou.edu * [GitHub](https://github.com/shaynuhcon)
Markdown
UTF-8
2,037
3
3
[]
no_license
# @karcass/migration-commands <a href="https://github.com/karcass-ts/cli-service">CliService</a> commands for creation, doing and undoing TypeORM migrations. This commands included by default in <a href="https://github.com/karcass-ts/karcass">karcass</a>. ## Installation ``` npm install @karcass/migration-commands ``` ## Usage index.ts: ```typescript import { CliService } from '@karcass/cli-service' import { createConnection } from 'typeorm' import { CreateMigrationCommand, MigrateCommand, MigrateUndoCommand } from '@karcass/migration-commands' const cliService = new CliService() const connection = await createConnection({ type: 'sqlite', database: 'test/test.sqlite', }) cliService.add(CreateMigrationCommand, () => new CreateMigrationCommand()) cliService.add(MigrateCommand, () => new MigrateCommand(connection)) cliService.add(MigrateUndoCommand, () => new MigrateUndoCommand(connection)) await cliService.run() ``` Output: ``` === Available commands: === --help Show this help migrations:generate <path/name> Create migration with name from argument, e.g. migrations:generate MyBundle/Migrations/MyMigrationName migrations:migrate Doing migrations migrations:migrate:undo Reverts last migration ``` So running `ts-node index.ts migrations:generate test/MyMigration` will create a file with name like `test/1577032764-MyMigration.ts` and contents like: ```typescript import { MigrationInterface, QueryRunner } from 'typeorm' export default class MyMigration1577032764233 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<any> {} public async down(queryRunner: QueryRunner): Promise<any> {} } ``` Command `ts-node index.ts migrations:migrate` will apply all non-applied migrations. Command `ts-noed index.ts migrations:migrate:undo` reverts one last migrated migration. More about migrations in TypeORM you can read <a href="https://github.com/typeorm/typeorm/blob/master/docs/migrations.md">here</a>.
Swift
UTF-8
1,239
2.84375
3
[]
no_license
// // DataViewController.swift // Midterm // // Created by Locker,Todd (TRL43) on 11/2/16. // Copyright © 2016 Locker,Todd. All rights reserved. // import UIKit class DataViewController: UIViewController { @IBOutlet weak var dataLabel: UILabel? var dataObject: String = "" @IBOutlet weak var innerLabel: UILabel? var textData: String = "" // This is called immediately after the view successfully loads override func viewDidLoad() { super.viewDidLoad() // Nothing else to do here because everything was initialized in ModelController.swift } // This is called right before the view appears. This is where the label's text is actually set. override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Guard added by TRL43 guard let dLabel = self.dataLabel else { print("ERROR: Could not unwrap the dataLabel") return } // Guard added by TRL43 guard let iLabel = self.innerLabel else { print("ERROR: Could not unwrap the innerLabel") return } dLabel.text = self.dataObject iLabel.text = self.textData } }
Markdown
UTF-8
888
2.625
3
[ "MIT" ]
permissive
--- layout: post title: "How it Feels" comments: false date: 2020-03-11 12:00:00 -0500 categories: general draft: false --- As crazy as this entire week has been, today feels like the turning point. The day we'll never forget. In the last hour: * Donald Trump gave a disastrous speech meant to reassure the country (and to a certain degree, the world). It had the exact opposite effect. As of this writing, markets are tanking again. * Tom Hanks revealed he has Coronavirus. I'm not sure why this is having such a huge impact but I suppose he's a global celebrity and it's becoming clear that this is unstoppable no matter who you are. * The NBA is suspending its season because Rudy Gobert tested positive for COVID-19. A very strange combination of events but collectively it feels like the panic around COVID-19 has started in North America. I'm not sure what I'm going to be doing just yet.
Java
UTF-8
333
1.742188
2
[]
no_license
package isola.model.html.basic; import isola.constants.MimeTypes; public abstract class JavascriptCode extends Script { /** * * Default constructor */ public JavascriptCode() { super(MimeTypes.text_javascript); } /** * * This method must be implemented by all scripts. */ public abstract String getCode(); }
Ruby
UTF-8
2,382
2.59375
3
[]
no_license
require 'open-uri' require 'json' def brands_filename File.expand_path("../phone_brands.json", __FILE__) end def models_filename File.expand_path("../phone_models.json", __FILE__) end def details_filename File.expand_path("../phone_details.json", __FILE__) end open("http://www.handsetdetection.com/apiv3/device/vendors.json", "Authorization" => %Q{Digest username="85af651535", realm="APIv3", nonce="APIv3", uri="/apiv3/device/vendors.json", response="fbff703672c744847de0f20e2b744628", opaque="APIv3", qop=auth, nc=00000002, cnonce="e401bf33544bdebe"}) { |brands| #puts "dokument #{f.read.inspect}" brands = JSON.parse(brands.read)["vendor"] #writing brands to file File.open(brands_filename, "w") do |f| f.write(JSON.pretty_generate({"brands" => brands })) end brands_models = {} brands.each do |brand| uri = URI.escape("http://www.handsetdetection.com/apiv3/device/models/#{brand}.json") puts "Getting models for brand #{brand}" open(uri, "Authorization" => %Q{Digest username="85af651535", realm="APIv3", nonce="APIv3", uri="/apiv3/device/vendors.json", response="fbff703672c744847de0f20e2b744628", opaque="APIv3", qop=auth, nc=00000002, cnonce="e401bf33544bdebe"}) { |models| brands_models[brand] = JSON.parse(models.read)["model"] } end #writing models to file File.open(models_filename, "w") do |f| f.write(JSON.pretty_generate({"models" => brands_models })) end details = {} brands_models.each do |brand, models| details[brand] = {} models.each do |model| puts "Getting details for brand #{brand} model #{model}" uri = URI.escape("http://www.handsetdetection.com/apiv3/device/view/#{brand}/#{model}.json")#.gsub(" ", "%20") begin open(uri, "Authorization" => %Q{Digest username="85af651535", realm="APIv3", nonce="APIv3", uri="/apiv3/device/vendors.json", response="fbff703672c744847de0f20e2b744628", opaque="APIv3", qop=auth, nc=00000002, cnonce="e401bf33544bdebe"}) do |detail| details[brand][model] = JSON.parse(detail.read)["device"] end rescue Exception => e puts "Error getting details for brand #{brand} model #{model} : #{e.message}" end end unless models.nil? end #writing details to file File.open(details_filename, "w") do |f| f.write(JSON.pretty_generate(details)) end }
Swift
UTF-8
589
3.3125
3
[]
no_license
/* Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2] Example 2: Input: nums = [1], k = 1 Output: [1] Note: You may assume k is always valid, 1 ≤ k ≤ number of unique elements. Your algorithm's time complexity must be better than O(n log n), where n is the array's size. */ class Solution { func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] { let dict = nums.reduce(into: [:]) { $0[$1, default: 0] += 1 } return Array(dict.sorted { $0.1 > $1.1 }.map { $0.0 }[0..<k]) } }
Java
UTF-8
742
3.90625
4
[]
no_license
package com.trainee.aizaz.java; import java.util.ArrayList; import java.util.ListIterator; /** * The purpose of this class is to get collection objects one by one * in reverse oder using cursors. */ public class TraversingInCollections { public static void main(String args[]) { ArrayList<String> al = new ArrayList<String>(); al.add("alan"); al.add("morries"); al.add("john"); al.add("tom"); ListIterator<String> litr = al.listIterator(al.size()); /** * we are using hsaPrevious() to get collection object in reverse order: */ while (litr.hasPrevious()) { String str = litr.previous(); System.out.println(str); } } }
C++
UTF-8
382
3.28125
3
[ "MIT" ]
permissive
#include <iostream> #include <string> // #include <iterator> // #include <algorithm> // #include <numeric> using namespace std; void swap(int[]); main() { int a[] = {3, 8}; swap(a); cout << "main: " << a[0] << " " << a[1] << "\n"; return 1; } void swap(int a[]) { int temp = a[0]; a[0] = a[1]; a[1] = temp; cout << "swap: " << a[0] << " " << a[1] << "\n"; }
C#
UTF-8
2,508
3.234375
3
[]
no_license
using Microsoft.VisualStudio.TestTools.UnitTesting; using OpgaveFlexyBox; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OpgaveFlexyBox.Tests { [TestClass()] public class ToolsTests { [TestMethod()] public void ReverseStringTest() // testing for true result { string input = "this is the text for testing"; string output = Tools.ReverseString(input); string reversed = new string(input.Reverse().ToArray()); if (output == reversed) { Assert.IsFalse(false, "String is reversed correctly"); return; } Assert.IsFalse(true, "String not reversed"); } [TestMethod()] public void IsPalindromeTest() { string input = "Never odd or even"; bool output = Tools.IsPalindrome(input); if (output) { Assert.IsFalse(false, "Palindrome found"); return; } Assert.IsFalse(true, "Palindrome not found"); } [TestMethod()] public void IsNOTPalindromeTest() { string input = "This is not a palindrome"; bool output = Tools.IsPalindrome(input); if (!output) { Assert.IsFalse(false, "Found out string wasn't a palindrome"); return; } Assert.IsFalse(true, "Failed to notice string wasn't a palindrome"); } [TestMethod()] public void MissingElementsTest() { Dictionary<int[], List<int>> testData = new Dictionary<int[], List<int>>(); // <input, expected> testData.Add(new int[] { 4, 6, 9 }, new List<int>() { 5, 7, 8 }); testData.Add(new int[] { 2, 3, 4 }, new List<int>() { }); testData.Add(new int[] { 1, 3, 4 }, new List<int>() { 2 }); testData.Add(new int[] { }, new List<int>() { }); foreach (var item in testData) { List<int> output = Tools.MissingElements(item.Key).ToList(); if (!output.SequenceEqual(item.Value)) { Assert.IsFalse(true, "Testing failed at input: " + string.Join(",", item.Key)); return; } } Assert.IsFalse(false, "All test data passed"); } } }
C#
UTF-8
650
2.765625
3
[ "MIT" ]
permissive
using TMPro; /// <summary> /// Handles UI, updating general texts and other elements /// </summary> public class UIManager : Singleton<UIManager> { public TextMeshProUGUI GoldText; /// <summary> /// Update gold text when gold changes /// </summary> /// <param name="gold"></param> public void OnGoldChanged(int gold) { if (GoldText != null) GoldText.text = "" + gold; } protected virtual void OnEnable() { CharacterInventory.OnGoldChanged += OnGoldChanged; } protected virtual void OnDisable() { CharacterInventory.OnGoldChanged -= OnGoldChanged; } }
Python
UTF-8
1,144
2.796875
3
[]
no_license
from subdomains.date_handler import DateHandler from subdomains.plate import LicensePlate from services.settings_handler import SettingsHandler from services.time_methods import is_time_in_range class Predictor: def __init__(self,date_n_time,plates,mode="production") -> None: self.date_n_time=DateHandler(date_n_time) self.plates=LicensePlate(plates) self.mode=mode def can_my_vehicle_be_on_the_road(self)->bool: day_of_the_week_as_integer=self.date_n_time.get_day_as_integer() time=self.date_n_time.get_hour_as_time_object() last_digit_of_plate=self.plates.get_last_digit() day_settings=SettingsHandler(day_of_the_week_as_integer,self.mode) restricted_time_segments=day_settings.get_restricted_time_segments() restricted_plate_last_digits=day_settings.get_restricted_plate_ending_digits() if not last_digit_of_plate in restricted_plate_last_digits: return True for restricted_time_segment in restricted_time_segments: if is_time_in_range(*restricted_time_segment,time): return False return True
C++
UTF-8
479
3.578125
4
[]
no_license
/* Given a Singly Linked List of size N, delete all alternate nodes of the list. Example 1: Input: LinkedList: 1->2->3->4->5->6 Output: 1->3->5 Explanation: Deleting alternate nodes results in the linked list with elements 1->3->5. Example 2: Input: LinkedList: 99->59->42->20 Output: 99->42 */ // TC-O(N) SC-O(1) void deleteAlt(struct Node *head){ Node*curr=head; while(curr && curr->next){ curr->next=curr->next->next; curr=curr->next; } }
JavaScript
UTF-8
3,024
2.71875
3
[]
no_license
import React from 'react'; import ItemList from '../item-list'; import { withData, withSwapiService } from '../hoc-helpers'; // ============================================================================= /** * Компонент (функция) высшего порядка - HOC; * В первом параметре принимает компонент со списком собственных параметров, * а в теле принимаемого компонента разворачивается рендер-функция, переданная * в качестве второго параметра данного HOC-компонента */ const withChildFunction = (Wrapped, fn) => { return (props) => { return ( <Wrapped {...props}> {fn} </Wrapped> ) }; }; /** * Рендер-функции для HOC-компонента с моделями */ const renderName = ({ name }) => <span>{name}</span>; const renderPerson = ({ name, gender, birthYear }) => <div>{name} <span className="badge badge-dark">{gender}</span>&nbsp; <span className="badge badge-dark">{birthYear}</span> </div>; const renderStarship = ({ name, model, length }) => <div>{name} <span className="badge badge-dark">{model}</span>&nbsp; <span className="badge badge-dark">{length}</span> </div>; const renderPlanet = ({ name, diameter, population }) => <div>{name} <span className="badge badge-dark">{diameter}</span>&nbsp; <span className="badge badge-dark">{population}</span> </div>; // ============================================================================= /** * Здесь для генерации каждого конкретного списка применяется паттерн * "Композиция функций" - это когда берется результат одной функции и поверх нее * применятся еще одна функция. * В контексте React - это "Композиция компонентов высшего порядка" */ const mapPersonMethodsToProps = (swapiService) => { return { getData: swapiService.getAllPeople }; }; const PersonList = withSwapiService ( withData(withChildFunction(ItemList, renderPerson)), mapPersonMethodsToProps ); const mapPlanetMethodsToProps = (swapiService) => { return { getData: swapiService.getAllPlanets }; }; const PlanetList = withSwapiService ( withData(withChildFunction(ItemList, renderPlanet)), mapPlanetMethodsToProps ) const mapStarshipMethodsToProps = (swapiService) => { return { getData: swapiService.getAllStarships }; }; const StarshipList = withSwapiService ( withData(withChildFunction(ItemList, renderStarship)), mapStarshipMethodsToProps ) export { PersonList, PlanetList, StarshipList };
Java
UTF-8
13,157
1.710938
2
[]
no_license
package com.ziploan.team.verification_module.borrowerdetails.credit; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.CardView; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TableLayout; import android.widget.TextView; import com.ziploan.team.R; import com.ziploan.team.databinding.CreditLayoutBinding; import com.ziploan.team.utils.AppConstant; import com.ziploan.team.verification_module.base.BaseFragment; import com.ziploan.team.webapi.APIExecutor; import com.ziploan.team.webapi.cibil.CibilLiveDatum; import com.ziploan.team.webapi.cibil.CibilResponse; import com.ziploan.team.webapi.cibil.ReqCibilDatum; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class CreditFragment extends BaseFragment { private CreditLayoutBinding binding; private RecyclerView cibil_recycle_view; private RecyclerView sec_cibil_recycle_view; private CibilResponse cibilResponse; private TextView bank_name; private TextView holder_name; private TextView total_debit; private TextView total_credit; private TextView total_bounce; private TextView total_cash_deposit; private TextView sec_bank_name; private TextView sec_holder_name; private TextView sec_total_debit; private TextView sec_total_credit; private TextView sec_total_bounce; private TextView sec_cash_deposite; private TextView secondary_bank_title; private TableLayout secondary_table; private TextView sec_cbil_info_title; private MyAdapter mAdapter; private MyAdapter1 mAdapter1; private LinearLayoutManager mLayoutManager; private LinearLayoutManager mLayoutManager1; public static CreditFragment newInstance(String id) { CreditFragment creditFragment = new CreditFragment(); Bundle bundle = new Bundle(); bundle.putString(AppConstant.Key.LOAN_REQUEST_ID, id); creditFragment.setArguments(bundle); return creditFragment; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { binding = CreditLayoutBinding.inflate(inflater, container, false); return binding.getRoot(); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); cibil_recycle_view = view.findViewById(R.id.cibil_recycle_view); sec_cibil_recycle_view = view.findViewById(R.id.sec_cibil_recycle_view); secondary_bank_title = view.findViewById(R.id.secondary_bank_title); secondary_table = view.findViewById(R.id.secondary_table); sec_cbil_info_title = view.findViewById(R.id.sec_cbil_info_title); bank_name = view.findViewById(R.id.bank_name); holder_name = view.findViewById(R.id.holder_name); total_debit = view.findViewById(R.id.total_debit); total_credit = view.findViewById(R.id.total_credit); total_bounce = view.findViewById(R.id.total_bounce); total_cash_deposit = view.findViewById(R.id.total_cash_deposit); sec_bank_name = view.findViewById(R.id.sec_bank_name); sec_holder_name = view.findViewById(R.id.sec_holder_name); sec_total_debit = view.findViewById(R.id.sec_total_debit); sec_total_credit = view.findViewById(R.id.sec_total_credit); sec_total_bounce = view.findViewById(R.id.sec_total_bounce); sec_cash_deposite = view.findViewById(R.id.sec_cash_deposite); getBankInfo(); mAdapter = new MyAdapter(); mAdapter1 = new MyAdapter1(); mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false); mLayoutManager1 = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false); cibil_recycle_view.setHasFixedSize(true); cibil_recycle_view.setLayoutManager(mLayoutManager); cibil_recycle_view.setAdapter(mAdapter); sec_cibil_recycle_view.setHasFixedSize(true); sec_cibil_recycle_view.setLayoutManager(mLayoutManager1); sec_cibil_recycle_view.setAdapter(mAdapter1); } private void getBankInfo() { //showProgressDialog(getActivity(), "Please wait..."); Call<CibilResponse> call = APIExecutor.getAPIServiceSerializeNull(mContext) .getBankInfo(getArguments().getString(AppConstant.Key.LOAN_REQUEST_ID)); call.enqueue(new Callback<CibilResponse>() { @Override public void onResponse(Call<CibilResponse> call, Response<CibilResponse> response) { hideProgressDialog(); if (response != null && response.isSuccessful() && response.body() != null) { cibilResponse = response.body(); if(cibilResponse.getResponse() != null) { if (cibilResponse.getResponse().getScannedData() != null && cibilResponse.getResponse().getScannedData().size() > 0) { bank_name.setText(cibilResponse.getResponse().getScannedData().get(0).getBankName()); holder_name.setText(cibilResponse.getResponse().getScannedData().get(0).getAccountHolderName()); total_debit.setText(cibilResponse.getResponse().getScannedData().get(0).getTotalDebit()); total_credit.setText(cibilResponse.getResponse().getScannedData().get(0).getTotalCredit()); total_bounce.setText(cibilResponse.getResponse().getScannedData().get(0).getTotalOutwBounce()); total_cash_deposit.setText(cibilResponse.getResponse().getScannedData().get(0).getTotalCashDeposit()); if (cibilResponse.getResponse().getScannedData().size() > 1) { secondary_bank_title.setVisibility(View.VISIBLE); secondary_table.setVisibility(View.VISIBLE); sec_bank_name.setText(cibilResponse.getResponse().getScannedData().get(1).getBankName()); sec_holder_name.setText(cibilResponse.getResponse().getScannedData().get(1).getAccountHolderName()); sec_total_debit.setText(cibilResponse.getResponse().getScannedData().get(1).getTotalDebit()); sec_total_credit.setText(cibilResponse.getResponse().getScannedData().get(1).getTotalCredit()); sec_total_bounce.setText(cibilResponse.getResponse().getScannedData().get(1).getTotalOutwBounce()); sec_cash_deposite.setText(cibilResponse.getResponse().getScannedData().get(1).getTotalCashDeposit()); } } if(cibilResponse.getResponse().getReqCibilData() != null) { for (ReqCibilDatum reqCibilDatum : cibilResponse.getResponse().getReqCibilData()) { if (reqCibilDatum.getApplicantType().equals(1)) { mAdapter.setData(cibilResponse.getResponse().getReqCibilData().get(0).getCibilLiveData()); } else if (reqCibilDatum.getApplicantType().equals(2)) { sec_cbil_info_title.setVisibility(View.VISIBLE); mAdapter1.setData(cibilResponse.getResponse().getReqCibilData().get(1).getCibilLiveData()); } } } } } else { checkTokenValidity(response); } } @Override public void onFailure(Call<CibilResponse> call, Throwable t) { t.printStackTrace(); hideProgressDialog(); } }); } static class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> { private List<CibilLiveDatum> mDataset; public static class ViewHolder extends RecyclerView.ViewHolder { public TextView loan_name; public TextView loan_type; public TextView sanctioned_amount; public TextView current_balance; public TextView date_opened; public TextView date_reported; public TextView emi; public ViewHolder(View v) { super(v); loan_name = v.findViewById(R.id.loan_name); loan_type = v.findViewById(R.id.loan_type); sanctioned_amount = v.findViewById(R.id.sanctioned_amount); current_balance = v.findViewById(R.id.current_balance); date_opened = v.findViewById(R.id.date_opened); date_reported = v.findViewById(R.id.date_reported); emi = v.findViewById(R.id.emi); } } public void setData(List<CibilLiveDatum> dataset){ this.mDataset = dataset; notifyDataSetChanged(); } @Override public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.cibil_info_item_layout, parent, false); ViewHolder vh = new ViewHolder(v); return vh; } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.loan_type.setText(mDataset.get(position).getLoanType()); holder.loan_name.setText(mDataset.get(position).getAccountType()); holder.current_balance.setText(mDataset.get(position).getCurrentbalance()); holder.date_opened.setText(mDataset.get(position).getDateopeneddisbursed().getDate() + ""); holder.date_reported.setText(mDataset.get(position).getDatereportedcertified().getDate() + ""); holder.emi.setText(mDataset.get(position).getEmiFromatted()); holder.sanctioned_amount.setText(mDataset.get(position).getHighcreditsanctionedamount()); } @Override public int getItemCount() { return mDataset != null ? mDataset.size() : 0; } } static class MyAdapter1 extends RecyclerView.Adapter<MyAdapter1.ViewHolder> { private List<CibilLiveDatum> mDataset; public static class ViewHolder extends RecyclerView.ViewHolder { public TextView loan_name; public TextView loan_type; public TextView sanctioned_amount; public TextView current_balance; public TextView date_opened; public TextView date_reported; public TextView emi; public ViewHolder(View v) { super(v); loan_name = v.findViewById(R.id.loan_name); loan_type = v.findViewById(R.id.loan_type); sanctioned_amount = v.findViewById(R.id.sanctioned_amount); current_balance = v.findViewById(R.id.current_balance); date_opened = v.findViewById(R.id.date_opened); date_reported = v.findViewById(R.id.date_reported); emi = v.findViewById(R.id.emi); } } public void setData(List<CibilLiveDatum> dataset){ this.mDataset = dataset; notifyDataSetChanged(); } @Override public MyAdapter1.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.cibil_info_item_layout, parent, false); ViewHolder vh = new ViewHolder(v); return vh; } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.loan_type.setText(mDataset.get(position).getLoanType()); holder.loan_name.setText(mDataset.get(position).getAccountType()); holder.current_balance.setText(mDataset.get(position).getCurrentbalance()); holder.date_opened.setText(mDataset.get(position).getDateopeneddisbursed().getDate() + ""); holder.date_reported.setText(mDataset.get(position).getDatereportedcertified().getDate() + ""); holder.emi.setText(mDataset.get(position).getEmi() + ""); holder.sanctioned_amount.setText(mDataset.get(position).getHighcreditsanctionedamount()); } @Override public int getItemCount() { return mDataset != null ? mDataset.size() : 0; } } public CibilResponse getCibilResponse() { return cibilResponse; } }
Markdown
UTF-8
1,586
2.625
3
[]
no_license
# Article R353-165 I.-Sans préjudice des dispositions des articles L. 353-6 et L. 353-12, en cas de non-respect par le bailleur au sens du I de l'article R. 353-159, des engagements prévus par la convention, le préfet peut, après avoir mis le gestionnaire en mesure de présenter ses observations, prononcer des pénalités, dans les conditions précisées par la convention. II.-En cas de non-respect par le gestionnaire d'un logement-foyer dénommé résidence sociale des engagements prévus dans la convention conditionnant le bénéfice de l'aide personnalisée au logement, l'autorité administrative compétente peut retirer l'agrément d'intermédiation locative et de gestion locative sociale mentionné aux articles L. 365-4 et R. 365-8. **Liens relatifs à cet article** _Codifié par_: - Décret n°78-622 du 31 mai 1978 _Modifié par_: - Décret n°2011-356 du 30 mars 2011 - art. 1 _Cité par_: - Code de la construction et de l'habitation. - art. Annexe 1 au III art R353-159 (V) - Code de la construction et de l'habitation. - art. Annexe 2 au III art R353-159 (V) - Code de la construction et de l'habitation. - art. R353-155 (V) _Cite_: - Code de la construction et de l'habitation. - art. L353-12 - Code de la construction et de l'habitation. - art. L353-6 - Code de la construction et de l'habitation. - art. L365-4 - Code de la construction et de l'habitation. - art. R353-159 - Code de la construction et de l'habitation. - art. R365-8 _Nouveaux textes_: - Code de la construction et de l'habitation. - art. R353-164-1 (Ab)
Markdown
UTF-8
16,117
3.03125
3
[]
no_license
--- layout: post title: Hadoop系列(5)之容量调度器Capacity Scheduler配置 date: 2016-02-01 10:30:35 categories: 大数据 tags: Hadoop --- ## 1. 应用场景 本文只关注配置,关于调度器的算法以及核心内容将在下一篇介绍。 Capacity Scheduler是YARN中默认的资源调度器,但是在默认情况下只有root.default 一个queue。而当不同用户提交任务时,任务都会在这个队里里面按优先级先进先出,大大影响了多用户的资源使用率。现在公司的任务主要分为三种: * 每天晚上进行的日常任务dailyTask,这些任务需要在尽可能短的时间内完成,且由于关乎业务,所以一旦启动就必须提供尽可能多的资源,因为我分配的资源也最多 70%,队列名位dailyTask。 * 白天,通过Hive来获取一些数据信息,这部分任务由其他的同事进行操作,对查询速度要求并不是很高,且断断续续的,我分配的中等20%,队列名hive。 * 最后这种我定义为是其他的类型,长时间的一些数据处理任务,分配资源少一些10%,队列名为default(这个队列一定要存在)。 需要说明的是以下几点: * 单个队列比如dailyTask,如果有多个任务在队列里面,那么只能有一个任务在运行,其他任务在等待。 * 虽然我设置了队列的资源容量capacity,但是由于资源是共享式的,所以如果有其他queue的资源处理空闲,那么该queue就会从空闲的queue借资源,但是该queue资源最多不会超过 maximum-capacity。所以dailyTask由于在晚上时候运行,其他queue都是空闲的,所以它的实际资源利用率基本上是 maximum-capacity,也就是100%。而白天只有Hive队列和Default队列在使用,所以他们两会共享dailyTask的空余的70%资源。 * 如果在HIVE队列和Default队列都在运行时候,突然dailyTask队列add进了任务了,dailyTask就会等待借出去的资源被回收再分配。 * 目前这样的配置,刚好符合现在的需求,相比于公平调度器较为复杂的配置,目前容量调度器无疑更合适,所以先选择容量调度器。 ## 2. 配置 1.首先在yarn-site.xml中配置调度器类型 ```xml <property> <name>yarn.resourcemanager.scheduler.class</name> <value>org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler</value> </property> ``` 2.在Capacity Scheduler专属配置文件capacity-scheduler.xml,需要说明默认存在root的queue,其他的队列都是它的子队列。 * yarn.scheduler.capacity.root.default.maximum-capacity,队列最大可使用的资源率。 * capacity:队列的资源容量(百分比)。 当系统非常繁忙时,应保证每个队列的容量得到满足,而如果每个队列应用程序较少,可将剩余资源共享给其他队列。注意,所有队列的容量之和应小于100。 * maximum-capacity:队列的资源使用上限(百分比)。由于存在资源共享,因此一个队列使用的资源量可能超过其容量,而最多使用资源量可通过该参数限制。 * user-limit-factor:单个用户最多可以使用的资源因子,默认情况为1,表示单个用户最多可以使用队列的容量不管集群有空闲,如果该值设为5,表示这个用户最多可以使用5*capacity的容量。实际上单个用户的使用资源为 min(user-limit-factor*capacity,maximum-capacity)。这里需要注意的是,如果队列中有多个用户的任务,那么每个用户的使用量将稀释。 * minimum-user-limit-percent:每个用户最低资源保障(百分比)。任何时刻,一个队列中每个用户可使用的资源量均有一定的限制。当一个队列中同时运行多个用户的应用程序时中,每个用户的使用资源量在一个最小值和最大值之间浮动,其中,最小值取决于正在运行的应用程序数目,而最大值则由minimum-user-limit-percent决定。比如,假设minimum-user-limit-percent为25。当两个用户向该队列提交应用程序时,每个用户可使用资源量不能超过50%,如果三个用户提交应用程序,则每个用户可使用资源量不能超多33%,如果四个或者更多用户提交应用程序,则每个用户可用资源量不能超过25%。 * maximum-applications :集群或者队列中同时处于等待和运行状态的应用程序数目上限,这是一个强限制,一旦集群中应用程序数目超过该上限,后续提交的应用程序将被拒绝,默认值为10000。所有队列的数目上限可通过参数yarn.scheduler.capacity.maximum-applications设置(可看做默认值),而单个队列可通过参数yarn.scheduler.capacity.<queue-path>.maximum-applications设置适合自己的值。 * maximum-am-resource-percent:集群中用于运行应用程序ApplicationMaster的资源比例上限,该参数通常用于限制处于活动状态的应用程序数目。该参数类型为浮点型,默认是0.1,表示10%。所有队列的ApplicationMaster资源比例上限可通过参数yarn.scheduler.capacity. maximum-am-resource-percent设置(可看做默认值),而单个队列可通过参数yarn.scheduler.capacity.<queue-path>. maximum-am-resource-percent设置适合自己的值。 * state :队列状态可以为STOPPED或者RUNNING,如果一个队列处于STOPPED状态,用户不可以将应用程序提交到该队列或者它的子队列中,类似的,如果ROOT队列处于STOPPED状态,用户不可以向集群中提交应用程序,但正在运行的应用程序仍可以正常运行结束,以便队列可以优雅地退出。 * acl_submit_applications:限定哪些Linux用户/用户组可向给定队列中提交应用程序。需要注意的是,该属性具有继承性,即如果一个用户可以向某个队列中提交应用程序,则它可以向它的所有子队列中提交应用程序。配置该属性时,用户之间或用户组之间用“,”分割,用户和用户组之间用空格分割,比如“user1, user2 group1,group2”。 * acl_administer_queue:为队列指定一个管理员,该管理员可控制该队列的所有应用程序,比如杀死任意一个应用程序等。同样,该属性具有继承性,如果一个用户可以向某个队列中提交应用程序,则它可以向它的所有子队列中提交应用程序。 ```xml <property> <name>yarn.scheduler.capacity.maximum-applications</name> <value>10000</value> <description> Maximum number of applications that can be pending and running. </description> </property> <property> <name>yarn.scheduler.capacity.maximum-am-resource-percent</name> <value>0.1</value> <description> Maximum percent of resources in the cluster which can be used to run application masters i.e. controls number of concurrent running applications. </description> </property> <property> <name>yarn.scheduler.capacity.resource-calculator</name> <value>org.apache.hadoop.yarn.util.resource.DefaultResourceCalculator</value> <description> The ResourceCalculator implementation to be used to compare Resources in the scheduler. The default i.e. DefaultResourceCalculator only uses Memory while DominantResourceCalculator uses dominant-resource to compare multi-dimensional resources such as Memory, CPU etc. </description> </property> <property> <name>yarn.scheduler.capacity.root.queues</name> <value>default,dailyTask,hive</value> <description> The queues at the this level (root is the root queue).具有三个子队列 </description> </property> <!-- default --> <property> <name>yarn.scheduler.capacity.root.default.capacity</name> <value>20</value> <description>Default queue target capacity.</description> </property> <property> <name>yarn.scheduler.capacity.root.default.user-limit-factor</name> <value>1</value> <description> Default queue user limit a percentage from 0.0 to 1.0. </description> </property> <property> <name>yarn.scheduler.capacity.root.default.maximum-capacity</name> <value>100</value> <description> The maximum capacity of the default queue. </description> </property> <property> <name>yarn.scheduler.capacity.root.default.state</name> <value>RUNNING</value> <description> The state of the default queue. State can be one of RUNNING or STOPPED. </description> </property> <property> <name>yarn.scheduler.capacity.root.default.acl_submit_applications</name> <value>*</value> <description> The ACL of who can submit jobs to the default queue. </description> </property> <property> <name>yarn.scheduler.capacity.root.default.acl_administer_queue</name> <value>*</value> <description> The ACL of who can administer jobs on the default queue. </description> </property> <!--dailyTask --> <property> <name>yarn.scheduler.capacity.root.dailyTask.capacity</name> <value>70</value> <description>Default queue target capacity.</description> </property> <property> <name>yarn.scheduler.capacity.root.dailyTask.user-limit-factor</name> <value>1</value> <description> Default queue user limit a percentage from 0.0 to 1.0. </description> </property> <property> <name>yarn.scheduler.capacity.root.dailyTask.maximum-capacity</name> <value>100</value> <description> The maximum capacity of the default queue.. </description> </property> <property> <name>yarn.scheduler.capacity.root.dailyTask.state</name> <value>RUNNING</value> <description> The state of the default queue. State can be one of RUNNING or STOPPED. </description> </property> <property> <name>yarn.scheduler.capacity.root.dailyTask.acl_submit_applications</name> <value>hadoop</value> <description> The ACL of who can submit jobs to the default queue. </description> </property> <property> <name>yarn.scheduler.capacity.root.dailyTask.acl_administer_queue</name> <value>hadoop</value> <description> The ACL of who can administer jobs on the default queue. </description> </property> <!--hive --> <property> <name>yarn.scheduler.capacity.root.hive.capacity</name> <value>10</value> <description>Default queue target capacity.</description> </property> <property> <name>yarn.scheduler.capacity.root.hive.user-limit-factor</name> <value>1</value> <description> Default queue user limit a percentage from 0.0 to 1.0. </description> </property> <property> <name>yarn.scheduler.capacity.root.hive.maximum-capacity</name> <value>100</value> <description> The maximum capacity of the default queue.. </description> </property> <property> <name>yarn.scheduler.capacity.root.hive.state</name> <value>RUNNING</value> <description> The state of the default queue. State can be one of RUNNING or STOPPED. </description> </property> <property> <name>yarn.scheduler.capacity.root.hive.acl_submit_applications</name> <value>*</value> <description> The ACL of who can submit jobs to the default queue. </description> </property> <property> <name>yarn.scheduler.capacity.root.hive.acl_administer_queue</name> <value>*</value> <description> The ACL of who can administer jobs on the default queue. </description> </property> <property> <name>yarn.scheduler.capacity.node-locality-delay</name> <value>40</value> <description> Number of missed scheduling opportunities after which the CapacityScheduler attempts to schedule rack-local containers. Typically this should be set to number of nodes in the cluster, By default is setting approximately number of nodes in one rack which is 40. </description> </property> <property> <name>yarn.scheduler.capacity.queue-mappings</name> <value></value> <description> A list of mappings that will be used to assign jobs to queues The syntax for this list is [u|g]:[name]:[queue_name][,next mapping]* Typically this list will be used to map users to queues, for example, u:%user:%user maps all users to queues with the same name as the user. 进行过映射后,user只能访问对应的quue_name,后续的queue.name设置都没用了。 </description> </property> <property> <name>yarn.scheduler.capacity.queue-mappings-override.enable</name> <value>false</value> <description> If a queue mapping is present, will it override the value specified by the user? This can be used by administrators to place jobs in queues that are different than the one specified by the user. The default is false. </description> </property> ``` ## 3. 如何使用该队列 ```shell mapreduce:在Job的代码中,设置Job属于的队列,例如hive: conf.setQueueName("hive"); hive:在执行hive任务时,设置hive属于的队列,例如dailyTask: set mapred.job.queue.name=dailyTask; ``` ## 4. 刷新配置 生产环境中,队列及其容量的修改在现实中是不可避免的,而每次修改,需要重启集群,这个代价很高,如果修改队列及其容量的配置不重启呢: 1.在主节点上根据具体需求,修改好mapred-site.xml和capacity-scheduler.xml 2.把配置同步到所有节点上yarn rmadmin -refreshQueues 这样就可以动态修改集群的队列及其容量配置,不需要重启了,刷新mapreduce的web管理控制台可以看到结果。 注意:如果配置没有同步到所有的节点,一些队列会无法启用。 可以查看http://hadoop-master:8088/cluster/scheduler ![img](../image/hadoop/capacity-schedule.png) ```shell 队列容量=yarn.scheduler.capacity.<queue-path>.capacity/100 队列绝对容量=父队列的 队列绝对容量*队列容量 队列最大容量=yarn.scheduler.capacity.<queue-path>.maximum-capacity/100 队列绝对最大容量=父队列的 队列绝对最大容量*队列最大容量 绝对资源使用比=使用的资源/全局资源 资源使用比=使用的资源/(全局资源 * 队列绝对容量) 最小分配量=yarn.scheduler.minimum-allocation-mb 用户上限=MAX(yarn.scheduler.capacity.<queue-path>.minimum-user-limit-percent,1/队列用户数量) 用户调整因子=yarn.scheduler.capacity.<queue-path>.user-limit-factor 最大提交应用=yarn.scheduler.capacity.<queue-path>.maximum-applications 如果小于0 设置为(yarn.scheduler.capacity.maximum-applications*队列绝对容量) 单用户最大提交应用=最大提交应用*(用户上限/100)*用户调整因子 AM资源占比(AM可占用队列资源最大的百分比) =yarn.scheduler.capacity.<queue-path>.maximum-am-resource-percent 如果为空,设置为yarn.scheduler.capacity.maximum-am-resource-percent 最大活跃应用数量=全局总资源/最小分配量*AM资源占比*队列绝对最大容量 单用户最大活跃应用数量=(全局总资源/最小分配量*AM资源占比*队列绝对容量)*用户上限*用户调整因子 本地延迟分配次数=yarn.scheduler.capacity.node-locality-delay<code> ``` ## 5. 总结 本文介绍了如何配置yarn的容量调度器Capacity Scheduler配置。 本文完 * 原创文章,转载请注明: 转载自[Lamborryan](<http://www.lamborryan.com>),作者:[Ruan Chengfeng](<http://www.lamborryan.com/about/>) * 本文链接地址:http://www.lamborryan.com/hadoop-capacity-scheduler * 本文基于[署名2.5中国大陆许可协议](<http://creativecommons.org/licenses/by/2.5/cn/>)发布,欢迎转载、演绎或用于商业目的,但是必须保留本文署名和文章链接。 如您有任何疑问或者授权方面的协商,请邮件联系我。
PHP
UTF-8
1,066
2.671875
3
[]
no_license
<?php namespace App\Entity; use ApiPlatform\Core\Annotation\ApiResource; use App\Repository\BookRepository; use Doctrine\ORM\Mapping as ORM; /** * @ApiResource() * @ORM\Entity(repositoryClass=BookRepository::class) */ class Book { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(name="`id`",type="integer") */ private $id; /** * @ORM\Column(name="`title`",type="string", length=500, nullable=true) */ private $title; /** * @ORM\Column(name="`authors`",type="array", nullable=true) */ private $authors = []; public function getId(): ?int { return $this->id; } public function getTitle(): ?string { return $this->title; } public function setTitle(?string $title): self { $this->title = $title; return $this; } public function getAuthors(): ?array { return $this->authors; } public function setAuthors(?array $authors): self { $this->authors = $authors; return $this; } }
SQL
UTF-8
4,087
3.234375
3
[ "Apache-2.0" ]
permissive
-- phpMyAdmin SQL Dump -- version 5.0.2 -- https://www.phpmyadmin.net/ -- -- Servidor: localhost -- Tiempo de generación: 06-05-2020 a las 12:15:38 -- Versión del servidor: 10.4.11-MariaDB -- Versión de PHP: 7.4.5 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `roomview` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `empleados` -- CREATE TABLE `empleados` ( `EMP_NO` int(4) NOT NULL, `NOMBRE` varchar(25) DEFAULT NULL, `APELLIDO` varchar(14) DEFAULT NULL, `CLAVE` varchar(25) DEFAULT NULL, `DPTO` varchar(25) DEFAULT NULL, `TIPO_EMP` varchar(25) DEFAULT NULL, `EMAIL` varchar(25) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `empleados` -- INSERT INTO `empleados` (`EMP_NO`, `NOMBRE`, `APELLIDO`, `CLAVE`, `DPTO`, `TIPO_EMP`, `EMAIL`) VALUES (1000, 'ADMIN', 'ADMIN', '1000AdminA', 'ADMINISTRADOR', 'ADMIN', 'admin@gmail.com'), (1001, 'LUIS', 'GARCIA', '1001LuisG', 'MARKETING', 'JEFE', 'luisgarcia@gmail.com'), (1002, 'OLGA', 'PEREZ', '1002OlgaP', 'INFORMATICA', 'EMPLEADO', 'olgaperez@hotmail.com'), (1003, 'CESAR', 'LOPEZ', '1003CesarL', 'RRHH', 'JEFE', 'cesarlopez@gmail.com'), (1004, 'JULIAN', 'MONTES', '1004JulianM', 'ADMINISTRACION', 'EMPLEADO', 'julianmontes@gmail.com'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `reserva` -- CREATE TABLE `reserva` ( `id` int(11) NOT NULL, `title` varchar(255) NOT NULL, `descripcion` text NOT NULL, `color` varchar(255) NOT NULL, `textcolor` varchar(255) NOT NULL DEFAULT 'white', `start` text NOT NULL, `sala_no` int(11) NOT NULL, `emp_no` int(11) NOT NULL, `hora` text NOT NULL, `dia` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Volcado de datos para la tabla `reserva` -- INSERT INTO `reserva` (`id`, `title`, `descripcion`, `color`, `textcolor`, `start`, `sala_no`, `emp_no`, `hora`, `dia`) VALUES (1, 'Evento 1', 'celebrando', '#FFFF0F', '#00000', '2020-04-25 12:30', 1, 1001, '12:30', '2020-04-25'), (2, 'evento 2', 'hola ', 'blue', 'white', '2020-04-26 12:30', 3, 1001, '12:30', '2020-04-26 '), (3, 'pepe', 'prueba', 'red', 'white', '2020-05-01 10:30', 4, 1001, '10:30', '2020-05-01 '), (9, 'dsfds', 'dfdff', '#00dbfe', 'white', '2020-05-15 10:30', 2, 1001, '10:30', '2020-05-15 '), (20, 'Prueba 2', 'dsaffds', 'blue', 'white', '2020-05-14 10:30', 3, 1001, '10:30', '2020-05-14'), (22, 'sala 4', '', '#000000', 'white', '2020-05-14 10:30', 4, 1001, '10:30', '2020-05-14'), (23, 'cambiar', '', '#000000', 'white', '2020-05-08 12:19', 3, 1001, '12:19', '2020-05-08'), (24, 'cambiar', '', '#0043ff', 'white', '2020-05-07 03:16', 2, 1001, '03:16', '2020-05-07'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `salas` -- CREATE TABLE `salas` ( `SALA_NO` int(4) NOT NULL, `TIPO` varchar(25) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `salas` -- INSERT INTO `salas` (`SALA_NO`, `TIPO`) VALUES (1, 'VIDEOCONFERENCIA'), (2, 'ESTANDAR'), (3, 'ESTANDAR'), (4, 'VIDEOCONFERENCIA'); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `empleados` -- ALTER TABLE `empleados` ADD PRIMARY KEY (`EMP_NO`); -- -- Indices de la tabla `reserva` -- ALTER TABLE `reserva` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `salas` -- ALTER TABLE `salas` ADD PRIMARY KEY (`SALA_NO`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `reserva` -- ALTER TABLE `reserva` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=25; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Python
UTF-8
79
2.765625
3
[]
no_license
student={"name":"ashwin","age":23} print(student['name']) print(student["age"])
Java
UTF-8
1,142
2.328125
2
[]
no_license
package com.company.spring_rest_app.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.SessionAttribute; import javax.servlet.http.HttpSession; import java.time.Duration; import java.time.LocalDateTime; @Controller @RequestMapping("/time") public class TrackTimeController { @RequestMapping public String trackTime(@SessionAttribute("sessionStartTime") LocalDateTime startDateTime, Model model) { Duration duration = Duration.between(startDateTime, LocalDateTime.now()); model.addAttribute("sessionTimeDuration", duration.getSeconds()); return "time-page"; } @RequestMapping("/clear") public String clearTime(HttpSession session) { session.invalidate(); return "redirect:/time"; } // @RequestMapping("/clear") // public RedirectView clearTime(HttpSession session) { // session.invalidate(); // RedirectView rv = new RedirectView(); // rv.setUrl("/time"); // return rv; // } }
PHP
UTF-8
4,203
2.90625
3
[]
no_license
<?php require_once './Util/DataSource.php'; require_once './Util/Usuario.php'; class OperacoesBanco { private $linkDB; function __construct() { $this->linkDB = new DataSource(); } function __destruct() { $this->linkDB = NULL; } function inserirUser($obj) { $sql = "INSERT INTO usuario(nome, email, senha, imagemURL) VALUES(?, ?, ?, ?)"; //tratamento do sql injection $stm = mysqli_prepare($this->linkDB->con, $sql); if(!$stm) { return false; } $nome = $obj->getNome(); $email = $obj->getEmail(); $senha = md5($obj->getSenha()); $imagem = $obj->getImagemURL(); if(!$stm->bind_param("ssss", $nome, $email, $senha, $imagem)) { return false; } return $stm->execute(); } function getUser($id){ $resultado = mysqli_query($this->linkDB->con, "SELECT * FROM usuario WHERE id = ".$id); if ($resultado && mysqli_num_rows($resultado) == 1){ $dados = mysqli_fetch_assoc($resultado); $user = new Usuario($dados['email'], $dados['senha'], $dados['nome']); $user->setImagemURL($dados['imagemURL']); $user->setId($dados['id']); return $user; }else{ return null; } } function itemExiste($campo, $item, $tabela) { $resultado = mysqli_query($this->linkDB->con, "SELECT * FROM ".$tabela." WHERE ".$campo." = '".$item."'"); return $resultado && mysqli_num_rows($resultado) > 0; } function update($id, $campo, $valor){ $sql = "UPDATE usuario SET ".$campo." = ? WHERE ID = ".$id; //tratamento do sql injection $stm = mysqli_prepare($this->linkDB->con, $sql); if(!$stm) { return false; } if(!$stm->bind_param("s", $valor)) { return false; } return $stm->execute(); } function login($email, $senha){ $newSenha = md5($senha); $resultado = mysqli_query($this->linkDB->con, "SELECT * FROM usuario WHERE email = '".$email."' AND senha = '".$newSenha."'"); if ($resultado && mysqli_num_rows($resultado) == 1){ $dados = mysqli_fetch_assoc($resultado); $user = Array('email' => $dados['email'], 'imagemURL' => $dados['imagemURL'],'nome' => $dados['nome'], 'id' => $dados['id']); return $user; }else{ return null; } } function deleteUser($id){ $resultado = mysqli_query($this->linkDB->con, "DELETE FROM usuario WHERE id = ".$id); return $resultado; } function criarSala($nomeSala, $idUser){ $sql = "INSERT INTO sala(nome, idCriador) VALUES(?, ?)"; //tratamento do sql injection $stm = mysqli_prepare($this->linkDB->con, $sql); if(!$stm) { return false; } if(!$stm->bind_param("si", $nomeSala, $idUser)) { return false; } return $stm->execute(); } /* function solicitaSala($nomeSala, $idUser){ $sql = "INSERT INTO usersala(idUser, idCriador, aprovado) VALUES(?, ?, false)"; //tratamento do sql injection $stm = mysqli_prepare($this->linkDB->con, $sql); echo '<script>console.log("foi");</script>'; if(!$stm) { return false; } echo '<script>console.log("foi1");</script>'; $resultado = mysqli_query($this->linkDB->con, "SELECT id FROM sala WHERE nome = '".$nomeSala."'"); $idSala = mysqli_fetch_assoc($resultado)['id']; echo '<script>console.log("'.$idSala.'");</script>'; if(!$stm->bind_param("ii", $idUser, $idSala)) { return false; } return $stm->execute(); }*/ }
Markdown
UTF-8
2,020
2.984375
3
[ "MIT" ]
permissive
Fast Expression Evaluator Library (c++, .net) ==== Yet another Expression Evaluator, but with **compilation** into **native code** With this library you can evaluate math expressions fast and easily. Get Started: --- var expression = new ExpressionEvaluator("sqrt(r^2 - x^2)"); expression.SetVariableValue("r", 10); expression.SetVariableValue("x", 5); Console.WriteLine(expression.Execute()); Also you can see [Tests](https://github.com/DrA1ex/FEEL/tree/master/ExpressionEvaluator.Test), simple demo [project](https://github.com/DrA1ex/FEEL/blob/master/ExpressionCalculatorDemo/Program.cs), [benchmark](https://github.com/DrA1ex/FEEL/blob/master/ExpressionEvaluatorNetBenchmark/Program.cs), or advanced example [Curves Demo](https://github.com/DrA1ex/FEEL.CurveDemo). Installation: --- For all platforms: FEEL require Visual C++ 2015 Redistributable. You can download it from here: https://www.microsoft.com/download/details.aspx?id=48145 For .NET version: Install-Package Feel.Net For C++: See [releases](https://github.com/DrA1ex/FEEL/releases) section Features: --- 1. Easy extensible (you can add more operations if you want) 2. Fast (expression **compiling** into **native code**) 3. Powerful (you can use variables and change it without side effects) At this point Expression Evaluator supports only Windows platform. Compile isn't perfect now, but more faster, than generic solution. Some benchmarks: --- ``` Expression: "(cos(x)^0.5*cos(200*x)+abs(x)^0.5-0.7)*(4-x^2)^0.01" Start value: -1.5 End value: 1.5 Steps: 1000000 (1m) .NET Benchmark results: Library name Avg. time FEEL (this library): 343.42 ms Ciloci.Flee: 376.78 ms (9.72 % slower) NCalc: 3280.52 ms (855.26 % slower) C# compiled code: 194.35 ms (43.41 % faster) C++ Benchmark results: Library name Avg. time FEEL (this library): 223.8 ms C++ compiled code: 123.2 ms (81.3941% faster) ``` License: --- The MIT License
Java
UTF-8
1,254
2.75
3
[]
no_license
package chapter4; import EDU.oswego.cs.dl.util.concurrent.Callable; import java.lang.reflect.InvocationTargetException; /** * @author lili * @date 2022/6/19 10:46 */ public class FutureResult { // Fragments protected Object value = null; protected boolean ready = false; protected InvocationTargetException exception = null; public synchronized Object get() throws InterruptedException, InvocationTargetException { while (!ready) wait(); if (exception != null) throw exception; else return value; } public Runnable setter(final Callable function) { return new Runnable() { public void run() { try { set(function.call()); } catch (Throwable e) { setException(e); } } }; } synchronized void set(Object result) { value = result; ready = true; notifyAll(); } synchronized void setException(Throwable e) { exception = new InvocationTargetException(e); ready = true; notifyAll(); } // ... other auxiliary and convenience methods ... }
C++
UTF-8
636
2.59375
3
[ "Apache-2.0" ]
permissive
#ifndef TREEMODELITEM_H #define TREEMODELITEM_H #include <QStringList> class TreeModel; class TreeModelItem { public: TreeModelItem(QString label); ~TreeModelItem(); QString label() const; void setLabel(QString label); void setData(QStringList data); QVariant data(int index); void setChildrenColumns(QStringList columns); void addChild(QString label, QStringList data, QString path = QString()); bool hasChildren(); TreeModel *children(); void printItem(int tab = 0); private: QString m_label; QStringList m_data; TreeModel *m_children; }; #endif // TREEMODELITEM_H
Markdown
UTF-8
4,230
2.75
3
[ "MIT" ]
permissive
--- layout: post title: Postdoc on regional coastal ocean modelling (Vancouver Island, Canada) subtitle: University of Victoria tags: [postdoc, Canada, coastal ocean, numerical modelling, climate change] comments: false --- We are seeking a postdoctoral scholar for a Regional Coastal Ocean Modelling position investigating the fate of Canada's coastal oceans over the next century. The scholar will (1) produce high-resolution regional ocean models of Canada's coastlines (using ROMS and CICE), and (2) assess how these coastal oceans will respond to a warming climate by subjecting these regional ocean models to downscaled global climate model projections. Regional ocean models will be developed first for the west coast (British Columbia), followed by the eastern Arctic and Atlantic Canada. This work is part of a larger 3-year project funded by the NSERC Alliance program on the blue carbon potential of Canada's coastal marine ecosystems, and how environmental change will impact blue carbon storage in the future. We expect the successful candidate to have the following background and expertise: * A PhD in Atmospheric Sciences, Physical Oceanography, Applied Mathematics, or a related field. * Extensive experience with regional ocean modeling using ROMS; * Experience with software development for ocean and/or climate modeling applications; * Experience with version control of community-developed codes (e.g. git); * Experience with code development in Fortran; and * Experience working as a collegial team member in an interdisciplinary group of scientists. Experience with CICE and polar ocean modeling are a plus, but not required. The postdoctoral fellow will be expected to publish manuscripts in high-quality peer-reviewed journals, and present their findings at national and international scientific conferences. This position is supported through the University of Victoria, the National Science and Engineering Council of Canada (NSERC), and Fisheries and Oceans Canada (DFO). The position will be supervised primarily by Prof. Hansi Singh, head of the Climate Dynamics research group in the School of Earth and Ocean Sciences at the University of Victoria (https://hansialice.github.io<https://hansialice.github.io/>), and advised by Prof. Parker MacReady, head of the Coastal Ocean Modeling Group at the University of Washington School of Oceanography (https://faculty.washington.edu/pmacc/cmg/cmg.html). The postdoctoral fellow will also work closely with Prof. Julia Baum (Dept. of Biology at the University of Victoria; https://www.juliakbaum.org<https://www.juliakbaum.org/>) and Prof. Mary O?Connor (Dept. of Zoology at the University of British Columbia; http://oconnorlab.weebly.com<http://oconnorlab.weebly.com/>), who will be applying coastal projections from this research to kelp and seagrass species distribution models and projections. The postdoctoral fellow will sit at the School of Earth and Ocean Sciences at the University of Victoria on beautiful Vancouver Island in British Columbia, and will have the opportunity to collaborate locally with scientists at several nearby research centres, including the Canadian Centre for Climate Modeling and Analysis (CCCMA), the Pacific Climate Impacts Consortium (PCIC), and the Pacific Institute for Climate Solutions (PICS). Funding is available for up to three years (with continued funding subject to a yearly performance review). The position will include a competitive salary and a full benefits package (including an allowance for relocation). We especially encourage applications from members of groups experiencing barriers to equity in the physical sciences (women, under-represented minorities, LGBTQIA individuals, persons with disabilities). Please contact Prof. Hansi Singh (hansingh@uvic.ca) with questions. Interested applicants should submit the following material to Prof. Singh: (1) a cover letter, (2) an up-to-date CV, (3) two recent publications demonstrating the required background and expertise for the position, and (4) contact information for three professional references. Applications will be reviewed starting August 22, 2022, and will be accepted until the position is filled. Proposed Start Date: Fall 2022.
Markdown
UTF-8
582
3.078125
3
[]
no_license
# The DOM Spend the next 10 minutes reading through the following introduction to the DOM https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction Answer the following questions 1. What is the DOM? 1. What does the DOM do? 1. Is the DOM part of JavaScript? 1. Why might JavaScript need the DOM? If you answer all the above you may continue with these 1. How do you access the DOM? 1. What does the "window" object represent? 1. What does the "document" object represent? 1. What is an "element"? 1. What is a "node list"? 1. What is an "attribute"?
Java
IBM852
3,744
2.359375
2
[]
no_license
package com.virtualcondo.controllers; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.virtualcondo.models.IndexAdministrador; import com.virtualcondo.models.Usuario; import com.virtualcondo.persistencia.DAOAdministrador; import com.virtualcondo.persistencia.UsuarioDAO; import com.virtualcondo.persistencia.VisitaDAO; @WebServlet("/login") public class Login extends HttpServlet { private static final long serialVersionUID = 1L; public Login() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); Usuario u = (Usuario) session.getAttribute("Usuario"); if(u == null) { RequestDispatcher view = request.getRequestDispatcher("WEB-INF/jsp/login.jsp"); view.forward(request, response); } else { if(u.getTipoUsu().getId() == 1) { request.setAttribute("visitas", new VisitaDAO().listarVisitasMorador(u.getId())); RequestDispatcher view = request.getRequestDispatcher("WEB-INF/jsp/morador/index-morador.jsp"); view.forward(request, response); } else if(u.getTipoUsu().getId() == 2) { IndexAdministrador iA = new DAOAdministrador().popularIndexAdmin(); iA.setVisitas(new VisitaDAO().listarVisitas()); request.setAttribute("adminPage", iA); RequestDispatcher view = request.getRequestDispatcher("WEB-INF/jsp/admin/index-admin.jsp"); view.forward(request, response); } else if(u.getTipoUsu().getId() == 3) { RequestDispatcher view = request.getRequestDispatcher("WEB-INF/jsp/colaborador/index-colaborador.jsp"); view.forward(request, response); } } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String email = request.getParameter("email"); String senha = request.getParameter("senha"); Usuario u = null; try{ u = new UsuarioDAO().autenticarUsuario(senha, email); }catch(RuntimeException e) { request.setAttribute("msg", "Servio indisponvel. Tente novamente mais tarde<br>" + e.getMessage()); request.setAttribute("email", email); request.setAttribute("senha", senha); RequestDispatcher view = request.getRequestDispatcher("WEB-INF/jsp/login.jsp"); view.forward(request, response); return; } if(u != null) { HttpSession session = request.getSession(); session.setAttribute("Usuario", u); if(u.getTipoUsu().getId() == 1) { request.setAttribute("visitas", new VisitaDAO().listarVisitasMorador(u.getId())); RequestDispatcher view = request.getRequestDispatcher("WEB-INF/jsp/morador/index-morador.jsp"); view.forward(request, response); } else if(u.getTipoUsu().getId() == 2) { IndexAdministrador iA = new DAOAdministrador().popularIndexAdmin(); iA.setVisitas(new VisitaDAO().listarVisitas()); request.setAttribute("adminPage", iA); RequestDispatcher view = request.getRequestDispatcher("WEB-INF/jsp/admin/index-admin.jsp"); view.forward(request, response); } else if(u.getTipoUsu().getId() == 3) { RequestDispatcher view = request.getRequestDispatcher("WEB-INF/jsp/colaborador/index-colaborador.jsp"); view.forward(request, response); } } else { request.setAttribute("msg", "Email ou senha incorreto."); RequestDispatcher view = request.getRequestDispatcher("WEB-INF/jsp/login.jsp"); view.forward(request, response); } } }
C++
UTF-8
2,981
2.78125
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <fstream> #include <sstream> #include <vector> #include <cstdlib> #include <cstdio> #include <sys/wait.h> #include <iostream> using namespace std; int main(int argc, char* argv[]) { //Initial check for arguments if (argc != 2) { perror("Only one email argument."); exit(1); } int numFiles = 0; int numProcs = 0; int link[2]; char listChars[4096]; char procChars[4096]; vector<char*> homeworkElements; pid_t pid; // Fork pipe(link); pid = fork(); // If child if (pid == 0) { dup2(link[1], STDOUT_FILENO); close(link[0]); close(link[1]); execl("/bin/ls", "ls", (char *)0); } else { close(link[1]); int nbytes = read(link[0], listChars, sizeof(listChars)); char* fileName = strtok(listChars, "\n"); while (fileName != NULL) { homeworkElements.push_back(fileName); fileName = strtok(NULL, "\n"); } numFiles = homeworkElements.size(); wait(NULL); } // Fork pipe(link); pid = fork(); // If child if (pid == 0) { dup2(link[1], STDOUT_FILENO); close(link[0]); close(link[1]); execl("/bin/ps", "ps", "-e", (char *)NULL); } else { close(link[1]); int nbytes = read(link[0], procChars, sizeof(procChars)); char* procInfo = strtok(procChars, "\n"); while (procInfo != NULL) { homeworkElements.push_back(procInfo); procInfo = strtok(NULL, "\n"); } numProcs = homeworkElements.size() - numFiles - 1; wait(NULL); } // Create output.dat file to write to ofstream outputFile; outputFile.open("./output.dat"); // Write to outputFile for (int i = 0; i < homeworkElements.size(); i++) { outputFile << homeworkElements[i] << "\n"; } stringstream convertOne; convertOne << numFiles; string numFileStr = convertOne.str(); stringstream convertTwo; convertTwo << numProcs; string numProcsStr = convertTwo.str(); // Hardcoded subject line string subject = "There are " + numFileStr + " files and " + numProcsStr + " processes."; // Read from output.dat std::ifstream ifs("output.dat"); std::string msg((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>())); char command[1024]; sprintf(command, "mail -s '%s' '%s'", subject.c_str(), argv[1]); FILE *fp_mail = popen(command, "w"); // Send an error if fp_mail isn't opened correctly if (fp_mail == NULL) { perror("Failed to send mail."); exit(1); } // Compile whole email fprintf(fp_mail, "To: %s\n", argv[1]); fprintf(fp_mail, "Subject: %s\n\n", subject.c_str()); fwrite(msg.c_str(), 1, strlen(msg.c_str()), fp_mail); fwrite(".\n", 1, 2, fp_mail); // Try and close fp_mail and check for errors if (pclose(fp_mail) != 0) { fprintf(stderr, "Could not close file because of errors.\n"); } // Close outputFile.dat outputFile.close(); return 0; }
JavaScript
UTF-8
2,745
2.765625
3
[]
no_license
const { BillModel } = require("../billModel"); const { ObjectId } = require("mongodb"); const moment = require("moment"); const BillList = async () => { const billList = await BillModel.find({}).catch((err) => { throw new Error("Get bill failed"); }); return billList; }; const getBillByID = async (id) => { const bill = await BillModel.find({ _id: ObjectId(id) }).lean(); return bill; }; const saveBill = async (bill) => { const newBill = new BillModel(bill); await newBill.save(); }; const getTotalByMonths = async () => { const bills = await BillModel.find({}).catch((err) => { throw new Error("Get bill list failed!!"); }); var today = moment(); arrLength = today.month(); var months = Array(arrLength + 1); for (let i = 0; i < arrLength + 1; i++) { months[i] = {}; months[i].total = 0; months[i].label = moment(i + 1, "MM").format("MMMM"); } console.log(bills.length); bills.forEach((bill) => { if (moment(bill.date, "DD/MM/YYYY").year() == today.year()) { var month = moment(bill.date, "DD/MM/YYYY").month(); months[month].total += bill.total; } }); console.log(months); return months; }; const getTotalByDays = async () => { const bills = await BillModel.find({}).catch((err) => { throw err; }); var today = moment(); arrLength = today.date(); var days = Array(arrLength + 1); for (let i = 0; i < arrLength + 1; i++) { days[i] = {}; days[i].label = i + 1; days[i].total = 0; } bills.forEach((bill) => { if ( (moment(bill.date, "DD/MM/YYYY").month() == today.month()) & (moment(bill.date, "DD/MM/YYYY").year() == today.year()) ) { var billDay = moment(bill.date, "DD/MM/YYYY").date(); days[billDay].total += bill.total; } }); return days; }; const getDrinkStatistic = async () => { const bills = await BillModel.find({}).catch((err) => { throw err; }); var productArray = []; var saleArray = []; bills.forEach((bill) => { var products = bill.productList; products.forEach((product) => { if (productArray.includes(product.name)) { var index = productArray.indexOf(product.name); saleArray[index] += product.quantity; } else { productArray.push(product.name); saleArray.push(product.quantity); } }); }); return { productArray, saleArray }; }; module.exports = { BillList, getBillByID, saveBill, getTotalByMonths, getTotalByDays, getDrinkStatistic, };
Java
UTF-8
663
1.765625
2
[]
no_license
package com.pingidentity.adapters.htmlform.pwdreset.model; import org.sourceid.util.log.AttributeMap; public class GeneratedCode { private AttributeMap attributeMap; private String code; public GeneratedCode(AttributeMap map, String code) { this.attributeMap = map; this.code = code; } public AttributeMap getAttributeMap() { return this.attributeMap; } public String getCode() { return this.code; } } /* Location: D:\workhouse\PasswordReset\myformadapter\src\!\com\pingidentity\adapters\htmlform\pwdreset\model\GeneratedCode.class * Java compiler version: 8 (52.0) * JD-Core Version: 0.7.1 */
Java
UTF-8
2,313
2.734375
3
[]
no_license
package tr.edu.metu.thesis.gson; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; public class AnswerAdapter extends TypeAdapter<GsonParticipantAnswerList>{ private AnswerItemAdapter _itemAdapter = new AnswerItemAdapter(); public static class AnswerItemAdapter extends TypeAdapter<GsonParticipantAnswer>{ @Override public GsonParticipantAnswer read(JsonReader reader) throws IOException { GsonParticipantAnswer answer = null; if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return null; } if(reader.hasNext()){ reader.beginObject(); reader.nextName(); int id = reader.nextInt(); reader.nextName(); String value = reader.nextString(); reader.nextName(); int selectedOption = reader.nextInt(); reader.endObject(); answer = new GsonParticipantAnswer(id); answer.setSelectedOption(selectedOption); answer.setValue(value); return answer; } return null; } @Override public void write(JsonWriter writer, GsonParticipantAnswer obj) throws IOException { } } @Override public GsonParticipantAnswerList read(JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return null; } List<GsonParticipantAnswer> answers = new ArrayList<GsonParticipantAnswer>(); reader.beginArray(); while(reader.hasNext()){ GsonParticipantAnswer answer = _itemAdapter.read(reader); answers.add(answer); } reader.endArray(); return new GsonParticipantAnswerList(answers); } @Override public void write(JsonWriter writer, GsonParticipantAnswerList obj) throws IOException { } }
Markdown
UTF-8
9,364
3.0625
3
[]
no_license
# 人生是场长跑,你是同学中的哪一个? 【长投学堂14天小白训练营——82期11班】 2019年6月11日 星期二 早上7:00 同学们早上好,新的一天又开始了~ 今天是开营第二天,你按时学习了吗? 每年放假回家,最累不是陪爸妈,而是同学会! 我们来看看长投人眼里的同学会又发生了哪些与理财投资相关的事情呢? 同学会真的是一个神奇的组织,刚毕业那几年是为了联络感情,几年后因为大家的境遇都不相同,共同话题是越来越少了,有的只是各自的吐槽。 这不,班班今年参加同学会的时候,A同学说:“我在市内买了一套房子,现在每个月要还4000的房贷,这样的日子要30年,遥遥无期啊。” B同学说:“现在生娃了才知道是真的费钱啊,奶粉、尿不湿、玩具,真的无底洞啊” 班班还记得A同学当班长时的飒爽风姿,B同学作为学习委代表在讲台上演讲的自信。 现在好像被变了一个人,人生真的是变化莫测啊。 今天,班班推荐你读读【长投创始人】小熊老师(也称为暖手同学)的犀利之作,看看他对学生会有什么样的体会?又从同学会中误出了什么呢? 他的语言风趣直白发人深思!涉及到的话题不仅仅是全员关心的话题,更是一个人生必须认真面对、且深思的话题——房产。《人生是场长跑,你是同学中的哪一个》送给你。 【晨读原文】 人生是场长跑,你是同学中的哪一个? 这次春节,见了几个高中同学,也参加了一次同学会。 首先大家知道同学会的主要目的吗? 高中同学会,一般目的有三个: 1、男同学炫耀自己多么多么的成功 2、女同学炫耀自己还没老,或者孩子多么多么成功 3、续前缘打旧炮。 第三点估计大家比较迷惑,举个例子: A男高中的时候崇拜校花B,但是A男长的比较挫,又不参与任何学校活动等等,也不敢和女生说话的。所以那时候B当然看不上A,A也只能yy 但是现在这么多年过去了,A突然功成名就了,B却嫁了一个俗夫,这时候B就觉得A也不错了。A么,顺便放下心头的一块大石。 今天我们不讲第二第三点了,呵呵,有兴趣的你们可以自己讨论。 我们只讲第一点。 要知道,高中时候,大家的世界观人生观基本上已经形成了,但是高中时候成绩好的,过了20年来看,未必是事业上最成功的 我这里举四个人的例子: A男,我最好的朋友,大学毕业就进入设计院,作为他们系最好的学生被某建筑设计院看中。 他当年没考上研究生竟然也是他的运气,因为和他同届考上研究生的人毕业后成为他的下属的下属。37岁当上设计院院长,成为该设计院最年轻院长。 现在呢?现在他每天的工作就是劝手下人辞职,去年他们设计院有150人,现在只有60人了。 据他估计,等到他把这些人全部砍掉之后,领导就要砍掉他了。他还有12年的房贷要还,基本上没有积蓄。 B男,也是我最好的朋友,高三直升复旦数学系,硕博连读。数学系博士毕业,进入四大会计师事务所,36岁成为高级经理Senior Manager。 当时刚刚进入会计事务所的时候,年薪就30万了。现在年薪接近百万。五年前在上海市中心老西门买房,320平米,1200万的房子。他是一个纯理工男,但是要成为合伙人,必须要出去谈生意,有指标的。 他去年年中开始无薪休假,在家休养,因为得了轻度抑郁。后来因为房贷和家庭的压力,今年年初又开始上班了,现在估计还有1000多万的房贷要还。 C男,交大硕士毕业,进入全球顶尖的咨询公司,一干就是20年。 这次同学聚会,老的我们几乎都不认识了。现在还奋战在咨询行业第一线,显然不太得志,所以一直郁郁寡欢。 D男,他的经历最好玩了。交大本科毕业,放弃研究生机会,进入IBM做销售,当时被我的几位同学鄙夷说吃青春饭。 后来因为和IBM另一个女员工好上了并结婚,不得不从IBM辞职,跳槽到HP。7年前,被人底薪挖到一个信息安全公司,一步步从高层做到了CEO。 这里要说的是D男,他从2003年开始,当时大家手里有点积蓄的都开始买房了。 A男、B男和C男都买了一套三室两厅的房子,因为当时房价不贵,他们收入又高。D男却花了同样的钱,买了两套房子,一个两室一厅,一个一室一厅。 等到2009年中国金融危机的时候,A男和D男同时卖出了手中的房产(都升值了),A男在外环边买了一套别墅,D男考虑良久,买了陆家嘴的仁恒滨江花园一套小房子和太原路的一套小房子。 2011年B男卖出了自己的房子,买入了老西门的那套豪宅。 现在,他们三人的境遇已经完全不同了。A男和B男现在被房贷压的喘不过气了,B男为了解决房贷问题,自己全家搬到小房子,把老西门豪宅出租出去。 A男前两天还问我借钱,被我拒绝了。 D男现在也准备卖出两套房子中的一套,不过他是为了投资海外房产 各个阶段,他们几个各领风骚: 1.大学阶段 - C男最风光,因为成绩最好 2.大学毕业后 - A男最风光,因为一进设计院就被委以重任,刚刚签约就被派出去面试别人。工资也远远比别人要高。 3.大学毕业后五年到10年 - B男风光期来了,因为他毕业比别人晚,但是一进四大工资就高出很多 4.大学毕业后10年 - D男一步步赶上并超过以上三位了。 从上面这么一个萝莉啰嗦的故事,我想说明什么呢? 1. 人生是一个长跑,不到最后你不知道谁赢谁输的。 2、短期内靠高负债你有可能很风光,但最后还是要付出代价的 3、决定一个人成功与否的,不是你的学历,不是你的工作,不是你的关系,而是你的思维。这是我深切的感受到的 A男和B男,属于始终没有这个思维的。他们都是我最好的朋友,我也试图和他们去说过,但是结果就...,反正差点吵起来吧,哈哈。 但是D男却很清楚一些人生财富的哲理,比如: 1、延迟满足,宁愿住小房子,不要摆阔 2、房产是投资,而不仅仅是炫耀或者享受用的 3、别人恐慌的时候要贪婪。 D男还有一些很有意思的投资,比如他自己做过风投,投过一两家创业公司,可惜没成功,但是他也及时收手。 他还投资过私募基金,我给A、B、D三个都布道过我的私募,A没钱,B怕风险(他的P2P上刚刚吃过亏),D准备把其他私募的钱取出来投到我这里。 他明白分散投资的理念,上次和我咨询,我们把他的资产理了一遍,发觉他的房产太多了,而股权类的比较少。所以他决定要重新分配财产。 所以最后我感叹说,他的成功,不是偶然的。 顺便说一下,A、B、D的三个人的买车经历: 1. A先是买了一辆北京吉普,用来泡妞。后来又换成了斯柯达。 2. B先是买了一辆标致307,后来换成奥迪A4,今年又换成宝马X5 3. D先是买了一辆标致307,一直开到现在 最后,总结一下,人生的财富终值取决于你是否有投资的理念,和你的收入等有一点关系,但关系不大。 各位来长投学习的,在我看来,只要别走上歪路,不要想着一步登天的超越你的同学,不出5年10年必将超过同龄人。 【班班领读】 这篇文章是小熊老师参加了一场同学会后的真实感悟。 看过老板娘水媚物语的《30岁前的每一天》的小伙伴,想必都知道了,我们的小熊老师在老板娘的眼里又叫暖手同学,仅仅是因为小熊老师的手好暖和哦,给水媚姐的那一个冬天带去了温暖。 人生是场长跑。晨读里,跑在这个跑道上的是4位男同学的故事。好吧,不得不承认,原来男人与男人之间也是相当的八卦哈。 文章中,讲述了A、B、C、D四位男生,从毕业一路走到中年的四种不同经历。有高开低走的,有曾经辉煌的,有变成垃圾股的,也有成为杠杠潜力股的。想一想,你现在又处在人生中的哪一段呢? 那么,到底是什么让同一个班级走出来的男生拉开如此大的差距呢?看到最后发现,原来男生也是买买买哒。当然,男生买买买的理念,我们倒是也可以借鉴一下,看一下一贯以更理性的形象出现的男性的购买观念。 首先,我个人认为ABCD四个人对待财富的不同态度造成了他们当下的不同情况。 决定一个人成功与否的,不是你的学历,不是你的工作,不是你的关系,而是你的思维! 看ABC 某个时段内有可能很风光,但是谁才是笑到最后的人呢?? 或许我们一直默默无闻,从未风光过,但是记住这场长跑才刚刚开始!我们也有机会像D一样实现弯道超车! 因为是长跑,所以要有打持久战的气度,徐图之的耐心和弯道超车的信心!
Java
UTF-8
2,303
2.40625
2
[]
no_license
package mattmess.miscarrows.item; import java.util.List; import mattmess.miscarrows.MiscArrows; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; public class ItemMiscArrow extends Item { private IIcon fire, ice, slime, potion, teleport, explosive, item; public ItemMiscArrow() { this.setUnlocalizedName("misc_arrow"); this.setTextureName("miscarrows:misc_arrow"); this.setCreativeTab(MiscArrows.tab); this.hasSubtypes = true; } @Override public IIcon getIconFromDamage(int damage) { switch (damage) { case 1: return fire; case 2: return ice; case 3: return slime; case 4: return potion; case 5: return teleport; case 6: return explosive; case 7: return item; } return super.getIconFromDamage(damage); } public void registerIcons(IIconRegister icon) { super.registerIcons(icon); fire = icon.registerIcon("miscarrows:misc_arrow_fire"); ice = icon.registerIcon("miscarrows:misc_arrow_ice"); slime = icon.registerIcon("miscarrows:misc_arrow_slime"); potion = icon.registerIcon("miscarrows:misc_arrow_potion"); teleport = icon.registerIcon("miscarrows:misc_arrow_teleport"); explosive = icon.registerIcon("miscarrows:misc_arrow_explosive"); item = icon.registerIcon("miscarrows:misc_arrow_item"); } @Override public String getUnlocalizedName(ItemStack itemStack){ String name = getUnlocalizedName(); switch(itemStack.getItemDamage()){ case 1: return name + ".fire"; case 2: return name + ".ice"; case 3: return name + ".slime"; case 4: return name + ".potion"; case 5: return name + ".teleport"; case 6: return name + ".explosive"; case 7: return name + ".item"; } return name + ".normal"; } @Override public void getSubItems(Item item, CreativeTabs tab, List list) { list.add(MiscArrows.fireArrow); list.add(MiscArrows.iceArrow); list.add(MiscArrows.slimeArrow); //list.add(MiscArrows.itemArrow); //list.add(MiscArrows.potionArrow); list.add(MiscArrows.teleportArrow); list.add(MiscArrows.explosiveArrow); } }
Markdown
UTF-8
3,212
3.28125
3
[]
no_license
## Inspiration This time around, we wanted to focus on the social impact of our product and we thought about how great it would be to make a website that teaches you how to code. We pulled inspiration from sites like CodeHS and are making plans to expand on that. ## What it does Codegrounds allows someone to learn langauges (in this case we only implemented basic JavaScript for now) through interactive lessons and tutorials. Users will have access to a code editor within the browser as well, allowing them to write code and try it out. Additionally, it keeps track of the user's progress and the code that they write. ## How we built it We split the entire project into two things, a backend and frontend. The backend is written in TypeScript and uses Koa and PostgreSQL (TypeORM) to store users, run code, and serve as a RESTful API that could be consumed by the client. It runs on Docker containers in a cluster swarm hosted on a VPS. It's then hosted on a domain via Nginx and Cloudflare. The frontend is written using JavaScript and TypeScript and it is a React application. It handles most of the UI and makes API calls where necessary. Additionally, we implemented the monaco-editor which is the code editor used within Visual Studio Code, since it has support for the browser. ## Challenges we ran into One of the biggest challenges for the backend and frontend were authentication. Using Koa Session, the backend was supposed to set a session cookie, however React has strict rules on what cookies it will accept so it took hours to try and get it working. Another challenge we faced was getting the actual text editor and the code runner working. The code has to be sanitized and updated before it can be run since it has tests that it has to pass to be considered valid. Additionally, we also had to prevent bad code from being run (such as an infinite while loop) that could potentially break the server. ## Accomplishments that we're proud of We are proud of the pace that we managed to work with for this project. Towards the end of Saturday, we hadn't made much progress however today we were able to get many of the challenging things like code saving and validation done. We are also proud of the fact that we managed to get the authentication and code runners working, because they were a really big challenge. Additionally, we were at somewhat of a disadvantage because we had 3 members on our team instead of 4. ## What we learned We learned a lot about the React APIs especially stuff like state, mounting, and dependencies. We also learned that functional programming is not a good idea for React because it makes stuff harder. ## What's next for Codegrounds We have plans to expand it and probably rewrite it because it's built on code written mostly between 1 and 6 AM. Multiple choice questions were somewhat implemented so we want to build off of that and also introduce other types of lessons and content such as videos, images, and interactive code sessions. Additionally we had some plans for potential live collaboration, we aren't too sure about that yet. We want to support many langauges and probably focus on marketing for this product as we believe it has a place.
Python
UTF-8
6,360
2.65625
3
[]
no_license
from sklearn.feature_extraction.text import CountVectorizer from sklearn.metrics.pairwise import cosine_similarity from sklearn.feature_extraction.text import TfidfVectorizer import pickle import dill import math from math import log parse_fields = ['WORK EXPERIENCE', 'EDUCATION', 'SKILLS', 'AWARDS', 'CERTIFICATIONS', 'ADDITIONAL INFORMATION'] companies = ['amazon', 'apple', 'facebook', 'ibm', 'microsoft', 'oracle', 'twitter'] num_category = 7 num_company = 7 train1_size = 100 train2_size = 50 test_size = 50 def my_normalize(m): for i in range(num_category): for j in range(num_company): m[i][j] = m[i][j] + 0.001 for i in range(num_category): sum = 0 for j in range(num_company): sum = sum + m[i][j] for j in range(num_company): m[i][j] = m[i][j] / sum # for i in range(num_category): # minscore = 2 # maxscore = -1 # # for j in range(num_company): # if m[i][j] < minscore: # minscore = m[i][j] # if m[i][j] > maxscore: # maxscore = m[i][j] # minscore = minscore * 0.8 # maxscore = maxscore + minscore * 0.2 # diff = maxscore - minscore # if diff == 0: # return m # for j in range(num_company): # m[i][j] = (m[i][j]-minscore)/diff return m def my_col_normalize(m): for i in range(num_category): for j in range(num_company): m[i][j] = m[i][j] + 0.001 for i in range(num_company): sum = 0 for j in range(num_category): sum = sum + m[j][i] for j in range(num_category): m[j][i] = m[j][i] / sum return m def get_sim_vector(tfidf, tfidf_matrix, doc): response = tfidf.transform([doc]) sim = cosine_similarity(response, tfidf_matrix) return sim[0] def get_class(sim): cur_max = -1 max_index = 0 for j in range(num_company): if sim[j] > cur_max: cur_max = sim[j] max_index = j return max_index with open('resume_data.pkl', 'rb') as input: all_resumes = dill.load(input) for i in range(num_category): for j in range(num_company): for d in range(len(all_resumes[i][j])): all_resumes[i][j][d] = all_resumes[i][j][d].lower().replace(companies[j], '') ######################################################################### # the naive TF-IDF ######################################################################### score_matrix = [[0 for i in range(num_company)] for j in range(num_company)] correct = 0.0 total = 0.0 train_set = [] for c in range(num_company): doc = '' for i in range(num_category): for d in range(train1_size): doc = doc + all_resumes[c][d][i] train_set.append(doc) tfidf_vectorizer = TfidfVectorizer() tfidf_matrix_train = tfidf_vectorizer.fit_transform(train_set) print "--------- Simple TF-IDF approach----------" for c in range(num_company): #print c for d in range(test_size): doc = '' for i in range(num_category): idx = train1_size + train2_size + d doc = doc + all_resumes[c][idx][0] response = tfidf_vectorizer.transform([doc]) sim = cosine_similarity(response, tfidf_matrix_train) final_score = sim[0] print "Cosine similarity", final_score # cur_max = -1 # max_index = 0 # for j in range(num_company): # if final_score[j] > cur_max: # cur_max = final_score[j] # max_index = j # total = total + 1 # if max_index == c: # correct = correct + 1 # print "" # print 'Naive tf-idf score: ' + str(correct / total) ################################################################################## # weighted categorical TF-IDF ################################################################################## print "------- Weighted TF-IDF----------" score_matrix = [[0 for i in range(num_company)] for j in range(num_company)] tfidfs = [] tfidf_trains = [] for i in range(num_category): # print 'category:' + str(i) train_set = [] for c in range(num_company): doc = '' for d in range(train1_size): doc = doc + all_resumes[c][d][i] train_set.append(doc) tfidf_vectorizer = TfidfVectorizer() tfidfs.append(tfidf_vectorizer) tfidf_matrix_train = tfidf_vectorizer.fit_transform(train_set) tfidf_trains.append(tfidf_matrix_train) for c in range(num_company): score = 0.0 for d in range(train2_size): idx = train1_size + d test_doc = all_resumes[c][idx][i] sim = get_sim_vector(tfidf_vectorizer, tfidf_matrix_train, test_doc) if get_class(sim) == c: score = score + 1 score = score / train2_size / (1.0 / num_company) score_matrix[i][c] = score score_matrix = my_normalize(score_matrix) score_matrix = my_col_normalize(score_matrix) print score_matrix for i in range(num_category): for j in range(num_company): round(score_matrix[i][j], 3), print ' ' correct = 0 total = 0 for c in range(num_company): for d in range(test_size): test_matrix = [[0 for i in range(num_company)] for j in range(num_company)] for i in range(num_category): idx = train1_size + train2_size + d test_doc = all_resumes[c][idx][i] response = tfidfs[i].transform([test_doc]) sim = cosine_similarity(response, tfidf_trains[i]) score = sim[0] test_matrix[i] = score test_matrix = my_normalize(test_matrix) #print test_matrix final_score = [] for j in range(num_company): s = 10000000.0 for i in range(num_category): s = s * (0.1 + score_matrix[i][j]) * (0.1 + test_matrix[i][j]) # s = s*(0.3+test_matrix[i][j]) final_score.append(s) cur_max = -1 max_index = 0 for j in range(num_company): if final_score[j] > cur_max: cur_max = final_score[j] max_index = j total = total + 1 if max_index == c: correct = correct + 1 # print "" # print 'weighted categorical TF-IDF: ' + str(correct * 1.0 / total)
JavaScript
UTF-8
5,074
2.890625
3
[]
no_license
function downloadCSV() { // se realizeaza download-ul in format CSV const rows = [ getHeaders(), getValues() ]; // si iau informatiile din chart-uri if (rows[1] !== null) { // daca avem informatii in chart-uri let csvContent = "data:text/csv;charset=utf-8,"; rows.forEach(function (rowArray) { // le parcurgem let row = rowArray.join(","); csvContent += row + "\r\n"; // si creeam un string in format csv }); var encodedUri = encodeURI(csvContent); // apoi punem informatiile intr-un fisier, si il descarcam var link = document.createElement("a"); link.setAttribute("href", encodedUri); link.setAttribute("download", "csvData.csv"); document.body.appendChild(link); link.click(); } } function downloadXML() { // descarcarea in format XML // semana cu cea in CSV const data = getHeaders(); const data1 = getValues(); if (data1 != null) { const toXml = (data, data1) => { var result = '<?xml version="1.0" encoding="UTF-8"?> \n<valori> \n'; for (var i = 0; i < data.length; i++) { // doar ca aici creem un string in format XML result = result + `\t <${data[i]}><value>${data1[i]}</value></${data[i]}>\n` } return result + '</valori>'; } var xmltext = toXml(data, data1); var filename = "xmlData.xml"; var pom = document.createElement('a'); var bb = new Blob([xmltext], { type: 'text/plain' }); pom.setAttribute('href', window.URL.createObjectURL(bb)); pom.setAttribute('download', filename); pom.dataset.downloadurl = ['text/plain', pom.download, pom.href].join(':'); pom.draggable = true; pom.classList.add('dragout'); pom.click(); } } function downloadPDF() { // pentru PDF am folosit jsPDF const data = getHeaders(); const data1 = getValues(); if (data1 != null) { var doc = new jsPDF(); var specialElementHandlers = { '#bypassme': function (element, renderer) { return true; } }; var margin = { top: 0, left: 0, right: 0, bottom: 0 }; var source = ""; for (var i = 0; i < data.length; i++) { source = source + "<p>" + data[i] + " : " + data1[i] + "</p><br/>"; // creeam un string corespunzator } doc.fromHTML(source, 50, 50, { 'width': 100, 'elementHandlers': specialElementHandlers }, function (bla) { doc.save('pdfData.pdf'); }, // si descarcam pdf-ul folosind magia jsPDF margin); } } function tweakLib() { // functie adaugata pentru canvas2svg pentru a putea transforma chart-ul in svg C2S.prototype.getContext = function (contextId) { if (contextId == "2d" || contextId == "2D") { return this; } return null; } C2S.prototype.style = function () { return this.__canvas.style } C2S.prototype.getAttribute = function (name) { return this[name]; } C2S.prototype.addEventListener = function (type, listener, eventListenerOptions) { console.log("canvas2svg.addEventListener() not implemented.") } } function downloadSVG() { // pentru SVG am folosit canvas2svg var selectedChart = getSelectedChart(); // luam chart-ul selectat if (selectedChart !== undefined) { var chartType; var context; var W = 500; var H = 500; if (selectedChart === 0) { chartType = pieChartData; context = document.getElementById("chart-pie").getContext("2d"); } else if (selectedChart === 1) { chartType = lineChartData; context = document.getElementById("chart-line").getContext("2d"); H = 700; } else if (selectedChart === 2) { chartType = barChartData; context = document.getElementById("chart-bar").getContext("2d"); H = 700; } // si practic se deseneaza iar un chart in format svg folosind canvas2svg if (chartType !== undefined && context != undefined) { var chart = new Chart(context, chartType); tweakLib(); chartType.options.responsive = false; chartType.options.animation = false; var svgContext = C2S(H, W); var mySvg = new Chart(svgContext, chartType); var bb = new Blob([svgContext.getSerializedSvg(true)], { type: 'text/plain' }); var filename = "svgData.svg"; var pom = document.createElement('a'); pom.setAttribute('href', window.URL.createObjectURL(bb)); pom.setAttribute('download', filename); pom.dataset.downloadurl = ['text/plain', pom.download, pom.href].join(':'); pom.draggable = true; pom.classList.add('dragout'); pom.click(); } } }
Java
UTF-8
296
1.515625
2
[]
no_license
package com.cssl.service; import com.baomidou.mybatisplus.extension.service.IService; import com.cssl.pojo.Users; /** * @program: ZProj * @Date: 2019/6/11 16:53 * @Author: Mr.Deng * @Description: */ /** * plus提供的业务 */ public interface Userservice extends IService<Users> { }
JavaScript
UTF-8
1,245
2.5625
3
[]
no_license
/* *@functionName: JS *@params1: 参数1 *@params2: 参数2 *@params3: 参数3 *@version: V1.0.5 */ import {updateQueue} from './Component' export function addEvent(dom, eventType, handler) { let store ; if(dom.store){ //单例模式了 store = dom.store }else { dom.store = {} store = dom.store } store[eventType] = handler if(!document[eventType])// 如果有很多个元素都绑定了click时间只挂一次就可以了 document[eventType] = dispatchEvent } function dispatchEvent(event) { let {target, type} = event let eventType = `on${type}` updateQueue.isBatchingUpdate = true let syntheticEvent = createSyntheticEvent(event) //模拟冒泡过程 while(target){ let {store} = target let handler = store&&store[eventType] handler&&handler.call(target,syntheticEvent) target = target.parentNode } updateQueue.isBatchingUpdate = false updateQueue.batchUpdate() } //源码里做了一些了浏览器兼容性的适配 function createSyntheticEvent(event) { let syntheticEvent = {} for(let key in event){ syntheticEvent[key] = event[key] } return syntheticEvent }
Python
UTF-8
7,299
3.046875
3
[ "MIT" ]
permissive
print('Importando as bibliotecas necessárias...') # Importando as bibliotecas necessárias from bs4 import BeautifulSoup import urllib.request as urllib_request import pandas as pd import datetime import time from urllib.request import Request, urlopen from urllib.error import URLError, HTTPError import matplotlib.pyplot as plt # Setando os ids dos apps ids = {'Nubank': '814456780', 'Neon': '1127996388', 'C6': '1463463143', 'Inter': '839711154', 'Digio': '1128793569', 'Next': '1133682678', 'PAN': '1410400504'} # Coloque aqui o caminho do arquivo path = 'C:\\Users\\vinicius.oliveira\\Praticando_Web_Scrap\\data\\' df_rank = pd.read_csv(path + 'bank_rank_iOS.csv') # Definindo um dicionário vazio para armazenamento rank = {} # Setando a data e a hora now = datetime.datetime.now() ano = now.year mes = now.month dia = now.day horas = now.hour minutos = now.minute # Acertando alguns valores if len(str(mes)) == 1: mes = '0' + str(mes) if len(str(dia)) == 1: dia = '0' + str(dia) if len(str(horas)) == 1: horas = '0' + str(horas) if len(str(minutos)) == 1: minutos = '0' + str(minutos) data = f'{dia}/{mes}/{ano}' hora = f'{horas}:{minutos}' rank['Data'] = data rank['Hora'] = hora # Laço para baixar os dados do site da App Store for app in ids.keys(): # Definindo a url url = f'https://apps.apple.com/br/app/id{ids[app]}' headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'} # Fazendo a requisição try: req = Request(url, headers = headers) response = urlopen(req) print(f'{app} --> {response.getcode()}. Foi...') html = response.read() # Capturando o HTTPError caso ocorra except HTTPError as e: print('\nHTTPError\n') print(e.status, e.reason) # Capturando o URLError caso ocorra except URLError as e: print('\nURLError\n') print(e.reason) # Decodificando o html html = html.decode('utf-8') # Função para tratar o html def trata_html(input): return " ".join(input.split()).replace('> <', '><') # Tratando o html html = trata_html(html) # Instanciando a classe BeautifulSoup soup = BeautifulSoup(html, 'html.parser') # Armazenando o rank do app rank['Categoria'] = str(soup.findAll('li', {'class': 'inline-list__item'})[0].getText().split(' em ')[1].strip()) rank[app] = int(str(soup.findAll('li', {'class': 'inline-list__item'})[0]).split('Nº ')[1].split(' em ')[0]) time.sleep(3) ########### Exportando o .csv ######################################################################################### print('Exportando o .csv...') # Armazenando os dados novos novos = pd.DataFrame([rank]) df_rank = pd.concat([df_rank, novos], ignore_index=True) # Exportando o .csv df_rank.to_csv(path + 'bank_rank_iOS.csv', index=False) df_rank = pd.read_csv(path + 'bank_rank_iOS.csv') df_rank['Data'] = df_rank['Data'].apply(lambda x: datetime.datetime.strptime(x, '%d/%m/%Y')) # Agrupando por semana semana = {df_rank['Data'][i].isocalendar()[1]: df_rank['Data'][i].date() for i in range(len(df_rank))} df_rank['Semana'] = df_rank['Data'].apply(lambda x: semana[x.isocalendar()[1]]) df_rank_semanal = df_rank.groupby('Semana').mean().astype(int) df_rank.drop('Semana', axis=1, inplace=True) df_rank_semanal.reset_index(inplace=True) # Definindo as cores cores = {'Nubank': '#8A06BD', 'Neon': '#00D8D8', 'C6': '#242424', 'Inter': '#FF7A01', 'Digio': '#007ebd', 'Next': '#01FF5E', 'PAN': '#00AFFF'} # Configurando as figura plt.figure(figsize=(12, 10)) apps = df_rank_semanal.iloc[:, 1:].mean().sort_values().index # Iterando em cada app for app in apps: # Inicializando um contador cont = 0 # Plotando o gráfico para cada app plt.plot(df_rank_semanal['Semana'], df_rank_semanal[app], color=cores[app], label=app, linewidth=5) # Iternando em cada par (data, ranking) para cada app for x,y in zip(df_rank_semanal['Semana'], df_rank_semanal[f'{app}']): # Condição para mudar as posições das anotações do app da Nubank if app == 'Nubank': # Setando as posições das anotações do app da Nubank y_pos = 5 x_pos = 10 # Condição para mudar as posições das anotações do app da Neon elif app == 'Neon': # Setando as posições das anotações do app da Neon y_pos = 5 x_pos = -5 # Condição para mudar as posições das anotações do app da C6 elif app == 'C6': # Setando as posições das anotações do app da C6 y_pos = 5 x_pos = 10 # Condição para mudar as posições das anotações do app da Inter elif app == 'Inter': # Setando as posições das anotações do app da Inter y_pos = 5 x_pos = 10 # Condição para mudar as posições das anotações do app da Digio elif app == 'Digio': # Setando as posições das anotações do app da Digio y_pos = 5 x_pos = 10 # Condição para mudar as posições das anotações do app da Next elif app == 'Next': # Setando as posições das anotações do app da Next y_pos = 5 x_pos = 10 # Condição para mudar as posições das anotações do app da PAN elif app == 'PAN': # Setando as posições das anotações do app da PAN y_pos = 5 x_pos = 10 # Condição para mostrar não mostrar todas as anotações if cont % 2 == 0 or cont == df_rank_semanal.shape[0] - 1: # label -> anotação que vai aparecer anotacao = f'{y}' # Plotando as anotações plt.annotate(anotacao, (x,y), # coordenada da anotação textcoords="offset points", # como posicionar a anotação xytext=(x_pos, y_pos), # distância da anotação para o seu respectivo ponto (x,y) ha='center', # alinhamento horizontal da anotação. Pode ser 'left', 'right' ou 'center' fontsize=20, # tamanho da fonte da anotação color=cores[app]) # cor da anotação # Incrementanndo o contador cont += 1 limite = df_rank_semanal.iloc[:, 1:].max().max() + 5 # Invertendo o eixo y plt.ylim(limite, -1) # Colocando grid plt.grid(True) # Definindo o título plt.title('Ranking AppStore (média semanal) - Bancos digitais', fontsize=30) # Definindo a legenda plt.legend(labels=apps, fontsize=12, loc=0, fancybox=True) # Definindo o label do eixo y plt.ylabel('Ranking', fontsize=25) # Definindo o label do eixo x plt.xlabel('Semana', fontsize=25) # Formatando os ticks plt.xticks(fontsize=16, rotation=20) plt.yticks(fontsize=16) # Salvando a figura plt.savefig('images\\Ranking_AppStore-Bancos_digitais.png')
C++
UTF-8
13,651
2.8125
3
[]
no_license
#include "App.h" /// <summary> /// Default constructor /// </summary> App::App() { //Seed random based on time srand(time(0)); //Textures for flightweighting m_floorTexture = new sf::Texture(); m_wallTexture = new sf::Texture(); m_floorTexture->loadFromFile("floor.png"); m_wallTexture->loadFromFile("wall.png"); //Generation flags m_RWGenerated = false; m_CAGenerated = false; m_gridGenerated = false; //Render window m_window = new sf::RenderWindow(sf::VideoMode(1280, 720), "4th Year Project Simon Dowling C00190305"); //TGUI m_gui = new tgui::Gui(*m_window); //Create UI createUI(); } /// <summary> /// Deconstructor /// </summary> App::~App() { } /// <summary> /// Update loop for the application. /// </summary> void App::run() { sf::Clock clock; sf::Int32 lag = 0; sf::Time timeSinceLastUpdate = sf::Time::Zero; const sf::Time timePerFrame = sf::seconds(1.0f / 60.0f); timeSinceLastUpdate = clock.restart(); while (m_window->isOpen()) { sf::Event event; while (m_window->pollEvent(event)) { if (event.type == sf::Event::Closed) { m_window->close(); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Escape)) { m_window->close(); } //Update gui elements using sfml event m_gui->handleEvent(event); } timeSinceLastUpdate += clock.restart(); if (timeSinceLastUpdate > timePerFrame) { //Update call update(timeSinceLastUpdate.asMilliseconds()); timeSinceLastUpdate = sf::Time::Zero; } //Render call render(); } } /// <summary> /// Updates application. /// </summary> void App::update(sf::Int32 dt) { if (m_CAGenerated == true) { m_buttonExportCA->setEnabled(true); } if (m_RWGenerated == true) { m_buttonExportRW->setEnabled(true); } if (m_gridGenerated == true) { m_buttonExportGrid->setEnabled(true); } if (m_RWGenerated == true && m_CAGenerated == true) { m_buttonGenerateGrid->setEnabled(true); } } /// <summary> /// Renders game entities. /// </summary> void App::render() { m_window->clear(sf::Color(234, 194, 226, 255)); if (m_RWGenerated == true) { m_randomWalkGenerator->draw(*m_window); } if (m_CAGenerated == true) { m_cellularAutomataGenerator->draw(*m_window); } if (m_gridGenerated == true) { m_grid->draw(*m_window); } m_gui->draw(); m_window->display(); } /// <summary> /// Generates a random walk level based on input /// </summary> /// \param ebMaxWalkers : tgui editbox /// \param ebChanceToChangeDirection : tgui editbox /// \param ebChanceToDestroyWalker : tgui editbox /// \param ebChanceToSpawnNewWalker : tgui editbox /// \param ebFillPercentage : tgui editbox void App::generateRW(tgui::EditBox::Ptr ebMaxWalkers, tgui::EditBox::Ptr ebFillPercentage, tgui::EditBox::Ptr ebChanceToChangeDirection, tgui::EditBox::Ptr ebChanceToDestroyWalker, tgui::EditBox::Ptr ebChanceToSpawnNewWalker) { m_randomWalkGenerator = std::make_shared<RandomWalkGenerator>(30, 30); m_randomWalkGenerator->generate(30, 300, parse_string<int>(ebMaxWalkers->getText().toAnsiString()), parse_string<float>(ebFillPercentage->getText().toAnsiString()), parse_string<float>(ebChanceToChangeDirection->getText().toAnsiString()), parse_string<float>(ebChanceToDestroyWalker->getText().toAnsiString()), parse_string<float>(ebChanceToSpawnNewWalker->getText().toAnsiString())); m_randomWalkGenerator->createTileArray(m_floorTexture, m_wallTexture); m_RWGenerated = true; } /// <summary> /// Exports the binary data to a text file /// </summary> /// \param ebFileName : tgui editbox void App::exportRW(tgui::EditBox::Ptr ebFileName) { //Open file and give it a filename std::ofstream file{ ebFileName->getText().toAnsiString() + ".txt" }; for (int i = 0; i < m_randomWalkGenerator->getData().size(); i++) { for (int j = 0; j < m_randomWalkGenerator->getData()[i].size(); j++) { //Write line file << std::to_string(m_randomWalkGenerator->getData()[j].at(i)) + ","; } //End line in document file << std::endl; } //Close file when writing is finished file.close(); } /// <summary> /// Generates a cellular automata level based on input /// </summary> /// \param ebNumSimulationSteps : tgui editbot /// \param ebBirthLimit : tgui editbot /// \param ebDeathLimit : tgui editbot /// \param ebChanceStartAlive : tgui editbot void App::generateCA(tgui::EditBox::Ptr ebNumSimulationSteps, tgui::EditBox::Ptr ebBirthLimit, tgui::EditBox::Ptr ebDeathLimit, tgui::EditBox::Ptr ebChanceStartAlive) { m_cellularAutomataGenerator = std::make_shared<CellularAutomataGenerator>(30, 30, parse_string<int>(ebNumSimulationSteps->getText().toAnsiString())); m_cellularAutomataGenerator->generate(300, 300, parse_string<int>(ebNumSimulationSteps->getText().toAnsiString()), parse_string<int>(ebBirthLimit->getText().toAnsiString()), parse_string<int>(ebDeathLimit->getText().toAnsiString()), parse_string<float>(ebChanceStartAlive->getText().toAnsiString())); m_cellularAutomataGenerator->createTileArray(m_floorTexture, m_wallTexture); m_CAGenerated = true; } /// <summary> /// Exports the binary data to a text file /// </summary> void App::exportCA(tgui::EditBox::Ptr ebFileName) { //Open file and give filename std::ofstream file{ ebFileName->getText().toAnsiString() + ".txt" }; for (int i = 0; i < m_cellularAutomataGenerator->getData().size(); i++) { for (int j = 0; j < m_cellularAutomataGenerator->getData()[i].size(); j++) { //Write data to line file << std::to_string(m_cellularAutomataGenerator->getData()[j].at(i)) + ","; } //End line in document file << std::endl; } //Close file when writing is finished file.close(); } /// <summary> /// Generates a combined grid based on input /// </summary> /// \param ebOverlapX: tgui editbot /// \param ebOverlapY : tgui editbot void App::generateGrid(tgui::EditBox::Ptr ebOverlapX, tgui::EditBox::Ptr ebOverlapY) { m_grid = std::make_shared<Grid>(m_randomWalkGenerator, m_cellularAutomataGenerator, parse_string<int>(ebOverlapX->getText().toAnsiString()), parse_string<int>(ebOverlapY->getText().toAnsiString())); m_grid->generate(700, 300); m_grid->createTiles(m_floorTexture, m_wallTexture); m_gridGenerated = true; } /// <summary> /// Exports the binary data to a text file /// </summary> void App::exportGrid(tgui::EditBox::Ptr ebFileName) { //Open file and give filename std::ofstream file{ ebFileName->getText().toAnsiString() + ".txt" }; for (int i = 0; i < m_grid->getData().size(); i++) { for (int j = 0; j < m_grid->getData()[i].size(); j++) { //Write line of data file << std::to_string(m_grid->getData()[j].at(i)) + ","; } //end line in document file << std::endl; } //close file when finished writing file.close(); } /// <summary> /// Creates and allocates tgui UI objects. /// </summary> void App::createUI() { //Random walk elements m_labelRW = tgui::Label::create("Random Walk Settings"); m_labelRW->setPosition(0, 50); m_labelRW->setSize(200, 20); m_gui->add(m_labelRW); m_labelMaxWalkers = tgui::Label::create("Maximum Walkers:"); m_labelMaxWalkers->setPosition(0, 100); m_gui->add(m_labelMaxWalkers); m_ebMaxWalkers = tgui::EditBox::create(); m_ebMaxWalkers->setSize(60, 15); m_ebMaxWalkers->setPosition(185, 100); m_ebMaxWalkers->setText("10"); m_gui->add(m_ebMaxWalkers); m_labelFillPercentage = tgui::Label::create("Fill Percentage:"); m_labelFillPercentage->setPosition(0, 120); m_gui->add(m_labelFillPercentage); m_ebFillPercentage = tgui::EditBox::copy(m_ebMaxWalkers); m_ebFillPercentage->setPosition(185, 120); m_ebFillPercentage->setText("0.3f"); m_gui->add(m_ebFillPercentage); m_labelChanceToChangeDirection = tgui::Label::create("Chance to change direction:"); m_labelChanceToChangeDirection->setPosition(0, 140); m_gui->add(m_labelChanceToChangeDirection); m_ebChanceToChangeDirection = tgui::EditBox::copy(m_ebMaxWalkers); m_ebChanceToChangeDirection->setPosition(185, 140); m_ebChanceToChangeDirection->setText("0.2f"); m_gui->add(m_ebChanceToChangeDirection); m_labelChanceToDestroyWalker = tgui::Label::create("Chance to destroy walker:"); m_labelChanceToDestroyWalker->setPosition(0, 160); m_gui->add(m_labelChanceToDestroyWalker); m_ebChanceToDestroyWalker = tgui::EditBox::copy(m_ebMaxWalkers); m_ebChanceToDestroyWalker->setPosition(185, 160); m_ebChanceToDestroyWalker->setText("0.1f"); m_gui->add(m_ebChanceToDestroyWalker); m_labelChanceToSpawnNewWalker = tgui::Label::create("Chance to spawn walker:"); m_labelChanceToSpawnNewWalker->setPosition(0, 180); m_gui->add(m_labelChanceToSpawnNewWalker); m_ebChanceToSpawnNewWalker = tgui::EditBox::copy(m_ebMaxWalkers); m_ebChanceToSpawnNewWalker->setPosition(185, 180); m_ebChanceToSpawnNewWalker->setText("0.2f"); m_gui->add(m_ebChanceToSpawnNewWalker); m_buttonGenerateRW = tgui::Button::create("Generate"); m_buttonGenerateRW->setSize(100, 20); m_buttonGenerateRW->setPosition(0, 220); m_gui->add(m_buttonGenerateRW); m_buttonGenerateRW->connect("pressed", &App::generateRW, this, m_ebMaxWalkers, m_ebFillPercentage, m_ebChanceToChangeDirection, m_ebChanceToDestroyWalker, m_ebChanceToSpawnNewWalker); m_buttonExportRW = tgui::Button::create("Export"); m_buttonExportRW->setSize(100, 20); m_buttonExportRW->setPosition(0, 245); m_buttonExportRW->setEnabled(false); m_gui->add(m_buttonExportRW); m_ebRWFileName = tgui::EditBox::create(); m_ebRWFileName->setSize(100, 20); m_ebRWFileName->setPosition(110, 245); m_ebRWFileName->setText("RW file name"); m_gui->add(m_ebRWFileName); m_buttonExportRW->connect("pressed", &App::exportRW, this, m_ebRWFileName); //Cellular Automata elements m_labelCA = tgui::Label::create("Cellular Automata Settings"); m_labelCA->setPosition(320, 50); m_labelCA->setSize(200, 20); m_gui->add(m_labelCA); m_labelNumSimulationSteps = tgui::Label::create("Simulation steps:"); m_labelNumSimulationSteps->setPosition(320, 120); m_gui->add(m_labelNumSimulationSteps); m_ebNumSimulationSteps = tgui::EditBox::copy(m_ebMaxWalkers); m_ebNumSimulationSteps->setPosition(505, 120); m_ebNumSimulationSteps->setText("3"); m_gui->add(m_ebNumSimulationSteps); m_labelBirthLimit = tgui::Label::create("Birth limit:"); m_labelBirthLimit->setPosition(320, 140); m_gui->add(m_labelBirthLimit); m_ebBirthLimit = tgui::EditBox::copy(m_ebMaxWalkers); m_ebBirthLimit->setPosition(505, 140); m_ebBirthLimit->setText("4"); m_gui->add(m_ebBirthLimit); m_labelDeathLimit = tgui::Label::create("Death limit:"); m_labelDeathLimit->setPosition(320, 160); m_gui->add(m_labelDeathLimit); m_ebDeathLimit = tgui::EditBox::copy(m_ebMaxWalkers); m_ebDeathLimit->setPosition(505, 160); m_ebDeathLimit->setText("3"); m_gui->add(m_ebDeathLimit); m_labelChanceStartAlive = tgui::Label::create("Chance to start alive:"); m_labelChanceStartAlive->setPosition(320, 180); m_gui->add(m_labelChanceStartAlive); m_ebChanceStartAlive = tgui::EditBox::copy(m_ebMaxWalkers); m_ebChanceStartAlive->setPosition(505, 180); m_ebChanceStartAlive->setText("0.4f"); m_gui->add(m_ebChanceStartAlive); m_buttonGenerateCA = tgui::Button::create("Generate"); m_buttonGenerateCA->setSize(100, 20); m_buttonGenerateCA->setPosition(320, 220); m_gui->add(m_buttonGenerateCA); m_buttonGenerateCA->connect("pressed", &App::generateCA, this, m_ebNumSimulationSteps, m_ebBirthLimit, m_ebDeathLimit, m_ebChanceStartAlive); m_buttonExportCA = tgui::Button::create("Export"); m_buttonExportCA->setSize(100, 20); m_buttonExportCA->setPosition(320, 245); m_buttonExportCA->setEnabled(false); m_gui->add(m_buttonExportCA); m_ebCAFileName = tgui::EditBox::create(); m_ebCAFileName->setSize(100, 20); m_ebCAFileName->setPosition(430, 245); m_ebCAFileName->setText("CA file name"); m_gui->add(m_ebCAFileName); m_buttonExportCA->connect("pressed", &App::exportCA, this, m_ebCAFileName); //Combination grid elements m_labelOverlapPoint = tgui::Label::create("Overlap Point (x, y):"); m_labelOverlapPoint->setPosition(700, 120); m_gui->add(m_labelOverlapPoint); m_ebOverlapX = tgui::EditBox::create(); m_ebOverlapX->setSize(60, 15); m_ebOverlapX->setPosition(840, 120); m_ebOverlapX->setText("15"); m_gui->add(m_ebOverlapX); m_ebOverlapY = tgui::EditBox::create(); m_ebOverlapY->setSize(60, 15); m_ebOverlapY->setPosition(910, 120); m_ebOverlapY->setText("15"); m_gui->add(m_ebOverlapY); m_labelOverlapSettings = tgui::Label::create("Overlap Settings"); m_labelOverlapSettings->setPosition(700, 50); m_gui->add(m_labelOverlapSettings); m_buttonGenerateGrid = tgui::Button::create("Generate"); m_buttonGenerateGrid->setSize(100, 20); m_buttonGenerateGrid->setPosition(700, 220); m_buttonGenerateGrid->setEnabled(false); m_gui->add(m_buttonGenerateGrid); m_buttonGenerateGrid->connect("pressed", &App::generateGrid, this, m_ebOverlapX, m_ebOverlapY); m_buttonExportGrid = tgui::Button::create("Export"); m_buttonExportGrid->setSize(100, 20); m_buttonExportGrid->setPosition(700, 245); m_buttonExportGrid->setEnabled(false); m_gui->add(m_buttonExportGrid); m_ebGridFileName = tgui::EditBox::create(); m_ebGridFileName->setSize(100, 20); m_ebGridFileName->setPosition(810, 245); m_ebGridFileName->setText("Grid file name"); m_gui->add(m_ebGridFileName); m_buttonExportGrid->connect("pressed", &App::exportGrid, this, m_ebGridFileName); } /// <summary> /// Gets numbers and their data types from strings /// </summary> template <typename RETURN_TYPE, typename STRING_TYPE> RETURN_TYPE App::parse_string(const STRING_TYPE& str) { std::stringstream buf; buf << str; RETURN_TYPE val; buf >> val; return val; }
Go
UTF-8
212
3.3125
3
[]
no_license
package main import "fmt" func main() { const ( sunday = iota monday tuesday wednesday thursday friday saturday ) fmt.Println(sunday, monday, tuesday, wednesday, thursday, friday, saturday) }
Java
UTF-8
24,994
1.8125
2
[]
no_license
package hsco.pms.rnt.prm.RNT02030500; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.nexacro.xapi.data.DataSet; import hsco.cmm.dao.BaseDao; import hsco.cmm.exception.NexaDaoException; import hsco.cmm.exception.NexaServiceException; import hsco.cmm.ria.nexacro.NexacroConstant; import hsco.cmm.ria.nexacro.map.DataSetMap; import hsco.cmm.service.BaseService; import hsco.cmm.util.ObjectUtil; @Service("RNT02030500Service") public class RNT02030500ServiceImpl extends BaseService{ protected Logger log = LoggerFactory.getLogger(this.getClass()); /** * 매입임대 계약자상세정보 * @param tranInfo * @param inVar * @param inDataset * @param outVar * @param outDataset * @throws NexaServiceException */ @SuppressWarnings({ "rawtypes", "unchecked" }) public void selectPuchasRentCntrctDetailList( DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaServiceException { DataSetMap inDsMap = (DataSetMap)inDataset.get("input1"); Map inMap = null; if (inDsMap != null) inMap = inDsMap.get(0); List <Map> records = (List<Map>)baseDao.list("RNT02030500DAO.selectPuchasRentCntrctDetailList", inMap); DataSetMap outDsMap = new DataSetMap(); outDsMap.setRowMaps(records); outDataset.put("output1", outDsMap); } /** * 매입임대 자격변경 정보 * @param tranInfo * @param inVar * @param inDataset * @param outVar * @param outDataset * @throws NexaServiceException */ @SuppressWarnings({ "rawtypes", "unchecked" }) public void selectPuchasQualfChangeList( DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaServiceException { DataSetMap inDsMap = (DataSetMap)inDataset.get("input1"); Map inMap = null; if (inDsMap != null) inMap = inDsMap.get(0); List <Map> records = (List<Map>)baseDao.list("RNT02030500DAO.selectPuchasQualfChangeList", inMap); DataSetMap outDsMap = new DataSetMap(); outDsMap.setRowMaps(records); outDataset.put("output1", outDsMap); } /** * 매입임대 자격변경 처리 * @param tranInfo * @param inVar * @param inDataset * @param outVar * @param outDataset */ @SuppressWarnings({ "rawtypes", "unchecked" }) public void savePuchasQualfChange(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) { DataSetMap inDsMap = (DataSetMap) inDataset.get("input1"); Map inMap = null; if (inDsMap != null) inMap = inDsMap.get(0); DataSetMap inDsMap2 = (DataSetMap) inDataset.get("input2"); Map inMap2 = null; if (inDsMap2 != null) inMap2 = inDsMap2.get(0); int rowType = ((Integer) inMap.get(NexacroConstant.DATASET_ROW_TYPE)).intValue(); if ( rowType == DataSet.ROW_TYPE_DELETED ){ //자격변경시 생성된 보증금 순번 조회 Map tempMap = new HashMap<String, Object>(); int gtnDfnnt = Integer.parseInt((String)inMap.get("GTN_DFNNT")); tempMap.put("CNTRCTR_NO", inMap.get("CNTRCTR_NO")); tempMap.put("CHANGE_DE", inMap.get("CHANGE_DE")); tempMap.put("GTN_DFNNT", Math.abs(gtnDfnnt)); String gtnSn = (String) baseDao.select("RNT02030700DAO.selectGtnSn", tempMap); //자격변경시 생성된 보증금 삭제 inMap.put("GTN_SN", gtnSn); baseDao.delete("RNT02030700DAO.rentGtnD", inMap); //보증금 납부요청 String[] arrSqlId = { "RNT02030700DAO.unpaidGtnList"}; //보증금 미납내역 //미납내역 납부요청(보증금) for(int sqlIdx=0; sqlIdx<arrSqlId.length; sqlIdx++){ List <Map> unpaidMap = (List<Map>)baseDao.list(arrSqlId[sqlIdx], inMap); Map<String, String> rqestMap = new HashMap<String, String>(); if(unpaidMap != null && unpaidMap.size() > 0){ //기존의 납부요청 내용 일괄 삭제 rqestMap.put("IN_FLAG", "DELETE"); //작업구분 rqestMap.put( "IN_BANK_CD", "%"); //은행코드 rqestMap.put( "IN_ACCT_NO", "%"); //계좌번호 rqestMap.put( "IN_TR_DATE", (String)inMap.get("CHANGE_DE")); //거래일자 rqestMap.put( "IN_TR_SDATE", (String)inMap.get("TR_SDATE")); //거래시작일 rqestMap.put( "IN_TR_EDATE", (String)inMap.get("TR_EDATE")); //2주 더... //거래종료일 rqestMap.put( "IN_CRT_DIV", "RN"); //계약구분 rqestMap.put( "IN_CRT_ID", (String)inMap.get("CNTRCTR_NO")); //계약자 rqestMap.put( "IN_BILL_SEQ", ""); //청구순번 rqestMap.put( "IN_CORT_CODE", ""); //납부코드 rqestMap.put( "IN_PAY_NUM", ""); //납부번호 rqestMap.put( "IN_REC_CLASS", ""); //납부구분 rqestMap.put( "IN_REC_SEQ", ""); //납부순번 rqestMap.put( "IN_PAYEND_DATE", ""); //납입기한 rqestMap.put( "IN_BILL_AMT", "0"); //결제금액 rqestMap.put( "IN_PAY_AMT", "0"); //납부대상금액 rqestMap.put( "IN_SALE_AMT", "0"); //차감금액 rqestMap.put( "IN_INT_AMT", "0"); //연체금액 rqestMap.put( "IN_BILL_DIV", "A"); //납부구분(A-일괄,B-개별) rqestMap.put( "IN_BJ_YN", "B"); //보증금전용계좌 등록 rqestMap.put( "S_USER_ID", (String)inMap.get("S_USER_ID")); baseDao.update("RNT02030400DAO.SP_VA_BILL_UID", rqestMap); //납부요청 내용 상세 등록 for(int i=0; i<unpaidMap.size(); i++){ rqestMap.clear(); rqestMap.put("IN_FLAG", "DETAIL"); //작업구분 rqestMap.put( "IN_BANK_CD", ""); //은행코드 rqestMap.put( "IN_ACCT_NO", ""); //계좌번호 rqestMap.put( "IN_TR_DATE", (String)inMap.get("CHANGE_DE")); //거래일자 rqestMap.put( "IN_TR_SDATE", (String)inMap.get("TR_SDATE")); //거래시작일 rqestMap.put( "IN_TR_EDATE", (String)inMap.get("TR_EDATE")); //2주 더... //거래종료일 rqestMap.put( "IN_CRT_DIV", "RN"); //계약구분 rqestMap.put( "IN_CRT_ID", (String)inMap.get("CNTRCTR_NO")); //계약자 rqestMap.put( "IN_BILL_SEQ", String.valueOf(i+1)); //청구순번 rqestMap.put( "IN_CORT_CODE", (String)unpaidMap.get(i).get("CORT_CODE")); //납부코드 rqestMap.put( "IN_PAY_NUM", "0"); //납부번호 rqestMap.put( "IN_REC_CLASS", "0"); //납부구분 rqestMap.put( "IN_REC_SEQ", "0"); //납부순번 rqestMap.put( "IN_PAYEND_DATE", (String)unpaidMap.get(i).get("PAYEND_DATE")); //납입기한 rqestMap.put( "IN_BILL_AMT", String.valueOf(unpaidMap.get(i).get("TOT_AMT"))); //결제금액 rqestMap.put( "IN_PAY_AMT", String.valueOf(unpaidMap.get(i).get("TOT_AMT"))); //납부대상금액 rqestMap.put( "IN_SALE_AMT", String.valueOf(unpaidMap.get(i).get("APPAY_AMT")));//차감금액 rqestMap.put( "IN_INT_AMT", String.valueOf(unpaidMap.get(i).get("CHA_AMT"))); //연체금액 rqestMap.put( "IN_BILL_DIV", "A"); //납부구분(A-일괄,B-개별) rqestMap.put( "IN_BJ_YN", "B"); //보증금전용계좌 등록 rqestMap.put( "S_USER_ID", (String)inMap.get("S_USER_ID")); baseDao.update("RNT02030400DAO.SP_VA_BILL_UID", rqestMap); } //납부요청 내용 총 합계 등록 rqestMap.put("IN_FLAG", "MASTER"); //작업구분 rqestMap.put( "IN_BANK_CD", (String)inMap.get("BANK_CODE")); //은행코드 rqestMap.put( "IN_ACCT_NO", (String)inMap.get("ACNUTNO")); //계좌번호 rqestMap.put( "IN_TR_DATE", (String)inMap.get("CHANGE_DE")); //거래일자 rqestMap.put( "IN_TR_SDATE", (String)inMap.get("TR_SDATE")); //거래시작일 rqestMap.put( "IN_TR_EDATE", (String)inMap.get("TR_EDATE")); //2주 더... //거래종료일 rqestMap.put( "IN_CRT_DIV", "RN"); //계약구분 rqestMap.put( "IN_CRT_ID", (String)inMap.get("CNTRCTR_NO")); //계약자 rqestMap.put( "IN_BILL_SEQ", ""); //청구순번 rqestMap.put( "IN_CORT_CODE", ""); //납부코드 rqestMap.put( "IN_PAY_NUM", ""); //납부번호 rqestMap.put( "IN_REC_CLASS", ""); //납부구분 rqestMap.put( "IN_REC_SEQ", ""); //납부순번 rqestMap.put( "IN_PAYEND_DATE", ""); //납입기한 rqestMap.put( "IN_BILL_AMT", "0"); //결제금액 rqestMap.put( "IN_PAY_AMT", "0"); //납부대상금액 rqestMap.put( "IN_SALE_AMT", "0"); //차감금액 rqestMap.put( "IN_INT_AMT", "0"); //연체금액 rqestMap.put( "IN_BILL_DIV", "A"); //납부구분(A-일괄,B-개별) rqestMap.put( "IN_BJ_YN", "B"); //보증금전용계좌 등록 rqestMap.put( "S_USER_ID", (String)inMap.get("S_USER_ID")); baseDao.update("RNT02030400DAO.SP_VA_BILL_UID", rqestMap); }else { //기존의 납부요청 내용 일괄 삭제 rqestMap.put("IN_FLAG", "DELETE"); //작업구분 rqestMap.put( "IN_BANK_CD", "%"); //은행코드 rqestMap.put( "IN_ACCT_NO", "%"); //계좌번호 rqestMap.put( "IN_TR_DATE", (String)inMap.get("CHANGE_DE")); //거래일자 rqestMap.put( "IN_TR_SDATE", (String)inMap.get("TR_SDATE")); //거래시작일 rqestMap.put( "IN_TR_EDATE", (String)inMap.get("TR_EDATE")); //2주 더... //거래종료일 rqestMap.put( "IN_CRT_DIV", "RN"); //계약구분 rqestMap.put( "IN_CRT_ID", (String)inMap.get("CNTRCTR_NO")); //계약자 rqestMap.put( "IN_BILL_SEQ", ""); //청구순번 rqestMap.put( "IN_CORT_CODE", ""); //납부코드 rqestMap.put( "IN_PAY_NUM", ""); //납부번호 rqestMap.put( "IN_REC_CLASS", ""); //납부구분 rqestMap.put( "IN_REC_SEQ", ""); //납부순번 rqestMap.put( "IN_PAYEND_DATE", ""); //납입기한 rqestMap.put( "IN_BILL_AMT", "0"); //결제금액 rqestMap.put( "IN_PAY_AMT", "0"); //납부대상금액 rqestMap.put( "IN_SALE_AMT", "0"); //차감금액 rqestMap.put( "IN_INT_AMT", "0"); //연체금액 rqestMap.put( "IN_BILL_DIV", "A"); //납부구분(A-일괄,B-개별) rqestMap.put( "IN_BJ_YN", "B"); //보증금전용계좌 등록 rqestMap.put( "S_USER_ID", (String)inMap.get("S_USER_ID")); baseDao.update("RNT02030400DAO.SP_VA_BILL_UID", rqestMap); } } baseDao.delete("RNT02030500DAO.deleteRentQualChg", inMap); Map tempMap2 = new HashMap<String, Object>(); tempMap2.put("CNTRCTR_NO", inMap.get("CNTRCTR_NO")); tempMap2.put("CHANGE_DE", inMap.get("CHANGE_DE_BFCHG")); tempMap2.put("RM", ""); tempMap2.put("QUALF_SE_AFTCH", inMap.get("QUALF_SE_BFCHG")); tempMap2.put("GTN_AFTCH", inMap.get("GTN_BFCHG")); tempMap2.put("RNTCHRG_AFTCH", inMap.get("RNTCHRG_BFCHG")); baseDao.update("RNT02030500DAO.updatePuchasContract", tempMap2); // 계약정보 업데이트 inMap2.put("CHANGE_DE", inMap.get("CHANGE_DE")); inMap2.put("CHANGE_NO", inMap.get("CHANGE_NO")); baseDao.insert("RNT02000000DAO.deleteDdcAmount", inMap2); }else if(rowType == DataSet.ROW_TYPE_INSERTED){ baseDao.insert("RNT02030500DAO.savePuchasQualfChangeC", inMap); baseDao.update("RNT02030500DAO.updatePuchasContract", inMap); // 계약정보 업데이트 String changeNo = (String)baseDao.select("RNT02030500DAO.selectChangeNo", inMap); inMap2.put("CHANGE_NO", changeNo); baseDao.insert("RNT02000000DAO.saveDdcAmount", inMap2); int gtnDfnnt = Integer.parseInt((String)inMap.get("GTN_AFTCH")) - Integer.parseInt((String)inMap.get("GTN_BFCHG")); // 보증금 차액 if(gtnDfnnt > 0){ //증액보증금 등록 inMap.put("GTN_DFNNT", gtnDfnnt); inMap.put("QUALF_SE", inMap.get("QUALF_SE_AFTCH")); baseDao.insert("RNT02030700DAO.rentGtnC", inMap); } //증액보증금 납부요청 String[] arrSqlId = { "RNT02030700DAO.unpaidGtnList"}; //보증금 미납내역 //미납내역 납부요청(보증금) for(int sqlIdx=0; sqlIdx<arrSqlId.length; sqlIdx++){ List <Map> unpaidMap = (List<Map>)baseDao.list(arrSqlId[sqlIdx], inMap); Map<String, String> rqestMap = new HashMap<String, String>(); if(unpaidMap != null && unpaidMap.size() > 0){ //기존의 납부요청 내용 일괄 삭제 rqestMap.put("IN_FLAG", "DELETE"); //작업구분 rqestMap.put( "IN_BANK_CD", "%"); //은행코드 rqestMap.put( "IN_ACCT_NO", "%"); //계좌번호 rqestMap.put( "IN_TR_DATE", (String)inMap.get("CHANGE_DE")); //거래일자 rqestMap.put( "IN_TR_SDATE", (String)inMap.get("TR_SDATE")); //거래시작일 rqestMap.put( "IN_TR_EDATE", (String)inMap.get("TR_EDATE")); //2주 더... //거래종료일 rqestMap.put( "IN_CRT_DIV", "RN"); //계약구분 rqestMap.put( "IN_CRT_ID", (String)inMap.get("CNTRCTR_NO")); //계약자 rqestMap.put( "IN_BILL_SEQ", ""); //청구순번 rqestMap.put( "IN_CORT_CODE", ""); //납부코드 rqestMap.put( "IN_PAY_NUM", ""); //납부번호 rqestMap.put( "IN_REC_CLASS", ""); //납부구분 rqestMap.put( "IN_REC_SEQ", ""); //납부순번 rqestMap.put( "IN_PAYEND_DATE", ""); //납입기한 rqestMap.put( "IN_BILL_AMT", "0"); //결제금액 rqestMap.put( "IN_PAY_AMT", "0"); //납부대상금액 rqestMap.put( "IN_SALE_AMT", "0"); //차감금액 rqestMap.put( "IN_INT_AMT", "0"); //연체금액 rqestMap.put( "IN_BILL_DIV", "A"); //납부구분(A-일괄,B-개별) rqestMap.put( "IN_BJ_YN", "B"); //보증금전용계좌 등록 rqestMap.put( "S_USER_ID", (String)inMap.get("S_USER_ID")); baseDao.update("RNT02030400DAO.SP_VA_BILL_UID", rqestMap); //납부요청 내용 상세 등록 for(int i=0; i<unpaidMap.size(); i++){ rqestMap.clear(); rqestMap.put("IN_FLAG", "DETAIL"); //작업구분 rqestMap.put( "IN_BANK_CD", ""); //은행코드 rqestMap.put( "IN_ACCT_NO", ""); //계좌번호 rqestMap.put( "IN_TR_DATE", (String)inMap.get("CHANGE_DE")); //거래일자 rqestMap.put( "IN_TR_SDATE", (String)inMap.get("TR_SDATE")); //거래시작일 rqestMap.put( "IN_TR_EDATE", (String)inMap.get("TR_EDATE")); //2주 더... //거래종료일 rqestMap.put( "IN_CRT_DIV", "RN"); //계약구분 rqestMap.put( "IN_CRT_ID", (String)inMap.get("CNTRCTR_NO")); //계약자 rqestMap.put( "IN_BILL_SEQ", String.valueOf(i+1)); //청구순번 rqestMap.put( "IN_CORT_CODE", (String)unpaidMap.get(i).get("CORT_CODE")); //납부코드 rqestMap.put( "IN_PAY_NUM", "0"); //납부번호 rqestMap.put( "IN_REC_CLASS", "0"); //납부구분 rqestMap.put( "IN_REC_SEQ", "0"); //납부순번 rqestMap.put( "IN_PAYEND_DATE", (String)unpaidMap.get(i).get("PAYEND_DATE")); //납입기한 rqestMap.put( "IN_BILL_AMT", String.valueOf(unpaidMap.get(i).get("TOT_AMT"))); //결제금액 rqestMap.put( "IN_PAY_AMT", String.valueOf(unpaidMap.get(i).get("TOT_AMT"))); //납부대상금액 rqestMap.put( "IN_SALE_AMT", String.valueOf(unpaidMap.get(i).get("APPAY_AMT")));//차감금액 rqestMap.put( "IN_INT_AMT", String.valueOf(unpaidMap.get(i).get("CHA_AMT"))); //연체금액 rqestMap.put( "IN_BILL_DIV", "A"); //납부구분(A-일괄,B-개별) rqestMap.put( "IN_BJ_YN", "B"); //보증금전용계좌 등록 rqestMap.put( "S_USER_ID", (String)inMap.get("S_USER_ID")); baseDao.update("RNT02030400DAO.SP_VA_BILL_UID", rqestMap); } //납부요청 내용 총 합계 등록 rqestMap.put("IN_FLAG", "MASTER"); //작업구분 rqestMap.put( "IN_BANK_CD", (String)inMap.get("BANK_CODE")); //은행코드 rqestMap.put( "IN_ACCT_NO", (String)inMap.get("ACNUTNO")); //계좌번호 rqestMap.put( "IN_TR_DATE", (String)inMap.get("CHANGE_DE")); //거래일자 rqestMap.put( "IN_TR_SDATE", (String)inMap.get("TR_SDATE")); //거래시작일 rqestMap.put( "IN_TR_EDATE", (String)inMap.get("TR_EDATE")); //2주 더... //거래종료일 rqestMap.put( "IN_CRT_DIV", "RN"); //계약구분 rqestMap.put( "IN_CRT_ID", (String)inMap.get("CNTRCTR_NO")); //계약자 rqestMap.put( "IN_BILL_SEQ", ""); //청구순번 rqestMap.put( "IN_CORT_CODE", ""); //납부코드 rqestMap.put( "IN_PAY_NUM", ""); //납부번호 rqestMap.put( "IN_REC_CLASS", ""); //납부구분 rqestMap.put( "IN_REC_SEQ", ""); //납부순번 rqestMap.put( "IN_PAYEND_DATE", ""); //납입기한 rqestMap.put( "IN_BILL_AMT", "0"); //결제금액 rqestMap.put( "IN_PAY_AMT", "0"); //납부대상금액 rqestMap.put( "IN_SALE_AMT", "0"); //차감금액 rqestMap.put( "IN_INT_AMT", "0"); //연체금액 rqestMap.put( "IN_BILL_DIV", "A"); //납부구분(A-일괄,B-개별) rqestMap.put( "IN_BJ_YN", "B"); //보증금전용계좌 등록 rqestMap.put( "S_USER_ID", (String)inMap.get("S_USER_ID")); baseDao.update("RNT02030400DAO.SP_VA_BILL_UID", rqestMap); } } }else { baseDao.insert("RNT02030500DAO.updatePuchasQualfChange", inMap); } } @SuppressWarnings({ "unchecked", "rawtypes" }) public void innerSanctnUbiDataset(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaDaoException{ DataSetMap inDsMap = (DataSetMap)inDataset.get("input1"); Map<String, Object> inMap = null; if (inDsMap != null) inMap = inDsMap.get(0); List <Map> records; //계약정보 상세 records = (List<Map>)baseDao.list("RNT02030500DAO.selectPuchasRentCntrctDetailList", inMap); DataSetMap outDsMap = new DataSetMap(); outDsMap.setRowMaps(records); outDataset.put("output1", outDsMap); //자격변경정보 상세 records = (List<Map>)baseDao.list("RNT02030500DAO.selectPuchasQualfChangeList", inMap); outDsMap = new DataSetMap(); outDsMap.setRowMaps(records); outDataset.put("output2", outDsMap); //결제자 이름 목록 records = (List<Map>)baseDao.list("RNT02030500DAO.sanctnerNmDetail", inMap); outDsMap = new DataSetMap(); outDsMap.setRowMaps(records); outDataset.put("output3", outDsMap); } @SuppressWarnings({ "unchecked", "rawtypes" }) public void sanctnerNmDetail(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaDaoException{ DataSetMap inDsMap = (DataSetMap)inDataset.get("input1"); Map<String, Object> inMap = null; if (inDsMap != null) inMap = inDsMap.get(0); List <Map> records; records = (List<Map>)baseDao.list("RNT02030500DAO.sanctnerNmDetail", inMap); DataSetMap outDsMap = new DataSetMap(); outDsMap.setRowMaps(records); outDataset.put("output1", outDsMap); } @SuppressWarnings({ "rawtypes" }) public void rentQualfChangeU(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) { //결제번호 수정 DataSetMap list = (DataSetMap) inDataset.get("input1"); for (int x = 0; x < list.size(); x++) { Map map = list.get(x); baseDao.update("RNT02030500DAO.savePuchasQualfChangeU", map); } } /** * 내부결재 후처리 메소드 (결재상태 저장) * @param (Map sanctnInfo) * @return void * @throws NexaServiceException */ @SuppressWarnings({ "rawtypes", "unchecked" }) public void postProcess(BaseDao baseDao, DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaServiceException { Map sanctnInfo = null; DataSetMap dsSetMap = inDataset.get("input1"); List<Map> list = dsSetMap.getRowMaps(); int lsize = (list == null) ? 0 : list.size(); if(lsize > 0){ sanctnInfo = (Map)list.get(0); } String currSanctionSttus = (String)sanctnInfo.get("LAST_SANCTN_STTUS"); // 최종결재상태 Map recordMap = null; StringTokenizer st = new StringTokenizer(sanctnInfo.get("JOB_KEY").toString(),"^"); if(st.hasMoreTokens()){ recordMap = new HashMap<String, String>(); recordMap.put("ACCNUT_YEAR", st.nextToken()); recordMap.put("ENDW_INCME_DECSN_NO", st.nextToken()); } } /** * 매입임대 해약 첨부파일 목록 * @param tranInfo * @param inVar * @param inDataset * @param outVar * @param outDataset * @throws NexaServiceException */ @SuppressWarnings({ "rawtypes", "unchecked" }) public void selectQualfChangeAtchList(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaDaoException { DataSetMap inDsMap = (DataSetMap)inDataset.get("input1"); Map<String, Object> inMap = null; if (inDsMap != null) inMap = inDsMap.get(0); List <Map> records; records = (List<Map>)baseDao.list("RNT02030500DAO.selectQualfChangeAtchList", inMap); DataSetMap outDsMap = new DataSetMap(); outDsMap.setRowMaps(records); outDataset.put("output1", outDsMap); } //첨부파일 CUD @SuppressWarnings({ "rawtypes" }) public void saveQualfChangeAtchCUD(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) { DataSetMap inDsMap = (DataSetMap) inDataset.get("input1"); Map inMap = null; if (inDsMap != null) inMap = inDsMap.get(0); // 1. 첨부 삭제 baseDao.delete("RNT02030500DAO.saveQualfChangeAtchD", inMap); // 2. 공통첨부파일의 정보로 첨부 등록 baseDao.insert("RNT02030500DAO.saveQualfChangeAtchC", inMap); } /** * 매입임대 보증금 임대료 조회 * @param tranInfo * @param inVar * @param inDataset * @param outVar * @param outDataset * @throws NexaServiceException */ @SuppressWarnings({ "rawtypes", "unchecked" }) public void selectAmount( DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaServiceException { DataSetMap inDsMap = (DataSetMap)inDataset.get("input1"); Map inMap = null; if (inDsMap != null) inMap = inDsMap.get(0); List <Map> records = (List<Map>)baseDao.list("RNT02030500DAO.selectAmount", inMap); DataSetMap outDsMap = new DataSetMap(); outDsMap.setRowMaps(records); outDataset.put("output1", outDsMap); } /** * 전자결제번호 입력 * @param (DataSetMap, inVar, inDataset, outVar, outDataset) * @return int * @throws NexaServiceException */ @SuppressWarnings({ "rawtypes" }) public void approveU(DataSetMap tranInfo, Map<String, Object> inVar, Map<String, DataSetMap> inDataset, Map<String, Object> outVar, Map<String, DataSetMap> outDataset) throws NexaServiceException { DataSetMap list = (DataSetMap) inDataset.get("input1"); List <Map> records; Map map = list.get(0); baseDao.update("RNT02030500DAO.approveU", map); DataSetMap outDsMap = new DataSetMap(); outDsMap.add(map); outDataset.put("output1", outDsMap); } }
C++
UTF-8
1,868
3.5
4
[]
no_license
/* * @lc app=leetcode.cn id=113 lang=cpp * * [113] 路径总和 II */ #include <iostream> #include <vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; // @lc code=start /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> ret; vector<TreeNode*> node_list; int cal = 0; while(root || !node_list.empty()) { while(root) { cal += root->val; node_list.push_back(root); root = root->left; } root = node_list.back(); root = root->right; if(!root && cal == sum) { vector<int> tmp; cout << "build tmp" << endl; for(TreeNode* i : node_list) { cout << "\tpush: " << i->val << endl; tmp.push_back(i->val); } ret.push_back(tmp); } else { } node_list.pop_back(); if(root->right) { root = root->right; } else { if(cal == sum) { vector<int> tmp; cout << "build tmp" << endl; for(TreeNode* i : node_list) { cout << "\tpush: " << i->val << endl; tmp.push_back(i->val); } ret.push_back(tmp); } } } return ret; } }; // @lc code=end
C
UTF-8
5,158
2.75
3
[]
no_license
/* * led.c * * Created on: 07-Oct-2016 * Author: Admin */ /* * led.c * * Created on: 07-Oct-2016 * Author: Admin */ /* * led.c * * Created on: 07-Oct-2016 * Author: Admin */ #include "MKL25Z4.h" #include <math.h> #include "led.h" LEDColour_t LEDColour=OFF; //Set initial colour uint16_t value=100;// Set initial brightness LED_Init() { SIM_BASE_PTR->SCGC6 |= SIM_SCGC6_TPM2_MASK; //clock select for TPM2 ,ENABLES TPM2 SIM_BASE_PTR->SCGC6 |= SIM_SCGC6_TPM0_MASK; //clock select for TPM0, ENABLES TPM0 SIM_BASE_PTR->SOPT2 |= SIM_SOPT2_TPMSRC(1); //Select clock source to PLL/2 TPM2_BASE_PTR->SC = TPM_SC_CMOD(1) | TPM_SC_PS(7); //CMOD is clock mode selection to 1 amd prescalar to 1 i.e 128 for TPM0 TPM2_BASE_PTR->MOD = 1875; //set MOD value, timer counter is set to MOD value when reaches 0 TPM0_BASE_PTR->SC = TPM_SC_CMOD(1) | TPM_SC_PS(7); //CMOD is clock mode selection to 1 amd prescalar to 1 i.e 128 for TPM0 TPM0_BASE_PTR->MOD = 1875;// set MOD value, timer counter is setto MOD value when reaches 0 SIM_BASE_PTR->SCGC5 |= SIM_SCGC5_PORTB_MASK; //clock select for PORTB, Enables PORTB SIM_BASE_PTR->SCGC5 |= SIM_SCGC5_PORTD_MASK;//clock select for PORTD, Enables PORTD PORTB_BASE_PTR->PCR[18] = PORTB_BASE_PTR->PCR[19] = PORT_PCR_MUX(3); //set alternate function as TPM channel for port B pin 18 PORTD_BASE_PTR->PCR[1]=PORT_PCR_MUX(4);// set alternate function as TPM channel for port D pin 1 //Set mode selection to edge aligned PWM TPM2_BASE_PTR->CONTROLS[0].CnSC = TPM_CnSC_MSB_MASK |TPM_CnSC_ELSA_MASK; TPM2_BASE_PTR->CONTROLS[1].CnSC = TPM_CnSC_MSB_MASK |TPM_CnSC_ELSA_MASK; TPM0_BASE_PTR->CONTROLS[1].CnSC = TPM_CnSC_MSB_MASK |TPM_CnSC_ELSA_MASK; } void LED_Control(uint8_t Character) { if(Character=='w' && value<1000) //with character 'w', the brightness of the LED is increased every 100 values { value+=100; } else if(Character=='s' && value>0)//with character 's', the brightness of the LED is decreased every 100 values { value-=100; } else if(Character=='a') //with character 'a', the LED colours are cycled in the forward direction { LEDColour++; if(LEDColour>=8)//wrap around { LEDColour=0; } } else if(Character=='d') //with character 'd', the LED colours are cycles in the backward direction { LEDColour--; if(LEDColour==0) // wrap around { LEDColour=7; } } LEDFunction(LEDColour, value); // Call to LED function } LEDFunction(LEDColour_t LEDColour, uint16_t Brightness) { if(LEDColour==RED) { TPM2_BASE_PTR->CONTROLS[0].CnV = Brightness; //Channel value for RED LEDColour with brightness value TPM2_BASE_PTR->CONTROLS[1].CnV = 0;//Channel value for GREEN LEDColour with brightness value as 0 TPM0_BASE_PTR->CONTROLS[1].CnV = 0; //Channel value for BLUE LEDColour with brightness value as 0 } else if(LEDColour==YELLOW) { TPM2_BASE_PTR->CONTROLS[0].CnV = TPM2_BASE_PTR->CONTROLS[1].CnV = Brightness; ////Channel value for RED and YELLOWLEDColour with brightness value TPM0_BASE_PTR->CONTROLS[1].CnV = 0; //Channel value for BLUE LEDColour with brightness value } else if(LEDColour==GREEN) { TPM2_BASE_PTR->CONTROLS[1].CnV = Brightness; //Channel value for GREEN LEDColour with brightness value TPM2_BASE_PTR->CONTROLS[0].CnV = 0; //Channel value for RED LEDColour with brightness value as 0 TPM0_BASE_PTR->CONTROLS[1].CnV = 0; //Channel value for BLUE LEDColour with brightness value as 0 } else if(LEDColour==BLUE) { TPM0_BASE_PTR->CONTROLS[1].CnV = Brightness; //Channel value for BLUE LEDColour with brightness value TPM2_BASE_PTR->CONTROLS[1].CnV = 0; //Channel value for GREEN LEDColour with brightness value as 0 TPM2_BASE_PTR->CONTROLS[0].CnV = 0; //Channel value for RED LEDColour with brightness value as 0 } else if(LEDColour==MAGENTA) { TPM2_BASE_PTR->CONTROLS[0].CnV = TPM0_BASE_PTR->CONTROLS[1].CnV = Brightness; //Channel value for RED and BLUELEDColour with brightness value TPM2_BASE_PTR->CONTROLS[1].CnV = 0; //Channel value for GREEN LEDColour with brightness value as 0 } else if(LEDColour==CYAN) { TPM2_BASE_PTR->CONTROLS[1].CnV = TPM0_BASE_PTR->CONTROLS[1].CnV = Brightness; //Channel value for GREEN and BLUE LEDColour with brightness value TPM2_BASE_PTR->CONTROLS[0].CnV = 0; //Channel value for RED LEDColour with brightness value as 0 } else if(LEDColour==WHITE) { TPM2_BASE_PTR->CONTROLS[1].CnV = TPM2_BASE_PTR->CONTROLS[0].CnV=TPM0_BASE_PTR->CONTROLS[1].CnV = Brightness; //Channel value for RED, GREEN and BLUE LEDColour with brightness value } else if(LEDColour==OFF) { TPM2_BASE_PTR->CONTROLS[0].CnV = 0; //Channel value for RED LEDColour with brightness value as 0 TPM2_BASE_PTR->CONTROLS[1].CnV = 0; //Channel value for GREEN LEDColour with brightness value as 0 TPM0_BASE_PTR->CONTROLS[1].CnV = 0; //Channel value for BLUE LEDColour with brightness value AS 0 } }
Java
UTF-8
471
1.898438
2
[]
no_license
package test.yangguoqin.com.jni_test; import android.app.Activity; import android.os.Bundle; /** * @创建者 Administrator * @创时间 2016/1/28 15:03 * @描述 ${todo} * @包名 test.yangguoqin.com.jni_test * @版本 $$Rev$$ * @更新者 $$Author$$ * @更新时间 $$Date$$ * @更新描述 ${todo} */ public class aaa extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } }
TypeScript
UTF-8
2,091
3.078125
3
[ "MIT" ]
permissive
import { ArgumentOutOfRangeException } from "linq-to-typescript" import { asAsync, expectAsync, itAsync, itEnumerable, itParallel } from "../TestHelpers" describe("elementAt", () => { it("String", () => { expect("abc".elementAt(0)).toBe("a") expect("abc".elementAt(1)).toBe("b") expect("abc".elementAt(2)).toBe("c") expect(() => "abc".elementAt(3)).toThrowError(ArgumentOutOfRangeException) }) itEnumerable("Basic", (asEnumerable) => { expect(asEnumerable([1]).elementAt(0)).toBe(1) expect(asEnumerable([1, 2]).elementAt(1)).toBe(2) }) itAsync("Basic", async () => { expect(await asAsync([1]).elementAt(0)).toBe(1) expect(await asAsync([1, 2]).elementAt(1)).toBe(2) }) itParallel("Basic", async (asParallel) => { expect(await asParallel([1]).elementAt(0)).toBe(1) expect(await asParallel([1, 2]).elementAt(1)).toBe(2) }) itEnumerable("empty array throws exception", (asEnumerable) => expect(() => asEnumerable([]).elementAt(0)).toThrowError(ArgumentOutOfRangeException)) itAsync("empty array throws exception", async () => { const expect = await expectAsync(asAsync([]).elementAt(0)) expect.toThrowError(ArgumentOutOfRangeException) }) itParallel("empty array throws exception", async (asParallel) => { const expect = await expectAsync(asParallel([]).elementAt(0)) expect.toThrowError(ArgumentOutOfRangeException) }) itEnumerable("negative index throws exception", (asEnumerable) => { expect(() => asEnumerable([1, 2]).elementAt(-1)).toThrowError(ArgumentOutOfRangeException) }) itAsync("negative index throws exception", async () => { const expect = await expectAsync(asAsync([1, 2]).elementAt(-1)) expect.toThrowError(ArgumentOutOfRangeException) }) itParallel("negative index throws exception", async (asParallel) => { const expect = await expectAsync(asParallel([1, 2]).elementAt(-1)) expect.toThrowError(ArgumentOutOfRangeException) }) })
Python
UTF-8
1,043
2.71875
3
[]
no_license
import utils # set_up def set_up_profesor(): profesor_list=[ {'DNI':'213233212','nombre': 'Roberto','apellido': 'Pineda'}, {'DNI':'2973273','nombre': 'Braulio','apellido': 'Berlanga'}, {'DNI': '6565906956','nombre': 'Hipolito','apellido': 'Vasquez'}, {'DNI':'355454354','nombre':'Martin','apellido':'Pérez'}, {'DNI':'8658587','nombre':'Mirta','apellido':'Arevalo'}, {'DNI':'38767686','nombre':'Sergio','apellido':'Pérez'}, {'DNI':'694345678','nombre':'Agusto','apellido':'Diaz'} ] return profesor_list # create one def insert_profesor(DNI,nombre,apellido): mydict={"DNI":DNI,"nombre":nombre,"apellido":apellido} return mydict # find def find_profesor(DNI): query={'DNI':DNI} return query # delete def delete_profesor(DNI): query={"DNI":DNI} return query # update def update_profesor_DNI(DNI): query_DNI={"DNI":DNI} return query_DNI def update_profesor(new_value,field): my_dict={'$set':{field:new_value}} return my_dict