text
stringlengths
1
1.05M
import React from 'react'; import { render } from '@testing-library/react'; import {A} from './A'; describe('Test A component', () => { it('should render A component', () => { const { container } = render(<A />); }); })
#!/bin/bash # Copyright 2020 Cortex Labs, Inc. # # 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. set -euo pipefail CORTEX_VERSION=master slim="false" while [[ $# -gt 0 ]]; do key="$1" case $key in --include-slim) slim="true" shift ;; *) positional_args+=("$1") shift ;; esac done set -- "${positional_args[@]}" image=$1 echo "$DOCKER_PASSWORD" | docker login -u "$DOCKER_USERNAME" --password-stdin docker push cortexlabs/${image}:${CORTEX_VERSION} if [ "$slim" == "true" ]; then if [ "$image" == "python-predictor-gpu" ]; then for cuda in 10.0 10.1 10.2 11.0; do docker push cortexlabs/${image}-slim:${CORTEX_VERSION}-cuda${cuda} done else docker push cortexlabs/${image}-slim:${CORTEX_VERSION} fi fi
<filename>word_forms/word_forms.py try: from nltk.corpus import wordnet as wn raise_lookuperror_if_wordnet_data_absent = wn.synsets("python") except LookupError: import nltk nltk.download("wordnet") import inflect from .constants import (ALL_WORDNET_WORDS, CONJUGATED_VERB_LIST, ADJECTIVE_TO_ADVERB) def belongs(lemma, lemma_list): """ args: - lemma : a Wordnet lemma e.g. Lemma('administration.n.02.governance') - lemma_list : a list of lemmas returns True if lemma is in lemma_list and False otherwise. The NLTK Wordnet implementation of Lemma is such that two lemmas are considered equal only if their names are the same. i.e Lemma('regulate.v.02.govern') == Lemma('govern.v.02.govern') Therefore the python statement "lemma in lemma_list" yields unexpected results. This function implements the expected behavior for the statement "lemma in list_list". """ for element in lemma_list: if (element.name() == lemma.name() and element.synset() == lemma.synset()): return True return False def get_related_lemmas(word): """ args - word : a word e.g. "lovely" returns a list of related lemmas e.g [Lemma('cover_girl.n.01.lovely'), Lemma('lovely.s.01.lovely'), Lemma('adorable.s.01.lovely'), Lemma('comeliness.n.01.loveliness')] returns [] if Wordnet doesn't recognize the word """ all_lemmas_for_this_word = [lemma for ss in wn.synsets(word) for lemma in ss.lemmas() if lemma.name() == word] all_related_lemmas = [lemma for lemma in all_lemmas_for_this_word] new_lemmas = [] for lemma in all_lemmas_for_this_word: for new_lemma in (lemma.derivationally_related_forms() + lemma.pertainyms()): if (not belongs(new_lemma, all_related_lemmas) and not belongs(new_lemma, new_lemmas)): new_lemmas.append(new_lemma) while len(new_lemmas) > 0: all_lemmas_for_new_words = [] for new_lemma in new_lemmas: word = new_lemma.name() all_lemmas_for_this_word = [lemma for ss in wn.synsets(word) for lemma in ss.lemmas() if lemma.name() == word] for lemma in all_lemmas_for_this_word: if not belongs(lemma, all_lemmas_for_new_words): all_lemmas_for_new_words.append(lemma) all_related_lemmas += all_lemmas_for_new_words new_lemmas = [] for lemma in all_lemmas_for_new_words: for new_lemma in (lemma.derivationally_related_forms() + lemma.pertainyms()): if (not belongs(new_lemma, all_related_lemmas) and not belongs(new_lemma, new_lemmas)): new_lemmas.append(new_lemma) return all_related_lemmas def singularize(noun): """ args - noun : a noun e.g "man" returns the singular form of the word if it finds one. Otherwise, returns the word itself. """ singular = inflect.engine().singular_noun(noun) if singular in ALL_WORDNET_WORDS: return singular return noun def get_word_forms(word): """ args word : a word e.g "love" returns the related word forms corresponding to the input word. the output is a dictionary with four keys "n" (noun), "a" (adjective), "v" (verb) and "r" (adverb). The value for each key is a python Set containing related word forms with that part of speech. e.g. {'a': {'lovable', 'loveable'}, 'n': {'love', 'lover', 'lovers', 'loves'}, 'r': set(), 'v': {'love', 'loved', 'loves', 'loving'}} """ word = singularize(word) related_lemmas = get_related_lemmas(word) related_words_dict = {"n" : set(), "a" : set(), "v" : set(), "r" : set()} for lemma in related_lemmas: pos = lemma.synset().pos() if pos == "s": pos = "a" related_words_dict[pos].add(lemma.name()) noun_set = [noun for noun in related_words_dict["n"]] for noun in noun_set: related_words_dict["n"].add(inflect.engine().plural_noun(noun)) verb_set = [verb for verb in related_words_dict["v"]] for verb in verb_set: for conjugated_verbs in CONJUGATED_VERB_LIST: if verb in conjugated_verbs: for conjugated_verb in conjugated_verbs: related_words_dict["v"].add(conjugated_verb) adjective_set = [adjective for adjective in related_words_dict["a"]] for adjective in adjective_set: try: related_words_dict["r"].add(ADJECTIVE_TO_ADVERB[adjective]) except KeyError: pass return related_words_dict
<filename>google/cloud/talent/v4beta1/google-cloud-talent-v4beta1-ruby/proto_docs/google/cloud/talent/v4beta1/application.rb # frozen_string_literal: true # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Auto-generated by gapic-generator-ruby. DO NOT EDIT! module Google module Cloud module Talent module V4beta1 # Resource that represents a job application record of a candidate. # @!attribute [rw] name # @return [::String] # Required during application update. # # Resource name assigned to an application by the API. # # The format is # "projects/\\{project_id}/tenants/\\{tenant_id}/profiles/\\{profile_id}/applications/\\{application_id}". # For example, "projects/foo/tenants/bar/profiles/baz/applications/qux". # @!attribute [rw] external_id # @return [::String] # Required. Client side application identifier, used to uniquely identify the # application. # # The maximum number of allowed characters is 255. # @!attribute [r] profile # @return [::String] # Output only. Resource name of the candidate of this application. # # The format is # "projects/\\{project_id}/tenants/\\{tenant_id}/profiles/\\{profile_id}". # For example, "projects/foo/tenants/bar/profiles/baz". # @!attribute [rw] job # @return [::String] # Required. Resource name of the job which the candidate applied for. # # The format is # "projects/\\{project_id}/tenants/\\{tenant_id}/jobs/\\{job_id}". For example, # "projects/foo/tenants/bar/jobs/baz". # @!attribute [rw] company # @return [::String] # Resource name of the company which the candidate applied for. # # The format is # "projects/\\{project_id}/tenants/\\{tenant_id}/companies/\\{company_id}". # For example, "projects/foo/tenants/bar/companies/baz". # @!attribute [rw] application_date # @return [::Google::Type::Date] # The application date. # @!attribute [rw] stage # @return [::Google::Cloud::Talent::V4beta1::Application::ApplicationStage] # Required. What is the most recent stage of the application (that is, new, # screen, send cv, hired, finished work)? This field is intentionally not # comprehensive of every possible status, but instead, represents statuses # that would be used to indicate to the ML models good / bad matches. # @!attribute [rw] state # @return [::Google::Cloud::Talent::V4beta1::Application::ApplicationState] # The application state. # @!attribute [rw] interviews # @return [::Array<::Google::Cloud::Talent::V4beta1::Interview>] # All interviews (screen, onsite, and so on) conducted as part of this # application (includes details such as user conducting the interview, # timestamp, feedback, and so on). # @!attribute [rw] referral # @return [::Google::Protobuf::BoolValue] # If the candidate is referred by a employee. # @!attribute [rw] create_time # @return [::Google::Protobuf::Timestamp] # Required. Reflects the time that the application was created. # @!attribute [rw] update_time # @return [::Google::Protobuf::Timestamp] # The last update timestamp. # @!attribute [rw] outcome_notes # @return [::String] # Free text reason behind the recruitement outcome (for example, reason for # withdraw / reject, reason for an unsuccessful finish, and so on). # # Number of characters allowed is 100. # @!attribute [rw] outcome # @return [::Google::Cloud::Talent::V4beta1::Outcome] # Outcome positiveness shows how positive the outcome is. # @!attribute [r] is_match # @return [::Google::Protobuf::BoolValue] # Output only. Indicates whether this job application is a match to # application related filters. This value is only applicable in profile # search response. # @!attribute [r] job_title_snippet # @return [::String] # Output only. Job title snippet shows how the job title is related to a # search query. It's empty if the job title isn't related to the search # query. class Application include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods # Enum that represents the application status. module ApplicationState # Default value. APPLICATION_STATE_UNSPECIFIED = 0 # The current stage is in progress or pending, for example, interviews in # progress. IN_PROGRESS = 1 # The current stage was terminated by a candidate decision. CANDIDATE_WITHDREW = 2 # The current stage was terminated by an employer or agency decision. EMPLOYER_WITHDREW = 3 # The current stage is successfully completed, but the next stage (if # applicable) has not begun. COMPLETED = 4 # The current stage was closed without an exception, or terminated for # reasons unrealated to the candidate. CLOSED = 5 end # The stage of the application. module ApplicationStage # Default value. APPLICATION_STAGE_UNSPECIFIED = 0 # Candidate has applied or a recruiter put candidate into consideration but # candidate is not yet screened / no decision has been made to move or not # move the candidate to the next stage. NEW = 1 # A recruiter decided to screen the candidate for this role. SCREEN = 2 # Candidate is being / was sent to the customer / hiring manager for # detailed review. HIRING_MANAGER_REVIEW = 3 # Candidate was approved by the client / hiring manager and is being / was # interviewed for the role. INTERVIEW = 4 # Candidate will be / has been given an offer of employment. OFFER_EXTENDED = 5 # Candidate has accepted their offer of employment. OFFER_ACCEPTED = 6 # Candidate has begun (or completed) their employment or assignment with # the employer. STARTED = 7 end end end end end end
python train_tar.py --home --dset a2r --K 3 --KK 2 --file target --gpu_id 0 python train_tar.py --home --dset r2a --K 3 --KK 2 --file target --gpu_id 0 python train_tar.py --home --dset r2c --K 3 --KK 2 --file target --gpu_id 0 python train_tar.py --home --dset r2p --K 3 --KK 2 --file target --gpu_id 0 python train_tar.py --home --dset p2a --K 3 --KK 2 --file target --gpu_id 0 python train_tar.py --home --dset p2c --K 3 --KK 2 --file target --gpu_id 0 python train_tar.py --home --dset a2p --K 3 --KK 2 --file target --gpu_id 0 python train_tar.py --home --dset a2c --K 3 --KK 2 --file target --gpu_id 0 python train_tar.py --home --dset p2r --K 3 --KK 2 --file target --gpu_id 0 python train_tar.py --home --dset c2a --K 3 --KK 2 --file target --gpu_id 0 python train_tar.py --home --dset c2p --K 3 --KK 2 --file target --gpu_id 0 python train_tar.py --home --dset c2r --K 3 --KK 2 --file target --gpu_id 0
cmake /opt/mysql-server -DDOWNLOAD_BOOST=1 -DWITH_BOOST=/tmp/boost make kiyoshi cp ./plugin_output_directory/ha_kiyoshi.so /usr/lib/mysql/plugin/
/** * @jest-environment ./prisma/prisma-test-environment.js */ import bcrypt from 'bcryptjs' import request from 'supertest' import { v4 as uuid } from 'uuid' import { app } from '@infra/http/app' import { prisma } from '@infra/prisma/client' import { redisConnection } from '@infra/redis/connection' describe('Authenticate User (e2e)', () => { beforeAll(async () => { await prisma.user.create({ data: { id: uuid(), name: '<NAME>', email: '<EMAIL>', password: await bcrypt.hash('<PASSWORD>', 8), }, }) }) afterAll(async () => { redisConnection.disconnect() await prisma.$disconnect() }) it('should be able to authenticate', async () => { const response = await request(app).post('/sessions').send({ email: '<EMAIL>', password: '<PASSWORD>', }) expect(response.status).toBe(200) expect(response.body).toEqual( expect.objectContaining({ token: expect.any(String), }) ) }) })
import numpy as np import cv2 def preprocess_clothing_image(image, item_name): if item_name in ["han", "jakobs1", "jakobs2"]: # Apply specific preprocessing for problematic items # Example: handle differently or apply custom transformations pass elif item_name in ["shapes", "shirts", "swim", "trousers"]: # Handle unhandled shapes and clothing categories # Example: define specific preprocessing for these categories pass else: # Apply general preprocessing for other items # Example: resize, normalize, and standardize the images processed_image = cv2.resize(image, (224, 224)) # Example resizing to a standard size processed_image = processed_image / 255.0 # Example normalization # Additional preprocessing steps as needed return processed_image # Example usage item_name = "ga" # Replace with actual item name from the dataset image_path = "path_to_image.jpg" # Replace with actual image path image = cv2.imread(image_path) processed_image = preprocess_clothing_image(image, item_name) # Further processing or saving the preprocessed image
package org.jooby.rocker; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.isA; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.io.InputStream; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.Map; import java.util.Optional; import org.jooby.MediaType; import org.jooby.Renderer; import org.jooby.Renderer.Context; import org.jooby.Route; import org.jooby.View; import org.jooby.test.MockUnit; import org.jooby.test.MockUnit.Block; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.fizzed.rocker.BindableRockerModel; import com.fizzed.rocker.RenderingException; import com.fizzed.rocker.Rocker; import com.fizzed.rocker.RockerModel; import com.fizzed.rocker.RockerOutputFactory; import com.fizzed.rocker.RockerTemplate; import com.fizzed.rocker.RockerTemplateCustomizer; import com.fizzed.rocker.runtime.ArrayOfByteArraysOutput; import com.google.common.collect.ImmutableMap; @RunWith(PowerMockRunner.class) @PrepareForTest({RockerRenderer.class, Rocker.class, Channels.class, Rocker.class }) public class RockerRenderTest { private Block send = unit -> { ReadableByteChannel channel = unit.mock(ReadableByteChannel.class); ArrayOfByteArraysOutput output = unit.get(ArrayOfByteArraysOutput.class); expect(output.getByteLength()).andReturn(1024); expect(output.asReadableByteChannel()).andReturn(channel); InputStream stream = unit.mock(InputStream.class); unit.mockStatic(Channels.class); expect(Channels.newInputStream(channel)).andReturn(stream); Context context = unit.get(Renderer.Context.class); expect(context.type(MediaType.html)).andReturn(context); expect(context.length(1024)).andReturn(context); context.send(stream); }; @Test public void renderNone() throws Exception { new RockerRenderer("", ".rocker.html") .render(null, null); } @Test public void renderRockerModel() throws Exception { new MockUnit(RockerModel.class, Renderer.Context.class) .expect(model(RockerModel.class)) .expect(send) .run(unit -> { new RockerRenderer("", ".rocker.html") .render(unit.get(RockerModel.class), unit.get(Renderer.Context.class)); }); } @Test public void renderRequestTemplate() throws Exception { Map<String, Object> locals = ImmutableMap.of("foo", "bar"); new MockUnit(RockerModel.class, Renderer.Context.class) .expect(model(RockerModel.class)) .expect(send) .expect(unit -> { Context context = unit.get(Renderer.Context.class); expect(context.locals()).andReturn(locals); }) .run(unit -> { new RockerRenderer("", ".rocker.html") .render(unit.get(RockerModel.class), unit.get(Renderer.Context.class)); }, unit -> { RequestRockerTemplate template = new RequestRockerTemplate(unit.get(RockerModel.class)) { @Override protected void __doRender() throws IOException, RenderingException { } }; unit.captured(RockerTemplateCustomizer.class).iterator().next().customize(template); assertEquals(locals, template.locals); }); } @Test public void renderTemplate() throws Exception { new MockUnit(RockerModel.class, Renderer.Context.class, RockerTemplate.class) .expect(model(RockerModel.class)) .expect(send) .run(unit -> { new RockerRenderer("", ".rocker.html") .render(unit.get(RockerModel.class), unit.get(Renderer.Context.class)); }, unit -> { unit.captured(RockerTemplateCustomizer.class).iterator().next() .customize(unit.get(RockerTemplate.class)); }); } @Test public void renderView() throws Exception { new MockUnit(BindableRockerModel.class, Renderer.Context.class, View.class) .expect(view("", "index")) .expect(model(BindableRockerModel.class)) .expect(send) .run(unit -> { new RockerRenderer("", ".rocker.html") .render(unit.get(View.class), unit.get(Renderer.Context.class)); }); } @Test public void renderViewWithPrefix() throws Exception { new MockUnit(BindableRockerModel.class, Renderer.Context.class, View.class) .expect(view("/", "index")) .expect(model(BindableRockerModel.class)) .expect(send) .run(unit -> { new RockerRenderer("/", ".rocker.html") .render(unit.get(View.class), unit.get(Renderer.Context.class)); }); } @Test public void rockerPrefixPath() throws Exception { assertEquals("foo", RockerRenderer.path("/foo")); assertEquals("foo", RockerRenderer.path("foo")); } @Test public void renderViewWithPrefix2() throws Exception { new MockUnit(BindableRockerModel.class, Renderer.Context.class, View.class) .expect(view("views", "index")) .expect(model(BindableRockerModel.class)) .expect(send) .run(unit -> { new RockerRenderer("views", ".rocker.html") .render(unit.get(View.class), unit.get(Renderer.Context.class)); }); } @SuppressWarnings("unchecked") private Block model(final Class<? extends RockerModel> class1) { return unit -> { RockerModel model = unit.get(class1); ArrayOfByteArraysOutput output = unit.registerMock(ArrayOfByteArraysOutput.class); expect(model.render(isA(RockerOutputFactory.class), unit.capture(RockerTemplateCustomizer.class))).andReturn(output); }; } @SuppressWarnings({"rawtypes", "unchecked" }) private Block view(final String prefix, final String name) { return unit -> { View view = unit.get(View.class); expect(view.name()).andReturn(name); Map data = ImmutableMap.of(); expect(view.model()).andReturn(data); BindableRockerModel model = unit.get(BindableRockerModel.class); expect(model.bind(data)).andReturn(model); unit.mockStatic(Rocker.class); expect(Rocker.template(Route.normalize( Optional.ofNullable(prefix).map(p -> p + "/" + name).orElse(name) + ".rocker.html") .substring(1))) .andReturn(model); }; } }
import random user_choice = input("Enter your choice (rock, paper, or scissors): ") computer_choice = random.choice(["rock", "paper", "scissors"]) # Game logic if user_choice == computer_choice: result = "It's a tie!" elif (user_choice == "rock" and computer_choice == "scissors") or (user_choice == "scissors" and computer_choice == "paper") or (user_choice == "paper" and computer_choice == "rock"): result = "You win!" else: result = "Computer wins!" # Display the choices and result print(f"You chose {user_choice}, computer chose {computer_choice}. {result}")
import React, { Component } from 'react'; class LoginForm extends Component { constructor(props) { super(props); this.state = { username: '', password: '', error: false, errorMessage: '', }; } handleChange = (event) => { const { name, value } = event.target; this.setState({ [name]: value, error: false, errorMessage: '', }); }; validateForm = () => { const { username, password } = this.state; if (username === '' || password === '') { this.setState({ error: true, errorMessage: 'Username and password cannot be empty', }); } else if (username !== 'example' || password !== 'example') { this.setState({ error: true, errorMessage: 'Invalid credentials', }); } else { this.setState({ error: false, errorMessage: '', }); } }; render() { const { username, password, error, errorMessage } = this.state; return ( <form> <input type='text' placeholder='Username' name='username' value={username} onChange={this.handleChange} /> <input type='password' placeholder='Password' name='password' value={password} onChange={this.handleChange} /> <button onClick={this.validateForm}>Login</button> {error && <p style={{color: 'red'}}>{errorMessage}</p>} </form> ); } } export default LoginForm;
import java.util.Scanner; public class AddTwoNumbers { public static void main(String[] args) { int num1, num2, sum; Scanner sc = new Scanner(System.in); System.out.println("Enter First Number:"); num1 = sc.nextInt(); System.out.println("Enter Second Number:"); num2 = sc.nextInt(); sc.close(); sum = num1 + num2; System.out.println("Sum of these numbers: "+sum); } }
<filename>github_backup/__init__.py __version__ = '0.40.2'
export * from '../esm/es2017/wv-sitemap-manager.define.js';
<reponame>handsomekuroji/handsomekuroji-gatsby<gh_stars>0 export default (object) => { const url = object.url const name = object.title const author = { copyrightHolder: { '@id': `${url}#author`, }, publisher: { '@id': `${url}#publisher`, }, author: { '@id': `${url}#author`, }, editor: { '@id': `${url}#author`, }, } const meta = { url, name, alternateName: name, description: object.description, } const account = { sameAs: [`https://twitter.com/${object.twitter}`, `https://www.facebook.com/${object.facebook}`], } return { author, meta, account, } }
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera.filmstrip; import com.android.camera.widget.FilmstripLayout; /** * The filmstrip panel holding the filmstrip and other controls/widgets. */ public interface FilmstripContentPanel { /** * Sets the listener. */ void setFilmstripListener(FilmstripLayout.Listener listener); /** * Hides this panel with animation. * * @return {@code false} if already hidden. */ boolean animateHide(); /** * Hides this panel */ void hide(); /** * Shows this panel */ void show(); /** * Called when the back key is pressed. * * @return Whether the UI responded to the key event. */ boolean onBackPressed(); /** * An listener interface extending {@link * com.android.camera.filmstrip.FilmstripController.FilmstripListener} defining extra callbacks * for filmstrip being shown and hidden. */ interface Listener extends FilmstripController.FilmstripListener { /** * Callback on a swipe out of filmstrip. */ public void onSwipeOut(); /** * Callback on a swiping out begins. */ public void onSwipeOutBegin(); /** * Callback when the filmstrip becomes invisible or gone. */ public void onFilmstripHidden(); /** * Callback when the filmstrip is shown in full-screen. */ public void onFilmstripShown(); } }
#!/bin/bash # Permissions for the orchestrator to read other pods kubectl apply -f cluster-role.yaml # The Orchestrator and the Data master service kubectl apply -f services.yaml sleep 3 # The Orchestration deployments kubectl apply -f orchestration-deployments-all-off.yaml # The DaemonSet of storage adapters kubectl apply -f storage-adapter-edge1-all-off.yaml kubectl apply -f storage-adapter-edge2-all-off.yaml kubectl apply -f storage-adapter-cloud1-all-off.yaml # The first step kubectl apply -f step1-deployment-edge1.yaml kubectl apply -f step1-deployment-edge2.yaml kubectl apply -f step1-deployment-cloud1.yaml # The second step kubectl apply -f step2-deployment-edge1.yaml kubectl apply -f step2-deployment-edge2.yaml kubectl apply -f step2-deployment-cloud1.yaml # The third step kubectl apply -f step3-deployment-edge1.yaml kubectl apply -f step3-deployment-edge2.yaml kubectl apply -f step3-deployment-cloud1.yaml # The fourth step. kubectl apply -f step4-deployment-cloud1.yaml
function getRandomHexColor() { return `#${Math.floor(Math.random() * 16777215).toString(16)}`; } const colorEl = document.querySelector(".change-color"); const colorSpanEl = document.querySelector(".color"); colorEl.addEventListener("click", () => { const newColor = getRandomHexColor(); console.log(newColor); document.body.style.backgroundColor = newColor; colorSpanEl.textContent = newColor; });
source ./templates/support.sh populate var_accounts_user_umask grep -q umask /etc/profile && \ sed -i "s/umask.*/umask $var_accounts_user_umask/g" /etc/profile if ! [ $? -eq 0 ]; then echo "umask $var_accounts_user_umask" >> /etc/profile fi
setting_file=${1} work_dir=${2} GPU=${3} # load settings . ${setting_file} # mkdir mkdir -p ${checkpoint_path} ${log_path} ${result_root} ${dist_path} # training CUDA_VISIBLE_DEVICES=${GPU} python ${GITHUB_path}/train.py --dist_url $dist_url --cfgs_file $cfgs_file \ --checkpoint_path $checkpoint_path --batch_size $batch_size --world_size 1 --max_epochs ${max_epochs} --learning_rate ${learning_rate} \ --cuda --sent_weight $sent_weight --mask_weight $mask_weight --gated_mask --seed ${seed} --tensorboard_dir ${tensorboard_dir}| tee ${log_path}/${id}-0 # CUDA_VISIBLE_DEVICES=0 python ${GITHUB_path}/train.py --dist_url $dist_url --cfgs_file $cfgs_file \ # --checkpoint_path $checkpoint_path --batch_size $batch_size --world_size 3 --rank 0 --max_epochs ${max_epochs} \ # --cuda --sent_weight $sent_weight --mask_weight $mask_weight --gated_mask | tee ${log_path}/${id}-0 # CUDA_VISIBLE_DEVICES=1 python ${GITHUB_path}/train.py --dist_url $dist_url --cfgs_file $cfgs_file \ # --checkpoint_path $checkpoint_path --batch_size $batch_size --world_size 3 --rank 1 --max_epochs ${max_epochs} \ # --cuda --sent_weight $sent_weight --mask_weight $mask_weight --gated_mask | tee ${log_path}/${id}-1 # CUDA_VISIBLE_DEVICES=2 python ${GITHUB_path}/train.py --dist_url $dist_url --cfgs_file $cfgs_file \ # --checkpoint_path $checkpoint_path --batch_size $batch_size --world_size 3 --rank 2 --max_epochs ${max_epochs} \ # --cuda --sent_weight $sent_weight --mask_weight $mask_weight --gated_mask | tee ${log_path}/${id}-2
set -e root_dir=$(dirname $(dirname $(dirname $(readlink -f "$0")))) env_path="${root_dir}/.env.local" source "${env_path}" if [ "$REACT_APP_TOGGLE_THE_GRAPH" != "true" ]; then echo "The graph feature flag is toggled off. Exiting..." exit 0 fi docker-compose down -v; if [ -d "data" ] then echo "Found old data for the graph node - deleting it"; # we need to sudo this to remove system locked files sudo rm -rf data/; fi
def gen_fibonacci(N): # Generate the first two numbers fibonacci = [0, 1] # Generate rest of the numbers while len(fibonacci) < N: fibonacci.append(fibonacci[-1] + fibonacci[-2]) return fibonacci
package org.zyf.scholarship.zxj.service; import org.zyf.scholarship.zxj.entity.ZyfZxj; import com.baomidou.mybatisplus.extension.service.IService; /** * @Description: 助学金 * @Author: jeecg-boot * @Date: 2021-02-23 * @Version: V1.0 */ public interface IZyfZxjService extends IService<ZyfZxj> { }
# Copyright 2017 BBVA # # 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 os import json import pytest from apitest.core.loaders import _load_from_file @pytest.fixture def build_temp_file(apitest_json): def _temp_file(path): with open(path, "w") as f: f.write(json.dumps(apitest_json)) return _temp_file def test__load_from_file_runs_ok(): with pytest.raises(AssertionError): _load_from_file(None) def test__load_from_file_runs_from_file_uri(tmpdir, build_temp_file, apitest_json): file_path = os.path.join(str(tmpdir), os.path.basename("file://asdf.json")) # create the file first build_temp_file(file_path) assert _load_from_file(file_path) == apitest_json
#!/usr/bin/bash # Copyright (c) 2020. Huawei Technologies Co.,Ltd.ALL rights reserved. # This program is licensed under Mulan PSL v2. # You can use it according to the terms and conditions of the Mulan PSL v2. # http://license.coscl.org.cn/MulanPSL2 # THIS PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the Mulan PSL v2 for more details. # ############################################# # @Author : doraemon2020 # @Contact : xcl_job@163.com # @Date : 2020-04-09 # @License : Mulan PSL v2 # @Desc : Use chronyc to control chronyd # ############################################ source ${OET_PATH}/libs/locallibs/common_lib.sh function pre_test() { LOG_INFO "Start to prepare the test environment." DNF_INSTALL "chrony" systemctl start chronyd LOG_INFO "End to prepare the test environment." } function run_test() { LOG_INFO "Start to run test." systemctl status chronyd | grep running CHECK_RESULT $? rm -rf testlog expect -d <<ENF0 spawn chronyc log_file testlog expect "chronyc>" send "help\\r" expect "chronyc>" send "sourcestats -v\\r" expect "chronyc>" send "quit\\r" ENF0 CHECK_RESULT $? grep -i Manual testlog CHECK_RESULT $? grep "Name/IP Address" testlog CHECK_RESULT $? LOG_INFO "End to run test." } function post_test() { LOG_INFO "Start to restore the test environment." rm -rf testlog systemctl stop chronyd DNF_REMOVE LOG_INFO "End to restore the test environment." } main "$@"
package net.community.chest.mail.message; import java.io.IOException; import java.io.OutputStream; import net.community.chest.io.output.OutputStreamEmbedder; /** * <P>Copyright 2007 as per GPLv2</P> * * @author <NAME>. * @since Sep 19, 2007 9:04:32 AM */ public class EOMHunterOutputStream extends OutputStreamEmbedder implements EOMDataStreamHunter { private boolean _haveEOM /* =false */; /* * @see net.community.chest.mail.message.EOMDataStreamHunter#isEOMDetected() */ @Override public boolean isEOMDetected () { return _haveEOM; } /* * @see net.community.chest.mail.message.EOMDataStreamHunter#setEOMDetected(boolean) */ @Override public void setEOMDetected (boolean haveEOM) { _haveEOM = haveEOM; } private boolean _echoEOM /* =false */; /* * @see net.community.chest.mail.message.EOMDataStreamHunter#isEchoEOM() */ @Override public boolean isEchoEOM () { return _echoEOM; } /* * @see net.community.chest.mail.message.EOMDataStreamHunter#setEchoEOM(boolean) */ @Override public void setEchoEOM (boolean echoEOM) { _echoEOM = echoEOM; } /** * @param os output stream to write data to while "hunting" for EOM * @param echoEOM If set, then EOM is "echoed" to the "real" stream * after its detection. Otherwise, it is omitted from the real stream. * @param realClose If set, the calling "close" on this stream also * closes the "real" stream */ public EOMHunterOutputStream (OutputStream os, boolean echoEOM, boolean realClose) { super(os, realClose); setEchoEOM(echoEOM); } /** * Creates an output stream that does not echo the EOM (if found), and calls * the underlying stream's "close" method on calling its "close". * @param os output stream to write data to while "hunting" for EOM */ public EOMHunterOutputStream (OutputStream os) { this(os, false, true); } // maximum EOM signal is CRLF.CRLF (we accept LF.LF as well as similar variations) private final byte[] _lastBuf=new byte[EOMHunter.MAX_EOM_SEQLEN]; // number of valid bytes in _lastBuf private int _bufPos /* =0 */; /** * Writes the specified buffer while analyzing it * @param buf buffer to be written * @param offset offset of data in buffer * @param len number of bytes to be written * @param echoToOutput if FALSE, then only the EOM state is updated, * but the data is not written to the real output stream.<B>Note:</B> * this method can be used to set the internal EOM state to some * initial value without affecting the real output stream * @throws IOException unable to write */ protected void write (byte[] buf, int offset, int len, boolean echoToOutput) throws IOException { if (null == this.out) throw new IOException("No output stream to write buffer to"); if ((offset < 0) || (len < 0)) throw new IOException("Bad/Illegal buffer range"); if (0 == len) return; final int maxPos=(offset + len); if ((null == buf) || (maxPos > buf.length)) throw new IOException("Bad buffer positions"); // not allowed to write data after EOM has been detected if (isEOMDetected()) throw new IOException("Data buffer write after EOM"); // NOTE !!! we check only on buffer "edges" and not in between if (len >= _lastBuf.length) { if ((_bufPos > 0) && echoToOutput) // flush out any previous data this.out.write(_lastBuf, 0, _bufPos); // do not write last sequence as it may be the EOM final int writeLen=(len - _lastBuf.length); if ((writeLen > 0) && echoToOutput) this.out.write(buf, offset, writeLen); System.arraycopy(buf, offset + writeLen, _lastBuf, 0, _lastBuf.length); _bufPos = _lastBuf.length; } else { // check how much data we should carry over from current EOM buffer hunter final int totalLen=_bufPos + len; // if appending to current data exceeds buffer size, then make room for appending if (totalLen > _lastBuf.length) { // flush out the extra bytes from start of buffer to make room final int writeLen=(totalLen - _lastBuf.length); if (echoToOutput) this.out.write(_lastBuf, 0, writeLen); // "shift" down the written bytes to make room for new data for (int i=writeLen; i < _bufPos; i++) _lastBuf[i-writeLen] = _lastBuf[i]; _bufPos -= writeLen; } System.arraycopy(buf, offset, _lastBuf, _bufPos, len); _bufPos += len; } setEOMDetected(EOMHunter.checkEOMBuffer(_lastBuf, 0, _bufPos) > 0); } /* * @see java.io.FilterOutputStream#write(byte[], int, int) */ @Override public void write (byte[] buf, int offset, int len) throws IOException { write(buf, offset, len , true); } /** * @param val value to be written * @param echoToOutput if FALSE, then only the EOM state is updated, * but the data is not written to the real output stream.<B>Note:</B> * this method can be used to set the internal EOM state to some * initial value without affecting the real output stream * @throws IOException unable to write */ protected void write (int val, boolean echoToOutput) throws IOException { if (null == this.out) throw new IOException("No output stream to write character to"); // not allowed to write data after EOM has been detected if (isEOMDetected()) throw new IOException("Character write after EOM"); /* If character cannot possibly be part of a EOM sequence then * flush any previous buffer and this character as well */ if ((val != '\r') && (val != '\n') && (val != '.')) { if (_bufPos > 0) { if (echoToOutput) this.out.write(_lastBuf, 0, _bufPos); _bufPos = 0; } if (echoToOutput) this.out.write(val); } else // character might complete a sequence { // make root for the new value if (_bufPos >= _lastBuf.length) { for (int i=1; i < _lastBuf.length; i++) _lastBuf[i-1] = _lastBuf[i]; _lastBuf[_lastBuf.length-1] = (byte) val; } else // append new value { _lastBuf[_bufPos] = (byte) val; _bufPos++; } setEOMDetected(EOMHunter.checkEOMBuffer(_lastBuf, 0, _bufPos) > 0); } } /* * @see net.community.chest.io.OutputStreamEmbedder#write(int) */ @Override public void write (int val) throws IOException { write(val, true); } /* NOTE !!! must be called to ensure echoing of EOM and/or flushing of internal EOM buffer * @see net.community.chest.io.OutputStreamEmbedder#close() */ @Override public void close () throws IOException { if (this.out != null) { // check if have any leftovers from EOM hunt if (_bufPos > 0) { // write the CRLF that comes before the '.' (but not the '.' or the following CRLF) if (isEOMDetected() && (!isEchoEOM()) && (_bufPos >= EOMHunter.MIN_EOM_SEQLEN)) this.out.write(_lastBuf, 0, _bufPos - EOMHunter.MIN_EOM_SEQLEN); else if ((!isEOMDetected()) || isEchoEOM()) this.out.write(_lastBuf, 0, _bufPos); } super.close(); } } }
#! /bin/sh - # @(#)makesyscalls.sh 8.1 (Berkeley) 6/10/93 # $FreeBSD: src/sys/kern/makesyscalls.sh,v 1.60 2003/04/01 01:12:24 jeff Exp $ # # Copyright (c) 2004-2008 Apple Inc. All rights reserved. # # @APPLE_OSREFERENCE_LICENSE_HEADER_START@ # # This file contains Original Code and/or Modifications of Original Code # as defined in and that are subject to the Apple Public Source License # Version 2.0 (the 'License'). You may not use this file except in # compliance with the License. Please obtain a copy of the License at # http://www.opensource.apple.com/apsl/ and read it before using this # file. # # The Original Code and all software distributed under the License are # distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER # EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, # INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. # Please see the License for the specific language governing rights and # limitations under the License. # # @APPLE_OSREFERENCE_LICENSE_HEADER_END@ # set -e input_file="" # first argument # output type: output_syscallnamesfile=0 output_sysprotofile=0 output_syshdrfile=0 output_syscalltablefile=0 output_auditevfile=0 # output files: syscallnamesfile="syscalls.c" sysprotofile="sysproto.h" sysproto_h=_SYS_SYSPROTO_H_ syshdrfile="syscall.h" syscall_h=_SYS_SYSCALL_H_ syscalltablefile="init_sysent.c" auditevfile="audit_kevents.c" syscallprefix="SYS_" switchname="sysent" namesname="syscallnames" # tmp files: syslegal="sysent.syslegal.$$" sysent="sysent.switch.$$" sysinc="sysinc.switch.$$" sysarg="sysarg.switch.$$" sysprotoend="sysprotoend.$$" syscallnamestempfile="syscallnamesfile.$$" syshdrtempfile="syshdrtempfile.$$" audittempfile="audittempfile.$$" trap "rm $syslegal $sysent $sysinc $sysarg $sysprotoend $syscallnamestempfile $syshdrtempfile $audittempfile" 0 touch $syslegal $sysent $sysinc $sysarg $sysprotoend $syscallnamestempfile $syshdrtempfile $audittempfile case $# in 0) echo "usage: $0 input-file [<names|proto|header|table|audit> [<config-file>]]" 1>&2 exit 1 ;; esac input_file="$1" shift if [ -n "$1" ]; then case $1 in names) output_syscallnamesfile=1 ;; proto) output_sysprotofile=1 ;; header) output_syshdrfile=1 ;; table) output_syscalltablefile=1 ;; audit) output_auditevfile=1 ;; esac shift; else output_syscallnamesfile=1 output_sysprotofile=1 output_syshdrfile=1 output_syscalltablefile=1 output_auditevfile=1 fi if [ -n "$1" -a -f "$1" ]; then . $1 fi sed -e ' s/\$//g :join /\\$/{a\ N s/\\\n// b join } 2,${ /^#/!s/\([{}()*,;]\)/ \1 /g } ' < "$input_file" | awk " BEGIN { syslegal = \"$syslegal\" sysprotofile = \"$sysprotofile\" sysprotoend = \"$sysprotoend\" sysproto_h = \"$sysproto_h\" syscall_h = \"$syscall_h\" sysent = \"$sysent\" syscalltablefile = \"$syscalltablefile\" sysinc = \"$sysinc\" sysarg = \"$sysarg\" syscallnamesfile = \"$syscallnamesfile\" syscallnamestempfile = \"$syscallnamestempfile\" syshdrfile = \"$syshdrfile\" syshdrtempfile = \"$syshdrtempfile\" audittempfile = \"$audittempfile\" syscallprefix = \"$syscallprefix\" switchname = \"$switchname\" namesname = \"$namesname\" infile = \"$input_file\" "' printf "/*\n" > syslegal printf " * Copyright (c) 2004-2008 Apple Inc. All rights reserved.\n" > syslegal printf " * \n" > syslegal printf " * @APPLE_OSREFERENCE_LICENSE_HEADER_START@\n" > syslegal printf " * \n" > syslegal printf " * This file contains Original Code and/or Modifications of Original Code\n" > syslegal printf " * as defined in and that are subject to the Apple Public Source License\n" > syslegal printf " * Version 2.0 (the \047License\047). You may not use this file except in\n" > syslegal printf " * compliance with the License. The rights granted to you under the License\n" > syslegal printf " * may not be used to create, or enable the creation or redistribution of,\n" > syslegal printf " * unlawful or unlicensed copies of an Apple operating system, or to\n" > syslegal printf " * circumvent, violate, or enable the circumvention or violation of, any\n" > syslegal printf " * terms of an Apple operating system software license agreement.\n" > syslegal printf " * \n" > syslegal printf " * Please obtain a copy of the License at\n" > syslegal printf " * http://www.opensource.apple.com/apsl/ and read it before using this file.\n" > syslegal printf " * \n" > syslegal printf " * The Original Code and all software distributed under the License are\n" > syslegal printf " * distributed on an \047AS IS\047 basis, WITHOUT WARRANTY OF ANY KIND, EITHER\n" > syslegal printf " * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,\n" > syslegal printf " * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,\n" > syslegal printf " * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.\n" > syslegal printf " * Please see the License for the specific language governing rights and\n" > syslegal printf " * limitations under the License.\n" > syslegal printf " * \n" > syslegal printf " * @APPLE_OSREFERENCE_LICENSE_HEADER_END@\n" > syslegal printf " * \n" > syslegal printf " * \n" > syslegal printf " * System call switch table.\n *\n" > syslegal printf " * DO NOT EDIT-- this file is automatically generated.\n" > syslegal printf " * created from %s\n */\n\n", infile > syslegal } NR == 1 { printf "\n/* The casts are bogus but will do for now. */\n" > sysent printf "__private_extern__ const struct sysent %s[] = {\n",switchname > sysent printf "#ifndef %s\n", sysproto_h > sysarg printf "#define\t%s\n\n", sysproto_h > sysarg printf "#ifndef %s\n", syscall_h > syshdrtempfile printf "#define\t%s\n\n", syscall_h > syshdrtempfile printf "#include <sys/appleapiopts.h>\n" > syshdrtempfile printf "#ifdef __APPLE_API_PRIVATE\n" > syshdrtempfile printf "#include <sys/appleapiopts.h>\n" > sysarg printf "#include <sys/cdefs.h>\n" > sysarg printf "#include <sys/mount_internal.h>\n" > sysarg printf "#include <sys/types.h>\n" > sysarg printf "#include <sys/sem_internal.h>\n" > sysarg printf "#include <sys/semaphore.h>\n" > sysarg printf "#include <sys/wait.h>\n" > sysarg printf "#include <mach/shared_region.h>\n" > sysarg printf "\n#ifdef KERNEL\n" > sysarg printf "#ifdef __APPLE_API_PRIVATE\n" > sysarg printf "/*\n" > sysarg printf " * The kernel may support multiple userspace ABIs, and must use\n" > sysarg printf " * argument structures with elements large enough for any of them.\n" > sysarg printf "*/\n" > sysarg printf "\n" > sysarg printf "#ifndef __arm__\n" > sysarg printf "#define\tPAD_(t)\t(sizeof(uint64_t) <= sizeof(t) \\\n " > sysarg printf "\t\t? 0 : sizeof(uint64_t) - sizeof(t))\n" > sysarg printf "#else\n" > sysarg printf "#define\tPAD_(t)\t(sizeof(uint32_t) <= sizeof(t) \\\n" > sysarg printf " ? 0 : sizeof(uint32_t) - sizeof(t))\n" > sysarg printf "#endif\n" > sysarg printf "#if BYTE_ORDER == LITTLE_ENDIAN\n"> sysarg printf "#define\tPADL_(t)\t0\n" > sysarg printf "#define\tPADR_(t)\tPAD_(t)\n" > sysarg printf "#else\n" > sysarg printf "#define\tPADL_(t)\tPAD_(t)\n" > sysarg printf "#define\tPADR_(t)\t0\n" > sysarg printf "#endif\n" > sysarg printf "\n__BEGIN_DECLS\n" > sysarg printf "#if !defined(__arm__)\n" > sysarg printf "void munge_w(const void *, void *); \n" > sysarg printf "void munge_ww(const void *, void *); \n" > sysarg printf "void munge_www(const void *, void *); \n" > sysarg printf "void munge_wwww(const void *, void *); \n" > sysarg printf "void munge_wwwww(const void *, void *); \n" > sysarg printf "void munge_wwwwww(const void *, void *); \n" > sysarg printf "void munge_wwwwwww(const void *, void *); \n" > sysarg printf "void munge_wwwwwwww(const void *, void *); \n" > sysarg printf "void munge_wl(const void *, void *); \n" > sysarg printf "void munge_wlw(const void *, void *); \n" > sysarg printf "void munge_wlwwwll(const void *, void *); \n" > sysarg printf "void munge_wlwwwllw(const void *, void *); \n" > sysarg printf "void munge_wlwwlwlw(const void *, void *); \n" > sysarg printf "void munge_wllwwll(const void *, void *); \n" > sysarg printf "void munge_wwwl(const void *, void *); \n" > sysarg printf "void munge_wwwlw(const void *, void *); \n" > sysarg printf "void munge_wwwlww(const void *, void *); \n" > sysarg printf "void munge_wwlwww(const void *, void *); \n" > sysarg printf "void munge_wwwwlw(const void *, void *); \n" > sysarg printf "void munge_wwwwl(const void *, void *); \n" > sysarg printf "void munge_wwwwwl(const void *, void *); \n" > sysarg printf "void munge_wwwwwlww(const void *, void *); \n" > sysarg printf "void munge_wwwwwllw(const void *, void *); \n" > sysarg printf "void munge_wwwwwlll(const void *, void *); \n" > sysarg printf "void munge_wwwwwwll(const void *, void *); \n" > sysarg printf "void munge_wwwwwwl(const void *, void *); \n" > sysarg printf "void munge_wwwwwwlw(const void *, void *); \n" > sysarg printf "void munge_wsw(const void *, void *); \n" > sysarg printf "void munge_wws(const void *, void *); \n" > sysarg printf "void munge_wwwsw(const void *, void *); \n" > sysarg printf "void munge_llllll(const void *, void *); \n" > sysarg printf "#else \n" > sysarg printf "/* ARM does not need mungers for BSD system calls. */\n" > sysarg printf "#define munge_w NULL \n" > sysarg printf "#define munge_ww NULL \n" > sysarg printf "#define munge_www NULL \n" > sysarg printf "#define munge_wwww NULL \n" > sysarg printf "#define munge_wwwww NULL \n" > sysarg printf "#define munge_wwwwww NULL \n" > sysarg printf "#define munge_wwwwwww NULL \n" > sysarg printf "#define munge_wwwwwwww NULL \n" > sysarg printf "#define munge_wl NULL \n" > sysarg printf "#define munge_wlw NULL \n" > sysarg printf "#define munge_wlwwwll NULL \n" > sysarg printf "#define munge_wlwwwllw NULL \n" > sysarg printf "#define munge_wlwwlwlw NULL \n" > sysarg printf "#define munge_wllwwll NULL \n" > sysarg printf "#define munge_wwwl NULL \n" > sysarg printf "#define munge_wwwlw NULL \n" > sysarg printf "#define munge_wwwlww NULL\n" > sysarg printf "#define munge_wwlwww NULL \n" > sysarg printf "#define munge_wwwwl NULL \n" > sysarg printf "#define munge_wwwwlw NULL \n" > sysarg printf "#define munge_wwwwwl NULL \n" > sysarg printf "#define munge_wwwwwlww NULL \n" > sysarg printf "#define munge_wwwwwllw NULL \n" > sysarg printf "#define munge_wwwwwlll NULL \n" > sysarg printf "#define munge_wwwwwwl NULL \n" > sysarg printf "#define munge_wwwwwwlw NULL \n" > sysarg printf "#define munge_wsw NULL \n" > sysarg printf "#define munge_wws NULL \n" > sysarg printf "#define munge_wwwsw NULL \n" > sysarg printf "#define munge_llllll NULL \n" > sysarg printf "#endif /* __arm__ */\n" > sysarg printf "\n" > sysarg printf "/* Active 64-bit user ABIs do not need munging */\n" > sysarg printf "#define munge_d NULL \n" > sysarg printf "#define munge_dd NULL \n" > sysarg printf "#define munge_ddd NULL \n" > sysarg printf "#define munge_dddd NULL \n" > sysarg printf "#define munge_ddddd NULL \n" > sysarg printf "#define munge_dddddd NULL \n" > sysarg printf "#define munge_ddddddd NULL \n" > sysarg printf "#define munge_dddddddd NULL \n" > sysarg printf "\n" > sysarg printf "const char *%s[] = {\n", namesname > syscallnamestempfile printf "#include <sys/param.h>\n" > audittempfile printf "#include <sys/types.h>\n\n" > audittempfile printf "#include <bsm/audit.h>\n" > audittempfile printf "#include <bsm/audit_kevents.h>\n\n" > audittempfile printf "#if CONFIG_AUDIT\n\n" > audittempfile printf "au_event_t sys_au_event[] = {\n" > audittempfile next } NF == 0 || $1 ~ /^;/ { next } $1 ~ /^#[ ]*include/ { print > sysinc next } $1 ~ /^#[ ]*if/ { print > sysent print > sysarg print > syscallnamestempfile print > sysprotoend print > audittempfile savesyscall = syscall_num skip_for_header = 0 next } $1 ~ /^#[ ]*else/ { print > sysent print > sysarg print > syscallnamestempfile print > sysprotoend print > audittempfile syscall_num = savesyscall skip_for_header = 1 next } $1 ~ /^#/ { print > sysent print > sysarg print > syscallnamestempfile print > sysprotoend print > audittempfile skip_for_header = 0 next } syscall_num != $1 { printf "%s: line %d: syscall number out of sync at %d\n", infile, NR, syscall_num printf "line is:\n" print exit 1 } function align_comment(linesize, location, thefile) { printf(" ") > thefile while (linesize < location) { printf(" ") > thefile linesize++ } } function parserr(was, wanted) { printf "%s: line %d: unexpected %s (expected %s)\n", infile, NR, was, wanted exit 1 } function parseline() { funcname = "" current_field = 4 # skip number, audit event, type args_start = 0 args_end = 0 comments_start = 0 comments_end = 0 argc = 0 argssize = "0" additional_comments = " " # find start and end of call name and arguments if ($current_field != "{") parserr($current_field, "{") args_start = current_field current_field++ while (current_field <= NF) { if ($current_field == "}") { args_end = current_field break } current_field++ } if (args_end == 0) { printf "%s: line %d: invalid call name and arguments\n", infile, NR exit 1 } # find start and end of optional comments current_field++ if (current_field < NF && $current_field == "{") { comments_start = current_field while (current_field <= NF) { if ($current_field == "}") { comments_end = current_field break } current_field++ } if (comments_end == 0) { printf "%s: line %d: invalid comments \n", infile, NR exit 1 } } if ($args_end != "}") parserr($args_end, "}") args_end-- if ($args_end != ";") parserr($args_end, ";") args_end-- # skip any NO_SYSCALL_STUB qualifier if ($args_end == "NO_SYSCALL_STUB") args_end-- if ($args_end != ")") parserr($args_end, ")") args_end-- # extract additional comments if (comments_start != 0) { current_field = comments_start + 1 while (current_field < comments_end) { additional_comments = additional_comments $current_field " " current_field++ } } # get function return type current_field = args_start + 1 returntype = $current_field # get function name and set up to get arguments current_field++ funcname = $current_field argalias = funcname "_args" current_field++ # bump past function name if ($current_field != "(") parserr($current_field, "(") current_field++ if (current_field == args_end) { if ($current_field != "void") parserr($current_field, "argument definition") return } # extract argument types and names while (current_field <= args_end) { argc++ argtype[argc]="" ext_argtype[argc]="" oldf="" while (current_field < args_end && $(current_field + 1) != ",") { if (argtype[argc] != "" && oldf != "*") { argtype[argc] = argtype[argc] " "; } argtype[argc] = argtype[argc] $current_field; ext_argtype[argc] = argtype[argc]; oldf = $current_field; current_field++ } if (argtype[argc] == "") parserr($current_field, "argument definition") argname[argc] = $current_field; current_field += 2; # skip name, and any comma } if (argc > 8) { printf "%s: line %d: too many arguments!\n", infile, NR exit 1 } if (argc != 0) argssize = "AC(" argalias ")" } { auditev = $2; } { add_sysent_entry = 1 add_sysnames_entry = 1 add_sysheader_entry = 1 add_sysproto_entry = 1 add_64bit_unsafe = 0 add_64bit_fakesafe = 0 add_resv = "0" my_flags = "0" if ($3 != "ALL" && $3 != "UALL") { files_keyword_OK = 0 add_sysent_entry = 0 add_sysnames_entry = 0 add_sysheader_entry = 0 add_sysproto_entry = 0 if (match($3, "[T]") != 0) { add_sysent_entry = 1 files_keyword_OK = 1 } if (match($3, "[N]") != 0) { add_sysnames_entry = 1 files_keyword_OK = 1 } if (match($3, "[H]") != 0) { add_sysheader_entry = 1 files_keyword_OK = 1 } if (match($3, "[P]") != 0) { add_sysproto_entry = 1 files_keyword_OK = 1 } if (match($3, "[U]") != 0) { add_64bit_unsafe = 1 } if (match($3, "[F]") != 0) { add_64bit_fakesafe = 1 } if (files_keyword_OK == 0) { printf "%s: line %d: unrecognized keyword %s\n", infile, NR, $2 exit 1 } } else if ($3 == "UALL") { add_64bit_unsafe = 1; } parseline() # output function argument structures to sysproto.h and build the # name of the appropriate argument mungers munge32 = "NULL" munge64 = "NULL" size32 = 0 if ((funcname != "nosys" && funcname != "enosys") || (syscall_num == 0 && funcname == "nosys")) { if (argc != 0) { if (add_sysproto_entry == 1) { printf("struct %s {\n", argalias) > sysarg } munge32 = "munge_" munge64 = "munge_" for (i = 1; i <= argc; i++) { # Build name of argument munger. # We account for all sys call argument types here. # This is where you add any new types. With LP64 support # each argument consumes 64-bits. # see .../xnu/bsd/dev/ppc/munge.s for munge argument types. if (argtype[i] == "long") { if (add_64bit_unsafe == 0) ext_argtype[i] = "user_long_t"; munge32 = munge32 "s" munge64 = munge64 "d" size32 += 4 } else if (argtype[i] == "u_long") { if (add_64bit_unsafe == 0) ext_argtype[i] = "user_ulong_t"; munge32 = munge32 "w" munge64 = munge64 "d" size32 += 4 } else if (argtype[i] == "size_t") { if (add_64bit_unsafe == 0) ext_argtype[i] = "user_size_t"; munge32 = munge32 "w" munge64 = munge64 "d" size32 += 4 } else if (argtype[i] == "ssize_t") { if (add_64bit_unsafe == 0) ext_argtype[i] = "user_ssize_t"; munge32 = munge32 "s" munge64 = munge64 "d" size32 += 4 } else if (argtype[i] == "user_ssize_t" || argtype[i] == "user_long_t") { munge32 = munge32 "s" munge64 = munge64 "d" size32 += 4 } else if (argtype[i] == "user_addr_t" || argtype[i] == "user_size_t" || argtype[i] == "user_ulong_t") { munge32 = munge32 "w" munge64 = munge64 "d" size32 += 4 } else if (argtype[i] == "caddr_t" || argtype[i] == "semun_t" || match(argtype[i], "[\*]") != 0) { if (add_64bit_unsafe == 0) ext_argtype[i] = "user_addr_t"; munge32 = munge32 "w" munge64 = munge64 "d" size32 += 4 } else if (argtype[i] == "int" || argtype[i] == "u_int" || argtype[i] == "uid_t" || argtype[i] == "pid_t" || argtype[i] == "id_t" || argtype[i] == "idtype_t" || argtype[i] == "socklen_t" || argtype[i] == "uint32_t" || argtype[i] == "int32_t" || argtype[i] == "sigset_t" || argtype[i] == "gid_t" || argtype[i] == "unsigned int" || argtype[i] == "mode_t" || argtype[i] == "key_t" || argtype[i] == "mach_port_name_t" || argtype[i] == "au_asid_t") { munge32 = munge32 "w" munge64 = munge64 "d" size32 += 4 } else if (argtype[i] == "off_t" || argtype[i] == "int64_t" || argtype[i] == "uint64_t") { munge32 = munge32 "l" munge64 = munge64 "d" size32 += 8 } else { printf "%s: line %d: invalid type \"%s\" \n", infile, NR, argtype[i] printf "You need to add \"%s\" into the type checking code. \n", argtype[i] exit 1 } if (add_sysproto_entry == 1) { printf("\tchar %s_l_[PADL_(%s)]; " \ "%s %s; char %s_r_[PADR_(%s)];\n", argname[i], ext_argtype[i], ext_argtype[i], argname[i], argname[i], ext_argtype[i]) > sysarg } } if (add_sysproto_entry == 1) { printf("};\n") > sysarg } } else if (add_sysproto_entry == 1) { printf("struct %s {\n\tint32_t dummy;\n};\n", argalias) > sysarg } } # output to init_sysent.c tempname = funcname if (add_sysent_entry == 0) { argssize = "0" munge32 = "NULL" munge64 = "NULL" munge_ret = "_SYSCALL_RET_NONE" if (tempname != "enosys") { tempname = "nosys" } } else { # figure out which return value type to munge if (returntype == "user_addr_t") { munge_ret = "_SYSCALL_RET_ADDR_T" } else if (returntype == "user_ssize_t") { munge_ret = "_SYSCALL_RET_SSIZE_T" } else if (returntype == "user_size_t") { munge_ret = "_SYSCALL_RET_SIZE_T" } else if (returntype == "int") { munge_ret = "_SYSCALL_RET_INT_T" } else if (returntype == "u_int" || returntype == "mach_port_name_t") { munge_ret = "_SYSCALL_RET_UINT_T" } else if (returntype == "uint32_t") { munge_ret = "_SYSCALL_RET_UINT_T" } else if (returntype == "uint64_t") { munge_ret = "_SYSCALL_RET_UINT64_T" } else if (returntype == "off_t") { munge_ret = "_SYSCALL_RET_OFF_T" } else if (returntype == "void") { munge_ret = "_SYSCALL_RET_NONE" } else { printf "%s: line %d: invalid return type \"%s\" \n", infile, NR, returntype printf "You need to add \"%s\" into the return type checking code. \n", returntype exit 1 } } if (add_64bit_unsafe == 1 && add_64bit_fakesafe == 0) my_flags = "UNSAFE_64BIT"; printf("\t{%s, %s, %s, \(sy_call_t *\)%s, %s, %s, %s, %s},", argssize, add_resv, my_flags, tempname, munge32, munge64, munge_ret, size32) > sysent linesize = length(argssize) + length(add_resv) + length(my_flags) + length(tempname) + \ length(munge32) + length(munge64) + length(munge_ret) + 28 align_comment(linesize, 88, sysent) printf("/* %d = %s%s*/\n", syscall_num, funcname, additional_comments) > sysent # output to syscalls.c if (add_sysnames_entry == 1) { tempname = funcname if (funcname == "nosys" || funcname == "enosys") { if (syscall_num == 0) tempname = "syscall" else tempname = "#" syscall_num } printf("\t\"%s\", ", tempname) > syscallnamestempfile linesize = length(tempname) + 8 align_comment(linesize, 25, syscallnamestempfile) if (substr(tempname,1,1) == "#") { printf("/* %d =%s*/\n", syscall_num, additional_comments) > syscallnamestempfile } else { printf("/* %d = %s%s*/\n", syscall_num, tempname, additional_comments) > syscallnamestempfile } } # output to syscalls.h if (add_sysheader_entry == 1) { tempname = funcname if (syscall_num == 0) { tempname = "syscall" } if (tempname != "nosys" && tempname != "enosys") { printf("#define\t%s%s", syscallprefix, tempname) > syshdrtempfile linesize = length(syscallprefix) + length(tempname) + 12 align_comment(linesize, 30, syshdrtempfile) printf("%d\n", syscall_num) > syshdrtempfile # special case for gettimeofday on ppc - cctools project uses old name if (tempname == "ppc_gettimeofday") { printf("#define\t%s%s", syscallprefix, "gettimeofday") > syshdrtempfile linesize = length(syscallprefix) + length(tempname) + 12 align_comment(linesize, 30, syshdrtempfile) printf("%d\n", syscall_num) > syshdrtempfile } } else if (skip_for_header == 0) { printf("\t\t\t/* %d %s*/\n", syscall_num, additional_comments) > syshdrtempfile } } # output function prototypes to sysproto.h if (add_sysproto_entry == 1) { if (funcname =="exit") { printf("void %s(struct proc *, struct %s *, int32_t *);\n", funcname, argalias) > sysprotoend } else if ((funcname != "nosys" && funcname != "enosys") || (syscall_num == 0 && funcname == "nosys")) { printf("int %s(struct proc *, struct %s *, %s *);\n", funcname, argalias, returntype) > sysprotoend } } # output to audit_kevents.c printf("\t%s,\t\t", auditev) > audittempfile printf("/* %d = %s%s*/\n", syscall_num, tempname, additional_comments) > audittempfile syscall_num++ next } END { printf "#define AC(name) (sizeof(struct name) / sizeof(syscall_arg_t))\n" > sysinc printf "\n" > sysinc printf("\n__END_DECLS\n") > sysprotoend printf("#undef PAD_\n") > sysprotoend printf("#undef PADL_\n") > sysprotoend printf("#undef PADR_\n") > sysprotoend printf "\n#endif /* __APPLE_API_PRIVATE */\n" > sysprotoend printf "#endif /* KERNEL */\n" > sysprotoend printf("\n#endif /* !%s */\n", sysproto_h) > sysprotoend printf("};\n") > sysent printf("int nsysent = sizeof(sysent) / sizeof(sysent[0]);\n") > sysent printf("/* Verify that NUM_SYSENT reflects the latest syscall count */\n") > sysent printf("int nsysent_size_check[((sizeof(sysent) / sizeof(sysent[0])) == NUM_SYSENT) ? 1 : -1] __unused;\n") > sysent printf("};\n") > syscallnamestempfile printf("#define\t%sMAXSYSCALL\t%d\n", syscallprefix, syscall_num) \ > syshdrtempfile printf("\n#endif /* __APPLE_API_PRIVATE */\n") > syshdrtempfile printf("#endif /* !%s */\n", syscall_h) > syshdrtempfile printf("};\n\n") > audittempfile printf("#endif /* AUDIT */\n") > audittempfile } ' # define value in syscall table file to permit redifintion because of the way # __private_extern__ (doesn't) work. if [ $output_syscalltablefile -eq 1 ]; then cat $syslegal > $syscalltablefile printf "#define __INIT_SYSENT_C__ 1\n" >> $syscalltablefile cat $sysinc $sysent >> $syscalltablefile fi if [ $output_syscallnamesfile -eq 1 ]; then cat $syslegal $syscallnamestempfile > $syscallnamesfile fi if [ $output_sysprotofile -eq 1 ]; then cat $syslegal $sysarg $sysprotoend > $sysprotofile fi if [ $output_syshdrfile -eq 1 ]; then cat $syslegal $syshdrtempfile > $syshdrfile fi if [ $output_auditevfile -eq 1 ]; then cat $syslegal $audittempfile > $auditevfile fi
<filename>mantis-tests/src/test/java/ru/stqa/pft/mantis/tests/ChangePasswordTests.java package ru.stqa.pft.mantis.tests; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import ru.stqa.pft.mantis.model.MailMessage; import ru.stqa.pft.mantis.model.UserData; import ru.stqa.pft.mantis.model.Users; import javax.mail.MessagingException; import java.io.IOException; import java.util.List; import static org.testng.Assert.assertTrue; public class ChangePasswordTests extends TestBase { @BeforeMethod public void startMailServer() { app.mail().start(); } @Test public void testChangePassword() throws IOException, MessagingException { String newPassword = "<PASSWORD>"; app.goTo().login("administrator", "root"); app.goTo().manageUsersPage(); Users usersList = app.db().users(); UserData selectedUser = usersList.iterator().next(); String username = selectedUser.getUsername(); app.admin().selectUserByName(username); app.admin().resetPassword(); List<MailMessage> mailMessages = app.mail().waitForMail(1, 10000); String confirmationLink = app.registration().findConfirmationLink(mailMessages, selectedUser.getEmail()); app.admin().changePassword(confirmationLink, newPassword); assertTrue(app.newSession().login(username, newPassword)); } @AfterMethod(alwaysRun = true) public void stopMailServer() { app.mail().stop(); } }
#!/bin/bash function init_conf() { gpu=$1 mode=$2 test_file=$3 attention=$4 geohash=$5 prefix_word=$6 poi_att=$7 poi_word=$8 if [ $# -lt 2 ];then return 1 fi conf_name=conf/poi_qac_personalized/poi_qac_personalized.local.conf conf=$conf_name.Att$attention-$geohash-$prefix_word-$poi_att-$poi_word out=mst-pac-$test_file-Att$attention-$geohash-$prefix_word-$poi_att-$poi_word-$gpu cp $conf_name.template $conf sed -i "s#<attention>#$attention#g" $conf sed -i "s#<test_file>#$test_file#g" $conf sed -i "s#<geohash>#$geohash#g" $conf sed -i "s#<prefix_word>#$prefix_word#g" $conf sed -i "s#<poi_att>#$poi_att#g" $conf sed -i "s#<poi_word>#$poi_word#g" $conf return 0 } function dy_train() { local conf=$1 local out=$2 if [ "$conf" == "" -o "$out" == "" ];then return 1 fi sh run.sh -c $conf -m train 1>../tmp/logs/output/train/$out-train.out 2>../tmp/logs/error/train/$out-train.err } function dy_pred() { local conf=$1 local out=$2 if [ "$conf" == "" -o "$out" == "" ];then return 1 fi sh run.sh -c $conf -m predict 1>../tmp/logs/output/test/$out-pred.out 2>../tmp/logs/error/test/$out-pred.err } conf="" out="" run_type=$1 # model_opts_02="False True False None False" # model_opts_02="True True False cross False" model_opts_02="True True False cross_dot_ffn False" #train eval opts=\$model_opts_02 init_conf 2 nn train $opts dy_train $conf $out
// Copyright (C) MongoDB, Inc. 2017-present. // // 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 package command import ( "context" "github.com/rentiansheng/bk_bsonbson" "github.com/rentiansheng/bk_bson/x/bsonx" "github.com/rentiansheng/bk_bsonx/mongo/driver/session" "github.com/rentiansheng/bk_bsonx/network/description" "github.com/rentiansheng/bk_bsonx/network/result" "github.com/rentiansheng/bk_bsonx/network/wiremessage" ) // ListDatabases represents the listDatabases command. // // The listDatabases command lists the databases in a MongoDB deployment. type ListDatabases struct { Clock *session.ClusterClock Filter bsonx.Doc Opts []bsonx.Elem Session *session.Client result result.ListDatabases err error } // Encode will encode this command into a wire message for the given server description. func (ld *ListDatabases) Encode(desc description.SelectedServer) (wiremessage.WireMessage, error) { encoded, err := ld.encode(desc) if err != nil { return nil, err } return encoded.Encode(desc) } func (ld *ListDatabases) encode(desc description.SelectedServer) (*Read, error) { cmd := bsonx.Doc{{"listDatabases", bsonx.Int32(1)}} if ld.Filter != nil { cmd = append(cmd, bsonx.Elem{"filter", bsonx.Document(ld.Filter)}) } cmd = append(cmd, ld.Opts...) return &Read{ Clock: ld.Clock, DB: "admin", Command: cmd, Session: ld.Session, }, nil } // Decode will decode the wire message using the provided server description. Errors during decoding // are deferred until either the Result or Err methods are called. func (ld *ListDatabases) Decode(desc description.SelectedServer, wm wiremessage.WireMessage) *ListDatabases { rdr, err := (&Read{}).Decode(desc, wm).Result() if err != nil { ld.err = err return ld } return ld.decode(desc, rdr) } func (ld *ListDatabases) decode(desc description.SelectedServer, rdr bson.Raw) *ListDatabases { ld.err = bson.Unmarshal(rdr, &ld.result) return ld } // Result returns the result of a decoded wire message and server description. func (ld *ListDatabases) Result() (result.ListDatabases, error) { if ld.err != nil { return result.ListDatabases{}, ld.err } return ld.result, nil } // Err returns the error set on this command. func (ld *ListDatabases) Err() error { return ld.err } // RoundTrip handles the execution of this command using the provided wiremessage.ReadWriter. func (ld *ListDatabases) RoundTrip(ctx context.Context, desc description.SelectedServer, rw wiremessage.ReadWriter) (result.ListDatabases, error) { cmd, err := ld.encode(desc) if err != nil { return result.ListDatabases{}, err } rdr, err := cmd.RoundTrip(ctx, desc, rw) if err != nil { return result.ListDatabases{}, err } return ld.decode(desc, rdr).Result() }
<gh_stars>10-100 package com.gank.gankly.ui.web.normal; import android.support.annotation.NonNull; import com.gank.gankly.data.entity.ReadHistory; import com.gank.gankly.data.entity.UrlCollect; import com.gank.gankly.mvp.IBasePresenter; import com.gank.gankly.mvp.IBaseView; /** * Create by LingYan on 2016-10-27 * Email:<EMAIL> */ public interface WebContract { interface View extends IBaseView { void onCollect(); void onCancelCollect(); UrlCollect getCollect(); void setCollectIcon(boolean isCollect); } interface Presenter extends IBasePresenter { void findCollectUrl(@NonNull String url); void insetHistoryUrl(@NonNull ReadHistory readHistory); void cancelCollect(); void collectAction(boolean isCollect); void collect(); } }
#!/bin/bash PATH=/pubhome/soft/amber/amber20_21/bin:$PATH antechamber -i ligand.mol2 -fi mol2 -o ligand.gjf -fo gcrt -pf y -gn "%nproc=8" antechamber -i ${lig}.log -fi gout -o ${lig}_resp.mol2 -fo mol2 -c resp -pf y sed -i "s/MOL /${lig} /" ${lig}_resp.mol2 parmchk2 -i ${lig}_resp.mol2 -f mol2 -o ${lig}.frcmod echo "source leaprc.protein.ff19SB source leaprc.gaff ${lig}=loadmol2 ${lig}_resp.mol2 loadamberparams ${lig}.frcmod saveoff ${lig} ${lig}.lib saveamberparm ${lig} ${lig}.prmtop ${lig}.inpcrd quit" > leap.in tleap -f leap.in
<gh_stars>0 package fr.efrei.tp3.view; import fr.efrei.tp3.model.logic.ProgrammerBean; import javax.swing.*; import java.awt.*; import java.util.List; /** * Abstract class that represents an abstract view of the application * This class establishes a service contract for the controller to interact with the view */ public abstract class ViewManager extends JFrame { public ViewManager(String title){ super(title); } // Menu public abstract JMenuItem getLeaveMenuItem(); public abstract JMenuItem getAddMenuItem(); public abstract JMenuItem getModifyMenuItem(); public abstract JMenuItem getDeleteMenuItem(); public abstract JMenuItem getProgrammerMenuDisplayAll(); // Panels public abstract JPanel getEditPanel(); public abstract JPanel getMainPanel(); public abstract JPanel getDisplayPanel(); // Personal number input public abstract JTextField getPersonalNumberField(); // Form Fields public abstract JTextField getFormLastNameField(); public abstract JTextField getFormFirstNameField(); public abstract JTextField getFormHobbyField(); public abstract JTextField getFormManagerField(); public abstract JTextField getFormAddressField(); public abstract JTextField getFormUsernameField(); public abstract JTextField getFormBirthDayField(); public abstract JComboBox<String> getFormBirthMonthField(); public abstract JTextField getFormBirthYearField(); public abstract JTextField getFormHireDayField(); public abstract JComboBox<String> getFormHireMonthField(); public abstract JTextField getFormHireYearField(); // Buttons public abstract JButton getValidationButton(); public abstract JButton getCancelButton(); public abstract JButton getSearchButton(); public abstract JButton getResetButton(); // Table public abstract void storeProgrammersIntoRow(List<ProgrammerBean> programmers); // Form public abstract Component[] getFormComponents(); }
#!/bin/bash # Set environment variables from .env and set NODE_ENV to test source <(dotenv-export | sed 's/\\n/\n/g') export NODE_ENV=test yarn run api:init > /dev/null 2>&1 & yarn run api:install > /dev/null 2>&1 & yarn run api:serve > /dev/null 2>&1 & # Run our web server as a background process yarn run serve > /dev/null 2>&1 & # Polling to see if the server is up and running yet TRIES=0 RETRY_LIMIT=50 RETRY_INTERVAL=0.5 SERVER_UP=false while [ $TRIES -lt $RETRY_LIMIT ]; do if netstat -tulpn 2>/dev/null | grep -q ":$WEB_SERVER_PORT_TEST.*LISTEN"; then SERVER_UP=true break else sleep $RETRY_INTERVAL let TRIES=TRIES+1 fi done # Only run this if API server is operational if $SERVER_UP; then for browser in "$@"; do export TEST_BROWSER="$browser" echo -e "\n---------- $TEST_BROWSER test start ----------" npx dotenv cucumberjs spec/cucumber/features -- --compiler js:babel-register --require spec/cucumber/steps echo -e "----------- $TEST_BROWSER test end -----------\n" done else >&2 echo "Web server failed to start" fi # Terminate all processes within the same process group by sending a SIGTERM signal kill -15 0
<filename>formant_ros2_adapter/scripts/message_utils/utils.py<gh_stars>1-10 import re import importlib import array import json import numpy as np NUMPY_DTYPE_TO_BUILTIN_MAPPING = { np.uint8: int, np.uint16: int, np.uint32: int, np.uint64: int, np.int8: int, np.int16: int, np.int32: int, np.int64: int, np.float32: float, np.float64: float, np.bool: bool, } def get_message_type_from_string(message_type_string: str): """ Returns a ROS2 message type for the provided ROS2 message type string """ try: path = message_type_string.replace("/", ".").split(".") module_name = ".".join(path[:-1]) module = importlib.import_module(module_name) return getattr(module, path[-1]) except: print("Couldn't import ROS2 message type from string: ", message_type_string) return None def parse(m): if type(m) in [bool, str, int, float]: return m elif type(m) == bytes: return str(m) elif type(m) in NUMPY_DTYPE_TO_BUILTIN_MAPPING.keys(): return NUMPY_DTYPE_TO_BUILTIN_MAPPING[type(m)](m) elif type(m) in [list, array.array, np.ndarray]: return [parse(o) for o in m] else: return {k: parse(getattr(m, k)) for k in m._fields_and_field_types} def message_to_json(message) -> str: """ Converts any ROS2 message into a JSON string """ return json.dumps(parse(message)) rosMessagePathRegex = re.compile( r"^([a-zA-Z])([0-9a-zA-Z_])*(\[[0-9]+\])?(\.([a-zA-Z])([0-9a-zA-Z_])*(\[[0-9]+\])?)*" ) def get_message_path_value(message, messagePath: str): """ Returns the message value at the end of the provided message path """ if not rosMessagePathRegex.fullmatch(messagePath): raise ValueError("Invalid message path in configuration: " + messagePath) # parse the message path steps = [] for substring in messagePath.split("."): indexStart = None try: indexStart = substring.index("[") except ValueError: pass if indexStart: if indexStart == 0: steps.append(("indexing", substring)) else: steps.append(("attribute", substring[:indexStart])) steps.append(("indexing", substring[indexStart:])) else: steps.append(("attribute", substring)) # index based on the message path try: for step in steps: if step[0] == "attribute": message = getattr(message, step[1]) elif step[0] == "indexing": indices = [int(s[1:]) for s in step[1].split("]")] for index in indices: message = message[index] except (AttributeError, KeyError): return None return message
<reponame>Nijooke/create-react-app import React from 'react'; import logo from './logo.svg'; import styles from './styles'; const App: React.FC = () => { return ( <div css={styles.app}> <header css={styles.appHeader}> <img src={logo} css={styles.appLogo} alt="logo" /> <p> Edit <code>src/App.tsx</code> and save to reload. </p> <a css={styles.appLink} href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> </header> </div> ); }; export default App;
<reponame>CompilerLuke/TopLangCompiler<filename>TopLangCompiler/core/file.cpp // // file.cpp // TopLangCompiler // // Created by <NAME> on 22/09/2019. // Copyright © 2019 <NAME>. All rights reserved. // #include <stdio.h> #include "file.h" #include <limits.h> namespace top { namespace io { FILE* open(string src, FileMode mode) { const char* fmode = ""; if (mode == FileMode::Read) fmode = "rb"; if (mode == FileMode::Write) fmode = "wb"; char src_buffer[100]; to_cstr(src, src_buffer, 100); return fopen(src_buffer, fmode); } string read_file(FILE* file, Allocator allocator, void* allocator_data) { fseek(file, 0, SEEK_END); long fsize = ftell(file); fseek(file, 0, SEEK_SET); /* same as rewind(f); */ char* buffer = alloc<char>(allocator, allocator_data, fsize + 1); fread(buffer, 1, fsize, file); buffer[fsize] = '\0'; assert(fsize < INT_MAX); return { buffer, (unsigned int) fsize }; } void write_file(FILE* file, string src) { fwrite(src.data, 1, len(src), file); } void destroy(FILE* file) { fclose(file); } } }
<reponame>Fast1804/fastlib package org.fast1804.utils; /** * @program: fastlib * @description: json formatter * @author: hqs.pub * @create: 2020-04-19 21:10 **/ public class JsonHelper { }
public class MyClass { private int myField; public void SetMyField(int value) { myField = value; } } // Example MyClass myInstance = new MyClass(); myInstance.SetMyField(10); // myField in MyClass is now set to 10
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ggCircle = void 0; var ggCircle = { "viewBox": "0 0 1792 1792", "children": [{ "name": "path", "attribs": { "d": "M717 1354l271-271-279-279-88 88 192 191-96 96-279-279 279-279 40 40 87-87-127-128-454 454zM1075 1346l454-454-454-454-271 271 279 279 88-88-192-191 96-96 279 279-279 279-40-40-87 88zM1792 896q0 182-71 348t-191 286-286 191-348 71-348-71-286-191-191-286-71-348 71-348 191-286 286-191 348-71 348 71 286 191 191 286 71 348z" } }] }; exports.ggCircle = ggCircle;
#!/bin/bash # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. JAVA_VERSION="1.7" RED="\033[0;31m" GREEN="\033[0;32m" BLUE="\033[0;35m" ENDCOLOR="\033[0m" error() { echo -e "$RED""$*""$ENDCOLOR" exit 1 } success() { echo -e "$GREEN""$*""$ENDCOLOR" } info() { echo -e "$BLUE""$*""$ENDCOLOR" } PACKAGE_VERSION=$(cat package.json \ | grep version \ | head -1 \ | awk -F: '{ print $2 }' \ | sed 's/[",]//g' \ | tr -d '[[:space:]]') success "Preparing version $PACKAGE_VERSION" repo_root=$(pwd) rm -rf android ./gradlew :ReactAndroid:installArchives || error "Couldn't generate artifacts" success "Generated artifacts for Maven" npm install success "Killing any running packagers" lsof -i :8081 | grep LISTEN lsof -i :8081 | grep LISTEN | /usr/bin/awk '{print $2}' | xargs kill info "Start the packager in another terminal by running 'npm start' from the root" info "and then press any key." info "" read -n 1 ./gradlew :packages:rn-tester:android:app:installJscDebug || error "Couldn't build RNTester Android" info "Press any key to run RNTester in an already running Android emulator/device" info "" read -n 1 adb shell am start -n com.facebook.react.uiapp/.RNTesterActivity success "Installing CocoaPods dependencies" rm -rf packages/rn-tester/Pods (cd packages/rn-tester && pod install) info "Press any key to open the workspace in Xcode, then build and test manually." info "" read -n 1 open "packages/rn-tester/RNTesterPods.xcworkspace" info "When done testing RNTester app on iOS and Android press any key to continue." info "" read -n 1 success "Killing packager" lsof -i :8081 | grep LISTEN lsof -i :8081 | grep LISTEN | /usr/bin/awk '{print $2}' | xargs kill npm pack PACKAGE=$(pwd)/react-native-$PACKAGE_VERSION.tgz success "Package bundled ($PACKAGE)" node scripts/set-rn-template-version.js "file:$PACKAGE" success "React Native version changed in the template" project_name="RNTestProject" cd /tmp/ rm -rf "$project_name" node "$repo_root/cli.js" init "$project_name" --template "$repo_root" info "Double checking the versions in package.json are correct:" grep "\"react-native\": \".*react-native-$PACKAGE_VERSION.tgz\"" "/tmp/${project_name}/package.json" || error "Incorrect version number in /tmp/${project_name}/package.json" grep -E "com.facebook.react:react-native:\\+" "${project_name}/android/app/build.gradle" || error "Dependency in /tmp/${project_name}/android/app/build.gradle must be com.facebook.react:react-native:+" success "New sample project generated at /tmp/${project_name}" cd "/tmp/${project_name}" info "Test the following on Android:" info " - Disable Fast Refresh. It might be enabled from last time (the setting is stored on the device)" info " - Verify 'Reload JS' works" info "" info "Press any key to run the sample in Android emulator/device" info "" read -n 1 cd "/tmp/${project_name}" && npx react-native run-android info "Test the following on iOS:" info " - Disable Fast Refresh. It might be enabled from last time (the setting is stored on the device)" info " - Verify 'Reload JS' works" info " - Test Chrome debugger by adding breakpoints and reloading JS. We don't have tests for Chrome debugging." info " - Disable Chrome debugging." info " - Enable Fast Refresh, change a file (index.js) and save. The UI should refresh." info " - Disable Fast Refresh." info "" info "Press any key to open the project in Xcode" info "" read -n 1 open "/tmp/${project_name}/ios/${project_name}.xcworkspace" cd "$repo_root" info "Next steps:" info " - https://github.com/facebook/react-native/blob/master/Releases.md"
#!/bin/bash # -- vw daemon test # NAME='vw-daemon-test' export PATH="vowpalwabbit:../build/vowpalwabbit:${PATH}" # The VW under test VW=`which vw` MODEL=$NAME.model TRAINSET=$NAME.train PREDREF=$NAME.predref PREDOUT=$NAME.predict NETCAT_STATUS=$NAME.netcat-status PORT=54248 while [ $# -gt 0 ] do case "$1" in --foreground) Foreground="$1" ;; --json) JSON="$1 --chain_hash" ;; --port) PORT="$2" shift ;; --vw) VW="$2" shift ;; *) echo "$NAME: unknown argument $1" exit 1 ;; esac shift done # Test if the VW command is available ${VW} --version > /dev/null 2>&1 # -- make sure we can find vw first if [ $? -eq 0 ]; then : cool found vw at: $VW else echo "$NAME: can not find 'vw' in $PATH - sorry" exit 1 fi # -- and netcat NETCAT=`which netcat` if [ -x "$NETCAT" ]; then : cool found netcat at: $NETCAT else NETCAT=`which nc` if [ -x "$NETCAT" ]; then : "no netcat but found 'nc' at: $NETCAT" else echo "$NAME: can not find 'netcat' not 'nc' in $PATH - sorry" exit 1 fi fi # -- and pkill PKILL=`which pkill` if [ -x "$PKILL" ]; then : cool found pkill at: $PKILL else echo "$NAME: can not find 'pkill' in $PATH - sorry" exit 1 fi # A command (+pattern) that is unlikely to match anything but our own test DaemonCmd="$VW -t -i $MODEL --daemon $Foreground --num_children 1 --quiet --port $PORT $JSON" # libtool may wrap vw with '.libs/lt-vw' so we need to be flexible # on the exact process pattern we try to kill. DaemonPat=`echo $DaemonCmd | sed 's/^[^ ]*vw /.*vw /'` stop_daemon() { # Make sure we are not running. May ignore 'error' that we're not $PKILL -9 -f "$DaemonPat" 2>&1 | grep -q 'no process found' # relinquish CPU by forcing some context switches to be safe # (let existing vw daemon procs die) if echo "$DaemonPat" | grep -q -v -- --foreground; then wait else sleep 0.1 fi } start_daemon() { # echo starting daemon $DaemonCmd </dev/null >/dev/null & PID=$! # give it time to be ready if echo "$DaemonCmd" | grep -q -v -- --foreground; then wait; wait; wait else sleep 0.1 fi echo "$PID" } cleanup() { /bin/rm -f $MODEL $TRAINSET $PREDREF $PREDOUT $NETCAT_STATUS stop_daemon } # -- main cleanup txt_dataset() { # prepare training set cat > $TRAINSET <<EOF 0.55 1 '1| a 0.99 1 '2| b c EOF } json_dataset() { # prepare training set json cat > $TRAINSET <<EOF {"_label":{"Weight":1, "Label":0.55}, "_tag":"1", "a":true} {"_label":{"Weight":1, "Label":0.99}, "_tag":"2", "b":true, "c":true} EOF } if [ -n "$JSON" ]; then json_dataset else txt_dataset fi # prepare expected predict output cat > $PREDREF <<EOF 0.553585 1 0.733882 2 EOF # Train $VW -b 10 --quiet -d $TRAINSET -f $MODEL $JSON DaemonPid=`start_daemon` # Test --foreground argument PidsAreEqual=false for ProcessPid in $(pgrep -f "$DaemonPat" 2>&1) do if [ $DaemonPid -eq $ProcessPid ]; then PidsAreEqual=true fi done if [ $Foreground ]; then if ! $PidsAreEqual ; then echo "$NAME FAILED: --foreground, but vw has run in the background" stop_daemon exit 1 fi else if $PidsAreEqual ; then echo "$NAME FAILED: vw has not run in the background" stop_daemon exit 1 fi fi # Test on train-set # OpenBSD netcat quits immediately after stdin EOF # nc.traditional does not, so let's use -w 1 which will silently close the connection if the connection # or stdin are silent for more than 1 second DELAY_OPT="-w 1" # In case the VW command run immediately before is not yet ready to accept connections wait for a little bit sleep 1 $NETCAT $DELAY_OPT localhost $PORT < $TRAINSET > $PREDOUT $PKILL -9 $NETCAT # We should ignore small (< $Epsilon) floating-point differences (fuzzy compare) diff <(cut -c-5 $PREDREF) <(cut -c-5 $PREDOUT) case $? in 0) echo "$NAME: OK" cleanup exit 0 ;; 1) echo "$NAME FAILED: see $PREDREF vs $PREDOUT" stop_daemon exit 1 ;; *) echo "$NAME: diff failed - something is fishy" stop_daemon exit 2 ;; esac
<filename>Reference/qpc/html/search/files_7.js var searchData= [ ['options_2elnt_968',['options.lnt',['../options_8lnt.html',1,'']]] ];
<filename>common/management/commands/get_allegation_date_only.py from django.core.management.base import BaseCommand from common.models import Allegation class Command(BaseCommand): help = 'Get date only from incident date' def handle(self, *args, **options): for allegation in Allegation.objects.all()\ .filter(incident_date_only=None): if allegation.incident_date: allegation.incident_date_only = allegation.incident_date.date() allegation.save()
#!/bin/bash find . -name "*.java" -type f -exec wc -l {} \; | awk '{total += $1}END{print total}'
import { LoadingIndicator, Mode } from "@nstudio/nativescript-loading-indicator"; class Dialogs { private loader: LoadingIndicator; private loaderOptions; constructor() { this.loader = new LoadingIndicator(); this.loaderOptions = { message: 'Loading...', progress: 0.99, margin: 10, dimBackground: true, color: '#981e32', // color of indicator and labels // background box around indicator // hideBezel will override this if true backgroundColor: 'yellow', userInteractionEnabled: false, // default true. Set false so that the touches will fall through it. hideBezel: true, // default false, can hide the surrounding bezel mode: Mode.Indeterminate, // see options below } } public showLoader(): void { this.loader.show(this.loaderOptions); } public hideLoader(): void { this.loader.hide(); } }; const dialogs = new Dialogs(); export default dialogs;
package cmd import ( "github.com/spf13/cobra" ) var ( app string mode string ) var apiHttpCmd = &cobra.Command{ Use: "api", Short: "api", Long: "api server running on the given app and mode", Run: func(cmd *cobra.Command, args []string) { RunApi() }, } var adminHttpCmd = &cobra.Command{ Use: "admin", Short: "admin", Long: "admin server running on the given app and mode", Run: func(cmd *cobra.Command, args []string) { RunAdmin() }, } func init() { rootCmd.AddCommand(apiHttpCmd, adminHttpCmd) apiHttpCmd.Flags().StringVar(&app, "app", "", "chioce app") apiHttpCmd.Flags().StringVar(&mode, "mode", "", "chioce mode") apiHttpCmd.MarkFlagRequired("app") apiHttpCmd.MarkFlagRequired("mode") adminHttpCmd.Flags().StringVar(&app, "app", "", "chioce app") adminHttpCmd.Flags().StringVar(&mode, "mode", "", "chioce mode") adminHttpCmd.MarkFlagRequired("app") adminHttpCmd.MarkFlagRequired("mode") }
sudo apt update -y sudo apt install libpcap-dev openvswitch-switch -y sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -q build-essential python3-dev libpcap-dev python3-pip libnetfilter-queue-dev iptables-persistent netfilter-persistent sudo ovs-vsctl add-br br sudo ovs-ofctl del-flows br pip3 install -U pip pip3 install -U setuptools sudo /usr/bin/python3 -m pip install pandas pyyaml h5py flask pypcap kaitaistruct scapy NetfilterQueue sudo /usr/bin/python3 -m pip install --extra-index-url https://google-coral.github.io/py-repo/ tflite_runtime echo "net.ipv4.ip_forward=1" | sudo tee -a /etc/sysctl.conf sudo sysctl -p sudo iptables -A FORWARD -j NFQUEUE --queue-num 0 sudo netfilter-persistent save sudo netfilter-persistent start sudo cp ips.service /etc/systemd/system/ sudo systemctl enable ips sudo systemctl start ips
#!/bin/bash test_run_id="${1:-NOT_SET}" test_run_type="ingest-replica" feature_tag="@ingest-replica" mongo_import_key="NOT_SET" number_of_topics=3 if [[ "${test_run_id}" == "NOT_SET" ]]; then echo "Defaulting test_run_id to 1" test_run_id=1 fi ./run-dev-by-tags.sh "${test_run_id}" "${test_run_type}" "${feature_tag}" "${mongo_import_key}" "${number_of_topics}"
#!/bin/bash set -e if [ "${DEBUG}" = "true" ]; then set -x fi shopt -s extglob args=("$@") server=$HOME/server.sh csgo_dir=$HOME/server/csgo sourcemod_plugins_dir=$csgo_dir/addons/sourcemod/plugins mmsource_exact_version="${METAMOD_VERSION-"1.11.0"}" mmsource_version=$(echo ${mmsource_exact_version} | cut -f1-2 -d '.') mmsource_url="https://mms.alliedmods.net/mmsdrop/${mmsource_version}/mmsource-${mmsource_exact_version}-git${METAMOD_BUILD-1145}-linux.tar.gz" sourcemod_exact_version="${SOURCEMOD_VERSION-"1.10.0"}" sourcemod_version=$(echo ${sourcemod_exact_version} | cut -f1-2 -d '.') sourcemod_url="https://sm.alliedmods.net/smdrop/${sourcemod_version}/sourcemod-${sourcemod_exact_version}-git${SOURCEMOD_BUILD-6536}-linux.tar.gz" install_or_update_mod() { cd $csgo_dir if [ ! -f "$1" ]; then touch $1 fi installed=$(<$1) if [ "${installed}" = "$2" ]; then return fi if [ -z "${installed}" ]; then echo "> Installing mod ${1} from ${2} ..." else echo "> Updating mod ${1} from ${2} ..." fi wget -qO- $2 | tar zxf - echo $2 > $1 echo '> Done' } install_or_update_mods() { install_or_update_mod 'mmsource' $mmsource_url install_or_update_mod 'sourcemod' $sourcemod_url } install_or_update_plugin() { cd $csgo_dir if [ ! -f "${args[1]}" ]; then touch ${args[1]} fi installed=$(<${args[1]}) if [ "${installed}" = "${args[2]}" ]; then return fi if [ -z "${installed}" ]; then echo "> Installing SourceMod plugin ${args[1]} from ${args[2]} ..." else echo "> Updating SourceMod plugin ${args[1]} from ${args[2]} ..." fi wget -q -O plugin.zip ${args[2]} if [ -z "${installed}" ]; then unzip -qn plugin.zip else unzip -qo plugin.zip fi rm plugin.zip echo ${args[2]} > ${args[1]} echo '> Done' } manage_plugins() { echo '> Managing SourceMod plugins ...' cd $sourcemod_plugins_dir if [ "${SOURCEMOD_PLUGINS_DISABLED}" = "*" ]; then for plugin in *.smx; do if [ -f "${plugin}" ]; then echo "> Disabling ${plugin}" mv $plugin disabled fi done elif [ -n "${SOURCEMOD_PLUGINS_DISABLED}" ]; then for plugin in $(echo $SOURCEMOD_PLUGINS_DISABLED | sed "s/,/ /g"); do if [ -f "${plugin}.smx" ]; then echo "> Disabling ${plugin}.smx" mv "${plugin}.smx" disabled fi done fi cd disabled if [ "${SOURCEMOD_PLUGINS_ENABLED}" = "*" ]; then for plugin in *.smx; do if [ -f "${plugin}" ]; then echo "> Enabling ${plugin}" mv $plugin .. fi done elif [ -n "${SOURCEMOD_PLUGINS_ENABLED}" ]; then for plugin in $(echo $SOURCEMOD_PLUGINS_ENABLED | sed "s/,/ /g"); do if [ -f "${plugin}.smx" ]; then echo "> Enabling ${plugin}.smx" mv "${plugin}.smx" .. fi done fi echo '> Done' } manage_admins() { if [ -n "${SOURCEMOD_ADMINS}" ]; then admins_simple="${csgo_dir}/addons/sourcemod/configs/admins_simple.ini" if [ -f "${admins_simple}" ]; then > $admins_simple for steamid in $(echo $SOURCEMOD_ADMINS | sed "s/,/ /g"); do echo "\"$steamid\" \"z\"" >> $admins_simple done fi fi } if [ ! -z $1 ]; then $1 else $server install_or_update install_or_update_mods manage_plugins manage_admins $server should_add_server_configs $server should_disable_bots $server sync_custom_files exec $server start fi
<reponame>PinoEire/archi /** * This program and the accompanying materials * are made available under the terms of the License * which accompanies this distribution in the file LICENSE.txt */ package com.archimatetool.hammer.validation.issues; import org.eclipse.swt.graphics.Image; import com.archimatetool.hammer.IHammerImages; /** * Issue Type * * @author <NAME> */ public class OKType extends AbstractIssueType { public OKType() { super(Messages.OKType_0, Messages.OKType_1, Messages.OKType_2, null); } @Override public Image getImage() { return IHammerImages.ImageFactory.getImage(IHammerImages.ICON_OK); } }
<gh_stars>1-10 /* * Copyright (C) 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.cloud.dataflow.sdk.values; import com.google.cloud.dataflow.sdk.Pipeline; import java.util.Collection; /** * The abstract interface of things that might be input to a * {@link com.google.cloud.dataflow.sdk.transforms.PTransform}. */ public interface PInput { /** * Returns the owning Pipeline of this PInput. * * @throws IllegalStateException if the owning Pipeline hasn't been * set yet */ public Pipeline getPipeline(); /** * Expands this PInput into a list of its component input PValues. * * <p> A PValue expands to itself. * * <p> A tuple or list of PValues (e.g., * PCollectionTuple, and PCollectionList) expands to its component * PValues. * * <p> Not intended to be invoked directly by user code. */ public Collection<? extends PValue> expand(); /** * <p> After building, finalizes this PInput to make it ready for * being used as an input to a PTransform. * * <p> Automatically invoked whenever {@code apply()} is invoked on * this PInput, so users do not normally call this explicitly. */ public void finishSpecifying(); }
yum install unit unit-php
#!/bin/sh # # This script launches jgmenu in short-lived mode. # It can be run with a parallel with a long-running invocation of jgmenu # config_file=$(mktemp) trap "rm -f ${config_file}" EXIT cat <<'EOF' >${config_file} tint2_look = 0 terminal_exec = st #columns = 1 menu_margin_x = 5 menu_margin_y = 25 #menu_width = 200 #menu_height_min = 0 #menu_height_max = 0 menu_height_mode = static menu_padding_top = 5 menu_padding_right = 5 menu_padding_bottom = 5 menu_padding_left = 5 menu_radius = 1 menu_halign = right menu_valign = bottom font = Iosevka Nerd Font 10 color_menu_bg = #1b2b34 90 color_menu_border = #1b2b34 90 color_norm_bg = #1b2b34 0 color_norm_fg = #c0c5ce 100 color_sel_bg = #c0c5ce 85 color_sel_fg = #1b2b34 85 color_sel_border = #1b2b34 0 color_sep_fg = #c0c5ce 0 EOF ( printf "%b\n" " Logout,i3-msg exit,logout" printf "%b\n" " Poweroff,systemctl -i poweroff,shutdown" printf "%b\n" " Reboot,systemctl -i reboot,reboot" printf "%b\n" " Sleep,systemctl -i suspend,suspend" ) | jgmenu --simple --config-file=${config_file}
<filename>src/util/Functions/roundRect.ts export function roundRect(ctx: CanvasRenderingContext2D, x: number, y: number, width: number, height: number, radius: any, fill?: boolean, stroke?: boolean, fillstyle?: string) { if (typeof stroke === 'undefined') { stroke = true; } if (typeof radius === 'undefined') { radius = 5; } if (typeof radius === 'number') { radius = {tl: radius, tr: radius, br: radius, bl: radius}; } else { var defaultRadius = {tl: 0, tr: 0, br: 0, bl: 0}; for (var side in defaultRadius) { radius[side] = radius[side] || defaultRadius[side]; } } ctx.beginPath(); ctx.moveTo(x + radius.tl, y); ctx.lineTo(x + width - radius.tr, y); ctx.quadraticCurveTo(x + width, y, x + width, y + radius.tr); ctx.lineTo(x + width, y + height - radius.br); ctx.quadraticCurveTo(x + width, y + height, x + width - radius.br, y + height); ctx.lineTo(x + radius.bl, y + height); ctx.quadraticCurveTo(x, y + height, x, y + height - radius.bl); ctx.lineTo(x, y + radius.tl); ctx.quadraticCurveTo(x, y, x + radius.tl, y); ctx.closePath(); if (fill) { ctx.fillStyle = fillstyle; ctx.fill(); } if (stroke) { ctx.stroke(); } }
package math; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * * @author exponential-e * 백준 2487번: 섞기 수열 * * @see https://www.acmicpc.net/problem/2487 * */ public class Boj2487 { private static int[] elem; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(br.readLine()); int[] seq = new int[N + 1]; elem = new int[N + 1]; StringTokenizer st = new StringTokenizer(br.readLine()); for(int i = 1; i <= N; i++) { seq[i] = Integer.parseInt(st.nextToken()); } System.out.println(shake(N, seq)); } private static long shake(int n, int[] seq) { long result = 1; for(int i = 1; i <= n; i++) { if(elem[i] != 0) continue; int depth = recursion(seq, i, 0); // find cycle result = result * depth / gcd(result, depth); // lcm } return result; } private static int recursion(int[] s, int current, int count){ if(elem[current] != 0) return count; elem[current] = 1; return recursion(s, s[current], count + 1); } private static long gcd(long a, long b) { if(b == 0) return a; return gcd(b, a % b); } }
<html> <head> <title>Form Example</title> </head> <body> <h2>Form Example</h2> <form action="" method="post"> <label>Name</label><input type="text" name="name" required/> <br/><br/> <label>Email</label><input type="text" name="email" required/> <br/><br/> <input type="submit" value="Submit"/> </form> </body> </html>
import torch def draw_concat(Gs, Zs, reals, NoiseWeight, _, mode, kernel_size, channels, device, padder, G_num_layer, mode): # Implementation of the draw_concat function # (Assuming the implementation of draw_concat is provided elsewhere) # Placeholder for the actual implementation of draw_concat # Replace the following line with the actual implementation result = None return result def process_noise(Gs, Zs, reals, NoiseWeight, _, mode, kernel_size, channels, device, padder, G_num_layer): if mode == 'rec': noise_3 = draw_concat(Gs, Zs, reals, NoiseWeight, _, 'rec', kernel_size, channels, device, padder, G_num_layer, mode) RMSE = torch.sqrt(torch.nn.functional.mse_loss(reals, noise_3)) noise_weight = NoiseWeight * RMSE noise_3 = padder(noise_3) else: if mode == 'f': noise_3 = padder(draw_concat(Gs, Zs, reals, NoiseWeight, _, 'rand', kernel_size, channels, device, padder, G_num_layer, mode)) return noise_3, noise_weight
<reponame>rdbox-intec/r2s2_for_rostest #!/usr/bin/env python import unittest import rostest import rospy import os import sys import types import functools import json import re import urllib from typing import Any, Callable from swagger_client.configuration import Configuration from swagger_client.api_client import ApiClient from swagger_client.api.job_api import JobApi from swagger_client.api.internal_api import InternalApi from swagger_server.models.job import Job from swagger_server.models.record_list import RecordList from swagger_server.models.record import Record from swagger_server.models.api_response import ApiResponse class TestContainer(unittest.TestCase): """Now create your empty TestClass. Automatically add TestCase to this TestClass. """ def __init__(self, *args): super(self.__class__, self).__init__(*args) class ApiResult(object): def __init__(self, result: str): try: self.d = json.loads(result) except Exception: rospy.loginfo('Not comming result record.') self.d = {} def get_by_dot(self, keys: str) -> Any: try: return self.__get(self.d, keys) except KeyError: rospy.logwarn('KeyError: {}'.format(keys)) return None def __get(self, d: dict, keys: str) -> Any: if "." in keys: key, rest = keys.split(".", 1) return self.__get(d[key], rest) else: return d[keys] class ApiRecord(object): def __init__(self, record_list: RecordList): if len(record_list) != 1: raise ValueError('The length of the RecordList must be 1.') self.record = Record.from_dict(record_list[0]) self.result = ApiResult(self.record.result) def is_done(self) -> bool: return self.record.status.strip() == 'DONE' def get_result_by(self, keys: str) -> Any: return self.result.get_by_dot(keys) class ApiR2S2Client(object): def __init__(self, url: str, user: str, pswd: str, cert: str = None): # noqa: E501 self.recept_id = -1 self.conf = self.__build_config(url, user, pswd, cert) self.client = ApiClient(self.conf, header_name="Authorization", header_value=self.conf.get_basic_auth_token()) # https://github.com/swagger-api/swagger-codegen/issues/6503 self.client.rest_client.pool_manager.connection_pool_kw['retries'] = 10 self.job_api = JobApi(self.client) self.internal_api = InternalApi(self.client) def push_job(self, job: Job) -> ApiResponse: # tuple(data, status, headers) data, status, _ = self.job_api.put_job_with_http_info(job) if status != 200: raise RuntimeError('Failed to put in a job.') else: self.recept_id = data.id return data def search_job(self) -> ApiRecord: if self.recept_id < 0: raise ValueError('You need submit a JOB.') # tuple(data, status, headers) data, status, _ = self.job_api.find_job_with_http_info( id=self.recept_id) if status != 200: raise RuntimeError('Failed to find the Job.') else: return ApiRecord(RecordList.from_dict(data)) def __build_config(self, url: str, user: str, pswd: str, cert: str = None) -> Configuration: # noqa: E501 configuration = Configuration() configuration.host = url configuration.username = user configuration.password = <PASSWORD> if cert is not None: configuration.ssl_ca_cert = cert configuration.assert_hostname = False return configuration class TestCases(list): class TestCase(object): def __init__(self, target: str, method_name: str, expct, description=None): # noqa: E501 self.target = target self.method_name = method_name self.expct = expct if description is None: self.description = self.__make_template_description() else: self.description = self.__format_description(description) def __str__(self): return 'TestCase(target: {}, '\ 'method: {}, '\ 'expect: {}, '\ 'description: {})'.format(self.target, self.method_name, self.expct, self.description) def get_target(self) -> str: return self.target def get_description(self) -> str: return self.description def get_expect(self): return self.expct def get_method_name(self) -> str: return self.method_name def get_formal_method_name(self) -> str: return 'assert' + self.method_name def __make_template_description(self) -> str: return 'test_{}'.format('_'.join([str(self.target), str(self.method_name), re.sub(re.compile("[!-/:-@[-`{-~]"), '', str(self.expct))])) # noqa: E501 def __format_description(self, description: str) -> str: return 'test_{}'.format('_'.join(re.sub(re.compile("[!-/:-@[-`{-~]"), '', str(description)).split(' '))) # noqa: E501 def __init__(self, raw_params_tests: list): for test in raw_params_tests: test_case = TestCases.TestCase(test.get('target'), test.get('method'), test.get('expect'), test.get('description', None)) self.append(test_case) def __str__(self): ret = '' if isinstance(self, (list, tuple)): ret = ', '.join(str(elem) for elem in self) else: pass # handle other types here return 'TestCases({})'.format(ret) class TestBuilder(object): def __init__(self, test_cases: TestCases, record: ApiRecord): # noqa: E501 self.test_cases = test_cases self.record = record def add_test_cases_to_class(self, target_class): for test_case in self.test_cases: method_name = test_case.get_formal_method_name() target = self.record.get_result_by(test_case.get_target()) expct = test_case.get_expect() test_func = self.assemble_one_method(method_name, target, expct) test_name = test_case.get_description() setattr(target_class, test_name, test_func) def assemble_one_method(self, method_name: str, target: Any, expct: Any): def frame_method(self): do_something = getattr(self, method_name) do_something(target, expct) method = self.__copy_func(frame_method) return method def __copy_func(self, f: Callable): """Based on http://stackoverflow.com/a/6528148/190597 (<NAME>) """ g = types.FunctionType(f.__code__, f.__globals__, name=f.__name__, argdefs=f.__defaults__, closure=f.__closure__) g = functools.update_wrapper(g, f) g.__kwdefaults__ = f.__kwdefaults__ return g class IntegrationTest(object): def __init__(self, pcs: dict = None, tests: list = None): # Node if pcs is None and tests is None: rospy.init_node('integrationtest') # Param self.raw_params_pcs = self.__get_preconditions(pcs) self.raw_params_tests = self.__get_tests(tests) IntegrationTest.validate_cert_url(self.raw_params_pcs) self.test_cases = TestCases(self.raw_params_tests) self.apis_client = ApiR2S2Client( IntegrationTest.get_url(self.raw_params_pcs), IntegrationTest.get_user(), IntegrationTest.get_pass(), IntegrationTest.get_cert()) def run(self): # push job = self.__build_job_instance() self.apis_client.push_job(job) # Loop record = ApiRecord(RecordList.from_dict([{}])) rate = rospy.Rate(0.2) start = rospy.Time.now().to_sec() while not rospy.is_shutdown() and self.__within_the_time_limit(start): record = self.apis_client.search_job() if record.is_done(): break print('wait...') rate.sleep() # Test if self.__within_the_time_limit(start): if record.is_done(): self.__exec_rostest_success(record) else: self.__exec_rostest_failure(record) else: self.__exec_rostest_timeout(record) def __within_the_time_limit(self, start: float) -> int: limit = self.raw_params_pcs['timeout_sec'] end = rospy.Time.now().to_sec() return end - start <= limit def __exec_rostest_success(self, record: ApiRecord): tb = TestBuilder(self.test_cases, record) tb.add_test_cases_to_class(TestContainer) rostest.rosrun("r2s2_for_rostest", 'integrationtest', TestContainer) def __exec_rostest_failure(self, record: ApiRecord): rospy.logerr('The status that returned incorrect result!!!!!!!!!!!') tb = TestBuilder(self.test_cases, record) tb.add_test_cases_to_class(TestContainer) rostest.rosrun("r2s2_for_rostest", 'integrationtest', TestContainer) raise SyntaxError() def __exec_rostest_timeout(self, record: ApiRecord): rospy.logerr('This TESTS has timed out!!!!!!!!!!!') tb = TestBuilder(self.test_cases, record) tb.add_test_cases_to_class(TestContainer) rostest.rosrun("r2s2_for_rostest", 'integrationtest', TestContainer) raise TimeoutError() def __build_job_instance(self) -> Job: job = Job.from_dict(self.raw_params_pcs) job.id = -1 job.mid = -1 job.unique_name = os.getenv('CI_JOB_STAGE', 'main') job.uid = IntegrationTest.get_user() return job def __get_preconditions(self, v: dict = None) -> dict: if v is None: return rospy.get_param('~preconditions', {}) else: return v def __get_tests(self, v: list = None) -> list: if v is None: return rospy.get_param('~tests', []) else: return v @classmethod def get_user(cls) -> str: return os.environ['R2S2_USER'] @classmethod def get_pass(cls) -> str: return os.environ['R2S2_PASS'] @classmethod def get_cert(cls) -> str: return os.environ.get('R2S2_CERT', None) @classmethod def get_url(cls, pcs: dict) -> str: return os.environ.get('R2S2_URL', pcs.get('reception_url', None)) @classmethod def validate_cert_url(cls, pcs: dict): o = urllib.parse.urlparse(IntegrationTest.get_url(pcs)) if o.scheme == 'http': if IntegrationTest.get_cert() is not None: raise AssertionError('When communicating with' 'the http protocol, ' 'do not specify R2S2_CERT.') elif o.scheme == 'https': if IntegrationTest.get_cert() is None: raise AssertionError('When communicating with' 'the https protocol, ' 'specify R2S2_CERT.') else: raise AssertionError('Invalid protocol') def main(pcs: dict = None, tests: list = None): # Validate try: IntegrationTest.get_user() IntegrationTest.get_pass() except Exception: import traceback rospy.logerr(traceback.format_exc()) rospy.logerr('Please set the environment variables correctly.') rospy.logerr('R2S2_USER, R2S2_PASS, and (R2S2_URL, R2S2_CERT)') sys.exit(1) # Main processing try: test_master = IntegrationTest(pcs, tests) test_master.run() except Exception: import traceback rospy.logerr(traceback.format_exc()) rospy.logerr('An error has occurred during processing.') sys.exit(2) return True if __name__ == '__main__': main() # Successful sys.exit(0)
student_scores <- read.csv('student_scores.csv') # Compute the summary statistic summary_statistic <- summary(student_scores) # Display the result print(summary_statistic)
#!/usr/bin/env bash if [ -z "$KUBEVIRTCI_PATH" ]; then KUBEVIRTCI_PATH="$( cd "$(dirname "$BASH_SOURCE[0]")/../" echo "$(pwd)/" )" fi if [ -z "$KUBEVIRTCI_CONFIG_PATH" ]; then KUBEVIRTCI_CONFIG_PATH="$( cd "$(dirname "$BASH_SOURCE[0]")/../../" echo "$(pwd)/_ci-configs" )" fi KUBEVIRT_PROVIDER=${KUBEVIRT_PROVIDER:-k8s-1.13.3} KUBEVIRT_NUM_NODES=${KUBEVIRT_NUM_NODES:-1} KUBEVIRT_MEMORY_SIZE=${KUBEVIRT_MEMORY_SIZE:-5120M} KUBEVIRT_NUM_SECONDARY_NICS=${KUBEVIRT_NUM_NODES:-0} # If on a developer setup, expose ocp on 8443, so that the openshift web console can be used (the port is important because of auth redirects) if [ -z "${JOB_NAME}" ]; then KUBEVIRT_PROVIDER_EXTRA_ARGS="${KUBEVIRT_PROVIDER_EXTRA_ARGS} --ocp-port 8443" fi #If run on jenkins, let us create isolated environments based on the job and # the executor number provider_prefix=${JOB_NAME:-${KUBEVIRT_PROVIDER}}${EXECUTOR_NUMBER} job_prefix=${JOB_NAME:-kubevirt}${EXECUTOR_NUMBER} mkdir -p $KUBEVIRTCI_CONFIG_PATH/$KUBEVIRT_PROVIDER
import isEmpty from "lodash/isEmpty" import brim, {BrimWorkspace} from "../../brim" import {Thunk} from "../../state/types" import {Workspace} from "../../state/Workspaces/types" export const buildWorkspace = ( ws: Partial<Workspace> ): Thunk<Promise<BrimWorkspace>> => async ( dispatch, getState, {createZealot} ) => { if (!ws.host || !ws.port || !ws.id || !ws.name) throw new Error("must provide host, port, id, and name to build workspace") const zealot = createZealot(brim.workspace(ws as Workspace).getAddress()) const workspace = {...ws} // check version to test that zqd is available, retrieve/update version while doing so const {version} = await zealot.version() workspace.version = version // first time connection, need to determine auth type and set authData accordingly if (isEmpty(workspace.authType)) { const authMethod = await zealot.authMethod() if (authMethod.kind === "auth0") { const {client_id: clientId, domain} = authMethod.auth0 workspace.authType = "auth0" workspace.authData = { clientId, domain } } else { workspace.authType = "none" } } return brim.workspace(workspace as Workspace) }
import java.util.HashMap; import java.util.Map; public class LocalizationHelper { public static Map<String, String> getLocalizedUIElements(String languageCode) { Map<String, String> uiElements = new HashMap<>(); if (languageCode.equals("en")) { uiElements.put("ok", "OK"); uiElements.put("done", "Done"); uiElements.put("cancel", "Cancel"); uiElements.put("save", "Save"); uiElements.put("processing", "Processing..."); uiElements.put("trim", "Trim"); uiElements.put("cover", "Cover"); uiElements.put("albumsTitle", "Albums"); } else if (languageCode.equals("zh")) { uiElements.put("ok", "好的"); uiElements.put("done", "完成"); uiElements.put("cancel", "取消"); uiElements.put("save", "保存"); uiElements.put("processing", "处理中.."); uiElements.put("trim", "剪辑"); uiElements.put("cover", "封面"); uiElements.put("albumsTitle", "相簿"); } else { // Return English UI elements for any other language code uiElements.put("ok", "OK"); uiElements.put("done", "Done"); uiElements.put("cancel", "Cancel"); uiElements.put("save", "Save"); uiElements.put("processing", "Processing..."); uiElements.put("trim", "Trim"); uiElements.put("cover", "Cover"); uiElements.put("albumsTitle", "Albums"); } return uiElements; } public static void main(String[] args) { // Example usage Map<String, String> englishUI = getLocalizedUIElements("en"); System.out.println("English UI elements: " + englishUI); Map<String, String> chineseUI = getLocalizedUIElements("zh"); System.out.println("Chinese UI elements: " + chineseUI); } }
<filename>node_modules/@angular/compiler/src/view_compiler/view_compiler.d.ts import { CompileDirectiveMetadata, CompilePipeSummary } from '../compile_metadata'; import { CompileReflector } from '../compile_reflector'; import { CompilerConfig } from '../config'; import * as o from '../output/output_ast'; import { ElementSchemaRegistry } from '../schema/element_schema_registry'; import { TemplateAst } from '../template_parser/template_ast'; import { OutputContext } from '../util'; export declare class ViewCompileResult { viewClassVar: string; rendererTypeVar: string; constructor(viewClassVar: string, rendererTypeVar: string); } export declare class ViewCompiler { private _config; private _reflector; private _schemaRegistry; constructor(_config: CompilerConfig, _reflector: CompileReflector, _schemaRegistry: ElementSchemaRegistry); compileComponent(outputCtx: OutputContext, component: CompileDirectiveMetadata, template: TemplateAst[], styles: o.Expression, usedPipes: CompilePipeSummary[]): ViewCompileResult; }
/* eslint no-var: 0 */ /* eslint babel/object-shorthand: 0 */ // Karma configuration require('coffee-script/register'); var webpackConfig = require('./webpack/test.js'); const ibrik = require('ibrik'); delete webpackConfig.entry; module.exports = function (config) { config.set({ plugins: [ // fraworks 'karma-mocha', 'karma-chai', 'karma-chai-sinon', 'karma-phantomjs-shim', // environment 'karma-webpack', // launchers 'karma-chrome-launcher', 'karma-phantomjs-launcher', // reporters 'karma-notify-reporter', 'karma-nyan-reporter', 'karma-coverage', ], basePath: '', frameworks: ['mocha', 'chai', 'chai-sinon', 'phantomjs-shim'], // list of files / patterns to load in the browser files: [ {pattern: 'node_modules/babel-polyfill/dist/polyfill.js', included: false}, {pattern: 'app/scripts/**/__test__/*.js'}, {pattern: 'app/scripts/**/*.js', included: false}, ], exclude: [ 'app/scripts/main.js', ], preprocessors: { '**/__test__/*.js': ['webpack'], }, client: { mocha: { reporter: 'html', }, }, reporters: ['notify', 'nyan'], // reporters: ['notify', 'nyan', 'coverage'], coverageReporter: { instrumenters: {ibrik: ibrik}, type: 'text', includeAllSources: true, instrumenter: { '**/*.coffee': 'ibrik', }, }, notifyReporter: { reportEachFailure: true, reportSuccess: false, }, webpack: webpackConfig, webpackMiddleware: { stats: { colors: true, }, }, port: 9876, colors: true, // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_ERROR, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, browsers: ['PhantomJS'], singleRun: false, }); };
#!/bin/bash SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" . ${SCRIPT_DIR}/common.inc install_nightly() { if [[ "$ARG1" = "nightly" ]]; then return 0 else return 1 fi } get_swift() { local VER=$1 local DIR=swift-${VER} if [[ ! -d ${DIR} ]]; then mkdir ${DIR} pushd ${DIR} fetch https://swift.org/builds/swift-${VER}-release/ubuntu1604/swift-${VER}-RELEASE/swift-${VER}-RELEASE-ubuntu16.04.tar.gz | tar zxf - --strip-components 1 # work around insane installation issue chmod og+r ./usr/lib/swift/CoreFoundation/* popd fi } get_swift 3.1.1 get_swift 4.0.2 get_swift 4.0.3 get_swift 4.1 get_swift 4.1.1 get_swift 4.1.2 get_swift 4.2
import { getList, getClassify, ShanChuShangPin, HuoQuShangPin, XiuGaiShangPin } from '@/api/table' import { getToken, setToken, removeToken } from '@/utils/auth' import { resetRouter } from '@/router' const state = { toekn: getToken(), ShopList: [], } const mutations = { SET_LIST: (state, data) => { state.ShopList = data } } const actions = { // 获取所有商品列表 getList({ commit }, params) { return new Promise((resolve, reject) => { getList(params).then(res => { resolve(res) }).catch(err => { reject(err) }) }) }, // 获取所有商品分类 getClassify({ commit },query) { return new Promise((resolve, reject) => { getClassify(query).then(res => { resolve(res) }).catch(err => { reject(err) }) }) }, // 删除商品 ShanChuShangPin({ commit }, commodityId) { return new Promise((resolve, reject) => { ShanChuShangPin(commodityId).then(res => { resolve(res) }).catch(err => { reject(err) }) }) }, // 根据ID获取商品 HuoQuShangPin({ commit }, commodityId) { return new Promise((resolve, reject) => { HuoQuShangPin(commodityId).then(res => { resolve(res) }).catch(err => { reject(err) }) }) }, // 修改商品信息 XiuGaiShangPin({ commit }, data) { return new Promise((resolve, reject) => { XiuGaiShangPin(data).then(res => { resolve(res) }).catch(err => { reject(err) }) }) } } export default { namespaced: true, state, mutations, actions }
/usr/bin/gcc -c -o vars.o vars.c /usr/bin/yasm -f elf -m amd64 -o vars-addon.o vars-addon.asm /usr/bin/gcc -o vars vars-addon.o vars.o /usr/bin/strip vars /usr/bin/upx -q -9 vars
#!/usr/bin/env bash mongod --config mongod_dev.conf
#include <bits/stdc++.h> using namespace std; class Solution { public: bool isLongPressedName(string name, string typed) { if(name==typed) return true; return false; } }; int main() { return 0; }
#!/usr/bin/env bash ##################################################################### # FUNCTIONS ##################################################################### function cleanDirectory() { if [ ! -z "$1" ]; then if [ -d $1 ]; then rm -rf -- $1 fi mkdir $1 fi } ##################################################################### # PREPARATION ##################################################################### TARGET="Run-All-Tests" SKIP_BUILDING_CAKE=0 SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) SCRIPT=$SCRIPT_DIR/build.cake TOOLS_DIR=$SCRIPT_DIR/tools NUGET_EXE=$TOOLS_DIR/nuget.exe NUGET_URL="https://dist.nuget.org/win-x86-commandline/latest/nuget.exe" # Parse arguments. for i in "$@"; do case $1 in -t|--target) TARGET="$2"; shift ;; -s|--skipbuildingcake) SKIP_BUILDING_CAKE=1 ;; esac shift done # Make sure the tools folder exist. if [ ! -d $TOOLS_DIR ]; then mkdir $TOOLS_DIR fi # Download NuGet if it does not exist. if [ ! -f $NUGET_EXE ]; then echo "Downloading NuGet..." curl -Lsfo $NUGET_EXE $NUGET_URL if [ $? -ne 0 ]; then echo "An error occured while downloading nuget.exe." exit 1 fi fi ##################################################################### # BUILD CAKE ##################################################################### ROOT_DIR=$SCRIPT_DIR/../.. ARTIFACTS_DIR=$ROOT_DIR/artifacts # Build Cake. if [ ${SKIP_BUILDING_CAKE} -eq 0 ]; then $(cleanDirectory $ARTIFACTS_DIR) pushd $ROOT_DIR >/dev/null echo "Building Cake..." ./build.sh --target Copy-Files >/dev/null popd >/dev/null fi # Get the built Cake path. BUILT_CAKE_DIR=$(dirname $(find $ARTIFACTS_DIR -name 'Cake.exe')) if [ ! -d $BUILT_CAKE_DIR ]; then echo "Could not locate built Cake." exit 1 fi # Get the local Cake path. CAKE_DIR=$TOOLS_DIR/Cake CAKE_EXE=$CAKE_DIR/Cake.exe # Clean the local Cake path. if [ ${SKIP_BUILDING_CAKE} -eq 0 ]; then $(cleanDirectory $CAKE_DIR) >/dev/null fi # Copy the built Cake to the local Cake path. if [ ${SKIP_BUILDING_CAKE} -eq 0 ]; then cp -r "$BUILT_CAKE_DIR/"*.* "$CAKE_DIR/" fi # Ensure that Cake can be found where we expect it to. if [ ! -f $CAKE_EXE ]; then echo "Could not find Cake.exe at '$CAKE_EXE'." exit 1 fi ##################################################################### # SETUP ENVIRONMENT ##################################################################### export MyEnvironmentVariable="Hello World" ##################################################################### # RUN TESTS ##################################################################### mono $CAKE_EXE --version mono $CAKE_EXE "$SCRIPT" "--target=$TARGET" "--verbosity=quiet" "--platform=posix" "--customarg=hello"
#include <iostream> #include <vector> #include <algorithm> class MemoryManager { private: std::vector<char> memory; std::vector<std::pair<size_t, size_t>> allocatedBlocks; public: MemoryManager(size_t size) : memory(size, 0) {} char* allocate(size_t size) { for (size_t i = 0; i < memory.size(); ++i) { if (memory[i] == 0) { size_t j = i; while (j < memory.size() && memory[j] == 0 && j - i + 1 < size) { ++j; } if (j - i + 1 == size) { for (size_t k = i; k < j; ++k) { memory[k] = 1; } allocatedBlocks.emplace_back(i, j - 1); return &memory[i]; } i = j; } } return nullptr; } void free(char* ptr) { size_t index = ptr - &memory[0]; for (auto& block : allocatedBlocks) { if (block.first <= index && index <= block.second) { for (size_t i = block.first; i <= block.second; ++i) { memory[i] = 0; } allocatedBlocks.erase(std::remove(allocatedBlocks.begin(), allocatedBlocks.end(), block), allocatedBlocks.end()); break; } } } void defragment() { size_t freeIndex = 0; for (auto& block : allocatedBlocks) { size_t blockSize = block.second - block.first + 1; if (block.first != freeIndex) { for (size_t i = block.first; i <= block.second; ++i) { memory[freeIndex] = memory[i]; memory[i] = 0; ++freeIndex; } block.first = freeIndex - blockSize; block.second = freeIndex - 1; } freeIndex += blockSize; } } }; int main() { MemoryManager manager(20); char* ptr1 = manager.allocate(5); char* ptr2 = manager.allocate(8); manager.free(ptr1); manager.defragment(); char* ptr3 = manager.allocate(6); return 0; }
<gh_stars>0 import React, { Component } from 'react'; import '../styles/socket.css'; import io from 'socket.io-client'; class Chat extends Component { constructor(props) { super(props); this.socket = io('http://localhost:4000'); this.state={ partner:'', messages:[], message: '', name:'' } } componentWillUnmount(){ this.socket.close(); } componentDidMount(){ this.socket.open(); this.socket.on('connection', (data)=>{ }); this.socket.on('chat', (data)=>{ this.setState({ messages: [...this.state.messages, data], partner:'' }) }); this.socket.on('typing', (data)=>{ if(data.message === ""){ this.setState({ partner: "" }) } else{ this.setState({ partner: data.name }) } }); } send=(e)=>{ e.preventDefault(); this.socket.emit('chat', { name: this.state.name, message: this.state.message }); this.setState({ message:'' }) } typingMsg=(e)=>{ this.setState({ message: e.target.value }) this.socket.emit('typing', {name:this.state.name, message: e.target.value}); } typingName=(e)=>{ this.setState({ name: e.target.value }) } render() { return ( <form className='chat' onSubmit={this.send}> <div className='chat-window'> <div className='output'> <ul> {this.state.messages.map(msg=>{ return <li className='msges' key={Math.random()*12}><strong>{msg.name + ': '}</strong>{msg.message}</li> })} </ul> </div> <div className='feedback'> {this.state.partner ? <div>{this.state.partner + ' is typing...'}</div> : null} </div> </div> <input type="text" className='name inputss' value={this.state.name} onChange={this.typingName} placeholder="Name" /> <input type="text" className='message inputss' value={this.state.message} onChange={this.typingMsg} placeholder="Message" /> <button className='send' onClick={this.send}>Send</button> </form> ); } } export default Chat;
<form id="form"> <div> <label for="name">Name:</label> <input type="text" name="name" id="name"> </div> <div> <label for="age">Age:</label> <input type="number" name="age" id="age"> </div> <div> <label for="contact">Contact:</label> <input type="text" name="contact" id="contact"> </div> <div> <button type="submit">Submit</button> </div> </form> <script> document.getElementById('form').onsubmit=function(){ let name=document.getElementById('name').value; let age=document.getElementById('age').value; let contact=document.getElementById('contact').value; const data={ name:name, age:age, contact:contact }; fetch('/database/post',{ method:'POST', body:JSON.stringify(data), headers:{ 'content-type':'application/json' } }).then(res=>res.json()) .catch(err=>console.error(err)); return false; } </script>
#!/usr/bin/env bats load test_helper @test "installs tcl-build into PREFIX" { cd "$TMP" PREFIX="${PWD}/usr" run "${BATS_TEST_DIRNAME}/../install.sh" assert_success "" cd usr assert [ -x bin/tcl-build ] assert [ -x bin/tclenv-install ] assert [ -x bin/tclenv-uninstall ] assert [ -e share/tcl-build/8.6.4 ] assert [ -e share/tcl-build/8.5.15 ] } @test "build definitions don't have the executable bit" { cd "$TMP" PREFIX="${PWD}/usr" run "${BATS_TEST_DIRNAME}/../install.sh" assert_success "" run $BASH -c 'ls -l usr/share/tcl-build | tail -2 | cut -c1-10' assert_output <<OUT -rw-r--r-- -rw-r--r-- OUT } @test "overwrites old installation" { cd "$TMP" mkdir -p bin share/tcl-build touch bin/tcl-build touch share/tcl-build/8.6.4 PREFIX="$PWD" run "${BATS_TEST_DIRNAME}/../install.sh" assert_success "" assert [ -x bin/tcl-build ] run grep "install_package" share/tcl-build/8.6.4 assert_success } @test "unrelated files are untouched" { cd "$TMP" mkdir -p bin share/bananas chmod g-w bin touch bin/bananas touch share/bananas/docs PREFIX="$PWD" run "${BATS_TEST_DIRNAME}/../install.sh" assert_success "" assert [ -e bin/bananas ] assert [ -e share/bananas/docs ] run ls -ld bin assert_equal "r-x" "${output:4:3}" }
export const xplatVersion = '*'; export const nxVersion = '~8.8.0';
/** * The front card component that is used to show basic information * about an exercise. This is the overview, not the detailed view * * @format * @flow */ import React from 'react'; import {View, Text, TouchableOpacity} from 'react-native'; import {getBestLog, getLastLog, printLogLine} from 'components/utils'; import {retrieveData} from 'components/storage'; import {Theme, Color} from 'components/stylesheet.js'; import Icon from 'react-native-vector-icons/Ionicons'; class ExerciseCard extends React.Component { constructor(props) { super(props); this.state = { name: this.props.text, id: this.props.id, showInput: false, random: Math.random(), }; this.refresh = this.refresh.bind(this); this.onTouch = this.props.onTouch; retrieveData(this.props.id, this.refresh); } componentDidMount() { this._mounted = true; this.updaterID = setInterval(() => { if (this._mounted) { retrieveData(this.state.id, this.refresh); } }, 5000); } componentWillUnmount() { this._mounted = false; clearInterval(this.updaterID); } /** * @private * After the data has been loaded from the storage, update the state */ refresh(value) { let best = null; let last = null; if (value !== null) { best = getBestLog(value); last = getLastLog(value); } this.setState({ bestWeight: best ? best.weight : null, bestReps: best ? best.reps : null, bestDate: best ? new Date(best.date) : null, bestOneRM: best && best.oneRM ? best.oneRM : null, bestStrengthScore: best && best.score ? best.score : null, //--------------- lastWeight: last ? last.weight : null, lastReps: last ? last.reps : null, lastDate: last ? new Date(last.date) : null, lastOneRM: last && last.oneRM ? last.oneRM : null, lastStrengthScore: last && last.score ? last.score : null, }); } getSadWords() { let items = [ 'So sad.', 'Terrible.', 'Not cool.', 'Horrible.', 'Hit it!', 'Very sad.', 'Change it!', 'Many sad.', 'Such sad.', 'Do it.', 'Why?', //What would batman do 'Not ok.', 'Start now!', 'Your turn.', 'Yet!', ]; return items[Math.floor(this.state.random * items.length)]; } render() { return ( <View style={Theme.maincontainer}> <TouchableOpacity onPress={this.onTouch}> <View style={Theme.rowContainer}> <View> <Text style={Theme.title}>{this.state.name}</Text> {this.state.lastDate && ( <View style={Theme.sectionContainer}> <Text style={Theme.sectionTitle}>Last: </Text> <Text style={Theme.sectionDescription}> {printLogLine( '', this.state.lastWeight, this.state.lastReps, this.state.lastDate, )} </Text> </View> )} {this.state.bestDate && ( <View style={Theme.sectionContainer}> <Text style={Theme.sectionTitle}>Best: </Text> <Text style={Theme.sectionDescription}> {printLogLine( '', this.state.bestWeight, this.state.bestReps, this.state.bestDate, )} </Text> </View> )} {!this.state.lastDate && ( <View style={Theme.sectionContainer}> <Text style={Theme.sectionTitle}>No data available yet.</Text> <Text style={Theme.sectionDescription}> {this.getSadWords()}</Text> </View> )} </View> <Text style={{marginLeft: 'auto'}}> <Icon name="ios-arrow-forward" color={Color.active} size={25} /> </Text> </View> </TouchableOpacity> </View> ); } } export default ExerciseCard;
<h1>5 Places to Visit in Paris</h1> <ul> <li>The Louvre</li> <li>Notre Dame Cathedral</li> <li>Eiffel Tower</li> <li>Arc de Triomphe</li> <li>Sacré-Cœur</li> </ul>
package com.ibm.socialcrm.notesintegration.ui.dashboardcomposites; /**************************************************************** * IBM OpenSource * * (C) Copyright IBM Corp. 2012 * * Licensed under the Apache License v2.0 * http://www.apache.org/licenses/LICENSE-2.0 * ***************************************************************/ import java.lang.reflect.Constructor; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.resource.JFaceColors; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.ui.IPartListener; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.forms.events.HyperlinkAdapter; import org.eclipse.ui.forms.events.HyperlinkEvent; import org.eclipse.ui.internal.Workbench; import org.eclipse.ui.progress.UIJob; import com.ibm.socialcrm.notesintegration.core.BaseSugarEntry; import com.ibm.socialcrm.notesintegration.core.SugarAccount; import com.ibm.socialcrm.notesintegration.core.extensionpoints.DashboardContributionExtensionProcessor; import com.ibm.socialcrm.notesintegration.core.extensionpoints.ISametimeWidgetBuilder; import com.ibm.socialcrm.notesintegration.core.extensionpoints.SametimeWidgetContribution; import com.ibm.socialcrm.notesintegration.core.extensionpoints.SametimeWidgetContributionExtensionProcessor; import com.ibm.socialcrm.notesintegration.core.utils.SugarWebservicesOperations; import com.ibm.socialcrm.notesintegration.core.utils.UpdateSelectionsBroadcaster; import com.ibm.socialcrm.notesintegration.core.utils.SugarWebservicesOperations.GetInfo13RestulType; import com.ibm.socialcrm.notesintegration.ui.dashboardpanels.SugarItemsDashboard; import com.ibm.socialcrm.notesintegration.ui.progress.DashboardCompositeProgressIndicator; import com.ibm.socialcrm.notesintegration.ui.utils.UiUtils; import com.ibm.socialcrm.notesintegration.utils.ConstantStrings; import com.ibm.socialcrm.notesintegration.utils.GenericUtils; import com.ibm.socialcrm.notesintegration.utils.UtilsPlugin; import com.ibm.socialcrm.notesintegration.utils.UtilsPluginNLSKeys; import com.ibm.socialcrm.notesintegration.utils.GenericUtils.SugarType; import com.ibm.socialcrm.notesintegration.utils.widgets.EasyScrolledComposite; import com.ibm.socialcrm.notesintegration.utils.widgets.SFAHyperlink; /** * Specialized dashboard composite that encapsulates some common methods required for the informational tabs for each of the three basic sugar types (Contact, oppty, account). */ public abstract class AbstractInfoDashboardComposite extends AbstractDashboardComposite { public static final String ADDRESSCOMPOSITE = "ADDRESSCOMPOSITE"; //$NON-NLS-1$ public static final String EMAILCOMPOSITE = "EMAICOMPOSITE"; //$NON-NLS-1$ public static final String PHONECOMPOSITE = "PHONECOMPOSITE"; //$NON-NLS-1$ public int maxLabelWidth = -1; public Composite innerComposite; private EasyScrolledComposite scrolledComposite; private DashboardCompositeProgressIndicator progressIndicator; private String progressId; public AbstractInfoDashboardComposite(Composite parent, int style, String dashboardID, BaseSugarEntry sugarEntry) { super(parent, style, dashboardID, sugarEntry); // 41443 - set Shell title to SugarEntry's name addPartListener(); } private void addPartListener() { final IPartListener partListener = new IPartListener() { @Override public void partActivated(IWorkbenchPart arg0) { if (!Workbench.getInstance().getActiveWorkbenchWindow().getShell().getText().equalsIgnoreCase(getSugarEntry().getName())) { if (getSugarEntry() instanceof SugarAccount) { Workbench.getInstance().getActiveWorkbenchWindow().getShell().setText(getSugarEntry().getName() + " (" + ((SugarAccount) getSugarEntry()).getClientId() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ } else { Workbench.getInstance().getActiveWorkbenchWindow().getShell().setText(getSugarEntry().getName()); } } } @Override public void partBroughtToTop(IWorkbenchPart arg0) { // TODO Auto-generated method stub } @Override public void partClosed(IWorkbenchPart arg0) { // TODO Auto-generated method stub } @Override public void partDeactivated(IWorkbenchPart arg0) { // TODO Auto-generated method stub } @Override public void partOpened(IWorkbenchPart arg0) { // TODO Auto-generated method stub } }; Workbench.getInstance().getActiveWorkbenchWindow().getActivePage().addPartListener(partListener); this.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent arg0) { if (partListener != null) { if (Workbench.getInstance() != null && Workbench.getInstance().getActiveWorkbenchWindow() != null && Workbench.getInstance().getActiveWorkbenchWindow().getActivePage() != null) { Workbench.getInstance().getActiveWorkbenchWindow().getActivePage().removePartListener(partListener); } } } }); } @Override public void prepareTask() { progressIndicator = new DashboardCompositeProgressIndicator(getShell()); progressId = "progessBar_BasicTab_" + System.currentTimeMillis(); //$NON-NLS-1$ progressIndicator.populateProgress(getProgressComposite(), UtilsPlugin.getDefault().getResourceString(UtilsPluginNLSKeys.CARD_LOADING), progressId); // retrieve base tab information, then broadcast it to notify all the other tabs retrieveCardData(); } @Override public void createInnerComposite() { scrolledComposite = new EasyScrolledComposite(this, SWT.H_SCROLL | SWT.V_SCROLL); scrolledComposite.setLayout(GridLayoutFactory.fillDefaults().numColumns(1).create()); scrolledComposite.setLayoutData(GridDataFactory.fillDefaults().grab(true, true).create()); innerComposite = new Composite(scrolledComposite, SWT.NONE); innerComposite.setBackground(JFaceColors.getBannerBackground(Display.getDefault())); updateInnerComposite(innerComposite); UiUtils.recursiveSetBackgroundColor(innerComposite, JFaceColors.getBannerBackground(Display.getDefault())); scrolledComposite.setContent(innerComposite); } @Override public void selectedItemsChanged() { } public void retrieveCardData() { Job retrieveCardDataJob = new Job("Retrieving card data") //$NON-NLS-1$ { @Override protected IStatus run(IProgressMonitor arg0) { // *** Retreive card base tab data boolean isOK = SugarWebservicesOperations.getInstance().callSugarGetInfo13(getSugarEntry().getSugarType(), getSugarEntry().getId(), GetInfo13RestulType.BASECARD); // 102312 - remove following/unfollowing feature // if (isOK) { // // get the oppty/account Follow information // if (getSugarEntry().getSugarType().equals(SugarType.ACCOUNTS) || getSugarEntry().getSugarType().equals(SugarType.OPPORTUNITIES)) { // isOK = SugarWebservicesOperations.getInstance().callSugarGetInfo13(getSugarEntry().getSugarType(), getSugarEntry().getId(), GetInfo13RestulType.FOLLOWED); // } // } // *** update Sugar Entry Object if (isOK) { setBaseDataRetrieved(isOK); setSugarEntry(SugarWebservicesOperations.getInstance().getSugarEntryById(getSugarEntry().getId())); } else { // need to tell user the bad news if (AbstractInfoDashboardComposite.this.isDisposed()) { } else { Display.getDefault().syncExec(new Runnable() { @Override public void run() { if (SugarWebservicesOperations.getInstance().isInvalidSugarEntry()) { SugarWebservicesOperations.getInstance().resetInvalidSugarEntry(false); // Display an error msg and prompt user for credential... this should cover the case if pswd was changed // between the time period a session was created and a card was brought up. MessageDialog.openError(Display.getDefault().getShells()[0], UtilsPlugin.getDefault().getResourceString(UtilsPluginNLSKeys.CARD_RETRIEVE_ERROR), UtilsPlugin .getDefault().getResourceString(UtilsPluginNLSKeys.CARD_RETRIEVE_FAILURE_INVALID_SUGARENTRY)); AbstractInfoDashboardComposite.this.getShell().close(); } else if (SugarWebservicesOperations.getInstance().hasConnectionProblem()) { // Display an error msg and prompt user for credential... this should cover the case if pswd was changed // between the time period a session was created and a card was brought up. MessageDialog.openError(Display.getDefault().getShells()[0], UtilsPlugin.getDefault().getResourceString(UtilsPluginNLSKeys.CARD_RETRIEVE_ERROR), UtilsPlugin .getDefault().getResourceString(UtilsPluginNLSKeys.UI_CRM_SERVER_CONNECTION_ERROR)); SugarWebservicesOperations.getPropertyChangeSupport().firePropertyChange(SugarWebservicesOperations.BRING_UP_CREDENTIAL_PROMPT, true, false); AbstractInfoDashboardComposite.this.getShell().close(); } else { // A generic error msg MessageDialog.openError(Display.getDefault().getShells()[0], UtilsPlugin.getDefault().getResourceString(UtilsPluginNLSKeys.CARD_RETRIEVE_ERROR), UtilsPlugin .getDefault().getResourceString(UtilsPluginNLSKeys.CARD_RETRIEVE_FAILURE, new String[]{getSugarEntry().getName()})); AbstractInfoDashboardComposite.this.getShell().close(); } } }); } } final boolean isOKNow = isOK; if (isOKNow) { // *** Update base tab UI UIJob updateBaseCardUIJob = new UIJob("updateBaseCardUIJob") //$NON-NLS-1$ { @Override public IStatus runInUIThread(IProgressMonitor arg0) { afterBaseCardDataRetrievedForBaseTab(); return Status.OK_STATUS; } }; updateBaseCardUIJob.schedule(); // *** Notify other tabs to either proceed or abort. Those tabs should implement afterBaseCardDataRetrieved(). // Separate broadcast in a separate UIJob so the basecase can be updated and displayed before the other tabs // are notified. UIJob broadcastBaseCardIsReadyUIJob = new UIJob("broadcastBaseCardIsReady") //$NON-NLS-1$ { @Override public IStatus runInUIThread(IProgressMonitor arg0) { // UpdateSelectionsBroadcaster.getInstance().basecardDataRetrieved(isOKNow); UpdateSelectionsBroadcaster.getInstance().basecardDataRetrieved(getSugarEntry()); return Status.OK_STATUS; } }; broadcastBaseCardIsReadyUIJob.schedule(); } return Status.OK_STATUS; } }; retrieveCardDataJob.schedule(); } /* * Method called after basecard data was retrieved, it's called only by the base tab. It should be executed before the broadcast so basecase UI can be updated and displayed before other tabs is * notified. */ public void afterBaseCardDataRetrievedForBaseTab() { // Update card header information super.afterBaseCardDataRetrieved(); updateInnerCompositeWithData(); if (progressIndicator != null) { progressIndicator.removeProgress(getProgressComposite(), progressId); } getParent().layout(true, true); } @Override public void afterBaseCardDataRetrieved() { // Empty this method, because it's been called in the afterBaseCardDataRetrievedForBaseTab() method. } // Inner composites for business card. protected void createAddressComposite(Composite parent, BaseSugarEntry sugarEntry, int maxLabelWidth) { Label addressLabel = new Label(parent, SWT.NONE); addressLabel.setFont(SugarItemsDashboard.getInstance().getBusinessCardLabelFont()); addressLabel.setForeground(SugarItemsDashboard.getInstance().getBusinessCardFieldLabelColor()); addressLabel.setText(UtilsPlugin.getDefault().getResourceString(UtilsPluginNLSKeys.ADDRESS_LABEL)); if (isAtLeastOneAddressFieldAvailable(sugarEntry)) { int verticalSpan = 0; if (sugarEntry.getStreet() != null && !sugarEntry.getStreet().equals(ConstantStrings.EMPTY_STRING)) { Label label = new Label(parent, SWT.WRAP); label.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).create()); label.setText(sugarEntry.getStreet()); label.setToolTipText(sugarEntry.getStreet()); label.setFont(SugarItemsDashboard.getInstance().getNormalFontForBusinessCardData()); verticalSpan++; } String cityStatePostal = getCityStatePostal(sugarEntry).trim(); if (!cityStatePostal.equals(ConstantStrings.EMPTY_STRING)) { Label label = new Label(parent, SWT.WRAP); label.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).create()); label.setText(cityStatePostal); label.setToolTipText(cityStatePostal); label.setFont(SugarItemsDashboard.getInstance().getNormalFontForBusinessCardData()); verticalSpan++; } if (sugarEntry.getCountry() != null && !sugarEntry.getCountry().equals(ConstantStrings.EMPTY_STRING)) { Label label = new Label(parent, SWT.WRAP); label.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).create()); label.setText(sugarEntry.getCountry()); label.setToolTipText(sugarEntry.getCountry()); label.setFont(SugarItemsDashboard.getInstance().getNormalFontForBusinessCardData()); verticalSpan++; } addressLabel.setLayoutData(GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.BEGINNING).hint(maxLabelWidth == -1 ? SWT.DEFAULT : maxLabelWidth, SWT.DEFAULT).span(1, verticalSpan) .create()); } else if (!isBaseDataRetrieved()) { int verticalSpan = 1; addressLabel.setLayoutData(GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.BEGINNING).hint(maxLabelWidth == -1 ? SWT.DEFAULT : maxLabelWidth, SWT.DEFAULT).span(2, verticalSpan) .create()); } } protected void createEmailComposite(Composite parent, final String email, String labelText, int labelWidth, boolean suppressed) { Label label = new Label(parent, SWT.NONE); label.setFont(SugarItemsDashboard.getInstance().getBusinessCardLabelFont()); label.setForeground(SugarItemsDashboard.getInstance().getBusinessCardFieldLabelColor()); label.setLayoutData(GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.BEGINNING).hint((maxLabelWidth == -1 || maxLabelWidth == 0) ? SWT.DEFAULT : maxLabelWidth, SWT.DEFAULT).create()); label.setText(labelText); SFAHyperlink hyperLink = new SFAHyperlink(parent, SWT.NONE, true); hyperLink.setLayoutData(GridDataFactory.fillDefaults().indent(0, GenericUtils.getPlatformHyperlinkVerticalIndent()).create()); hyperLink.setStrikethrough(suppressed); hyperLink.setText(email); hyperLink.setFont(SugarItemsDashboard.getInstance().getNormalFontForBusinessCardData()); hyperLink.setForeground(SugarItemsDashboard.getInstance().getBusinessCardLinkColor()); if (!suppressed && email != null && !email.equals(ConstantStrings.EMPTY_STRING)) { hyperLink.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent arg0) { UiUtils.createEmail(email); } }); } } protected void createClickToCallComposite(Composite parent, final String phone, String labelText, int labelWidth, boolean suppressed) { boolean builtViaContribution = false; if (phone != null && !phone.equals(ConstantStrings.EMPTY_STRING) && !suppressed) { SametimeWidgetContribution sametimeWidgetContribution = SametimeWidgetContributionExtensionProcessor.getInstance().getSametimeWidgetContribution(); if (sametimeWidgetContribution != null) { try { Class builderClass = sametimeWidgetContribution.getBundle().loadClass(sametimeWidgetContribution.getBuilderClass()); Constructor constructor = builderClass.getConstructor(); ISametimeWidgetBuilder sametimeWidgetBuilder = (ISametimeWidgetBuilder) constructor.newInstance(); builtViaContribution = sametimeWidgetBuilder.createClickToCallComposite(parent, phone, labelText, labelWidth); } catch (Exception e) { UtilsPlugin.getDefault().logException(e, UtilsPlugin.PLUGIN_ID); } } } if (!builtViaContribution || suppressed) { Label phoneLabel = new Label(parent, SWT.NONE); phoneLabel.setText(labelText); phoneLabel.setFont(SugarItemsDashboard.getInstance().getBusinessCardLabelFont()); phoneLabel.setForeground(SugarItemsDashboard.getInstance().getBusinessCardFieldLabelColor()); phoneLabel.setLayoutData(GridDataFactory.fillDefaults().hint(labelWidth, SWT.DEFAULT).create()); if (suppressed) { SFAHyperlink hyperLink = new SFAHyperlink(parent, SWT.NONE); hyperLink.setLayoutData(GridDataFactory.fillDefaults().indent(0, GenericUtils.getPlatformHyperlinkVerticalIndent()).create()); hyperLink.setStrikethrough(true); hyperLink.setText(phone == null ? ConstantStrings.EMPTY_STRING : phone); hyperLink.setForeground(SugarItemsDashboard.getInstance().getBusinessCardLinkColor()); hyperLink.setFont(SugarItemsDashboard.getInstance().getNormalFontForBusinessCardData()); } else { Label phoneNumberLabel = new Label(parent, SWT.NONE); phoneNumberLabel.setText(phone == null ? ConstantStrings.EMPTY_STRING : phone); phoneNumberLabel.setFont(SugarItemsDashboard.getInstance().getNormalFontForBusinessCardData()); } } } private boolean isAtLeastOneAddressFieldAvailable(BaseSugarEntry sugarEntry) { return (sugarEntry != null && (sugarEntry.getStreet() != null && !sugarEntry.getStreet().equals(ConstantStrings.EMPTY_STRING)) || (sugarEntry.getCity() != null && !sugarEntry.getCity().equals(ConstantStrings.EMPTY_STRING)) || (sugarEntry.getState() != null && !sugarEntry.getState().equals(ConstantStrings.EMPTY_STRING)) || (sugarEntry.getPostalCode() != null && !sugarEntry.getPostalCode().equals(ConstantStrings.EMPTY_STRING)) || (sugarEntry.getCountry() != null && !sugarEntry.getCountry().equals( ConstantStrings.EMPTY_STRING))); } private String getCityStatePostal(BaseSugarEntry sugarEntry) { String cityStatePostal = ConstantStrings.EMPTY_STRING; boolean cityAvailable = sugarEntry.getCity() != null && !sugarEntry.getCity().equals(ConstantStrings.EMPTY_STRING); boolean stateAvailable = sugarEntry.getState() != null && !sugarEntry.getState().equals(ConstantStrings.EMPTY_STRING); boolean postalAvailable = sugarEntry.getPostalCode() != null && !sugarEntry.getPostalCode().equals(ConstantStrings.EMPTY_STRING); cityStatePostal = cityAvailable ? sugarEntry.getCity() : ConstantStrings.EMPTY_STRING; cityStatePostal += stateAvailable && cityAvailable ? ", " + sugarEntry.getState() : stateAvailable ? sugarEntry //$NON-NLS-1$ .getState() : ConstantStrings.EMPTY_STRING; cityStatePostal += postalAvailable && stateAvailable ? " " + sugarEntry.getPostalCode() : postalAvailable && cityAvailable ? ", " + sugarEntry.getPostalCode() //$NON-NLS-1$ //$NON-NLS-2$ : postalAvailable ? sugarEntry.getPostalCode() : ConstantStrings.EMPTY_STRING; return cityStatePostal; } protected int getMaxLabelWidth() { if (maxLabelWidth == -1) { Point point = computeMaxSize(this, getFieldLabels()); if (point != null) { maxLabelWidth = point.x; maxLabelWidth += 5; // Add a buffer to improve spacing } } return maxLabelWidth; } /** * Returns the set of labels used for the various data fields * * @return */ public abstract String[] getFieldLabels(); /** * Since this method is only used to compute label sizes, the getBusinessCardLabelFont() font is hardcoded. We can always change this as necessary. * * @param parent * @param arrays * @return */ public Point computeMaxSize(Composite parent, String[] arrays) { int width = -1; int height = -1; if (parent == null || arrays == null || arrays.length == 0) { return null; } GC gc = new GC(parent); gc.setFont(SugarItemsDashboard.getInstance().getBusinessCardLabelFont()); for (int i = 0; i < arrays.length; i++) { Point size = gc.textExtent(arrays[i]); // or textExtent width = Math.max(width, size.x); height = Math.max(height, size.y); } gc.dispose(); return new Point(width, height); } public abstract void updateInnerComposite(Composite innerComposite); }
from tkinter import * import tkinter.font as font import sqlite3 def main(): sub=Tk() sub.title("Choose any Subject") sub.geometry("420x550") sub.iconbitmap("logo/spectrumlogo.ico") db=sqlite3.connect("mark_list.db") #cursor c=db.cursor() #query the database c.execute("SELECT *,oid FROM mark_list") records=c.fetchall() l=len(c.fetchall()) n3=records[l-1][1] r3=records[l-1][2] b3=records[l-1][3] #commit_changes db.commit() #close connection db.close() f_new=font.Font(family='Times New',size=20,weight='bold') f1=font.Font(family='Times New',size=15,weight='bold') f2=font.Font(family='Times New',size=10,weight='bold') """n5=Label(sub,text=' ',fg='green',font=f1) r5=Label(sub,text=' ',fg='green',font=f1) b5=Label(sub,text=' ',fg='green',font=f1)""" wel=Label(sub,text="Welcome\nYou may enter your marks\n\n",fg='blue',font=f_new).grid(row=0,column=0,columnspan=3) full_name1=Label(sub,text="Name:{}\n Registration ID:{}\n Branch:{} ".format(n3,r3,b3),font=f1,fg='purple').grid(row=1,column=0,columnspan=3) """n5['text']=n3 n5.grid(row=1,column=2) branch=Label(sub,text=" Branch: ",font=f1,fg='purple').grid(row=2,column=0,columnspan=2) b5['text']=b3 b5.grid(row=2,column=2) reg_no=Label(sub,text="Registration ID: ",font=f1,fg='purple').grid(row=3,column=0,columnspan=2) r5['text']=r3 r5.grid(row=3,column=2)""" Label(sub,text=" \n\n").grid(row=3) def mark(text): import input_marks input_marks.sub=text input_marks.main() Label(sub,text='Click on the Respective Button to enter mark\n',fg='red',font=f2).grid(row=4,column=0,columnspan=3) #buttons chemistry=Button(sub,text='Chemistry',padx=5,pady=5,borderwidth=5,font=f1,fg='red',bg='yellow',command=lambda :mark("CHEMISTRY")) chemistry.grid(row=5,column=0) math=Button(sub,text='Math',padx=20,pady=5,borderwidth=5,fg='red',font=f1,bg='yellow',command=lambda :mark("MATH")) math.grid(row=5,column=1) computer=Button(sub,text='Computer',padx=5,pady=5,borderwidth=5,font=f1,fg='red',bg='yellow',command=lambda :mark("COMPUTER")) computer.grid(row=5,column=2) Label(sub,text="\n\n\n").grid(row=6) def submit(): sub.destroy() import last last.main() def cancel(): db=sqlite3.connect("mark_list.db") #cursor c=db.cursor() #query the database c.execute("SELECT *,oid FROM mark_list") records=c.fetchall() l=len(c.fetchall()) n6=records[l-1][1] c.execute("""UPDATE mark_list SET chemistry=? WHERE name=?""",(0,n6)) c.execute("""UPDATE mark_list SET math=? WHERE name=?""",(0,n6)) c.execute("""UPDATE mark_list SET computer=? WHERE name=?""",(0,n6)) c.execute("""UPDATE mark_list SET registration_no=? WHERE name=?""",(' ',n6)) c.execute("""UPDATE mark_list SET branch=? WHERE name=?""",(' ',n6)) c.execute("""UPDATE mark_list SET name=? WHERE name=?""",(' ',n6)) #commit_changes db.commit() #close connection db.close() sub.destroy() import input_details input_details.main() submit_m=Button(sub,text='Submit',padx=10,pady=1,borderwidth=5,bg='green',font=f1,command=submit) submit_m.grid(row=7,column=0,columnspan=3) cancel=Button(sub,text='Cancel',padx=3,pady=1,borderwidth=5,bg='red',font=f2,command=cancel) cancel.grid(row=8,column=0,columnspan=3) mainloop() if __name__=='__main__': main()
#!/bin/sh # # setup.sh # # The MIT License # # Copyright (C) 2014-2015 Shota Matsuda # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # readonly PROJECT_DIR="$(cd "$(dirname "$0")/../"; pwd)" cd "${PROJECT_DIR}" git submodule update --init "script/build_boost.sh" "script/build.sh" cmake "lib/googletest/googletest" "build/googletest"
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" > /dev/null 2>&1 && pwd)" . "$DIR/prelude.sh" cd src set -o errexit set -o verbose activate_venv export MYPY="$( if which cygpath 2> /dev/null; then PATH+=":$(cypath "${workdir}")/venv_3/Scripts" else PATH+=":${workdir}/venv_3/bin" fi PATH+=':/opt/mongodbtoolchain/v3/bin' which mypy )" echo "Found mypy executable at '$MYPY'" export extra_flags="" eval ${compile_env} python3 ./buildscripts/scons.py ${compile_flags} $extra_flags --stack-size=1024 GITDIFFFLAGS="${revision}" REVISION="${revision}" ENTERPRISE_REV="${enterprise_rev}" ${targets}
/* * Bell Canada, Network Big Data Team * Dev: <NAME> */ package spark-testing; /** * Created by <NAME> on 05-Oct-2016. * credits to: <NAME> * https://hadoopi.wordpress.com/category/inputformat/ * * changes done by <NAME>: * > support of compressed source files (the source data was gzip). TODO - support splittable compressed formats like bzip2 * > addition of line delimiter specification * > begin and end line regex: now it picks up lines between 2 regex record delimiters */ import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.util.LineReader; import com.google.common.base.Charsets; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.CompressionCodecFactory; public class PatternRecordReader2 extends RecordReader<LongWritable, Text> { private LineReader in; private long start; private long pos; private long end; private LongWritable key = new LongWritable(); private Text value = new Text(); //private static final Text EOL = new Text("\n"); private Pattern lineBeginPattern; private Pattern lineEndPattern; private String lineBeginRegex; private String lineEndRegex; private String delimiter; private int maxLengthRecord; private Text lEnd; // private Text lastDelimValue = new Text(); private static final Log LOG = LogFactory.getLog(RecordReader.class); @Override public void initialize(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException { // Retrieve configuration value Configuration job = context.getConfiguration(); this.lineBeginRegex = job.get("record.line.begin.regex"); this.lineEndRegex = job.get("record.line.end.regex"); //this.maxLengthRecord = job.getInt("mapred.linerecordreader.maxlength", Integer.MAX_VALUE); this.maxLengthRecord = job.getInt("mapreduce.input.linerecordreader.line.maxlength", Integer.MAX_VALUE); this.delimiter = job.get("textinputformat.record.delimiter"); byte[] recordDelimiterBytes; if (null != delimiter) { lEnd = new Text(delimiter); recordDelimiterBytes = lEnd.toString().getBytes(Charsets.UTF_8); } else{ lEnd = new Text("\n"); recordDelimiterBytes = null; } // Compile pattern only once per InputSplit lineBeginPattern = Pattern.compile(lineBeginRegex); lineEndPattern = Pattern.compile(lineEndRegex); // Retrieve FileSplit details FileSplit fileSplit = (FileSplit) split; start = fileSplit.getStart(); end = start + fileSplit.getLength(); final Path file = fileSplit.getPath(); FileSystem fs = file.getFileSystem(job); // Open FileSplit FSDataInputStream FSDataInputStream fileIn = fs.open(fileSplit.getPath()); // assumption: files are gzipped - which is not a splittable codec CompressionCodec codec = new CompressionCodecFactory(job).getCodec(file); if (codec != null) { LOG.info("Reading compressed file: " + file); in = new LineReader(codec.createInputStream(fileIn), job, recordDelimiterBytes); end = Long.MAX_VALUE; } else { LOG.info("Reading uncompressed file: " + file); // Skip first record if Split does not start at byte 0 (first line of file) boolean skipFirstLine = false; if (start != 0) { skipFirstLine = true; --start; fileIn.seek(start); } // Read FileSplit content in = new LineReader(fileIn, job, recordDelimiterBytes); if (skipFirstLine) { LOG.info("Need to skip first line of Split"); Text dummy = new Text(); start += readNext(dummy, 0, (int) Math.min((long) Integer.MAX_VALUE, end - start)); } this.pos = start; } } @Override public boolean nextKeyValue() throws IOException, InterruptedException { key.set(pos); int newSize = 0; // Get only the records for which the first byte // is located before end of current Split while (pos < end) { // Read new record and store content into value // value is a mutable parameter newSize = readNext(value, maxLengthRecord, Math.max( (int) Math.min(Integer.MAX_VALUE, end - pos), maxLengthRecord)); pos += newSize; if (newSize == 0) { break; } if (newSize < maxLengthRecord) { break; } LOG.error("Skipped radius of size " + newSize + " at pos " + (pos - newSize)); } // No bytes to read (end of split) if (newSize == 0) { key = null; value = null; return false; } else { return true; } } @Override public LongWritable getCurrentKey() throws IOException, InterruptedException { return key; } @Override public Text getCurrentValue() throws IOException, InterruptedException { return value; } @Override public float getProgress() throws IOException, InterruptedException { return start == end ? 0.0f : Math.min(1.0f, (pos - start) / (float) (end - start)); } @Override public void close() throws IOException { if (in != null) { in.close(); } } private int readNext(Text text, int maxLineLength, int maxBytesToConsume) throws IOException { int offset = 0; text.clear(); Text tmp = new Text(); // set linesOfInterest flag to false boolean linesOfInterest = false; // flag to read the lines boolean firstLine = false; //flag to indicate it's the first, so that we dont add new line at the begining for (int i = 0; i < maxBytesToConsume; i++) { int offsetTmp = in.readLine(tmp, maxLineLength, maxBytesToConsume); offset += offsetTmp; Matcher mBegin = lineBeginPattern.matcher(tmp.toString()); Matcher mEnd = lineEndPattern.matcher(tmp.toString()); // End of File if (offsetTmp == 0) { break; } if (mBegin.matches() && !linesOfInterest) { linesOfInterest = true; firstLine = true; } if (linesOfInterest) { if (!firstLine) { text.append(lEnd.getBytes(), 0, lEnd.getLength()); text.append(tmp.getBytes(), 0, tmp.getLength()); } else { text.append(tmp.getBytes(), 0, tmp.getLength()); firstLine = false; //next lines (iterations) will be next lines } } if (mEnd.matches() && linesOfInterest){ // the text will be detected from previous if, i.e. you will also get the line it found mEnd break; } } return offset; } }
#!/bin/sh export CHANNEL_NAME=chainedbidschannel export TIMEOUT=300 docker-compose -f docker-compose.yaml -f docker-compose-couch.yaml down function clearContainers () { CONTAINER_IDS=$(docker ps -aq) if [ -z "$CONTAINER_IDS" -o "$CONTAINER_IDS" == " " ]; then echo "---- No containers available for deletion ----" else docker rm -f $CONTAINER_IDS fi } function removeUnwantedImages() { DOCKER_IMAGE_IDS=$(docker images | grep "dev\|none\|test-vp\|peer[0-9]-" | awk '{print $3}') if [ -z "$DOCKER_IMAGE_IDS" -o "$DOCKER_IMAGE_IDS" == " " ]; then echo "---- No images available for deletion ----" else docker rmi -f $DOCKER_IMAGE_IDS fi } clearContainers removeUnwantedImages
<reponame>angilin/JavaTest package htmlparse; public class PbccrcQueryRecord { private String queryDate; private String type; private String queryNo; private String operator; private String queryReason; public String getQueryDate() { return queryDate; } public void setQueryDate(String queryDate) { this.queryDate = queryDate; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getQueryNo() { return queryNo; } public void setQueryNo(String queryNo) { this.queryNo = queryNo; } public String getOperator() { return operator; } public void setOperator(String operator) { this.operator = operator; } public String getQueryReason() { return queryReason; } public void setQueryReason(String queryReason) { this.queryReason = queryReason; } }
import { Button, FormControl, FormLabel, Textarea, Input, Modal, ModalBody, ModalCloseButton, ModalContent, ModalFooter, ModalHeader, ModalOverlay, HStack, useDisclosure, } from "@chakra-ui/core"; import React, { useState, useMemo, useEffect } from "react"; import db from "../../lib/firebase.js"; // import {sendTransaction} from './utils' import Wallet from '@project-serum/sol-wallet-adapter'; import { Account,Connection, SystemProgram,Transaction,TransactionInstruction, clusterApiUrl } from '@solana/web3.js'; const ConnectWallet = () => { const { isOpen, onOpen, onClose } = useDisclosure(); const [title, setTitle] = useState(""); const [description, setDescription] = useState(""); const [category, setCategory] = useState(""); const [isSaving, setSaving] = useState(false); const [balance, setBalance] = useState(""); const [network, setNetwork] = useState(clusterApiUrl('devnet')); // const handleSubmit = async () => { // setSaving(true); // const date = new Date(); // // await db.collection("posts").add({ // // title, // // upVotesCount: 0, // // downVotesCount: 0, // // createdAt: date.toUTCString(), // // updatedAt: date.toUTCString(), // // }); // await db.collection("dapps").add({ // title, // description, // category, // upVotesCount: 0, // downVotesCount: 0, // createdAt: date.toUTCString(), // updatedAt: date.toUTCString(), // }); // onClose(); // setTitle(""); // setDescription(""); // setCategory(""); // setSaving(false); // }; //sol wallet stuff // const network = clusterApiUrl('devnet'); const [providerUrl, setProviderUrl] = useState('https://www.sollet.io'); const connection = useMemo(() => new Connection(network), [network]); const wallet = useMemo(() => new Wallet(providerUrl, network), [ providerUrl, network, ]); const [, setConnected] = useState(false); useEffect(() => { wallet.on('connect', () => { setConnected(true); console.log('Connected to wallet ' + wallet.publicKey.toBase58()); }); wallet.on('disconnect', () => { setConnected(false); console.log('Disconnected from wallet'); }); return () => { wallet.disconnect(); }; }, [wallet]); // sendTransaction(network,connection,wallet); return ( <> {wallet.connected ? ( <> <div>Wallet address: {wallet.publicKey.toBase58()}.</div> <Button onClick="" colorScheme="blackAlpha">Send Transaction</Button> </> ) : ( <Button onClick={() => wallet.connect()} colorScheme="blackAlpha" mr={1}>Connect Wallet</Button> )} </> ); }; export default ConnectWallet;
#!/usr/bin/env bats # Copyright (c) 2016-2017 Bitnami # # 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. load ../script/libtest # 'bats' lacks loop support, unroll-them-all -> @test "Wait for kafka" { wait_for_kubeless_kafka_server_ready } @test "Test function: pubsub-python" { deploy_function pubsub-python verify_function pubsub-python kubeless_function_delete pubsub-python } @test "Test function: pubsub-python34" { deploy_function pubsub-python34 verify_function pubsub-python34 kubeless_function_delete pubsub-python34 } @test "Test function: pubsub-nodejs" { skip "This test is flaky until kubeless/kubeless/issues/519 is fixed" deploy_function pubsub-nodejs verify_function pubsub-nodejs test_kubeless_function_update pubsub-nodejs kubeless_function_delete pubsub-nodejs } @test "Test function: pubsub-ruby" { deploy_function pubsub-ruby verify_function pubsub-ruby kubeless_function_delete pubsub-ruby } @test "Test topic list" { wait_for_kubeless_kafka_server_ready for topic in topic1 topic2; do kubeless topic create $topic _wait_for_kubeless_kafka_topic_ready $topic done kubeless topic list >$BATS_TMPDIR/kubeless-topic-list grep -qxF topic1 $BATS_TMPDIR/kubeless-topic-list grep -qxF topic2 $BATS_TMPDIR/kubeless-topic-list } @test "Test topic deletion" { test_topic_deletion } @test "Verify Kafka after restart (if context=='minikube')" { local topic=$RANDOM kubeless topic create $topic sts_restart kubeless topic list | grep $topic } # vim: ts=2 sw=2 si et syntax=sh
#!/bin/bash RAI_UC_TOOLS=$(dirname $0) . $RAI_UC_TOOLS/env.sh exec $UC_TOOLS/linux/build.sh
<gh_stars>0 const mongoose = require("mongoose"); const express = require("express"); const session = require("express-session"); const cors = require("cors"); const bodyParser = require("body-parser"); const http = require("http"); const WebSocket = require("ws"); const categories = require("./routes/categories"); const rooms = require("./routes/rooms"); const questions = require("./models/questions.js"); const Question = mongoose.model("Questions"); const app = express(); const port = 3000; const dbName = "quizzer"; app.use(cors({ origin: true, credentials: true })); app.options("*", cors({ origin: true, credentials: true })); const sessionParser = session({ saveUninitialized: false, secret: "$eCuRiTy", resave: false, }); app.use(sessionParser); app.use(bodyParser.json()); app.use("/categories", categories); app.use("/rooms", rooms); app.get("/", (req, res) => { res.send("Welcome to quizzer-server"); }); app.get("/questions/:questionid", function (req, res) { const reqQuestionid = req.params.questionid; Question.findById(reqQuestionid) .then((question) => { const message = { id: question._id, question: question.question, answer: question.answer, category: question.category, }; res.send(message); }) .catch((err) => { res.sendStatus(500); throw err; }); }); // Here we set up the session app.post("/login", (req, res) => { console.log( `Updating session for ${req.body.clientType} in room ${req.body.roomid}` ); req.session.roomid = req.body.roomid; req.session.clientType = req.body.clientType; res.send({ result: "OK", message: "Session updated" }); }); const httpServer = http.createServer(app); const websocketServer = new WebSocket.Server({ noServer: true }); httpServer.on("upgrade", (req, networkSocket, head) => { sessionParser(req, {}, () => { if (req.session.roomid === undefined) { networkSocket.destroy(); return; } console.log("Session is parsed"); websocketServer.handleUpgrade(req, networkSocket, head, (newWebSocket) => { websocketServer.emit("connection", newWebSocket, req); }); }); }); websocketServer.on("connection", (socket, req) => { socket.roomid = req.session.roomid; socket.on("message", (message) => { req.session.reload((err) => { if (err) { throw err; } function outMessage(outMsg) { console.log("outMessage: ", outMsg); websocketServer.clients.forEach(function (client) { if (client.roomid === message.roomid) { client.send(JSON.stringify(outMsg)); } }); } message = JSON.parse(message); console.log("New message: ", message); switch (message.messageType) { case "NEW_QUESTION": outMessage({ messageType: "NEW_QUESTION", }); break; case "NEW_ANSWER": outMessage({ messageType: "NEW_ANSWER", payload: message.payload, }); break; case "CLOSE_QUESTION": outMessage({ messageType: "CLOSE_QUESTION", }); break; case "SHOW_ANSWER": outMessage({ messageType: "SHOW_ANSWER", payload: message.payload, }); break; case "SHOW_ANSWERS": outMessage({ messageType: "SHOW_ANSWERS", }); break; case "END_ROUND": outMessage({ messageType: "END_ROUND", }); break; case "END_QUIZ": outMessage({ messageType: "END_QUIZ", }); break; case "NEW_TEAM": outMessage({ messageType: "NEW_TEAM", payload: message.payload, }); break; case "TEAM_APPROVED": outMessage({ messageType: "TEAM_APPROVED", payload: message.payload, }); break; default: break; } req.session.save(); }); }); }); // Start the server. httpServer.listen(port, () => { console.log( `quizzer-server & websockets listening at http://localhost:${port}` ); mongoose.connect( `mongodb://localhost:27017/${dbName}`, { useNewUrlParser: true, useUnifiedTopology: true }, () => { console.log(`quizzer db started on port ${port}`); } ); });
""" Tests for util/random.py Functions --------- probvec sample_without_replacement """ import numpy as np from numpy.testing import assert_array_equal, assert_raises from nose.tools import eq_ from quantecon.random import probvec, sample_without_replacement # probvec # class TestProbvec: def setUp(self): self.m, self.k = 2, 3 # m vectors of dimension k seed = 1234 self.out_parallel = probvec(self.m, self.k, random_state=seed) self.out_cpu = \ probvec(self.m, self.k, random_state=seed, parallel=False) def test_shape(self): for out in [self.out_parallel, self.out_cpu]: eq_(out.shape, (self.m, self.k)) def test_parallel_cpu(self): assert_array_equal(self.out_parallel, self.out_cpu) # sample_without_replacement # def test_sample_without_replacement_shape(): assert_array_equal(sample_without_replacement(2, 0).shape, (0,)) n, k, m = 5, 3, 4 assert_array_equal( sample_without_replacement(n, k).shape, (k,) ) assert_array_equal( sample_without_replacement(n, k, num_trials=m).shape, (m, k) ) def test_sample_without_replacement_uniqueness(): n = 10 a = sample_without_replacement(n, n) b = np.unique(a) eq_(len(b), n) def test_sample_without_replacement_value_error(): # n <= 0 assert_raises(ValueError, sample_without_replacement, 0, 2) assert_raises(ValueError, sample_without_replacement, -1, -1) # k > n assert_raises(ValueError, sample_without_replacement, 2, 3) if __name__ == '__main__': import sys import nose argv = sys.argv[:] argv.append('--verbose') argv.append('--nocapture') nose.main(argv=argv, defaultTest=__file__)
#!/bin/sh echo $@ dest=/usr/local/bin/hlx error_exit() { echo "$1" 1>&2 exit 1 } ask() { # https://djm.me/ask local prompt default reply while true; do if [ "${2:-}" = "Y" ]; then prompt="Y/n" default=Y elif [ "${2:-}" = "N" ]; then prompt="y/N" default=N else prompt="y/n" default= fi # Ask the question (not using "read -p" as it uses stderr not stdout) echo "$1 [$prompt] " # Read the answer (use /dev/tty in case stdin is redirected from somewhere else) read reply </dev/tty # Default? if [ -z "$reply" ]; then reply=$default fi # Check if the reply is valid case "$reply" in Y*|y*) return 0 ;; N*|n*) return 1 ;; esac done } if [ -L $dest -o -f $dest ]; then if [ -x $dest ]; then old_version=$($dest --version) if [ x"$@" == x"--overwrite" ]; then rm $dest elif ! ask "hlx version $old_version ($dest) exists, overwrite?" Y; then exit 1 fi else rm $dest fi fi if cp a.out $dest; then chmod 755 $dest # TODO: respect umask version=$($dest --version) # hlx bash completion # remove traces of previous installations sed -i '' '/###-begin-hlx-completions-###/,/###-end-hlx-completions-###/d' ~/.bash_profile # remove trailing empty lines sed -i '' -e :a -e '/^\n*$/{$d;N;};/\n$/ba' ~/.bash_profile # append hlx bash completion printf '\n' >> ~/.bash_profile hlx completion >> ~/.bash_profile echo "hlx version $version successfully installed: $dest" else error_exit "failed to install hlx, aborting" fi
import Component from '@ember/component'; import {getParameterByName, setParameterByName} from 'kursausschreibung/framework/url-helpers'; function filterParam(getParam) { let filters = document.getElementsByClassName('filter-tag'); let activeClass = 'uk-active'; if(getParam) { let filterValue = getParameterByName('filter'); for (let item of filters) { document.getElementById(item.id).classList.remove(activeClass); if(item.id.indexOf('tag'+filterValue) >= 0) { document.getElementById(item.id).classList.add(activeClass); } } } else { for (let item of filters) { if(item.className.indexOf(activeClass) >= 0) { setParameterByName('filter',item.id.substring(3,item.id.length)); } } } } export default Component.extend({ actions: { queryChanged(query) { this.get('queryChanged')(query); } }, didRender() { filterParam(true); }, click() { filterParam(false); } });
<gh_stars>0 import { CATALOG, MANAGEMENT } from '@shell/config/types'; import { getVendor } from '@shell/config/private-label'; import { SETTING } from '@shell/config/settings'; import { findBy } from '@shell/utils/array'; import { createCssVars } from '@shell/utils/color'; export default { async fetch() { if ( this.$store.getters['management/canList'](CATALOG.APP) ) { this.apps = await this.$store.dispatch('management/findAll', { type: CATALOG.APP }); } }, data() { return { apps: [] }; }, computed: { globalSettings() { return this.$store.getters['management/all'](MANAGEMENT.SETTING); }, brand() { const setting = findBy(this.globalSettings, 'id', SETTING.BRAND); return setting?.value; }, color() { const setting = findBy(this.globalSettings, 'id', SETTING.PRIMARY_COLOR); return setting?.value; }, linkColor() { const setting = findBy(this.globalSettings, 'id', SETTING.LINK_COLOR); return setting?.value; }, theme() { const setting = findBy(this.globalSettings, 'id', SETTING.THEME); // This handles cases where the settings update after the page loads (like on log out) if (setting?.value) { return setting?.value; } return this.$store.getters['prefs/theme']; }, cspAdapter() { return findBy(this.apps, 'metadata.name', 'csp-adapter' ); } }, watch: { color(neu) { if (neu) { this.setCustomColor(neu); } else { this.removeCustomColor(); } }, linkColor(neu) { if (neu) { this.setCustomColor(neu, 'link'); } else { this.removeCustomColor('link'); } }, theme() { if (this.color) { this.setCustomColor(this.color); } if (this.linkColor) { this.setCustomColor(this.linkColor, 'link'); } }, cspAdapter(neu) { if (neu && !this.brand) { const brandSetting = findBy(this.globalSettings, 'id', SETTING.BRAND); if (brandSetting) { brandSetting.value = 'suse'; brandSetting.save(); } else { const schema = this.$store.getters['management/schemaFor'](MANAGEMENT.SETTING); const url = schema?.linkFor('collection'); if (url) { this.$store.dispatch('management/create', { type: MANAGEMENT.SETTING, metadata: { name: SETTING.BRAND }, value: 'suse', default: '' }).then(setting => setting.save()); } } } else if (!neu) { const brandSetting = findBy(this.globalSettings, 'id', SETTING.BRAND); if (brandSetting) { brandSetting.value = ''; brandSetting.save(); } } } }, methods: { setCustomColor(color, name = 'primary') { const vars = createCssVars(color, this.theme, name); for (const prop in vars) { document.body.style.setProperty(prop, vars[prop]); } }, removeCustomColor(name = 'primary') { const vars = createCssVars('rgb(0,0,0)', this.theme, name); for (const prop in vars) { document.body.style.removeProperty(prop); } } }, head() { let cssClass = `overflow-hidden dashboard-body`; const out = { bodyAttrs: { class: `theme-${ this.theme } ${ cssClass }` }, title: getVendor(), }; if (getVendor() === 'Harvester') { const ico = require(`~shell/assets/images/pl/harvester.png`); out.title = 'Harvester'; out.link = [{ hid: 'icon', rel: 'icon', type: 'image/x-icon', href: ico }]; } let brandMeta; if ( this.brand ) { try { brandMeta = require(`~shell/assets/brand/${ this.brand }/metadata.json`); } catch { return out; } } if (brandMeta?.hasStylesheet === 'true') { cssClass = `${ cssClass } ${ this.brand } theme-${ this.theme }`; } else { cssClass = `theme-${ this.theme } overflow-hidden dashboard-body`; this.$store.dispatch('prefs/setBrandStyle', this.theme === 'dark'); } out.bodyAttrs.class = cssClass; return out; }, };
from argparse import ArgumentParser import torch parser = ArgumentParser() parser.add_argument("--dataset_path", type=str, default="", help="Path or url of the dataset. If empty download from S3.") parser.add_argument("--dataset_cache", type=str, default='./dataset_cache', help="Path or url of the dataset cache") parser.add_argument("--model", type=str, default="openai-gpt", help="Model type (openai-gpt or gpt2)", choices=['openai-gpt', 'gpt2']) # anything besides gpt2 will load openai-gpt parser.add_argument("--model_checkpoint", type=str, default="", help="Path, url or short name of the model") parser.add_argument("--max_history", type=int, default=8, help="Number of previous utterances to keep in history") parser.add_argument("--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu", help="Device (cuda or cpu)") parser.add_argument("--no_sample", action='store_true', help="Set to use greedy decoding instead of sampling") parser.add_argument("--max_length", type=int, default=20, help="Maximum length of the output utterances") parser.add_argument("--min_length", type=int, default=1, help="Minimum length of the output utterances") parser.add_argument("--seed", type=int, default=0, help="Seed") parser.add_argument("--temperature", type=float, default=0.7, help="Sampling softmax temperature") parser.add_argument("--top_k", type=int, default=0, help="Filter top-k tokens before sampling (<=0: no filtering)") parser.add_argument("--top_p", type=float, default=0.9, help="Nucleus filtering (top-p) before sampling (<=0.0: no filtering)") parser.add_argument("--bias_method", type=str, default='cap', help="Method to bias the model probs. choices: ['naive', 'cap', 'scale']") parser.add_argument("--bias_cap", type=float, default=2.0, help="Caps the amount of word frequency bias") parser.add_argument("--bias_scale", type=float, default=1.0, help="constant by which to multiply the bias factor") parser.add_argument("--insert_qa_cond", type=str, default="retro", help="How/when to insert QA model's answer. choices: [`at_start`, `if_most_likely`, `retro`, `none`]") parser.add_argument("--qa_conf_thresh", type=float, default=0.5, help="Minimum score needed for qa output to be used") parser.add_argument("--username", type=str, default="BarackObama", help="(case-sensitive) Twitter username of interest.") parser.add_argument("--name", type=str, default="<NAME>", help="Name of interest, e.g. `<NAME>` or `rihanna`") parser.add_argument("--verbose", type=int, default="1") FLAGS = parser.parse_args()
#!/usr/bin/env zsh # WORKDIR: ../ (project root) # svg-term npx svg-term --window --in ./images/zsh-record.cast --out ./images/preview.svg # replace:font perl -i -pe 's/"Monaco,/"Menlo,Monaco,/g' ./images/preview.svg # replace:arrow perl -i -pe 's/➤/▶/g' ./images/preview.svg
import random while True: user_message = input('User: ') if user_message == 'hello': response_options = ['Hi', 'Hi there', 'Hello, how are you?', 'Hey there'] bot_response = random.choice(response_options) print(bot_response) elif user_message == 'exit': break
class BankAccount: def __init__(self, account_holder, initial_balance): self.account_holder = account_holder self.balance = initial_balance def deposit(self, amount): self.balance += amount def withdraw(self, amount): if self.balance >= amount: self.balance -= amount else: print("Insufficient funds") def get_balance(self): return self.balance def transfer(self, recipient, amount): if self.balance >= amount: self.balance -= amount recipient.deposit(amount) else: print("Insufficient funds")
package com.wing.spring.setInject; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.stereotype.Component; /** * Created by xsls on 2019/8/26. */ @Component public class TulingBeanDefiantionResigeter implements BeanDefinitionRegistryPostProcessor { @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(InstF.class); registry.registerBeanDefinition("instF",rootBeanDefinition); } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } }
var util = require("../../utils/helper.js"), utils = getApp().helper; Page({ data: { currency: 0, bout_ratio: 0, total_bout: 0, bout: 0, page: 2, list: [ { name: "" }, { step_num: 0 }, { user_currency: 0 }, { user_num: 0 }, { status: 0 } ] }, onReachBottom: function() { var e = this, i = e.data.over; if (!i) { var o = this.data.list, r = this.data.page; this.setData({ loading: !0 }), getApp().request({ url: getApp().api.step.activity_log, data: { page: r }, success: function(t) { for (var a = 0; a < t.data.list.length; a++) o.push(t.data.list[a]); t.data.list.length < 10 && (i = !0), e.setData({ list: o, page: r + 1, loading: !1, over: i }); } }); } }, onLoad: function(t) { getApp().page.onLoad(this, t); var r = this, a = util.formatTime(new Date()), s = a[0] + a[1] + a[2] + a[3] + a[5] + a[6] + a[8] + a[9]; getApp().core.showLoading({ title: "数据加载中...", mask: !0 }), getApp().request({ url: getApp().api.step.activity_log, success: function(t) { getApp().core.hideLoading(); var a = t.data.info, e = 0; 0 < a.currency && (e = a.currency); for (var i = t.data.list, o = 0; o < i.length; o++) null != i[o].open_date && (i[o].date = i[o].open_date.replace("-", "").replace("-", "")); r.setData({ currency: e, bout_ratio: a.bout_ratio, total_bout: a.total_bout, bout: a.bout, time: s, list: i }); } }); } });
import React, { Fragment, useEffect, useState } from 'react'; import { useSelector, useDispatch } from 'react-redux'; import { Bullseye, Flex, Spinner, TextContent, Text, TextVariants, TextList, TextListVariants, TextListItem, TextListItemVariants, Title, Grid, GridItem, Stack, StackItem, Card, CardBody } from '@patternfly/react-core'; import { Table, TableHeader, TableBody, sortable, SortByDirection, ISortBy, TableText } from '@patternfly/react-table'; import { DateFormat } from '@redhat-cloud-services/frontend-components/DateFormat'; import InfoIcon from '@patternfly/react-icons/dist/js/icons/info-icon'; import { fetchApprovalRequests } from '../../../redux/actions/order-actions'; import { fetchApprovalRequests as fetchApprovalRequestsS } from '../../../redux/actions/order-actions-s'; import ordersMessages from '../../../messages/orders.messages'; import statesMessages, { getTranslatableState } from '../../../messages/states.messages'; import labelMessages from '../../../messages/labels.messages'; import useFormatMessage from '../../../utilities/use-format-message'; import { AnyObject, ApiCollectionResponse, StringObject } from '../../../types/common-types'; import { ApprovalRequest, OrderItemStateEnum } from '@redhat-cloud-services/catalog-client'; import { CatalogRootState } from '../../../types/redux'; import { OrderDetail } from '../../../redux/reducers/order-reducer'; import orderStatusMapper from '../order-status-mapper'; import { MAX_RETRY_LIMIT } from '../../../utilities/constants'; import { delay, isStandalone } from '../../../helpers/shared/helpers'; /** * We are using type conversion of **request as StringObject** because the generated client does not have correct states listed * Probably a discrepancy inside the OpenAPI spec */ const rowOrder = ['updated', 'group_name', 'decision']; const checkRequest = async ( fetchRequests: () => Promise<ApiCollectionResponse<any>> ) => { // eslint-disable-next-line no-constant-condition let retries = 0; while (retries <= MAX_RETRY_LIMIT) { const result = await fetchRequests(); if (result?.data.length > 0 || retries++ >= MAX_RETRY_LIMIT) { return 'Finished'; } await delay(3000); } }; const isEmpty = (approvalRequest?: ApiCollectionResponse<ApprovalRequest>) => !approvalRequest || !approvalRequest.data || approvalRequest.data.length === 0; const fetchApprovalRequestsData = (id: string) => isStandalone() ? fetchApprovalRequestsS(id) : fetchApprovalRequests(id); const ApprovalRequests: React.ComponentType = () => { const formatMessage = useFormatMessage(); const dispatch = useDispatch(); const [sortBy, setSortBy] = useState<ISortBy>({}); const { order, approvalRequest, platform, orderItem, portfolio, portfolioItem } = useSelector<CatalogRootState, OrderDetail>( ({ orderReducer: { orderDetail } }) => orderDetail ); const [isFetching, setFetching] = useState(true); useEffect(() => { if (orderItem?.id && isEmpty(approvalRequest)) { setFetching(true); checkRequest(() => dispatch( (fetchApprovalRequestsData(orderItem.id!) as unknown) as Promise< ApiCollectionResponse<ApprovalRequest> > ) ).then(() => setFetching(false)); } }, []); const handleSort = ( _e: React.SyntheticEvent, index: number, direction: SortByDirection ) => setSortBy({ index, direction }); if (isEmpty(approvalRequest) && !isFetching) { return ( <Bullseye id="no-approval-requests"> <Flex direction={{ default: 'column' }} grow={{ default: 'grow' }}> <Bullseye> <InfoIcon size="xl" /> </Bullseye> <Bullseye> <Title headingLevel="h1" size="2xl"> {formatMessage(ordersMessages.noApprovalRequests)} </Title> </Bullseye> </Flex> </Bullseye> ); } const columns = [ { title: 'Updated', transforms: [sortable] }, { title: 'Name', transforms: [sortable] }, 'Decision' ]; const approvalRequestDecision = (request: StringObject) => orderStatusMapper[ (statesMessages[getTranslatableState(request.decision)].defaultMessage || 'Unknown') as keyof typeof orderStatusMapper ]; const rows = approvalRequest?.data .map((request) => rowOrder.map((key) => { if (key === 'decision') { return ( <TableText> <TextContent style={{ color: approvalRequestDecision(request as StringObject) .color }} > {approvalRequestDecision(request as StringObject).icon} &nbsp; {formatMessage( statesMessages[ getTranslatableState( (request as StringObject)[key] as OrderItemStateEnum ) ] )} </TextContent> </TableText> ); } if (key === 'updated') { /** * The fragment here is required other wise the super smart PF table will delete the first React element */ return ( <Fragment> <DateFormat date={(request as StringObject)[key]} type="exact" /> </Fragment> ); } return (request as AnyObject)[key]; }) ) .sort((a: AnyObject, b: AnyObject) => a[sortBy.index!] < b[sortBy.index!] ? -1 : a[sortBy.index!] < b[sortBy.index!] ? 1 : 0 ) || []; return ( <TextContent> {isEmpty(approvalRequest) ? ( <Bullseye> <Flex direction={{ default: 'column' }} grow={{ default: 'grow' }}> <Bullseye id="creating-approval-request"> <Title headingLevel="h1" size="xl"> {formatMessage(ordersMessages.creatingApprovalRequest)} </Title> </Bullseye> <Bullseye> <Spinner size="xl" /> </Bullseye> </Flex> </Bullseye> ) : ( <Grid hasGutter> <GridItem md={12} lg={6} xl={4}> <Stack hasGutter> <StackItem> <Card> <CardBody> <Text className="pf-u-mb-md" component={TextVariants.h2}> {formatMessage(ordersMessages.approvalTitle)} </Text> <TextList component={TextListVariants.dl}> <TextListItem component={TextListItemVariants.dt}> {formatMessage(labelMessages.product)} </TextListItem> <TextListItem component={TextListItemVariants.dd}> {portfolioItem.name} </TextListItem> <TextListItem component={TextListItemVariants.dt}> {formatMessage(ordersMessages.orderID)} </TextListItem> <TextListItem component={TextListItemVariants.dd}> {order.id} </TextListItem> <TextListItem component={TextListItemVariants.dt}> {formatMessage(ordersMessages.orderDate)} </TextListItem> <TextListItem component={TextListItemVariants.dd}> <DateFormat date={order.created_at} variant="relative" /> </TextListItem> <TextListItem component={TextListItemVariants.dt}> {formatMessage(ordersMessages.orderedByLabel)} </TextListItem> <TextListItem component={TextListItemVariants.dd}> {order.owner} </TextListItem> <TextListItem component={TextListItemVariants.dt}> {formatMessage(labelMessages.portfolio)} </TextListItem> <TextListItem component={TextListItemVariants.dd}> {portfolio.name} </TextListItem> <TextListItem component={TextListItemVariants.dt}> {formatMessage(labelMessages.platform)} </TextListItem> <TextListItem component={TextListItemVariants.dd}> {platform.name} </TextListItem> </TextList> </CardBody> </Card> </StackItem> <StackItem> <Card> <CardBody> <Text className="pf-u-mb-md" component={TextVariants.h2}> {formatMessage(ordersMessages.approvalParameters)} </Text> <TextList className="overflow-wrap" component={TextListVariants.dl} > {Object.entries(orderItem?.service_parameters || []).map( ([key, value]) => ( <Fragment key={key}> <TextListItem component={TextListItemVariants.dt}> {key} </TextListItem> <TextListItem component={TextListItemVariants.dd}> {value} </TextListItem> </Fragment> ) )} </TextList> </CardBody> </Card> </StackItem> </Stack> </GridItem> <GridItem md={12} lg={6} xl={8}> <Card> <CardBody> <Text className="pf-u-mb-md" component={TextVariants.h2}> {formatMessage(ordersMessages.activity)} </Text> <Table aria-label="Approval request activity" onSort={handleSort} sortBy={sortBy} cells={columns} rows={ sortBy.direction === SortByDirection.asc ? rows : rows.reverse() } > <TableHeader /> <TableBody /> </Table> </CardBody> </Card> </GridItem> </Grid> )} </TextContent> ); }; export default ApprovalRequests;