text
stringlengths
1
1.05M
// Copyright (C) 2019-2021, <NAME>. // @author xiongfa.li // @version V1.0 // Description: package layout import ( "fmt" "github.com/xfali/neve-gen/pkg/buildin" "github.com/xfali/neve-gen/pkg/generator" "github.com/xfali/neve-gen/pkg/model" "github.com/xfali/neve-gen/pkg/stage" "gopkg.in/yaml.v2" "io/ioutil" "path/filepath" ) func CreateStages(target, tmplRoot string) []stage.Stage { var ret []stage.Stage ret = append(ret, stage.NewGenProjectStage(target, tmplRoot)) ret = append(ret, stage.NewGenGoModStage(target, tmplRoot)) ret = append(ret, stage.NewGenMainStage(target, tmplRoot)) ret = append(ret, stage.NewGenHandlerStage(target, tmplRoot)) ret = append(ret, stage.NewGenServiceStage(target, tmplRoot)) ret = append(ret, stage.NeGenServiceImplStage(target, tmplRoot)) return ret } func ParseStages(target, tmplRoot string) ([]stage.Stage, error) { m, err := LoadLayoutSpec(tmplRoot) if err != nil { return nil, err } fac := generator.NewFileTemplateFactory(tmplRoot) var ret []stage.Stage //ret = append(ret, stage.NewGenProjectStage(target, tmplRoot)) for _, spec := range m.Sepc.TemplateSepcs { s, err := CreateStagesByTemplateSpec(target, fac, spec, m.Sepc.TemplateSepcs) if err != nil { return nil, err } ret = append(ret, s) } return ret, nil } func ParseBuildinStages(target string) ([]stage.Stage, error) { m, err := LoadBuildinLayoutSpec() if err != nil { return nil, err } fac := generator.NewBuildinTemplateFactory() var ret []stage.Stage //ret = append(ret, stage.NewGenProjectStage(target, tmplRoot)) for _, spec := range m.Sepc.TemplateSepcs { s, err := CreateStagesByTemplateSpec(target, fac, spec, m.Sepc.TemplateSepcs) if err != nil { return nil, err } ret = append(ret, s) } return ret, nil } func CreateStagesByTemplateSpec(target string, factory generator.Factory, spec model.TemplateSepc, all []model.TemplateSepc) (stage.Stage, error) { switch spec.Type { case model.TemplateTypeApp: return stage.NewAppStage(target, factory, spec), nil case model.TemplateTypeModule: return stage.NewModuleStage(target, factory, spec), nil //case model.TemplateTypeGobatisModel: // return stage.NewGenGobatisModelStage(target, spec), nil //case model.TemplateTypeGobatisProxy: // return stage.NewGenGobatisStage(target, spec), nil case model.TemplateTypeGobatisMapper: return stage.NeGenGobatisMapperStage(target, spec), nil case model.TemplateTypeSwagger: return stage.NewSwaggerStage(target, spec, all), nil default: return nil, fmt.Errorf("Type: %s not support\nSpec: %v .", spec.Type, spec) } } func LoadLayoutSpec(path string) (*model.TemplateLayoutConfig, error) { f, err := ioutil.ReadFile(filepath.Join(path, model.TemplateLayoutSpecFile)) if err != nil { return nil, err } m := &model.TemplateLayoutConfig{ } err = yaml.Unmarshal(f, &m) if err != nil { return nil, err } return m, err } func LoadBuildinLayoutSpec() (*model.TemplateLayoutConfig, error) { f := []byte(buildin.GetBuildTemplate(model.TemplateLayoutSpecFile)) if len(f) == 0 { return nil, fmt.Errorf("Buildin template layout spec file is empty. ") } m := &model.TemplateLayoutConfig{ } err := yaml.Unmarshal(f, &m) if err != nil { return nil, err } return m, err }
#!/bin/sh Yeast=`ls ${GTTESTDATA}/ltrharvest/s_cer/chr[01][0-9].*.gz` bin/gt packedindex mkindex -sprank -tis -dna -pl -bsize 10 -locfreq 32 -dir rev\ -db ${Yeast}\ -indexname pck-yeast env -i GT_MEM_BOOKKEEPING=off time bin/gt tagerator -rw -pck pck-yeast -k 2\ -t yeast.1000 > tmp.prot gprof bin/gt gmon.out
<reponame>Pouja/coverage-istanbul-loader<filename>src/types/istanbul-lib-instrument/index.d.ts export * from "istanbul-lib-instrument"; declare module "istanbul-lib-instrument" { export interface RawSourceMap { version: string; sources: string[]; names: string[]; sourcesContent?: string[]; mappings: string; } }
<filename>src/sentry/static/sentry/app/views/organizationIntegrations/installedIntegration.tsx import React from 'react'; import styled from '@emotion/styled'; import Access from 'app/components/acl/access'; import Alert from 'app/components/alert'; import Button from 'app/components/button'; import CircleIndicator from 'app/components/circleIndicator'; import Confirm from 'app/components/confirm'; import Tooltip from 'app/components/tooltip'; import {IconDelete, IconSettings, IconWarning} from 'app/icons'; import {t} from 'app/locale'; import space from 'app/styles/space'; import {IntegrationProvider, Integration, Organization, ObjectStatus} from 'app/types'; import {SingleIntegrationEvent} from 'app/utils/integrationUtil'; import theme from 'app/utils/theme'; import AddIntegrationButton from './addIntegrationButton'; import IntegrationItem from './integrationItem'; const CONFIGURABLE_FEATURES = ['commits', 'alert-rule']; export type Props = { organization: Organization; provider: IntegrationProvider; integration: Integration; onRemove: (integration: Integration) => void; onDisable: (integration: Integration) => void; onReAuthIntegration: (integration: Integration) => void; trackIntegrationEvent: ( options: Pick<SingleIntegrationEvent, 'eventKey' | 'eventName'> ) => void; //analytics callback className?: string; showReauthMessage: boolean; }; export default class InstalledIntegration extends React.Component<Props> { /** * Integrations have additional configuration when any of the conditions are * met: * * - The Integration has organization-specific configuration options. * - The Integration has configurable features */ hasConfiguration() { const {integration, provider} = this.props; return ( integration.configOrganization.length > 0 || provider.features.filter(f => CONFIGURABLE_FEATURES.includes(f)).length > 0 ); } handleReAuthIntegration = (integration: Integration) => { this.props.onReAuthIntegration(integration); }; handleUninstallClick = () => { this.props.trackIntegrationEvent({ eventKey: 'integrations.uninstall_clicked', eventName: 'Integrations: Uninstall Clicked', }); }; getRemovalBodyAndText(aspects: Integration['provider']['aspects']) { if (aspects && aspects.removal_dialog) { return { body: aspects.removal_dialog.body, actionText: aspects.removal_dialog.actionText, }; } else { return { body: t( 'Deleting this integration will remove any project associated data. This action cannot be undone. Are you sure you want to delete this integration?' ), actionText: t('Delete'), }; } } handleRemove(integration: Integration) { this.props.onRemove(integration); this.props.trackIntegrationEvent({ eventKey: 'integrations.uninstall_completed', eventName: 'Integrations: Uninstall Completed', }); } get removeConfirmProps() { const {integration} = this.props; const {body, actionText} = this.getRemovalBodyAndText(integration.provider.aspects); const message = ( <React.Fragment> <Alert type="error" icon="icon-circle-exclamation"> {t('Deleting this integration has consequences!')} </Alert> {body} </React.Fragment> ); return { message, confirmText: actionText, onConfirm: () => this.handleRemove(integration), }; } get disableConfirmProps() { const {integration} = this.props; const {body, actionText} = integration.provider.aspects.disable_dialog || {}; const message = ( <React.Fragment> <Alert type="error" icon="icon-circle-exclamation"> {t('This integration cannot be removed in Sentry')} </Alert> {body} </React.Fragment> ); return { message, confirmText: actionText, onConfirm: () => this.props.onDisable(integration), }; } render() { const { className, integration, provider, organization, showReauthMessage, } = this.props; const removeConfirmProps = integration.status === 'active' && integration.provider.canDisable ? this.disableConfirmProps : this.removeConfirmProps; return ( <Access access={['org:integrations']}> {({hasAccess}) => ( <IntegrationFlex key={integration.id} className={className}> <IntegrationItemBox> <IntegrationItem integration={integration} /> </IntegrationItemBox> <div> {showReauthMessage && ( <Tooltip disabled={hasAccess} title={t( 'You must be an organization owner, manager or admin to upgrade' )} > <AddIntegrationButton disabled={!hasAccess} provider={provider} onAddIntegration={this.handleReAuthIntegration} integrationId={integration.id} priority="primary" size="small" buttonText={t('Upgrade Now')} organization={organization} icon={<IconWarning size="sm" />} /> </Tooltip> )} <Tooltip disabled={this.hasConfiguration() && hasAccess} position="left" title={ !this.hasConfiguration() ? t('Integration not configurable') : t( 'You must be an organization owner, manager or admin to configure' ) } > <StyledButton borderless icon={<IconSettings />} disabled={ !this.hasConfiguration() || !hasAccess || integration.status !== 'active' } to={`/settings/${organization.slug}/integrations/${provider.key}/${integration.id}/`} data-test-id="integration-configure-button" > {t('Configure')} </StyledButton> </Tooltip> </div> <div> <Tooltip disabled={hasAccess} title={t( 'You must be an organization owner, manager or admin to uninstall' )} > <Confirm priority="danger" onConfirming={this.handleUninstallClick} disabled={!hasAccess} {...removeConfirmProps} > <StyledButton disabled={!hasAccess} borderless icon={<IconDelete />} data-test-id="integration-remove-button" > {t('Uninstall')} </StyledButton> </Confirm> </Tooltip> </div> <IntegrationStatus status={integration.status} /> </IntegrationFlex> )} </Access> ); } } const StyledButton = styled(Button)` color: ${p => p.theme.gray500}; `; const IntegrationFlex = styled('div')` display: flex; align-items: center; `; const IntegrationItemBox = styled('div')` flex: 1; `; const IntegrationStatus = styled( (props: React.HTMLAttributes<HTMLElement> & {status: ObjectStatus}) => { const {status, ...p} = props; const color = status === 'active' ? theme.success : theme.gray500; const titleText = status === 'active' ? t('This Integration can be disabled by clicking the Uninstall button') : t('This Integration has been disconnected from the external provider'); return ( <Tooltip title={titleText}> <div {...p}> <CircleIndicator size={6} color={color} /> <IntegrationStatusText>{`${ status === 'active' ? t('enabled') : t('disabled') }`}</IntegrationStatusText> </div> </Tooltip> ); } )` display: flex; align-items: center; color: ${p => p.theme.gray500}; font-weight: light; text-transform: capitalize; &:before { content: '|'; color: ${p => p.theme.gray400}; margin-right: ${space(1)}; font-weight: normal; } `; const IntegrationStatusText = styled('div')` margin: 0 ${space(0.75)} 0 ${space(0.5)}; `;
is_consistent() { val= active_low_sysfs=`cat $GPIO_SYSFS/gpio$nr/active_low` val_sysfs=`cat $GPIO_SYSFS/gpio$nr/value` dir_sysfs=`cat $GPIO_SYSFS/gpio$nr/direction` gpio_this_debugfs=`cat $GPIO_DEBUGFS |grep "gpio-$nr" | sed "s/(.*)//g"` dir_debugfs=`echo $gpio_this_debugfs | awk '{print $2}'` val_debugfs=`echo $gpio_this_debugfs | awk '{print $3}'` if [ $val_debugfs = "lo" ]; then val=0 elif [ $val_debugfs = "hi" ]; then val=1 fi if [ $active_low_sysfs = "1" ]; then if [ $val = "0" ]; then val="1" else val="0" fi fi if [ $val_sysfs = $val ] && [ $dir_sysfs = $dir_debugfs ]; then echo -n "." else echo "test fail, exit" die fi } test_pin_logic() { nr=$1 direction=$2 active_low=$3 value=$4 echo $direction > $GPIO_SYSFS/gpio$nr/direction echo $active_low > $GPIO_SYSFS/gpio$nr/active_low if [ $direction = "out" ]; then echo $value > $GPIO_SYSFS/gpio$nr/value fi is_consistent $nr } test_one_pin() { nr=$1 echo -n "test pin<$nr>" echo $nr > $GPIO_SYSFS/export 2>/dev/null if [ X$? != X0 ]; then echo "test GPIO pin $nr failed" die fi #"Checking if the sysfs is consistent with debugfs: " is_consistent $nr #"Checking the logic of active_low: " test_pin_logic $nr out 1 1 test_pin_logic $nr out 1 0 test_pin_logic $nr out 0 1 test_pin_logic $nr out 0 0 #"Checking the logic of direction: " test_pin_logic $nr in 1 1 test_pin_logic $nr out 1 0 test_pin_logic $nr low 0 1 test_pin_logic $nr high 0 0 echo $nr > $GPIO_SYSFS/unexport echo "successful" } test_one_pin_fail() { nr=$1 echo $nr > $GPIO_SYSFS/export 2>/dev/null if [ X$? != X0 ]; then echo "test invalid pin $nr successful" else echo "test invalid pin $nr failed" echo $nr > $GPIO_SYSFS/unexport 2>/dev/null die fi } list_chip() { echo `ls -d $GPIO_DRV_SYSFS/gpiochip* 2>/dev/null` } test_chip() { chip=$1 name=`basename $chip` base=`cat $chip/base` ngpio=`cat $chip/ngpio` printf "%-10s %-5s %-5s\n" $name $base $ngpio if [ $ngpio = "0" ]; then echo "number of gpio is zero is not allowed". fi test_one_pin $base test_one_pin $(($base + $ngpio - 1)) test_one_pin $((( RANDOM % $ngpio ) + $base )) } test_chips_sysfs() { gpiochip=`list_chip $module` if [ X"$gpiochip" = X ]; then if [ X"$valid" = Xfalse ]; then echo "successful" else echo "fail" die fi else for chip in $gpiochip; do test_chip $chip done fi }
var specHelper = require(__dirname + "/../_specHelper.js").specHelper; var should = require('should'); describe('plugins', function(){ var jobDelay = 100; var jobs = { "slowAdd": { plugins: [ 'jobLock' ], pluginOptions: { jobLock: {}, }, perform: function(a,b,callback){ var answer = a + b; setTimeout(function(){ callback(null, answer); }, jobDelay); }, }, "uniqueJob": { plugins: [ 'queueLock', 'delayQueueLock' ], pluginOptions: { queueLock: {}, delayQueueLock: {} }, perform: function(a,b,callback){ var answer = a + b; callback(null, answer); }, } }; before(function(done){ specHelper.connect(function(){ specHelper.cleanup(function(){ queue = new specHelper.NR.queue({connection: specHelper.cleanConnectionDetails(), queue: specHelper.queue}, jobs, function(){ done(); }); }); }); }); afterEach(function(done){ specHelper.cleanup(function(){ done(); }); }); beforeEach(function(done){ specHelper.cleanup(function(){ done(); }); }); describe('queueLock',function(){ it('will not enque a job with the same args if it is already in the queue', function(done){ queue.enqueue(specHelper.queue, "uniqueJob", [1,2], function(){ queue.enqueue(specHelper.queue, "uniqueJob", [1,2], function(){ queue.length(specHelper.queue, function(err, len){ len.should.equal(1); done(); }); }); }); }); it('will enque a job with the different args', function(done){ queue.enqueue(specHelper.queue, "uniqueJob", [1,2], function(){ queue.enqueue(specHelper.queue, "uniqueJob", [3,4], function(){ queue.length(specHelper.queue, function(err, len){ len.should.equal(2); done(); }); }); }); }); }); });
#!/bin/bash #Aquest script s'ocuparà de crear les carpetes pels nous repositoris FTP. #S'executarà per part de l'usuari www-data (Apache) i necessitarà drets de sudo per fer els chown # Rebrà com a paràmetres el nom de repositori i un id d'usuari. # Retornarà 0 en cas de success i un valor >0 en cas d'error: # 0 Success # 1 La carpeta arrel $PATH no existeix # 2 El nombre de parametres és incorrecte # 3 La carpeta a crear ja existeix (controlat via PHP, però per si de cas) # 4 el ID no és numèric major a 2000 #### Variables #### ROOT=/serveis/ftp/data; #Carpeta on es crearan els shares LOG_FILE=$ROOT/../create_ftp.log; #Hi desarem els logs del que fem #### Verificacions i control dels paràmetres #### #La carpeta $path ha d'existir if [ ! -d $ROOT ]; then exit 1; fi #Hem de rebre 2 parametres if (( $# != 2 )); then exit 2; fi # Lectura de paràmetres REPOSITORI=$1; ID=$2 #La carpeta share no pot exisitir prèviament if [ -d $ROOT/$REPOSITORI ]; then exit 3; fi #ID ha de ser numeric > 2000 if [[ $ID =~ '^[0-9]+$' ]] || (( $ID < 2000 )); then exit 4; fi echo `date` "Created folder=$ROOT/$REPOSITORI with owner=$ID" >> $LOG_FILE; mkdir $ROOT/$REPOSITORI; chmod 700 $ROOT/$REPOSITORI; chown $ID $ROOT/$REPOSITORI;
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { ExpenseComponent } from './expense/expense.component'; @NgModule({ declarations: [ AppComponent, ExpenseComponent ], imports: [ BrowserModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
#!/bin/bash # # test run image # function docker-run-mycentos7javadocker() { docker pull georgesan/mycentos7javadocker:latest ${WINPTY_CMD} docker run -i -t --rm \ -e http_proxy=${http_proxy} -e https_proxy=${https_proxy} -e no_proxy="${no_proxy}" \ georgesan/mycentos7javadocker:latest } docker-run-mycentos7javadocker
<gh_stars>0 const express = require("express"); const path = require("path"); const test = require("./test"); const router = express.Router(); router.use("/test", test); module.exports = router;
<filename>baza-1.sql -- phpMyAdmin SQL Dump -- version 4.7.4 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Jan 20, 2018 at 08:48 PM -- Server version: 10.1.30-MariaDB -- PHP Version: 7.2.1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; 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 */; -- -- Database: `baza` -- -- -------------------------------------------------------- -- -- Table structure for table `galerija` -- CREATE TABLE `galerija` ( `id_slike` int(255) NOT NULL, `naziv` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `putanja` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `id_strana` int(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `korisnik` -- CREATE TABLE `korisnik` ( `id_korisnik` int(255) NOT NULL, `id_uloge` int(255) NOT NULL, `username` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `korisnik` -- INSERT INTO `korisnik` (`id_korisnik`, `id_uloge`, `username`, `password`) VALUES (1, 1, 'admin', '<PASSWORD>'); -- -------------------------------------------------------- -- -- Table structure for table `meni` -- CREATE TABLE `meni` ( `id_meni` int(255) NOT NULL, `ime_linka` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `link` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `roditelj` int(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `meni` -- INSERT INTO `meni` (`id_meni`, `ime_linka`, `link`, `roditelj`) VALUES (1, 'home', 'index.php?ime_linka=home', 0), (2, 'games', 'index.php?ime_linka=games', 0), (3, 'author', 'index.php?ime_linka=author', 0), (4, 'login', 'index.php?ime_linka=login', 0), (5, 'register', 'index.php?ime_linka=register', 0); -- -------------------------------------------------------- -- -- Table structure for table `uloge` -- CREATE TABLE `uloge` ( `id_uloge` int(255) NOT NULL, `naziv` varchar(255) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `uloge` -- INSERT INTO `uloge` (`id_uloge`, `naziv`) VALUES (1, 'admin'), (2, 'korisnik'); -- -- Indexes for dumped tables -- -- -- Indexes for table `galerija` -- ALTER TABLE `galerija` ADD PRIMARY KEY (`id_slike`); -- -- Indexes for table `korisnik` -- ALTER TABLE `korisnik` ADD PRIMARY KEY (`id_korisnik`); -- -- Indexes for table `meni` -- ALTER TABLE `meni` ADD PRIMARY KEY (`id_meni`); -- -- Indexes for table `uloge` -- ALTER TABLE `uloge` ADD PRIMARY KEY (`id_uloge`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `korisnik` -- ALTER TABLE `korisnik` MODIFY `id_korisnik` int(255) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `meni` -- ALTER TABLE `meni` MODIFY `id_meni` int(255) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT for table `uloge` -- ALTER TABLE `uloge` MODIFY `id_uloge` int(255) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; 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 */;
SELECT CustomerID, SUM(Price) FROM Orders GROUP BY CustomerID;
#!/bin/sh setkeycodes 0x88 0x1a9 # 0x88 presentation setkeycodes 0xD9 138 # I key (high keycode: "info")
<reponame>itsmealex56/myPyVenture<filename>Chapter 3/jackenpoy.py<gh_stars>0 import random random_choice = random.randint(0,2) if random_choice == 0: computer_choice = 'rock' elif random_choice == 1: computer_choice = 'paper' else: computer_choice = 'scissors' my_choice = input('Rock, Paper, or Scissors? ') while my_choice != "": if my_choice == 'rock': if computer_choice == 'scissors': print('You chose rock and computer chose scissors...You won') elif computer_choice == 'rock': print('You chose rock and computer chose rock...You are both tied') else: print('You chose rock and computer chose paper...You lose') elif my_choice == 'paper': if computer_choice == 'scissors': print('You chose paper and computer chose scissors...You lose') elif computer_choice == 'rock': print('You chose paper and computer chose rock...You won') else: print('You chose paper and computer chose paper...You are both tied') else: if computer_choice == 'scissors': print('You chose scissors and computer chose scissors...You are both tied') elif computer_choice == 'rock': print('You chose scissors and computer chose rock...You lose') else: print('You chose scissors and computer chose paper...You won') print('Computer has pick', computer_choice)
<filename>lib/src/kbasesearchengine/parse/SimpleSubObjectConsumer.java package kbasesearchengine.parse; import java.io.IOException; import java.io.StringWriter; import java.util.Map; import com.fasterxml.jackson.core.JsonGenerator; import kbasesearchengine.common.ObjectJsonPath; import us.kbase.common.service.UObject; public class SimpleSubObjectConsumer implements SubObjectConsumer { private Map<ObjectJsonPath, String> data; private String nextPath = null; private StringWriter outChars = null; private JsonGenerator nextGen = null; public SimpleSubObjectConsumer(Map<ObjectJsonPath, String> data) { this.data = data; } @Override public void nextObject(String path) throws IOException, ObjectParseException { flush(); nextPath = path; outChars = new StringWriter(); nextGen = UObject.getMapper().getFactory().createGenerator(outChars); } @Override public JsonGenerator getOutput() throws IOException, ObjectParseException { if (nextGen == null) { throw new ObjectParseException("JsonGenerator wasn't initialized"); } return nextGen; } @Override public void flush() throws IOException, ObjectParseException { if (nextPath != null && nextGen != null && outChars != null) { nextGen.close(); data.put(new ObjectJsonPath(nextPath), outChars.toString()); nextPath = null; outChars = null; nextGen = null; } } }
def gcd(x, y): if x == 0: return y return gcd(y % x, x) result = gcd(8, 10) print(result)
<filename>scala-sbt/build.sbt name := "{{project_name}}" version := "1.0" scalaVersion := "2.12.3"
import { createHabit, deleteHabit, getAllHabits } from '@api' import { Layout } from '@components' import { IconButton, makeStyles, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, TextField, Typography } from '@material-ui/core' import AddIcon from '@material-ui/icons/AddCircle' import DeleteIcon from '@material-ui/icons/Delete' import PropTypes from 'prop-types' import React, { useState } from 'react' import { useMutation, useQuery, useQueryClient } from 'react-query' const habitFormInitialState = { title: '', metric: '', points: 0, note: '' } const useStyles = makeStyles({ table: { minWidth: 650, '& thead': { background: '#3f51b5', '& th': { color: 'white' } } } }) const HabitEditor = ({ location }) => { const queryClient = useQueryClient() const [formData, setFormData] = useState(habitFormInitialState) const { data: habits } = useQuery('habits', getAllHabits) const { mutate: createHabitMutation } = useMutation(createHabit, { onSuccess: () => { queryClient.invalidateQueries('habits') } }) const { mutate: deleteHabitMutation } = useMutation(deleteHabit, { onSuccess: () => { queryClient.invalidateQueries('habits') } }) const classes = useStyles() return ( <Layout location={location}> <Typography variant="h5" gutterBottom> Habits </Typography> <TableContainer component={Paper}> <Table className={classes.table} aria-label="simple table"> <TableHead> <TableRow> <TableCell>Title</TableCell> <TableCell>Metric</TableCell> <TableCell>Points</TableCell> <TableCell /> </TableRow> </TableHead> <TableBody> {(habits || []).map(habit => ( <TableRow key={habit.id}> <TableCell component="th" scope="habit"> {habit.title} </TableCell> <TableCell>{habit.metric}</TableCell> <TableCell>{habit.points}</TableCell> <TableCell> <IconButton color="secondary" aria-label="remove" component="span" onClick={() => deleteHabitMutation(habit.id)}> <DeleteIcon /> </IconButton> </TableCell> </TableRow> ))} <TableRow> <TableCell component="th" scope="row"> <TextField required label="Title" fullWidth onChange={e => { setFormData({ ...formData, title: e.target.value }) }} value={formData.title} /> </TableCell> <TableCell align="right"> <TextField required label="Metric" fullWidth onChange={e => { setFormData({ ...formData, metric: e.target.value }) }} value={formData.metric} /> </TableCell> <TableCell align="right"> <TextField type="number" required label="Points" fullWidth onChange={e => { setFormData({ ...formData, points: +e.target.value }) }} value={formData.points} /> </TableCell> <TableCell> <IconButton color="primary" aria-label="create new" component="span" onClick={() => createHabitMutation(formData)}> <AddIcon /> </IconButton> </TableCell> </TableRow> </TableBody> </Table> </TableContainer> </Layout> ) } HabitEditor.propTypes = { location: PropTypes.string } export default HabitEditor
# import libraries from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split import numpy as np # Create the model def create_model(): model = Sequential() model.add(Dense(64, activation='relu', input_shape=(5,))) model.add(Dense(64, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) return model # Scale and split the data into train and test sets def scale_data(x, y): scaler = MinMaxScaler() x = scaler.fit_transform(x) return train_test_split(x, y, test_size=0.2) # Train the model on given data def train_model(model, x_train, y_train): model.fit(x_train, y_train, epochs=100, batch_size=32, verbose=0) return model if __name__ == "__main__": # Create the model model = create_model() # Scale and split the data x_train, x_test, y_train, y_test = scale_data(x, y) # Train the model model = train_model(model, x_train, y_train)
<gh_stars>0 #include <fstream> /* * Лаба №4 * ИВБ-3-14 * <NAME> * 12 вариант Определить количество дорог. */ int main(int argc, char **argv) { std::ifstream In = std::ifstream("input.txt"); int N, n; In>>N; int count = 0; for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) { In>>n; if(n == 1) count++; } In.close(); count/=2; std::ofstream Out = std::ofstream("output.txt"); Out<<count; Out.close(); return 0; }
<filename>test/routes/index.js<gh_stars>1-10 module.exports = { homeRoutes: require('./homeRoutes'), usersRoutes: require('./usersRoutes') };
/* * KALUKALU WebAPP */ WebApp = { server: null, call: function(method, params, callback) { """ Methods: discover, search, playsong, cache. """ url = WebApp.server + method; $.get(url, params, callback); } discover: function () { this.call('discover', function(data) { console.log(data); }); } }
#!/bin/bash resource_group_name=$1 storage_account_name=$2 storage_acct_key=$3 blob_container_name=$4 file_name=$5 file_path=$6 storage_base_url="https://""$storage_account_name"".blob.core.windows.net" az storage blob upload --account-name "$storage_account_name" --account-key "$storage_acct_key" -c "$blob_container_name" -n "$file_name" -f "$file_path" --verbose end=`date -u -d "120 minutes" '+%Y-%m-%dT%H:%MZ'` sas="$(az storage blob generate-sas --account-name "$storage_account_name" --account-key "$storage_acct_key" -c "$blob_container_name" -n "$file_name" --permissions r --expiry $end --https-only)" file_url="$storage_base_url""/""$blob_container_name""/""$file_name""?""$sas" file_url=${file_url//\"/""} echo $file_url
#!/bin/bash # # DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" export DOCKER_OSS_LABEL="GPDB 5 OSS" export DOCKER_OSS_TAG="kochanpivotal/gpdb5-pxf" export DOCKER_LATEST_OSS_TAG="kochanpivotal/gpdb5-pxf:latest" # Use Cases specific export DC_USE_CASE1_SCRIPT="docker-compose -f ./usecase1/docker-compose.yml" export DC_USE_CASE2_SCRIPT="docker-compose -f ./usecase2/docker-compose-postgres9.6.yml" export DC_USE_CASE3_SCRIPT="docker-compose -f ./usecase3/docker-compose.yml" export DC_USE_CASE4_SCRIPT="docker-compose -f ./usecase4/docker-compose.yml" export DC_USE_CASE5_SCRIPT="docker-compose -f ./usecase5/docker-compose.yml" export DC_USE_CASE6_SCRIPT="docker-compose -f ./usecase6/docker-compose.yml" export DC_USE_CASE7_SCRIPT="docker-compose -f ./usecase7/docker-compose.yml" export DC_USE_CASE8_SCRIPT="docker-compose -f ./usecase8/docker-compose.yml"
package com.hapramp.ui.fragments; import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.crashlytics.android.Crashlytics; import com.hapramp.R; import com.hapramp.analytics.AnalyticsParams; import com.hapramp.analytics.AnalyticsUtil; import com.hapramp.utils.CrashReporterKeys; import com.hapramp.views.feedlist.FeedListView; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; /** * Created by Ankit on 4/14/2018. */ public class HotFragment extends Fragment implements FeedListView.FeedListViewListener{ @BindView(R.id.feedListView) FeedListView feedListView; private Unbinder unbinder; private Context context; @Override public void onAttach(Context context) { super.onAttach(context); this.context = context; AnalyticsUtil.getInstance(getActivity()).setCurrentScreen(getActivity(), AnalyticsParams.SCREEN_HOT, null); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Crashlytics.setString(CrashReporterKeys.UI_ACTION, "hot fragment"); setRetainInstance(true); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_hot, null); unbinder = ButterKnife.bind(this, view); return view; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { feedListView.setFeedListViewListener(this); feedListView.initialLoading(); fetchPosts(); } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } private void fetchPosts() { // rawApiCaller.requestHotFeeds(context); } //FEEDLIST CALLBACKS @Override public void onRetryFeedLoading() { fetchPosts(); } @Override public void onRefreshFeeds() { fetchPosts(); } @Override public void onLoadMoreFeeds() { } @Override public void onHideCommunityList() { //NA } @Override public void onShowCommunityList() { //NA } }
<filename>polymer-app/app/edit/src/d4l-header/d4l-header.js Polymer({ is: 'd4l-header', behaviors: [ D4L.Logging, D4L.Helpers ], properties: { logLevel: { type: Number, value: 3 }, app: { type: Object }, auth: { type: Object }, db: { type: Object, notify: true }, io: { type: Object }, mode: { type: String, value: 'detail' }, page: { type: String, observer: '__page' }, pageTitle: { type: String }, responsivePageTitle: { type: String, computed: '__computeResponsivePageTitle(pageTitle, app.title)' }, pageMode: { type: String }, header: { type: Object, notify: true }, allowBack: { type: Boolean, value: false }, isMobile: { type: Boolean, value: false }, __userImage: { type: String, computed: '__computeUserImage(auth.user.person.avatar)' } }, observers: [ ], __page: function() { Polymer.updateStyles(); }, __viewHome: function(){ this.fire('view-entity', '/'); }, __back: function() { this.fire('back-button-clicked'); }, __computeResponsivePageTitle: function(title) { const defaultTitle = this.get('app.title'); if (!title) return defaultTitle; return title; }, __computeUserImage: function(image){ const imageSize = /_normal/i; if (!image) { return; } return image.replace(imageSize, ''); } });
import re # define the regular expression reg_exp = re.compile(r'[A-Za-z]+') # function to test if a given string matches the regex def test_string(string): if re.match(reg_exp, string): print('The string matches the regualar expression.') else: print('The string does not match the regular expression.')
<reponame>jromay/gulp-json-structure-validator<gh_stars>1-10 var gutil = require('gulp-util'); var fs = require('fs'); var path = require('path'); var expect = require('chai').expect; var gulpJsonStructureValidator = require('../'); describe('test', function() { describe('plugin', function() { var file; beforeEach(function() { file = new gutil.File({ path: __dirname + '/fixture/diff-key.json', cwd: __dirname, base: __dirname + '/fixture' , contents: fs.readFileSync('./test/fixture/diff-key.json') }); }); it('should fail on forgotten key', function(done) { var stream = gulpJsonStructureValidator({template: __dirname + '/fixture/diff-key.json.templateerror'}); stream.on('error', function () { done(); }); stream.once('end', function () { expect(true).to.be.false; done(); }); stream.write(file); stream.end(); }); it('should not fail on equal structure', function(done) { var stream = gulpJsonStructureValidator({template: __dirname + '/fixture/diff-key.json.templateok'}); var count = 0; stream.on('data', function () { count++; }); stream.on('error', function () { expect(false).to.be.true; }); stream.once('end', function () { expect(count).to.equal(1); done(); }); stream.write(file); stream.end(); }); }); });
<reponame>frankpolte/UBIA<gh_stars>10-100 /* * app.h * * Created on: 05.11.2019 * Author: pvvx */ #ifndef APP_H_ #define APP_H_ void user_init(); void ExtDevPowerOn(); void ExtDevPowerOff(); static inline u32 clock_tik_exceed(u32 ref, u32 span_us){ return ((u32)(clock_time() - ref) > span_us); } #endif /* APP_H_ */
package consensus import ( "container/list" "sync" "github.com/nspcc-dev/neo-go/pkg/util" ) // relayCache is a payload cache which is used to store // last consensus payloads. type relayCache struct { *sync.RWMutex maxCap int elems map[util.Uint256]*list.Element queue *list.List } // hashable is a type of items which can be stored in the relayCache. type hashable interface { Hash() util.Uint256 } func newFIFOCache(capacity int) *relayCache { return &relayCache{ RWMutex: new(sync.RWMutex), maxCap: capacity, elems: make(map[util.Uint256]*list.Element), queue: list.New(), } } // Add adds payload into a cache if it doesn't already exist. func (c *relayCache) Add(p hashable) { c.Lock() defer c.Unlock() h := p.Hash() if c.elems[h] != nil { return } if c.queue.Len() >= c.maxCap { first := c.queue.Front() c.queue.Remove(first) delete(c.elems, first.Value.(hashable).Hash()) } e := c.queue.PushBack(p) c.elems[h] = e } // Has checks if an item is already in cache. func (c *relayCache) Has(h util.Uint256) bool { c.RLock() defer c.RUnlock() return c.elems[h] != nil } // Get returns payload with the specified hash from cache. func (c *relayCache) Get(h util.Uint256) hashable { c.RLock() defer c.RUnlock() e, ok := c.elems[h] if !ok { return hashable(nil) } return e.Value.(hashable) }
<filename>src/icons/legacy/Anchor.tsx // Generated by script, don't edit it please. import createSvgIcon from '../../createSvgIcon'; import AnchorSvg from '@rsuite/icon-font/lib/legacy/Anchor'; const Anchor = createSvgIcon({ as: AnchorSvg, ariaLabel: 'anchor', category: 'legacy', displayName: 'Anchor' }); export default Anchor;
def min_jumps(distance): jumps = [0] jump_distances = [] # Iterate through all possible jump distances for d in range(1, distance + 1): # Calculate the number of jumps for each jump distance min_jumps = float('inf') for j in jump_distances: if d - j >= 0: min_jumps = min(min_jumps, jumps[d - j] + 1) jumps.append(min_jumps) jump_distances.append(d) # Return the minimum number of jumps return jumps[distance] min_jumps(50)
# Program to query the data from the database SELECT * from countries WHERE population > 10000000
<filename>src/main/java/com/bot/commands/moderation/RemovePrefixCommand.java<gh_stars>10-100 package com.bot.commands.moderation; import com.bot.commands.ModerationCommand; import com.bot.db.GuildDAO; import com.bot.models.InternalGuild; import com.jagrosh.jdautilities.command.CommandEvent; import datadog.trace.api.Trace; import java.util.ArrayList; import java.util.Arrays; public class RemovePrefixCommand extends ModerationCommand { private GuildDAO guildDAO; public RemovePrefixCommand() { this.name = "removeprefix"; this.help = "Removes one or more custom prefixes from the current custom prefixes."; this.arguments = "<One or more custom prefixes, separated by spaces>"; guildDAO = GuildDAO.getInstance(); } @Override @Trace(operationName = "executeCommand", resourceName = "RemovePrefix") protected void executeCommand(CommandEvent commandEvent) { InternalGuild guild = guildDAO.getGuildById(commandEvent.getGuild().getId()); if (commandEvent.getArgs().isEmpty()) { commandEvent.reply(commandEvent.getClient().getWarning() + " You must specify at least one custom prefix to remove."); return; } ArrayList<String> prefixes = guild.getPrefixList(); prefixes.removeAll(Arrays.asList(commandEvent.getArgs().split(" "))); if (guildDAO.updateGuildPrefixes(commandEvent.getGuild().getId(), prefixes)) { commandEvent.getMessage().addReaction(commandEvent.getClient().getSuccess()).queue(); } else { commandEvent.reply(commandEvent.getClient().getError() + " Failed to update prefixes for server. Please contact a developer on the support server if this issue persists."); metricsManager.markCommandFailed(this, commandEvent.getAuthor(), commandEvent.getGuild()); } } }
package http import ( "../../cc" "../../cc/err" "../orm" "encoding/json" "io/ioutil" "stgogo/comn/convert" ) func init() { cc.AddActionGroup( "/v1x1/post/fav", func( a cc.ActionGroup ) error { a.GET( "/add", func( ap cc.ActionPackage ) ( cc.HttpErrReturn, cc.StatusCode ) { var ( e error pid string ) if pid = ap.R.FormValue("id"); pid == "" { return cc.HerArgInvalid( "id" ) } id, e := GetIdByAtk( ap.R ); err.Assert( e ) npid, e := convert.Atoi64( pid ); err.Assert( e ) _, e = orm.AddFav( id, npid ); err.Assert( e ) return cc.HerOk() } ) a.POST( "/update", func( ap cc.ActionPackage ) ( cc.HttpErrReturn, cc.StatusCode ) { var ( e error favList []int64 ) b, e := ioutil.ReadAll( ap.R.Body); err.Assert( e ) e = json.Unmarshal( b, &favList ); err.Assert( e ) id, e := GetIdByAtk( ap.R ); err.Assert( e ) _, e = orm.UpdateFav( id, favList ); err.Assert( e ) return cc.HerOk() } ) a.GET( "/remove", func( ap cc.ActionPackage ) ( cc.HttpErrReturn, cc.StatusCode ) { var ( e error pid string ) if pid = ap.R.FormValue("id"); pid == "" { return cc.HerArgInvalid( "id" ) } id, e := GetIdByAtk( ap.R ); err.Assert( e ) npid, e := convert.Atoi64( pid ); err.Assert( e ) _, e = orm.RemoveFav( id, npid ); err.Assert( e ) return cc.HerOk() } ) a.GET( "/check", func( ap cc.ActionPackage ) ( cc.HttpErrReturn, cc.StatusCode ) { var ( e error pid string isFav bool ) if pid = ap.R.FormValue("id"); pid == "" { return cc.HerArgInvalid( "id" ) } id, e := GetIdByAtk( ap.R ); err.Assert( e ) npid, e := convert.Atoi64( pid ); err.Assert( e ) isFav, e = orm.IsPostFav( id, npid ); err.Assert( e ) return cc.HerOkWithString( convert.Bool2a( isFav ) ) } ) return nil } ) }
import EmberObject from '@ember/object'; import EnterSubmitsFormMixin from 'ember-cli-text-support-mixins/mixins/enter-submits-form'; import { module, test } from 'qunit'; module('Unit | Mixin | enter submits form', function() { // Replace this with your real tests. test('it works', function (assert) { let EnterSubmitsFormObject = EmberObject.extend(EnterSubmitsFormMixin); let subject = EnterSubmitsFormObject.create(); assert.ok(subject); }); });
import { FC } from 'react'; export const Footer: FC = () => { return ( <footer className="px-4 sm:px-6 py-12 mt-24"> <p className="text-center text-sm dark:text-white text-black"> &copy;{new Date().getFullYear()}{' '} <a className="text-indipurp-500 font-bold underline focus:(font-bold text-indipurp-500) hover:text-indipurp-400" target="_blank" rel="noopener noreferrer" href="https://evanschaba.com" > <NAME> </a> . All rights reserved. </p> </footer> ); };
<reponame>eyny/clicktron<gh_stars>1-10 package com.clicktron; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.InputEvent; import javafx.scene.input.KeyCode; import javafx.scene.input.MouseButton; public class Model { /*************************************************************************** * * * Fields * * * **************************************************************************/ // Sets if the loop will not end until it is stopped by user private boolean loopInfinite; public boolean isLoopInfinite() {return loopInfinite;} public void setLoopInfinite(boolean loopInfinite) { this.loopInfinite = loopInfinite; } // Sets number of iteration in a finite loop private int loopCount; public int getLoopCount() {return loopCount;} public void setLoopCount(int loopCount) { this.loopCount = loopCount; } // Sets interval time in milliseconds between each iteration private int interval; public int getInterval() {return interval;} public void setInterval(int interval) { this.interval = interval; } // Sets consecutive press count for the button private int pressCount; public int getPressCount() {return pressCount;} public void setPressCount(int pressCount) { this.pressCount = pressCount; } // Sets if the cursor position is predetermined by user private boolean cursorCurrent; public boolean isCursorCurrent() {return cursorCurrent;} public void setCursorCurrent(boolean cursorCurrent) { this.cursorCurrent = cursorCurrent; } // Sets custom cursor position private int[] customCursorPos = new int[2]; public int getCustomCursorPos(int index) {return customCursorPos[index];} public void setCustomCursorPos(int x, int y) { this.customCursorPos[0] = x; this.customCursorPos[1] = y; } // Controller can assign a function to be called whenever the loop is ended public Runnable onLoopEnded; // Button storage and converter public ButtonStorage buttonStorage; // Private fields private Thread outerThread; private Robot robot; /*************************************************************************** * * * Methods * * * **************************************************************************/ // Constructor public Model() { buttonStorage = new ButtonStorage(); try { // The robot does not catch exception while working thus leave that job to Thread.sleep robot = new Robot() { @Override public synchronized void delay(int ms) { return; } }; } catch (Exception e) { e.printStackTrace(); } } // The loop to press mouse or keyboard button repeatedly private Runnable outerLoop = () -> { for (int i = 0; i < getLoopCount(); i++) { if (isLoopInfinite()) { i = 0; } try { Thread.sleep(getInterval()); } catch (InterruptedException e) { break; } for (int j = 0; j < getPressCount(); j++) { if (!isCursorCurrent()) { robot.mouseMove(getCustomCursorPos(0), getCustomCursorPos(1)); } if (this.buttonStorage.hasKeyCode) { int keyCode = this.buttonStorage.getKeyCode(); if (keyCode != 0) { robot.keyPress(keyCode); robot.keyRelease(keyCode); } } else { robot.mousePress(this.buttonStorage.getAwtMouseValue()); robot.mouseRelease(this.buttonStorage.getAwtMouseValue()); } } System.out.println(i + 1 + ". step is completed!"); } if (onLoopEnded != null) onLoopEnded.run(); }; // Start the loop public void startLoop() { outerThread = new Thread(outerLoop); outerThread.start(); } // Stop the loop public void stopLoop() { outerThread.interrupt(); } /*************************************************************************** * * * Inner Classes * * * **************************************************************************/ // Stores mouse and keyboard button information // Converts javaFX keyboard keys to AWT keys (Not required in JavaFX 11 due to javafx.scene.robot) public class ButtonStorage { private int awtKeyValue; private int awtMouseValue; private boolean hasKeyCode; private int generateAwtCode(MouseButton fxMouseButton) { if (fxMouseButton == MouseButton.PRIMARY) return InputEvent.BUTTON1_DOWN_MASK; else if (fxMouseButton == MouseButton.MIDDLE) return InputEvent.BUTTON2_DOWN_MASK; else if (fxMouseButton == MouseButton.SECONDARY) return InputEvent.BUTTON3_DOWN_MASK; return -1; } private int generateAwtCode(KeyCode fxKeyCode) { int finalCode = 0; String awtString = fxKeyCode.toString(); // Turn DIGIT[number] to [number] awtString = awtString.replaceAll("DIGIT",""); // Turn CAPS into CAPS_LOCK if (awtString.equals("CAPS")) awtString = "CAPS_LOCK"; // Add VK_ prefix awtString = "VK_" + awtString; try { finalCode = KeyEvent.class.getField(awtString).getInt(null); } catch (Exception e) { e.printStackTrace(); } return finalCode; } public int getAwtMouseValue() { return this.awtMouseValue; } public int getKeyCode() { return this.awtKeyValue; } public void setButton(MouseButton fxMouseButton) { this.hasKeyCode = false; this.awtMouseValue = generateAwtCode(fxMouseButton); } public void setButton(KeyCode fxKeyCode) { this.hasKeyCode = true; awtKeyValue = generateAwtCode(fxKeyCode); } } }
<filename>libs/uix/baseclass/home_screen.py<gh_stars>1-10 from kivymd.uix.screen import MDScreen import utils utils.load_kv("home_screen.kv") class HomeScreen(MDScreen): """ Example Screen. """ # def update_label(self): # HomeScreen().ids.lbl.text = self.formula # def add_number(self, instance): # if self.formula == '0': # self.formula = '' # self.formula += str(instance.text) # self.update_label()
#!/usr/bin/env bats # vim: set filetype=sh: load utils @test "grep_path" { . $APPMGR_HOME/share/appmgr/common x=`grep_path "app-.*" "$APPMGR_HOME/test/data/app-common:/does-not-exist"|sort|sed s,$APPMGR_HOME/,,|xargs` eq '$x' 'test/data/app-common/app-bar test/data/app-common/app-faz test/data/app-common/app-foo' x=`grep_path "app-f.*" "$APPMGR_HOME/test/data/app-common:/does-not-exist"|sort|sed s,$APPMGR_HOME/,,|xargs` eq '$x' 'test/data/app-common/app-faz test/data/app-common/app-foo' x=`grep_path "app-b.*" "$APPMGR_HOME/test/data/app-common:/does-not-exist:$APPMGR_HOME/test/data/app-common-extra"|sort|sed s,$APPMGR_HOME/,,|xargs` match '${x}' ".*/app-baz.*" }
if [ -f /usr/local/bin/modmeta-relay ]; then rm /usr/local/bin/modmeta-relay fi
package com.share.system.data.entity; import lombok.Data; @Data public class TimeQuery { /** * 开始时间 */ private String startTime; /** * 结束时间 */ private String endTime; }
export * from './RadioGroupTest';
#!/bin/sh if [[ "${CI}" ]]; then echo "CI environment detected. Skipping SwiftFormat." exit 0 fi if ! which swiftformat >/dev/null; then if which brew >/dev/null; then brew update && brew install swiftformat else echo "WARNING: Tried to automatically install SwiftFormat using `brew` but `brew` itself could not be found. Please install SwiftFormat manually and try again." fi fi if which swiftformat >/dev/null; then swiftformat . else echo "WARNING: SwiftFormat is missing. Please install it manually and try again." fi
<filename>GEP-Components/manager/routesmanager-api/src/main/java/com/esri/ges/manager/routes/DefaultRoute.java package com.esri.ges.manager.routes; import java.util.Date; import com.esri.ges.spatial.Geometry; import com.esri.ges.spatial.Point; public class DefaultRoute implements Route { private String driverName; private Date lastUpdated; private String passengerName; private Date routeEnd; private String routeName; private Date routeStart; private Geometry shape; private String vehicleName; private Point routeStartPoint; private Point routeEndPoint; private String dispatchAck; public DefaultRoute() { } public DefaultRoute( Route seed ) { if( seed != null ) { setDriverName( seed.getDriverName() ); setLastUpdated( seed.getLastUpdated() ); setPassengerName( seed.getPassengerName() ); setRouteEnd( seed.getRouteEnd() ); setRouteName( seed.getRouteName() ); setRouteStart( seed.getRouteStart() ); setShape( seed.getShape() ); setVehicleName( seed.getVehicleName() ); setRouteStartPoint( seed.getRouteStartPoint() ); setRouteEndPoint( seed.getRouteEndPoint() ); setDispatchAck( seed.getDispatchAck() ); } } @Override public String getDriverName() { return driverName; } @Override public Date getLastUpdated() { return lastUpdated; } @Override public String getPassengerName() { return passengerName; } @Override public Date getRouteEnd() { return routeEnd; } @Override public String getRouteName() { return routeName; } @Override public Date getRouteStart() { return routeStart; } @Override public Geometry getShape() { return shape; } @Override public String getVehicleName() { return vehicleName; } @Override public Point getRouteEndPoint() { return routeEndPoint; } @Override public Point getRouteStartPoint() { return routeStartPoint; } public void setDriverName(String driverName) { this.driverName = driverName; } public void setLastUpdated(Date lastUpdated) { this.lastUpdated = lastUpdated; } public void setPassengerName(String passengerName) { this.passengerName = passengerName; } public void setRouteEnd(Date routeEnd) { this.routeEnd = routeEnd; } public void setRouteName(String routeName) { this.routeName = routeName; } public void setRouteStart(Date routeStart) { this.routeStart = routeStart; } public void setShape(Geometry shape) { this.shape = shape; } public void setVehicleName(String vehicleName) { this.vehicleName = vehicleName; } public void setRouteEndPoint( Point routeEndPoint ) { this.routeEndPoint = routeEndPoint; } public void setRouteStartPoint( Point routeStartPoint ) { this.routeStartPoint = routeStartPoint; } @Override public String getDispatchAck() { return dispatchAck; } public void setDispatchAck(String dispatchAck) { this.dispatchAck = dispatchAck; } }
from matrixio_hal import sensors import time # IMU imu = sensors.IMU() while True: print("\x1B[2J") print("yaw: {}".format(imu.yaw)) print("pitch: {}".format(imu.pitch)) print("roll: {}".format(imu.roll)) print("accel_x: {}".format(imu.accel_x)) print("accel_y: {}".format(imu.accel_y)) print("accel_z: {}".format(imu.accel_z)) print("gyro_x: {}".format(imu.gyro_x)) print("gyro_y: {}".format(imu.gyro_y)) print("gyro_z: {}".format(imu.gyro_z)) print("mag_x: {}".format(imu.mag_x)) print("mag_y: {}".format(imu.mag_y)) print("mag_z: {}".format(imu.mag_z)) time.sleep(0.1) imu.update()
#!/bin/bash astyle --style=kr --indent=spaces --convert-tabs --recursive "./*.cpp" astyle --style=kr --indent=spaces --convert-tabs --recursive "./*.h" astyle --style=kr --indent=spaces --convert-tabs --recursive "./*.c"
<reponame>1Guardian/Opal-Browser<filename>gighmmpiobklfepjocnamgkkbiglidom/lib/options.js /* * This file is part of Adblock Plus <https://adblockplus.org/>, * Copyright (C) 2006-present eyeo GmbH * * Adblock Plus is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * Adblock Plus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. */ /** @module options */ "use strict"; const {checkWhitelisted} = require("./whitelisting"); const info = require("info"); const {port} = require("./messaging"); const optionsUrl = browser.runtime.getManifest().options_ui.page; const openOptionsPageAPISupported = ( // Some versions of Firefox for Android before version 57 do have a // runtime.openOptionsPage but it doesn't do anything. // https://bugzilla.mozilla.org/show_bug.cgi?id=1364945 (info.application != "fennec" || parseInt(info.applicationVersion, 10) >= 57) ); function findOptionsPage() { return browser.tabs.query({}).then(tabs => { return new Promise((resolve, reject) => { // Firefox won't let us query for moz-extension:// pages, though // starting with Firefox 56 an extension can query for its own URLs: // https://bugzilla.mozilla.org/show_bug.cgi?id=1271354 let fullOptionsUrl = browser.extension.getURL(optionsUrl); let optionsTab = tabs.find(tab => tab.url == fullOptionsUrl); if (optionsTab) { resolve(optionsTab); return; } // Newly created tabs might have about:blank as their URL in Firefox or // an empty string on Chrome (80) rather than the final options page URL, // we need to wait for those to finish loading. let potentialOptionTabIds = new Set( tabs.filter(tab => (tab.url == "about:blank" || !tab.url) && tab.status == "loading").map(tab => tab.id) ); if (potentialOptionTabIds.size == 0) { resolve(); return; } let removeListener; let updateListener = (tabId, changeInfo, tab) => { if (potentialOptionTabIds.has(tabId) && changeInfo.status == "complete") { potentialOptionTabIds.delete(tabId); let urlMatch = tab.url == fullOptionsUrl; if (urlMatch || potentialOptionTabIds.size == 0) { browser.tabs.onUpdated.removeListener(updateListener); browser.tabs.onRemoved.removeListener(removeListener); resolve(urlMatch ? tab : null); } } }; browser.tabs.onUpdated.addListener(updateListener); removeListener = removedTabId => { potentialOptionTabIds.delete(removedTabId); if (potentialOptionTabIds.size == 0) { browser.tabs.onUpdated.removeListener(updateListener); browser.tabs.onRemoved.removeListener(removeListener); } }; browser.tabs.onRemoved.addListener(removeListener); }); }); } function openOptionsPage() { if (openOptionsPageAPISupported) return browser.runtime.openOptionsPage(); return browser.tabs.create({url: optionsUrl}); } function waitForOptionsPage(tab) { return new Promise(resolve => { function onMessage(message, optionsPort) { if (message.type != "app.listen") return; optionsPort.onMessage.removeListener(onMessage); resolve([tab, optionsPort]); } function onConnect(optionsPort) { if (optionsPort.name != "ui" || optionsPort.sender.tab.id != tab.id) return; browser.runtime.onConnect.removeListener(onConnect); optionsPort.onMessage.addListener(onMessage); } browser.runtime.onConnect.addListener(onConnect); }); } function focusOptionsPage(tab) { if (openOptionsPageAPISupported) return browser.runtime.openOptionsPage(); let focusTab = () => browser.tabs.update(tab.id, {active: true}); if ("windows" in browser) return browser.windows.update(tab.windowId, {focused: true}).then(focusTab); // Firefox for Android before version 57 does not support // runtime.openOptionsPage, nor does it support the windows API. // Since there is effectively only one window on the mobile browser, // we can just bring the tab to focus instead. return focusTab(); } let showOptions = /** * Opens the options page, or switches to its existing tab. * @returns {Promise.<Array>} * Promise resolving to an Array containg the tab Object of the options page * and sometimes (when the page was just opened) a messaging port. */ exports.showOptions = () => { return findOptionsPage().then(existingTab => { if (existingTab) return focusOptionsPage(existingTab).then(() => existingTab); return openOptionsPage().then(findOptionsPage).then(waitForOptionsPage); }); }; // We need to clear the popup URL on Firefox for Android in order for the // options page to open instead of the bubble. Unfortunately there's a bug[1] // which prevents us from doing that, so we must avoid setting the URL on // Firefox from the manifest at all, instead setting it here only for // non-mobile. // [1] - https://bugzilla.mozilla.org/show_bug.cgi?id=1414613 if ("getBrowserInfo" in browser.runtime) { Promise.all([browser.browserAction.getPopup({}), browser.runtime.getBrowserInfo()]).then( ([popup, browserInfo]) => { if (!popup && browserInfo.name != "Fennec") browser.browserAction.setPopup({popup: "popup.html"}); } ); } // On Firefox for Android, open the options page directly when the browser // action is clicked. browser.browserAction.onClicked.addListener(() => { browser.tabs.query({active: true, lastFocusedWindow: true}).then( ([tab]) => { let currentPage = new ext.Page(tab); showOptions().then(([optionsTab, optionsPort]) => { if (!/^https?:$/.test(currentPage.url.protocol)) return; optionsPort.postMessage({ type: "app.respond", action: "showPageOptions", args: [ { host: currentPage.url.hostname.replace(/^www\./, ""), whitelisted: !!checkWhitelisted(currentPage) } ] }); }); } ); }); /** * Opens the options page in a new tab and waits for it to load, or switches to * the existing tab if the options page is already open. * * @event "options.open" * @returns {object} optionsTab */ port.on("options.open", (message, sender) => showOptions().then(([optionsTab, optionsPort]) => optionsTab) );
<gh_stars>0 package se.chalmers.watchmetest; /** * A class containing constant values used in testing of the application WatchME * @author mattiashenriksson * */ public class Constants { /** * Index for "Add movie"-button in add movie view in robotium ui-tests. */ public static final int ADD_MOVIE_BUTTON = 1; /** * Index for title text field in add movie view in robotium ui-tests. */ public static final int TITLE_FIELD = 0; /** * Index for tag field in add movie view in robotium ui-tests. */ public static final int TAG_FIELD = 1; /** * Index for note field in add movie view in robotium ui-tests. */ public static final int NOTE_FIELD = 2; /** * Index for date picker in add movie view in robotium ui-tests. */ public static final int DATE_PICKER = 0; /** * Index for rating bar in add movie view in robotium ui-tests. */ public static final int RATING_BAR = 0; /** * When added in view pager fragment gets an id. This is the tag lists id. */ public static final int TAG_LIST_FRAGMENT_VIEW_PAGER_ID = 1; /** * When added in view pager fragment gets an id. This is the tag lists id. */ public static final int MOVIE_LIST_FRAGMENT_VIEW_PAGER_ID = 0; /** * Milliseconds to wait before closing a dialog in robotium ui-tests. */ public static final int WAIT_FOR_DIALOG_TO_CLOSE_TIME = 1000; }
version=$(git describe --tags --dirty) buildTime=$(date +"%F %T%Z") echo -X "'"github.com/mt-inside/badpod/pkg/data.Version=${version}"'" -X "'"github.com/mt-inside/badpod/pkg/data.BuildTime=${buildTime}"'"
CREATE TABLE users ( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, username VARCHAR(255) UNIQUE, email VARCHAR(255) UNIQUE, password VARCHAR(255) NOT NULL ); CREATE TABLE threads( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255) NOT NULL, category_id INT NOT NULL, user_id INT NOT NULL ); CREATE TABLE posts( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, thread_id INT NOT NULL, user_id INT NOT NULL, body TEXT ); CREATE TABLE categories( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL );
private class CustomIterator implements Iterator<Integer> { private int cursor; @Override public boolean hasNext() { return cursor < elements.size(); } @Override public Integer next() { int element = elements.get(cursor); cursor++; if (element % 2 == 0) { return element * 2; // Double the value if the element is even } else { return element * element; // Square the value if the element is odd } } }
<filename>player/src/test/java/fr/unice/polytech/si3/qgl/soyouz/classes/objectives/sailor/RowersObjectiveTest.java package fr.unice.polytech.si3.qgl.soyouz.classes.objectives.sailor; import fr.unice.polytech.si3.qgl.soyouz.classes.actions.MoveAction; import fr.unice.polytech.si3.qgl.soyouz.classes.actions.OarAction; import fr.unice.polytech.si3.qgl.soyouz.classes.marineland.Deck; import fr.unice.polytech.si3.qgl.soyouz.classes.marineland.Marin; import fr.unice.polytech.si3.qgl.soyouz.classes.marineland.entities.Bateau; import fr.unice.polytech.si3.qgl.soyouz.classes.marineland.entities.onboard.DeckEntity; import fr.unice.polytech.si3.qgl.soyouz.classes.marineland.entities.onboard.Rame; import fr.unice.polytech.si3.qgl.soyouz.classes.utilities.Pair; import fr.unice.polytech.si3.qgl.soyouz.classes.utilities.Util; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.*; class RowersObjectiveTest { RowersObjective roLeft; RowersObjective roRight; @BeforeEach void setUp() { DeckEntity[] ent = { new Rame(0, 0), new Rame(0, 2), new Rame(1, 0), new Rame(1, 2), new Rame(2, 2) }; Bateau ship = new Bateau("Peqoq", new Deck(3, 3), ent); List<Marin> immutableRower = new ArrayList<>(); immutableRower.add(new Marin(0, 2, 2, "Tom")); immutableRower.add(new Marin(2, 1, 2, "Tim")); List<Marin> mutableRower = new ArrayList<>(); mutableRower.add(new Marin(1, 0, 1, "Tam")); List<Marin> immutableRower2 = new ArrayList<>(); immutableRower2.add(new Marin(3, 0, 0, "Tum")); immutableRower2.add(new Marin(4, 1, 0, "Tym")); List<Marin> mutableRower2 = new ArrayList<>(); List<Marin> immutableRowerLeft = immutableRower.stream().filter(rower -> rower.getY() == 0) .collect(Collectors.toList()); List<Marin> immutableRowerRight = immutableRower.stream().filter(rower -> rower.getY() > 0) .collect(Collectors.toList()); List<Marin> immutableRower2Left = immutableRower2.stream().filter(rower -> rower.getY() == 0) .collect(Collectors.toList()); List<Marin> immutableRower2Right = immutableRower2.stream().filter(rower -> rower.getY() > 0) .collect(Collectors.toList()); mutableRower2.add(new Marin(5, 0, 1, "Tem")); roLeft = new RowersObjective(ship, mutableRower, immutableRowerLeft, immutableRowerRight, Pair.of(2, 1)); roRight = new RowersObjective(ship, mutableRower2, immutableRower2Left, immutableRower2Right, Pair.of(1, 2)); } @Test void isValidated() { assertFalse(roLeft.isValidated()); assertFalse(roRight.isValidated()); roLeft.resolve(); roRight.resolve(); assertTrue(roLeft.isValidated()); assertTrue(roRight.isValidated()); } @Test void resolve() { List<MoveAction> nbMoveActionRoLeft = Util.filterType(roLeft.resolve().stream() .filter(act -> act instanceof MoveAction), MoveAction.class).collect(Collectors.toList()); long nbOarActionRoLeft = roLeft.resolve().stream().filter(act -> act instanceof OarAction).count(); List<MoveAction> nbMoveActionRoRight = Util.filterType(roRight.resolve().stream() .filter(act -> act instanceof MoveAction), MoveAction.class).collect(Collectors.toList()); long nbOarActionRoRight = roRight.resolve().stream().filter(act -> act instanceof OarAction).count(); assertEquals(1, nbMoveActionRoLeft.size()); assertEquals(3, nbOarActionRoLeft); assertEquals(1, nbMoveActionRoRight.size()); assertEquals(3, nbOarActionRoRight); nbMoveActionRoLeft.forEach(act -> { assertEquals(-1, act.getYDistance()); assertEquals(0, act.getXDistance()); }); nbMoveActionRoRight.forEach(act -> { assertEquals(1, act.getYDistance()); assertEquals(0, act.getXDistance()); }); } }
#!/usr/bin/env bash root_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" if ! kubectl get ns "{{ (datasource "config").onepassword.namespace }}" &> /dev/null; then kubectl create ns "{{ (datasource "config").onepassword.namespace }}" fi helm repo add 1password https://1password.github.io/connect-helm-charts/ helm repo update helm upgrade --install connect 1password/connect \ -n "{{ (datasource "config").onepassword.namespace }}" \ --version "{{ (datasource "config").onepassword.chart_version }}" \ --set operator.create=true \ --set operator.token.value="{{ (datasource "config").onepassword.operator.token }}" \ --set operator.watchNamespace="{{ (datasource "config").onepassword.operator.watchNamespace }}" \ --set-file "connect.credentials={{ (datasource "config").onepassword.credentials }}"
TERMUX_PKG_HOMEPAGE=http://developer.android.com/tools/help/index.html TERMUX_PKG_DESCRIPTION="Command which takes in class files and reformulates them for usage on Android" TERMUX_PKG_LICENSE="Apache-2.0" TERMUX_PKG_VERSION=$TERMUX_ANDROID_BUILD_TOOLS_VERSION TERMUX_PKG_PLATFORM_INDEPENDENT=true termux_step_make_install () { # Rewrite packages to avoid using com.android.* classes which may clash with # classes in the Android runtime on devices (see #1801): local JARJAR=$TERMUX_PKG_CACHEDIR/jarjar.jar local RULEFILE=$TERMUX_PKG_TMPDIR/jarjar-rule.txt local REWRITTEN_DX=$TERMUX_PKG_TMPDIR/dx-rewritten.jar termux_download \ http://central.maven.org/maven2/com/googlecode/jarjar/jarjar/1.3/jarjar-1.3.jar \ $JARJAR \ 4225c8ee1bf3079c4b07c76fe03c3e28809a22204db6249c9417efa4f804b3a7 echo 'rule com.android.** dx.@1' > $RULEFILE java -jar $JARJAR process $RULEFILE \ $ANDROID_HOME/build-tools/${TERMUX_PKG_VERSION}/lib/dx.jar \ $REWRITTEN_DX # Dex the rewritten jar file: mkdir -p $TERMUX_PREFIX/share/dex $TERMUX_D8 \ --release \ --min-api 21 \ --output $TERMUX_PKG_TMPDIR \ $REWRITTEN_DX cd $TERMUX_PKG_TMPDIR jar cf dx.jar classes.dex mv dx.jar $TERMUX_PREFIX/share/dex/dx.jar install $TERMUX_PKG_BUILDER_DIR/dx $TERMUX_PREFIX/bin/dx perl -p -i -e "s%\@TERMUX_PREFIX\@%${TERMUX_PREFIX}%g" $TERMUX_PREFIX/bin/dx }
def extract_percent_rsrzoutliers(val_summ: dict) -> float: if "percent_rsrzoutliers" in val_summ: return val_summ["percent_rsrzoutliers"] else: return 0
#!/bin/sh # Copyright (c) 2015 The Sikacoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. DIR="$1" COMMIT="$2" if [ -z "$COMMIT" ]; then COMMIT=HEAD fi # Taken from git-subtree (Copyright (C) 2009 Avery Pennarun <apenwarr@gmail.com>) find_latest_squash() { dir="$1" sq= main= sub= git log --grep="^git-subtree-dir: $dir/*\$" \ --pretty=format:'START %H%n%s%n%n%b%nEND%n' "$COMMIT" | while read a b junk; do case "$a" in START) sq="$b" ;; git-subtree-mainline:) main="$b" ;; git-subtree-split:) sub="$b" ;; END) if [ -n "$sub" ]; then if [ -n "$main" ]; then # a rejoin commit? # Pretend its sub was a squash. sq="$sub" fi echo "$sq" "$sub" break fi sq= main= sub= ;; esac done } latest_squash="$(find_latest_squash "$DIR")" if [ -z "$latest_squash" ]; then echo "ERROR: $DIR is not a subtree" >&2 exit 2 fi set $latest_squash old=$1 rev=$2 if [ "d$(git cat-file -t $rev 2>/dev/null)" != dcommit ]; then echo "ERROR: subtree commit $rev unavailable. Fetch/update the subtree repository" >&2 exit 2 fi tree_subtree=$(git show -s --format="%T" $rev) echo "$DIR in $COMMIT was last updated to upstream commit $rev (tree $tree_subtree)" tree_actual=$(git ls-tree -d "$COMMIT" "$DIR" | head -n 1) if [ -z "$tree_actual" ]; then echo "FAIL: subtree directory $DIR not found in $COMMIT" >&2 exit 1 fi set $tree_actual tree_actual_type=$2 tree_actual_tree=$3 echo "$DIR in $COMMIT currently refers to $tree_actual_type $tree_actual_tree" if [ "d$tree_actual_type" != "dtree" ]; then echo "FAIL: subtree directory $DIR is not a tree in $COMMIT" >&2 exit 1 fi if [ "$tree_actual_tree" != "$tree_subtree" ]; then git diff-tree $tree_actual_tree $tree_subtree >&2 echo "FAIL: subtree directory tree doesn't match subtree commit tree" >&2 exit 1 fi echo "GOOD"
<gh_stars>1-10 /** Flexible interface for persistent entities using ES6 classes and mixins * and <NAME>'s node-postgres * @requires validate.js * @author jcondor * @license * Copyright 2020 <NAME> * All rights reserved * This software is licensed under the MIT license found in the file LICENSE * in the root directory of this repository */ 'use strict' const Params = require('./QueryParameters') const validate = require('validate.js') const help = require('./helpers') /** Generate a base class for a database-persistent subclass or data structure * from another class (i.e. function-style mixin) * @param {Class} Base - Base class to extend * @example * // Create a persistent user from a user which does not support a database * class VolatileUser { ... } * class User extends Perseest.Mixin(VolatileUser) { * static db = new Perseest.Config(table, pk, { ... }); * } * @returns {Class} Extended (i.e. mixed) class to be used as the base class * for a persistent subclass */ function Mixin (Base) { if (!Base) Base = class {} class PerseestClass extends Base { /** Base class for a database-persistent subclass or data structure * @param {...*} args - Arguments for the superclass constructor */ constructor (...args) { super(...args) if (!this.exists) this.exists = false } /** Save the entity in the database. If the entity exists already (i.e. * 'this.exists' is truthy, fallback to update() * @throws Database must raise no errors * @throws Hooks must run successfully * @returns {boolean} true if the user was saved, false otherwise */ async save () { try { if (this.exists) { return await this.update() } const ret = await this.constructor.db.queries.run('save', new Params({ conf: this.constructor.db, ent: this, columns: [...this.constructor.db.columns] .filter(([k, v]) => !this.constructor.db.columns.attribute(k, 'serial')) .map(([k, v]) => k) })) if (ret) this.exists = true return ret } catch (err) { throw err } } /** Update entity columns selectively * @param {array} args - Fields to update * @throws Specified keys must be valid persistent properties * @throws Database must raise no errors * @throws Hooks must run successfully * @example something.update(); // Update all the entity keys * @example * // Update just email and name for a user * user.update('email', 'name') * user.update(['email','name']) // Works equally * user.update(new Set(['email','name'])) // Any iterable collection works * @returns {boolean} true if the user was updated, false otherwise */ async update (...keys) { // Update all the columns if none is specified if (keys.length === 0) { keys = [...this.constructor.db.columns] .filter(([k, v]) => !this.constructor.db.columns.attribute(k, 'serial')) .map(([k, v]) => k) } // If specific keys are given, validate them else { if (!validate.isString(keys[0]) && help.isIterable(keys[0])) { keys = keys[0] } for (const k of keys) { if (!validate.isString(k)) { throw new TypeError('Columns must be specified as strings') } if (!this.constructor.db.columns.has(k)) { throw new Error(`${k} is not present in the database table`) } } } // Query the database try { return await this.constructor.db.queries.run('update', new Params({ conf: this.constructor.db, ent: this, columns: keys })) } catch (err) { throw err } } /** Fetch an entity from the database using an arbitrary identifier * @param {string} key - Identifier column * @param {*} value - Identifier value * @throus Key must be a column usable as a univocal identifier * @throws Database must raise no errors * @throws Hooks must run successfully * @returns {*|null} The fetched entity, or null if it does not exist */ static async fetch (key, value) { if (!this.db.columns.attribute(key, 'id')) { throw new Error(`Field ${key} is not a univocal identifier`) } try { return await this.db.queries.run('fetch', new Params({ conf: this.db, key: key, kval: value })) } catch (err) { throw err } } /** Fetch multiple entities according to a match condition * @param {object} cond - Match condition in the form { column: value } * @returns {Array<*>} An array containing the fetched entities */ static async fetchMany (cond = {}) { const [cols, vals] = Object.entries(cond) .reduce((acc, [k, v]) => [acc[0].concat(k), acc[1].concat(v)], [[], []]) try { return await this.db.queries.run('fetchMany', new Params({ conf: this.db, columns: cols, values: vals })) } catch (err) { throw err } } /** Remove the entity from the database * @throws Database must raise no errors * @throws Hooks must run successfully * @returns {boolean} true if the entity was removed, false if not found */ async delete () { // Hooks delegated to the static delete function return (!this.exists) ? false : await this.constructor.delete( this.constructor.db.primaryKey, this[this.constructor.db.primaryKey]) } /** Remove a user by arbitrary key-value pair (key must be an identifier) * @param {string} key - Field used as univocal identifier * @param {string} value - Identifier value * @throws Key must be a column usable as univocal identifier * @throws Identifier value must be valid * @throws Database must raise no errors * @throws Hooks must run successfully * @returns {boolean} true if the user was removed, false if not found */ static async delete (key, value) { if (!this.db.columns.attribute(key, 'id')) { throw new Error(`Field ${key} is not a univocal identifier`) } try { return await this.db.queries.run('delete', new Params({ conf: this.db, key: key, kval: value })) } catch (err) { throw err } } /** Remove multiple users according to a match condition * @param {object} cond - Match condition in the form { column: value } * @returns {number} the number of deleted columns */ static async deleteMany (cond = {}) { const [cols, vals] = Object.entries(cond) .reduce((acc, [k, v]) => [acc[0].concat(k), acc[1].concat(v)], [[], []]) if (!cols.length) { throw new Error('Attempted to call deleteMany without a delete condition') } try { return await this.db.queries.run('deleteMany', new Params({ conf: this.db, columns: cols, values: vals })) } catch (err) { throw err } } } return PerseestClass } module.exports = { PerseestMixin: Mixin, PerseestClass: Mixin() }
/* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable @typescript-eslint/explicit-module-boundary-types */ import { call, put, all, takeEvery, takeLatest, select } from 'redux-saga/effects'; import { AxiosResponse } from 'axios'; import * as stocksActions from 'src/redux/Stocks/Actions'; import * as api from '@share/Api'; import { ActionTypes, Actions, DataDomain } from 'src/redux/Stocks/Types'; import { selectFavoriteSymbols } from 'src/redux/Favorites/Selectors'; /** * Initiate the fetching of stock quote. * It will dispatch STOCKS/FETCH_STOCK_QUOTE_PENDING action. * Once the fetching is successful, it will dispatch FETCH_STOCK_QUOTE_FULFILLED action. * If the fetching failed, it will dispatch FETCH_STOCK_QUOTE_REJECTED action. * * @param action - Fetch stock quote action creator */ export function* fetchStockQuoteSaga(action: Actions.Quote.FetchAction) { try { yield put(stocksActions.fetchStockQuotePending(action.stockSymbol)); const response = yield call(api.fetchStockQuoteUrl, action.stockSymbol); yield put(stocksActions.fetchStockQuoteFulfilled(action.stockSymbol, response.data)); } catch (error) { yield put(stocksActions.fetchStockQuoteRejected(action.stockSymbol, error)); } } /** * Initiate the fetching of stock Chart data. * It will dispatch STOCKS/FETCH_STOCK_CHART_PENDING action. * STOCKS/FETCH_STOCK_CHART_FULFILLED action will be dispatched if data fetching was successful. * STOCKS/FETCH_STOCK_CHART_REJECTED action will be dispatched if data fetching was unsuccessful. * * @param action - Fetch stock Chart action */ export function* fetchStockChartSaga(action: Actions.Chart.FetchAction) { try { const { stockSymbol, chartRange } = action; yield put(stocksActions.fetchStockChartPending(action.stockSymbol)); const response = yield call(api.fetchStockChartUrl, stockSymbol, chartRange); yield put(stocksActions.fetchStockChartFulfilled(action.stockSymbol, response.data)); } catch (error) { yield put(stocksActions.fetchStockChartRejected(action.stockSymbol, error)); } } /** * Initiate the fetching of stock quote batch data. * It will dispatch STOCKS/FETCH_STOCK_QUOTE_PENDING action to the provided stock symbols. * STOCKS/FETCH_STOCK_QUOTE_FULFILLED action will dispatched for corresponding stock symbol if data fetching was successful. * STOCKS/FETCH_STOCK_QUOTE_REJECTED action will dispatched for corresponding stock symbol if data fetching was unsuccessful. * * @param action - Fetch stock quote batch action */ export function* fetchStockQuoteBatchSaga(action: Actions.Batch.FetchQuoteAction) { try { const stockSymbols: string[] = yield select(selectFavoriteSymbols); yield all(stockSymbols.map((stock) => put(stocksActions.fetchStockQuotePending(stock)))); const response: AxiosResponse<DataDomain.QuoteBatch> = yield call( api.fetchStockQuoteBatchUrl, stockSymbols, ); const { data } = response; yield all( stockSymbols.map((stock) => put(stocksActions.fetchStockQuoteFulfilled(stock, data[stock].quote)), ), ); } catch (error) { const stockSymbols: string[] = yield select(selectFavoriteSymbols); yield all( stockSymbols.map((stock) => put(stocksActions.fetchStockQuoteRejected(stock, error))), ); } } // /** // * Initiate the fetching of stock chart batch data. // * It will dispatch STOCKS/FETCH_STOCK_CHART_PENDING action to the provided stock symbols. // * STOCKS/FETCH_STOCK_CHART_FULFILLED action will dispatched for corresponding stock symbol if data fetching was successful. // * STOCKS/FETCH_STOCK_CHART_REJECTED action will dispatched for corresponding stock symbol if data fetching was unsuccessful. // * // * @param action - Fetch stock chart batch action // */ // export function* fetchStockChartBatchSaga(action: FetchStockChartBatchAction) { // try { // const { stockSymbols, range, sort } = action; // for (const stock of stockSymbols) { // yield put(stocksActions.fetchStockChartPending(stock)); // } // const response: AxiosResponse<StockChartBatch> = yield call( // api.fetchStockChartBatchUrl, // stockSymbols, // range, // sort, // ); // const { data } = response; // for (const [symbol, stockChartData] of Object.entries(data)) { // yield put(stocksActions.fetchStockChartFulfilled(symbol, stockChartData.chart)); // } // } catch (error) { // for (const stock of action.stockSymbols) { // yield put(stocksActions.fetchStockChartRejected(stock, error)); // } // } // } // /** // * Initiate the fetching of stock chart batch data. // * It will dispatch STOCKS/FETCH_STOCK_QUOTE_PENDING and STOCKS/FETCH_STOCK_CHART_PENDING action to the provided stock symbols. // * STOCKS/FETCH_STOCK_QUOTE_FULFILLED and STOCKS/FETCH_STOCK_CHART_FULFILLED action will dispatched for corresponding stock symbol if data fetching was successful. // * STOCKS/FETCH_STOCK_QUOTE_REJECTED and STOCKS/FETCH_STOCK_CHART_REJECTED action will dispatched for corresponding stock symbol if data fetching was unsuccessful. // * // * @param action - Fetch stock chart batch action // */ // export function* fetchStockQuoteChartBatchSaga(action: FetchStockQuoteChartBatchAction) { // try { // const { stockSymbols, range, sort } = action; // for (const stock of stockSymbols) { // yield put(stocksActions.fetchStockQuotePending(stock)); // yield put(stocksActions.fetchStockChartPending(stock)); // } // const response: AxiosResponse<StockQuoteChartBatch> = yield call( // api.fetchStockQuoteChartBatchUrl, // stockSymbols, // range, // sort, // ); // const { data } = response; // for (const [symbol, stockChartData] of Object.entries(data)) { // yield put(stocksActions.fetchStockQuoteFulfilled(symbol, stockChartData.quote)); // yield put(stocksActions.fetchStockChartFulfilled(symbol, stockChartData.chart)); // } // } catch (error) { // for (const stock of action.stockSymbols) { // yield put(stocksActions.fetchStockQuoteRejected(stock, error)); // yield put(stocksActions.fetchStockChartRejected(stock, error)); // } // } // } /** * Initiate the fetching of Symbols metadata. * * It will dispatch STOCKS/FETCH_SYMBOLS_METADATA_PENDING action. * STOCKS/FETCH_SYMBOLS_METADATA_FULFILLED action is dispatched if data fetching was successful. * STOCKS/FETCH_SYMBOLS_METADATA_REJECTED action is dispatched if data fetching was unsuccessful. * * @param action - Fetch Symbols metadata action */ export function* fetchSymbolsMetadataSaga(action: Actions.SymbolsMetadata.FetchAction) { try { yield put(stocksActions.fetchSymbolsMetadataPending()); const response = yield call(api.fetchSymbolsMetadataUrl); yield put(stocksActions.fetchSymbolsMetadataFulfilled(response.data)); } catch (error) { yield put(stocksActions.fetchSymbolsMetadataRejected(error)); } } export default function* watchStocksSagas() { yield takeEvery(ActionTypes.FETCH_STOCK_QUOTE, fetchStockQuoteSaga); yield takeEvery(ActionTypes.FETCH_STOCK_CHART, fetchStockChartSaga); yield takeLatest(ActionTypes.FETCH_STOCK_QUOTE_BATCH, fetchStockQuoteBatchSaga); // yield takeLatest(ActionTypes.FETCH_STOCK_CHART_BATCH, fetchStockChartBatchSaga); // yield takeLatest(ActionTypes.FETCH_STOCK_QUOTE_CHART_BATCH, fetchStockQuoteChartBatchSaga); yield takeLatest(ActionTypes.FETCH_SYMBOLS_METADATA, fetchSymbolsMetadataSaga); }
function areAnagrams(str1, str2) { let s1 = str1.split('').sort().join(''); let s2 = str2.split('').sort().join(''); if (s1 == s2) { return true; } return false; } console.log(areAnagrams("listen", "silent")); // Output: true
<reponame>skatsuta/8086disasm<gh_stars>0 // generated by stringer -type=Sreg; DO NOT EDIT package disasm import "fmt" const _Sreg_name = "escsssds" var _Sreg_index = [...]uint8{0, 2, 4, 6, 8} func (i Sreg) String() string { if i < 0 || i+1 >= Sreg(len(_Sreg_index)) { return fmt.Sprintf("Sreg(%d)", i) } return _Sreg_name[_Sreg_index[i]:_Sreg_index[i+1]] }
/* * Copyright (c) 2015, EURECOM (www.eurecom.fr) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the FreeBSD Project. */ #if HAVE_CONFIG_H # include "config.h" #endif #include <stdio.h> #include <stdint.h> #define G_LOG_DOMAIN ("UI") #include <gtk/gtk.h> #include "rc.h" #include "ui_notebook.h" #include "ui_tree_view.h" #include "ui_signal_dissect_view.h" static ui_text_view_t *terminal_view; void ui_notebook_terminal_clear ( void) { ui_signal_dissect_clear_view (terminal_view); } void ui_notebook_terminal_append_data ( gchar * text, gint length) { ui_signal_set_text (terminal_view, text, length); } int ui_notebook_create ( GtkWidget * vbox) { GtkWidget *notebook; GtkWidget *vbox_notebook, *vbox_terminal; if (!vbox) return RC_BAD_PARAM; notebook = gtk_notebook_new (); vbox_notebook = gtk_box_new (GTK_ORIENTATION_VERTICAL, 0); ui_tree_view_create (NULL, vbox_notebook); gtk_notebook_append_page (GTK_NOTEBOOK (notebook), vbox_notebook, NULL); gtk_notebook_set_tab_label_text (GTK_NOTEBOOK (notebook), vbox_notebook, "Messages list"); #if defined (FILTERS_TAB) vbox_notebook = gtk_box_new (GTK_ORIENTATION_VERTICAL, 0); gtk_notebook_append_page (GTK_NOTEBOOK (notebook), vbox_notebook, NULL); gtk_notebook_set_tab_label_text (GTK_NOTEBOOK (notebook), vbox_notebook, "Filters"); #endif vbox_notebook = gtk_box_new (GTK_ORIENTATION_VERTICAL, 0); gtk_notebook_append_page (GTK_NOTEBOOK (notebook), vbox_notebook, NULL); gtk_notebook_set_tab_label_text (GTK_NOTEBOOK (notebook), vbox_notebook, "Terminal"); vbox_terminal = gtk_paned_new (GTK_ORIENTATION_HORIZONTAL); terminal_view = ui_signal_dissect_new (vbox_terminal); gtk_box_pack_start (GTK_BOX (vbox_notebook), vbox_terminal, TRUE, TRUE, 5); /* * Add the notebook to the vbox of the main window */ gtk_box_pack_start (GTK_BOX (vbox), notebook, TRUE, TRUE, 0); return RC_OK; }
const unique = arr => [...new Set(arr)]; unique([1, 3, 2, 1, 3, 4]); // [1, 2, 3, 4]
#!/bin/bash if [[ $# -lt 1 ]] then echo "Usage: $0 <service-name>" exit 1 fi # Retrieve route information GET_ROUTE=`oc get route $1 -o JSON` if [[ $? -ne 0 ]] then echo "Error. Cannot obtain route for ${1}" exit 1 fi # extract host name from response HOST_NAME=`echo ${GET_ROUTE} | jq '.spec.host' | cut -d'"' -f 2` # generate /model/predict endpoint URL ENDPOINT_URL="http://${HOST_NAME}/model/predict" # display URL echo $ENDPOINT_URL
class BugDataset(object): def __init__(self, file): f = open(file, 'r') self.info = f.readline().strip() def find_duplicates(self): duplicates = [] bug_reports = self.info.split('\n') for bug_report in bug_reports: bug_info = bug_report.split() bug_id = bug_info[0] for duplicate_id in bug_info[1:]: duplicates.append((bug_id, duplicate_id)) return duplicates
<gh_stars>0 const chalk = require("chalk"), shell = require("shelljs"); const {name, version} = JSON.parse(shell.cat("package.json")); module.exports = function(subtitle = "development script") { shell.exec("clear"); shell.echo(chalk` {bold.rgb(55,125,71) ${name} v${version}} {rgb(55,125,71) ${subtitle}} `); };
var searchData= [ ['color',['Color',['../classColor.html',1,'']]], ['config',['Config',['../classConfig.html',1,'']]], ['configviz',['ConfigViz',['../classConfigViz.html',1,'']]] ];
<gh_stars>0 import React from 'react'; // nodejs library that concatenates classes // @material-ui/core components import { makeStyles } from '@material-ui/core/styles'; import classNames from 'classnames'; // @material-ui/icons import GridItem from 'components/Grid/GridItem.js'; import sectionTextStyle from 'assets/jss/material-kit-pro-react/views/blogPostSections/sectionTextStyle.js'; import GridContainer from 'components/Grid/GridContainer'; const useStyles = makeStyles(sectionTextStyle); export default function Results() { const classes = useStyles(); const imgClasses = classNames( classes.imgRaised, classes.imgRounded, classes.imgFluid ); return ( <GridContainer justify="center"> <GridItem xs={12} sm={10} md={10} className={classes.section}> <GridContainer justify="center"> <GridItem xs={12} sm={10} md={10}> <h3 className={classes.title}>Results</h3> <p> I used the python folium library to visualize geographic details of Baton Rouge and its neighborhoods. </p> <br /> </GridItem> </GridContainer> <GridContainer justify="center"> <GridItem xs={5} sm={5} md={5}> <h3 className={classes.title}>Baton Rouge Neighborhoods</h3> <img src={"https://tntheall.s3.amazonaws.com/assets/data/foliummap.PNG"} alt="folium map" className={imgClasses} /> <p> A map created from geospatial data of the East Baton Rouge Area </p> <a href="https://opendata.arcgis.com/datasets/7c5e82ef83834de2ad2478efc86744ae_0.geojson" target="_blank" rel="noreferrer" > Housing Data </a> </GridItem> <GridItem xs={5} sm={5} md={5}> <h3 className={classes.title}>Pandas Data Frame Head</h3> <img src={"https://tntheall.s3.amazonaws.com/assets/data/avgCoordDataFrame.PNG"} alt="Pandas Data Frame Coordinates Head" className={imgClasses} /> <p> A map created from geospatial data of the East Baton Rouge Area </p> <a href="https://opendata.arcgis.com/datasets/7c5e82ef83834de2ad2478efc86744ae_0.geojson" target="_blank" rel="noreferrer" > Housing Data </a> </GridItem> </GridContainer> <GridContainer justify="center"> <GridItem xs={12} sm={10} md={10}> <p> I utilized the Foursquare API to explore the restaurants in each neighborhood and segment them. I designed the limit as 50 venues. I used the section {'"'}food{'"'} and sorted by popularity. The radius is the maximum distance between the two geolocations converted to meters from each neighborhood based on their given latitude and longitude information. The radius is the maximum distance between the two geolocations converted to meters from each neighborhood based on their given latitude and longitude information. </p> <p> The search resulted in 1514 venues with 57 unique Restaurant Categories </p> <p> Each of these results was run through a KMeans clustering algorithm. The best K was determined using the elbow method. 3 clusters was determined to be the best grouping. </p> </GridItem> </GridContainer> <GridContainer justify="center"> <GridItem xs={5} sm={5} md={5}> <h3>Elbow Method using distortion</h3> <img src={"https://tntheall.s3.amazonaws.com/assets/data/elbowDistortion.PNG"} alt="eblow method using distortion" className={imgClasses} /> </GridItem> <GridItem xs={5} sm={5} md={5}> <h3>Elbow Method using intertia</h3> <img src={"https://tntheall.s3.amazonaws.com/assets/data/elbowIntertia.PNG"} alt="eblow method using intertia" className={imgClasses} /> </GridItem> </GridContainer> <GridContainer justify="center"> <GridItem xs={12} sm={10} md={10}> <h3>Baton Rouge Neighborhoods Most Common Restaurants Clusters</h3> <img src={"https://tntheall.s3.amazonaws.com/assets/data/foliumCluster.PNG"} className={imgClasses} alt="Map of Baton Rouge Neighborhood Clusters" /> <p> A map created from K-means clustering of the East Baton Rouge Area. The Zillow Housing Score was added to make a Cholorpleth map. Data could not be obtained for the black neighborhoods. The darker green neighborhoods where housing is more expensive. While the lighter green neighborhoods are cheaper. </p> <a href="https://www.zillow.com/baton-rouge-la/home-values/" target="_blank" rel="noreferrer" > Housing Data </a> <a href="https://github.com/travistheall/Coursera_Capstone/blob/master/notebooks/Api%20Popular%20Restaurants.ipynb" target="_blank" rel="noreferrer" > Jupytr Notebook </a> </GridItem> </GridContainer> <GridContainer justify="center"> <GridItem xs={3} sm={3} md={3}> <h3>Cluster 0 (Red Dots) Common Categories</h3> <img src={"https://tntheall.s3.amazonaws.com/assets/data/MostCommonCluster0.PNG"} alt="Cluster 0 bar graph" className={imgClasses} /> <p> Most Common Restaurants in this cluster are primarily American Restaurants and burger joints. These are located in the Northern Most neighborhoods and the Southern half of Baton Rouge. This is located in the area where the average housing index is the highest at $218,431 </p> </GridItem> <GridItem xs={3} sm={3} md={3}> <h3>Cluster 1 (South Purple Dots) Common Categories</h3> <img src={"https://tntheall.s3.amazonaws.com/assets/data/MostCommonCluster1.PNG"} alt="Cluster 1 bar graph" className={imgClasses} /> <p> Most Common Restaurants in this cluster are {'"'}Food{'"'} This means that they are not typical restaurants. These are places that serve food, but aren{"'"}t restaurants like a food bank. This is located in the area where the average housing index is the lowest at $77,200 </p> </GridItem> <GridItem xs={3} sm={3} md={3}> <h3>Cluster 2 (Greene Dots) Common Categories</h3> <img src={"https://tntheall.s3.amazonaws.com/assets/data/MostCommonCluster2.PNG"} alt="Cluster 2 bar graph" className={imgClasses} /> <p> Most Common Restaurants in this cluster are Fast Food Take Out locations. This is located in the area where the average housing index is in the middle at $92,246 </p> </GridItem> </GridContainer> <GridContainer justify="center"> <GridItem xs={12} sm={10} md={10}> <h3>Baton Rouge Neighborhoods Popular Restaurants Clusters</h3> <img src={"https://tntheall.s3.amazonaws.com/assets/data/foliumPop.PNG"} className={imgClasses} /> <p> A map created from K-means clustering of the East Baton Rouge Area. The Zillow Housing Score was added to make a Cholorpleth map. Data could not be obtained for the black neighborhoods. The darker green neighborhoods where housing is more expensive. While the lighter green neighborhoods are cheaper. </p> <a href="https://www.zillow.com/baton-rouge-la/home-values/" target="_blank" rel="noreferrer" > Zillow Data (2) </a> <a href="https://github.com/travistheall/Coursera_Capstone/blob/master/notebooks/Api%20Popular%20Restaurants.ipynb" target="_blank" rel="noreferrer" > Jupyter Notebook </a> </GridItem> </GridContainer> <GridContainer justify="center"> <GridItem xs={3} sm={3} md={3}> <h3>Popular Cluster 0 bar graph</h3> <img src={"https://tntheall.s3.amazonaws.com/assets/data/popClust0.PNG"} alt="Popular Cluster 0 bar graph" className={imgClasses} /> <p> Most Popular Restaurants in this cluster are primarily Italian Restaurants and burger joints. These are located in the Northern Most neighborhoods and the Southern half of Baton Rouge. This is located in the area where the average housing index is in the middle at $166,025 </p> </GridItem> <GridItem xs={3} sm={3} md={3}> <h3>Popular Cluster 1 bar graph</h3> <img src={"https://tntheall.s3.amazonaws.com/assets/data/popClust1.PNG"} alt="Popular Cluster 1 bar graph" className={imgClasses} /> <p> Most Common Restaurants in this cluster are Fast Food restaurants. This is located in the area where the average housing index is the highest at $192,875 </p> </GridItem> <GridItem xs={3} sm={3} md={3}> <h3>Popular Cluster 2 bar graph</h3> <img src={"https://tntheall.s3.amazonaws.com/assets/data/popClust2.PNG"} alt="Popular Cluster 2 bar graph" className={imgClasses} /> <p> Most Common Restaurants in this cluster are American Restaurants. This is located in the area where the average housing index is in the middle at $66,175 </p> </GridItem> </GridContainer> </GridItem> </GridContainer> ); }
#!/bin/bash wigToBigWig 2> /dev/null || [[ "$?" == 255 ]]
import React from 'react' import {storiesOf, addDecorator} from '@storybook/react' import {TextInput} from '@smashing/text-input' import {withA11y} from '@storybook/addon-a11y' import {SmashingThemeProvider} from '@smashing/theme' addDecorator(withA11y) storiesOf('Core|TextInput', module) .addDecorator(story => ( <SmashingThemeProvider theme={{ defaults: { textInput: {} }, fontFamilies: { display: 'arial' } }} > {story()} </SmashingThemeProvider> )) .add('appearance:default', () => ( <React.Fragment> <div> <TextInput placeholder="Your name" /> </div> </React.Fragment> )) .add('appearance:underline', () => ( <React.Fragment> <div> <TextInput appearance="underline" placeholder="Your name" /> </div> </React.Fragment> )) .add('appearance:neutral', () => ( <React.Fragment> <div> <TextInput appearance="neutral" placeholder="Your name" /> </div> </React.Fragment> )) .add('appearance:minimal', () => ( <React.Fragment> <div> <TextInput appearance="minimal" placeholder="Your name" /> </div> </React.Fragment> )) .add('appearance:default:disabled', () => ( <React.Fragment> <div> <TextInput placeholder="Your name" value="Your name" disabled /> </div> </React.Fragment> )) .add('appearance:minimal:disabled', () => ( <React.Fragment> <div> <TextInput appearance="minimal" placeholder="Your name" value="Your name" disabled /> </div> </React.Fragment> )) .add('appearance:underline:disabled', () => ( <React.Fragment> <div> <TextInput appearance="underline" placeholder="Your name" value="Your name" disabled /> </div> </React.Fragment> )) .add('appearance:neutral:disabled', () => ( <React.Fragment> <div> <TextInput appearance="neutral" placeholder="<NAME>" value="<NAME>" disabled /> </div> </React.Fragment> )) .add('borderRadius:30', () => ( <React.Fragment> <div> <TextInput placeholder="<NAME>" borderRadius={30} /> </div> </React.Fragment> )) .add('height:40', () => ( <React.Fragment> <div> <TextInput placeholder="<NAME>" height={40} /> </div> </React.Fragment> )) .add('height:undefined', () => ( <React.Fragment> <div> <TextInput placeholder="<NAME>" height={undefined} /> </div> </React.Fragment> )) .add('appearance:default:invalid', () => ( <React.Fragment> <div> <TextInput placeholder="<NAME>" invalid /> </div> </React.Fragment> )) .add('appearance:minimal:invalid', () => ( <React.Fragment> <div> <TextInput placeholder="<NAME>" invalid appearance="minimal" /> </div> </React.Fragment> )) .add('appearance:neutral:invalid', () => ( <React.Fragment> <div> <TextInput placeholder="<NAME>" invalid appearance="neutral" /> </div> </React.Fragment> )) .add('appearance:underline:invalid', () => ( <React.Fragment> <div> <TextInput placeholder="<NAME>" invalid appearance="underline" /> </div> </React.Fragment> )) .add('full', () => ( <React.Fragment> <div> <TextInput placeholder="<NAME>" full /> </div> </React.Fragment> ))
#!/bin/bash cd c/ make HTSLIB_INCDIR=$PREFIX/include HTSLIB_LIBDIR=$PREFIX/lib make install
#include "Buffer.h" void Buffer::reset(int size ) { buf = bufstart; cur=0; this->size = size; } int Buffer::getSize() { return cur; } int Buffer::getCurr() { return cur; } uint8_t* Buffer::getBuffer() { return bufstart; } uint16_t Buffer::getShort() { consume(2); return *(uint16_t*)(buf-2); } uint32_t Buffer::getLong() { consume(4); return *(uint32_t*)(buf-4); } uint64_t Buffer::getLongLong() { consume(8); return *(uint64_t*)(buf-8); } void Buffer::consume(int n){ buf = buf+n; cur = cur+n; } uint8_t Buffer::getByte(){ consume(1); return *(buf-1); } char* Buffer::getRaw(){ return (char*)buf; } void Buffer::append(uint16_t input){ *(uint16_t*)buf = input; consume(2); } void Buffer::append(uint64_t input){ *(uint64_t*)buf = input; consume(8); } void Buffer::append(uint32_t input){ *(uint32_t*)buf = input; consume(4); } void Buffer::append(uint8_t input){ *buf = input; consume(1); } void Buffer::appendLengthValue(std::string& input){ *buf = (uint8_t)input.size(); consume(1); memcpy(buf,input.c_str(),input.size()); consume(input.size()); } void Buffer::getLengthValue(std::string& input){ uint8_t len = getByte(); input.assign(getRaw(),len); consume(len); }
<gh_stars>10-100 import * as sinon from "sinon"; import * as chai from "chai"; import * as sinonChai from "sinon-chai"; import { isTooManyTries } from "../../tooManyTries"; import { retryAsyncUntilTruthy, retryUntilTruthy } from "./retry"; const should = require("chai").should(); chai.should(); chai.use(sinonChai); describe("Retry Util", function () { describe("RetryUntilThruthy", function () { it("Success: returns a truthy value immediatly", async function () { const expectedResult = 1; const callback = sinon.stub<any, number>(); callback.returns(expectedResult); const actualResult = await retryUntilTruthy(callback); callback.should.have.been.calledOnce; actualResult.should.be.equal(expectedResult); }); it("Success one returns a truthy value", async function () { const expectedResult = 1; const callback = sinon.stub<any, number | undefined | null>(); callback.onFirstCall().returns(undefined); callback.onSecondCall().returns(null); callback.onThirdCall().returns(expectedResult); const actualResult = await retryUntilTruthy(callback); callback.should.have.been.callCount(3); actualResult!.should.be.equal(expectedResult); }); it("Fails: always return falsy values", async function () { const result = -1; const callback = sinon.stub<any, number>(); callback.returns(result); const maxTry = 3; try { await retryUntilTruthy(callback, { maxTry, delay: 2 }); } catch (err) { callback.should.have.been.callCount(maxTry); isTooManyTries(err).should.be.true; } }); it("Fails: fn always throw an error", async function () { const errMsg = "BOOM"; const callback = sinon.stub<any, number>(); callback.throws(new Error(errMsg)); const maxTry = 3; try { await retryUntilTruthy(callback, { maxTry, delay: 2 }); } catch (err) { callback.should.have.been.callCount(maxTry); isTooManyTries(err).should.be.false; (err as Error).message.should.equals(errMsg); } }); }); describe("RetryAsyncUntilTruthy", function () { it("Success: returns a truthy value immediatly", async function () { const expectedResult = 1; const callback = sinon.stub<any, Promise<number>>(); callback.resolves(expectedResult); const actualResult = await retryAsyncUntilTruthy(callback); callback.should.have.been.calledOnce; actualResult.should.equals(expectedResult); }); it("Success one returns truthy value", async function () { const expectedResult = 1; const callback = sinon.stub<any, Promise<number | undefined | null>>(); callback.onFirstCall().resolves(undefined); callback.onSecondCall().resolves(null); callback.onThirdCall().resolves(expectedResult); const actualResult = await retryAsyncUntilTruthy(callback); callback.should.have.been.callCount(3); actualResult!.should.equals(expectedResult); }); it("Fails: always return a falsy value", async function () { const result = false; const callback = sinon.stub<any, Promise<boolean>>(); callback.resolves(result); const maxTry = 3; try { await retryAsyncUntilTruthy(callback, { maxTry, delay: 2 }); } catch (err) { callback.should.have.been.callCount(maxTry); isTooManyTries(err).should.be.true; } }); it("Fails: fn always throw an error", async function () { const errMsg = "BOOM"; const callback = sinon.stub(); callback.rejects(new Error(errMsg)); const maxTry = 3; try { await retryAsyncUntilTruthy(callback, { maxTry, delay: 2 }); } catch (err) { callback.should.have.been.callCount(maxTry); isTooManyTries(err).should.be.false; (err as Error).message.should.equals(errMsg); } }); }); });
<gh_stars>1-10 package Predict_the_Winner; public class Solution { public boolean PredictTheWinner(int[] nums) { int N = nums.length; return predict(nums, 0, N - 1, new Integer[N][N]) >= 0; } private int predict(int[] nums, int lo, int hi, Integer[][] mem){ if (mem[lo][hi] == null){ mem[lo][hi] = lo == hi ? nums[lo] : Math.max(nums[lo] - predict(nums, lo + 1, hi, mem), nums[hi] - predict(nums, lo, hi - 1, mem)); } return mem[lo][hi]; } public static void main(String[] args) { Solution s = new Solution(); System.out.println(s.PredictTheWinner(new int[]{1, 5, 2})); System.out.println(s.PredictTheWinner(new int[]{1, 5, 233, 7})); } }
var $ = window.Zepto; var root = window.player; var $scope = $(document.body); var songList = []; var controlManager; var audioControl = new root.AudioControl(); // 初始化加载歌曲列表中的第几首歌 var initSongIndex = 0; function bindClick() { $scope.on('play:change', function (event,index) { audioControl.getAudio(songList[index].audio); $scope.append(audioControl.audio); if (audioControl.status === 'play') { audioControl.play(); root.processor.start(); } root.processor.renderAllTime(songList[index].duration) root.render(songList[index]); root.processor.updata(0); }); $scope.on('click', '.btn-prev', function () { $scope.trigger('play:change', controlManager.prev() ); }); $scope.on('click', '.btn-next', function () { $scope.trigger('play:change', controlManager.next() ); }); $scope.on('click', '.btn-play', function () { if (audioControl.status === 'play') { audioControl.pause(); root.processor.stop(); } else { audioControl.play(); root.processor.start(); } $(this).toggleClass('playing'); }); $scope.on('click', '.btn-like', function () { $(this).toggleClass('liking'); }); $scope.on('click', '.btn-list', function () { root.playList.show(controlManager); }); } function getData(url) { $.ajax({ url: url, type: 'GET', success: function (data) { songList = data; controlManager = new root.ControlManager(initSongIndex, data.length); bindClick(); root.playList.renderList(songList); $scope.trigger('play:change', initSongIndex); }, error: function (error) { console.log(error); } }); } getData('../../mock/data.json');
<filename>Week5/oefening 4/js/index.js<gh_stars>0 /** * @Author: <NAME> * @Date: 2018-03-15T11:40:20+01:00 * @Email: <EMAIL> * @Filename: index.js * @Last modified by: <NAME> * @Last modified time: 15-03-2018 * @License: Apache 2.0 * @Copyright: Copyright © 2017-2018 Artevelde University College Ghent */ let found = document.getElementById('found'); let boxes = Array.from(document.getElementsByClassName('memory-block')); let imageArray = [ "img/cuddles.png", "img/discobear.jpg", "img/giggles.png", "img/handy.png", "img/mime.png", "img/monkey.png", "img/nutty.png", "img/pop.png", "img/russell.png", "img/themole.png" ]; let pairArray = []; let checking = {}; function code(index) { console.log(imageArray[index]); console.log(checking); } function randomizer() { for(let i = 0; i < boxes.length; i++) { let index = Math.floor(Math.random()*pairArray.length); if(checking[pairArray[index]] != undefined) { if(checking[pairArray[index]].times != 2) { checking[pairArray[index]].times = checking[pairArray[index]].times + 1; code(index); } } else { checking[pairArray[index]] = {times: 1}; } code(index); } } while(pairArray.length !== 8) { let index = Math.floor(Math.random()*imageArray.length); if(pairArray.indexOf(imageArray[index]) == -1) { pairArray.push(imageArray[index]); } else { } } randomizer(); console.log(pairArray); console.log(imageArray); let fullArray = []; for(let i = 0; i < 2; i++) { for(let j = 0; j < pairArray.length; j++) { fullArray.push(pairArray[j]); } } console.log(fullArray); for(let i = 0; i < boxes.length; i++) { let index = Math.floor(Math.random()*fullArray.length); boxes[i].innerHTML = "<img src=\"" + fullArray[index] + "\" >"; fullArray.splice(index, 1); } //console.log(boxes); /*for(let i = 0; i < 8; i++) { let index = Math.floor(Math.random()*imageArray.length); pairArray.push({img: imageArray[index], times: 2}); } console.log(usedImg); for(let i = 0; i < boxes.length; i++) { let index = Math.floor(Math.random() * usedImg.length); while(usedImg[index].times > 0) { boxes[i].innerHTML = "<img src=\"" + usedImg[index].img + "\">"; usedImg[index].times--; } }*/ let revealcount = 0; let revealed = []; let reveal = function() { this.style.opacity = 1; revealed.push(this); console.log(revealed); revealcount++; console.log(revealcount); if(revealcount == 2) { let pic1 = revealed[0].firstChild; let pic2 = revealed[1].firstChild; console.log("pic 1 = " + pic1.src); console.log("pic 2 = " + pic2.src); if(pic1.src == pic2.src) { found.innerHTML += "<img src=\"" + pic1.src + "\" style='width:64px; height:64px;'>"; pic1.className = "memory-found"; pic2.className = "memory-found"; pic1.parentNode.removeEventListener('click', reveal); pic2.parentNode.removeEventListener('click', reveal); revealcount = 0; revealed = []; } } else if(revealcount > 2) { for(let i = 0; i < revealed.length; i++) { revealed[i].style.opacity = 0; } revealcount = 0; } else { setTimeout(function() { for(let i = 0; i < revealed.length; i++) { revealed[i].style.opacity = 0; } revealcount = 0; revealed = []; }, 2000); } let unfound = Array.from(document.getElementsByClassName('memory-block')); console.log(unfound); if(unfound.length == 0) { alert('Einde van spel'); } } // Add EventListener for(let i = 0; i < boxes.length; i++) { boxes[i].addEventListener('click', reveal); }
package cloud import ( "fmt" "sync" ) var ( backendRegistry = map[string]*backendRegistryEntry{} backendRegistryMutex sync.Mutex ) type backendRegistryEntry struct { Alias string HumanReadableName string ProviderFunc func([]byte) (Provider, error) } func registerProvider(alias, humanReadableName string, providerFunc func([]byte) (Provider, error)) { backendRegistryMutex.Lock() defer backendRegistryMutex.Unlock() backendRegistry[alias] = &backendRegistryEntry{ Alias: alias, HumanReadableName: humanReadableName, ProviderFunc: providerFunc, } } // NewProvider creates a new provider given the alias and provider-specific // configuration. The alias must match what is passed to registerProvider by the // provider, and the configuration is passed to the provider for parsing. func NewProvider(alias string, cfg []byte) (Provider, error) { backendRegistryMutex.Lock() defer backendRegistryMutex.Unlock() backend, ok := backendRegistry[alias] if !ok { return nil, fmt.Errorf("unknown cloud provider: %s", alias) } return backend.ProviderFunc(cfg) }
#!/bin/bash source ${0%/*}/config.sh source ${0%/*}/doconfig.sh source ${0%/*}/functions.sh USAGE=" Usage: ./$(basename $0) Navigates to local SHEBANQ after 2 seconds. " showUsage "$1" "$USAGE" localhost="https://127.0.0.1:8100/" sleep 2 open "$localhost"
#!/bin/bash echo "Entering $(cd "$(dirname "$0")" && pwd -P)/$(basename "$0") in $(pwd)" # Fail the whole script if any command fails set -e ## Diagnostic output # Output lines of this script as they are read. set -o verbose # Output expanded lines of this script as they are executed. set -o xtrace export SHELLOPTS ### ### Argument parsing ### # Optional argument $1 defaults to "all". export GROUP=$1 if [[ "${GROUP}" == "" ]]; then export GROUP=all fi # Optional argument $2 is one of: # downloadjdk, buildjdk # It defaults to downloadjdk. export BUILDJDK=$2 if [[ "${BUILDJDK}" == "" ]]; then export BUILDJDK=buildjdk fi if [[ "${BUILDJDK}" != "buildjdk" && "${BUILDJDK}" != "downloadjdk" ]]; then echo "Bad argument '${BUILDJDK}'; should be omitted or one of: downloadjdk, buildjdk." exit 1 fi ### ### Build the Checker Framework ### if [ -d "/tmp/plume-scripts" ] ; then (cd /tmp/plume-scripts && git pull -q) else (cd /tmp && git clone --depth 1 -q https://github.com/plume-lib/plume-scripts.git) fi # For debugging /tmp/plume-scripts/ci-info typetools eval $(/tmp/plume-scripts/ci-info typetools) export CHECKERFRAMEWORK="${CHECKERFRAMEWORK:-$(pwd -P)}" echo "CHECKERFRAMEWORK=$CHECKERFRAMEWORK" ROOTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" SCRIPTDIR=$ROOTDIR/checker/bin-devel/ source "$SCRIPTDIR/build.sh" "${BUILDJDK}" # The above command builds or downloads the JDK, so there is no need for a # subsequent command to build it except to test building it. ### ### Run the test ### echo "In checker-framework/.travis-build.sh GROUP=$GROUP" ### TESTS OF THIS REPOSITORY case $GROUP in all) # Run cftests-junit and cftests-nonjunit separately, because cftests-all it takes too long to run on Travis under JDK 11. "$SCRIPTDIR/test-cftests-junit.sh" "$SCRIPTDIR/test-cftests-nonjunit.sh" "$SCRIPTDIR/test-jdk-jar.sh" "$SCRIPTDIR/test-misc.sh" "$SCRIPTDIR/test-cf-inference.sh" "$SCRIPTDIR/test-plume-lib.sh" "$SCRIPTDIR/test-daikon.sh" "$SCRIPTDIR/test-guava.sh" "$SCRIPTDIR/test-downstream.sh" ;; *) "${SCRIPTDIR}/test-${GROUP}.sh" esac echo Exiting "$(cd "$(dirname "$0")" && pwd -P)/$(basename "$0") in $(pwd)"
// Copyright (c) 2015, Fujana Solutions - <NAME>. All rights reserved. // For licensing, see LICENSE.md CKEDITOR.plugins.add( 'imageuploader', { init: function( editor ) { var pathname = $('.ckediteImageUploadUrl').text(); // Returns path only editor.config.filebrowserBrowseUrl = pathname+'/public/plugins/ckeditor/plugins/imageuploader/imgbrowser.php'; } });
#!/bin/bash #SBATCH -J Act_relu_1 #SBATCH --mail-user=eger@ukp.informatik.tu-darmstadt.de #SBATCH --mail-type=FAIL #SBATCH -e /work/scratch/se55gyhe/log/output.err.%j #SBATCH -o /work/scratch/se55gyhe/log/output.out.%j #SBATCH -n 1 # Number of cores #SBATCH --mem-per-cpu=6000 #SBATCH -t 23:59:00 # Hours, minutes and seconds, or '#SBATCH -t 10' -only mins #module load intel python/3.5 python3 /home/se55gyhe/Act_func/sequence_tagging/arg_min/PE-my.py relu 273 Adamax 1 0.4518937311641469 0.00224995140917454 varscaling 0.05
class AddServiceInformationFields < ActiveRecord::Migration[5.0] def change add_column :services, :purpose, :text add_column :services, :how_it_works, :text add_column :services, :typical_users, :text add_column :services, :frequency_used, :text add_column :services, :duration_until_outcome, :text add_column :services, :start_page_url, :string add_column :services, :paper_form_url, :string end end
<filename>cypress/integration/HomePage_spec.js describe('The Home Page', () => { it('successfully loads', () => { cy.visit('/'); cy.url().should('equal', Cypress.config('baseUrl')); cy.contains('Home'); cy.contains('AD&D 2nd Edition'); cy.contains('D&D 3.5'); }); });
#!/bin/bash set -eu -o pipefail git init -q git config commit.gpgsign false function write_files() { local base_dir=${1:?directory to write them into} local num_files=${2:?amount of files to write} local nonce=${3:?something to make files more unique} mkdir -p "$base_dir" for file_id in $(seq -w "$num_files"); do seq "$file_id" > "$base_dir/$file_id" echo "$nonce" >> "$base_dir/$file_id" done } dirs=(. a b c a/a a/b a/c a/a/a) rounds=15 git checkout -q -b main for round in $(seq $rounds); do dir_index=$(( round % ${#dirs[@]} )) num_files=$(( (round + 1) * 6 )) write_files "${dirs[$dir_index]}" $num_files "$round" git add . git commit -qm "$round $num_files" done echo hello world > referee git add referee git commit -qm "to be forgotten" git tag -m "a tag object" referrer git reset --hard HEAD~1 # speed up all access by creating a pack git gc --aggressive git multi-pack-index write
#include <string.h> #include <stdio.h> #include <stdlib.h> #include "../headers/functions.h" void rotate1I(Node **pt, int *h) { Node *ptu = (*pt)->left; if(ptu->bal == -1) { (*pt)->left = ptu->right; ptu->right = (*pt); (*pt) = ptu; ptu->right->bal = 0; } else { Node *ptv = ptu->right; ptu->right = ptv->left; ptv->left = ptu; (*pt)->left = ptv->right; ptv->right = (*pt); if(ptv->bal == 1) ptu->bal = -1; else if(ptv->bal == -1) { (*pt)->bal = 1; ptu->bal = 0; } else ptu->bal = 0; (*pt)->bal = 0; (*pt) = ptv; } (*pt)->bal = 0; *h = 0; } void rotate2I(Node **pt, int *h) { Node *ptu = (*pt)->right; if(ptu->bal == 1) { (*pt)->right = ptu->left; ptu->left = (*pt); (*pt) = ptu; ptu->left->bal = 0; } else { Node *ptv = ptu->left; ptu->left = ptv->right; ptv->right = ptu; (*pt)->right = ptv->left; ptv->left = (*pt); if(ptv->bal == 1) { (*pt)->bal = -1; ptu->bal = 0; } else if(ptv->bal == -1) { ptu->bal = 1; } else { ptu->bal = 0; } (*pt)->bal = 0; (*pt) = ptv; } (*pt)->bal = 0; *h = 0; } void insertAVL(int inKey, Node **pt, int *h) { if(*pt == NULL) { Node *new = (Node*)malloc(sizeof(Node)); new->key = inKey; new->bal = 0; new->left = NULL; new->right = NULL; (*pt) = new; *h = 1; } else { if((*pt)->key == inKey) { puts("Found element!"); return; } else if(inKey < (*pt)->key) { insertAVL(inKey, &(*pt)->left, h); if(*h) { switch ((*pt)->bal) { case 1: (*pt)->bal = 0; *h = 0; break; case 0: (*pt)->bal = -1; break; case -1: rotate1I(pt, h); break; } } } else { insertAVL(inKey, &(*pt)->right, h); if(*h) { switch ((*pt)->bal) { case -1: (*pt)->bal = 0; *h = 0; break; case 0: (*pt)->bal = 1; break; case 1: rotate2I(pt, h); break; } } } } } void rotate1R(Node **pt, int *h) { Node *ptu = (*pt)->left; if(ptu->bal <= 0) { (*pt)->left = ptu->right; ptu->right = (*pt); (*pt) = ptu; if(ptu->bal == -1) { ptu->bal = (*pt)->right->bal = 0; *h = 1; } else { ptu->bal = 1; (*pt)->right->bal = -1; *h = 0; } } else { Node * ptv = ptu->right; ptu->right = ptv->left; ptv->left = ptu; (*pt)->left = ptv->right; ptv->right = (*pt); (*pt) = ptv; switch(ptv->bal) { case -1: ptu->bal = 0; (*pt)->right->bal = 1; break; case 0: ptu->bal = 0; (*pt)->right->bal = 0; break; case 1: ptu->bal = -1; (*pt)->right->bal = 0; break; } (*pt)->bal = 0; *h = 1; } } void rotate2R(Node **pt, int *h) { Node *ptu = (*pt)->right; if(ptu->bal >= 0) { (*pt)->right = ptu->left; ptu->left = (*pt); (*pt) = ptu; if(ptu->bal == 1) { ptu->bal = (*pt)->left->bal = 0; *h = 1; } else { ptu->bal = -1; (*pt)->left->bal = 1; *h = 0; } } else { Node * ptv = ptu->left; ptu->left = ptv->right; ptv->right = ptu; (*pt)->right = ptv->left; ptv->left = (*pt); (*pt) = ptv; switch(ptv->bal) { case -1: ptu->bal = 0; (*pt)->left->bal = -1; break; case 0: ptu->bal = 0; (*pt)->left->bal = 0; break; case 1: ptu->bal = 1; (*pt)->left->bal = 0; break; } (*pt)->bal = 0; *h = 1; } } void swap(Node **pt, Node **dadS) { Node *temp; temp = (*pt); (*pt) = (*dadS); (*dadS) = temp; temp->bal = (*pt)->bal; temp->key = (*pt)->key; temp->left = (*pt)->left; temp->right = (*pt)->right; //swap (*pt)->bal = (*dadS)->bal; (*pt)->key = (*dadS)->key; (*pt)->left = (*dadS)->left; (*pt)->right = (*dadS)->right; (*dadS)->bal = temp->bal; (*dadS)->key = temp->key; (*dadS)->left = temp->left; (*dadS)->right = temp->right; } void balance(Node **pt, char where, int *h) { if(*h) { if(where == 'R') { switch((*pt)->bal) { case 1: (*pt)->bal = 0; break; case 0: (*pt)->bal = -1; (*h) = 0; break; case -1: rotate1R(pt, h); break; } } else { switch((*pt)->bal) { case -1: (*pt)->bal = 0; break; case 0: (*pt)->bal = 1; (*h) = 0; break; case 1: rotate2R(pt, h); break; } } } } void removeAVL(int x, Node **pt, int *h) { if((*pt) == NULL){ puts("element does not exist!"); *h = 0; } else { if(x < (*pt)->key) { removeAVL(x, &(*pt)->left, h); balance(pt, 'L', h); } else { if(x > (*pt)->key) { removeAVL(x, &(*pt)->right, h); balance(pt, 'R', h); } else { Node *aux = (*pt); if((*pt)->left == NULL) { (*pt) = (*pt)->right; *h = 1; } else { if((*pt)->right == NULL) { (*pt) = (*pt)->left; *h = 1; } else { Node *s = (*pt)->right; if(s->left == NULL) { s->left = (*pt)->left; s->bal = (*pt)->bal; (*pt) = s; *h = 1; } else { Node *dadS; while(s->left != NULL) { dadS = s; s = s->left; } swap(pt, &dadS->left); removeAVL(x, &(*pt)->right, h); } balance(pt, 'R', h); } free(aux); } } } } } int height(Node *pt) { int hl, hr, diff; if(pt == NULL) { return 0; } else { hl = height(pt->left); hr = height(pt->right); if (hl > hr) return hl+1; else return hr+1; } } int checkAVL(Node *pt) { int hl, hr, diff, flag; if(pt->left != NULL) { flag = checkAVL(pt->left); } if(pt->right != NULL) { flag = checkAVL(pt->right); } hl = height(pt->left); hr = height(pt->right); diff = hr - hl; if(diff >= -1 && diff <= 1) flag = 1; else flag = 0; return flag; } void countNodes(Node *pt, int *sum) { if(pt->left != NULL) countNodes(pt->left, sum); if(pt->right != NULL) countNodes(pt->right, sum); *sum += 1; } void outputAVL(Node *pt) { printf("%d (%d);\n", pt->key, pt->bal); if(pt->left != NULL) outputAVL(pt->left); //printf("%d (%d);\n", pt->key, pt->bal); if(pt->right != NULL) outputAVL(pt->right); /* printf("%d (%d);\n", pt->key, pt->bal); */ } void freeAVL(Node **pt) { if((*pt)->left != NULL) freeAVL(&(*pt)->left); if((*pt)->right != NULL) freeAVL(&(*pt)->right); free(*pt); } void paInVec(int *vec, int seed) { int i, j; for(i = 0, j = 0; i < _10K; i++, j+=seed) { vec[i] = j; } } void tests(Node **pt, int *vec, int *sum, int *h) { int i; countNodes(*pt, sum); printf("\tNumber of Nodes: %d\n",*sum); if(checkAVL(*pt)) puts("\tIt's AVL!"); else puts("\tIt's not AVL!"); puts("\t1000 nodes removed."); for(i = 0; i < K; i++) { removeAVL(vec[i], &(*pt), h); } *sum = 0; countNodes(*pt, sum); printf("\tNumber of Nodes: %d\n",*sum); if(checkAVL(*pt)) printf("\tIt's AVL!\n"); else printf("\tIt's not AVL!"); }
# Copyright 2021, The TensorFlow Federated Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import collections import tensorflow as tf from tensorflow_federated.python.simulation import dictionary_manager class DictionaryManagerTest(tf.test.TestCase): def test_metrics_are_saved(self): dict_manager = dictionary_manager.DictionaryMetricsManager() actual_metrics = dict_manager.metrics self.assertEqual(actual_metrics, collections.OrderedDict()) self.assertIsNone(dict_manager.latest_round_num) round_0_metrics = {'a': 2, 'b': 5} expected_metrics = collections.OrderedDict([(0, round_0_metrics)]) dict_manager.save_metrics(round_0_metrics, 0) actual_metrics = dict_manager.metrics self.assertEqual(actual_metrics, expected_metrics) self.assertEqual(dict_manager.latest_round_num, 0) round_5_metrics = {'c': 5} expected_metrics = collections.OrderedDict([(0, round_0_metrics), (5, round_5_metrics)]) dict_manager.save_metrics(round_5_metrics, 5) actual_metrics = dict_manager.metrics self.assertEqual(actual_metrics, expected_metrics) self.assertEqual(dict_manager.latest_round_num, 5) def test_get_metrics_returns_copy(self): dict_manager = dictionary_manager.DictionaryMetricsManager() round_0_metrics = {'a': 2, 'b': 5} dict_manager.save_metrics(round_0_metrics, 0) dict_manager.metrics[1] = 'foo' expected_metrics = collections.OrderedDict([(0, round_0_metrics)]) self.assertEqual(dict_manager.metrics, expected_metrics) def test_save_metrics_raises_if_round_num_is_negative(self): dict_manager = dictionary_manager.DictionaryMetricsManager() with self.assertRaises(ValueError): dict_manager.save_metrics({'a': 1}, -1) def test_clear_metrics_raises_if_round_num_is_negative(self): dict_manager = dictionary_manager.DictionaryMetricsManager() with self.assertRaises(ValueError): dict_manager.clear_metrics(round_num=-1) def test_clear_metrics_removes_rounds_after_input_arg(self): dict_manager = dictionary_manager.DictionaryMetricsManager() dict_manager.save_metrics({'a': 1}, 0) dict_manager.save_metrics({'b': 2}, 5) dict_manager.save_metrics({'c': 3}, 10) dict_manager.clear_metrics(round_num=7) expected_metrics = collections.OrderedDict([(0, {'a': 1}), (5, {'b': 2})]) self.assertEqual(dict_manager.metrics, expected_metrics) self.assertEqual(dict_manager.latest_round_num, 5) def test_clear_metrics_removes_rounds_equal_to_input_arg(self): dict_manager = dictionary_manager.DictionaryMetricsManager() dict_manager.save_metrics({'a': 1}, 0) dict_manager.save_metrics({'b': 2}, 5) dict_manager.save_metrics({'c': 3}, 10) dict_manager.clear_metrics(round_num=10) expected_metrics = collections.OrderedDict([(0, {'a': 1}), (5, {'b': 2})]) self.assertEqual(dict_manager.metrics, expected_metrics) self.assertEqual(dict_manager.latest_round_num, 5) def test_clear_all_metrics(self): dict_manager = dictionary_manager.DictionaryMetricsManager() dict_manager.save_metrics({'a': 1}, 0) dict_manager.save_metrics({'b': 2}, 5) dict_manager.save_metrics({'c': 3}, 10) dict_manager.clear_metrics(round_num=0) self.assertEqual(dict_manager.metrics, collections.OrderedDict()) self.assertIsNone(dict_manager.latest_round_num) if __name__ == '__main__': tf.test.main()
/** * * Copyright 2015 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Model from './Model'; export default class LogModel extends Model { static get OPERATION_TYPES() { return { CREATED: 'C', UPDATED: 'U', DELETED: 'D' }; } constructor(data, key) { super(key); this.type = data.type; this.time = data.time || Date.now(); this.memoKey = data.memoKey; } static get UPDATED() { return 'LogModel-updated'; } static get storeName() { return 'LogModel'; } }
#!/bin/bash # # install OSSE + TIKA + SOLR + fileserver + ETL(python) # download vagrantfile and this install script # XENIAL=$(lsb_release -c | cut -f2) if [ "$XENIAL" != "xenial" ]; then echo "sorry, tested only with xenial ;("; 1>&2 exit1; fi if [ "$(id -u)" != "0" ]; then echo "ERROR - This script must be run as root" 1>&2 exit 1 fi IP='127.0.0.1' [ -z $1 ] || IP=$1 PORT='3310' [ -z $2 ] || PORT=$2 export LC_ALL=C # install clamav apt-get update apt-get -y install clamav-daemon systemctl stop clamav-daemon.socket systemctl disable clamav-daemon.socket systemctl stop clamav-daemon.service rm /lib/systemd/system/clamav-daemon.socket cat > /lib/systemd/system/clamav-daemon.service << EOF [Unit] Description=Clam AntiVirus userspace daemon ConditionPathExistsGlob=/var/lib/clamav/main.{c[vl]d,inc} ConditionPathExistsGlob=/var/lib/clamav/daily.{c[vl]d,inc} [Service] ExecStart=/usr/sbin/clamd --foreground=true ExecReload=/bin/kill -USR2 \$MAINPID StandardOutput=syslog [Install] WantedBy=multi-user.target EOF cat > /etc/clamav/clamd.conf <<EOF User clamav TCPSocket ${PORT} TCPAddr ${IP} AllowSupplementaryGroups false ScanMail true ScanArchive true ArchiveBlockEncrypted false MaxDirectoryRecursion 15 FollowDirectorySymlinks false FollowFileSymlinks false ReadTimeout 180 MaxThreads 12 MaxConnectionQueueLength 15 LogSyslog false LogRotate true LogFacility LOG_LOCAL6 LogClean false LogVerbose true DatabaseDirectory /var/lib/clamav OfficialDatabaseOnly false SelfCheck 3600 Foreground false Debug false ScanPE true MaxEmbeddedPE 10M ScanOLE2 true ScanPDF true ScanHTML true MaxHTMLNormalize 10M MaxHTMLNoTags 2M MaxScriptNormalize 5M MaxZipTypeRcg 1M ScanSWF true DetectBrokenExecutables false ExitOnOOM false LeaveTemporaryFiles false AlgorithmicDetection true ScanELF true IdleTimeout 30 CrossFilesystems true PhishingSignatures true PhishingScanURLs true PhishingAlwaysBlockSSLMismatch false PhishingAlwaysBlockCloak false PartitionIntersection false DetectPUA false ScanPartialMessages false HeuristicScanPrecedence false StructuredDataDetection false CommandReadTimeout 5 SendBufTimeout 200 MaxQueue 100 ExtendedDetectionInfo true OLE2BlockMacros false ScanOnAccess false AllowAllMatchScan true ForceToDisk false DisableCertCheck false DisableCache false MaxScanSize 100M MaxFileSize 25M MaxRecursion 16 MaxFiles 10000 MaxPartitions 50 MaxIconsPE 100 PCREMatchLimit 10000 PCRERecMatchLimit 5000 PCREMaxFileSize 25M ScanXMLDOCS true ScanHWP3 true MaxRecHWP3 16 StatsEnabled false StatsPEDisabled true StatsHostID auto StatsTimeout 10 StreamMaxLength 25M LogFile /var/log/clamav/clamav.log LogTime true LogFileUnlock false LogFileMaxSize 0 Bytecode true BytecodeSecurity TrustSigned BytecodeTimeout 60000 EOF systemctl daemon-reload systemctl enable clamav-daemon.service systemctl start clamav-daemon.service
import React from 'react' import PropTypes from 'prop-types' import { makeStyles } from '@material-ui/core/styles' import { Paper } from '@material-ui/core' import EchelonProperty from './EchelonProperty' import HostilityProperty from './HostilityProperty' import StatusGroupReduced from './StatusGroupReduced' import TextProperty from './TextProperty' const useStyles = makeStyles(theme => ({ paper: { userSelect: 'none', padding: theme.spacing(4), height: 'auto', pointerEvents: 'auto', gridArea: 'R', display: 'grid', gridGap: '0.5em', gridTemplateColumns: 'auto auto', gridAutoRows: 'min-content' }, twoColumns: { gridColumn: '1 / span 2' } })) const AreaProperties = props => { const classes = useStyles() return ( <Paper className={ classes.paper } elevation={ 4 } > <TextProperty label='Name' property='name' properties={props.properties} onCommit={props.update} className={classes.twoColumns}/> <TextProperty label={'Unique Designation'} property={'t'} properties={props.properties} onCommit={props.update} className={ classes.twoColumns } /> <TextProperty label={'Additional Information'} property={'h'} properties={props.properties} onCommit={props.update} className={ classes.twoColumns }/> <HostilityProperty properties={props.properties} onCommit={props.update}/> <EchelonProperty properties={props.properties} onCommit={props.update}/> <StatusGroupReduced properties={props.properties} onCommit={props.update}/> <TextProperty label={'Effective (from)'} property={'w'} properties={props.properties} onCommit={props.update} className={ classes.twoColumns } /> <TextProperty label={'Effective (to)'} property={'w1'} properties={props.properties} onCommit={props.update} className={ classes.twoColumns } /> <TextProperty label={'Altitude (from)'} property={'x'} properties={props.properties} onCommit={props.update} className={ classes.twoColumns } /> <TextProperty label={'Altitude (to)'} property={'x1'} properties={props.properties} onCommit={props.update} className={ classes.twoColumns } /> {/* TODO: ENY property */} </Paper> ) } AreaProperties.propTypes = { properties: PropTypes.object.isRequired, update: PropTypes.func.isRequired } export default AreaProperties
import { expect } from 'chai'; import { FilesystemServer, FilesystemClient, WebsocketTransport } from '../../src'; const BROKER_ADDR = 'http://localhost:9999/'; describe('flows - remote', () => { let server; let client; let session; it('should start server and session', () => { server = new FilesystemServer({ '/welcome': { content: 'Hello, world!' } }); session = WebsocketTransport.share(BROKER_ADDR, server); expect(session).to.be.a('string'); expect(session.length).to.be.at.least(10); }); it('should start a client and join a session', done => { client = new FilesystemClient(); WebsocketTransport.join(session, client); client.stream.on('connect', done); }); it('should read remote file', done => { client.readFile('/welcome', (err, buffer) => { if (err) { return done(err); } expect(buffer).to.be.an.instanceOf(Buffer); expect(buffer.toString()).to.equal('Hello, world!'); done(); }); }); });
docker build -t bill-payee-service-javascript . docker run -d -p 80:80 bill-payee-service-javascript
#!/bin/bash #================================================= # Lisence: MIT # Author: @P3TERX,@Meloncn # OpenWrt Starting 固件编译自动化程序 #================================================= #feeds 更新并安装完毕后执行此脚本 # # 此脚本执行时所作位置:/home/runner/work/openwrt-newifi3/openwrt-newifi3/openwrt # 在克隆目标项目目录内 # #插件位置:/home/runner/work/openwrt-newifi3/openwrt-newifi3/openwrt/package/lean/luci-theme-argon #================================================= # 脚本当前执行目录 echo ”脚本当前执行目录“ pwd # 清理无用冲突数据 #rm -rf ./package/lean/luci-theme-argon_new readme.md README.md # luci-theme-argon 主题更新 #rm -rf ./package/lean/luci-theme-argon #git clone https://github.com/jerrykuku/luci-theme-argon.git ./package/lean/luci-theme-argon/ #rm -rf ./package/lean/luci-theme-argon/README* ./package/lean/luci-theme-argon/Screenshots/ #echo "luci-theme-argon 更新完成" # luci-app-ssr-plus 插件更新 #rm -rf ./package/lean/luci-app-ssr-plus #git clone https://github.com/fw876/helloworld.git ./package/lean/luci-app-ssr-plus #mv ./package/lean/luci-app-ssr-plus/luci-app-ssr-plus/* ./package/lean/luci-app-ssr-plus/ #rm -rf ./package/lean/luci-app-ssr-plus/luci-app-ssr-plus #rm -rf ./package/lean/luci-app-ssr-plus/README.md #echo "luci-app-ssr-plus 更新完成"
#! /bin/sh # Copyright (C) 2011-2013 Free Software Foundation, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Check that automake really automatically distributes all the files # it advertises to do. # Related to automake bug#7819. # Keep this test in sync with sister test 'autodist-subdir.sh'. am_create_testdir=empty . test-init.sh cat > configure.ac <<END AC_INIT([$me], [1.0]) AC_CONFIG_AUX_DIR([.]) AM_INIT_AUTOMAKE AC_CONFIG_FILES([Makefile]) AC_OUTPUT END $ACLOCAL $AUTOCONF # The automake manual states that the list of automatically-distributed # files should be given by 'automake --help'. list=$($AUTOMAKE --help \ | sed -n '/^Files.*automatically distributed.*if found.*always/,/^ *$/p' \ | sed 1d) # Normalize whitespace, just in case. list=$(echo $list) test -n "$list" cat > Makefile.am <<'END' include distfiles.am check-local: ## For debugging. @echo DIST_COMMON: @for f in $(DIST_COMMON); do echo " $$f"; done @echo DISTDIR: @ls -l $(distdir) | sed 's/^/ /' ## Now the checks. @for f in $(autodist_list); do \ echo "file: $$f"; \ test -f $(distdir)/$$f \ || { echo $$f: distdir fail >&2; exit 1; }; \ ## Some filenames might contain dots, but this won't cause spurious ## failures, and "spurious successes" are so unlikely that they're ## not worth worrying about. echo ' ' $(DIST_COMMON) ' ' | grep "[ /]$$f " >/dev/null \ || { echo $$f: distcom fail >&2; exit 1; }; \ done END : First try listing the automatically-distributed files in proper : targets in Makefile.am echo "MAINTAINERCLEANFILES = $list" > distfiles.am for f in $list; do echo "$f :; touch $f"; done >> distfiles.am cat distfiles.am # For debugging. $AUTOMAKE -a ./configure $MAKE distdir autodist_list="$list" $MAKE check $MAKE maintainer-clean test ! -e README # Sanity check. rm -rf $me-1.0 # Remove $(distdir). : Now try creating the automatically-distributed files before : running automake. : > distfiles.am for f in $list; do echo dummy > $f done ls -l # For debugging. $AUTOMAKE ./configure $MAKE distdir autodist_list="$list" $MAKE check :
<filename>deploy/aws-lambda/main.go package main import ( "os" "fmt" "strconv" "time" "github.com/akrylysov/algnhsa" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/dynamodb" "github.com/jhaals/yopass/pkg/yopass" ) func main() { maxLength, _ := strconv.Atoi(os.Getenv("MAX_LENGTH")) if maxLength == 0 { maxLength = 10000 } y := yopass.New(NewDynamo(os.Getenv("TABLE_NAME")), maxLength) algnhsa.ListenAndServe( y.HTTPHandler(), nil) } // Dynamo Database implementation type Dynamo struct { tableName string svc *dynamodb.DynamoDB } // NewDynamo returns a database client func NewDynamo(tableName string) yopass.Database { return &Dynamo{tableName: tableName, svc: dynamodb.New(session.New())} } // Get item from dynamo func (d *Dynamo) Get(key string) (string, error) { input := &dynamodb.GetItemInput{ Key: map[string]*dynamodb.AttributeValue{ "id": { S: aws.String(key), }, }, TableName: aws.String(d.tableName), } result, err := d.svc.GetItem(input) if err != nil { return "", err } if len(result.Item) == 0 { return "", fmt.Errorf("Key not found in database") } return *result.Item["secret"].S, nil } // Delete item func (d *Dynamo) Delete(key string) error { input := &dynamodb.DeleteItemInput{ Key: map[string]*dynamodb.AttributeValue{ "id": { S: aws.String(key), }, }, TableName: aws.String(d.tableName), } _, err := d.svc.DeleteItem(input) return err } // Put item in Dynamo func (d *Dynamo) Put(key, value string, expiration int32) error { input := &dynamodb.PutItemInput{ // TABLE GENERATED NAME Item: map[string]*dynamodb.AttributeValue{ "id": { S: aws.String(key), }, "secret": { S: aws.String(value), }, "ttl": { N: aws.String( fmt.Sprintf( "%d", time.Now().Unix()+int64(expiration))), }, }, TableName: aws.String(d.tableName), } _, err := d.svc.PutItem(input) return err }
Support Vector Machines (SVMs) are commonly used for supervised learning tasks and are known for their high accuracy. SVMs are particularly effective when the dataset is characterized by high class separability. SVMs use a hyperplane to divide data points into different classes and can be easily adjusted to optimize the model’s accuracy.
<reponame>AlanLang/alanui-mobile import * as React from 'react'; import * as classNames from 'classnames'; import {NavLink} from 'react-router-dom'; import {BaseProps} from '../../src/components/common/BaseProps'; import {Content} from '../../src/components/Page'; import {MENUS} from '../common/Menus'; import List, {ListItem, ListItemAction, ListItemText} from '../../src/components/List'; import Icon from '../../src/components/Icon'; interface OverviewCaseProps extends BaseProps { } export default class OverviewCase extends React.PureComponent<OverviewCaseProps, any> { render() { const {className} = this.props; const styleClass = classNames( 'OverviewCase', className, ); const menus = MENUS.filter((menu) => { return ['Overview'].indexOf(menu.name) === -1; }); return ( <Content className={styleClass}> <List> { menus.map((menu, index) => ( <ListItem key={index.toString()}> <NavLink to={menu.path} activeClassName="active"> <Icon icon={menu.icon}/> <ListItemText> {menu.name} <span style={{display:"inlie-block",marginLeft:12,color:"#858585",fontSize:"12px"}}>{menu.text}</span> </ListItemText> <ListItemAction> <Icon icon="chevron_right"/> </ListItemAction> </NavLink> </ListItem> )) } </List> </Content> ); } }
#!/bin/sh set -e set -u set -o pipefail function on_error { echo "$(realpath -mq "${0}"):$1: error: Unexpected failure" } trap 'on_error $LINENO' ERR if [ -z ${UNLOCALIZED_RESOURCES_FOLDER_PATH+x} ]; then # If UNLOCALIZED_RESOURCES_FOLDER_PATH is not set, then there's nowhere for us to copy # resources to, so exit 0 (signalling the script phase was successful). exit 0 fi mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt > "$RESOURCES_TO_COPY" XCASSET_FILES=() # This protects against multiple targets copying the same framework dependency at the same time. The solution # was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") case "${TARGETED_DEVICE_FAMILY:-}" in 1,2) TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone" ;; 1) TARGET_DEVICE_ARGS="--target-device iphone" ;; 2) TARGET_DEVICE_ARGS="--target-device ipad" ;; 3) TARGET_DEVICE_ARGS="--target-device tv" ;; 4) TARGET_DEVICE_ARGS="--target-device watch" ;; *) TARGET_DEVICE_ARGS="--target-device mac" ;; esac install_resource() { if [[ "$1" = /* ]] ; then RESOURCE_PATH="$1" else RESOURCE_PATH="${PODS_ROOT}/$1" fi if [[ ! -e "$RESOURCE_PATH" ]] ; then cat << EOM error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script. EOM exit 1 fi case $RESOURCE_PATH in *.storyboard) echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" || true ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ;; *.xib) echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" || true ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ;; *.framework) echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" || true mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" || true rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" ;; *.xcdatamodel) echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\"" || true xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom" ;; *.xcdatamodeld) echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\"" || true xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd" ;; *.xcmappingmodel) echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\"" || true xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm" ;; *.xcassets) ABSOLUTE_XCASSET_FILE="$RESOURCE_PATH" XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE") ;; *) echo "$RESOURCE_PATH" || true echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY" ;; esac } if [[ "$CONFIGURATION" == "Debug" ]]; then install_resource "${PODS_ROOT}/../../Hdk/Assets/HdkSDKResource.bundle" fi if [[ "$CONFIGURATION" == "Release" ]]; then install_resource "${PODS_ROOT}/../../Hdk/Assets/HdkSDKResource.bundle" fi mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" fi rm -f "$RESOURCES_TO_COPY" if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "${XCASSET_FILES:-}" ] then # Find all other xcassets (this unfortunately includes those of path pods and other targets). OTHER_XCASSETS=$(find -L "$PWD" -iname "*.xcassets" -type d) while read line; do if [[ $line != "${PODS_ROOT}*" ]]; then XCASSET_FILES+=("$line") fi done <<<"$OTHER_XCASSETS" if [ -z ${ASSETCATALOG_COMPILER_APPICON_NAME+x} ]; then printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" else printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" --app-icon "${ASSETCATALOG_COMPILER_APPICON_NAME}" --output-partial-info-plist "${TARGET_TEMP_DIR}/assetcatalog_generated_info_cocoapods.plist" fi fi
rm */2792.csv rm */2792.csv
class DoublyLinkedList: class Node: def __init__(self, data=None, next=None, prev=None): self.data = data self.next = next self.prev = prev def __init__(self): self.head = None self.tail = None self.count = 0 # other methods ... def __iter__(self): cursor = self.head while cursor is not None: yield cursor.data cursor = cursor.next def __reversed__(self): cursor = self.tail while cursor is not None: yield cursor.data cursor = cursor.prev
<gh_stars>10-100 // // Created by ooooo on 2020/2/12. // #ifndef CPP_0055__SOLUTION3_H_ #define CPP_0055__SOLUTION3_H_ #include <iostream> #include <vector> using namespace std; /** * 贪心 */ class Solution { public: bool canJump(vector<int> &nums) { // k 表示能跳的最远距离 int k = 0; for (int i = 0; i < nums.size(); ++i) { if (i > k) return false; k = max(k, i + nums[i]); } return true; } }; #endif //CPP_0055__SOLUTION3_H_