repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
ReachVignesh/PopDeemTest | photoprint_v1_1/src/main/java/jsoft/projects/photoclick/FbPhotos.java | package jsoft.projects.photoclick;
import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.MatrixCursor;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.*;
import android.widget.CompoundButton.OnCheckedChangeListener;
import com.facebook.Session;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import jsoft.projects.photoclick.cart.ShoppingCart;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import util.DpsControlApplication;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.Random;
public class FbPhotos extends BaseActivity {
int counter=0;
String imgPath = null;
String upLoadServerUri = "http://photoclick.arion.kz/photo_android/UploadToServer.php";
String lineEnd = "\r\n";
String twoHypens = "--";
String boundary = "*****";
TextView tvMulMsg;
private ArrayList<String> selectedItems;
private ArrayList<String> imageIds;
private ArrayList<String> imageUrls;
private DisplayImageOptions options;
private ImageAdapter imageAdapter;
private ProgressDialog dialog = null;
private String albumId;
Context context;
TextView count_price;
DpsControlApplication selection;
String free;
private static ArrayList<String> fbImages;
Session session;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_image_grid);
selection = (DpsControlApplication)getApplication();
context = this;
Bundle extras = getIntent().getExtras();
albumId = extras.getString("albumId");
count_price=(TextView)findViewById(R.id.count_price);
session = new Session(getApplicationContext());
DpsControlApplication.exception_handler_home(this);
ActionBar actionBar = getActionBar();
assert actionBar != null;
actionBar.setDisplayHomeAsUpEnabled(true);
tvMulMsg = (TextView) findViewById(R.id.tvMulMsg);
count_price = (TextView) findViewById(R.id.count_price);
if(selection.getPreferences().getString("free","0").equalsIgnoreCase("btnfree")) {
count_price .setVisibility(View.INVISIBLE);
} else if (selection.getPreferences().getString("pay","0").equalsIgnoreCase("btnpay"))
{
count_price .setVisibility(View.VISIBLE);
}
// if(selection.getPreferences().getString("pay","0").equalsIgnoreCase("btnpay")) {
// count_price .setVisibility(View.VISIBLE);
// } else
// {
// count_price .setVisibility(View.INVISIBLE);
// }
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
String url = "https://graph.facebook.com/" + albumId + "/photos?limit=500&offset=0&fields=images&access_token=" + session.getAccessToken();
// String url = "https://graph.facebook.com/" + albumId + "/photos?limit=500&offset=0&until=yesterday&fields=images&access_token=" + session.getAccessToken();
try {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
String algorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(algorithm);
tmf.init(keyStore);
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpEntity.getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
String jString = "[" + builder.toString() + "]";
JSONArray jsonArray = new JSONArray(jString);
String temp = jsonArray.getJSONObject(0).get("data").toString();
JSONArray jsonAlbumsArray = new JSONArray(temp);
MatrixCursor mcImages = new MatrixCursor(new String[] { "source", "id" }); // properties from the JSONObjects
for (int i = 0; i < jsonAlbumsArray.length(); i++) {
JSONObject jo = jsonAlbumsArray.getJSONObject(i);
JSONArray ja = jo.getJSONArray("images");
JSONObject joImages = ja.getJSONObject(0);
mcImages.addRow(new Object[] { joImages.get("source"),
jo.get("id") });
}
this.imageUrls = new ArrayList<String>();
this.imageIds = new ArrayList<String>();
String tempUrl;
for (int i = 0; i < mcImages.getCount(); i++) {
mcImages.moveToPosition(i);
int dataColumnIndex = mcImages.getColumnIndex("source");
tempUrl = mcImages.getString(dataColumnIndex);
//images = LoadImageFromWebOperations(temp);
imageUrls.add(tempUrl);
dataColumnIndex = mcImages.getColumnIndex("id");
imageIds.add(mcImages.getString(dataColumnIndex));
}
mcImages.close();
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.stub_image)
.showImageForEmptyUri(R.drawable.image_for_empty_url)
.cacheInMemory().cacheOnDisc().build();
imageAdapter = new ImageAdapter(this, imageUrls);
GridView gridView = (GridView) findViewById(R.id.gridview);
gridView.setAdapter(imageAdapter);
} catch (Exception e) {
e.printStackTrace();
}
Button button = (Button) findViewById(R.id.btnViewImg);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
btnChoosePhotosClick(v);
}
});
}
public void getcount(){
selectedItems = imageAdapter .getCheckedItems();
int value = 30 * selectedItems.size();
count_price.setText((getResources().getString(R.string.price))+value);
SharedPreferences.Editor edit = selection.getPreferences().edit();
edit.putString("Amt",(getResources().getString(R.string.price))+value);
edit.commit();
}
@Override
protected void onStop() {
imageLoader.stop();
super.onStop();
}
public static Drawable LoadImageFromWebOperations(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
return null;
}
}
public void btnChoosePhotosClick(View v) {
fbImages = new ArrayList<String>();
// selectedItems = imageAdapter .getCheckedItems();
final ArrayList<String> selectedItems = imageAdapter.getCheckedItems();
// selectedItems = imageAdapter .getCheckedItems();
if(selection.getPreferences().getString("free","").equalsIgnoreCase("btnfree")) {
if(selectedItems.size()>4 && selectedItems.size()<26){
dialog = ProgressDialog.show(FbPhotos.this, "",(getResources().getString(R.string.on_progress)), true);
new Thread(new Runnable() {
public void run() {
new DownloadFileFromURL().execute(selectedItems.toArray());
}
}).start();
}else {
Toast.makeText(context,(getResources().getString(R.string.free_toast)), Toast.LENGTH_LONG).show();
}
} else {
if(selectedItems.size()>0){
dialog = ProgressDialog.show(FbPhotos.this, "", (getResources().getString(R.string.on_progress)), true);
new Thread(new Runnable() {
public void run() {
new DownloadFileFromURL().execute(selectedItems.toArray());
}
}).start();
}else {
Toast.makeText(context,(getResources().getString(R.string.paid_toast)), Toast.LENGTH_LONG).show();
}
}
/*dialog = ProgressDialog.show(FbPhotos.this, "", "On Progress...",
true);
new Thread(new Runnable() {
public void run() {
new DownloadFileFromURL().execute(selectedItems.toArray());
}
}).start();*/
}
public class ImageAdapter extends BaseAdapter {
ArrayList<String> mList;
LayoutInflater mInflater;
Context mContext;
SparseBooleanArray msparseBooleanArray;
public ImageAdapter(Context context, ArrayList<String> imageUrls) {
mContext = context;
mInflater = LayoutInflater.from(mContext);
msparseBooleanArray = new SparseBooleanArray();
mList = new ArrayList<String>();
this.mList = imageUrls;
imageLoader.init(ImageLoaderConfiguration.createDefault(context));
}
public ArrayList<String> getCheckedItems() {
ArrayList<String> mTempArray = new ArrayList<String>();
for (int i = 0; i < mList.size(); i++) {
if (msparseBooleanArray.get(i)) {
mTempArray.add(mList.get(i));
}
}
return mTempArray;
}
// public void clearAllCheckedItems(){
// for (int i = 0; i < mList.size(); i++) {
// if (msparseBooleanArray.get(i)) {
// mTempArray.add(mList.get(i));
// }
// }
// }
@Override
public int getCount() {
return imageUrls.size();
}
@Override
public Object getItem(int position) { // argument is position
return null;
}
@Override
public long getItemId(int position) { // argument is position
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_multiphoto_item,
null);
}
final CheckBox mCheckBox = (CheckBox) convertView
.findViewById(R.id.checkBox1);
final ImageView imageView = (ImageView) convertView
.findViewById(R.id.imageView1);
imageLoader.displayImage("" + imageUrls.get(position), imageView,
options, new SimpleImageLoadingListener() {
// @Override
public void onLoadingComplete(Bitmap loadedImage) {
Animation anim = AnimationUtils.loadAnimation(
FbPhotos.this, R.anim.fade_in);
imageView.setAnimation(anim);
anim.start();
}
});
imageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
boolean flag = (mCheckBox.isChecked()) ? false : true;
mCheckBox.setChecked(flag);
}
});
mCheckBox.setTag(position);
mCheckBox.setChecked(msparseBooleanArray.get(position));
mCheckBox.setOnCheckedChangeListener(mCheckedChangeListener);
return convertView;
}
OnCheckedChangeListener mCheckedChangeListener = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
msparseBooleanArray.put((Integer) buttonView.getTag(),
isChecked);
getcount();
}
};
}
class DownloadFileFromURL extends AsyncTask<Object, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(Object... params) {
int count;
File directory = new File(Environment.getExternalStorageDirectory(),"/fb_images");
if(directory.exists() == false)
{
directory.mkdir();
}
for(int i = 0; i<params.length; i++){
try{
URL url = new URL(params[i].toString());
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
String imgName = randString(5);
File fileName = new File(directory+"/fb_image"+imgName+".jpg");
fbImages.add(fileName.toString());
// Log.d("Facebook Images",randString(3));
OutputStream output = new FileOutputStream(fileName);
// counter++;
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch(MalformedURLException e){
e.printStackTrace();
} catch(ClientProtocolException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
//pDialog.setProgress(Integer.parseInt(progress[0]));
super.onProgressUpdate(progress);
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
@Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
//dismissDialog(progress_bar_type);
// Displaying downloaded image into image view
// Reading image path from sdcard
// UploadFile(selectedItems);
Log.d("Image Urls at page No 413 of FbPhotos", fbImages.toString());
ShoppingCart cart = new ShoppingCart(FbPhotos.this);
cart.addToCart(fbImages);
// if(fbImages.size()>0){
// Intent iDetails = new Intent(FbPhotos.this, Details.class);
// iDetails.putExtra("fbImgs", true);
// startActivity(iDetails);
// dialog.dismiss();
// }else {
// Toast.makeText(context, "Not a single image selected", Toast.LENGTH_SHORT).show();
// }
Intent iDetails = new Intent(FbPhotos.this, DetailsFb.class);
iDetails.putExtra("fbImgs", true);
startActivity(iDetails);
dialog.dismiss();
}
}
public static void DeleteFbImages(){
for(int i=0 ;i< fbImages.size();i++){
String delImg = Environment.getExternalStorageDirectory().toString()+"/fb_images/fb_image"+i+".jpg";
DeleteFile(delImg);
}
File path = new File (Environment.getExternalStorageDirectory().toString()+"/fb_images");
if(path.exists()){
path.delete();
}
}
public static void DeleteFile(String fileName){
File file = new File(fileName);
if(!file.exists()){
System.out.println("not exists");
return;
}
if(!file.isDirectory()){
System.out.println("Deleted");
file.delete();
return;
}
}
@Override
public boolean onOptionsItemSelected(MenuItem menuItem)
{
finish();
Intent i = new Intent(this, FbGallery.class);
startActivity(i);
return true;
}
public static String randString(int length)
{
Random rnd = new Random();
String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
char[] text = new char[length];
for (int i = 0; i < length; i++)
{
text[i] = characters.charAt(rnd.nextInt(characters.length()));
}
return new String(text);
}
} |
odalabasmaz/awsgenie | resource-terminator/src/test/java/io/github/odalabasmaz/awsgenie/terminator/TerminatorHelper.java | <reponame>odalabasmaz/awsgenie
package io.github.odalabasmaz.awsgenie.terminator;
import io.github.odalabasmaz.awsgenie.fetcher.credentials.AWSClientConfiguration;
public class TerminatorHelper {
public static AWSClientConfiguration getRegion1Account1Configuration() {
return new AWSClientConfiguration() {
@Override
public String getAssumeRoleArn() {
return "account1";
}
@Override
public String getRegion() {
return "region1";
}
};
}
public static AWSClientConfiguration getRegion2Account2Configuration() {
return new AWSClientConfiguration() {
@Override
public String getAssumeRoleArn() {
return "account2";
}
@Override
public String getRegion() {
return "region2";
}
};
}
}
|
djmott/xtl | docs/html/classxtd_1_1var_1_1inner__base.js | var classxtd_1_1var_1_1inner__base =
[
[ "ptr", "classxtd_1_1var_1_1inner__base.html#ace126bd1d08b32c204ab02995ce6b27d", null ],
[ "~inner_base", "classxtd_1_1var_1_1inner__base.html#a3bb02ede86122fc9f5cd3d190849d7fe", null ],
[ "inner_base", "classxtd_1_1var_1_1inner__base.html#a412a8af2e167d7acca976bb7bfdbc52c", null ],
[ "inner_base", "classxtd_1_1var_1_1inner__base.html#a77e5074a44c5529dd05388fad6182076", null ],
[ "clone", "classxtd_1_1var_1_1inner__base.html#a5dc8674827163254c853b7b185c87b14", null ],
[ "get_type", "classxtd_1_1var_1_1inner__base.html#a3504b2e0daad7b7066caa8c40eb841cc", null ],
[ "is_pod", "classxtd_1_1var_1_1inner__base.html#a152dddad51984ff93ddfb27bf5056849", null ],
[ "operator=", "classxtd_1_1var_1_1inner__base.html#aa9ba9eabcbd318ff04fe00a03592f8ad", null ],
[ "size", "classxtd_1_1var_1_1inner__base.html#a2d34009db087c7d63ed2d19cf5baf028", null ]
]; |
galahq/gala | spec/policies/forum_policy_spec.rb | <reponame>galahq/gala
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe ForumPolicy, type: :policy do
subject { described_class }
describe 'Scope' do
it 'includes the forums the reader can participate in' do
reader = create :reader
kase = create :case
global_forum = kase.forums.merge(GlobalCommunity.instance.forums).first
create :enrollment, case: kase, reader: reader
my_group = create :group, name: 'My Group'
create :group_membership, :admin, group: my_group, reader: reader
create :deployment, group: my_group, case: kase
my_forum = kase.forums.merge(my_group.community.forums).first
scope = ForumPolicy::Scope.new(reader, Forum).resolve
expect(scope).to include global_forum, my_forum
end
it 'includes no forums if the user is not enrolled in the case' do
reader = create :reader
kase = create :case
global_forum = kase.forums.merge(GlobalCommunity.instance.forums).first
my_group = create :group, name: 'My Group'
create :group_membership, :admin, group: my_group, reader: reader
create :deployment, group: my_group, case: kase
my_forum = kase.forums.merge(my_group.community.forums).first
scope = ForumPolicy::Scope.new(reader, Forum).resolve
expect(scope).not_to include global_forum, my_forum
end
end
permissions :show? do
it 'allows a reader who is enrolled in the case to read the Global ' \
'Community’s forum' do
reader = create :reader
kase = create :case
global_forum = kase.forums.merge(GlobalCommunity.instance.forums).first
create :enrollment, case: kase, reader: reader
expect(subject).to permit reader, global_forum
end
it 'allows a reader who is enrolled in the case to read the forum of a ' \
'community they belong to' do
reader = create :reader
kase = create :case
create :enrollment, case: kase, reader: reader
my_group = create :group, name: 'My Group'
create :group_membership, :admin, group: my_group, reader: reader
create :deployment, group: my_group, case: kase
my_forum = kase.forums.merge(my_group.community.forums).first
expect(subject).to permit reader, my_forum
end
it 'does not allow a reader who is enrolled to read the forum of a '\
'different community' do
reader = create :reader
kase = create :case
create :enrollment, case: kase, reader: reader
other_group = create :group, name: 'My Group'
create :deployment, group: other_group, case: kase
other_forum = kase.forums.merge(other_group.community.forums).first
expect(subject).not_to permit reader, other_forum
end
it 'does not allow a reader who is not enrolled to read the Global ' \
'Community’s forum' do
reader = create :reader
kase = create :case
global_forum = kase.forums.merge(GlobalCommunity.instance.forums).first
expect(subject).not_to permit reader, global_forum
end
end
permissions :moderate? do
it 'denies a normal reader from moderating forums' do
reader = build :reader
forum = build :forum
expect(subject).not_to permit reader, forum
end
it 'permits case authors to moderate the global community forum ' \
'for their case' do
kase = create :case
author = build :reader
kase.editorships.create editor: author
forum = build :forum, case: kase
expect(subject).to permit author, forum
end
it 'denies case authors from moderating non-global forums ' \
'on their case' do
kase = create :case
author = build :reader
kase.editorships.create editor: author
forum = build :forum, :with_community, case: kase
expect(subject).not_to permit author, forum
end
it 'denies case authors from moderating the global community forum ' \
'on someone else’s case' do
kase = create :case
author = build :reader
kase.editorships.create editor: author
author2 = build :reader
kase2 = create :case
kase2.editorships.create editor: author2
forum = build :forum, case: kase2
expect(subject).not_to permit author, forum
end
it 'permits group admins to moderate their community’s forums' do
admin = build :reader
group = build :group
create :group_membership, :admin, group: group, reader: admin
kase = build :case
community = build :community, group: group
forum = build :forum, case: kase, community: community
expect(subject).to permit admin, forum
end
it 'denies group admins from moderating other forums' do
admin = build :reader
group = build :group
create :group_membership, :admin, group: group, reader: admin
kase = build :case
forum = build :forum, case: kase
expect(subject).not_to permit admin, forum
end
it 'allows editors to moderate any forum' do
editor = build :reader, :editor
forum = build :forum
expect(subject).to permit editor, forum
end
end
end
|
vu-luong/ezyhttp | ezyhttp-server-graphql/src/test/java/com/tvd12/ezyhttp/server/graphql/test/datafetcher/GraphQLWelcomeDataFetcher.java | package com.tvd12.ezyhttp.server.graphql.test.datafetcher;
import com.tvd12.ezyfox.bean.annotation.EzySingleton;
import com.tvd12.ezyhttp.server.graphql.GraphQLDataFetcher;
import com.tvd12.ezyhttp.server.graphql.test.datafetcher.GraphQLWelcomeDataFetcher.WelcomeRequest;
import lombok.Data;
@EzySingleton
public class GraphQLWelcomeDataFetcher implements GraphQLDataFetcher<WelcomeRequest, String> {
public String getData(WelcomeRequest argument) {
return "Welcome " + argument.getName();
}
@Override
public String getQueryName() {
return "welcome";
}
@Data
public static class WelcomeRequest {
private String name;
}
}
|
Taeir/aidm-optimal-groups | src/main/java/nl/tudelft/aidm/optimalgroups/metric/matching/gini/GiniCoefficientStudentRank.java | package nl.tudelft.aidm.optimalgroups.metric.matching.gini;
import nl.tudelft.aidm.optimalgroups.metric.rank.AssignedRank;
import nl.tudelft.aidm.optimalgroups.metric.rank.WorstAssignedRank;
import nl.tudelft.aidm.optimalgroups.model.agent.Agent;
import nl.tudelft.aidm.optimalgroups.model.group.Group;
import nl.tudelft.aidm.optimalgroups.model.matching.Match;
import nl.tudelft.aidm.optimalgroups.model.matching.Matching;
import nl.tudelft.aidm.optimalgroups.model.project.Project;
import java.io.PrintStream;
import java.util.stream.Collectors;
public class GiniCoefficientStudentRank implements GiniCoefficient
{
private final double giniCoefficient;
public GiniCoefficientStudentRank(Matching<Agent, Project> matching)
{
int worstRank = new WorstAssignedRank.ProjectToStudents(matching).asInt();
var welfare = matching.asList().stream()
.map(match -> match.from().projectPreference().rankOf(match.to()))
.filter(rank -> rank.isPresent() || rank.unacceptable())
// flip rank to income (good rank -> higher income) and handle unacceptibles by assigned them income = 0
.map(rank -> rank.unacceptable() ? 0 : worstRank - rank.asInt() + 1)
.collect(Collectors.toList());
var sumAbsDiff = welfare.stream().flatMap(i ->
welfare.stream().map(j ->
Math.abs(i - j)
))
.mapToInt(Integer::intValue) // for sum method of IntStream
.sum();
int n = welfare.size();
int sum = welfare.stream().mapToInt(Integer::intValue).sum();
this.giniCoefficient = sumAbsDiff / (2.0 * n * sum);
}
public Double asDouble()
{
return this.giniCoefficient;
}
public void printResult(PrintStream printStream)
{
printStream.printf("Gini-coef over student ranks: %f\n", asDouble());
}
}
|
dbonino/diozero | diozero-core/src/test/java/com/diozero/util/SchedulerTest.java | package com.diozero.util;
/*
* #%L
* Organisation: diozero
* Project: Device I/O Zero - Core
* Filename: SchedulerTest.java
*
* This file is part of the diozero project. More information about this project
* can be found at http://www.diozero.com/
* %%
* Copyright (C) 2016 - 2021 diozero
* %%
* 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.
* #L%
*/
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class SchedulerTest {
static int scheduler_instance = 0;
static long last_call = 0;
public static void main(String[] args) {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1, new DaemonThreadFactory());
ScheduledFuture<?> future = scheduler.scheduleAtFixedRate(() -> {
long now = System.currentTimeMillis();
long diff = now - last_call;
last_call = now;
System.out.format("Thread: %s, Time between calls: %d%n", Thread.currentThread().getName(),
Long.valueOf(diff));
} , 100, 100, TimeUnit.MILLISECONDS);
SleepUtil.sleepSeconds(5);
future.cancel(true);
scheduler.shutdownNow();
System.out.println("Finished");
}
}
class DaemonThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
DaemonThreadFactory() {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
namePrefix = "daemon-pool-" + poolNumber.getAndIncrement() + "-thread-";
}
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
t.setDaemon(true);
return t;
}
}
|
impira/yugabyte-db | managed/src/main/java/com/yugabyte/yw/forms/PagedRequestFormData.java | <gh_stars>1000+
// Copyright (c) YugaByte, Inc.
package com.yugabyte.yw.forms;
import play.data.validation.Constraints;
public class PagedRequestFormData<F, S> {
@Constraints.Required() public F filter;
@Constraints.Required() public S sortBy;
@Constraints.Required() public int offset;
@Constraints.Required() public int limit;
}
|
sindaZeng/XHuiCloud | XHuiCloud-upms/XHuiCloud-upms-service/src/main/java/com/xhuicloud/upms/controller/SysMenuController.java | /*
* MIT License
* Copyright <2021-2022>
*
* 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.
* @Author: Sinda
* @Email: <EMAIL>
*/
package com.xhuicloud.upms.controller;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xhuicloud.common.core.utils.Response;
import com.xhuicloud.common.log.annotation.SysLog;
import com.xhuicloud.common.security.utils.SecurityHolder;
import com.xhuicloud.upms.dto.MenuTree;
import com.xhuicloud.upms.entity.SysMenu;
import com.xhuicloud.upms.service.SysMenuService;
import com.xhuicloud.upms.utils.TreeUtil;
import com.xhuicloud.upms.vo.MenuVo;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @program: XHuiCloud
* @description: SysMenuController
* @author: Sinda
* @create: 2020-01-02 23:26
*/
@RestController
@RequestMapping("/menu")
@AllArgsConstructor
@Api(value = "menu", tags = "菜单管理模块")
public class SysMenuController {
private final SysMenuService sysMenuService;
/**
* 返回当前用户的树形菜单集合
*
* @return 当前用户的树形菜单
*/
@GetMapping
public Response getUserMenu() {
Set<MenuVo> all = new HashSet<>();
SecurityHolder.getRoles()
.forEach(roleCode -> all.addAll(sysMenuService.findMenuByRoleCode(roleCode)));
List<MenuTree> menuTreeList = all.stream()
.filter(menuVo -> 0 == menuVo.getType())
.map(MenuTree::new)
.sorted(Comparator.comparingInt(MenuTree::getSort))
.collect(Collectors.toList());
return Response.success(TreeUtil.build(menuTreeList, 0));
}
/**
* 返回角色的菜单集合
*
* @param roleId
* @return
*/
@GetMapping("/tree/{roleId}")
public Response getRoleTree(@PathVariable Integer roleId) {
return Response.success(sysMenuService.findMenuByRoleId(roleId)
.stream()
.map(MenuVo::getId)
.collect(Collectors.toList()));
}
/**
* 树形菜单
*
* @return
*/
@GetMapping(value = "/tree")
public Response getMenuTree(@RequestParam Boolean disabled) {
return Response.success(TreeUtil.buildMenuTree(disabled, sysMenuService
.list(Wrappers.<SysMenu>lambdaQuery()
.orderByAsc(SysMenu::getSort)), 0));
}
/**
* 新增菜单
*
* @param sysMenu
* @return
*/
@SysLog("新增菜单")
@PostMapping
@PreAuthorize("@authorize.hasPermission('sys_add_menu')")
public Response save(@Valid @RequestBody SysMenu sysMenu) {
return Response.success(sysMenuService.saveMenu(sysMenu));
}
/**
* 禁用,启用 菜单
*
* @param id
* @return
*/
@SysLog("开启禁用菜单")
@DeleteMapping("/{id}")
@PreAuthorize("@authorize.hasPermission('sys_delete_menu')")
public Response delete(@PathVariable Integer id) {
return Response.success(sysMenuService.deleteMenu(id));
}
/**
* 编辑菜单
*
* @param sysMenu
* @return
*/
@SysLog("编辑菜单")
@PutMapping
@PreAuthorize("@authorize.hasPermission('sys_editor_menu')")
public Response update(@Valid @RequestBody SysMenu sysMenu) {
return Response.success(sysMenuService.updateMenu(sysMenu));
}
}
|
VirusTrack/COVIDvu | work/test/covidvu/pipeline/test_vuregions.py | #!/usr/bin/env python3
# See: https://github.com/VirusTrack/COVIDvu/blob/master/LICENSE
# vim: set fileencoding=utf-8:
from covidvu.pipeline.vuregions import main
import json
import os
# --- constants ---
TEST_BUNDLE_OUTPUT_FILE_NAME = 'bundle-test-regions.json'
TEST_MASTER_DATABASE = os.path.join('./resources/test_databases', 'test-virustrack.db')
TEST_SITE_DATA = './resources/test_pipeline'
# +++ tests +++
def test_main():
bundle, \
bundleFileName = main(TEST_MASTER_DATABASE, TEST_SITE_DATA, TEST_BUNDLE_OUTPUT_FILE_NAME)
assert bundle
assert isinstance(bundle, dict)
assert 'confirmed' in bundle
assert 'North America' in bundle['confirmed']
assert os.path.exists(bundleFileName)
altBundle = json.load(open(bundleFileName, 'r'))
assert bundle['confirmed'].keys() == altBundle['confirmed'].keys()
os.unlink(bundleFileName)
test_main()
|
GammaCodeX/Advent2018 | 5/parser.rb | <filename>5/parser.rb
class Parser
def self.parse text
text.each_char.reduce([]) do |acc, char|
if(acc.last == char.swapcase)
acc.pop
else
acc.push char
end
acc
end.join
end
end
|
tizzen33/core | homeassistant/components/notion/binary_sensor.py | """Support for Notion binary sensors."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Literal
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_CONNECTIVITY,
DEVICE_CLASS_DOOR,
DEVICE_CLASS_GARAGE_DOOR,
DEVICE_CLASS_MOISTURE,
DEVICE_CLASS_SMOKE,
DEVICE_CLASS_WINDOW,
BinarySensorEntity,
BinarySensorEntityDescription,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ENTITY_CATEGORY_DIAGNOSTIC
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from . import NotionEntity
from .const import (
DATA_COORDINATOR,
DOMAIN,
LOGGER,
SENSOR_BATTERY,
SENSOR_DOOR,
SENSOR_GARAGE_DOOR,
SENSOR_LEAK,
SENSOR_MISSING,
SENSOR_SAFE,
SENSOR_SLIDING,
SENSOR_SMOKE_CO,
SENSOR_WINDOW_HINGED_HORIZONTAL,
SENSOR_WINDOW_HINGED_VERTICAL,
)
@dataclass
class NotionBinarySensorDescriptionMixin:
"""Define an entity description mixin for binary and regular sensors."""
on_state: Literal["alarm", "critical", "leak", "not_missing", "open"]
@dataclass
class NotionBinarySensorDescription(
BinarySensorEntityDescription, NotionBinarySensorDescriptionMixin
):
"""Describe a Notion binary sensor."""
BINARY_SENSOR_DESCRIPTIONS = (
NotionBinarySensorDescription(
key=SENSOR_BATTERY,
name="Low Battery",
device_class=DEVICE_CLASS_BATTERY,
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
on_state="critical",
),
NotionBinarySensorDescription(
key=SENSOR_DOOR,
name="Door",
device_class=DEVICE_CLASS_DOOR,
on_state="open",
),
NotionBinarySensorDescription(
key=SENSOR_GARAGE_DOOR,
name="Garage Door",
device_class=DEVICE_CLASS_GARAGE_DOOR,
on_state="open",
),
NotionBinarySensorDescription(
key=SENSOR_LEAK,
name="Leak Detector",
device_class=DEVICE_CLASS_MOISTURE,
on_state="leak",
),
NotionBinarySensorDescription(
key=SENSOR_MISSING,
name="Missing",
device_class=DEVICE_CLASS_CONNECTIVITY,
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
on_state="not_missing",
),
NotionBinarySensorDescription(
key=SENSOR_SAFE,
name="Safe",
device_class=DEVICE_CLASS_DOOR,
on_state="open",
),
NotionBinarySensorDescription(
key=SENSOR_SLIDING,
name="Sliding Door/Window",
device_class=DEVICE_CLASS_DOOR,
on_state="open",
),
NotionBinarySensorDescription(
key=SENSOR_SMOKE_CO,
name="Smoke/Carbon Monoxide Detector",
device_class=DEVICE_CLASS_SMOKE,
on_state="alarm",
),
NotionBinarySensorDescription(
key=SENSOR_WINDOW_HINGED_HORIZONTAL,
name="Hinged Window",
device_class=DEVICE_CLASS_WINDOW,
on_state="open",
),
NotionBinarySensorDescription(
key=SENSOR_WINDOW_HINGED_VERTICAL,
name="Hinged Window",
device_class=DEVICE_CLASS_WINDOW,
on_state="open",
),
)
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Set up Notion sensors based on a config entry."""
coordinator = hass.data[DOMAIN][entry.entry_id][DATA_COORDINATOR]
async_add_entities(
[
NotionBinarySensor(
coordinator,
task_id,
sensor["id"],
sensor["bridge"]["id"],
sensor["system_id"],
description,
)
for task_id, task in coordinator.data["tasks"].items()
for description in BINARY_SENSOR_DESCRIPTIONS
if description.key == task["task_type"]
and (sensor := coordinator.data["sensors"][task["sensor_id"]])
]
)
class NotionBinarySensor(NotionEntity, BinarySensorEntity):
"""Define a Notion sensor."""
entity_description: NotionBinarySensorDescription
@callback
def _async_update_from_latest_data(self) -> None:
"""Fetch new state data for the sensor."""
task = self.coordinator.data["tasks"][self._task_id]
if "value" in task["status"]:
state = task["status"]["value"]
elif task["status"].get("insights", {}).get("primary"):
state = task["status"]["insights"]["primary"]["to_state"]
else:
LOGGER.warning("Unknown data payload: %s", task["status"])
state = None
self._attr_is_on = self.entity_description.on_state == state
|
Canglangweiwei/CatEye | app/src/main/java/com/cicinnus/cateye/module/cinema/cinema_detail/adapter/MovieDateAdapter.java | <filename>app/src/main/java/com/cicinnus/cateye/module/cinema/cinema_detail/adapter/MovieDateAdapter.java
package com.cicinnus.cateye.module.cinema.cinema_detail.adapter;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.TextView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.cicinnus.cateye.R;
import com.cicinnus.cateye.module.cinema.cinema_detail.bean.CinemaMovieBean;
import com.cicinnus.retrofitlib.utils.TimeUtil;
import com.cicinnus.retrofitlib.utils.UIUtils;
import java.util.List;
/**
* Created by Cicinnus on 2017/6/22.
*/
public class MovieDateAdapter extends BaseQuickAdapter<CinemaMovieBean.DataBean.MoviesBean.ShowsBean, BaseViewHolder> {
private int selectedPos = 0;
private OnMovieDateClickListener onMovieDateClickListener;
public MovieDateAdapter() {
super(R.layout.item_movie_date);
}
@Override
public void setNewData(@Nullable List<CinemaMovieBean.DataBean.MoviesBean.ShowsBean> data) {
super.setNewData(data);
if (data != null) {
data.get(0).isSelect = true;
for (int i = 1; i < data.size(); i++) {
data.get(i).isSelect = false;
}
selectedPos = 0;
}
}
@Override
protected void convert(final BaseViewHolder helper, final CinemaMovieBean.DataBean.MoviesBean.ShowsBean item) {
int index = TimeUtil.dayForWeek(item.getShowDate());
int currentIndex = TimeUtil.dayForWeek(TimeUtil.dateYMD(System.currentTimeMillis()));
String dateText;
if (index == currentIndex) {
dateText = "今天";
} else if (index == currentIndex + 1) {
dateText = "明天";
} else if (index == currentIndex + 2) {
dateText = "后天";
} else {
dateText = switchDate(index);
}
helper.setText(R.id.tv_date, String.format("%s%s%s", dateText,
item.getShowDate().substring(5, item.getShowDate().length())
.replace("-", "月"), "日")).
setVisible(R.id.view_indicator, item.isSelect).
setTextColor(R.id.tv_date, item.isSelect ? mContext.getResources().getColor(R.color.colorPrimary) :
mContext.getResources().getColor(R.color.text_primary));
if (item.getPreferential() == 1) {
Drawable drawable = mContext.getResources().getDrawable(R.drawable.ic_benefit_26);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
((TextView) helper.getView(R.id.tv_date)).setCompoundDrawablePadding(UIUtils.dp2px(mContext, 6));
((TextView) helper.getView(R.id.tv_date)).setCompoundDrawables(null, null, drawable, null);
} else {
((TextView) helper.getView(R.id.tv_date)).setCompoundDrawables(null, null, null, null);
}
helper.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (selectedPos != helper.getAdapterPosition()) {
mData.get(selectedPos).isSelect = false;
notifyItemChanged(selectedPos);
selectedPos = helper.getAdapterPosition();
mData.get(selectedPos).isSelect = true;
notifyItemChanged(selectedPos);
}
if (onMovieDateClickListener != null) {
onMovieDateClickListener.onClick(item);
}
}
});
}
private String switchDate(int index) {
String[] week = new String[]{"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
return week[index % 7];
}
public void setOnMovieDateClickListener(OnMovieDateClickListener onMovieDateClickListener) {
this.onMovieDateClickListener = onMovieDateClickListener;
}
public interface OnMovieDateClickListener {
void onClick(CinemaMovieBean.DataBean.MoviesBean.ShowsBean item);
}
}
|
Donders-Institute/hpc-qaas | internal/server/connector.go | <filename>internal/server/connector.go
package server
import (
"golang.org/x/crypto/ssh"
)
// Connector is an interface to be able to mock SSH connections
type Connector interface {
NewClient(remoteServer string, clientConfig *ssh.ClientConfig) (*ssh.Client, error)
NewSession(client *ssh.Client) (*ssh.Session, error)
Run(session *ssh.Session, command string) error
CombinedOutput(session *ssh.Session, command string) ([]byte, error)
CloseSession(session *ssh.Session) error
CloseConnection(client *ssh.Client)
}
// SSHConnector is used tp replace the standard SSH library functions
type SSHConnector struct {
Description string
}
// NewClient makes it possible to mock SSH dial
func (c SSHConnector) NewClient(remoteServer string, clientConfig *ssh.ClientConfig) (*ssh.Client, error) {
return ssh.Dial("tcp", remoteServer, clientConfig)
}
// NewSession makes it possible to mock a SSH session
func (c SSHConnector) NewSession(client *ssh.Client) (*ssh.Session, error) {
return client.NewSession()
}
// Run makes it possible to mock a remote Run command
func (c SSHConnector) Run(session *ssh.Session, command string) error {
return session.Run(command)
}
// CombinedOutput makes it possible to mock a local CombinedOutput
func (c SSHConnector) CombinedOutput(session *ssh.Session, command string) ([]byte, error) {
return session.CombinedOutput(command)
}
// CloseSession makes it possible to mock the closing of a session
func (c SSHConnector) CloseSession(session *ssh.Session) error {
return session.Close()
}
// CloseConnection makes it possible to mock the closing of a session
func (c SSHConnector) CloseConnection(client *ssh.Client) {
client.Conn.Close()
}
|
Richard-Ballard/arbee-utils | src/main/java/com/github/richardballard/arbeeutils/id/AllBasedByIdSpecifier.java | /*
* (C) Copyright 2016 <NAME>.
*
* 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.github.richardballard.arbeeutils.id;
import com.google.common.collect.ImmutableSet;
import net.jcip.annotations.Immutable;
import org.jetbrains.annotations.NotNull;
import java.util.Optional;
/**
* This implementation of {@link ByIdSpecifier} defaults to including everything, but may have exclusions.
*/
@SuppressWarnings("WeakerAccess")
@Immutable
class AllBasedByIdSpecifier<T> implements ByIdSpecifier<T> {
private final @NotNull ImmutableSet<T> exclusions;
public AllBasedByIdSpecifier(final @NotNull Iterable<? extends T> exclusions) {
this.exclusions = ImmutableSet.copyOf(exclusions);
}
@Override
public boolean test(final @NotNull T value) {
return !exclusions.contains(value);
}
/**
* This instance has no record of include ids - return empty to indicate this is not applicable.
*/
@Override
@SuppressWarnings("OptionalContainsCollection")
public @NotNull Optional<ImmutableSet<T>> getIncludeIds() {
return Optional.empty();
}
@Override
@SuppressWarnings("OptionalContainsCollection")
public @NotNull Optional<ImmutableSet<T>> getExcludeIds() {
return Optional.of(exclusions);
}
@Override
public boolean equals(final Object o) {
if(this == o) {
return true;
}
if(o == null || getClass() != o.getClass()) {
return false;
}
final AllBasedByIdSpecifier<?> that = (AllBasedByIdSpecifier<?>) o;
return exclusions.equals(that.exclusions);
}
@Override
public int hashCode() {
return exclusions.hashCode();
}
@Override
public String toString() {
return "AllBasedByIdSpecifier{" +
"exclusions=" + exclusions +
'}';
}
}
|
rimmartin/cctbx_project | scitbx/stl/vector_io.h | <filename>scitbx/stl/vector_io.h<gh_stars>100-1000
#ifndef SCITBX_STD_VECTOR_IO_H
#define SCITBX_STD_VECTOR_IO_H
#include <ostream>
#include <vector>
namespace scitbx {
template <typename ElementType>
std::ostream& operator << (std::ostream& o, std::vector<ElementType> const& a) {
return o << af::const_ref<ElementType>(&a[0], a.size());
}
}
#endif
|
mzeitler/openstrom | firmware/prototype - final/firmware/src/system_config/default/framework/peripheral/pmp/templates/pmp_AddressControl_Default.h | /*******************************************************************************
PMP Peripheral Library Template Implementation
File Name:
pmp_AddressControl_Default.h
Summary:
PMP PLIB Template Implementation
Description:
This header file contains template implementations
For Feature : AddressControl
and its Variant : Default
For following APIs :
PLIB_PMP_ExistsAddressControl
PLIB_PMP_AddressSet
PLIB_PMP_AddressGet
PLIB_PMP_AddressLinesA0A1Set
PLIB_PMP_AddressLinesA0A1Get
*******************************************************************************/
//DOM-IGNORE-BEGIN
/*******************************************************************************
Copyright (c) 2012 released Microchip Technology Inc. All rights reserved.
Microchip licenses to you the right to use, modify, copy and distribute
Software only when embedded on a Microchip microcontroller or digital signal
controller that is integrated into your product or third party product
(pursuant to the sublicense terms in the accompanying license agreement).
You should refer to the license agreement accompanying this Software for
additional information regarding your rights and obligations.
SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF
MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
IN NO EVENT SHALL MICROCHIP OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER
CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR
OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
*******************************************************************************/
//DOM-IGNORE-END
#ifndef _PMP_ADDRESSCONTROL_DEFAULT_H
#define _PMP_ADDRESSCONTROL_DEFAULT_H
//******************************************************************************
/* Function : PMP_ExistsAddressControl_Default
Summary:
Implements Default variant of PLIB_PMP_ExistsAddressControl
Description:
This template implements the Default variant of the PLIB_PMP_ExistsAddressControl function.
*/
#define PLIB_PMP_ExistsAddressControl PLIB_PMP_ExistsAddressControl
PLIB_TEMPLATE bool PMP_ExistsAddressControl_Default( PMP_MODULE_ID index )
{
return true;
}
//******************************************************************************
/* Function : PMP_AddressSet_Default
Summary:
Implements Default variant of PLIB_PMP_AddressSet
Description:
This template implements the Default variant of the PLIB_PMP_AddressSet function.
*/
PLIB_TEMPLATE void PMP_AddressSet_Default( PMP_MODULE_ID index , uint32_t address )
{
PMADDR = address;
}
//******************************************************************************
/* Function : PMP_AddressGet_Default
Summary:
Implements Default variant of PLIB_PMP_AddressGet
Description:
This template implements the Default variant of the PLIB_PMP_AddressGet function.
*/
PLIB_TEMPLATE uint32_t PMP_AddressGet_Default( PMP_MODULE_ID index )
{
return PMADDR;
}
//******************************************************************************
/* Function : PMP_AddressLinesA0A1Set_Default
Summary:
Implements Default variant of PLIB_PMP_AddressLinesA0A1Set
Description:
This template implements the Default variant of the PLIB_PMP_AddressLinesA0A1Set function.
*/
PLIB_TEMPLATE void PMP_AddressLinesA0A1Set_Default( PMP_MODULE_ID index , uint8_t address )
{
PMADDR = (( PMADDR & ~(0x3)) | ((0x3)&((address) << (_PMADDR_ADDR_POSITION))));
}
//******************************************************************************
/* Function : PMP_AddressLinesA0A1Get_Default
Summary:
Implements Default variant of PLIB_PMP_AddressLinesA0A1Get
Description:
This template implements the Default variant of the PLIB_PMP_AddressLinesA0A1Get function.
*/
PLIB_TEMPLATE uint8_t PMP_AddressLinesA0A1Get_Default( PMP_MODULE_ID index )
{
return (uint8_t)((PMADDR) & (3));
}
#endif /*_PMP_ADDRESSCONTROL_DEFAULT_H*/
/******************************************************************************
End of File
*/
|
cojen/Maker | src/main/java/org/cojen/maker/Candidate.java | /*
* Copyright (C) 2019 Cojen.org
*
* 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 org.cojen.maker;
/**
* Partial-order comparator for selecting the best method to bind to.
*
* @author <NAME>
*/
final class Candidate {
/**
* Compares method which have the same number of parameters, which are known to be all
* possible candidates to bind to. For a method to be strictly "better" than another, all
* parameter types must be better or equal based on conversion cost.
*
* @param params actual types supplied to the invoke method
* @return -1 if if method a is better, 1 if b is better, or 0 if neither is strictly better
*/
public static int compare(Type[] params, Type.Method a, Type.Method b) {
Type[] aParams = a.paramTypes();
Type[] bParams = b.paramTypes();
int best = 0;
for (int i=0; i<params.length; i++) {
if (i >= aParams.length || i >= bParams.length) {
// Assume varargs.
break;
}
int cmp = compare(params[i], aParams[i], bParams[i]);
if (best == 0) {
best = cmp;
} else if (cmp != 0 && best != cmp) {
return 0;
}
}
if (best == 0) {
if (a.isVarargs()) {
if (!b.isVarargs()) {
return 1;
}
} else if (b.isVarargs()) {
return -1;
}
}
return best;
}
public static int compare(Type param, Type aParam, Type bParam) {
int aCost = param.canConvertTo(aParam);
int bCost = param.canConvertTo(bParam);
if (aCost != bCost) {
return aCost < bCost ? -1 : 1;
}
if (aCost != 0) {
return 0;
}
if (param.equals(aParam)) {
return param.equals(bParam) ? 0 : -1;
} else if (param.equals(bParam)) {
return 1;
}
// Both a and b are supertypes of the actual param.
if (param.isArray()) {
if (aParam.isArray()) {
if (bParam.isArray()) {
return compare(root(param), root(aParam), root(bParam));
} else {
return -1;
}
} else {
if (bParam.isArray()) {
return 1;
} else {
return 0; // not expected
}
}
}
int aSpec = specialization(aParam);
int bSpec = specialization(bParam);
return Integer.compare(bSpec, aSpec);
}
private static Type root(Type type) {
while (true) {
Type next = type.elementType();
if (next == null) {
return type;
}
type = next;
}
}
private static int specialization(Type type) {
int spec = 0;
while ((type = type.superType()) != null) {
spec++;
}
return spec;
}
}
|
daejunpark/jsaf | tests/html_tests/websitesource/4,yahoo.com/test_files/pretty.js | <reponame>daejunpark/jsaf<gh_stars>1-10
(function ()
{
if(! window.YFPAD)
{
window.YFPAD = {
};
}
var a = [];
YFPAD.debug = (function ()
{
});
YFPAD.ff_debug = (function ()
{
if(window.chocsickle)
{
chocsickle.add.apply(window, arguments);
}
});
YFPAD.lang = {
bind : (function (f, b, e)
{
var d, c;
if(! Function.prototype.bind)
{
d = (function (g)
{
if(b)
{
e.apply(f, [g, b, ]);
}
else
{
e.apply(f, arguments);
}
});
}
else
{
d = e.bind(f);
}
return d;
}),
mix : (function (d, c)
{
var b;
for(b in c)
{
if(c.hasOwnProperty(b))
{
d[b] = c[b];
}
}
return d;
}),
delay : (function (e, g, d, b)
{
var c = YFPAD.lang.bind(d, b, e), f = setTimeout(c, g);
return f;
}),
createHash : (function (c)
{
var d = [], e, b = encodeURIComponent;
for(e in c)
{
if(c.hasOwnProperty(e))
{
d.push(b(e) + "=" + b(String(c[e])));
}
}
return d.join("&");
}),
parseHash : (function (f)
{
if(f === null)
{
return false;
}
var e = f.split("&"), h = null, d = {
},
c = decodeURIComponent,
g = 0,
b = 0;
if(f.length)
{
for(g, b = e.length;g < b;g ++)
{
h = e[g].split("=");
d[c(h[0])] = c(h[1]);
}
}
return d;
})
};
YFPAD.dom = {
byId : (function (b)
{
return document.getElementById(b);
}),
addListener : (function (f, e, b, d)
{
var c = e;
if(d)
{
c = YFPAD.lang.bind(d, [], e);
}
if(window.addEventListener)
{
b.addEventListener(f, c, 0);
}
else
{
if(window.attachEvent)
{
b.attachEvent("on" + f, c);
}
}
a.push({
element : b,
"function" : e,
scope : d,
event : f,
bound : c
});
}),
removeListenerHelper : (function (d, c, b)
{
if(window.removeEventListener)
{
b.removeEventListener(d, c, 0);
}
else
{
if(window.detachEvent)
{
b.detachEvent("on" + d, c);
}
}
}),
removeListener : (function (e, d, c)
{
for(var f = 0, b = a.length;f < b;f ++)
{
if(a[f] && a[f].element === c && a[f].event === e)
{
if(a[f]["function"] === d || a[f].bound === d)
{
YFPAD.dom.removeListenerHelper(a[f].event, a[f].bound, a[f].element);
a[f] = null;
}
}
}
}),
purgeListeners : (function (c)
{
var d = YFPAD.dom.listeners;
for(var e = 0, b = a.length;e < b;e ++)
{
if(a[e] && a[e].element === c)
{
YFPAD.dom.removeListenerHelper(a[e].event, a[e].bound, a[e].element);
a[e] = null;
}
}
}),
preventDefault : (function (b)
{
if(b.preventDefault)
{
b.preventDefault();
}
else
{
b.returnValue = false;
}
}),
hasClass : (function (b, c)
{
var d = " ", e = b.className.toString().replace(/\s+/g, d);
return c && (d + e + d).indexOf(d + c + d) > - 1;
}),
byClassName : (function (f, h)
{
var g = h || document, c = [], d, e, b;
if(g.getElementsByClassName)
{
c = g.getElementsByClassName(f);
}
else
{
if(g && g.getElementsByTagName)
{
e = g.getElementsByTagName("*");
if(! e)
{
return [];
}
for(d = 0, b = e.length;d < b;++ d)
{
if(YFPAD.dom.hasClass(e[d], f))
{
c[c.length] = e[d];
}
}
}
}
return c;
}),
nodeCreate : (function (d)
{
var e = document.createElement("DIV"), c = document.createDocumentFragment(),
b;
e.innerHTML = d;
b = e.childNodes;
while(b[0])
{
c.appendChild(b[0].parentNode.removeChild(b[0]));
}
return c;
}),
getParent : (function (b, c)
{
if(YFPAD.dom.hasClass(c, b))
{
return c;
}
else
{
if(c.parentNode)
{
return YFPAD.dom.getParent(b, c.parentNode);
}
}
return null;
}),
clear : (function (b)
{
if(b)
{
b.innerHTML = "";
}
}),
visible : (function (c, b)
{
if(c)
{
if(b)
{
c.style.visibility = "visible";
}
else
{
c.style.visibility = "hidden";
}
}
}),
display : (function (c, b)
{
if(c)
{
if(b)
{
c.style.display = b;
}
else
{
c.style.display = "";
}
}
}),
isHidden : (function (b)
{
return (b && b.style.display !== "none" && b.style.display !== "");
}),
isVisible : (function (b)
{
return (b && b.style.visibility === "visible");
})
};
YFPAD.Base = (function (c)
{
var e = YFPAD.dom, d = YFPAD.lang, b = YFPAD.util, f;
f = (function (g)
{
d.mix(this, g.extend);
this.config = d.mix(this.config, g.conf);
YFPAD.ff_debug("ad_config", this.config);
this.start();
});
f.prototype = {
interaction_track : (function (i, q, o)
{
var h = o ? o : "1", j = this.config, m = j.nspace, l = j.beap,
p = j.rd,
g = "",
k = Math.random();
if(j.apt)
{
g = l[0] + "seq$" + i + ",label$" + q + ",type$click,time$" + k + l[1];
}
else
{
g = p + m + i + "/id=" + q + "/" + k + "/*" + h;
}
b.pixelTrack(g);
}),
detect : (function ()
{
var h = this.config, g = document.body, i = YFPAD.ua;
h.cap = i.isIE;
h.fv = i.isFlash;
if(h.cap > 0)
{
g.style.behavior = "url(#default#clientCaps)";
h.lan = (g.connectionType === "lan") ? 1 : 0;
}
else
{
h.ncap = i.isFireFox;
}
h.flash = (i.isFlash <= h.nfv);
this.config = h;
}),
init : (function ()
{
}),
start : (function ()
{
var h, g = this.config.pixels, j = (function ()
{
if(typeof (g) === "object")
{
for(h = 0;h < g.length;h ++)
{
YFPAD.util.pixelTrack(g[h]);
}
}
});
if(this.config.apt || (this.config.r0.indexOf("/X=3/") !== - 1 || this.config.r0.indexOf("/X=6/") !== - 1))
{
this.config.apt = true;
this.config.clickTags.apt = true;
}
else
{
if(this.config.rd === "")
{
YFPAD.debug("config.rd is blank");
}
else
{
if(/\/$/.test(this.config.rd))
{
YFPAD.debug("config.rd has a trailing slash: " + this.config.rd);
}
}
this.config.apt = false;
this.config.clickTags.apt = "";
}
this.detect();
this.init();
e.addListener("load", this.ad_init, window, this);
e.addListener("load", j, window);
}),
config : {
domain : "yahoo.com",
expires : 172800000,
key1 : "CRZY" + (new Date()).getDay(),
rd : "",
z1 : "",
nspace : "",
beap : [],
flash : false,
apt : false,
fv : 0,
nv : 0,
lan : 0,
cap : 0,
ncap : 0,
done : 0,
auto : 0,
narrow : YFPAD.ua.isNarrow,
flashvars : ""
}
};
return new f(c);
});
})();
(function (a)
{
function e(h)
{
var g = h.match(/[0-9]+.?[0-9]*/);
if(g && g[0])
{
return parseFloat(g[0]);
}
return 0;
}
var d = a.className.toString(), c = navigator.userAgent.toString(),
f = YFPAD.dom,
b = {
html : a,
os : (function ()
{
var g = "other";
if((/windows|win32/i).test(c))
{
g = "windows";
}
else
{
if((/macintosh/i).test(c))
{
g = "macintosh";
}
else
{
if((/iphone|ipod/i).test(c))
{
g = "ios";
}
else
{
if((/linux/i).test(c))
{
g = "linux";
}
}
}
}
return g;
})(),
isIE : (function ()
{
if(f.hasClass(a, "ua-ie"))
{
return d.match(/ua-ie(\d+)/)[1] || 1;
}
return 0;
})(),
isFireFox : (function ()
{
if(f.hasClass(a, "ua-ff"))
{
return d.match(/ua-ff(\d+)/)[1] || 1;
}
return 0;
})(),
isSafari : (function ()
{
var g = c.match(/Version\/([0-9.]+)\s?Safari/);
if(g && g[1])
{
return e(g[1]);
}
return 0;
})(),
isChrome : (function ()
{
var g = c.match(/Chrome\/([0-9.]+)/);
if(g && g[1])
{
return parseInt(g[1]);
}
return 0;
})(),
isWebKit : (function ()
{
if(f.hasClass(a, "ua-wk"))
{
return d.match(/ua-wk(\d+)/)[1] || 1;
}
return 0;
})(),
isFlash : (function ()
{
var g = 0;
if(/flash-[0-9]+/.test(d))
{
g = parseInt(d.match(/flash-([0-9]+)/)[1], 10) || 0;
}
return g;
})(),
isNarrow : (function ()
{
var g = f.hasClass(a, "lite-page") ? true : false;
return g;
})()
};
YFPAD.ua = b;
})(document.documentElement);
(function ()
{
if(! window.YFPAD)
{
window.YFPAD = {
};
}
var b = YFPAD.lang, a = {
test : (function (c)
{
var d = (navigator.cookieEnabled) ? true : false;
if(typeof navigator.cookieEnabled == "undefined" && ! d)
{
document.cookie = "fpadtestcookie";
d = (document.cookie.indexOf("fpadtestcookie") != - 1) ? true : false;
}
return d;
}),
set : (function (g, e, f, c)
{
var d = new Date(), h = b.createHash(e);
f = f || "yahoo.com";
c = c || 172800000;
d.setTime(d.getTime() + c);
document.cookie = g + "=" + h + "; expires=" + d.toGMTString() + "; domain=" + f + "; path=/";
}),
get : (function (g)
{
var d = " " + document.cookie + ";", f = new RegExp(" " + g + "=([a-zA-Z0-9&=_]+);"),
e = d.match(f);
if(e)
{
e = e[1];
}
return b.parseHash(e) || 0;
}),
remove : (function (d, c)
{
a.set(d, "", c, - 345600000);
})
};
YFPAD.cookie = a;
})();
(function ()
{
if(! window.YFPAD)
{
window.YFPAD = {
};
}
var c = YFPAD.lang, a = {
toggleTakeover : (function (d)
{
if(window.ad_takeover)
{
ad_takeover(d);
}
}),
adRunning : (function (d)
{
if(window.ad_running)
{
window.ad_running(d);
}
}),
YAD_init : (function (d)
{
window.YAD = {
play : (function (e)
{
d("play", e);
}),
track : (function (e)
{
d("track", e);
}),
button : {
close : (function (e)
{
d("close", e);
})
},
close : (function (e)
{
d("close", e);
}),
show : (function (e)
{
d("show", e);
}),
hide : (function (e)
{
d("hide", e);
})
};
}),
adAction : {
},
registerAdAction : (function (d)
{
if(d.ad)
{
a.adAction[d.ad] = d;
}
}),
inString : (function (d, e)
{
return (d.indexOf(e) !== - 1);
}),
getInt : (function (e)
{
var d = e.match(/[0-9]+/gi);
if(d !== null)
{
return parseInt(d.join(""), 10);
}
return 0;
}),
generateFlashRedirects : (function (d)
{
return c.createHash(d);
}),
pixelTrack : (function (d)
{
if(d)
{
var e = new Image();
e.onload = (function ()
{
e = null;
});
YFPAD.ff_debug("pixels", d);
e.src = d;
}
})
};
function b(e)
{
var f, d = YFPAD.util.adAction;
for(f in d)
{
if(typeof d[f].callback === "function")
{
d[f].callback.call(d[f].context, e);
}
}
}
YFPAD.util = a;
window.ad_action = b;
})();
|
zer0infinity/CuteForCoast | coast/foundation/base/cuteTest/AnythingSTLTest.h | /*
* Copyright (c) 2005, <NAME> and IFS Institute for Software at HSR Rapperswil, Switzerland
* Copyright (c) 2015, <NAME>, Faculty of Computer Science,
* University of Applied Sciences Rapperswil (HSR),
* 8640 Rapperswil, Switzerland
* All rights reserved.
*
* This library/application is free software; you can redistribute and/or modify it under the terms of
* the license that is included with this library/application in the file license.txt.
*/
#ifndef AnythingSTLTest_H
#define AnythingSTLTest_H
#include "cute.h"
#include "Anything.h"//lint !e537
class AnythingSTLTest {
void checkRange(const Anything &, long n, long length);
void checkFill(const Anything &);
void checkFillSizeType(const Anything &);
void checkSimpleInsert(const Anything &, const char *msg);
void checkInsertInArray(const Anything &a, long testpos, const char *msg, long n = 1);
void checkInsertWithKeys(const Anything &a, const long testpos, const char *m, const long n = 1);
public:
static void runAllTests(cute::suite &s);
void testSimpleSwap();
void testSwapWithDifferentAllocator();
void testFrontBackPushPop();
void testRangeAssign();
void testFillAssign();
void testFillAssignWithSizeType();
void testRangeCtor();
void testFillCtor();
void testFillCtorWithSizeType();
void testSimpleInsertToEmptyAny();
void testSimpleInsertAtEnd();
void testSimpleInsertAtBegin();
void testSimpleInsertInArray();
void testSimpleInsertWithKeys();
void testFillInsertToEmptyAny();
void testFillInsertInArray();
void testFillInsertWithKeys();
void testFillInsertZero();
void testIterInsertToEmptyAny();
void testIterInsertInArray();
void testIterInsertWithKeys();
void testIterInsertZero();
};
#endif
|
synergycp/express-elect-seed | api/src/config.example.js | <gh_stars>0
var config = module.exports;
module.exports['@literal'] = true;
var PRODUCTION = process.env.NODE_ENV !== 'develop';
config.express = {
port: process.env.API_PORT || 3000,
// Bind only to localhost.
// Overridden in production.
ip: '127.0.0.1'
};
if (PRODUCTION) {
config.express.ip = '0.0.0.0';
}
|
jgroups-extras/manet | src/main/java/urv/olsr/core/OLSRThread.java | <gh_stars>1-10
package urv.olsr.core;
import urv.olsr.data.OLSRNode;
import urv.olsr.data.duplicate.DuplicateTable;
import urv.olsr.data.mpr.MprSelectorSet;
import urv.olsr.data.mpr.MprSet;
import urv.olsr.data.neighbour.NeighborTable;
import urv.olsr.data.topology.TopologyInformationBaseTable;
import urv.olsr.mcast.TopologyInformationSender;
import urv.olsr.mcast.MulticastGroupsTable;
import urv.olsr.mcast.MulticastNetworkGraphComputationController;
import urv.olsr.message.OLSRMessageSender;
import urv.olsr.message.OLSRPacketFactory;
import urv.olsr.message.generator.HelloMessageGenerator;
import urv.olsr.message.generator.TcMessageGenerator;
/**
* This class is used to execute the OLSR tasks periodically
*
* @author <NAME>
*
*/
public class OLSRThread extends Thread {
// CONSTANTS --
private static final int BASE_TIME = 100; // 100 ms
private static final int HELLO_INTERVAL = BASE_TIME*20;
private static final int TC_INTERVAL = BASE_TIME*50;
private static final int INTERVAL_LCM = BASE_TIME*90;
public static final int TC_MESSAGE_VALIDITY_TIME = (4*TC_INTERVAL)/1000; //Time in seconds
public static final int HELLO_MESSAGE_VALIDITY_TIME = (4*HELLO_INTERVAL)/1000; //Time in seconds
// CLASS FIELDS --
private OLSRMessageSender olsrMessageSender;
private NeighborTable neighborTable;
private DuplicateTable duplicateTable;
private TopologyInformationBaseTable topologyTable;
private MulticastGroupsTable multicastGroupsTable;
private MprComputationController mprComputationController;
private RoutingTableComputationController routingTableComputationController;
private MulticastNetworkGraphComputationController multicastNetworkGraphComputationController;
// Message Generators
private HelloMessageGenerator helloMessageGenerator;
private TcMessageGenerator tcMessageGenerator;
private TopologyInformationSender controllerUpper;
private boolean extraTCMessage = false;
// CONSTRUCTORS --
public OLSRThread(OLSRMessageSender sender, NeighborTable neighborTable, MprComputationController mprComputationController,
RoutingTableComputationController routingTableComputationController, MprSelectorSet mprSelectorSet,
OLSRPacketFactory olsrPacketFactory, TopologyInformationBaseTable topologyTable, DuplicateTable duplicateTable,
TopologyInformationSender controllerUpper, MulticastNetworkGraphComputationController multicastNetworkGraphComputationController,
MulticastGroupsTable multicastGroupsTable, OLSRNode localNode){
this.olsrMessageSender = sender;
this.neighborTable = neighborTable;
this.mprComputationController = mprComputationController;
this.routingTableComputationController = routingTableComputationController;
this.topologyTable = topologyTable;
this.duplicateTable = duplicateTable;
this.helloMessageGenerator = new HelloMessageGenerator(sender, neighborTable, olsrPacketFactory);
this.tcMessageGenerator = new TcMessageGenerator(sender, mprSelectorSet, olsrPacketFactory, multicastGroupsTable, localNode);
this.controllerUpper = controllerUpper;
this.multicastNetworkGraphComputationController = multicastNetworkGraphComputationController;
this.multicastGroupsTable = multicastGroupsTable;
}
// OVERRIDDEN METHODS --
public void run(){
int countHello = 0;
int countTc = 0;
int count = 0;
long timeBefore = System.currentTimeMillis();
long timeNow;
long diff;
while(true){
try {
// Wait the BASE_TIME defined interval to execute the process again
Thread.sleep(BASE_TIME);
timeNow = System.currentTimeMillis();
diff = timeNow-timeBefore;
// Recalculation of the time elapsed between executions
count += diff;
countHello += diff;
countTc += diff;
timeBefore = timeNow;
neighborTable.decreaseTimeAndProcessEntries(diff);
duplicateTable.decreaseTimeAndProcessEntries(diff);
topologyTable.decreaseTimeAndProcessEntries(diff);
// MPR recomputation
if (neighborTable.isRecomputeMprFlag()){
//If the computation was ok, there is no need to recompute again
if (mprComputationController.computeNewMprSet()==true){
neighborTable.setRecomputeMprFlag(false);
MprSet mprSet = mprComputationController.getMprSet();
neighborTable.onMPRSetChange(mprSet);
}
}
// Routing Table recomputation
if (neighborTable.isNeighborTableChangedFlag() || topologyTable.isTopologyTableChangedFlag()){
neighborTable.setNeighborTableChangedFlag(false);
topologyTable.setTopologyTableChangedFlag(false);
// MulticastNetworkGraph recomputation
multicastGroupsTable.setMulticastGroupsTableChangedFlag(false);
multicastNetworkGraphComputationController.computeNewMulticastNetworkGraph();
// Report event up to the stacks (networkGraph)
controllerUpper.sendTopologyInformationEvent();
routingTableComputationController.computeNewRoutingTable();
}
if (multicastGroupsTable.isMulticastGroupsTableChangedFlag()){
multicastGroupsTable.setMulticastGroupsTableChangedFlag(false);
multicastNetworkGraphComputationController.computeNewMulticastNetworkGraph();
// Report event up to the stacks (networkGraph)
controllerUpper.sendTopologyInformationEvent();
}
// Generation of HELLO Messages
if (countHello >= HELLO_INTERVAL){
helloMessageGenerator.generateAndSend();
countHello = countHello % HELLO_INTERVAL;
}
// Generation of TC messages
if (countTc >= TC_INTERVAL){
tcMessageGenerator.generateAndSend();
countTc = countTc % TC_INTERVAL;
extraTCMessage = false;
} else if (extraTCMessage){
tcMessageGenerator.generateAndSend();
extraTCMessage = false;
}
if (count >= INTERVAL_LCM) {
// As Log is a Singleton class... maybe we only need a node to invoke printLoggables()
// Solution: printLoggables is now invoked from another thread!!!!!
//Log.getInstance().printLoggables();
count = count % INTERVAL_LCM;
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
// ACCESS METHODS --
public void setExtraTCMessage(boolean value){
extraTCMessage = value;
}
} |
mistraltechnologies/bog-javassist | src/test/java/com/mistraltech/bog/examples/model/Person.java | <reponame>mistraltechnologies/bog-javassist
package com.mistraltech.bog.examples.model;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Person extends Addressee {
private int age;
private List<Phone> phones;
public Person(String name, int age, Address address) {
super(name, address);
this.age = age;
}
public int getAge() {
return age;
}
public void setPhones(List<Phone> phones) {
this.phones = phones;
}
public List<Phone> getPhones() {
return phones;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
", phones=" + phones +
'}';
}
}
|
loongson-zn/Bitbucket-papi | src/papi_preset.c | /*
* File: papi_preset.c
* CVS:
* Author: <NAME>
* <EMAIL>
* Mods: <your name here>
* <your email address>
*/
#include "papi.h"
#include "papi_internal.h"
#include "papi_memory.h"
/* Defined in papi_data.c */
extern hwi_presets_t _papi_hwi_presets;
/* This routine copies values from a dense 'findem' array of events into the sparse
global _papi_hwi_presets array, which is assumed to be empty at initialization.
Multiple dense arrays can be copied into the sparse array, allowing event overloading
at run-time, or allowing a baseline table to be augmented by a model specific table
at init time. This method supports adding new events; overriding existing events, or
deleting deprecated events.
*/
int _papi_hwi_setup_all_presets(hwi_search_t * findem, hwi_dev_notes_t *notes, int substrate)
{
int i, pnum, preset_index, did_something = 0;
/* dense array of events is terminated with a 0 preset.
don't do anything if NULL pointer. This allows just notes to be loaded.
It's also good defensive programming.
*/
if (findem != NULL) {
for (pnum = 0; (pnum < PAPI_MAX_PRESET_EVENTS) && (findem[pnum].event_code != 0);
pnum++) {
/* find the index for the event to be initialized */
preset_index = (findem[pnum].event_code & PAPI_PRESET_AND_MASK);
for(i=0;i<PAPI_MAX_COUNTER_TERMS;i++){
if ( findem[pnum].data.native[i] != PAPI_NULL ){
int blah = PAPI_SUBSTRATE_MASK(substrate);
findem[pnum].data.native[i]|=blah;
}
//findem[pnum].data.native[i]|=PAPI_SUBSTRATE_MASK(substrate);
}
/* count and set the number of native terms in this event */
for (i = 0; (i < PAPI_MAX_COUNTER_TERMS) && (findem[pnum].data.native[i] != PAPI_NULL); i++);
_papi_hwi_presets.count[preset_index] = i;
/* if the native event array is empty, free the data pointer.
this allows existing events to be 'undefined' by overloading with nulls */
if (i == 0) {
if (_papi_hwi_presets.data[preset_index] != NULL)
papi_valid_free(_papi_hwi_presets.data[preset_index]);
}
/* otherwise malloc a data istructure for the sparse array and copy
the event data into it. Kevin assures me that the data won't
*actually* be duplicated unless it is modified */
else {
_papi_hwi_presets.data[preset_index] = papi_malloc(sizeof(hwi_preset_data_t));
*_papi_hwi_presets.data[preset_index] = findem[pnum].data;
}
did_something++;
}
}
/* optional dense array of event notes is terminated with a 0 preset */
if (notes != NULL) {
for (pnum = 0; (pnum < PAPI_MAX_PRESET_EVENTS) && (notes[pnum].event_code != 0);
pnum++) {
/* strdup the note string into the sparse preset data array */
preset_index = (notes[pnum].event_code & PAPI_PRESET_AND_MASK);
if (_papi_hwi_presets.dev_note[preset_index] != NULL)
papi_free(_papi_hwi_presets.dev_note[preset_index]);
_papi_hwi_presets.dev_note[preset_index] = papi_strdup(notes[pnum].dev_note);
}
}
return (did_something ? 0 : PAPI_ESBSTR);
}
int _papi_hwi_cleanup_all_presets(void)
{
int preset_index;
for (preset_index = 0; preset_index < PAPI_MAX_PRESET_EVENTS; preset_index++) {
/* free the names and descriptions if they were malloc'd by PAPI */
papi_valid_free(_papi_hwi_presets.info[preset_index].symbol);
_papi_hwi_presets.info[preset_index].symbol = NULL;
papi_valid_free(_papi_hwi_presets.info[preset_index].long_descr);
_papi_hwi_presets.info[preset_index].long_descr = NULL;
papi_valid_free(_papi_hwi_presets.info[preset_index].short_descr);
_papi_hwi_presets.info[preset_index].short_descr = NULL;
/* free the data and or note string if they exist */
if (_papi_hwi_presets.data[preset_index] != NULL) {
papi_free(_papi_hwi_presets.data[preset_index]);
_papi_hwi_presets.data[preset_index] = NULL;
}
if (_papi_hwi_presets.dev_note[preset_index] != NULL) {
_papi_hwi_presets.dev_note[preset_index] = NULL;
}
}
return (PAPI_OK);
}
/* The following code is proof of principle for reading preset events from an
xml file. It has been tested and works for pentium3. It relys on the expat
library and is invoked by adding
XMLFLAG = -DXML
to the Makefile. It is presently hardcoded to look for "./papi_events.xml"
*/
#ifdef XML
#define BUFFSIZE 8192
#define SPARSE_BEGIN 0
#define SPARSE_EVENT_SEARCH 1
#define SPARSE_EVENT 2
#define SPARSE_DESC 3
#define ARCH_SEARCH 4
#define DENSE_EVENT_SEARCH 5
#define DENSE_NATIVE_SEARCH 6
#define DENSE_NATIVE_DESC 7
#define FINISHED 8
char buffer[BUFFSIZE], *xml_arch;
int location=SPARSE_BEGIN, sparse_index=0, native_index, error=0;
/* The function below, _xml_start(), is a hook into expat's XML
* parser. _xml_start() defines how the parser handles the
* opening tags in PAPI's XML file. This function can be understood
* more easily if you follow along with its logic while looking at
* papi_events.xml. The location variable is a global telling us
* where we are in the XML file. Have we found our architecture's
* events yet? Are we looking at an event definition?...etc.
*/
static void _xml_start(void *data, const char *el, const char **attr) {
int native_encoding;
if(location==SPARSE_BEGIN && !strcmp("papistdevents", el)) {
location=SPARSE_EVENT_SEARCH;
}
else if(location==SPARSE_EVENT_SEARCH && !strcmp("papievent", el)) {
_papi_hwi_presets.info[sparse_index].symbol = papi_strdup(attr[1]);
// strcpy(_papi_hwi_presets.info[sparse_index].symbol, attr[1]);
location=SPARSE_EVENT;
}
else if(location==SPARSE_EVENT && !strcmp("desc", el)) {
location=SPARSE_DESC;
}
else if(location==ARCH_SEARCH && !strcmp("availevents", el) &&
!strcmp(xml_arch, attr[1])) {
location=DENSE_EVENT_SEARCH;
}
else if(location==DENSE_EVENT_SEARCH && !strcmp("papievent", el)) {
if(!strcmp("PAPI_NULL", attr[1])) {
location=FINISHED;
return;
}
else if(PAPI_event_name_to_code((char *)attr[1], &sparse_index) != PAPI_OK) {
PAPIERROR("Improper Preset name given in XML file for %s.", attr[1]);
error=1;
}
sparse_index &= PAPI_PRESET_AND_MASK;
/* allocate and initialize data space for this event */
papi_valid_free(_papi_hwi_presets.data[sparse_index]);
_papi_hwi_presets.data[sparse_index] = papi_malloc(sizeof(hwi_preset_data_t));
native_index=0;
_papi_hwi_presets.data[sparse_index]->native[native_index]=PAPI_NULL;
_papi_hwi_presets.data[sparse_index]->operation[0]='\0';
if(attr[2]) { /* derived event */
_papi_hwi_presets.data[sparse_index]->derived = _papi_hwi_derived_type((char *)attr[3]);
/* where does DERIVED POSTSCRIPT get encoded?? */
if (_papi_hwi_presets.data[sparse_index]->derived == -1) {
PAPIERROR("No derived type match for %s in Preset XML file.", attr[3]);
error=1;
}
if(attr[5]) {
_papi_hwi_presets.count[sparse_index] = atoi(attr[5]);
}
else {
PAPIERROR("No count given for %s in Preset XML file.", attr[1]);
error=1;
}
}
else {
_papi_hwi_presets.data[sparse_index]->derived=NOT_DERIVED;
_papi_hwi_presets.count[sparse_index] = 1;
}
location=DENSE_NATIVE_SEARCH;
}
else if(location==DENSE_NATIVE_SEARCH && !strcmp("native", el)) {
location=DENSE_NATIVE_DESC;
}
else if(location==DENSE_NATIVE_DESC && !strcmp("event", el)) {
if(_papi_hwi_native_name_to_code(attr[1], &native_encoding)!=PAPI_OK) {
printf("Improper Native name given in XML file for %s\n", attr[1]);
PAPIERROR("Improper Native name given in XML file for %s\n", attr[1]);
error=1;
}
_papi_hwi_presets.data[sparse_index]->native[native_index]=native_encoding;
native_index++;
_papi_hwi_presets.data[sparse_index]->native[native_index]=PAPI_NULL;
}
else if(location && location!=ARCH_SEARCH && location!=FINISHED) {
PAPIERROR("Poorly-formed Preset XML document.");
error=1;
}
}
/* The function below, _xml_end(), is a hook into expat's XML
* parser. _xml_end() defines how the parser handles the
* end tags in PAPI's XML file.
*/
static void _xml_end(void *data, const char *el) {
int i;
if(location==SPARSE_EVENT_SEARCH && !strcmp("papistdevents", el)) {
for(i=sparse_index; i<PAPI_MAX_PRESET_EVENTS; i++) {
_papi_hwi_presets.info[i].symbol = NULL;
_papi_hwi_presets.info[i].long_descr = NULL;
_papi_hwi_presets.info[i].short_descr = NULL;
}
location=ARCH_SEARCH;
}
else if(location==DENSE_NATIVE_DESC && !strcmp("native", el)) {
location=DENSE_EVENT_SEARCH;
}
else if(location==DENSE_EVENT_SEARCH && !strcmp("availevents", el)) {
location=FINISHED;
}
}
/* The function below, _xml_content(), is a hook into expat's XML
* parser. _xml_content() defines how the parser handles the
* text between tags in PAPI's XML file. The information between
* tags is usally text for event descriptions.
*/
static void _xml_content(void *data, const char *el, const int len) {
int i;
if(location==SPARSE_DESC) {
_papi_hwi_presets.info[sparse_index].long_descr = papi_malloc(len+1);
for(i=0; i<len; i++) _papi_hwi_presets.info[sparse_index].long_descr[i]=el[i];
_papi_hwi_presets.info[sparse_index].long_descr[len]='\0';
/* the XML data currently doesn't contain a short description */
_papi_hwi_presets.info[sparse_index].short_descr = NULL;
sparse_index++;
_papi_hwi_presets.data[sparse_index] = NULL;
location=SPARSE_EVENT_SEARCH;
}
}
int _xml_papi_hwi_setup_all_presets(char *arch, hwi_dev_notes_t *notes) {
int done = 0;
FILE *fp = fopen("./papi_events.xml", "r");
XML_Parser p = XML_ParserCreate(NULL);
if(!p) {
PAPIERROR("Couldn't allocate memory for XML parser.");
return(PAPI_ESYS);
}
XML_SetElementHandler(p, _xml_start, _xml_end);
XML_SetCharacterDataHandler(p, _xml_content);
if(fp==NULL) {
PAPIERROR("Error opening Preset XML file.");
return(PAPI_ESYS);
}
xml_arch = arch;
do {
int len;
void *buffer = XML_GetBuffer(p, BUFFSIZE);
if(buffer==NULL) {
PAPIERROR("Couldn't allocate memory for XML buffer.");
return(PAPI_ESYS);
}
len = fread(buffer, 1, BUFFSIZE, fp);
if(ferror(fp)) {
PAPIERROR("XML read error.");
return(PAPI_ESYS);
}
done = feof(fp);
if(!XML_ParseBuffer(p, len, len == 0)) {
PAPIERROR("Parse error at line %d:\n%s\n",
XML_GetCurrentLineNumber(p),
XML_ErrorString(XML_GetErrorCode(p)));
return(PAPI_ESYS);
}
if(error) return(PAPI_ESYS);
} while(!done);
XML_ParserFree(p);
fclose(fp);
return(PAPI_OK);
}
#endif
|
Strilanc/PaperImpl-PeriodFindCutQubits | src/dirty_period_finding/decompositions/modular_bimultiplication_rules.py | # -*- coding: utf-8 -*-
# Copyright 2017 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.
from __future__ import unicode_literals
from projectq.cengines import DecompositionRule
from dirty_period_finding.gates import (
ModularBimultiplicationGate,
ModularScaledAdditionGate,
RotateBitsGate,
ModularNegate,
)
def do_bimultiplication(gate, forward_reg, inverse_reg, controls):
"""
Reversibly multiplies one register by a constant and another register by
the modular multiplicative inverse of that constant.
N: len(forward_reg) + len(inverse_reg) + len(controls)
Size: O(N lg N)
Depth: O(N)
Diagram:
c c
━/━━━━━●━━━ ━/━━━━━●━━━━━━━●━━━━━━━●━━━━━━●━━━━━━●━━━━
n ┌───┴──┐ n ┌──┴──┐┌───┴───┐┌──┴──┐┌──┴──┐ │
━/━┥ ×K%R ┝━ = ━/━━┥ A ┝┥-AK⁻¹%R┝┥ A ┝┥━╲ ╱━┝━━━┿━━━━
n ├──────┤ n ├─────┤├───────┤├─────┤│ ╳ │┌──┴──┐
━/━┥×K⁻¹%R┝━ ━/━━┥+AK%R┝┥ A ┝┥+AK%R┝┥━╱ ╲━┝┥×-1%R┝━
└──────┘ └─────┘└───────┘└─────┘└─────┘└─────┘
Args:
gate (ModularBimultiplicationGate):
The gate being decomposed.
forward_reg (projectq.types.Qureg):
The register to mod-multiply by the forward factor.
inverse_reg (projectq.types.Qureg):
The register to mod-multiply by the inverse factor.
controls (list[Qubit]):
Control qubits.
"""
n = len(forward_reg)
assert len(inverse_reg) == n
assert 0 < gate.modulus <= 1 << n
# Trivial cases.
if gate.factor == 1:
return
if gate.factor == -1:
ModularNegate | forward_reg
ModularNegate | inverse_reg
return
scale_add = ModularScaledAdditionGate(gate.factor, gate.modulus)
scale_sub = ModularScaledAdditionGate(-gate.inverse_factor, gate.modulus)
scale_add & controls | (forward_reg, inverse_reg)
scale_sub & controls | (inverse_reg, forward_reg)
scale_add & controls | (forward_reg, inverse_reg)
RotateBitsGate(n) & controls | forward_reg + inverse_reg
ModularNegate(gate.modulus) & controls | inverse_reg
decompose_into_adds_and_rotate = DecompositionRule(
gate_class=ModularBimultiplicationGate,
gate_decomposer=lambda cmd: do_bimultiplication(
cmd.gate,
forward_reg=cmd.qubits[0],
inverse_reg=cmd.qubits[1],
controls=cmd.control_qubits))
all_defined_decomposition_rules = [
decompose_into_adds_and_rotate,
]
|
sheldhur/Vector | app/lib/consoleLogSQL.js | // import highliteSQl from 'sequelize-log-syntax-colors';
import sqlformatter from 'sqlformatter';
function highliteSQl(text, outputType = 'bash') {
let keyWords = [
'PRAGMA', 'CREATE', 'EXISTS', 'INTEGER', 'PRIMARY', 'VARCHAR',
'DATETIME', 'NULL', 'REFERENCES', 'AND', 'AS', 'ASC', 'INDEX_LIST',
'BETWEEN', 'BY', 'CASE', 'CURRENT_DATE', 'CURRENT_TIME', 'DELETE',
'DESC', 'DISTINCT', 'EACH', 'ELSE', 'ELSEIF', 'FALSE', 'FOR', 'FROM',
'GROUP', 'HAVING', 'IF', 'IN', 'INSERT', 'INTERVAL', 'INTO', 'IS',
'JOIN', 'KEY', 'KEYS', 'LEFT', 'LIKE', 'LIMIT', 'MATCH', 'NOT',
'ON', 'OPTION', 'OR', 'ORDER', 'OUT', 'OUTER', 'REPLACE', 'TINYINT',
'RIGHT', 'SELECT', 'SET', 'TABLE', 'THEN', 'TO', 'TRUE', 'UPDATE',
'VALUES', 'WHEN', 'WHERE', 'UNSIGNED', 'CASCADE', 'UNIQUE', 'DEFAULT',
'ENGINE', 'TEXT', 'auto_increment', 'SHOW', 'INDEX'
],
len = keyWords.length,
i;
// adding lowercase keyword support
for (i = 0; i < len; i += 1) {
keyWords.push(keyWords[i].toLowerCase());
}
let regEx;
const color = {
none: '\x1b[0m',
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
magenta: '\x1b[35m',
};
// just store original
// to compare for
let newText = text;
// regex time
// looking fo defaults
// newText = newText.replace(/Executing \(default\): /g, '');
// numbers - same color as strings
newText = newText.replace(/(\d+)/g, `${color.green}$1${color.none}`);
// special chars
newText = newText.replace(/(=|%|\/|\*|-|,|;|:|\+|<|>)/g, `${color.yellow}$1${color.none}`);
// strings - text inside single quotes and backticks
newText = newText.replace(/(['`].*?['`])/g, `${color.green}$1${color.none}`);
// functions - any string followed by a '('
newText = newText.replace(/(\w*?)\(/g, `${color.red}$1${color.none}(`);
// brackets - same as special chars
newText = newText.replace(/([\(\)])/g, `${color.yellow}$1${color.none}`);
// reserved mysql keywords
for (i = 0; i < keyWords.length; i += 1) {
// regex pattern will be formulated based on the array values surrounded by word boundaries. since the replace function does not accept a string as a regex pattern, we will use a regex object this time
regEx = new RegExp(`\\b${keyWords[i]}\\b`, 'g');
newText = newText.replace(regEx, color.magenta + keyWords[i] + color.none);
}
if (outputType === 'css') {
const colorCSS = {};
for (const name in color) {
colorCSS[color[name]] = name;
}
const colorParams = newText.match(/\x1b\[[\d]{1,2}m/ig).map((item) => {
const color = colorCSS[item];
let style = '';
switch (color) {
case 'magenta':
style = 'font-weight: bold; color: blue';
break;
case 'yellow':
style = 'color: black';
break;
default:
style = `font-weight: bold; color:${color}`;
}
return style;
});
newText = newText.replace(/\x1b\[[\d]{1,2}m/ig, '%c');
colorParams.unshift(newText);
return colorParams;
}
return newText;
}
export default function (string) {
const stringSplit = string.match(/(.*executing\s+\([^\s]+\):\s)(.+(\s+.+)*)/i);
try {
console.groupCollapsed(...highliteSQl(stringSplit[1] + stringSplit[2].replace(/[\r\n\s]+/g, ' '), 'css'));
console.log(...highliteSQl(stringSplit[1] + sqlformatter.format(stringSplit[2]), 'css'));
console.groupEnd();
} catch (e) {
throw new Error(`Can't parse query string: ${string}`);
}
}
|
STRIDES-Codes/Exploring-the-Microbiome- | src/metaspades/src/common/paired_info/histptr.hpp | //***************************************************************************
//* Copyright (c) 2015-2016 Saint Petersburg State University
//* All Rights Reserved
//* See file LICENSE for details.
//***************************************************************************
#pragma once
namespace omnigraph {
namespace de {
template<class T>
class StrongWeakPtr {
public:
typedef T element_type;
typedef T* pointer;
StrongWeakPtr() noexcept
: ptr_() {}
StrongWeakPtr(std::nullptr_t) noexcept
: ptr_() {}
StrongWeakPtr(pointer p, bool owning = true) noexcept
: ptr_(std::move(p), owning) {}
StrongWeakPtr(StrongWeakPtr &&p) noexcept
: ptr_(p.ptr_) {
p.ptr_ = raw_type();
}
StrongWeakPtr &operator=(StrongWeakPtr &&p) noexcept {
swap(p);
return *this;
}
~StrongWeakPtr() {
reset();
}
StrongWeakPtr &operator=(std::nullptr_t) noexcept {
reset();
return *this;
}
typename std::add_lvalue_reference<T>::type operator*() const {
return *ptr_.getPointer();
}
pointer operator->() const noexcept {
return ptr_.getPointer();
}
pointer get() const noexcept {
return ptr_.getPointer();
}
explicit operator bool() const noexcept {
return ptr_.getPointer() != nullptr;
}
bool owning() const noexcept {
return ptr_.getInt();
}
pointer release() noexcept {
pointer p = ptr_.getPointer();
ptr_ = raw_type();
return p;
}
void reset(pointer p = pointer(), bool own = true) {
if (ptr_.getInt())
delete ptr_.getPointer();
ptr_ = raw_type(p, own);
}
void swap(StrongWeakPtr &p) noexcept {
std::swap(p.ptr_, ptr_);
}
private:
llvm::PointerIntPair<pointer, 1, bool> ptr_;
typedef decltype(ptr_) raw_type;
};
template<class T>
inline void swap(StrongWeakPtr<T> &x, StrongWeakPtr<T> &y) noexcept {
x.swap(y);
}
template<class T>
inline bool operator==(const StrongWeakPtr<T> &x, const StrongWeakPtr<T> &y) noexcept {
return x.get() == y.get();
}
template<class T>
inline bool operator!=(const StrongWeakPtr<T> &x, const StrongWeakPtr<T> &y) noexcept {
return !(x == y);
}
template<class T1, class T2>
inline bool operator<(const StrongWeakPtr<T1> &x, const StrongWeakPtr<T2> &y) noexcept {
typedef typename StrongWeakPtr<T1>::pointer P1;
typedef typename StrongWeakPtr<T2>::pointer P2;
typedef typename std::common_type<P1, P2>::type Common;
using namespace std;
return less<Common>()(x.get(), y.get());
}
template<class T1, class T2>
inline bool operator>(const StrongWeakPtr<T1> &x, const StrongWeakPtr<T2> &y) noexcept {
return y < x;
}
template<class T1, class T2>
inline bool operator<=(const StrongWeakPtr<T1> &x, const StrongWeakPtr<T2> &y) noexcept {
return !(y < x);
}
template<class T1, class T2>
inline bool operator>=(const StrongWeakPtr<T1> &x, const StrongWeakPtr<T2> &y) noexcept {
return !(x < y);
}
template<class T>
inline bool operator==(const StrongWeakPtr<T> &x, std::nullptr_t) noexcept {
return !x;
}
template<class T>
inline bool operator==(std::nullptr_t, const StrongWeakPtr<T> &x) noexcept {
return !x;
}
template<class T>
inline bool operator!=(const StrongWeakPtr<T> &x, std::nullptr_t) noexcept {
return static_cast<bool>(x);
}
template<class T>
inline bool operator!=(std::nullptr_t, const StrongWeakPtr<T> &x) noexcept {
return static_cast<bool>(x);
}
template<class T, class... Args>
StrongWeakPtr<T>
make_sw(Args&&... args) {
return StrongWeakPtr<T>(new T(std::forward<Args>(args)...));
}
}
}
|
rutsatz/echo3ext20 | src/java/org/sgodden/echo/ext20/testapp/WindowTest.java | <filename>src/java/org/sgodden/echo/ext20/testapp/WindowTest.java
/* =================================================================
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# ================================================================= */
package org.sgodden.echo.ext20.testapp;
import nextapp.echo.app.event.ActionEvent;
import nextapp.echo.app.event.ActionListener;
import org.sgodden.echo.ext20.Button;
import org.sgodden.echo.ext20.Panel;
import org.sgodden.echo.ext20.Window;
import org.sgodden.echo.ext20.layout.FitLayout;
/**
* Tests windows.
* @author sgodden
*/
@SuppressWarnings({"serial"})
public class WindowTest
extends Panel {
//private static final transient Log log = LogFactory.getLog(WindowTest.class);
public WindowTest(){
super("Window");
add(makeWindowTestButton());
add(makeWindowTestButtonNotResizable());
add(makeModalWindowTestButton());
}
private Button makeWindowTestButton(){
Button ret = new Button("Open window");
ret.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
WindowTest.this.add(makeTestWindow(true));
}
});
return ret;
}
private Button makeWindowTestButtonNotResizable(){
Button ret = new Button("Open window (not resizable)");
ret.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
WindowTest.this.add(makeTestWindow(false));
}
});
return ret;
}
private Button makeModalWindowTestButton(){
Button ret = new Button("Open modal window");
ret.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
WindowTest.this.add(makeModalTestWindow());
}
});
return ret;
}
private TestWindow makeTestWindow(boolean resizable) {
TestWindow ret = new TestWindow();
ret.setResizable(resizable);
return ret;
}
private TestWindow makeModalTestWindow() {
TestWindow ret = new TestWindow();
ret.setModal(true);
return ret;
}
private static class TestWindow extends Window {
private int clickCount = 0;
private TestWindow(){
super(new FitLayout(), "Grid and form");
setWidth(400);
setHeight(400);
UserPanel up = new UserPanel(false);
up.createUI();
add(up);
Button closeButton = new Button("Close me");
addButton(closeButton);
closeButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
close();
}
});
Button changeTitleButton = new Button("Change window title");
addButton(changeTitleButton);
changeTitleButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
setTitle("Grid and form: " + ++clickCount);
}});
}
}
} |
janbodnar/Java-Advanced | datetime/IslamicDateEx.java | <reponame>janbodnar/Java-Advanced<filename>datetime/IslamicDateEx.java<gh_stars>10-100
package com.zetcode;
import java.time.LocalDate;
import java.time.chrono.HijrahDate;
public class IslamicDateEx {
public static void main(String[] args) {
var nowIslamic = HijrahDate.now();
System.out.println("Islamic date: " + nowIslamic);
var nowGregorian = LocalDate.now();
System.out.println("Gregorian date: " + nowGregorian);
}
}
|
fochoao/cpython | Lib/site-packages/argparseqt/typeHelpers.py | import argparse
class Serial(str):
pass
def rgb(val):
if len(val) != 6:
raise argparse.ArgumentTypeError('Expected 6 characters but received "%s"' % val)
try:
return tuple(int(val[i:i+2], 16) for i in (0, 2, 4))
except:
raise argparse.ArgumentTypeError('Invalid hex string: %s' % val)
def rgba(val):
if len(val) != 8:
raise argparse.ArgumentTypeError('Expected 8 characters but received "%s"' % val)
try:
return tuple(int(val[i:i+2], 16) for i in (0, 2, 4, 6))
except:
raise argparse.ArgumentTypeError('Invalid hex string: %s' % val)
|
hsiafan/cocoa | webkit/preferences.h | #import <Foundation/NSGeometry.h>
#import <Foundation/NSRange.h>
#import <stdbool.h>
#import <stdint.h>
#import <stdlib.h>
#import <utils.h>
void* C_Preferences_Alloc();
void* C_WKPreferences_AllocPreferences();
void* C_WKPreferences_Init(void* ptr);
void* C_WKPreferences_NewPreferences();
void* C_WKPreferences_Autorelease(void* ptr);
void* C_WKPreferences_Retain(void* ptr);
double C_WKPreferences_MinimumFontSize(void* ptr);
void C_WKPreferences_SetMinimumFontSize(void* ptr, double value);
bool C_WKPreferences_TabFocusesLinks(void* ptr);
void C_WKPreferences_SetTabFocusesLinks(void* ptr, bool value);
bool C_WKPreferences_JavaScriptCanOpenWindowsAutomatically(void* ptr);
void C_WKPreferences_SetJavaScriptCanOpenWindowsAutomatically(void* ptr, bool value);
bool C_WKPreferences_IsFraudulentWebsiteWarningEnabled(void* ptr);
void C_WKPreferences_SetFraudulentWebsiteWarningEnabled(void* ptr, bool value);
bool C_WKPreferences_TextInteractionEnabled(void* ptr);
void C_WKPreferences_SetTextInteractionEnabled(void* ptr, bool value);
|
JianpingZeng/xcc | xcc/java/backend/pass/PassRegisterationUtility.java | /*
* Extremely Compiler Collection
* Copyright (c) 2015-2020, <NAME>.
*
* 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 backend.pass;
import backend.analysis.*;
import backend.analysis.aa.AliasAnalysis;
import backend.codegen.*;
import backend.codegen.dagisel.RegisterScheduler;
import backend.codegen.dagisel.ScheduleDAGFast;
import backend.codegen.linearscan.SimpleRegisterCoalescer;
import backend.support.*;
import backend.target.TargetData;
import backend.transform.ipo.AlwaysInliner;
import backend.transform.ipo.BasicInliner;
import backend.transform.ipo.RaiseAllocations;
import backend.transform.scalars.*;
/**
* @author <NAME>
* @version 0.4
*/
public final class PassRegisterationUtility {
/**
* This method is helpful for registering all of passes into Pass DataBase.
*/
public static void registerPasses() {
// Analysis passes.
new RegisterPass("Live Interval Analysis", "liveintervals", LiveIntervalAnalysis.class);
new RegisterPass("Dominance Frontier Construction", "domfrontier", DominanceFrontier.class, true, true);
new RegisterPass("Dominator Tree Construction", "domtree", DomTree.class, true, true);
new RegisterPass("Induction Variable Users", "iv-users", IVUsers.class, false, true);
new RegisterPass("Live Variable Analysis", "livevars", LiveVariables.class);
new RegisterPass("Natural Loop Information", "loops", LoopInfo.class, true, true);
new RegisterPass("Machine Dominator Tree Construction", "machinedomtree", MachineDomTree.class, true, true);
new RegisterPass("Machine Natural Loop Construction", "machine-loops", MachineLoopInfo.class, true, true);
new RegisterPass("Scalar Evolution Analysis", "scalar-evolution", ScalarEvolution.class, false, true);
new RegisterPass("Print out Dom tree into dot file", "dot-domtree", DomTreePrinter.class, false, true);
new RegisterPass("Print out cfg into dot file", "dot-cfg", CFGPrinter.class, false, true);
new RegisterPass("Alias Analysis Pass", "alias-analysis", AliasAnalysis.class, false, true);
new RegisterPass("Live interval Analysis for wimmer style ra", "wimmer-li",
backend.codegen.linearscan.LiveIntervalAnalysis.class);
new RegisterPass("Basic Call Graph Analysis", "call-graph", CallGraph.class, false, true);
new RegisterPass("Basic Function Inlining/Integration", "inline", BasicInliner.class, false, false);
new RegisterPass("Inliner for always_inline functions", "always-inline", AlwaysInliner.class, false, false);
// IPO transformation
new RegisterPass("Raise allocations from calls to instructions", "raiseallocs", RaiseAllocations.class);
// Scalar transformation
new RegisterPass("Break critical edges in CFG", "break-crit-edges", BreakCriticalEdge.class);
new RegisterPass("Simplify the CFG", "simplifycfg", CFGSimplifyPass.class);
new RegisterPass("Conditional Propagation", "condprop", ConditionalPropagate.class);
new RegisterPass("Simple constant propagation", "constprop", ConstantPropagation.class);
new RegisterPass("Dead Instruction Elimination", "die", DCE.class);
new RegisterPass("Global Value Numbering/Partial Redundancy Elimination", "gvnpre", GVNPRE.class);
new RegisterPass("Canonicalize Induction Variables[Morgen textbook]", "indvarsv1", InductionVarSimplify.class);
new RegisterPass("Canonicalize Induction Variables", "indvars", IndVarSimplify.class);
new RegisterPass("Loop closed SSA", "lcssa", LCSSA.class);
new RegisterPass("Loop Invariant Code Motion", "licm", LICM.class);
new RegisterPass("Delete dead loops", "loop-deletion", LoopDeletion.class);
new RegisterPass("Loop Simplification Pass", "loopsimplify", LoopSimplify.class);
new RegisterPass("Lower switch with branch", "lowerswitch", LowerSwitch.class);
new RegisterPass("Promote memory to Register", "mem2reg", Mem2Reg.class);
new RegisterPass("Sparse Conditional Constant Propagation", "sccp", SCCP.class);
new RegisterPass("Scalar Replacement of Aggregates", "scalarrepl", SROA.class);
new RegisterPass("Tail Call Elimination", "tailcallelim", TailCallElim.class);
new RegisterPass("Unify function exit nodes", "mergereturn", UnifyFunctionExitNodes.class);
new RegisterPass("Remove unreachable basic block from CFG", "unreachableblockelim", UnreachableBlockElim.class);
new RegisterPass("Combine redundant instruction", "instcombine", InstructionCombine.class, false, false);
// Machine Function Passes
new RegisterPass("Eliminate PHI nodes for register allocation", "phi-node-elimination", PhiElimination.class);
new RegisterPass("Prologue/Epilogue Insertion", "prologepilog", PrologEpilogInserter.class);
new RegisterPass("Two-Address instruction pass", "twoaddressinstruction", TwoAddrInstructionPass.class);
new RegisterPass("Remove unreachable machine blocks from the machine CFG", "unreachable-machineblockelim", UnreachableMachineBlockElim.class);
new RegisterPass("Machine Module Information", "machine-module=info", MachineModuleInfo.class);
new RegisterPass("Rearragement machine basic blocks in Function to reduce useless branch", "rearragementmbbs", RearrangementMBB.class);
new RegisterRegAlloc("linearscan", "Linear Scan Register Allocation", RegAllocLinearScan::createLinearScanRegAllocator);
new RegisterRegAlloc("local", "Local register allocator", RegAllocLocal::createLocalRegAllocator);
new RegisterRegAlloc("pbqp", "PBQP Register Allocator", RegAllocPBQP::createPBQPRegisterAllocator);
// Register scheduler.
new RegisterScheduler("fast", "Fast Instruction Scheduler", ScheduleDAGFast::createFastDAGScheduler);
new RegisterPass("register-coalescing", "Simple register coalescer", LiveIntervalCoalescing.class);
new RegisterPass("simple-register-coalescer", "Simple Register Coalescer", SimpleRegisterCoalescer.class);
new RegisterPass("live-stack-slot", "Live Analysis of Stack Slot", LiveStackSlot.class);
new RegisterPass("edge-bundles", "Bundle Machine CFG Edges", EdgeBundles.class);
new RegisterPass("dead-mi-elimination", "Remove dead machine instruction", DeadMachineInstructionElim.class);
new RegisterPass("Dwarf Exception handling preparation", "dwarf-exception-handling", DwarfEHPrepare.class);
new RegisterPass("Verify generated machine code", "machine-verifier", MachineCodeVerifier.class);
// Immutable Passes.
new RegisterPass("Target Data Layout", "targetdata", TargetData.class, false, true);
new RegisterPass("Print Module to stderr", "print-module", PrintModulePass.class, false, true);
new RegisterPass("Print Function to stderr", "print-function", PrintFunctionPass.class, true, true);
new RegisterPass("Print Basic Block to stderr", "print-bb", PrintBasicBlockPass.class, true, true);
new RegisterPass("Print out Machine Function to stderr", "print-machine-function", PrintMachineFunctionPass.class, true, true);
new RegisterPass("Print Loop to stderr", "print-loop", PrintLoopPass.class, true, true);
}
}
|
FujishigeTemma/Emoine | services/streamer/streamer.go | package streamer
import (
"context"
"errors"
"log"
"sync"
"github.com/google/uuid"
"github.com/traPtitech/Emoine/repository"
"github.com/gorilla/websocket"
"google.golang.org/protobuf/proto"
"github.com/traPtitech/Emoine/pb"
"github.com/traPtitech/Emoine/utils"
)
var (
// ErrAlreadyClosed 既に閉じられています
ErrAlreadyClosed = errors.New("already IsClosed")
// ErrBufferIsFull 送信バッファが溢れました
ErrBufferIsFull = errors.New("buffer is full")
)
// Streamer WebSocketストリーマー
type Streamer struct {
repo repository.Repository
clients map[string]*client
registry chan *client
messageBuffer chan *rawMessage
active bool
rwm sync.RWMutex
commentChan <-chan string
presentationId uint32
}
// NewStreamer WebSocketストリーマーを生成し起動します
func NewStreamer(repo repository.Repository, commentChan <-chan string) *Streamer {
s := &Streamer{
repo: repo,
clients: make(map[string]*client),
registry: make(chan *client),
messageBuffer: make(chan *rawMessage),
active: true,
commentChan: commentChan,
}
go s.run()
return s
}
func (s *Streamer) run() {
defer s.close()
for {
select {
case client := <-s.registry: // websocket接続が確立された時か、あるいは切断された時
if client.active {
s.clients[client.Key()] = client
} else {
delete(s.clients, client.Key())
}
m, err := marshalViewerMessage(client.UserID(), len(s.clients))
if err != nil {
log.Printf("error: %v", err)
break
}
s.SendAll(m)
case m := <-s.messageBuffer: // クライアントからメッセージを受け取った時
err := s.logger(m)
if err != nil {
log.Printf("error: %v", err)
}
s.SendAll(m)
case comment := <-s.commentChan: // twitter上のコメントを受け取った時
m, err := s.marshalCommentMessage(comment)
if err != nil {
log.Printf("error: %v", err)
break
}
s.SendAll(m)
}
}
}
func (s *Streamer) close() {
s.rwm.Lock()
defer s.rwm.Unlock()
m := &rawMessage{
messageType: websocket.CloseMessage,
data: websocket.FormatCloseMessage(websocket.CloseServiceRestart, "Server is stopping..."),
}
for _, client := range s.clients {
if err := client.PushMessage(m); err != nil {
log.Printf("error: %v", err)
}
delete(s.clients, client.Key())
if err := client.Close(); err != nil {
log.Printf("error: %v", err)
}
}
s.active = false
}
// SendAll すべてのclientにメッセージを送る
func (s *Streamer) SendAll(m *rawMessage) {
for _, client := range s.clients {
if err := client.PushMessage(m); err != nil {
log.Printf("error: %v", err)
}
}
}
func (s *Streamer) marshalCommentMessage(comment string) (*rawMessage, error) {
msg := &pb.Message{
Payload: &pb.Message_Comment{
Comment: &pb.Comment{
PresentationId: s.presentationId,
Text: comment,
},
},
}
data, err := proto.Marshal(msg)
if err != nil {
return nil, err
}
// use uuid.Nil as userID of twitter client
m := &rawMessage{uuid.Nil, websocket.BinaryMessage, data}
return m, nil
}
func marshalViewerMessage(userID uuid.UUID, length int) (*rawMessage, error) {
msg := &pb.Message{
Payload: &pb.Message_Viewer{
Viewer: &pb.Viewer{Count: uint32(length)},
},
}
data, err := proto.Marshal(msg)
if err != nil {
return nil, err
}
m := &rawMessage{userID, websocket.BinaryMessage, data}
return m, nil
}
// SendState すべてのclientに新しいstateを送る
func (s *Streamer) SendState(st *pb.State) {
s.presentationId = st.PresentationId
msg := &pb.Message{
Payload: &pb.Message_State{
State: st,
},
}
data, err := proto.Marshal(msg)
if err != nil {
log.Printf("error: %v", err)
return
}
for _, client := range s.clients {
m := &rawMessage{client.UserID(), websocket.BinaryMessage, data}
if err := client.PushMessage(m); err != nil {
log.Printf("error: %v", err)
}
}
}
// NewClient 新規クライアントを初期化・登録します
func (s *Streamer) NewClient(conn *websocket.Conn, currentState *pb.State) error {
var wg sync.WaitGroup
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
client := &client{
key: utils.RandAlphabetAndNumberString(20),
userID: uuid.New(),
conn: conn,
receiver: &s.messageBuffer,
sender: make(chan *rawMessage, messageBufferSize),
wg: &wg,
active: true,
}
s.registry <- client
defer func() {
if !client.IsClosed() {
if err := client.Close(); err != nil {
log.Printf("error: %v", err)
}
}
s.registry <- client
}()
wg.Add(1)
go client.ListenWrite(ctx)
go client.ListenRead(ctx)
msg := &pb.Message{
Payload: &pb.Message_State{
State: currentState,
},
}
data, err := proto.Marshal(msg)
if err != nil {
return err
}
m := &rawMessage{client.UserID(), websocket.BinaryMessage, data}
if err := client.PushMessage(m); err != nil {
return err
}
wg.Wait()
return nil
}
func (s *Streamer) ClientsCount() int {
return len(s.clients)
}
// IsClosed ストリーマーが停止しているかどうか
func (s *Streamer) IsClosed() bool {
s.rwm.RLock()
defer s.rwm.RUnlock()
return !s.active
}
|
nathanmentley/attollo | src/Server/Tools/DatabaseManager/CodeVersions/3.js | <reponame>nathanmentley/attollo<gh_stars>0
//Seed BlockContainerDefs
//Seed AddBlockContainerAreaDef
import constitute from 'constitute';
import Attollo from '../../../Common/Attollo';
var attollo = constitute(Attollo);
(function () {
var classDef = function () {};
classDef.prototype.Logic = function(dbContext, callback, errorCallback) {
Promise.all([
attollo.Services.Block.AddBlockContainerDef(dbContext, 'OneCol', 'One Column'),
attollo.Services.Block.AddBlockContainerDef(dbContext, 'TwoCol', 'Two Column'),
attollo.Services.Block.AddBlockContainerDef(dbContext, 'ThreeCol', 'Three Column'),
attollo.Services.Block.AddBlockContainerDef(dbContext, 'FourCol', 'Four Column')
])
.then(() => {
Promise.all([
attollo.Services.Block.AddBlockContainerAreaDef(dbContext, 'OneCol', 'First', 'First'),
attollo.Services.Block.AddBlockContainerAreaDef(dbContext, 'TwoCol', 'First', 'First'),
attollo.Services.Block.AddBlockContainerAreaDef(dbContext, 'TwoCol', 'Second', 'Second'),
attollo.Services.Block.AddBlockContainerAreaDef(dbContext, 'ThreeCol', 'First', 'First'),
attollo.Services.Block.AddBlockContainerAreaDef(dbContext, 'ThreeCol', 'Second', 'Second'),
attollo.Services.Block.AddBlockContainerAreaDef(dbContext, 'ThreeCol', 'Third', 'Third'),
attollo.Services.Block.AddBlockContainerAreaDef(dbContext, 'FourCol', 'First', 'First'),
attollo.Services.Block.AddBlockContainerAreaDef(dbContext, 'FourCol', 'Second', 'Second'),
attollo.Services.Block.AddBlockContainerAreaDef(dbContext, 'FourCol', 'Third', 'Third'),
attollo.Services.Block.AddBlockContainerAreaDef(dbContext, 'FourCol', 'Fourth', 'Fourth')
])
.then(() => {
callback();
})
.catch((err) => { errorCallback(err); });
})
.catch((err) => { errorCallback(err); });
};
module.exports = new classDef();
})(); |
0xlay/Distance | Client/Module/src/ModulesManager.cpp | #include "ModulesManager.hpp"
namespace Distance
{
namespace _internal
{
void ModulesManagerDestructor::init(Distance::ModulesManager* manager)
{
manager_ = manager;
}
ModulesManagerDestructor::~ModulesManagerDestructor()
{
delete manager_;
}
}
ModulesManager& ModulesManager::invoke()
{
if (!manager_)
{
manager_ = new ModulesManager();
destructor_.init(manager_);
}
return *manager_;
}
void ModulesManager::addModules(ModulesList modules)
{
modules_ = std::move(modules);
}
ModulesManager::~ModulesManager()
{
stopAll();
}
void ModulesManager::runAll()
{
for (const auto& [key, item] : modules_)
item->run();
}
void ModulesManager::stopAll()
{
for (const auto& [key, item] : modules_)
item->stop();
}
void ModulesManager::run(ModuleType mod)
{
modules_[mod]->run();
}
void ModulesManager::stop(ModuleType mod)
{
modules_[mod]->stop();
}
std::shared_ptr<Module::IModule> ModulesManager::getAccess(ModuleType mod) const
{
return modules_.at(mod);
}
ModulesList CreateModules()
{
// WARNING: If updated function, change function description in the header file
ModulesList modules;
modules[ModuleType::PcInfo] = std::make_shared<Module::PcInfo>();
// modules[ModuleType::Keylogger] = std::make_shared<Module::Keylogger>();
// modules[ModuleType::Netfilter] = std::make_shared<Module::Netfilter>();
modules[ModuleType::ProcessManager] = std::make_shared<Module::ProcessManager>();
modules[ModuleType::PowerManager] = std::make_shared<Module::PowerManager>();
modules[ModuleType::Screenshot] = std::make_shared<Module::Screenshot>();
return modules;
}
} // Distance |
sooftware/nlp-tasks | machine_translation/train.py | <gh_stars>10-100
# MIT License
# code by <NAME> @sooftware
import argparse
import torch
import torch.nn as nn
import numpy as np
import random
import wandb
from functools import partial
from torch.utils.data import DataLoader
from dataset import load_datas, TranslationDataset, collate_fn
from utils import train_tokenizer
from model import Transformer
from trainer import MachineTranslationTrainer
def _get_parser():
parser = argparse.ArgumentParser(description='NLP Tasks - Machine Translation')
# Basic arguments
parser.add_argument('--seed', type=int, default=7)
parser.add_argument('--data_dir', type=str, required=True)
parser.add_argument('--save_dir', type=str, default='checkpoints')
# Model arguments
parser.add_argument('--d_model', type=int, default=512)
parser.add_argument('--num_heads', type=int, default=8)
parser.add_argument('--num_encoder_layers', type=int, default=6)
parser.add_argument('--num_decoder_layers', type=int, default=6)
parser.add_argument('--feed_forward_dim', type=int, default=2048)
parser.add_argument('--activation', type=str, default='relu')
parser.add_argument('--dropout_p', type=float, default=0.1)
# Tokenizer arguments
parser.add_argument('--source_vocab_size', type=int, default=8000)
parser.add_argument('--target_vocab_size', type=int, default=32000)
parser.add_argument('--source_tokenizer_model_name', type=str, default="source")
parser.add_argument('--target_tokenizer_model_name', type=str, default="target")
parser.add_argument('--source_tokenizer_model_type', type=str, default="unigram")
parser.add_argument('--target_tokenizer_model_type', type=str, default="unigram")
# Training arguments
parser.add_argument('--valid_ratio', type=float, default=0.1)
parser.add_argument('--num_workers', type=int, default=4)
parser.add_argument('--batch_size', type=int, default=32)
parser.add_argument('--lr', type=float, default=3e-05)
parser.add_argument('--num_epochs', type=int, default=10)
parser.add_argument('--log_every', type=int, default=20)
parser.add_argument('--gradient_clip_val', type=float, default=1.0)
parser.add_argument('--accumulate_grad_batches', type=int, default=1)
parser.add_argument('--save_every', type=int, default=10_000)
return parser
def main():
wandb.init(project="NLP Tasks - Machine Translation")
parser = _get_parser()
args = parser.parse_args()
torch.manual_seed(args.seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
np.random.seed(args.seed)
random.seed(args.seed)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
train_sources, train_targets, valid_sources, valid_targets = load_datas(args.data_dir, args.valid_ratio)
source_tokenizer = train_tokenizer(texts=train_sources,
vocab_size=args.source_vocab_size,
model_name=args.source_tokenizer_model_name,
model_type=args.source_tokenizer_model_type)
target_tokenizer = train_tokenizer(texts=train_targets,
vocab_size=args.target_vocab_size,
model_name=args.target_tokenizer_model_name,
model_type=args.target_tokenizer_model_type)
train_dataset = TranslationDataset(sources=train_sources,
targets=train_targets,
source_tokenizer=source_tokenizer,
target_tokenizer=target_tokenizer)
valid_dataset = TranslationDataset(sources=valid_sources,
targets=valid_targets,
source_tokenizer=source_tokenizer,
target_tokenizer=target_tokenizer)
train_loader = DataLoader(dataset=train_dataset,
num_workers=args.num_workers,
collate_fn=partial(collate_fn, pad_token_id=source_tokenizer.pad_id()),
batch_size=args.batch_size,
drop_last=False)
valid_loader = DataLoader(dataset=valid_dataset,
num_workers=args.num_workers,
collate_fn=partial(collate_fn, pad_token_id=target_tokenizer.pad_id()),
batch_size=args.batch_size,
drop_last=False)
model = nn.DataParallel(Transformer(args.source_vocab_size, args.target_vocab_size))
wandb.watch(model)
criterion = nn.CrossEntropyLoss(ignore_index=target_tokenizer.PieceToId('<pad>'), reduction='mean')
optimizer = torch.optim.Adam(model.parameters(), lr=args.lr)
scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer=optimizer,
max_lr=args.lr,
epochs=args.num_epochs,
steps_per_epoch=len(train_loader),
anneal_strategy='linear')
MachineTranslationTrainer(
model=model,
train_loader=train_loader,
valid_loader=valid_loader,
criterion=criterion,
optimizer=optimizer,
scheduler=scheduler,
num_epochs=args.num_epochs,
device=device,
tokenizer=target_tokenizer,
gradient_clip_val=args.gradient_clip_val,
log_every=args.log_every,
save_every=args.save_every,
save_dir=args.save_dir,
accumulate_grad_batches=args.accumulate_grad_batches,
).fit()
if __name__ == '__main__':
main()
|
lijek/StationAPI | station-level-events-v0/src/main/java/net/modificationstation/stationapi/mixin/level/client/MixinChunkCache.java | <reponame>lijek/StationAPI
package net.modificationstation.stationapi.mixin.level.client;
import net.minecraft.level.Level;
import net.minecraft.level.chunk.ChunkCache;
import net.minecraft.level.source.LevelSource;
import net.modificationstation.stationapi.api.StationAPI;
import net.modificationstation.stationapi.api.event.level.gen.LevelGenEvent;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.util.*;
@Mixin(ChunkCache.class)
public class MixinChunkCache {
@Shadow
private Level level;
@Shadow
private LevelSource levelSource;
private Random modRandom;
@Inject(method = "decorate(Lnet/minecraft/level/source/LevelSource;II)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/level/source/LevelSource;decorate(Lnet/minecraft/level/source/LevelSource;II)V", shift = At.Shift.AFTER))
private void onPopulate(LevelSource levelSource, int chunkX, int chunkZ, CallbackInfo ci) {
int blockX = chunkX * 16;
int blockZ = chunkZ * 16;
if (modRandom == null)
modRandom = new Random();
modRandom.setSeed(level.getSeed());
long xRandomMultiplier = (modRandom.nextLong() / 2L) * 2L + 1L;
long zRandomMultiplier = (modRandom.nextLong() / 2L) * 2L + 1L;
modRandom.setSeed((long) chunkX * xRandomMultiplier + (long) chunkZ * zRandomMultiplier ^ level.getSeed());
StationAPI.EVENT_BUS.post(new LevelGenEvent.ChunkDecoration(level, this.levelSource, level.getBiomeSource().getBiome(blockX + 16, blockZ + 16), blockX, blockZ, modRandom));
}
}
|
iwyg/jmg-example | public/src/playground/index.js | <filename>public/src/playground/index.js
import 'styles/playground';
import 'babel-polyfill';
import 'modernizr';
import ObjectFit from 'object-fit';
import React from 'react';
import {render} from 'react-dom';
import {Provider} from 'react-redux';
import App from 'playground/components/App';
import configureStore from 'playground/modules/store';
import {ENV, PRODUCTION} from 'runtime/constants';
render(
<Provider store={configureStore()}>
<App limitImages={50} defaults={JMG_CONFIG}/>
</Provider>,
document.getElementById('main')
);
ObjectFit.polyfill({
selector: '.preview-image img',
fittype: 'contain',
disableCrossdomain: true
});
console.log('%c' + document.title, 'background:#90a4ae;color:white;font-weight: bold;padding:2px 4px');
if (ENV !== PRODUCTION) {
console.log('%crunning in ', 'color:lime', ENV);
}
|
ThorntonMatthewD/caseflow | app/models/etl/decision_review/appeal.rb | <filename>app/models/etl/decision_review/appeal.rb<gh_stars>100-1000
# frozen_string_literal: true
class ETL::DecisionReview::Appeal < ETL::DecisionReview
class << self
def unique_attributes
[
:closest_regional_office,
:docket_range_date,
:docket_type,
:established_at,
:poa_participant_id,
:stream_docket_number,
:stream_type,
:target_decision_date
]
end
def merge_original_attributes_to_target(original, target)
super
target.benefit_type = original.request_issues.pluck(:benefit_type).uniq.join(",")
target
end
end
end
|
valiro21/FastTrainService | Utils/src/Calendar.cpp | //
// Created by vrosca on 1/10/17.
//
#include <ctime>
#include "Calendar.hpp"
int Calendar::days_in_month[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
Calendar::Calendar() {
time_t t = time(0); // get time now
struct tm * now = localtime( & t );
year = (unsigned int) (now->tm_year + 1900);
month = (unsigned int) now->tm_mon + 1;
day = (unsigned int) (now->tm_mday);
hour = (unsigned int) now->tm_hour;
minute = (unsigned int) now->tm_min;
second = (unsigned int) now->tm_sec;
}
int Calendar::get_days_of_month (int month) {
if (month == 2 && isLeapYear ()) {
return 29;
}
return days_in_month[month];
}
void Calendar::add (int val, int type) {
int tmp_val, reminder = 0;
switch (type) {
case SECOND:
tmp_val = second + val;
if (tmp_val < 0) {
second = (unsigned int) (60 + tmp_val % 60);
if (second == 60) {
reminder = 1;
second = 0;
}
reminder += -1 + tmp_val / 60;
}
else {
second = (unsigned int) (tmp_val % 60);
reminder = tmp_val / 60;
}
add(reminder, MINUTE);
break;
case MINUTE:
tmp_val = minute + val;
if (tmp_val < 0) {
minute = (unsigned int) (60 + tmp_val % 60);
if (minute == 60) {
reminder = 1;
minute = 0;
}
reminder = -1 + tmp_val / 60;
}
else {
minute = (unsigned int) (tmp_val % 60);
reminder = tmp_val / 60;
}
add(reminder, HOUR);
break;
case HOUR:
tmp_val = hour + val;
if (tmp_val < 0) {
hour = (unsigned int) (24 + tmp_val % 24);
if (hour == 24) {
reminder = 1;
hour = 0;
}
reminder = -1 + tmp_val / 24;
}
else {
hour = (unsigned int) (tmp_val % 24);
reminder = tmp_val / 24;
}
add(reminder, DAY);
break;
case DAY:
tmp_val = day + val;
while (tmp_val > get_days_of_month(this->month)) {
tmp_val -= get_days_of_month(this->month);
month++;
if (month > 12) {
month = 1;
year++;
}
}
while (tmp_val < 1) {
unsigned int m = month - 1;
if (m == 0) {
m = 12;
year--;
}
tmp_val += get_days_of_month(m);
month = m;
}
day = (unsigned int) tmp_val;
break;
default:
return;
}
}
void Calendar::set (int val, int type) {
switch (type) {
case SECOND:
if (0 <= val && val < 60) {
second = (unsigned int) val;
}
break;
case MINUTE:
if (0 <= val && val < 60) {
minute = (unsigned int) val;
}
break;
case HOUR:
if (0 <= val && val < 24) {
hour = (unsigned int) val;
}
break;
case DAY:
if (1 <= val && val <= get_days_of_month(month))
day = (unsigned int) val;
break;
case MONTH:
if (1 <= val && val <= 12)
month = (unsigned int) val;
break;
case YEAR:
year = (unsigned int) val;
break;
default:
return;
}
}
unsigned int Calendar::get (int type) {
switch (type) {
case SECOND:
return second;
case MINUTE:
return minute;
case HOUR:
return hour;
case DAY:
return day;
case MONTH:
return month;
case YEAR:
return year;
default:
return 0;
}
}
bool Calendar::isLeapYear () {
if (year % 4) return false;
else if (year % 100) return true;
else return year % 400 == 0;
}
bool Calendar::isLeapYear (int year) {
if (year % 4) return false;
else if (year % 100) return true;
else return year % 400 == 0;
}
std::string Calendar::to_string() {
return std::to_string(get(DAY)) + "/"+ std::to_string(get(MONTH)) + "/" + std::to_string(get(YEAR));
}
json Calendar::toJSON () {
json calendar;
calendar["year"] = get(YEAR);
calendar["month"] = get(MONTH);
calendar["day"] = get(DAY);
calendar["hour"] = get(HOUR);
calendar["minute"] = get(MINUTE);
calendar["second"] = get(SECOND);
return calendar;
}
Calendar Calendar::fromJSON (json json_calendar) {
Calendar calendar;
calendar.set(json_calendar["year"].get<int>(), Calendar::YEAR);
calendar.set(json_calendar["month"].get<int>(), Calendar::MONTH);
calendar.set(json_calendar["day"].get<int>(), Calendar::DAY);
calendar.set(json_calendar["hour"].get<int>(), Calendar::HOUR);
calendar.set(json_calendar["minute"].get<int>(), Calendar::MINUTE);
calendar.set(json_calendar["second"].get<int>(), Calendar::SECOND);
return calendar;
}
int Calendar::getDayOfWeek () const {
int k = day;
int m = month - 2;
if (m < 1) m = 12 + m;
int C = year / 100;
int Y = year % 100;
if (month <= 2) Y--;
int reminder = (k + int (2.6 * (double)m - 0.2) - 2 * C + Y + int ((double)Y / 4.0) + int ((double)C / 4.0));
if (reminder < 0) {
reminder = 7 + (reminder % 7);
}
else{
reminder = reminder % 7;
}
if (reminder == 0) reminder = 7;
return reminder;
}
std::string Calendar::getDayName () {
int dayOfWeek = getDayOfWeek ();
switch (dayOfWeek) {
case 1: return "monday";
case 2: return "tuesday";
case 3: return "wednesday";
case 4: return "thursday";
case 5: return "friday";
case 6: return "saturday";
case 7: return "sunday";
default: return "date not found";
}
}
Calendar::Calendar(int year, int month, int day, int hour, int minute, int second) {
set(year, Calendar::YEAR);
set(month, Calendar::MONTH);
set(day, Calendar::DAY);
set(hour, Calendar::HOUR);
set(minute, Calendar::MINUTE);
set(second, Calendar::SECOND);
}
long long Calendar::toUnixTime () {
long long time = 0;
time += get(Calendar::SECOND);
time += get(Calendar::MINUTE) * 60;
time += get(Calendar::HOUR) * 60LL * 60LL;
time += ((long long)get(Calendar::DAY) - 1) * 24LL * 60LL * 60LL;
int m = get(Calendar::MONTH);
while (m > 1) {
time += (long long)(get_days_of_month(m-1)) * 24LL * 60LL * 60LL;
m--;
}
int y = get(Calendar::YEAR);
while (y > 1970) {
long long d = 365;
if (Calendar::isLeapYear(y-1))
d++;
time += d * 24 * 60 * 60;
y--;
}
return time * 1000;
}
void Calendar::setDayTimeUnix (unsigned long long time) {
int h = time / 3600; time -= h * 3600;
int m = time / 60;
int s = time % 60;
set (s, Calendar::SECOND);
set (m, Calendar::MINUTE);
set (h, Calendar::HOUR);
}
unsigned long long Calendar::getDayTimeUnix () {
return get(Calendar::HOUR) * 60 * 60 + get(Calendar::MINUTE) * 60 + get(Calendar::SECOND);
}
std::string Calendar::getDayTimeStr () {
std::string h = Calendar::toZeroStr (get(Calendar::HOUR));
std::string m = Calendar::toZeroStr (get(Calendar::MINUTE));
std::string s = Calendar::toZeroStr (get(Calendar::SECOND));
return h + ':' + m + ':' + s;
}
std::string Calendar::toZeroStr (int val) {
std::string s;
if (val < 10) {
s = "0";
}
s += std::to_string(val);
return s;
}
std::string Calendar::to_complete_string () {
std::string s = to_string ();
s += " ";
s += getDayTimeStr();
return s;
} |
p-g-krish/deepmac-tracker | data/js/9a/56/4b/00/00/00.24.js | <reponame>p-g-krish/deepmac-tracker
deepmacDetailCallback("9a564b000000/24",[{"a":"2800 Lockheed Way Carson City Nevada US 89706","o":"Cubix Corporation","d":"2017-05-28","t":"add","s":"ieee","c":"US"}]);
|
andtorg/pentaho-kettle | test/org/pentaho/di/trans/steps/dimensionlookup/DimensionLookupTest.java | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* 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 org.pentaho.di.trans.steps.dimensionlookup;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import org.junit.Before;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.pentaho.di.core.database.Database;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.logging.LogLevel;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.StepMeta;
public class DimensionLookupTest {
private StepMeta mockStepMeta;
private DimensionLookupMeta mockDimensionLookupMeta;
private DimensionLookupData mockDimensionLookupData;
private DatabaseMeta mockDatabaseMeta;
private RowMetaInterface mockOutputRowMeta;
private TransMeta mockTransMeta;
private Trans mockTrans;
private Connection mockConnection;
private DimensionLookup dimensionLookup;
@Before
public void setup() {
mockStepMeta = mock( StepMeta.class );
mockDimensionLookupMeta = mock( DimensionLookupMeta.class );
mockDimensionLookupData = mock( DimensionLookupData.class );
mockDatabaseMeta = mock( DatabaseMeta.class );
mockOutputRowMeta = mock( RowMetaInterface.class );
mockTransMeta = mock( TransMeta.class );
mockTrans = mock( Trans.class );
mockConnection = mock( Connection.class );
mockDimensionLookupData.outputRowMeta = mockOutputRowMeta;
String stepName = "testName";
when( mockStepMeta.getName() ).thenReturn( stepName );
when( mockTransMeta.findStep( stepName ) ).thenReturn( mockStepMeta );
when( mockTrans.getLogLevel() ).thenReturn( LogLevel.ROWLEVEL );
dimensionLookup = new DimensionLookup( mockStepMeta, mockDimensionLookupData, 0, mockTransMeta, mockTrans );
dimensionLookup.init( mockDimensionLookupMeta, mockDimensionLookupData );
}
public void prepareMocksForInsertTest() {
mockDimensionLookupData.schemaTable = "testSchemaTable";
ValueMetaInterface mockKeyValueMeta = mock( ValueMetaInterface.class );
when( mockDimensionLookupMeta.getDatabaseMeta() ).thenReturn( mockDatabaseMeta );
when( mockDatabaseMeta.quoteField( anyString() ) ).thenAnswer( new Answer<String>() {
public String answer( InvocationOnMock invocation ) throws Throwable {
return "\"" + invocation.getArguments()[0] + "\"";
}
} );
String keyField = "testKeyField";
when( mockDimensionLookupMeta.getKeyField() ).thenReturn( keyField );
when( mockDimensionLookupMeta.getVersionField() ).thenReturn( "testVersionField" );
when( mockDimensionLookupMeta.getDateFrom() ).thenReturn( "1900-01-01" );
when( mockDimensionLookupMeta.getDateTo() ).thenReturn( "1901-01-01" );
when( mockDimensionLookupMeta.getKeyLookup() ).thenReturn( new String[] {} );
when( mockDimensionLookupMeta.getFieldLookup() ).thenReturn( new String[] {} );
when( mockDimensionLookupMeta.getFieldUpdate() ).thenReturn( new int[] {} );
mockDimensionLookupData.keynrs = new int[] {};
mockDimensionLookupData.fieldnrs = new int[] {};
Database mockDatabase = mock( Database.class );
when( mockDatabase.getConnection() ).thenReturn( mockConnection );
mockDimensionLookupData.db = mockDatabase;
when( mockKeyValueMeta.getName() ).thenReturn( "testKey" );
when( mockOutputRowMeta.getValueMeta( 0 ) ).thenReturn( mockKeyValueMeta );
}
@Test
public void testDimInsertPreparesStatementWithReturnKeysForNullTechnicalKey() throws KettleException,
SQLException {
RowMetaInterface mockMetaInterface = mock( RowMetaInterface.class );
Object[] row = new Object[0];
Long technicalKey = null;
boolean newEntry = false;
Long versionNr = 2L;
Date dateFrom = new Date();
Date dateTo = new Date();
prepareMocksForInsertTest();
dimensionLookup.dimInsert( mockMetaInterface, row, technicalKey, newEntry, versionNr, dateFrom, dateTo );
// Insert statement with keys
verify( mockConnection, times( 1 ) ).prepareStatement( anyString(), eq( Statement.RETURN_GENERATED_KEYS ) );
// Update statement without
verify( mockConnection, times( 1 ) ).prepareStatement( anyString() );
}
@Test
public void testDimInsertPreparesStatementWithReturnKeysForNotNullTechnicalKey() throws KettleException,
SQLException {
RowMetaInterface mockMetaInterface = mock( RowMetaInterface.class );
Object[] row = new Object[0];
Long technicalKey = 1L;
boolean newEntry = false;
Long versionNr = 2L;
Date dateFrom = new Date();
Date dateTo = new Date();
prepareMocksForInsertTest();
dimensionLookup.dimInsert( mockMetaInterface, row, technicalKey, newEntry, versionNr, dateFrom, dateTo );
// Neither insert nor update should have keys
verify( mockConnection, times( 2 ) ).prepareStatement( anyString() );
}
}
|
commerceboard/geecommerce | core/src/main/java/com/geecommerce/core/json/genson/AttributeConverter.java | package com.geecommerce.core.json.genson;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.geecommerce.core.App;
import com.geecommerce.core.enums.AttributeType;
import com.geecommerce.core.enums.BackendType;
import com.geecommerce.core.enums.FilterIndexField;
import com.geecommerce.core.enums.FilterType;
import com.geecommerce.core.enums.FrontendInput;
import com.geecommerce.core.enums.FrontendOutput;
import com.geecommerce.core.enums.InputType;
import com.geecommerce.core.enums.ProductType;
import com.geecommerce.core.enums.Scope;
import com.geecommerce.core.service.annotation.Profile;
import com.geecommerce.core.system.attribute.model.Attribute;
import com.geecommerce.core.system.attribute.model.AttributeOption;
import com.geecommerce.core.type.ContextObject;
import com.geecommerce.core.type.Id;
import com.owlike.genson.Context;
import com.owlike.genson.Converter;
import com.owlike.genson.stream.ObjectReader;
import com.owlike.genson.stream.ObjectWriter;
import com.owlike.genson.stream.ValueType;
@Profile
public class AttributeConverter implements Converter<Attribute> {
private static final String KEY_ID = "id";
private static final String KEY_ID2 = "id2";
private static final String KEY_CODE = "code";
private static final String KEY_CODE2 = "code2";
private static final String KEY_TARGET_OBJECT_ID = "targetObjectId";
private static final String KEY_TYPE = "type";
private static final String KEY_SCOPES = "scopes";
private static final String KEY_EDITABLE = "editable";
private static final String KEY_ENABLED = "enabled";
private static final String KEY_SEARCHABLE = "searchable";
private static final String KEY_INCLUDE_IN_SEARCH_INDEX = "includeInSearchIndex";
private static final String KEY_FRONTEND_INPUT = "frontendInput";
private static final String KEY_FRONTEND_OUTPUT = "frontendOutput";
private static final String KEY_FRONTEND_LABEL = "frontendLabel";
private static final String KEY_FRONTEND_FORMAT = "frontendFormat";
private static final String KEY_FRONTEND_STYLE = "frontendStyle";
private static final String KEY_FRONTEND_CLASS = "frontendClass";
private static final String KEY_BACKEND_LABEL = "backendLabel";
private static final String KEY_BACKEND_TYPE = "backendType";
private static final String KEY_BACKEND_NOTE = "backendNote";
private static final String KEY_DEFAULT_VALUE = "defaultValue";
private static final String KEY_INPUT_TYPE = "inputType";
private static final String KEY_IS_OPTION_ATTRIBUTE = "optionAttribute";
private static final String KEY_IS_MULTIPLE_ALLOWED = "allowMultipleValues";
private static final String KEY_IS_I18N = "i18n";
private static final String KEY_OPTIONS = "options";
private static final String KEY_LINKED_ATTRIBUTE_IDS = "linkedAttributeIds";
private static final String KEY_PRODUCT_TYPES = "productTypes";
private static final String KEY_ALLOW_NEW_OPTIONS_VIA_IMPORT = "allowNewOptionsViaImport";
// Validation settings
public static final String KEY_VALIDATION_MIN = "validationMin";
public static final String KEY_VALIDATION_MAX = "validationMax";
public static final String KEY_VALIDATION_MIN_LENGTH = "validationMinLength";
public static final String KEY_VALIDATION_MAX_LENGTH = "validationMaxLength";
public static final String KEY_VALIDATION_FUTURE = "validationFuture";
public static final String KEY_VALIDATION_PAST = "validationPast";
public static final String KEY_VALIDATION_ASSERT_TRUE = "validationAssertTrue";
public static final String KEY_VALIDATION_ASSERT_FALSE = "validationAssertFalse";
public static final String KEY_VALIDATION_PATTERN = "validationPattern";
public static final String KEY_VALIDATION_SCRIPT = "validationScript";
public static final String KEY_VALIDATION_MESSAGE = "validationMessage";
// ProductList filter settings
public static final String KEY_INCLUDE_IN_PRODUCT_LIST_FILTER = "includeInProductListFilter";
public static final String KEY_PRODUCT_LIST_FILTER_TYPE = "productListFilterType";
public static final String KEY_PRODUCT_LIST_FILTER_INDEX_FIELDS = "productListFilterIndexFields";
public static final String KEY_PRODUCT_LIST_FILTER_KEY_ALIAS = "productListFilterKeyAlias";
public static final String KEY_PRODUCT_LIST_FILTER_FORMAT_LABEL = "productListFilterFormatLabel";
public static final String KEY_PRODUCT_LIST_FILTER_FORMAT_VALUE = "productListFilterFormatValue";
public static final String KEY_PRODUCT_LIST_FILTER_PARSE_VALUE = "productListFilterParseValue";
public static final String KEY_PRODUCT_LIST_FILTER_MULTI = "productListFilterMulti";
public static final String KEY_PRODUCT_LIST_FILTER_INHERIT_FROM_PARENT = "productListFilterInheritFromParent";
public static final String KEY_PRODUCT_LIST_FILTER_INCLUDE_CHILDREN = "productListFilterIncludeChildren";
public static final String KEY_PRODUCT_LIST_FILTER_POSITION = "productListFilterPosition";
public static final String KEY_SHOW_IN_QUERY = "showInQuery";
@SuppressWarnings("unchecked")
@Override
public Attribute deserialize(ObjectReader reader, Context ctx) throws IOException {
Attribute attr = App.get().model(Attribute.class);
ContextObjectConverter ctxObjConverter = new ContextObjectConverter();
ObjectReader obj = reader.beginObject();
while (obj.hasNext()) {
ValueType type = obj.next();
if (KEY_ID.equals(obj.name())) {
attr.setId(Id.valueOf(obj.valueAsString()));
} else if (KEY_ID2.equals(obj.name())) {
attr.setId2(Id.valueOf(obj.valueAsString()));
} else if (KEY_CODE.equals(obj.name())) {
attr.setCode(obj.valueAsString());
} else if (KEY_CODE2.equals(obj.name())) {
attr.setCode2(obj.valueAsString());
} else if (KEY_TARGET_OBJECT_ID.equals(obj.name())) {
attr.setTargetObjectId(Id.valueOf(obj.valueAsString()));
} else if (KEY_TYPE.equals(obj.name())) {
attr.setType(AttributeType.valueOf(obj.valueAsString()));
} else if (KEY_SCOPES.equals(obj.name())) {
ObjectReader arr = obj.beginArray();
List<Scope> scopes = new ArrayList<>();
while (arr.hasNext()) {
ValueType vt = arr.next();
if (vt == ValueType.STRING)
scopes.add(Scope.valueOf(obj.valueAsString()));
}
attr.setScopes(scopes);
obj.endArray();
} else if (KEY_EDITABLE.equals(obj.name())) {
attr.setEditable(obj.valueAsBoolean());
} else if (KEY_ENABLED.equals(obj.name())) {
attr.setEnabled(obj.valueAsBoolean());
} else if (KEY_SEARCHABLE.equals(obj.name())) {
attr.setSearchable(obj.valueAsBoolean());
} else if (KEY_INCLUDE_IN_SEARCH_INDEX.equals(obj.name())) {
attr.setIncludeInSearchIndex(obj.valueAsBoolean());
} else if (KEY_FRONTEND_INPUT.equals(obj.name())) {
attr.setFrontendInput(FrontendInput.valueOf(obj.valueAsString()));
} else if (KEY_FRONTEND_OUTPUT.equals(obj.name())) {
attr.setFrontendOutput(FrontendOutput.valueOf(obj.valueAsString()));
} else if (KEY_FRONTEND_LABEL.equals(obj.name())) {
attr.setFrontendLabel((ContextObject<String>) ctxObjConverter.deserialize(obj, ctx));
} else if (KEY_FRONTEND_FORMAT.equals(obj.name())) {
attr.setFrontendFormat((ContextObject<String>) ctxObjConverter.deserialize(obj, ctx));
} else if (KEY_FRONTEND_STYLE.equals(obj.name())) {
attr.setFrontendStyle(obj.valueAsString());
} else if (KEY_FRONTEND_CLASS.equals(obj.name())) {
attr.setFrontendClass(obj.valueAsString());
} else if (KEY_BACKEND_LABEL.equals(obj.name())) {
attr.setBackendLabel((ContextObject<String>) ctxObjConverter.deserialize(obj, ctx));
} else if (KEY_BACKEND_TYPE.equals(obj.name())) {
attr.setBackendType(BackendType.valueOf(obj.valueAsString()));
} else if (KEY_BACKEND_NOTE.equals(obj.name())) {
attr.setBackendNote((ContextObject<String>) ctxObjConverter.deserialize(obj, ctx));
} else if (KEY_DEFAULT_VALUE.equals(obj.name())) {
attr.setDefaultValue((ContextObject<String>) ctxObjConverter.deserialize(obj, ctx));
} else if (KEY_VALIDATION_MIN.equals(obj.name())) {
attr.setValidationMin((ContextObject<Double>) ctxObjConverter.deserialize(obj, ctx));
} else if (KEY_VALIDATION_MAX.equals(obj.name())) {
attr.setValidationMax((ContextObject<Double>) ctxObjConverter.deserialize(obj, ctx));
} else if (KEY_VALIDATION_MIN_LENGTH.equals(obj.name())) {
attr.setValidationMinLength((ContextObject<Integer>) ctxObjConverter.deserialize(obj, ctx));
} else if (KEY_VALIDATION_MAX_LENGTH.equals(obj.name())) {
attr.setValidationMaxLength((ContextObject<Integer>) ctxObjConverter.deserialize(obj, ctx));
} else if (KEY_VALIDATION_FUTURE.equals(obj.name())) {
attr.setValidationFuture((ContextObject<Boolean>) ctxObjConverter.deserialize(obj, ctx));
} else if (KEY_VALIDATION_PAST.equals(obj.name())) {
attr.setValidationPast((ContextObject<Boolean>) ctxObjConverter.deserialize(obj, ctx));
} else if (KEY_VALIDATION_ASSERT_TRUE.equals(obj.name())) {
attr.setValidationAssertTrue((ContextObject<Boolean>) ctxObjConverter.deserialize(obj, ctx));
} else if (KEY_VALIDATION_ASSERT_FALSE.equals(obj.name())) {
attr.setValidationAssertFalse((ContextObject<Boolean>) ctxObjConverter.deserialize(obj, ctx));
} else if (KEY_VALIDATION_PATTERN.equals(obj.name())) {
attr.setValidationPattern((ContextObject<String>) ctxObjConverter.deserialize(obj, ctx));
} else if (KEY_VALIDATION_SCRIPT.equals(obj.name())) {
attr.setValidationScript((ContextObject<String>) ctxObjConverter.deserialize(obj, ctx));
} else if (KEY_VALIDATION_MESSAGE.equals(obj.name())) {
attr.setValidationMessage((ContextObject<String>) ctxObjConverter.deserialize(obj, ctx));
} else if (KEY_INPUT_TYPE.equals(obj.name())) {
attr.setInputType(InputType.valueOf(obj.valueAsString()));
} else if (KEY_IS_OPTION_ATTRIBUTE.equals(obj.name())) {
attr.setOptionAttribute(obj.valueAsBoolean());
} else if (KEY_IS_MULTIPLE_ALLOWED.equals(obj.name())) {
attr.setAllowMultipleValues(obj.valueAsBoolean());
} else if (KEY_IS_I18N.equals(obj.name())) {
attr.setI18n(obj.valueAsBoolean());
} else if (KEY_INCLUDE_IN_PRODUCT_LIST_FILTER.equals(obj.name())) {
attr.setIncludeInProductListFilter(obj.valueAsBoolean());
} else if (KEY_PRODUCT_LIST_FILTER_TYPE.equals(obj.name())) {
attr.setProductListFilterType(FilterType.valueOf(obj.valueAsString()));
} else if (KEY_PRODUCT_LIST_FILTER_INDEX_FIELDS.equals(obj.name())) {
ObjectReader arr = obj.beginArray();
List<FilterIndexField> indexFields = new ArrayList<>();
while (arr.hasNext()) {
ValueType vt = arr.next();
if (vt == ValueType.STRING)
indexFields.add(FilterIndexField.valueOf(obj.valueAsString()));
}
attr.setProductListFilterIndexFields(indexFields);
obj.endArray();
} else if (KEY_PRODUCT_LIST_FILTER_KEY_ALIAS.equals(obj.name())) {
attr.setProductListFilterKeyAlias((ContextObject<String>) ctxObjConverter.deserialize(obj, ctx));
} else if (KEY_PRODUCT_LIST_FILTER_FORMAT_LABEL.equals(obj.name())) {
attr.setProductListFilterFormatLabel((ContextObject<String>) ctxObjConverter.deserialize(obj, ctx));
} else if (KEY_PRODUCT_LIST_FILTER_FORMAT_VALUE.equals(obj.name())) {
attr.setProductListFilterFormatValue((ContextObject<String>) ctxObjConverter.deserialize(obj, ctx));
} else if (KEY_PRODUCT_LIST_FILTER_PARSE_VALUE.equals(obj.name())) {
attr.setProductListFilterParseValue((ContextObject<String>) ctxObjConverter.deserialize(obj, ctx));
} else if (KEY_PRODUCT_LIST_FILTER_MULTI.equals(obj.name())) {
attr.setProductListFilterMulti(obj.valueAsBoolean());
} else if (KEY_PRODUCT_LIST_FILTER_INHERIT_FROM_PARENT.equals(obj.name())) {
attr.setProductListFilterInheritFromParent(obj.valueAsBoolean());
} else if (KEY_PRODUCT_LIST_FILTER_INCLUDE_CHILDREN.equals(obj.name())) {
attr.setProductListFilterIncludeChildren(obj.valueAsBoolean());
} else if (KEY_PRODUCT_LIST_FILTER_POSITION.equals(obj.name())) {
attr.setProductListFilterPosition(obj.valueAsInt());
} else if (KEY_SHOW_IN_QUERY.equals(obj.name())) {
attr.setShowInQuery(obj.valueAsBoolean());
} else if (KEY_LINKED_ATTRIBUTE_IDS.equals(obj.name())) {
List<Id> linkedAttributeIds = new ArrayList<>();
if (type == ValueType.ARRAY) {
ObjectReader array = obj.beginArray();
while (array.hasNext()) {
array.next();
linkedAttributeIds.add(Id.valueOf(array.valueAsString()));
}
obj.endArray();
} else {
linkedAttributeIds.add(Id.valueOf(obj.valueAsString()));
}
if (linkedAttributeIds.size() > 0)
attr.setLinkedAttributeIds(linkedAttributeIds);
} else if (KEY_PRODUCT_TYPES.equals(obj.name())) {
Set<ProductType> productTypes = new HashSet<>();
if (type == ValueType.ARRAY) {
ObjectReader array = obj.beginArray();
while (array.hasNext()) {
array.next();
productTypes.add(ProductType.valueOf(array.valueAsString()));
}
obj.endArray();
} else {
productTypes.add(ProductType.valueOf(obj.valueAsString()));
}
if (productTypes.size() > 0)
attr.setProductTypes(productTypes);
} else if (KEY_ALLOW_NEW_OPTIONS_VIA_IMPORT.equals(obj.name())) {
attr.setAllowNewOptionsViaImport(obj.valueAsBoolean());
}
}
reader.endObject();
return attr;
}
@Override
public void serialize(Attribute attr, ObjectWriter writer, Context ctx) throws IOException {
if (attr != null) {
ContextObjectConverter ctxObjConverter = new ContextObjectConverter();
AttributeOptionConverter attributeOptionConverter = new AttributeOptionConverter();
writer.beginObject();
if (attr.getId() != null && !ConvertUtil.ignoreProperty(KEY_ID)) {
writer.writeName(KEY_ID);
writer.writeValue(attr.getId().str());
}
if (attr.getId2() != null && !ConvertUtil.ignoreProperty(KEY_ID2)) {
writer.writeName(KEY_ID2);
writer.writeValue(attr.getId2().str());
}
if (attr.getCode() != null && !ConvertUtil.ignoreProperty(KEY_CODE)) {
writer.writeName(KEY_CODE);
writer.writeValue(attr.getCode());
}
if (attr.getCode2() != null && !ConvertUtil.ignoreProperty(KEY_CODE2)) {
writer.writeName(KEY_CODE2);
writer.writeValue(attr.getCode2());
}
if (attr.getTargetObjectId() != null && !ConvertUtil.ignoreProperty(KEY_TARGET_OBJECT_ID)) {
writer.writeName(KEY_TARGET_OBJECT_ID);
writer.writeValue(attr.getTargetObjectId().str());
}
if (attr.getType() != null && !ConvertUtil.ignoreProperty(KEY_TYPE)) {
writer.writeName(KEY_TYPE);
writer.writeValue(attr.getType().name());
}
if (attr.getScopes() != null && !ConvertUtil.ignoreProperty(KEY_SCOPES)) {
writer.writeName(KEY_SCOPES);
writer.beginArray();
for (Scope scope : attr.getScopes()) {
writer.writeValue(scope.name());
}
writer.endArray();
}
if (!ConvertUtil.ignoreProperty(KEY_EDITABLE)) {
writer.writeName(KEY_EDITABLE);
writer.writeValue(attr.isEditable());
}
if (!ConvertUtil.ignoreProperty(KEY_ENABLED)) {
writer.writeName(KEY_ENABLED);
writer.writeValue(attr.isEnabled());
}
if (!ConvertUtil.ignoreProperty(KEY_SEARCHABLE)) {
writer.writeName(KEY_SEARCHABLE);
writer.writeValue(attr.isSearchable());
}
if (!ConvertUtil.ignoreProperty(KEY_INCLUDE_IN_SEARCH_INDEX)) {
writer.writeName(KEY_INCLUDE_IN_SEARCH_INDEX);
writer.writeValue(attr.isIncludeInSearchIndex());
}
if (attr.getFrontendInput() != null && !ConvertUtil.ignoreProperty(KEY_FRONTEND_INPUT)) {
writer.writeName(KEY_FRONTEND_INPUT);
writer.writeValue(attr.getFrontendInput().name());
}
if (attr.getFrontendOutput() != null && !ConvertUtil.ignoreProperty(KEY_FRONTEND_OUTPUT)) {
writer.writeName(KEY_FRONTEND_OUTPUT);
writer.writeValue(attr.getFrontendOutput().name());
}
if (attr.getFrontendLabel() != null && !ConvertUtil.ignoreProperty(KEY_FRONTEND_LABEL)) {
writer.writeName(KEY_FRONTEND_LABEL);
ctxObjConverter.serialize(attr.getFrontendLabel(), writer, ctx);
}
if (attr.getFrontendFormat() != null && !ConvertUtil.ignoreProperty(KEY_FRONTEND_FORMAT)) {
writer.writeName(KEY_FRONTEND_FORMAT);
ctxObjConverter.serialize(attr.getFrontendFormat(), writer, ctx);
}
if (attr.getFrontendStyle() != null && !ConvertUtil.ignoreProperty(KEY_FRONTEND_STYLE)) {
writer.writeName(KEY_FRONTEND_STYLE);
writer.writeValue(attr.getFrontendStyle());
}
if (attr.getFrontendClass() != null && !ConvertUtil.ignoreProperty(KEY_FRONTEND_CLASS)) {
writer.writeName(KEY_FRONTEND_CLASS);
writer.writeValue(attr.getFrontendClass());
}
if (attr.getBackendLabel() != null && !ConvertUtil.ignoreProperty(KEY_BACKEND_LABEL)) {
writer.writeName(KEY_BACKEND_LABEL);
ctxObjConverter.serialize(attr.getBackendLabel(), writer, ctx);
}
if (attr.getBackendType() != null && !ConvertUtil.ignoreProperty(KEY_BACKEND_TYPE)) {
writer.writeName(KEY_BACKEND_TYPE);
writer.writeValue(attr.getBackendType().name());
}
if (attr.getBackendNote() != null && !ConvertUtil.ignoreProperty(KEY_BACKEND_NOTE)) {
writer.writeName(KEY_BACKEND_NOTE);
ctxObjConverter.serialize(attr.getBackendNote(), writer, ctx);
}
if (attr.getDefaultValue() != null && !ConvertUtil.ignoreProperty(KEY_DEFAULT_VALUE)) {
writer.writeName(KEY_DEFAULT_VALUE);
ctxObjConverter.serialize(attr.getDefaultValue(), writer, ctx);
}
if (attr.getValidationMin() != null && !ConvertUtil.ignoreProperty(KEY_VALIDATION_MIN)) {
writer.writeName(KEY_VALIDATION_MIN);
ctxObjConverter.serialize(attr.getValidationMin(), writer, ctx);
}
if (attr.getValidationMax() != null && !ConvertUtil.ignoreProperty(KEY_VALIDATION_MAX)) {
writer.writeName(KEY_VALIDATION_MAX);
ctxObjConverter.serialize(attr.getValidationMax(), writer, ctx);
}
if (attr.getValidationMinLength() != null && !ConvertUtil.ignoreProperty(KEY_VALIDATION_MIN_LENGTH)) {
writer.writeName(KEY_VALIDATION_MIN_LENGTH);
ctxObjConverter.serialize(attr.getValidationMinLength(), writer, ctx);
}
if (attr.getValidationMaxLength() != null && !ConvertUtil.ignoreProperty(KEY_VALIDATION_MAX_LENGTH)) {
writer.writeName(KEY_VALIDATION_MAX_LENGTH);
ctxObjConverter.serialize(attr.getValidationMaxLength(), writer, ctx);
}
if (attr.getValidationFuture() != null && !ConvertUtil.ignoreProperty(KEY_VALIDATION_FUTURE)) {
writer.writeName(KEY_VALIDATION_FUTURE);
ctxObjConverter.serialize(attr.getValidationFuture(), writer, ctx);
}
if (attr.getValidationPast() != null && !ConvertUtil.ignoreProperty(KEY_VALIDATION_PAST)) {
writer.writeName(KEY_VALIDATION_PAST);
ctxObjConverter.serialize(attr.getValidationPast(), writer, ctx);
}
if (attr.getValidationAssertTrue() != null && !ConvertUtil.ignoreProperty(KEY_VALIDATION_ASSERT_TRUE)) {
writer.writeName(KEY_VALIDATION_ASSERT_TRUE);
ctxObjConverter.serialize(attr.getValidationAssertTrue(), writer, ctx);
}
if (attr.getValidationAssertFalse() != null && !ConvertUtil.ignoreProperty(KEY_VALIDATION_ASSERT_FALSE)) {
writer.writeName(KEY_VALIDATION_ASSERT_FALSE);
ctxObjConverter.serialize(attr.getValidationAssertFalse(), writer, ctx);
}
if (attr.getValidationPattern() != null && !ConvertUtil.ignoreProperty(KEY_VALIDATION_PATTERN)) {
writer.writeName(KEY_VALIDATION_PATTERN);
ctxObjConverter.serialize(attr.getValidationPattern(), writer, ctx);
}
if (attr.getValidationScript() != null && !ConvertUtil.ignoreProperty(KEY_VALIDATION_SCRIPT)) {
writer.writeName(KEY_VALIDATION_SCRIPT);
ctxObjConverter.serialize(attr.getValidationScript(), writer, ctx);
}
if (attr.getValidationMessage() != null && !ConvertUtil.ignoreProperty(KEY_VALIDATION_MESSAGE)) {
writer.writeName(KEY_VALIDATION_MESSAGE);
ctxObjConverter.serialize(attr.getValidationMessage(), writer, ctx);
}
if (attr.getInputType() != null && !ConvertUtil.ignoreProperty(KEY_INPUT_TYPE)) {
writer.writeName(KEY_INPUT_TYPE);
writer.writeValue(attr.getInputType().name());
}
if (!ConvertUtil.ignoreProperty(KEY_IS_OPTION_ATTRIBUTE)) {
writer.writeName(KEY_IS_OPTION_ATTRIBUTE);
writer.writeValue(attr.isOptionAttribute());
}
if (!ConvertUtil.ignoreProperty(KEY_IS_MULTIPLE_ALLOWED)) {
writer.writeName(KEY_IS_MULTIPLE_ALLOWED);
writer.writeValue(attr.isAllowMultipleValues());
}
if (!ConvertUtil.ignoreProperty(KEY_IS_I18N)) {
writer.writeName(KEY_IS_I18N);
writer.writeValue(attr.isI18n());
}
if (!ConvertUtil.ignoreProperty(KEY_INCLUDE_IN_PRODUCT_LIST_FILTER)) {
writer.writeName(KEY_INCLUDE_IN_PRODUCT_LIST_FILTER);
writer.writeValue(attr.getIncludeInProductListFilter());
}
if (attr.getProductListFilterType() != null && !ConvertUtil.ignoreProperty(KEY_PRODUCT_LIST_FILTER_TYPE)) {
writer.writeName(KEY_PRODUCT_LIST_FILTER_TYPE);
writer.writeValue(attr.getProductListFilterType().name());
}
if (!ConvertUtil.ignoreProperty(KEY_ALLOW_NEW_OPTIONS_VIA_IMPORT)) {
writer.writeName(KEY_ALLOW_NEW_OPTIONS_VIA_IMPORT);
writer.writeValue(attr.isAllowNewOptionsViaImport());
}
List<FilterIndexField> indexFields = attr.getProductListFilterIndexFields();
if (!ConvertUtil.ignoreProperty(KEY_PRODUCT_LIST_FILTER_INDEX_FIELDS) && indexFields != null
&& indexFields.size() > 0) {
writer.writeName(KEY_PRODUCT_LIST_FILTER_INDEX_FIELDS);
writer.beginArray();
for (FilterIndexField filterIndexField : indexFields) {
writer.writeValue(filterIndexField.name());
}
writer.endArray();
}
if (attr.getProductListFilterKeyAlias() != null
&& !ConvertUtil.ignoreProperty(KEY_PRODUCT_LIST_FILTER_KEY_ALIAS)) {
writer.writeName(KEY_PRODUCT_LIST_FILTER_KEY_ALIAS);
ctxObjConverter.serialize(attr.getProductListFilterKeyAlias(), writer, ctx);
}
if (attr.getProductListFilterFormatLabel() != null
&& !ConvertUtil.ignoreProperty(KEY_PRODUCT_LIST_FILTER_FORMAT_LABEL)) {
writer.writeName(KEY_PRODUCT_LIST_FILTER_FORMAT_LABEL);
ctxObjConverter.serialize(attr.getProductListFilterFormatLabel(), writer, ctx);
}
if (attr.getProductListFilterFormatValue() != null
&& !ConvertUtil.ignoreProperty(KEY_PRODUCT_LIST_FILTER_FORMAT_VALUE)) {
writer.writeName(KEY_PRODUCT_LIST_FILTER_FORMAT_VALUE);
ctxObjConverter.serialize(attr.getProductListFilterFormatValue(), writer, ctx);
}
if (attr.getProductListFilterParseValue() != null
&& !ConvertUtil.ignoreProperty(KEY_PRODUCT_LIST_FILTER_PARSE_VALUE)) {
writer.writeName(KEY_PRODUCT_LIST_FILTER_PARSE_VALUE);
ctxObjConverter.serialize(attr.getProductListFilterParseValue(), writer, ctx);
}
if (!ConvertUtil.ignoreProperty(KEY_PRODUCT_LIST_FILTER_MULTI)) {
writer.writeName(KEY_PRODUCT_LIST_FILTER_MULTI);
writer.writeValue(attr.isProductListFilterMulti());
}
if (!ConvertUtil.ignoreProperty(KEY_PRODUCT_LIST_FILTER_INHERIT_FROM_PARENT)) {
writer.writeName(KEY_PRODUCT_LIST_FILTER_INHERIT_FROM_PARENT);
writer.writeValue(attr.isProductListFilterInheritFromParent());
}
if (!ConvertUtil.ignoreProperty(KEY_PRODUCT_LIST_FILTER_INCLUDE_CHILDREN)) {
writer.writeName(KEY_PRODUCT_LIST_FILTER_INCLUDE_CHILDREN);
writer.writeValue(attr.isProductListFilterIncludeChildren());
}
if (!ConvertUtil.ignoreProperty(KEY_PRODUCT_LIST_FILTER_POSITION)) {
writer.writeName(KEY_PRODUCT_LIST_FILTER_POSITION);
writer.writeValue(attr.getProductListFilterPosition());
}
if (!ConvertUtil.ignoreProperty(KEY_SHOW_IN_QUERY)) {
writer.writeName(KEY_SHOW_IN_QUERY);
writer.writeValue(attr.getShowInQuery());
}
if (attr.getLinkedAttributeIds() != null && !ConvertUtil.ignoreProperty(KEY_LINKED_ATTRIBUTE_IDS)) {
writer.writeName(KEY_LINKED_ATTRIBUTE_IDS);
writer.beginArray();
for (Id linkedAttrId : attr.getLinkedAttributeIds()) {
writer.writeValue(linkedAttrId.str());
}
writer.endArray();
}
if (attr.getProductTypes() != null && !ConvertUtil.ignoreProperty(KEY_PRODUCT_TYPES)) {
writer.writeName(KEY_PRODUCT_TYPES);
writer.beginArray();
for (ProductType productType : attr.getProductTypes()) {
writer.writeValue(productType.name());
}
writer.endArray();
}
if (attr.getOptions() != null && !ConvertUtil.ignoreProperty(KEY_OPTIONS)) {
writer.writeName(KEY_OPTIONS);
writer.beginArray();
for (AttributeOption option : attr.getOptions()) {
attributeOptionConverter.serialize(option, writer, ctx);
}
writer.endArray();
}
writer.endObject();
}
}
}
|
yuyu2172/ilv | ilv/collect_results/__init__.py | from collect_results_chainer import collect_results_chainer, collect_results_chainer_interactive
|
123844114/react-master | day2/a/src/music/mock/data.js | export default [
{
keyCode: 81,
title:'Heater 1',
name:'Q',
open:false
},
{
keyCode: 87,
title:'Heater 2',
name:'W',
open:false
},
{
keyCode: 69,
title:'Heater 3',
name:'E',
open:false
},
{
keyCode: 65,
title:'Heater 4',
name:'A',
open:false
},
{
keyCode: 83,
title:'Heater 5',
name:'S',
open:false
},
{
keyCode: 68,
title:'Heater 6',
name:'D',
open:false
},
{
keyCode: 90,
title:'Heater 7',
name:'Z',
open:false
},
{
keyCode: 88,
title:'Heater 8',
name:'X',
open:false
},
{
keyCode: 67,
title:'Heater 9',
name:'C',
open:false
}
] |
pacoolin/octopus | 1.utils/core/src/main/java/com/octopus/utils/xml/auto/defpro/impl/utils/ConcurrenceWaitTask.java | package com.octopus.utils.xml.auto.defpro.impl.utils;
import com.octopus.utils.thread.ThreadPool;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* User: wfgao_000
* Date: 15-5-6
* Time: 下午3:24
*/
public class ConcurrenceWaitTask implements Runnable{
static transient Log log = LogFactory.getLog(ConcurrenceWaitTask.class);
int total =0;
AtomicInteger finishedsize=new AtomicInteger(0);
AtomicInteger handleSize = new AtomicInteger(0);
AtomicInteger addSeize = new AtomicInteger(0);
int threadNum;
boolean iswait;
List<Runnable> finishedListeners = new ArrayList<Runnable>();
Object[] queue = null;
Object lock = new Object();
private final ReentrantLock takeLock = new ReentrantLock();
//private final Condition notEmpty = takeLock.newCondition();
String mainThreadName;
ThreadPool threadPool;
String threadPoolName;
//ExecutorService threadPool;
public ConcurrenceWaitTask(String name,int size,int threadnum,boolean iswait){
threadPoolName=name;
total=size;
queue = new Object[total+1];
//System.out.println(Thread.currentThread().getName()+" queue new "+total);
threadNum=threadnum;
this.iswait = iswait;
}
public void put(Object o){
//mainThreadName=Thread.currentThread().getName();
if(addSeize.intValue()<total){
queue[addSeize.intValue()]=o;
addSeize.addAndGet(1);
//System.out.println(Thread.currentThread().getName()+" queue put "+addSeize.intValue());
/* takeLock.lock();
try{
notEmpty.signalAll();
} catch (Exception e) {
log.error(e);
}finally {
takeLock.unlock();
}*/
}
try{
if(iswait && total==addSeize.intValue()){
synchronized (lock){
//log.error("---==================");
lock.wait();
}
}
}catch (Exception e){
e.printStackTrace();
}
}
public void start(){
threadPool = ThreadPool.getInstance().getThreadPool(threadPoolName,threadNum+1);
try {
threadPool.getExecutor().execute(this);
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
//threadPool.getExecutor().execute(this);
}
@Override
public void run() {
try{
while(true){
//System.out.println(Thread.currentThread().getName()+addSeize.intValue()+" "+handleSize+" "+queue[handleSize]);
if(addSeize.intValue()>handleSize.intValue()){
Object o = queue[handleSize.intValue()];
if(o instanceof String && o.equals("^exit")){
addSeize.set(0);
total=0;
finishedsize.set(0);
handleSize.set(0);
threadNum=0;
queue=null;
if(iswait){
synchronized (lock){
lock.notifyAll();
//log.error("addSeize finished");
}
//threadPool.shutdown();
}
doFinishedListener();
iswait=false;
//System.out.println(Thread.currentThread().getName()+"--R--break");
break;
}
//log.error("defeat "+handleSize.intValue());
//new Thread(new exerun(this,(Object[])o)).start();
threadPool.getExecutor().execute(new exerun(this,(Object[])o));
handleSize.incrementAndGet();
}else{
//takeLock.lock();
Thread.sleep(1);
//log.error("addSeize:"+addSeize.intValue()+" handleSize:"+handleSize.intValue()+" total:"+total);
//takeLock.unlock();
}
}
}catch (Exception e){
log.error("concurrent error",e);
}finally {
ThreadPool.getInstance().returnThreadPool(threadPool);
}
}
void finished(){
queue[addSeize.intValue()]="^exit";
addSeize.addAndGet(1);
//notEmpty.signalAll();
}
class exerun extends ConcurrenceExeRun{
ConcurrenceWaitTask parent;
public exerun(ConcurrenceWaitTask o,Object[] os) {
super(os);
parent=o;
//this.ex=e;
}
public void run(){
try{
doAction();
}catch (Exception e){
log.error("concurrent wait task error",e);
}finally {
takeLock.lock();
try{
finishedsize.addAndGet(1);
//System.out.println("=="+finishedsize.intValue());
if(finishedsize.intValue()==total){
finished();
}
}finally {
takeLock.unlock();
}
}
}
}
public void addFinishedListener(Runnable run){
finishedListeners.add(run);
}
void doFinishedListener(){
for(Runnable r:finishedListeners){
r.run();
}
}
}
|
cmarincia/enso | lib/scala/akka-native/src/main/java/org/enso/nativeimage/workarounds/ReplacementStatics.java | <reponame>cmarincia/enso
package org.enso.nativeimage.workarounds;
import com.oracle.svm.core.annotate.Substitute;
import com.oracle.svm.core.annotate.TargetClass;
/**
* Uses Native Image substitution capability to substitute the {@link
* scala.runtime.Statics#releaseFence()} function which causes problems when building the Native
* Image on GraalVM 20.2.0.
*/
@TargetClass(className = "scala.runtime.Statics")
final class ReplacementStatics {
/**
* Implements a "release fence" without using an unsupported {@link java.lang.invoke.MethodHandle}
* like the original one.
*
* <p>Instead, uses {@link sun.misc.Unsafe#storeFence()} under the hood.
*/
@Substitute
public static void releaseFence() {
Unsafe.unsafeInstance().storeFence();
}
}
|
trolldbois/metasploit-framework | lib/gemcache/ruby/1.9.1/arch/linux64/eventmachine-0.12.10/lib/em/protocols.rb | <filename>lib/gemcache/ruby/1.9.1/arch/linux64/eventmachine-0.12.10/lib/em/protocols.rb
module EventMachine
# This module contains various protocol implementations, including:
# - HttpClient and HttpClient2
# - Stomp
# - Memcache
# - SmtpClient and SmtpServer
# - SASLauth and SASLauthclient
# - LineAndTextProtocol and LineText2
# - HeaderAndContentProtocol
# - Postgres3
# - ObjectProtocol
#
# The protocol implementations live in separate files in the protocols/ subdirectory,
# but are auto-loaded when they are first referenced in your application.
#
# EventMachine::Protocols is also aliased to EM::P for easier usage.
#
module Protocols
# TODO : various autotools are completely useless with the lack of naming
# convention, we need to correct that!
autoload :TcpConnectTester, 'em/protocols/tcptest'
autoload :HttpClient, 'em/protocols/httpclient'
autoload :HttpClient2, 'em/protocols/httpclient2'
autoload :LineAndTextProtocol, 'em/protocols/line_and_text'
autoload :HeaderAndContentProtocol, 'em/protocols/header_and_content'
autoload :LineText2, 'em/protocols/linetext2'
autoload :Stomp, 'em/protocols/stomp'
autoload :SmtpClient, 'em/protocols/smtpclient'
autoload :SmtpServer, 'em/protocols/smtpserver'
autoload :SASLauth, 'em/protocols/saslauth'
autoload :Memcache, 'em/protocols/memcache'
autoload :Postgres3, 'em/protocols/postgres3'
autoload :ObjectProtocol, 'em/protocols/object_protocol'
autoload :Socks4, 'em/protocols/socks4'
end
end
|
Shtekata/14.Softuni-ReactJS | 06.Workshop-Components/origami-project/src/components/Footer/Footer.js | <reponame>Shtekata/14.Softuni-ReactJS
import x from './Footer.module.css';
import NavigationItem from '../NavigationItem/NavigationItem';
const Footer = () => (
<footer className={x.footer}>
<ul>
<NavigationItem>Going to 1</NavigationItem>
<NavigationItem>Going to 2</NavigationItem>
<NavigationItem>Going to 3</NavigationItem>
<NavigationItem>Going to 4</NavigationItem>
<NavigationItem>Going to 5</NavigationItem>
<NavigationItem>Going to 6</NavigationItem>
<NavigationItem>Going to 7</NavigationItem>
<NavigationItem>Going to 8</NavigationItem>
<NavigationItem>Going to 9</NavigationItem>
<NavigationItem>Going to 10</NavigationItem>
<NavigationItem>Going to 11</NavigationItem>
<NavigationItem><img src="blue-origami-bird-flipped.png" alt="Blue origami" /></NavigationItem>
</ul>
<p>Software University © 2021</p>
</footer>
);
export default Footer; |
jd-oss/mutator_rails | spec/spec_helper.rb | <reponame>jd-oss/mutator_rails
# frozen_string_literal: true
ENV['RACK_ENV'] = 'test'
require 'simplecov'
SimpleCov.add_filter '/spec/'
SimpleCov.start 'rails' unless File.basename($0).eql?('mutant')
require 'bundler/setup'
require 'mutator_rails'
require 'rspec/collection_matchers'
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = '.rspec_status'
# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!
config.expect_with :rspec do |c|
c.syntax = :expect
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
c.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups
end
|
nistefan/cmssw | EventFilter/L1TRawToDigi/plugins/implementations_stage2/GlobalExtBlkUnpacker.cc | <filename>EventFilter/L1TRawToDigi/plugins/implementations_stage2/GlobalExtBlkUnpacker.cc
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "EventFilter/L1TRawToDigi/plugins/UnpackerFactory.h"
#include "GTCollections.h"
#include "GlobalExtBlkUnpacker.h"
namespace l1t {
namespace stage2 {
bool
GlobalExtBlkUnpacker::unpack(const Block& block, UnpackerCollections *coll)
{
LogDebug("L1T") << "Block ID = " << block.header().getID() << " size = " << block.header().getSize();
unsigned int wdPerBX = 6; //should this be configured someplace else?
int nBX = int(ceil(block.header().getSize() / 6.)); // FOR GT Not sure what we have here...put at 6 because of 6 frames. Since there are 12 EGamma objects reported per event (see CMS IN-2013/005)
// Find the central, first and last BXs
int firstBX = -(ceil((double)nBX/2.)-1);
int lastBX;
if (nBX % 2 == 0) {
lastBX = ceil((double)nBX/2.);
} else {
lastBX = ceil((double)nBX/2.)-1;
}
auto res_ = static_cast<GTCollections*>(coll)->getExts();
res_->setBXRange(firstBX, lastBX);
LogDebug("L1T") << "nBX = " << nBX << " first BX = " << firstBX << " lastBX = " << lastBX;
// Loop over multiple BX and then number of EG cands filling collection
int numBX = 0; //positive int to count BX
for (int bx=firstBX; bx<=lastBX; bx++){
// If this is the first block, instantiate GlobalExt so it is there to fill from mult. blocks
if(block.header().getID()==24) {
LogDebug("L1T") << "Creating GT External Block for BX =" << bx;
GlobalExtBlk tExt = GlobalExtBlk();
res_->push_back(bx,tExt);
}
//fetch from collection
GlobalExtBlk ext = res_->at(bx,0);
//Determine offset of algorithm bits based on block.ID
// ID=24 offset = 0; ID=26 offset=64; ID=28 offset=128=2*64; ID=30 offset=3*64=192
int extOffset = ((block.header().getID()-24)/2)*64;
for(unsigned int wd=0; wd<wdPerBX; wd++) {
uint32_t raw_data = block.payload()[wd+numBX*wdPerBX];
LogDebug("L1T") << " payload word " << wd << " 0x" << hex << raw_data;
if(wd < 2) {
for(unsigned int bt=0; bt<32; bt++) {
int val = ((raw_data >> bt) & 0x1);
int extBit = bt+wd*32+extOffset;
if(val==1) ext.setExternalDecision(extBit,true);
}
}
}
// Put the object back into place (Must be better way???)
res_->set(bx,0,ext);
//ext.print(std::cout);
numBX++;
}
return true;
}
}
}
DEFINE_L1T_UNPACKER(l1t::stage2::GlobalExtBlkUnpacker);
|
ucdavis/ipa-web | src/main/java/edu/ucdavis/dss/ipa/entities/ScheduleInstructorNote.java | package edu.ucdavis.dss.ipa.entities;
import javax.persistence.*;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Holds meta data set by the AC about instructors for a certain schedule
*/
@Entity
@Table(name = "ScheduleInstructorNotes")
public class ScheduleInstructorNote {
private long id;
private Instructor instructor;
private Schedule schedule;
private Boolean assignmentsCompleted = false;
private String instructorComment;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "Id", unique = true, nullable = false)
@JsonProperty
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "InstructorId", nullable = false)
@JsonIgnore
public Instructor getInstructor() {
return instructor;
}
public void setInstructor(Instructor instructor) {
this.instructor = instructor;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ScheduleId", nullable = false)
@JsonIgnore
public Schedule getSchedule() {
return schedule;
}
public void setSchedule(Schedule schedule) {
this.schedule = schedule;
}
@Column(name = "assignmentsCompleted", nullable = false)
@JsonProperty
public Boolean getAssignmentsCompleted() {
return assignmentsCompleted;
}
public void setAssignmentsCompleted(Boolean assignmentsCompleted) {
this.assignmentsCompleted = assignmentsCompleted;
}
@Column(name = "InstructorComment", nullable = true)
@JsonProperty
public String getInstructorComment() {
return instructorComment;
}
public void setInstructorComment(String instructorComment) {
this.instructorComment = instructorComment;
}
@JsonProperty("instructorId")
@Transient
public long getInstructorIdentification() {
if(instructor != null) {
return instructor.getId();
} else {
return 0;
}
}
}
|
plamere/PlaylistBuilder | pbl/echonest_plugs.py | <reponame>plamere/PlaylistBuilder
'''
A set of sources and annotators for Echo Nest API. An Echo Nest track has
the following attributes::
{
"src": "Echo Nest Playlist Artist radio for weezer",
"artist": "Weezer",
"title": "Perfect Situation",
"id": "3oM0sxN8FZwgUvccT9n34d",
"duration": 255,
"echonest": {
"album_type": "unknown",
"artist_discovery": 0.3328849845870755,
"speechiness": 0.035816,
"duration": 255.37288,
"id": "SOZKJDU1461E3C9B6E",
"title": "Perfect Situation",
"acousticness": 0.03422,
"danceability": 0.452168,
"song_currency": 0.017234941438929167,
"artist_familiarity": 0.812078,
"artist_id": "AR633SY1187B9AC3B9",
"energy": 0.791129,
"song_hotttnesss": 0.391096,
"tempo": 93.946,
"artist_name": "Weezer",
"instrumentalness": 0.000311,
"key": 6,
"audio_md5": "dca9daa0723096d6ed7a5507b1bca17e",
"album_name": "Make Believe",
"album_date": "2005-05-09",
"liveness": 0.135915,
"artist_hotttnesss": 0.72962,
"mode": 1,
"time_signature": 4,
"loudness": -4.131,
"valence": 0.37193
}
}
'''
from track_manager import tlib
from engine import PBLException
import utils
import pprint
import pyen
en = None
debug = False
_en_song_buckets = [
'id:spotify', 'audio_summary', 'song_hotttnesss',
'song_currency', 'artist_hotttnesss', 'tracks',
'artist_familiarity', 'artist_discovery'
]
class EchoNestPlaylist(object):
'''
A track source that uses the Echo Nest playlist API to generate tracks
:param name: the name of the source
:param params: a dictionary of params (see the Echo Nest
playlist/static documentation for a full list of available
parameters.
'''
def __init__(self, name, params):
self.name = 'Echo Nest Playlist ' + name
self.params = params
self.buffer = None
self.params['limit'] = True
if 'bucket' not in self.params:
self.params['bucket'] = []
for bucket in _en_song_buckets:
self.params['bucket'].append(bucket)
def next_track(self):
'''
returns the next track in the stream
'''
if self.buffer == None:
self.buffer = []
try:
response = _get_en().get('playlist/static', **self.params)
except pyen.PyenException as e:
raise PBLException(self, e.msg)
for song in response['songs']:
id = _add_song(self.name, song)
self.buffer.append(id)
if len(self.buffer) > 0:
tid = self.buffer.pop(0)
return tid
else:
return None
class EchoNestGenreRadio(EchoNestPlaylist):
'''
A genre radio track source
:param genre: the genre of interest
:param count: the number of tracks to generate
'''
def __init__(self, genre, count):
'''
'''
params = { 'type': 'genre-radio', 'genre': genre.lower(), 'results': int(count) }
super(EchoNestGenreRadio, self).__init__('Genre radio for ' + genre, params)
class EchoNestHottestSongs(object):
'''
Returns the set of hotttest songs from the Echo Nest. TBD
:param count: the number of tracks to generate
'''
def __init__(self, count):
self.name = 'hotttest songs'
def next_track(self):
pass
class EchoNestArtistRadio(EchoNestPlaylist):
'''
A PBL source that generates a stream of tracks that are by
the given artist or similar artists
:param artist: the name of the artist
:param count: the number of tracks to generate
'''
def __init__(self, artist, count):
params = { 'type': 'artist-radio', 'artist': artist, 'results': int(count) }
super(EchoNestArtistRadio, self).__init__('Artist radio for ' + artist, params)
class EchoNestArtistPlaylist(EchoNestPlaylist):
'''
A PBL source that generates a stream of tracks by the given
artist
:param artist: the name of the artist
:param count: the number of tracks to generate
'''
def __init__(self, artist, count):
params = { 'type': 'artist', 'artist': artist, 'results': int(count) }
super(EchoNestArtistPlaylist, self).__init__('Artist playlist for ' + artist, params)
def _annotate_tracks_with_echonest_data(tids):
otids = tlib.annotate_tracks_from_cache('echonest', tids)
if len(otids) > 0:
stids = set(otids)
uris = [ 'spotify:track:' + tid for tid in otids]
try:
if debug:
print 'getting echonest info for', otids
response = _get_en().get('song/profile', track_id=uris, bucket=_en_song_buckets)
res = set()
for song in response['songs']:
for track in song['tracks']:
tid = utils.uri_to_id(track['foreign_id'])
if tid in stids:
res.add(tid)
tlib.annotate_track(tid, 'echonest', _flatten_en_song(song, tid))
diff = stids - res
if len(diff) > 0:
pass
#print 'requested', len(stids), 'collected', len(res)
except pyen.PyenException as e:
print 'annotate_tracks_with_echonest_data:no info for', otids
print 'echonest error', e.http_status, e.code, e.msg
for tid in otids:
tlib.annotate_track(tid, 'echonest', {'empty': 'empty'})
def _flatten_en_song(song, id):
for k,v in song['audio_summary'].items():
song[k] = v
if 'artist_foreign_ids' in song:
del song['artist_foreign_ids']
if 'audio_summary' in song:
del song['audio_summary']
if 'analysis_url' in song:
del song['analysis_url']
for track in song['tracks']:
tid = utils.uri_to_id(track['foreign_id'])
if id == tid:
if 'album_name' in track:
song['album_name'] = track['album_name']
if 'album_date' in track:
song['album_date'] = track['album_date']
if 'album_type' in track:
song['album_type'] = track['album_type']
del song['tracks']
return song
def _add_song(source, song):
id = utils.uri_to_id(song['tracks'][0]['foreign_id'])
dur = int(song['audio_summary']['duration'] )
tlib.make_track(id, song['title'], song['artist_name'], dur, source)
tlib.annotate_track(id, 'echonest', _flatten_en_song(song, id))
return id
_echonest_annotator = {
'name': 'echonest',
'annotator': _annotate_tracks_with_echonest_data,
'batch_size': 50
}
def _get_en():
global en
if en == None:
en = pyen.Pyen()
en.trace = False
return en
tlib.add_annotator(_echonest_annotator)
|
nnoco/playground | design-patterns/HeadFirst Design Patterns/src/day13/Knowledge.java | <filename>design-patterns/HeadFirst Design Patterns/src/day13/Knowledge.java<gh_stars>0
package day13;
public class Knowledge {
}
|
italankin/lnch | launcher/src/main/java/com/italankin/lnch/model/repository/search/match/Match.java | package com.italankin.lnch.model.repository.search.match;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import java.util.Set;
import androidx.annotation.ColorInt;
import androidx.annotation.DrawableRes;
public interface Match {
/**
* @return uri of match icon
*/
Uri getIcon();
/**
* @return drawable resource of the match icon
*/
@DrawableRes
int getIconResource();
CharSequence getLabel(Context context);
@ColorInt
int getColor(Context context);
@Override
String toString();
/**
* @return an intent, if present
*/
Intent getIntent();
/**
* @return kind of a match, e.g. application, shortcut, web result, etc.
*/
Kind getKind();
Set<Action> availableActions();
/**
* Kind of the object this match represents
*/
enum Kind {
APP,
SHORTCUT,
OTHER,
WEB,
URL
}
enum Action {
PIN,
INFO
}
}
|
ValtoFrameworks/ClanLib | Sources/Core/Zip/zip_archive.cpp | /*
** ClanLib SDK
** Copyright (c) 1997-2016 The ClanLib Team
**
** This software is provided 'as-is', without any express or implied
** warranty. In no event will the authors be held liable for any damages
** arising from the use of this software.
**
** Permission is granted to anyone to use this software for any purpose,
** including commercial applications, and to alter it and redistribute it
** freely, subject to the following restrictions:
**
** 1. The origin of this software must not be misrepresented; you must not
** claim that you wrote the original software. If you use this software
** in a product, an acknowledgment in the product documentation would be
** appreciated but is not required.
** 2. Altered source versions must be plainly marked as such, and must not be
** misrepresented as being the original software.
** 3. This notice may not be removed or altered from any source distribution.
**
** Note: Some of the libraries ClanLib may link to may have additional
** requirements or restrictions.
**
** File Author(s):
**
** <NAME>
** <NAME>
*/
#include "Core/precomp.h"
#include "API/Core/Zip/zip_archive.h"
#include "API/Core/IOData/file.h"
#include "API/Core/IOData/memory_device.h"
#include "API/Core/IOData/path_help.h"
#include "API/Core/Text/string_format.h"
#include "API/Core/Text/string_help.h"
#include "zip_archive_impl.h"
#include "zip_file_header.h"
#include "zip_64_end_of_central_directory_record.h"
#include "zip_64_end_of_central_directory_locator.h"
#include "zip_end_of_central_directory_record.h"
#include "zip_file_entry_impl.h"
#include "zip_iodevice_fileentry.h"
#include "zip_compression_method.h"
#include "zip_digital_signature.h"
#include <ctime>
#include <mutex>
namespace clan
{
ZipArchive::ZipArchive()
: impl(std::make_shared<ZipArchive_Impl>())
{
}
ZipArchive::ZipArchive(const std::string &filename)
: impl(std::make_shared<ZipArchive_Impl>())
{
IODevice input = File(filename);
impl->input = input;
load(input);
}
ZipArchive::ZipArchive(IODevice &input)
: impl(std::make_shared<ZipArchive_Impl>())
{
load(input);
}
ZipArchive::ZipArchive(const ZipArchive ©) : impl(copy.impl)
{
}
ZipArchive::~ZipArchive()
{
}
std::vector<ZipFileEntry> ZipArchive::get_file_list()
{
return impl->files;
}
std::vector<ZipFileEntry> ZipArchive::get_file_list(const std::string &dirpath)
{
std::string path = dirpath;
if (path.empty())
path = "/";
// Zip files expect the folders to be in the form of "/Folder/"
path = PathHelp::make_absolute("/", path, PathHelp::path_type_virtual);
path = PathHelp::add_trailing_slash(path, PathHelp::path_type_virtual);
std::vector<ZipFileEntry> files;
std::vector<std::string> added_directories;
for (auto & elem : impl->files)
{
std::string filename = elem.get_archive_filename();
if (filename[0] != '/')
{
filename.insert(filename.begin(), '/');
elem.set_archive_filename(filename);
}
if (filename.substr(0, path.size()) == path)
{
std::string::size_type subdir_slash_pos = filename.find('/', path.size());
if (subdir_slash_pos != std::string::npos) // subdirectory or files in a subdirectory
{
bool dir_added = false;
std::string directory_name = filename.substr(path.size(), subdir_slash_pos - path.size());
for (auto & added_directory : added_directories)
{
if (added_directory == directory_name)
dir_added = true;
}
if (!dir_added)
{
ZipFileEntry dir_entry;
dir_entry.set_archive_filename(directory_name);
dir_entry.set_directory(true);
files.push_back(dir_entry);
added_directories.push_back(directory_name);
}
}
else if (elem.get_archive_filename() != path)
{
std::string file_name = filename.substr(path.size(), std::string::npos);
ZipFileEntry file_entry;
file_entry.set_archive_filename(file_name);
files.push_back(file_entry);
}
}
}
return files;
}
IODevice ZipArchive::open_file(const std::string &filename)
{
int size = impl->files.size();
for (int i = 0; i < size; i++)
{
ZipFileEntry &entry = impl->files[i];
std::string entry_filename = entry.impl->record.filename;
if (entry_filename[0] == '/')
entry_filename = entry_filename.substr(1, std::string::npos);
if (entry_filename == filename)
{
switch (entry.impl->type)
{
case ZipFileEntry_Impl::type_file:
{
IODevice dupe = impl->input.duplicate();
return IODevice(new ZipIODevice_FileEntry(dupe, entry));
}
case ZipFileEntry_Impl::type_removed:
throw Exception(string_format("Unable to zip open file entry %1. The entry has been removed!", filename));
break;
case ZipFileEntry_Impl::type_added_memory:
return MemoryDevice(entry.impl->data);
case ZipFileEntry_Impl::type_added_file:
return File(entry.impl->filename);
}
throw Exception(string_format("Unknown zip file entry type %1", filename));
}
}
throw Exception(string_format("Unable to find zip index %1", filename));
}
std::string ZipArchive::get_pathname(const std::string &filename)
{
throw Exception("ZipArchive::get_pathname: function not implemented.");
}
IODevice ZipArchive::create_file(const std::string &filename, bool compress)
{
throw Exception("ZipArchive::create_file: function not implemented.");
}
void ZipArchive::add_file(const std::string &input_filename, const std::string &archive_filename)
{
ZipFileEntry file_entry;
file_entry.set_input_filename(input_filename);
file_entry.set_archive_filename(archive_filename);
impl->files.push_back(file_entry);
}
void ZipArchive::save()
{
throw Exception("ZipArchive::save: function not implemented.");
}
void ZipArchive::save(const std::string &filename)
{
File output(filename, File::create_always, File::access_read_write);
std::vector<int> local_header_offsets;
std::vector<uint32_t> crc32_codes;
int16_t dos_date = 0, dos_time = 0;
ZipArchive_Impl::calc_time_and_date(dos_date, dos_time);
std::vector<ZipFileEntry>::iterator it;
for (it = impl->files.begin(); it != impl->files.end(); ++it)
{
local_header_offsets.push_back(output.get_position());
std::string input_filename = (*it).get_input_filename();
std::string archive_filename = (*it).get_archive_filename();
File input(input_filename);
DataBuffer data(input.get_size());
input.read(data.get_data(), data.get_size());
uint32_t crc32 = ZipArchive_Impl::calc_crc32(data.get_data(), data.get_size());
crc32_codes.push_back(crc32);
// 1. local file header
ZipLocalFileHeader local_header;
local_header.version_needed_to_extract = 20;
local_header.general_purpose_bit_flag = ZIP_USE_UTF8;
local_header.compression_method = zip_compress_store;
local_header.last_mod_file_time = dos_time;
local_header.last_mod_file_date = dos_date;
local_header.crc32 = crc32;
local_header.uncompressed_size = data.get_size();
local_header.compressed_size = data.get_size();
local_header.file_name_length = archive_filename.size();
local_header.extra_field_length = 0;
local_header.filename = archive_filename;
local_header.extra_field = DataBuffer();
local_header.save(output);
// 2. Data (uncompressed for now)
output.write(data.get_data(), data.get_size());
}
int index = 0;
int offset_start_central_dir = output.get_position();
// write central directory entries.
for (it = impl->files.begin(); it != impl->files.end(); ++it)
{
std::string input_filename = (*it).get_input_filename();
std::string filename = (*it).get_archive_filename();
File input(input_filename);
(*it).impl->record.version_made_by = 20;
(*it).impl->record.version_needed_to_extract = 20;
(*it).impl->record.general_purpose_bit_flag = ZIP_USE_UTF8;
(*it).impl->record.compression_method = zip_compress_store;
(*it).impl->record.last_mod_file_time = dos_time;
(*it).impl->record.last_mod_file_date = dos_date;
(*it).impl->record.crc32 = crc32_codes[index];
(*it).impl->record.uncompressed_size = input.get_size();
(*it).impl->record.compressed_size = input.get_size(); // todo
(*it).impl->record.file_name_length = filename.size();
(*it).impl->record.extra_field_length = 0;
(*it).impl->record.filename = filename;
(*it).impl->record.extra_field = DataBuffer();
(*it).impl->record.file_comment_length = 0;
(*it).impl->record.disk_number_start = 0;
(*it).impl->record.internal_file_attributes = 0;
(*it).impl->record.external_file_attributes = 0;
(*it).impl->record.relative_offset_of_local_header = local_header_offsets[index];
(*it).impl->record.save(output);
index++;
}
/* ZipDigitalSignature digi_sign;
digi_sign.size_of_data = 0;
digi_sign.save(output);*/
int central_dir_size = output.get_position() - offset_start_central_dir;
ZipEndOfCentralDirectoryRecord central_dir_end;
central_dir_end.number_of_this_disk = 0;
central_dir_end.number_of_disk_with_start_of_central_directory = 0;
central_dir_end.number_of_entries_on_this_disk = local_header_offsets.size();
central_dir_end.number_of_entries_in_central_directory = local_header_offsets.size();
central_dir_end.size_of_central_directory = central_dir_size;
central_dir_end.offset_to_start_of_central_directory = offset_start_central_dir;
central_dir_end.file_comment_length = 0;
central_dir_end.file_comment = "";
central_dir_end.save(output);
}
void ZipArchive::load(IODevice &input)
{
impl->input = input;
// Load zip file structures:
// indicate the file is little-endian
input.set_little_endian_mode();
// Find end of central directory record:
int size_file = input.get_size();
char buffer[32 * 1024];
if (size_file > 32 * 1024) input.seek(-32 * 1024, IODevice::seek_end);
int size_buffer = input.read(buffer, 32 * 1024);
int end_record_pos = -1;
for (int pos = size_buffer - 4; pos >= 0; pos--)
{
#ifdef USE_BIG_ENDIAN
if (*(unsigned int *)(buffer+pos) == 0x504b0506)
#else
if (*(unsigned int *)(buffer + pos) == 0x06054b50)
#endif
{
end_record_pos = size_file - size_buffer + pos;
break;
}
}
if (end_record_pos == -1)
{
throw Exception("This appear not to be a zip file");
}
// Load end of central directory record:
ZipEndOfCentralDirectoryRecord end_of_directory;
input.seek(end_record_pos, IODevice::seek_set);
end_of_directory.load(input);
// Look for zip64 central directory locator:
bool zip64 = false;
Zip64EndOfCentralDirectoryLocator zip64_locator;
Zip64EndOfCentralDirectoryRecord zip64_end_of_directory;
int end64_locator = end_record_pos - 20;
input.seek(end64_locator, IODevice::seek_set);
if (input.read_uint32() == 0x07064b50)
{
// Load zip64 structures:
input.seek(end64_locator, IODevice::seek_set);
zip64_locator.load(input);
input.seek(int(end64_locator + zip64_locator.relative_offset_of_zip64_end_of_central_directory), IODevice::seek_set);
zip64_end_of_directory.load(input);
zip64 = true;
}
// Load central directory records:
if (zip64) input.seek(int(zip64_end_of_directory.offset_to_start_of_central_directory), IODevice::seek_set);
else input.seek(int(end_of_directory.offset_to_start_of_central_directory), IODevice::seek_set);
int64_t num_entries = end_of_directory.number_of_entries_in_central_directory;
if (zip64) num_entries = zip64_end_of_directory.number_of_entries_in_central_directory;
for (int i = 0; i < num_entries; i++)
{
ZipFileEntry entry;
entry.impl->record.load(input);
impl->files.push_back(entry);
}
}
/////////////////////////////////////////////////////////////////////////////
void ZipArchive_Impl::calc_time_and_date(int16_t &out_date, int16_t &out_time)
{
uint32_t day_of_month = 0;
uint32_t month = 0;
uint32_t year_from_1980 = 0;
uint32_t hour = 0;
uint32_t min = 0;
uint32_t sec = 0;
#if _MSC_VER >= 1400
time_t t = time(0);
tm tm_time;
localtime_s(&tm_time, &t);
day_of_month = tm_time.tm_mday;
month = tm_time.tm_mon + 1;
year_from_1980 = tm_time.tm_year - 80;
hour = tm_time.tm_hour;
min = tm_time.tm_min;
sec = tm_time.tm_sec;
#else
static std::recursive_mutex mutex;
std::unique_lock<std::recursive_mutex> mutex_lock(mutex);
time_t t = time(nullptr);
tm *tm_time = gmtime(&t);
day_of_month = tm_time->tm_mday;
month = tm_time->tm_mon + 1;
year_from_1980 = tm_time->tm_year - 80;
hour = tm_time->tm_hour;
min = tm_time->tm_min;
sec = tm_time->tm_sec;
mutex_lock.unlock();
#endif
out_date = (int16_t)(day_of_month + (month << 5) + (year_from_1980 << 9));
out_time = (int16_t)(sec / 2 + (min << 5) + (hour << 11));
}
uint32_t ZipArchive_Impl::calc_crc32(const void *data, int64_t size, uint32_t crc, bool last_block)
{
const char *d = (const char *)data;
for (uint32_t data_index = 0; data_index < size; data_index++)
{
uint8_t table_index = ((crc ^ d[data_index]) & 0xff);
crc = ((crc >> 8) & 0x00ffffff) ^ crc32_table[table_index];
}
if (last_block)
return ~crc;
else
return crc;
}
uint32_t ZipArchive_Impl::crc32_table[256] =
{
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba,
0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,
0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec,
0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,
0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940,
0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116,
0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,
0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a,
0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818,
0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,
0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c,
0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,
0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086,
0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4,
0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,
0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,
0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe,
0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,
0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252,
0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60,
0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,
0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,
0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04,
0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a,
0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,
0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e,
0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,
0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0,
0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6,
0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,
0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
};
}
|
enixdark/featurehub | backend/mr-db-sql/src/main/java/io/featurehub/db/utils/DatabaseBinder.java | package io.featurehub.db.utils;
import cd.connect.app.config.ConfigKey;
import cd.connect.app.config.DeclaredConfigResolver;
import io.ebean.Database;
import io.ebeaninternal.server.core.DefaultServer;
import org.glassfish.jersey.internal.inject.AbstractBinder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Singleton;
/**
* Use this module to configure the EbeanSource that you can use elsewhere.
*/
public class DatabaseBinder extends AbstractBinder {
private static final Logger log = LoggerFactory.getLogger(DatabaseBinder.class);
@ConfigKey("db.url")
String databaseUrl;
@ConfigKey("db.username")
String username;
@ConfigKey("db.password")
String password;
@ConfigKey("db.driver")
String driver = "";
@ConfigKey("db.connections")
Integer maxConnections;
@Override
protected void configure() {
DeclaredConfigResolver.resolve(this);
if (this.driver.length() == 0) {
this.driver = null;
}
EbeanHolder ebeanHolder = new EbeanHolder(this.databaseUrl, this.username, this.password, this.maxConnections, this.driver);
log.info("database platform initialised: {}", ((DefaultServer) ebeanHolder.getEbeanServer()).getDatabasePlatform().getName());
bind(ebeanHolder).to(EbeanSource.class).in(Singleton.class);
bind(ebeanHolder.getEbeanServer()).to(Database.class).in(Singleton.class);
}
}
|
pdpdds/sdldualsystem | sdl1/SGL4/SGLVertexIndexList.h | #ifndef SGLVERTEXINDEXLIST_H
#define SGLVERTEXINDEXLIST_H
#include <vector>
class SGLVertexIndexList
{
public:
std::vector<int> vilist;
public:
SGLVertexIndexList(void);
~SGLVertexIndexList(void);
void clear(void);
void addIndex(int index);
void addIndex(const int* indexBuffer, int count);
int& getLastIndex(void);
int& operator[](unsigned int index);
const int& operator[](unsigned int index) const;
int size(void) const;
};
#define SGLTextureIdList SGLVertexIndexList
#endif |
maxhgerlach/mpi4py | test/test_op.py | from mpi4py import MPI
import mpiunittest as unittest
import sys
try:
import array
except ImportError:
array = None
def asarray(typecode, data):
try:
memoryview
_tobytes = lambda s: memoryview(s).tobytes()
except NameError:
_tobytes = lambda s: buffer(s)[:]
try:
_frombytes = array.array.frombytes
except AttributeError:
_frombytes = array.array.fromstring
a = array.array(typecode, [])
_frombytes(a, _tobytes(data))
return a
def mysum_obj(a, b):
for i in range(len(a)):
b[i] = a[i] + b[i]
return b
def mysum_buf(a, b, dt):
assert dt == MPI.INT
assert len(a) == len(b)
b[:] = mysum_obj(asarray('i', a), asarray('i', b))
def mysum(ba, bb, dt):
if dt is None:
return mysum_obj(ba, bb)
else:
return mysum_buf(ba, bb, dt)
class TestOp(unittest.TestCase):
def testConstructor(self):
op = MPI.Op()
self.assertFalse(op)
self.assertEqual(op, MPI.OP_NULL)
@unittest.skipIf(array is None, 'array')
def testCreate(self):
for comm in [MPI.COMM_SELF, MPI.COMM_WORLD]:
for commute in [True, False]:
for N in range(4):
myop = MPI.Op.Create(mysum, commute)
self.assertFalse(myop.is_predefined)
try:
size = comm.Get_size()
rank = comm.Get_rank()
a = array.array('i', [i*(rank+1) for i in range(N)])
b = array.array('i', [0]*len(a))
comm.Allreduce([a, MPI.INT], [b, MPI.INT], myop)
scale = sum(range(1,size+1))
for i in range(N):
self.assertEqual(b[i], scale*i)
ret = myop(a, b)
self.assertTrue(ret is b)
for i in range(N):
self.assertEqual(b[i], a[i]+scale*i)
myop2 = MPI.Op(myop)
a = array.array('i', [1]*N)
b = array.array('i', [2]*N)
ret = myop2(a, b)
self.assertTrue(ret is b)
for i in range(N):
self.assertEqual(b[i], 3)
myop2 = None
finally:
myop.Free()
def testCreateMany(self):
N = 32 # max user-defined operations
#
ops = []
for i in range(N):
o = MPI.Op.Create(mysum)
ops.append(o)
for o in ops: o.Free() # cleanup
# another round
ops = []
for i in range(N):
o = MPI.Op.Create(mysum)
ops.append(o)
for o in ops: o.Free() # cleanup
def _test_call(self, op, args, res):
self.assertEqual(op(*args), res)
def testCall(self):
self._test_call(MPI.MIN, (2,3), 2)
self._test_call(MPI.MAX, (2,3), 3)
self._test_call(MPI.SUM, (2,3), 5)
self._test_call(MPI.PROD, (2,3), 6)
def xor(x,y): return bool(x) ^ bool(y)
for x, y in ((0, 0),
(0, 1),
(1, 0),
(1, 1)):
self._test_call(MPI.LAND, (x,y), x and y)
self._test_call(MPI.LOR, (x,y), x or y)
self._test_call(MPI.LXOR, (x,y), xor(x, y))
self._test_call(MPI.BAND, (x,y), x & y)
self._test_call(MPI.BOR, (x,y), x | y)
self._test_call(MPI.BXOR, (x,y), x ^ y)
if MPI.REPLACE:
self._test_call(MPI.REPLACE, (2,3), 3)
self._test_call(MPI.REPLACE, (3,2), 2)
if MPI.NO_OP:
self._test_call(MPI.NO_OP, (2,3), 2)
self._test_call(MPI.NO_OP, (3,2), 3)
def testMinMax(self):
x = [1]; y = [1]
res = MPI.MIN(x, y)
self.assertTrue(res is x)
res = MPI.MAX(x, y)
self.assertTrue(res is x)
def testMinMaxLoc(self):
x = [1]; i = [2]; u = [x, i]
y = [2]; j = [1]; v = [y, j]
res = MPI.MINLOC(u, v)
self.assertTrue(res[0] is x)
self.assertTrue(res[1] is i)
res = MPI.MINLOC(v, u)
self.assertTrue(res[0] is x)
self.assertTrue(res[1] is i)
res = MPI.MAXLOC(u, v)
self.assertTrue(res[0] is y)
self.assertTrue(res[1] is j)
res = MPI.MAXLOC(v, u)
self.assertTrue(res[0] is y)
self.assertTrue(res[1] is j)
#
x = [1]; i = 0; u = [x, i]
y = [1]; j = 1; v = [y, j]
res = MPI.MINLOC(u, v)
self.assertTrue(res[0] is x)
self.assertTrue(res[1] is i)
res = MPI.MAXLOC(u, v)
self.assertTrue(res[0] is x)
self.assertTrue(res[1] is i)
#
x = [1]; i = 1; u = [x, i]
y = [1]; j = 0; v = [y, j]
res = MPI.MINLOC(u, v)
self.assertTrue(res[0] is y)
self.assertTrue(res[1] is j)
res = MPI.MAXLOC(u, v)
self.assertTrue(res[0] is y)
self.assertTrue(res[1] is j)
#
x = [1]; i = [0]; u = [x, i]
y = [1]; j = [1]; v = [y, j]
res = MPI.MINLOC(u, v)
self.assertTrue(res[0] is x)
self.assertTrue(res[1] is i)
res = MPI.MAXLOC(u, v)
self.assertTrue(res[0] is x)
self.assertTrue(res[1] is i)
#
x = [1]; i = [1]; u = [x, i]
y = [1]; j = [0]; v = [y, j]
res = MPI.MINLOC(u, v)
self.assertTrue(res[0] is y)
self.assertTrue(res[1] is j)
res = MPI.MAXLOC(u, v)
self.assertTrue(res[0] is y)
self.assertTrue(res[1] is j)
@unittest.skipMPI('openmpi(<=1.8.1)')
def testIsCommutative(self):
try:
MPI.SUM.Is_commutative()
except NotImplementedError:
self.skipTest('mpi-op-is_commutative')
ops = [MPI.MAX, MPI.MIN,
MPI.SUM, MPI.PROD,
MPI.LAND, MPI.BAND,
MPI.LOR, MPI.BOR,
MPI.LXOR, MPI.BXOR,
MPI.MAXLOC, MPI.MINLOC,]
for op in ops:
flag = op.Is_commutative()
self.assertEqual(flag, op.is_commutative)
self.assertTrue(flag)
@unittest.skipMPI('openmpi(<=1.8.1)')
@unittest.skipMPI('mpich(==3.4.1)')
def testIsCommutativeExtra(self):
try:
MPI.SUM.Is_commutative()
except NotImplementedError:
self.skipTest('mpi-op-is_commutative')
ops = [MPI.REPLACE, MPI.NO_OP]
for op in ops:
if not op: continue
flag = op.Is_commutative()
self.assertEqual(flag, op.is_commutative)
#self.assertFalse(flag)
def testIsPredefined(self):
self.assertTrue(MPI.OP_NULL.is_predefined)
ops = [MPI.MAX, MPI.MIN,
MPI.SUM, MPI.PROD,
MPI.LAND, MPI.BAND,
MPI.LOR, MPI.BOR,
MPI.LXOR, MPI.BXOR,
MPI.MAXLOC, MPI.MINLOC,]
for op in ops:
self.assertTrue(op.is_predefined)
if __name__ == '__main__':
unittest.main()
|
kernt/infrakit | vendor/github.com/juju/schema/time_duration.go | // Copyright 2016 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package schema
import (
"reflect"
"time"
)
// TimeDuration returns a Checker that accepts a string value, and returns
// the parsed time.Duration value. Emtpy strings are considered empty time.Duration
func TimeDuration() Checker {
return timeDurationC{}
}
type timeDurationC struct{}
// Coerce implements Checker Coerce method.
func (c timeDurationC) Coerce(v interface{}, path []string) (interface{}, error) {
if v == nil {
return nil, error_{"string or time.Duration", v, path}
}
var empty time.Duration
switch reflect.TypeOf(v).Kind() {
case reflect.TypeOf(empty).Kind():
return v, nil
case reflect.String:
vstr := reflect.ValueOf(v).String()
if vstr == "" {
return empty, nil
}
v, err := time.ParseDuration(vstr)
if err != nil {
return nil, err
}
return v, nil
default:
return nil, error_{"string or time.Duration", v, path}
}
}
|
mscheltienne/neurotin-analysis | neurotin/model/viz.py | <gh_stars>0
from typing import Optional
import mne
import numpy as np
import pandas as pd
from mne.io import Info
from ..utils._checks import _check_type
def plot_topomap(weights, info: Optional[Info] = None, **kwargs) -> None:
"""Plot the weights as a topographic map.
Parameters
----------
weights : array | Series
If a numpy array is provided, the channel names must be provided in
info. If a Series is provided, the channel names are retrieved from
the index.
info : Info
MNE measurement information instance containing the channel names.
A standard 1020 montage is added.
"""
weights = _check_type(
weights, (pd.Series, np.ndarray), item_name="weights"
)
info = _check_type(info, (None, mne.io.Info), item_name="info")
if isinstance(weights, pd.Series):
data = weights.values
info = mne.create_info(list(weights.index), 1, "eeg")
info.set_montage("standard_1020")
else:
_check_info(info, weights.size)
info.set_montage("standard_1020")
mne.viz.plot_topomap(data, pos=info, **kwargs)
def _check_info(info: Optional[Info], n: int) -> None:
"""Check that info is valid if weights is a numpy array."""
if info is None:
raise ValueError("Info must be provided if weights is a numpy array.")
assert (
len(info.ch_names) == n
), "Info does not contain the same number of channels as weights."
|
borisskert/aram-all-time-table | backend-services/src/main/java/com/github/borisskert/aramalltimetable/profileicon/ProfileIconStore.java | package com.github.borisskert.aramalltimetable.profileicon;
import com.github.borisskert.aramalltimetable.riot.model.ProfileIcon;
import com.github.borisskert.aramalltimetable.store.StreamStore;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Optional;
@Service
public class ProfileIconStore {
private static final String PROFILE_ICON_STORE_NAME = "profileIcon";
private final StreamStore streamStore;
@Autowired
public ProfileIconStore(StreamStore streamStore) {
this.streamStore = streamStore;
}
public Optional<ProfileIcon> find(final Integer id) {
Optional<StreamStore.StreamDocument> maybeDocument = streamStore.find(PROFILE_ICON_STORE_NAME, id.toString());
return maybeDocument.map(this::readToProfileIcon);
}
public void create(ProfileIcon profileIcon) {
StreamStore.StreamDocument document = new StreamStore.StreamDocument(
new ByteArrayInputStream(profileIcon.getContent()),
profileIcon.getId().toString(),
profileIcon.getContentType(),
profileIcon.getContent().length
);
streamStore.create(PROFILE_ICON_STORE_NAME, profileIcon.getId().toString(), document);
}
public void update(ProfileIcon profileIcon) {
StreamStore.StreamDocument document = new StreamStore.StreamDocument(
new ByteArrayInputStream(profileIcon.getContent()),
profileIcon.getId().toString(),
profileIcon.getContentType(),
profileIcon.getContent().length
);
streamStore.update(PROFILE_ICON_STORE_NAME, profileIcon.getId().toString(), document);
}
private ProfileIcon readToProfileIcon(StreamStore.StreamDocument streamDocument) {
try {
return new ProfileIcon(
Integer.parseInt(streamDocument.getId()),
IOUtils.readFully(streamDocument.getStream(), streamDocument.getContentLength()),
streamDocument.getContentType()
);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
|
MetaPhase-Consulting/State-TalentMAP | src/reducers/synchronizations/index.js | <filename>src/reducers/synchronizations/index.js
import { patchSyncHasErrored, patchSyncIsLoading, putAllSyncsHasErrored, putAllSyncsIsLoading,
putAllSyncsSuccess, syncs, syncsHasErrored, syncsIsLoading } from './synchronizations';
export default {
syncs,
syncsHasErrored,
syncsIsLoading,
putAllSyncsSuccess,
putAllSyncsHasErrored,
putAllSyncsIsLoading,
patchSyncIsLoading,
patchSyncHasErrored,
};
|
HeavenWu/slimdx | source/direct3d10/ShaderResourceView.h | <reponame>HeavenWu/slimdx<gh_stars>10-100
/*
* Copyright (c) 2007-2012 SlimDX Group
*
* 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.
*/
#pragma once
#include "ResourceView.h"
namespace SlimDX
{
namespace Direct3D10
{
ref class Device;
ref class Resource;
value class ImageLoadInformation;
value class ShaderResourceViewDescription;
public ref class ShaderResourceView : public ResourceView
{
COMOBJECT(ID3D10ShaderResourceView, ShaderResourceView);
static ID3D10ShaderResourceView* ConstructFromFile( SlimDX::Direct3D10::Device^ device, System::String^ fileName, D3DX10_IMAGE_LOAD_INFO* loadInformation );
static ID3D10ShaderResourceView* ConstructFromMemory( SlimDX::Direct3D10::Device^ device, array<System::Byte>^ memory, D3DX10_IMAGE_LOAD_INFO* loadInformation );
static ID3D10ShaderResourceView* ConstructFromStream( SlimDX::Direct3D10::Device^ device, System::IO::Stream^ stream, int sizeInBytes, D3DX10_IMAGE_LOAD_INFO* loadInformation );
protected:
//no-op ctor for use by ShaderResourceView1
ShaderResourceView() { }
public:
property ShaderResourceViewDescription Description
{
ShaderResourceViewDescription get();
}
ShaderResourceView( SlimDX::Direct3D10::Device^ device, SlimDX::Direct3D10::Resource^ resource );
ShaderResourceView( SlimDX::Direct3D10::Device^ device, SlimDX::Direct3D10::Resource^ resource, ShaderResourceViewDescription description );
/// <summary>
/// Creates a shader resource view from a file.
/// </summary>
/// <param name="device">The device that will own the resource.</param>
/// <param name="fileName">The name of the file that contains the shader resource view.</param>
static ShaderResourceView^ FromFile( SlimDX::Direct3D10::Device^ device, System::String^ fileName );
/// <summary>
/// Creates a shader resource view from a file.
/// </summary>
/// <param name="device">The device that will own the resource.</param>
/// <param name="fileName">The name of the file that contains the shader resource view.</param>
static ShaderResourceView^ FromFile( SlimDX::Direct3D10::Device^ device, System::String^ fileName, ImageLoadInformation loadInformation );
static ShaderResourceView^ FromMemory( SlimDX::Direct3D10::Device^ device, array<System::Byte>^ memory );
static ShaderResourceView^ FromMemory( SlimDX::Direct3D10::Device^ device, array<System::Byte>^ memory, ImageLoadInformation loadInfo );
static ShaderResourceView^ FromStream( SlimDX::Direct3D10::Device^ device, System::IO::Stream^ stream, int sizeInBytes );
static ShaderResourceView^ FromStream( SlimDX::Direct3D10::Device^ device, System::IO::Stream^ stream, int sizeInBytes, ImageLoadInformation loadInfo );
};
}
}; |
dym270307872/outman-boot | boot-redis/boot-jedisCluster/src/main/java/cn/dyaoming/outman/service/RandomService.java | <filename>boot-redis/boot-jedisCluster/src/main/java/cn/dyaoming/outman/service/RandomService.java
package cn.dyaoming.outman.service;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.Random;
@Service
public class RandomService {
@Cacheable(value = "userInfo")
public String getRandom(int max){
return "返回值:" + new Random().nextInt(max);
}
@Cacheable(value = "publicInfo")
public String getRandom2(int max){
return "返回值:" + new Random().nextInt(max);
}
@CachePut(value = "userInfo",key="#name +'to userinfo'")
public String find(String name){
return "用户名:" + name;
}
@CacheEvict(value = "userInfo",key="#name +'to userinfo'")
public void delete(String name){
// return "用户名:" + name;
}
}
|
754340156/NQ_quanfu | allrichstore/UI/GoodsClass/Main/V/MenuHeaderView.h | <filename>allrichstore/UI/GoodsClass/Main/V/MenuHeaderView.h
//
// MenuHeaderView.h
// allrichstore
//
// Created by 任强宾 on 16/11/28.
// Copyright © 2016年 allrich88. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "GoodsClassVC.h"
@interface MenuHeaderView : UICollectionReusableView
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) QButton *btn;
@end
|
CarnationWang23/hyracks | hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/file/LineFileWriteOperatorDescriptor.java | /*
* Copyright 2009-2013 by The Regents of the University of California
* 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 from
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hyracks.dataflow.std.file;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.apache.hyracks.api.job.IOperatorDescriptorRegistry;
public class LineFileWriteOperatorDescriptor extends AbstractFileWriteOperatorDescriptor {
private static final long serialVersionUID = 1L;
private static class LineWriterImpl extends RecordWriter {
LineWriterImpl(File file, int[] columns, char separator) throws Exception {
super(columns, separator, new Object[] { file });
}
private static final long serialVersionUID = 1L;
@Override
public OutputStream createOutputStream(Object[] args) throws Exception {
return new FileOutputStream((File) args[0]);
}
}
private int[] columns;
private char separator;
public LineFileWriteOperatorDescriptor(IOperatorDescriptorRegistry spec, FileSplit[] splits) {
this(spec, splits, null, RecordWriter.COMMA);
}
public LineFileWriteOperatorDescriptor(IOperatorDescriptorRegistry spec, FileSplit[] splits, int[] columns) {
this(spec, splits, columns, RecordWriter.COMMA);
}
public LineFileWriteOperatorDescriptor(IOperatorDescriptorRegistry spec, FileSplit[] splits, int[] columns, char separator) {
super(spec, splits);
this.columns = columns;
this.separator = separator;
}
@Override
protected IRecordWriter createRecordWriter(FileSplit fileSplit, int index) throws Exception {
return new LineWriterImpl(fileSplit.getLocalFile().getFile(), columns, separator);
}
} |
BenKoehler/bk | examples/bkTools/progress.cpp | <reponame>BenKoehler/bk
/*
* MIT License
*
* Copyright (c) 2018-2019 <NAME>
*
* 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.
*/
#include <iostream>
#include <bk/Progress>
void on_task_finished(unsigned int taskId)
{
std::cout << "task finished (id " << taskId << ")" << std::endl;
}
void on_task_added(unsigned int taskId, double maxProgress, double currentProgress, std::string_view description)
{
std::cout << "task added (id " << taskId << ", \"" << description << "\") ; progress " << currentProgress << " / " << maxProgress << std::endl;
}
void on_progress_changed(double currentProgress)
{
// do nothing
}
int main(int, char**)
{
std::cout << std::fixed;
bk::ProgressManager progman;
// connect to functions with signature of the corresponding signals
progman.signal_task_added().connect(&on_task_added);
progman.signal_task_finished().connect(&on_task_finished);
// alternative: connect to lambda function
//progman.signal_task_finished().connect([](unsigned int taskId) { on_task_finished(taskId); });
int N = 1'000'000;
bk::Progress& prog = progman.emplace_task(N, "my calculation"); // add progress tracker for a task
prog.signal_current_changed().connect(&on_progress_changed); // call function every time progress changes
std::cout << "number of active tasks: " << progman.num_tasks() << std::endl;
for (int i = 0; i < N; ++i)
{
/* do stuff */
prog.increment(1);
}
std::cout << "number of active tasks: " << progman.num_tasks() << std::endl << std::endl;
/* output:
* task added (id 0, "my calculation") ; progress 0.000000 / 1000000.000000
* number of active tasks: 1
* task finished (id 0)
* number of active tasks: 0
*/
// ----------------------------------------------------------------------
bk::Progress& progParallel = progman.emplace_task(N, "my parallel calculation");
#pragma omp parallel for
for (int i = 0; i < N; ++i)
{
/* do stuff (parallel) */
#pragma omp critical
{ progParallel.increment(1); }
}
/* output:
* task added (id 1, "my parallel calculation") ; progress 0.000000 / 1000000.000000
* task finished (id 1)
*/
return EXIT_SUCCESS;
}
|
m-nakagawa/sample | jena-3.0.1/jena-sdb/src/test/java/sdb/DBTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sdb;
import java.sql.Connection ;
import java.util.List ;
import jena.cmd.CmdException;
import org.apache.jena.atlas.lib.Lib ;
import org.junit.runner.JUnitCore ;
import org.junit.runner.notification.RunListener ;
import sdb.cmd.CmdArgsDB ;
import sdb.junit.TextListener2 ;
import sdb.test.Params ;
import sdb.test.ParamsVocab ;
import sdb.test.TestI18N ;
import sdb.test.TestStringBasic ;
/** Run some DB tests to check setup */
public class DBTest extends CmdArgsDB
{
public static void main(String [] argv)
{
new DBTest(argv).mainAndExit() ;
}
String filename = null ;
public DBTest(String[] args)
{
super(args);
}
@Override
protected String getCommandName() { return Lib.className(this) ; }
@Override
protected String getSummary() { return getCommandName()+" <SPEC> "; }
@Override
protected void processModulesAndArgs()
{
List<String> args = getPositional() ;
setParams(args) ;
}
Params params = new Params() ;
{
params.put( ParamsVocab.TempTableName, "FOO") ;
params.put( ParamsVocab.BinaryType, "BLOB") ;
params.put( ParamsVocab.BinaryCol, "colBinary") ;
params.put( ParamsVocab.VarcharType, "VARCHAR(200)") ;
params.put( ParamsVocab.VarcharCol, "colVarchar") ;
}
@Override
protected void execCmd(List<String> args)
{
if ( isVerbose() )
{
for ( String k : params )
System.out.printf("%-20s = %-20s\n", k, params.get(k) );
System.out.println() ;
}
Connection jdbc = getModStore().getConnection().getSqlConnection() ;
// Hack to pass to calculated parameters to the test subsystem.
sdb.test.Env.set(jdbc, params, false) ;
JUnitCore x = new org.junit.runner.JUnitCore() ;
//RunListener listener = new TextListener2() ;
RunListener listener = new TextListener2(System.out) ;
x.addListener(listener) ;
//x.run(sdb.test.AllTests.class) ;
System.out.println("String basic") ;
x.run(TestStringBasic.class) ;
System.out.println("String I18N") ;
x.run(TestI18N.class) ;
// Better way of having parameters for a class than a @Parameterised test of one thing?
// Request request = Request.aClass(sdb.test.T.class) ;
// x.run(request) ;
}
private void setParams(List<String> args)
{
for ( String s : args )
{
String[] frags = s.split("=", 2) ;
if ( frags.length != 2)
throw new CmdException("Can't split '"+s+"'") ;
params.put(frags[0], frags[1] ) ;
}
}
}
|
smoorpal/conjure-go | vendor/github.com/palantir/witchcraft-go-tracing/wtracing/context.go | // Copyright (c) 2018 Palantir Technologies. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package wtracing
import (
"context"
)
type tracerContextKeyType string
const tracerContextKey = tracerContextKeyType("wtracing.tracer")
// ContextWithTracer returns a copy of the provided context with the provided Tracer included as a value.
func ContextWithTracer(ctx context.Context, tracer Tracer) context.Context {
return context.WithValue(ctx, tracerContextKey, tracer)
}
// TracerFromContext returns the Tracer stored in the provided context. Returns nil if no Tracer is stored in the
// context.
func TracerFromContext(ctx context.Context) Tracer {
if tracer, ok := ctx.Value(tracerContextKey).(Tracer); ok {
return tracer
}
return nil
}
type spanContextKeyType string
const spanContextKey = spanContextKeyType("wtracing.span")
// ContextWithSpan returns a copy of the provided context with the provided span set on it.
func ContextWithSpan(ctx context.Context, s Span) context.Context {
return context.WithValue(ctx, spanContextKey, s)
}
// SpanFromContext returns the span stored in the provided context, or nil if no span is stored in the context.
func SpanFromContext(ctx context.Context) Span {
if s, ok := ctx.Value(spanContextKey).(Span); ok {
return s
}
return nil
}
// StartSpanFromContext starts a new span with the provided parameters using the provided tracer and the span
// information in the provided context. If the context contains a span, the new span will be configured to be a child
// span of that span (unless any of the user-provided span options overrides this). Returns the newly started span and a
// copy of the provided context that has the new span set as its current span. Returns a nil span if the provided tracer
// is nil.
//
// This function does not read or set the tracer on the provided context. To start a span new span from the tracer set
// on a context, call StartSpanFromContext(TracerFromContext(ctx), ctx, spanName, spanOptions).
func StartSpanFromContext(ctx context.Context, tracer Tracer, spanName string, spanOptions ...SpanOption) (Span, context.Context) {
if tracer == nil {
return nil, ctx
}
if spanInCtx := SpanFromContext(ctx); spanInCtx != nil {
spanOptions = append([]SpanOption{WithParent(spanInCtx)}, spanOptions...)
}
newSpan := tracer.StartSpan(spanName, spanOptions...)
newCtx := ContextWithSpan(ctx, newSpan)
return newSpan, newCtx
}
// StartSpanFromTracerInContext starts a new span with the provided parameters using the tracer and the span information
// in the provided context. If the context contains a span, the new span will be configured to be a child span of that
// span (unless any of the user-provided span options overrides this). Returns the newly started span and a copy of the
// provided context that has the new span set as its current span.
//
// If the context does not contain a tracer, returns a no-op Span and an unmodified version of the provided context. The
// span returned by this function is always non-nil.
func StartSpanFromTracerInContext(ctx context.Context, spanName string, spanOptions ...SpanOption) (Span, context.Context) {
tracer := TracerFromContext(ctx)
if tracer == nil {
return &noopSpan{}, ctx
}
if spanInCtx := SpanFromContext(ctx); spanInCtx != nil {
spanOptions = append([]SpanOption{WithParent(spanInCtx)}, spanOptions...)
}
newSpan := tracer.StartSpan(spanName, spanOptions...)
newCtx := ContextWithSpan(ctx, newSpan)
return newSpan, newCtx
}
type noopSpan struct{}
func (noopSpan) Context() SpanContext {
return SpanContext{}
}
func (noopSpan) Finish() {}
func (noopSpan) Tag(string, string) {}
// TraceIDFromContext returns the traceId associated with the span stored in the provided context. Returns an empty
// string if no span is stored in the context.
func TraceIDFromContext(ctx context.Context) TraceID {
if span := SpanFromContext(ctx); span != nil {
return span.Context().TraceID
}
return ""
}
|
yesheng86/play-metronome | Play Metronome/XYSHintLineView.h | <filename>Play Metronome/XYSHintLineView.h
//
// XYSHintLineView.h
// Play Metronome
//
// Created by <NAME> on 8/13/14.
// Copyright (c) 2014 yesheng. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface XYSHintLineView : UIView
@property CGPoint rotationAxis;
- (void)appear;
- (void)disappear;
@end
|
arturluis/spatial | test/spatial/tests/feature/math/LowPrecisionRep.scala | package spatial.tests.feature.math
import spatial.dsl._
import spatial.lib._
@spatial class LowPrecisionRep extends SpatialTest { // Args N in multiple of 64
type T = Float
type B = Byte
def main(args: Array[String]): Unit = {
val data = Array.tabulate(1000){i => random[Float]( 256) - 128 }
val N = data.length
val dram = DRAM[T](N)
setMem(dram, data)
val dram_out = DRAM[B](N)
val sf = ArgOut[Float]
Accel {
val x = Reg[Float]
ConvertTo8Bit(dram_out,x,dram,64)
sf := x.value
}
val inputArray = getMem(dram)
val outputArray = getMem(dram_out)
val scalingFactor = getArg(sf)
val maxGold = inputArray.reduce{(a,b) => max(abs(a),abs(b)) }
val maxDelta = 2.0.to[T]*maxGold/127.to[T]
val goldArray = inputArray.map{a => (a/maxDelta).to[B] }
val matches = outputArray === goldArray
println("result: " + matches)
println("Scaling Factor: " + scalingFactor)
(0 until N).foreach{ i =>
println("input: " + inputArray(i) + ", gold: " + goldArray(i) + ", actual: " + outputArray(i))
}
assert(matches)
}
} |
liangchaoboy/qiniu-suits-java | src/main/java/com/qiniu/model/media/Item.java | <gh_stars>1-10
package com.qiniu.model.media;
public class Item {
public String cmd;
public Integer code;
public String desc;
public String error;
public String hash;
public String key;
public Integer returnOld;
}
|
jsoref/cf-ui | packages/cf-style-provider/src/felaTestContext.js | // this is a wrapper for testing, it passes fela based
// components fela's renderer and global theme
import React from 'react';
import StyleProvider from './StyleProvider';
export default (component, renderer) => (
<StyleProvider renderer={renderer} dev>
{component}
</StyleProvider>
);
|
Intel-EPID-SDK/epid-sdk | epid/verifier/unittests/nrverify-test.cc | /*############################################################################
# Copyright 2016-2019 Intel Corporation
#
# 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.
############################################################################*/
/*!
* \file
* \brief NrVerify unit tests.
*/
#include "gtest/gtest.h"
#include "testhelper/epid_gtest-testhelper.h"
#include "epid/verifier.h"
extern "C" {
#include "rlverify.h"
}
#include "testhelper/errors-testhelper.h"
#include "testhelper/verifier_wrapper-testhelper.h"
#include "verifier-testhelper.h"
namespace {
/////////////////////////////////////////////////////////////////////////
// Simple Errors
TEST_F(EpidVerifierTest, NrVerifyFailsGivenNullParameters) {
VerifierCtxObj verifier(this->kGrp01Key);
auto epid_signature = reinterpret_cast<EpidNonSplitSignature const*>(
this->kSigGrp01Member0Sha256RandombaseTest0.data());
SigRl const* sig_rl =
reinterpret_cast<SigRl const*>(this->kGrp01SigRl.data());
EXPECT_EQ(kEpidBadCtxErr,
EpidNrVerify(nullptr, &epid_signature->sigma0, this->kTest0.data(),
this->kTest0.size(), &sig_rl->bk[0],
&epid_signature->sigma[0], sizeof(NrProof)));
EXPECT_EQ(
kEpidBadSignatureErr,
EpidNrVerify(verifier, nullptr, this->kTest0.data(), this->kTest0.size(),
&sig_rl->bk[0], &epid_signature->sigma[0], sizeof(NrProof)));
EXPECT_EQ(kEpidBadMessageErr,
EpidNrVerify(verifier, &epid_signature->sigma0, nullptr,
this->kTest0.size(), &sig_rl->bk[0],
&epid_signature->sigma[0], sizeof(NrProof)));
EXPECT_EQ(kEpidBadSigRlEntryErr,
EpidNrVerify(verifier, &epid_signature->sigma0, this->kTest0.data(),
this->kTest0.size(), nullptr,
&epid_signature->sigma[0], sizeof(NrProof)));
EXPECT_EQ(kEpidBadNrProofErr,
EpidNrVerify(verifier, &epid_signature->sigma0, this->kTest0.data(),
this->kTest0.size(), &sig_rl->bk[0], nullptr,
sizeof(NrProof)));
EXPECT_EQ(kEpidBadNrProofErr,
EpidNrVerify(verifier, &epid_signature->sigma0, this->kTest0.data(),
this->kTest0.size(), &sig_rl->bk[0],
&epid_signature->sigma[0], 0));
}
/////////////////////////////////////////////////////////////////////
// Reject
TEST_F(EpidVerifierTest, NrVerifyRejectsSigWithTNotInG1) {
// * 4.2.2 step 1 - The verifier verifies that G1.inGroup(T) = true.
VerifierCtxObj verifier(this->kGrp01Key);
auto epid_signature = reinterpret_cast<EpidNonSplitSignature const*>(
this->kSigGrp01Member0Sha256RandombaseTest0.data());
SigRl const* sig_rl =
reinterpret_cast<SigRl const*>(this->kGrp01SigRl.data());
NrProof nr_proof = epid_signature->sigma[0];
nr_proof.T.x.data.data[0]++;
EXPECT_EQ(kEpidBadNrProofErr,
EpidNrVerify(verifier, &epid_signature->sigma0, this->kTest0.data(),
this->kTest0.size(), &sig_rl->bk[0], &nr_proof,
sizeof(NrProof)));
}
TEST_F(EpidVerifierTest, NrVerifyRejectsSigWithTIdentityOfG1) {
// * 4.2.2 step 2 - The verifier verifies that G1.isIdentity(T) = false.
VerifierCtxObj verifier(this->kGrp01Key);
auto epid_signature = reinterpret_cast<EpidNonSplitSignature const*>(
this->kSigGrp01Member0Sha256RandombaseTest0.data());
SigRl const* sig_rl =
reinterpret_cast<SigRl const*>(this->kGrp01SigRl.data());
NrProof nr_proof = epid_signature->sigma[0];
nr_proof.T = this->kG1IdentityStr;
EXPECT_EQ(kEpidBadNrProofErr,
EpidNrVerify(verifier, &epid_signature->sigma0, this->kTest0.data(),
this->kTest0.size(), &sig_rl->bk[0], &nr_proof,
sizeof(NrProof)));
}
TEST_F(EpidVerifierTest, NrVerifyRejectsSigWithCNotInRange) {
// * 4.2.2 step 3 - The verifier verifies that c, smu, snu in [0, p-1].
VerifierCtxObj verifier(this->kGrp01Key);
auto epid_signature = reinterpret_cast<EpidNonSplitSignature const*>(
this->kSigGrp01Member0Sha256RandombaseTest0.data());
SigRl const* sig_rl =
reinterpret_cast<SigRl const*>(this->kGrp01SigRl.data());
NrProof nr_proof = epid_signature->sigma[0];
nr_proof.c.data = this->kParamsStr.p.data;
EXPECT_EQ(kEpidBadNrProofErr,
EpidNrVerify(verifier, &epid_signature->sigma0, this->kTest0.data(),
this->kTest0.size(), &sig_rl->bk[0], &nr_proof,
sizeof(NrProof)));
}
TEST_F(EpidVerifierTest, NrVerifyRejectsSigWithSmuNotInRange) {
// * 4.2.2 step 3 - The verifier verifies that c, smu, snu in [0, p-1].
VerifierCtxObj verifier(this->kGrp01Key);
auto epid_signature = reinterpret_cast<EpidNonSplitSignature const*>(
this->kSigGrp01Member0Sha256RandombaseTest0.data());
SigRl const* sig_rl =
reinterpret_cast<SigRl const*>(this->kGrp01SigRl.data());
NrProof nr_proof = epid_signature->sigma[0];
nr_proof.smu.data = this->kParamsStr.p.data;
EXPECT_EQ(kEpidBadNrProofErr,
EpidNrVerify(verifier, &epid_signature->sigma0, this->kTest0.data(),
this->kTest0.size(), &sig_rl->bk[0], &nr_proof,
sizeof(NrProof)));
}
TEST_F(EpidVerifierTest, NrVerifyRejectsSigWithSnuNotInRange) {
// * 4.2.2 step 3 - The verifier verifies that c, smu, snu in [0, p-1].
VerifierCtxObj verifier(this->kGrp01Key);
auto epid_signature = reinterpret_cast<EpidNonSplitSignature const*>(
this->kSigGrp01Member0Sha256RandombaseTest0.data());
SigRl const* sig_rl =
reinterpret_cast<SigRl const*>(this->kGrp01SigRl.data());
NrProof nr_proof = epid_signature->sigma[0];
nr_proof.snu.data = this->kParamsStr.p.data;
EXPECT_EQ(kEpidBadNrProofErr,
EpidNrVerify(verifier, &epid_signature->sigma0, this->kTest0.data(),
this->kTest0.size(), &sig_rl->bk[0], &nr_proof,
sizeof(NrProof)));
}
// 4.2.2 step 4 - The verifier computes nc = (- c) mod p.
// This Step is not testable
// 4.2.2 step 5 - The verifier computes R1 = G1.multiExp(K, smu, B, snu).
// This Step is not testable
// 4.2.2 step 6 - The verifier computes R2 = G1.multiExp(K', smu, B', snu,
// T, nc).
// This Step is not testable
TEST_F(EpidVerifierTest, NrVerifyRejectsSigWithInvalidCommitment) {
// * 4.2.2 step 7 - The verifier verifies c = Fp.hash(p || g1 || B || K ||
// B' || K' || T || R1 || R2 || m).
// Refer to Section 7.1 for hash operation over a
// prime field.
VerifierCtxObj verifier(this->kGrp01Key);
auto epid_signature = reinterpret_cast<EpidNonSplitSignature const*>(
this->kSigGrp01Member0Sha256RandombaseTest0.data());
SigRl const* sig_rl =
reinterpret_cast<SigRl const*>(this->kGrp01SigRl.data());
std::vector<uint8_t> test_msg = this->kTest0;
test_msg[0]++;
EXPECT_EQ(kEpidBadNrProofErr,
EpidNrVerify(verifier, &epid_signature->sigma0, test_msg.data(),
test_msg.size(), &sig_rl->bk[0],
&epid_signature->sigma[0], sizeof(NrProof)));
}
TEST_F(EpidVerifierTest, NrVerifyRejectsSigWithValidCommitmentDiffHashAlg) {
// * 4.2.2 step 7 - The verifier verifies c = Fp.hash(p || g1 || B || K ||
// B' || K' || T || R1 || R2 || m).
// Refer to Section 7.1 for hash operation over a
// prime field.
VerifierCtxObj verifier(this->kGrpXKey);
auto epid_signature_sha384 = reinterpret_cast<EpidNonSplitSignature const*>(
this->kSigGrpXMember0Sha384RandbaseMsg0.data());
auto epid_signature_sha512 = reinterpret_cast<EpidNonSplitSignature const*>(
this->kSigGrpXMember0Sha512RandbaseMsg0.data());
SigRl const* sig_rl = reinterpret_cast<SigRl const*>(this->kGrpXSigRl.data());
EXPECT_EQ(kEpidBadNrProofErr,
EpidNrVerify(verifier, &epid_signature_sha384->sigma0,
this->kMsg0.data(), this->kMsg0.size(), &sig_rl->bk[0],
&epid_signature_sha384->sigma[0], sizeof(NrProof)));
EXPECT_EQ(kEpidBadNrProofErr,
EpidNrVerify(verifier, &epid_signature_sha512->sigma0,
this->kMsg0.data(), this->kMsg0.size(), &sig_rl->bk[0],
&epid_signature_sha512->sigma[0], sizeof(NrProof)));
}
/////////////////////////////////////////////////////////////////////
// Accept
// 4.2.2 step 8 - If all the above verifications succeed, the verifier
// outputs true. If any of the above verifications fails,
// the verifier aborts and outputs false
TEST_F(EpidVerifierTest, NrVerifyAcceptsSigWithRandomBaseNameSha256) {
VerifierCtxObj verifier(this->kGrp01Key);
auto epid_signature = reinterpret_cast<EpidNonSplitSignature const*>(
this->kSigGrp01Member0Sha256RandombaseTest0.data());
SigRl const* sig_rl =
reinterpret_cast<SigRl const*>(this->kGrp01SigRl.data());
EXPECT_EQ(kEpidSigValid,
EpidNrVerify(verifier, &epid_signature->sigma0, this->kTest0.data(),
this->kTest0.size(), &sig_rl->bk[0],
&epid_signature->sigma[0], sizeof(NrProof)));
}
TEST_F(EpidVerifierTest,
NrVerifyAcceptsSigWithRandomBaseNameSha256UsingIkgfData) {
VerifierCtxObj verifier(this->kPubKeyIkgfStr);
auto epid_signature = reinterpret_cast<EpidNonSplitSignature const*>(
this->kSigMember0Sha256RandombaseMsg0Ikgf.data());
SigRl const* sig_rl = reinterpret_cast<SigRl const*>(this->kSigRlIkgf.data());
EXPECT_EQ(kEpidSigValid,
EpidNrVerify(verifier, &epid_signature->sigma0, this->kMsg0.data(),
this->kMsg0.size(), &sig_rl->bk[2],
&epid_signature->sigma[2], sizeof(NrProof)));
}
TEST_F(EpidVerifierTest, NrVerifyAcceptsSigWithRandomBaseNameSha384) {
GroupPubKey pubkey01_sha384 = this->kGrp01Key;
pubkey01_sha384.gid.data[1] = 1;
VerifierCtxObj verifier(pubkey01_sha384);
auto epid_signature = reinterpret_cast<EpidNonSplitSignature const*>(
this->kSigGrp01Member0Sha384RandombaseTest0.data());
SigRl const* sig_rl =
reinterpret_cast<SigRl const*>(this->kGrp01SigRl.data());
EXPECT_EQ(kEpidSigValid,
EpidNrVerify(verifier, &epid_signature->sigma0, this->kTest0.data(),
this->kTest0.size(), &sig_rl->bk[0],
&epid_signature->sigma[0], sizeof(NrProof)));
}
TEST_F(EpidVerifierTest, NrVerifyAcceptsSigWithRandomBaseNameSha512) {
GroupPubKey pubkey01_sha512 = this->kGrp01Key;
pubkey01_sha512.gid.data[1] = 2;
VerifierCtxObj verifier(pubkey01_sha512);
auto epid_signature = reinterpret_cast<EpidNonSplitSignature const*>(
this->kSigGrp01Member0Sha512RandombaseTest0.data());
SigRl const* sig_rl =
reinterpret_cast<SigRl const*>(this->kGrp01SigRl.data());
EXPECT_EQ(kEpidSigValid,
EpidNrVerify(verifier, &epid_signature->sigma0, this->kTest0.data(),
this->kTest0.size(), &sig_rl->bk[0],
&epid_signature->sigma[0], sizeof(NrProof)));
}
TEST_F(EpidVerifierTest, NrVerifyAcceptsSigWithRandomBaseNameSha512256) {
GroupPubKey pubkey01_sha512256 = this->kGrpXKey;
pubkey01_sha512256.gid.data[1] = 3;
VerifierCtxObj verifier(pubkey01_sha512256);
auto epid_signature = reinterpret_cast<EpidNonSplitSignature const*>(
this->kSigGrpXMember0Sha512256RandombaseMsg0.data());
SigRl const* sig_rl = reinterpret_cast<SigRl const*>(this->kGrpXSigRl.data());
EXPECT_EQ(kEpidSigValid,
EpidNrVerify(verifier, &epid_signature->sigma0, this->kMsg0.data(),
this->kMsg0.size(), &sig_rl->bk[0],
&epid_signature->sigma[0], sizeof(NrProof)));
}
TEST_F(EpidVerifierTest, NrVerifyAcceptsMsgContainingAllPossibleBytes) {
GroupPubKey pub_key = this->kPubKeySigRlVerify;
// Initialize pubkey.gid to sha512
pub_key.gid.data[1] = 2;
VerifierCtxObj verifier(pub_key);
auto epid_signature =
(EpidNonSplitSignature*)kSigGrp01Member0Sha512kBsn0Data_0_255.data();
SigRl const* sig_rl =
reinterpret_cast<SigRl const*>(this->kGrp01SigRl.data());
EXPECT_EQ(
kEpidSigValid,
EpidNrVerify(verifier, &epid_signature->sigma0, this->kData_0_255.data(),
this->kData_0_255.size(), &sig_rl->bk[0],
&epid_signature->sigma[0], sizeof(NrProof)));
}
} // namespace
|
hernad/zimbra9 | zm-web-client/tiny_mce/custom/langs/sv.js | <gh_stars>0
/*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Web Client
* Copyright (C) 2014, 2016 Synacor, Inc.
*
* The contents of this file are subject to the Common Public Attribution License Version 1.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.zimbra.com/license
* The License is based on the Mozilla Public License Version 1.1 but Sections 14 and 15
* have been added to cover use of software over a computer network and provide for limited attribution
* for the Original Developer. In addition, Exhibit A has been modified to be consistent with Exhibit B.
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied.
* See the License for the specific language governing rights and limitations under the License.
* The Original Code is Zimbra Open Source Web Client.
* The Initial Developer of the Original Code is Zimbra, Inc. All rights to the Original Code were
* transferred by Zimbra, Inc. to Synacor, Inc. on September 14, 2015.
*
* All portions of the code are Copyright (C) 2014, 2016 Synacor, Inc. All Rights Reserved.
* ***** END LICENSE BLOCK *****
*/
tinymce.addI18n("sv",{
"Cut": "Klipp ut",
"Heading 5": "Rubrik 5",
"Header 2": "Rubrik 2",
"Your browser doesn't support direct access to the clipboard. Please use the Ctrl+X\/C\/V keyboard shortcuts instead.": "Din webbl\u00e4sare st\u00f6djer inte direkt \u00e5tkomst till urklipp. Anv\u00e4nd i st\u00e4llet kortkommandona Ctrl+X\/C\/V.",
"Heading 4": "Rubrik 4",
"Div": "Div",
"Heading 2": "Rubrik 2",
"Paste": "Klistra in",
"Close": "St\u00e4ng",
"Font Family": "Teckensnitt",
"Pre": "Pre",
"Align right": "H\u00f6gerjustera",
"New document": "Nytt dokument",
"Blockquote": "Blockcitat",
"Numbered list": "Numrerad lista",
"Heading 1": "Rubrik 1",
"Headings": "Rubriker",
"Increase indent": "\u00d6ka indrag",
"Formats": "Format",
"Headers": "Rubriker",
"Select all": "Markera allt",
"Header 3": "Rubrik 3",
"Blocks": "Block",
"Undo": "\u00c5ngra",
"Strikethrough": "Genomstruken",
"Bullet list": "Punktlista",
"Header 1": "Rubrik 1",
"Superscript": "Upph\u00f6jt",
"Clear formatting": "Rensa formatering",
"Font Sizes": "Teckensnittsstorlekar",
"Subscript": "Neds\u00e4nkt",
"Header 6": "Rubrik 6",
"Redo": "G\u00f6r om",
"Paragraph": "Stycke",
"Ok": "OK",
"Bold": "Fet",
"Code": "Kod",
"Italic": "Kursiv",
"Align center": "Centrera texten",
"Header 5": "Rubrik 5",
"Heading 6": "Rubrik 6",
"Heading 3": "Rubrik 3",
"Decrease indent": "Minska indrag",
"Header 4": "Rubrik 4",
"Paste is now in plain text mode. Contents will now be pasted as plain text until you toggle this option off.": "Klistra in \u00e4r nu i l\u00e4get f\u00f6r oformaterad text. Inneh\u00e5ll kommer att klistras in som oformaterad text tills du sl\u00e5r av detta l\u00e4ge.",
"Underline": "Understruken",
"Cancel": "Avbryt",
"Justify": "Justera",
"Inline": "Relativ",
"Copy": "Kopiera",
"Align left": "V\u00e4nsterjustera",
"Visual aids": "Visuella hj\u00e4lpmedel",
"Lower Greek": "Grekiska gemener",
"Square": "Fyrkant",
"Default": "Ange som standard",
"Lower Alpha": "Alfa gemener",
"Circle": "Cirkel",
"Disc": "Disk",
"Upper Alpha": "Alfa versaler",
"Upper Roman": "Romerska versaler",
"Lower Roman": "Romerska gemener",
"Name": "Namn",
"Anchor": "F\u00e4stpunkt",
"You have unsaved changes are you sure you want to navigate away?": "Du har osparade \u00e4ndringar, vill du \u00e4nd\u00e5 navigera bort?",
"Restore last draft": "\u00c5terst\u00e4ll senaste utkast",
"Special character": "Specialtecken",
"Source code": "K\u00e4llkod",
"B": "B",
"R": "R",
"G": "G",
"Color": "F\u00e4rg",
"Right to left": "H\u00f6ger till v\u00e4nster",
"Left to right": "V\u00e4nster till h\u00f6ger",
"Emoticons": "Uttryckssymboler",
"Robots": "Robotar",
"Document properties": "Dokumentegenskaper",
"Title": "Titel",
"Keywords": "Nyckelord",
"Encoding": "Kodning",
"Description": "Beskrivning",
"Author": "F\u00f6rfattare",
"Fullscreen": "Helsk\u00e4rm",
"Horizontal line": "V\u00e5gr\u00e4t linje",
"Horizontal space": "V\u00e5gr\u00e4tt avst\u00e5nd",
"Insert\/edit image": "Infoga\/redigera bild",
"General": "Allm\u00e4nt",
"Advanced": "Avancerat",
"Source": "K\u00e4lla",
"Border": "Ram",
"Constrain proportions": "Begr\u00e4nsa proportioner",
"Vertical space": "Lodr\u00e4tt avst\u00e5nd",
"Image description": "Bildbeskrivning",
"Style": "Stil",
"Dimensions": "M\u00e5tt",
"Insert image": "Infoga bild",
"Zoom in": "Zooma in",
"Contrast": "Kontrast",
"Back": "Bak\u00e5t",
"Gamma": "Gamma",
"Flip horizontally": "V\u00e4nd v\u00e5gr\u00e4tt",
"Resize": "\u00c4ndra storlek",
"Sharpen": "Sk\u00e4rpa",
"Zoom out": "Zooma ut",
"Image options": "Bildalternativ",
"Apply": "Anv\u00e4nd",
"Brightness": "Ljusstyrka",
"Rotate clockwise": "Rotera medurs",
"Rotate counterclockwise": "Rotera moturs",
"Edit image": "Redigera bild",
"Color levels": "F\u00e4rgniv\u00e5er",
"Crop": "Besk\u00e4r",
"Orientation": "Orientering",
"Flip vertically": "V\u00e4nd lodr\u00e4tt",
"Invert": "Invertera",
"Insert date\/time": "Infoga datum\/tid",
"Remove link": "Ta bort l\u00e4nk",
"Url": "Url",
"Text to display": "Text att visa",
"Anchors": "F\u00e4stpunkter",
"Insert link": "Infoga l\u00e4nk",
"New window": "Nytt f\u00f6nster",
"None": "Inga",
"The URL you entered seems to be an external link. Do you want to add the required http:\/\/ prefix?": "URL-adressen du angav verkar vara en extern l\u00e4nk. Vill du l\u00e4gga till prefixet http:\/\/?",
"Target": "M\u00e5l",
"The URL you entered seems to be an email address. Do you want to add the required mailto: prefix?": "URL-adressen du angav verkar vara en e-postadress. Vill du l\u00e4gga till det n\u00f6dv\u00e4ndiga prefixet mailto:?",
"Insert\/edit link": "Infoga\/redigera l\u00e4nk",
"Insert\/edit video": "Infoga\/redigera video",
"Poster": "Affisch",
"Alternative source": "Alternativ k\u00e4lla",
"Paste your embed code below:": "Klistra in din inb\u00e4ddningskod nedan:",
"Insert video": "Infoga video",
"Embed": "B\u00e4dda in",
"Nonbreaking space": "H\u00e5rd blanksteg",
"Page break": "Sydbrytning",
"Paste as text": "Klistra in som text",
"Preview": "F\u00f6rhandsgranskning",
"Print": "Skriv ut",
"Save": "Spara",
"Could not find the specified string.": "Kunde inte hitta den angivna str\u00e4ngen.",
"Replace": "Ers\u00e4tt",
"Next": "N\u00e4sta",
"Whole words": "Hela ord",
"Find and replace": "S\u00f6k och ers\u00e4tt",
"Replace with": "Ers\u00e4tt med:",
"Find": "S\u00f6k",
"Replace all": "Ers\u00e4tt alla",
"Match case": "Matcha gemener/versaler",
"Prev": "F\u00f6reg.",
"Spellcheck": "Stavningskontroll",
"Finish": "Slutf\u00f6r",
"Ignore all": "Ignorera alla",
"Ignore": "Ignorera",
"Add to Dictionary": "L\u00e4gg till i ordlista",
"Insert row before": "Infoga rad f\u00f6re",
"Rows": "Rader",
"Height": "H\u00f6jd",
"Paste row after": "Klistra in rad efter",
"Alignment": "Justering",
"Border color": "Ramf\u00e4rg",
"Column group": "Kolumngrupp",
"Row": "Rad",
"Insert column before": "Infoga kolumn f\u00f6re",
"Split cell": "Dela cell",
"Cell padding": "Cellutfyllnad",
"Cell spacing": "Cellavst\u00e5nd",
"Row type": "Radtyp",
"Insert table": "Infoga tabell",
"Body": "Br\u00f6dtext",
"Caption": "Bildtext",
"Footer": "Sidfot",
"Delete row": "Radera rad",
"Paste row before": "Klista in rad f\u00f6re",
"Scope": "Omfattning",
"Delete table": "Radera tabell",
"H Align": "H\u00f6gerjustera",
"Top": "\u00d6verst",
"Header cell": "Inneh\u00e5ller rubrik",
"Column": "Kolumn",
"Row group": "Radgrupp",
"Cell": "Cell",
"Middle": "Mitten",
"Cell type": "Celltyp",
"Copy row": "Kopiera rad",
"Row properties": "Radegenskaper",
"Table properties": "Tabellegenskaper",
"Bottom": "Nederst",
"V Align": "V\u00e4nsterjustering",
"Header": "Rubrik",
"Right": "H\u00f6ger",
"Insert column after": "Infoga kolumn efter",
"Cols": "Kolumner",
"Insert row after": "Infoga rad efter",
"Width": "Bredd",
"Cell properties": "Cellegenskaper",
"Left": "V\u00e4nster",
"Cut row": "Klipp ut rad",
"Delete column": "Radera kolumn",
"Center": "Centrera",
"Merge cells": "Sammanfoga celler",
"Insert template": "Infoga mall",
"Templates": "Mallar",
"Background color": "Bakgrundsf\u00e4rg",
"Custom...": "Anpassad...",
"Custom color": "Anpassad f\u00e4rg",
"No color": "Ingen f\u00e4rg",
"Text color": "Textf\u00e4rg",
"Show blocks": "Visa block",
"Show invisible characters": "Visa osynliga tecken",
"Words: {0}": "Ord: {0}",
"Insert": "Infoga",
"File": "Fil",
"Edit": "Redigera",
"Rich Text Area. Press ALT-F9 for menu. Press ALT-F10 for toolbar. Press ALT-0 for help": "RTF-omr\u00e5de. Tryck ALT-F9 f\u00f6r meny. Tryck ALT-F10 f\u00f6r verktygsf\u00e4lt. Tryck ALT-0 f\u00f6r hj\u00e4lp.",
"Tools": "Verktyg",
"View": "Visa",
"Table": "Tabell",
"Format": "Format"
});
|
CyberFlameGO/cloud-security-xsuaa-integration | java-security/src/main/java/com/sap/cloud/security/token/validation/validators/JwtSignatureAlgorithm.java | /**
* SPDX-FileCopyrightText: 2018-2021 SAP SE or an SAP affiliate company and Cloud Security Client Java contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
package com.sap.cloud.security.token.validation.validators;
/**
* This is represented by "kty" (Key Type) Parameter.
* https://www.rfc-editor.org/rfc/rfc7518.html#section-6.1
*/
public enum JwtSignatureAlgorithm {
RS256("RSA", "RS256", "SHA256withRSA")/* , ES256("EC", "ES256", "SHA256withECDSA")// Eliptic curve */;
private final String type;
private final String value;
private final String javaSignatureAlgorithm;
JwtSignatureAlgorithm(String type, String algorithm, String javaSignatureAlgorithm) {
this.type = type;
this.value = algorithm; // jwks, jwt header
this.javaSignatureAlgorithm = javaSignatureAlgorithm;
}
public String value() {
return value;
}
public String javaSignature() {
return javaSignatureAlgorithm;
}
public String type() {
return type;
}
public static JwtSignatureAlgorithm fromValue(String value) {
for (JwtSignatureAlgorithm algorithm : values()) {
if (algorithm.value.equals(value)) {
return algorithm;
}
}
return null;
}
public static JwtSignatureAlgorithm fromType(String type) {
for (JwtSignatureAlgorithm algorithm : values()) {
if (algorithm.type.equals(type)) {
return algorithm;
}
}
return null;
}
}
|
parlaylabs/botbuilder-java | libraries/bot-builder/src/main/java/com/microsoft/bot/builder/Middleware.java | <reponame>parlaylabs/botbuilder-java<gh_stars>0
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.microsoft.bot.builder;
/**
* Represents middleware that can operate on incoming activities.
* A {@link BotAdapter} passes incoming activities from the user's
* channel to the middleware's {@link OnTurn(TurnContext, NextDelegate)}
* method.
* <p>You can add middleware objects to your adapter’s middleware collection. The
* adapter processes and directs incoming activities in through the bot middleware
* pipeline to your bot’s logic and then back out again. As each activity flows in
* and out of the bot, each piece of middleware can inspect or act upon the activity,
* both before and after the bot logic runs.</p>
* <p>For each activity, the adapter calls middleware in the order in which you
* added it.</p>
*
* <example>
* This defines middleware that sends "before" and "after" messages
* before and after the adapter calls the bot's
* {@link Bot.OnTurn(TurnContext)} method.
* <code>
* public class SampleMiddleware : Middleware
* {
* public async Task OnTurn(TurnContext context, MiddlewareSet.NextDelegate next)
* {
* context.SendActivity("before");
* await next().ConfigureAwait(false);
* context.SendActivity("after");
* }
* }
* </code>
* </example>
* {@linkalso Bot}
*/
public interface Middleware
{
/**
* Processess an incoming activity.
* @param context The context object for this turn.
* @param next The delegate to call to continue the bot middleware pipeline.
* @return A task that represents the work queued to execute.
* Middleware calls the {@code next} delegate to pass control to
* the next middleware in the pipeline. If middleware doesn’t call the next delegate,
* the adapter does not call any of the subsequent middleware’s request handlers or the
* bot’s receive handler, and the pipeline short circuits.
* <p>The {@code context} provides information about the
* incoming activity, and other data needed to process the activity.</p>
*
* {@linkalso TurnContext}
* {@linkalso Bot.Schema.Activity}
*/
void OnTurn(TurnContext context, NextDelegate next) throws Exception;
}
|
JanStureNielsen/Chronicle-Websocket-Jetty | src/main/java/net/openhft/chronicle/websocket/jetty/JettyServletFactory.java | /*
* Copyright 2016 <EMAIL>frequencytrading.<EMAIL>
*
* 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 net.openhft.chronicle.websocket.jetty;
import net.openhft.chronicle.wire.MarshallableOut;
import net.openhft.chronicle.wire.WireIn;
import org.eclipse.jetty.websocket.servlet.*;
import java.util.function.BiConsumer;
import java.util.function.Function;
public class JettyServletFactory<T> extends WebSocketServlet implements WebSocketCreator {
private final Function<MarshallableOut, T> outWrapper;
private final BiConsumer<WireIn, T> channel;
public JettyServletFactory(Function<MarshallableOut, T> outWrapper, BiConsumer<WireIn, T> channel) {
this.outWrapper = outWrapper;
this.channel = channel;
}
@Override
public void configure(WebSocketServletFactory factory) {
factory.setCreator(this);
}
@Override
public Object createWebSocket(ServletUpgradeRequest servletUpgradeRequest, ServletUpgradeResponse servletUpgradeResponse) {
return new JettyWebSocketAdapter<>(outWrapper, channel);
}
} |
Nannf/LeetCode | SomeInterestingAlgorithms/src/TreeTraversal.java | import java.sql.SQLOutput;
import java.util.*;
/**
* @auth Nannf
* @date 2020/6/27 10:33
* @description: 二叉树遍历
*/
public class TreeTraversal {
public static void main(String[] args) {
TreeNode tree = new TreeNode(1);
TreeNode t1 = new TreeNode(2);
TreeNode t2 = new TreeNode(3);
TreeNode t4 = new TreeNode(4);
TreeNode t5 = new TreeNode(5);
TreeNode t6 = new TreeNode(6);
TreeNode t7 = new TreeNode(7);
TreeNode t8 = new TreeNode(8);
tree.left = t1;
tree.right = t2;
t1.left = t4;
t1.right = t5;
t2.left = t6;
t2.right = t7;
t4.left = t8;
postOrderTraversal(tree);
}
/**
* 前序遍历
*
* @param tree
*/
public static void preOrderTraversal_recursion(TreeNode tree) {
if (tree == null) {
return;
}
System.out.println(tree.val);
preOrderTraversal_recursion(tree.left);
preOrderTraversal_recursion(tree.right);
}
public static void preOrderTraversal(TreeNode tree) {
if (tree == null) {
return;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(tree);
while (!stack.isEmpty()) {
TreeNode root = stack.pop();
System.out.println(root.val);
if (root.right != null) {
stack.push(root.right);
}
if (root.left != null) {
stack.push(root.left);
}
}
}
/**
* 中序遍历
*
* @param tree
*/
public static void inOrderTraversal_recursion(TreeNode tree) {
if (tree == null) {
return;
}
inOrderTraversal_recursion(tree.left);
System.out.println(tree.val);
inOrderTraversal_recursion(tree.right);
}
public static void inOrderTraversal(TreeNode tree) {
if (tree == null) {
return;
}
Stack<TreeNode> stack = new Stack<>();
// 链表的操作指针
TreeNode tmp = tree;
while (!stack.isEmpty() || tmp != null) {
// 把当前节点和所有的左孩子节点全部入栈
while (tmp != null) {
stack.push(tmp);
tmp = tmp.left;
}
TreeNode t1 = stack.pop();
System.out.println(t1.val);
if (t1.right != null) {
tmp = t1.right;
} else {
tmp = null;
}
}
}
/**
* 后续遍历
*
* @param tree
*/
public static void postOrderTraversal_recursion(TreeNode tree) {
if (tree == null) {
return;
}
postOrderTraversal_recursion(tree.left);
postOrderTraversal_recursion(tree.right);
System.out.println(tree.val);
}
public static void postOrderTraversal(TreeNode tree) {
if (tree == null) {
return;
}
Stack<TreeNode> stack = new Stack<>();
TreeNode head = tree;
TreeNode prev = null;
while (!stack.isEmpty() || head != null) {
// 左孩子全部入栈
while (head != null) {
stack.push(head);
head = head.left;
}
// 获取栈顶元素
TreeNode tmp = stack.peek();
// 只有当栈顶元素没有右孩子或者右孩子已经访问过
if (tmp.right== null || tmp.right == prev) {
// 栈顶元素出栈
tmp = stack.pop();
System.out.println(tmp.val);
//
prev = tmp;
} else {
head = tmp.right;
}
}
}
public static void levelOrder(TreeNode root) {
if (root == null) {
return;
}
Queue<TreeNode> queue = new ArrayDeque<>();
queue.offer(root);
while(!queue.isEmpty()){
List<TreeNode> list = new ArrayList<>();
while(!queue.isEmpty()) {
TreeNode tmp = queue.poll();
list.add(tmp);
}
for (TreeNode t : list) {
System.out.print(t.getVal() + " ");
}
System.out.println();
for (TreeNode t :list) {
if (t.left != null) {
queue.offer(t.left);
}
if (t.right != null) {
queue.offer(t.right);
}
}
}
}
}
|
shahedex/tfjson | vendor/github.com/hashicorp/terraform/builtin/providers/mysql/resource_grant_test.go | <filename>vendor/github.com/hashicorp/terraform/builtin/providers/mysql/resource_grant_test.go<gh_stars>1-10
package mysql
import (
"fmt"
"log"
"strings"
"testing"
mysqlc "github.com/ziutek/mymysql/mysql"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)
func TestAccGrant(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccGrantCheckDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccGrantConfig_basic,
Check: resource.ComposeTestCheckFunc(
testAccPrivilegeExists("mysql_grant.test", "SELECT"),
resource.TestCheckResourceAttr("mysql_grant.test", "user", "jdoe"),
resource.TestCheckResourceAttr("mysql_grant.test", "host", "example.com"),
resource.TestCheckResourceAttr("mysql_grant.test", "database", "foo"),
),
},
},
})
}
func testAccPrivilegeExists(rn string, privilege string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[rn]
if !ok {
return fmt.Errorf("resource not found: %s", rn)
}
if rs.Primary.ID == "" {
return fmt.Errorf("grant id not set")
}
id := strings.Split(rs.Primary.ID, ":")
userhost := strings.Split(id[0], "@")
user := userhost[0]
host := userhost[1]
conn := testAccProvider.Meta().(*providerConfiguration).Conn
stmtSQL := fmt.Sprintf("SHOW GRANTS for '%s'@'%s'", user, host)
log.Println("Executing statement:", stmtSQL)
rows, _, err := conn.Query(stmtSQL)
if err != nil {
return fmt.Errorf("error reading grant: %s", err)
}
if len(rows) == 0 {
return fmt.Errorf("grant not found for '%s'@'%s'", user, host)
}
privilegeFound := false
for _, row := range rows {
log.Printf("Result Row: %s", row[0])
privIndex := strings.Index(string(row[0].([]byte)), privilege)
if privIndex != -1 {
privilegeFound = true
}
}
if !privilegeFound {
return fmt.Errorf("grant no found for '%s'@'%s'", user, host)
}
return nil
}
}
func testAccGrantCheckDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*providerConfiguration).Conn
for _, rs := range s.RootModule().Resources {
if rs.Type != "mysql_grant" {
continue
}
id := strings.Split(rs.Primary.ID, ":")
userhost := strings.Split(id[0], "@")
user := userhost[0]
host := userhost[1]
stmtSQL := fmt.Sprintf("SHOW GRANTS for '%s'@'%s'", user, host)
log.Println("Executing statement:", stmtSQL)
rows, _, err := conn.Query(stmtSQL)
if err != nil {
if mysqlErr, ok := err.(*mysqlc.Error); ok {
if mysqlErr.Code == mysqlc.ER_NONEXISTING_GRANT {
return nil
}
}
return fmt.Errorf("error reading grant: %s", err)
}
if len(rows) != 0 {
return fmt.Errorf("grant still exists for'%s'@'%s'", user, host)
}
}
return nil
}
const testAccGrantConfig_basic = `
resource "mysql_user" "test" {
user = "jdoe"
host = "example.com"
password = "password"
}
resource "mysql_grant" "test" {
user = "${mysql_user.test.user}"
host = "${mysql_user.test.host}"
database = "foo"
privileges = ["UPDATE", "SELECT"]
}
`
|
BearerPipelineTest/Waves | node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/PowNewPrecisionTest.scala | <filename>node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/PowNewPrecisionTest.scala
package com.wavesplatform.state.diffs.smart.predef
import com.wavesplatform.db.WithDomain
import com.wavesplatform.db.WithState.AddrWithBalance
import com.wavesplatform.features.BlockchainFeatures._
import com.wavesplatform.lang.directives.values.V5
import com.wavesplatform.lang.v1.compiler.TestCompiler
import com.wavesplatform.settings.TestFunctionalitySettings
import com.wavesplatform.test.PropSpec
import com.wavesplatform.transaction.TxHelpers
class PowNewPrecisionTest extends PropSpec with WithDomain {
private val contract = TestCompiler(V5).compileContract(
"""
| @Callable(i)
| func default() = {
| let digits8 = 8
| let alpha = 50
| let alphaDigits = 2
| let beta = 46000000
| let scale8 = 100000000
| let scale12 = 1000000000000
| let x = 2661956191736
| let y = 2554192264270
| let sk = (((fraction(scale12, x, y) + fraction(scale12, y, x)) / 2) / 10000)
| let r1 = (fraction((x + y), scale8, pow(sk, digits8, alpha, alphaDigits, digits8, CEILING)) + (2 * fraction(pow(fraction(x, y, scale8), 0, 5, 1, (digits8 / 2), DOWN), pow((sk - beta), digits8, alpha, alphaDigits, digits8, DOWN), scale8)))
| let r2 = pow(10, 6, 6, 0, 0, CEILING)
| [
| IntegerEntry("result1", r1),
| IntegerEntry("result2", r2)
| ]
| }
""".stripMargin
)
private val scenario = {
val master = TxHelpers.signer(0)
val invoker = TxHelpers.signer(1)
val balances = AddrWithBalance.enoughBalances(master, invoker)
val setScript = TxHelpers.setScript(master, contract)
val invoke = () => TxHelpers.invoke(master.toAddress, invoker = invoker)
(balances, setScript, invoke, master.toAddress)
}
private val settings =
TestFunctionalitySettings
.withFeatures(BlockV5, SynchronousCalls)
.copy(syncDAppCheckPaymentsHeight = 4)
property("pow changes precision after syncDAppCheckPaymentsHeight") {
val (balances, setScript, invoke, dApp) = scenario
withDomain(domainSettingsWithFS(settings), balances) { d =>
d.appendBlock(setScript)
d.appendBlock(invoke())
d.blockchain.accountData(dApp, "result1").get.value shouldBe 9049204201489L
d.blockchain.accountData(dApp, "result2").get.value shouldBe 1
d.appendBlock(invoke())
d.blockchain.accountData(dApp, "result1").get.value shouldBe 9049204201491L
d.blockchain.accountData(dApp, "result2").get.value shouldBe 0
}
}
}
|
wrhb123/cloudpods | pkg/keystone/driver/cas/class.go | // Copyright 2019 Yunion
//
// 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 cas
import (
"context"
"net/url"
"yunion.io/x/jsonutils"
"yunion.io/x/pkg/errors"
api "yunion.io/x/onecloud/pkg/apis/identity"
"yunion.io/x/onecloud/pkg/httperrors"
"yunion.io/x/onecloud/pkg/keystone/driver"
"yunion.io/x/onecloud/pkg/keystone/driver/utils"
"yunion.io/x/onecloud/pkg/keystone/models"
"yunion.io/x/onecloud/pkg/mcclient"
)
type SCASDriverClass struct{}
func (self *SCASDriverClass) IsSso() bool {
return true
}
func (self *SCASDriverClass) ForceSyncUser() bool {
return false
}
func (self *SCASDriverClass) GetDefaultIconUri(tmpName string) string {
return "https://www.apereo.org/sites/default/files/styles/project_logo/public/projects/logos/cas_max_logo_0.png"
}
func (self *SCASDriverClass) SingletonInstance() bool {
return false
}
func (self *SCASDriverClass) SyncMethod() string {
return api.IdentityProviderSyncOnAuth
}
func (self *SCASDriverClass) NewDriver(idpId, idpName, template, targetDomainId string, conf api.TConfigs) (driver.IIdentityBackend, error) {
return NewCASDriver(idpId, idpName, template, targetDomainId, conf)
}
func (self *SCASDriverClass) Name() string {
return api.IdentityDriverCAS
}
func (self *SCASDriverClass) ValidateConfig(ctx context.Context, userCred mcclient.TokenCredential, template string, tconf api.TConfigs, idpId, domainId string) (api.TConfigs, error) {
conf := api.SCASIdpConfigOptions{}
confJson := jsonutils.Marshal(tconf[api.IdentityDriverCAS])
err := confJson.Unmarshal(&conf)
if err != nil {
return tconf, errors.Wrap(err, "unmarshal config")
}
if len(conf.CASServerURL) == 0 {
return tconf, errors.Wrap(httperrors.ErrInputParameter, "empty cas_server_url")
}
_, err = url.Parse(conf.CASServerURL)
if err != nil {
return tconf, errors.Wrap(httperrors.ErrInputParameter, "invalid cas_server_url")
}
// validate uniqueness
unique, err := models.IdentityProviderManager.CheckUniqueness(idpId, domainId, api.IdentityDriverCAS, template, api.IdentityDriverCAS, "cas_server_url", jsonutils.NewString(conf.CASServerURL))
if err != nil {
return tconf, errors.Wrap(err, "IdentityProviderManager.CheckUniqueness")
}
if !unique {
return tconf, errors.Wrapf(httperrors.ErrDuplicateResource, "cas_server_url %s has been registered", conf.CASServerURL)
}
conf.SIdpAttributeOptions, err = utils.ValidateConfig(conf.SIdpAttributeOptions, userCred)
if err != nil {
return tconf, errors.Wrap(err, "ValidateConfig")
}
nconf := make(map[string]jsonutils.JSONObject)
err = confJson.Unmarshal(&nconf)
if err != nil {
return tconf, errors.Wrap(err, "Unmarshal old config")
}
err = jsonutils.Marshal(conf).Unmarshal(&nconf)
if err != nil {
return tconf, errors.Wrap(err, "Unmarshal new config")
}
tconf[api.IdentityDriverCAS] = nconf
return tconf, nil
}
func init() {
driver.RegisterDriverClass(&SCASDriverClass{})
}
|
jeap-rs/code-examples | spring-boot/static/src/main/java/io/reflectoring/staticdata/RandomQuotePrinter.java | package io.reflectoring.staticdata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import java.util.Random;
@Configuration
@EnableScheduling
class RandomQuotePrinter {
private static final Logger logger = LoggerFactory.getLogger(RandomQuotePrinter.class);
private final Random random = new Random();
private final QuotesProperties quotesProperties;
RandomQuotePrinter(QuotesProperties quotesProperties) {
this.quotesProperties = quotesProperties;
}
@Scheduled(fixedRate = 5000)
void printRandomQuote(){
int index = random.nextInt(quotesProperties.getQuotes().size());
Quote quote = quotesProperties.getQuotes().get(index);
logger.info("'{}' - {}", quote.getText(), quote.getAuthor());
}
}
|
mayonghui9182/helloWorld | sourceCode/javase/onJava8/src/main/java/strings/JGrep.java | package strings;// strings/JGrep.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// A very simple version of the "grep" program
// {java JGrep
// WhitherStringBuilder.java 'return|for|String'}
import java.util.regex.*;
import java.nio.file.*;
import java.util.stream.*;
public class JGrep {
public static void
main(String[] args) throws Exception {
if(args.length < 2) {
System.out.println(
"Usage: java JGrep file regex");
System.exit(0);
}
Pattern p = Pattern.compile(args[1]);
// Iterate through the lines of the input file:
int index = 0;
Matcher m = p.matcher("");
for(String line :
Files.readAllLines(Paths.get(args[0]))) {
m.reset(line);
while(m.find())
System.out.println(index++ + ": " +
m.group() + ": " + m.start());
}
}
}
/* Output:
0: for: 4
1: for: 4
*/
|
elsys/po-2015 | A/02/22/task1.c | #include <stdio.h>
void minmax(int *, int , int *, int *);
int main()
{
int arr[500];
int size;
int min, max;
int n, i=0;
scanf("%d",&n);
size=n;
while(i!=n)
{
scanf("%d",&arr[i]);
i++;
}
minmax(arr, size, &min, &max);
printf("%d", min+max);
return 0;
}
void minmax(int *arr, int size, int *min, int *max)
{
*min=arr[0];
*max=arr[0];
for(int i=0; i!=size; i++)
{
if(*min>arr[i])
{
*min=arr[i];
}
if(*max<arr[i])
{
*max=arr[i];
}
}
} |
Yannic/chromium | chrome/browser/extensions/chrome_extension_chooser_dialog.h | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_EXTENSIONS_CHROME_EXTENSION_CHOOSER_DIALOG_H_
#define CHROME_BROWSER_EXTENSIONS_CHROME_EXTENSION_CHOOSER_DIALOG_H_
#include "base/macros.h"
namespace content {
class WebContents;
}
namespace permissions {
class ChooserController;
}
class ChromeExtensionChooserDialog {
public:
explicit ChromeExtensionChooserDialog(content::WebContents* web_contents)
: web_contents_(web_contents) {}
ChromeExtensionChooserDialog(const ChromeExtensionChooserDialog&) = delete;
ChromeExtensionChooserDialog& operator=(const ChromeExtensionChooserDialog&) =
delete;
~ChromeExtensionChooserDialog() {}
void ShowDialog(
std::unique_ptr<permissions::ChooserController> chooser_controller) const;
private:
void ShowDialogImpl(
std::unique_ptr<permissions::ChooserController> chooser_controller) const;
content::WebContents* web_contents_;
};
#endif // CHROME_BROWSER_EXTENSIONS_CHROME_EXTENSION_CHOOSER_DIALOG_H_
|
mochixuan/ReactNode | React202006/r020606/src/App.js | <reponame>mochixuan/ReactNode
// import TestHook from './TestHook'
// export default TestHook;
// import ReduxApp from './redux-container/ReduxApp'
// export default ReduxApp;
// import ReduxHookApp from './redux-hook-container'
// export default ReduxHookApp
// import ContextTest from './contextTest'
// export default ContextTest;
// import DomTest from './dom/DomTest'
// export default DomTest;
import HistoryTest from './history/index'
export default HistoryTest |
nmehrle/athena-public-version | src/diagnostics/diagnostics.hpp | #ifndef DIAGNOSTICS_HPP_
#define DIAGNOSTICS_HPP_
// C++ header
#include <string>
// Athena++ headers
#include "../mesh/mesh.hpp"
#include "../athena_arrays.hpp"
class ParameterInput;
class Diagnostics {
public:
// data
std::string myname, type, grid;
Diagnostics *prev, *next;
AthenaArray<Real> data;
int ncycle;
// functions
Diagnostics(MeshBlock *pmb, ParameterInput *pin);
Diagnostics(MeshBlock *pmb, std::string name);
virtual ~Diagnostics();
Diagnostics* operator[](std::string name);
template<typename Dg> Diagnostics* AddDiagnostics(Dg const& d) {
Dg *pd = new Dg(d);
Diagnostics *p = this;
while (p->next != NULL) p = p->next;
p->next = pd;
p->next->prev= p;
p->next->next = NULL;
return p->next;
}
virtual void Progress(AthenaArray<Real> const& w) {}
virtual void Finalize(AthenaArray<Real> const& w) {}
protected:
MeshBlock *pmy_block_;
int ncells1_, ncells2_, ncells3_;
// geometric arrays
AthenaArray<Real> x1area_, x2area_, x2area_p1_, x3area_, x3area_p1_, vol_;
AthenaArray<Real> x1edge_, x1edge_p1_, x2edge_, x2edge_p1_, x3edge_, x3edge_p1_;
};
// register all diagnostics
// 1. divergence
class Divergence: public Diagnostics {
public:
Divergence(MeshBlock *pmb);
virtual ~Divergence();
void Finalize(AthenaArray<Real> const& w);
protected:
AthenaArray<Real> v1f1_, v2f2_, v3f3_;
};
// 2. curl
class Curl: public Diagnostics {
public:
Curl(MeshBlock *pmb);
virtual ~Curl();
void Finalize(AthenaArray<Real> const& w);
protected:
AthenaArray<Real> v3f2_, v2f3_, v1f3_, v3f1_, v2f1_, v1f2_;
};
// 3. hydro mean
class HydroMean : public Diagnostics {
public:
HydroMean(MeshBlock *pmb);
virtual ~HydroMean();
void Progress(AthenaArray<Real> const& w);
void Finalize(AthenaArray<Real> const& w);
protected:
int last_output_cycle_;
};
// 4. temperature anomaly
class TemperatureAnomaly: public Diagnostics {
public:
TemperatureAnomaly(MeshBlock *pmb);
virtual ~TemperatureAnomaly();
void Finalize(AthenaArray<Real> const& w);
};
// 5. pressure anomaly
class PressureAnomaly: public Diagnostics {
public:
PressureAnomaly(MeshBlock *pmb);
virtual ~PressureAnomaly();
void Finalize(AthenaArray<Real> const& w);
};
// 6. eddy flux
class EddyFlux: public Diagnostics {
public:
EddyFlux(MeshBlock *pmb);
virtual ~EddyFlux();
void Progress(AthenaArray<Real> const& w);
void Finalize(AthenaArray<Real> const& w);
protected:
AthenaArray<Real> eddy_, mean_;
};
// 7. total flux
class TotalFlux: public Diagnostics {
public:
TotalFlux(MeshBlock *pmb);
virtual ~TotalFlux();
void Progress(AthenaArray<Real> const& w);
void Finalize(AthenaArray<Real> const& w);
};
// 8. horizontal divergence
class HorizontalDivergence: public Diagnostics {
public:
HorizontalDivergence(MeshBlock *pmb);
virtual ~HorizontalDivergence();
void Finalize(AthenaArray<Real> const& w);
protected:
AthenaArray<Real> v2f2_, v3f3_;
};
// 9. Buoyancy
class Buoyancy: public Diagnostics {
public:
Buoyancy(MeshBlock *pmb);
virtual ~Buoyancy();
void Finalize(AthenaArray<Real> const& w);
protected:
AthenaArray<Real> wl_, wr_;
};
#endif
|
alancnet/fantasy-names | generators/game_of_thrones/free_citys.js | var generatorOf = require('../../generator-of');
module.exports = generatorOf(function generator$game_of_thrones$free_citys(type) {
var names1 = ["Adar", "Aer", "Ar", "Ball", "Bel", "Brach", "Daar", "Don", "Draq", "Garr", "Goran", "Gyll", "Har", "Harl", "Hor", "Ill", "Inn", "Irr", "Jaer", "Jaq", "Jor", "Laraz", "Laz", "Lys", "Maerr", "Mal", "Mar", "Nak", "Nor", "Nyess", "Sall", "Stall", "Syr", "Thor", "Treg", "Tych", "Var", "Varg", "Vog", "Vyr"];
var names2 = ["adhor", "an", "ano", "aphos", "aquo", "ar", "ario", "aro", "apho", "arro", "ello", "elos", "en", "enhor", "enno", "eo", "eqor", "ero", "esso", "icho", "idos", "illos", "io", "iphos", "iros", "o", "odos", "onar", "onno", "onos", "oquo", "or", "orno", "oros", "os", "yllo", "ynno", "yrio", "yros", "ys"];
var names3 = ["Ahr", "Aren", "Daen", "Dil", "Dor", "Erin", "Erl", "Faey", "Fer", "Firan", "Harr", "Hel", "Hen", "Il", "Iner", "Laen", "Ler", "Less", "Mel", "Mesh", "Min", "Nes", "Nil", "Noar", "Onal", "Or", "Phen", "Phir", "Sael", "Ser", "Sir", "Taen", "Tir", "Triann", "Vaer", "Vell", "Vor", "Waer", "Wen", "Wyn"];
var names4 = ["a", "aena", "aerah", "ala", "aleah", "anah", "anea", "aria", "asha", "aya", "eah", "ela", "ella", "elna", "era", "erah", "esa", "esha", "eya", "eyana", "ianna", "ila", "ina", "ira", "irah", "issa", "ola", "olana", "olla", "ona", "ora", "oreah", "orlah", "osha", "ylea", "ylla", "yna", "ynea", "ysa", "ysha"];
var names5 = ["Aen", "Ahr", "Aner", "Baerr", "Bah", "Bren", "Dirr", "Drenn", "Dyn", "Enn", "Eran", "Ess", "Faen", "Flaer", "For", "Fyll", "Hart", "Hest", "Hot", "Iran", "Irn", "Irr", "Maeg", "Mar", "Mop", "Naer", "Nah", "Nest", "Orl", "Orm", "Ost", "Paen", "Pahr", "Phass", "San", "Sorr", "Stass", "Vhass", "Voll", "Vyn"];
var names6 = ["aan", "aar", "aenor", "ah", "ahran", "anar", "ar", "aris", "assar", "atis", "el", "elar", "elion", "en", "enohr", "erah", "erion", "erris", "in", "inar", "ion", "ios", "irah", "iris", "iros", "ohr", "ohrin", "olis", "onnis", "oran", "oris", "orlan", "os", "oyor", "yl", "ymion", "yr", "yrion", "yris", "ys"];
i = Math.floor(this.random() * 10); {
if (type === 1) {
rnd = Math.floor(this.random() * names3.length);
rnd2 = Math.floor(this.random() * names4.length);
rnd3 = Math.floor(this.random() * names5.length);
rnd4 = Math.floor(this.random() * names6.length);
names = names3[rnd] + names4[rnd2] + " " + names5[rnd3] + names6[rnd4];
} else {
rnd = Math.floor(this.random() * names1.length);
rnd2 = Math.floor(this.random() * names2.length);
rnd3 = Math.floor(this.random() * names5.length);
rnd4 = Math.floor(this.random() * names6.length);
names = names1[rnd] + names2[rnd2] + " " + names5[rnd3] + names6[rnd4];
}
return names;
}
}) |
gregory-chekler/api | src/database/utils/constants.py | <reponame>gregory-chekler/api
"""
This file contains constants used throughout the codebase.
"""
SHORT_STR_LEN = 100
LONG_STR_LEN = 10000
TINY_STR_LEN = 15 |
steadylearner/code | src/__tests__/isReserved.test..js | const { isReserved } = require("..");
describe('Test simple cases', () => {
const reserved = ["title", "href"];
const withValid = "title";
const withInvalid = "will be false";
test("Simply verfiy it works with reserved words", () => {
expect(isReserved(reserved)(withValid))
.toBe(true);
});
test("Simply verfiy it fails with unreserved words", () => {
expect(isReserved(reserved)(withInvalid))
.toBe(false);
});
});
|
rsingh-flx/jfixture | jfixture/src/test/java/com/flextrade/jfixture/behaviours/tracing/TestDebugTracingStrategy.java | <reponame>rsingh-flx/jfixture
package com.flextrade.jfixture.behaviours.tracing;
import com.flextrade.jfixture.exceptions.ObjectCreationException;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class TestDebugTracingStrategy {
private DebugTracingStrategy strategy;
private StringBuilder appendable;
private Object request;
private Object response;
@Before
public void initialise() {
this.strategy = new DebugTracingStrategy();
this.appendable = new StringBuilder();
this.request = "request";
this.response = "response";
}
@Test
public void writing_request_is_formatted_correctly() throws IOException {
this.strategy.writeRequest(this.appendable, this.request);
assertEquals("Requested: request\n", this.appendable.toString());
}
@Test
public void writing_multiple_requests_are_indented() throws IOException {
this.strategy.writeRequest(this.appendable, this.request);
this.strategy.writeRequest(this.appendable, this.request);
assertEquals("Requested: request\n\tRequested: request\n", this.appendable.toString());
}
@Test
public void writing_response_is_formatted_correctly() throws IOException {
this.strategy.writeCreated(this.appendable, this.request, this.response);
assertEquals("Created: response\n", this.appendable.toString());
}
@Test
public void writing_multiple_requests_and_responses_are_indented() throws IOException {
this.strategy.writeRequest(this.appendable, this.request);
this.strategy.writeRequest(this.appendable, this.request);
this.strategy.writeCreated(this.appendable, this.request, this.response);
this.strategy.writeCreated(this.appendable, this.request, this.response);
assertEquals("Requested: request\n\tRequested: request\n\tCreated: response\nCreated: response\n", this.appendable.toString());
}
@Test
public void writing_errors_includes_the_inner_exceptions() throws IOException {
String nullPointerMessage = "null pointer message";
String objectCreationMessage = "creation message";
NullPointerException nullPointerException = new NullPointerException(nullPointerMessage);
Exception exception = new ObjectCreationException(objectCreationMessage, nullPointerException);
this.strategy.writeError(this.appendable, exception);
String errorMessage = this.appendable.toString();
assertTrue(errorMessage.contains(nullPointerMessage));
assertTrue(errorMessage.contains(objectCreationMessage));
}
}
|
FDA/Healthy-Citizen-Code | adp-frontend-web-v3/app/app.constants.js | <filename>adp-frontend-web-v3/app/app.constants.js
;(function () {
'use strict';
angular
.module('app')
.constant('APP_CONFIG', window.appConfig);
})(); |
FMSoftCN/iphone-like-demo | src/calculator/calc_size.h | /*
** $Id: calc_size.h 224 2007-07-03 09:38:24Z xwyan $
**
** calc_size.h: define the buttons layout of calc
**
** Copyright (C) 2006 Feynman Software.
**
** All right reserved by Feynman Software.
**
** Current maintainer: <NAME>.
**
** Create date: 2006/11/17
*/
#ifndef CALC_SIZE_H
#define CALC_SIZE_H
#ifdef __cplusplus
extern "C" {
#endif
#include "config.h"
#define CALCWINDOW_LX 0
#define CALCWINDOW_TY 0
#define CALCWINDOW_RX IPHONE_MAIN_WIDTH
#define CALCWINDOW_BY IPHONE_MAIN_HEIGHT
#define CALCWINDOW_WIDTH (CALCWINDOW_RX - CALCWINDOW_LX)
#define CALCWINDOW_HEIGHT (CALCWINDOW_BY - CALCWINDOW_TY)
//#define CALC_BMP_BN "res/calculator_num.png"
#define CALC_BMP_BN "res/calc_num.png"
#ifdef ENABLE_LANDSCAPE
#define CALC_BMP_BG "res/calculator_bg.png"
#define CALC_BMP_BC "res/calculator_click.png"
//the size of bottons
#define CALC_B_W 80
#define CALC_B_H 40
#define CALC_B_BORDERT 7
#define CALC_B_BORDERB 4
//static box displaying result
#define CALC_DISPLAY_T 10
#define CALC_DISPLAY_R 313
#define CALC_DISPLAY_L 65
#define CALC_DISPLAY_B 33
#define CALC_BEGIN_X 0
#define CALC_BEGIN_Y 39
#else
/*The following is for portrait.*/
//#define CALC_BMP_BG "res/calculator_bg_pt.png"
//#define CALC_BMP_BC "res/calculator_click_pt.png"
#define CALC_BMP_BG "res/calc_bg_pt.png"
#define CALC_BMP_BC "res/calc_ck_pt.png"
//the size of bottons
#define CALC_B_W 60
#define CALC_B_H 46//53
#define CALC_B_BORDERT 8//8//9
#define CALC_B_BORDERB 6//7
//static box displaying result
#define CALC_DISPLAY_T 31//15
#define CALC_DISPLAY_R 234
#define CALC_DISPLAY_L 10//25
#define CALC_DISPLAY_B 51//44
#define CALC_BEGIN_X 0
#define CALC_BEGIN_Y 90//52
#endif
/*the following is no use for this version*/
//the distance between bottons
#define BD 5 //border distance
#define HD 14//5 //H-distance
#define VD 14//6
#define B_W_SC 42
#define B_H_SC 20
#define HD_SC 5
#define VD_SC 4 //V-distance
#define BEGIN_X_SC (BD)
#define BEGIN_Y_SC (CALC_DISPLAY_B + 5)
#define ARROW_LEFT (BD)
#define ARROW_TOP VD
#define ARROW_RIGHT (ARROW_LEFT + 12)
#define ARROW_BOTTOM (ARROW_TOP + 10)
//static box display "M"
#define SM_W 20//13
#define SM_H 20//12
#define SM_X 263//(B_W + BD + 3)
#define SM_Y 15//(VD)
#define CHK_INV_W 50
#define CHK_INV_H 17
#define CHK_INV_X (CHK_HYP_X - HD - CHK_INV_W)
#define CHK_INV_Y BEGIN_Y_SC
#define CHK_HYP_W 50
#define CHK_HYP_H 17
#define CHK_HYP_X (CALCWINDOW_WIDTH - BD - CHK_HYP_W)
#define CHK_HYP_Y BEGIN_Y_SC
#define BTN_ANG_W (B_W_SC + 3)
#define BTN_ANG_H B_H_SC
#define BTN_ANG_X (CALCWINDOW_WIDTH - BD - 3 - BTN_ANG_W)
#define BTN_ANG_Y (BEGIN_Y_SC + B_H_SC + VD)
#define BTN_BASE_W BTN_ANG_W
#define BTN_BASE_H B_H_SC
#define BTN_BASE_X (BTN_ANG_X - BTN_BASE_W - HD + 1)
#define BTN_BASE_Y BTN_ANG_Y
#define BTN_UNIT_W 86
#define BTN_UNIT_H 21
#define BTN_UNIT_X (CALCWINDOW_WIDTH - BD - BTN_UNIT_W - BD - 1)
#define BTN_UNIT_Y BEGIN_Y
#ifdef __cplusplus
}
#endif
#endif /* CALC_SIZE_H */
|
veler/clipboardzanager | Android/app/src/test/java/com/etiennebaudoux/clipboardzanager/componentmodel/io/IoUtilsTest.java | package com.etiennebaudoux.clipboardzanager.componentmodel.io;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import static org.junit.Assert.assertArrayEquals;
public class IoUtilsTest {
@Test
public void copy() throws Exception {
byte[] data = new byte[] { 72, 101, 108, 108, 111 }; // Hello
ByteArrayInputStream input = new ByteArrayInputStream(data);
ByteArrayOutputStream output = new ByteArrayOutputStream();
IoUtils.copy(input, output);
assertArrayEquals(new byte[] { 72, 101, 108, 108, 111 }, output.toByteArray());
}
}
|
marcosppastor/MSV146 | scripts/npc/9270026.js | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 <NAME> <<EMAIL>>
<NAME> <<EMAIL>>
<NAME> <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation version 3 as published by
the Free Software Foundation. You may not use, modify or distribute
this program under any other version of the GNU Affero General Public
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* Sixx
Singa REG/VIP Eye Color Changer
*/
var status = 0;
var beauty = 0;
var colors = Array();
function start() {
cm.sendSimple("Hi, there! I'm Sixx, in charge of Da Yan Jing Lens Shop here at CBD! With #b#t5152039##k or #b#t5152040##k, you can let us take care of the rest and have the kind of beautiful look you've always craved! Remember, the first thing everyone notices about you are the eyes, and we can help you find the cosmetic lens that most fits you! Now, what would you like to use?\r\n#L1#Cosmetic Lenses: #i5152039##t5152039##l\r\n#L2#Cosmetic Lenses: #i5152040##t5152040##l");
}
function action(mode, type, selection) {
if (mode < 1)
cm.dispose();
else {
status++;
if (status == 1) {
if (selection == 1) {
beauty = 1;
var current = cm.getPlayer().getFace()% 100 + 20000 + cm.getPlayer().getGender() * 1000;
cm.sendYesNo("If you use the regular coupon, you'll be awarded a random pair of cosmetic lenses. Are you going to use a #b#t5152039##k and really make the change to your eyes?");
} else {
beauty = 2;
var current = cm.getPlayer().getFace()% 100 + 20000 + cm.getPlayer().getGender() * 1000;
colors = [current , current + 100, current + 200, current + 300, current +400, current + 500, current + 600, current + 700];
cm.sendStyle("With our specialized machine, you can see yourself after the treatment in advance. What kind of lens would you like to wear? Choose the style of your liking.", colors);
}
}
else if (status == 2) {
if (beauty == 1){
if (cm.haveItem(5152039)){
cm.gainItem(5152039, -1);
cm.setFace(Math.floor(Math.random() * 8) * 100 + current);
cm.sendOk("Enjoy your new and improved cosmetic lenses!");
} else
cm.sendOk("I'm sorry, but I don't think you have our cosmetic lens coupon with you right now. Without the coupon, I'm afraid I can't do it for you..");
} else if (beauty == 2){
if (cm.haveItem(5152040)){
cm.gainItem(5152040, -1);
cm.setFace(colors[selection]);
cm.sendOk("Enjoy your new and improved cosmetic lenses!");
} else
cm.sendOk("I'm sorry, but I don't think you have our cosmetic lens coupon with you right now. Without the coupon, I'm afraid I can't do it for you..");
}
cm.dispose();
}
}
}
|
RyanTruran/EmbeddedSystems.Playground | 01 - Independent Study/UTAustinX_610/Labware/CC3100_docs/simplelink_api/html/search/all_3.js | <filename>01 - Independent Study/UTAustinX_610/Labware/CC3100_docs/simplelink_api/html/search/all_3.js
var searchData=
[
['event_5fdropped_5fdevice_5fasync_5fgeneral_5ferror',['EVENT_DROPPED_DEVICE_ASYNC_GENERAL_ERROR',['../group__device.html#ga3186925e3acec312e7d74733b8b64a87',1,'device.h']]]
];
|
erasme/kjing | share/www/admin/kjing/device/deviceproperties.js | <filename>share/www/admin/kjing/device/deviceproperties.js
KJing.ResourceProperties.extend('KJing.DeviceProperties', {
deviceUrlField: undefined
}, {
build: function() {
KJing.DeviceProperties.base.build.apply(this, arguments);
this.deviceUrlField = new KJing.TextField({
title: 'URL du client Web', width: 300, disabled: true,
value: (new Core.Uri({ uri: '../client/?device='+this.resource.getId() })).toString() });
this.insertAt(this.deviceUrlField, 1);
}
});
KJing.ResourceProperties.register('device', KJing.DeviceProperties);
|
bhm/Cthulhator | cthulhator/src/main/java/com/bustiblelemons/cthulhator/character/creation/ui/PreviewCardFragment.java | <gh_stars>1-10
package com.bustiblelemons.cthulhator.character.creation.ui;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bustiblelemons.cthulhator.R;
import com.bustiblelemons.cthulhator.character.persistance.SavedCharacter;
import com.bustiblelemons.fragments.AbsParcelableArgFragment;
import com.bustiblelemons.views.loadingimage.RemoteImage;
import butterknife.ButterKnife;
import butterknife.InjectView;
/**
* Created by bhm on 21.09.14.
*/
public class PreviewCardFragment extends AbsParcelableArgFragment<SavedCharacter> {
@InjectView(R.id.icon)
RemoteImage imageView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_preview_card, container, false);
ButterKnife.inject(this, rootView);
return rootView;
}
@Override
protected void onInstanceArgumentRead(SavedCharacter instanceArgument) {
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.