content
stringlengths 10
4.9M
|
---|
def _transform(self, mixture_specs, targets_specs_list):
input_spectra = (
np.abs(mixture_specs) if np.iscomplexobj(mixture_specs) else mixture_specs
)
if self.apply_log:
input_spectra = np.log(np.maximum(input_spectra, EPSILON))
if self.mvn_dict:
input_spectra = apply_cmvn(input_spectra, self.mvn_dict)
source_attr = {}
target_attr = {}
if np.iscomplexobj(mixture_specs):
source_attr["spectrogram"] = th.tensor(
np.abs(mixture_specs), dtype=th.float32
)
target_attr["spectrogram"] = [
th.tensor(np.abs(t), dtype=th.float32) for t in targets_specs_list
]
source_attr["phase"] = th.tensor(np.angle(mixture_specs), dtype=th.float32)
target_attr["phase"] = [
th.tensor(np.angle(t), dtype=th.float32) for t in targets_specs_list
]
else:
source_attr["spectrogram"] = th.tensor(mixture_specs, dtype=th.float32)
target_attr["spectrogram"] = [
th.tensor(t, dtype=th.float32) for t in targets_specs_list
]
return {
"num_frames": mixture_specs.shape[0],
"feature": th.tensor(input_spectra, dtype=th.float32),
"source_attr": source_attr,
"target_attr": target_attr,
} |
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Location location = new Location("");
double latitude = getIntent().getDoubleExtra("latitude", 0);
double longitude = getIntent().getDoubleExtra("longitude", 0);
String city = getIntent().getStringExtra("city");
Log.d("LATITUDINE", String.valueOf(latitude));
location.setLatitude(latitude);
location.setLongitude(longitude);
Context context= getApplicationContext();
new MainActivity().download5dayData(location, context, new Response.Listener() {
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onResponse(Object response) {
List<Weather> dataw = new ArrayList<>();
DateTimeFormatter formatterinput = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
DateTimeFormatter formatteroutput = DateTimeFormatter.ofPattern("yyyy-MM-dd");
try {
LocalDate today = LocalDate.now();
String stoday = formatteroutput.format(today);
int j=0;
JSONObject jsonObject = new JSONObject(String.valueOf(response));
JSONArray weath = jsonObject.getJSONArray("list");
for (int i = 0; i < weath.length(); i++) {
JSONObject item = weath.getJSONObject(i);
String datee = item.getString("dt_txt");
LocalDate tempdate=LocalDate.parse(datee,formatterinput);
String fdatee=formatteroutput.format(tempdate);
if(j==5){
break;
}
if(!stoday.equals(fdatee)){
JSONArray weatday= item.getJSONArray("weather");
JSONObject temporaney=weatday.getJSONObject(0);
String wd = temporaney.getString("main");
LocalDate date= LocalDate.parse(fdatee);
dataw.add(new Weather("", 0, 0,"",0, wd,date,0,0));
Log.d("ARRAY:", String.valueOf(dataw.get(0).getDate()));
stoday=fdatee;
j++;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("SIZE", String.valueOf(dataw.size()));
setData(dataw);
}
});
if(city == null) return;
mMap.setMapType(MAP_TYPE_HYBRID);
UiSettings uiSettings = googleMap.getUiSettings();
uiSettings.setCompassEnabled(true);
uiSettings.setIndoorLevelPickerEnabled(true);
uiSettings.setMapToolbarEnabled(true);
uiSettings.setZoomControlsEnabled(true);
uiSettings.setMyLocationButtonEnabled(true);
uiSettings.setScrollGesturesEnabled(false);
LatLng position = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(position).title(String.format("%s", city)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 5));
} |
def mkdir(dir: str):
os.makedirs(dir, mode=0o777, exist_ok=True) |
import math as m
class Tessellation(object):
def __init__(self, type, xsize, ysize, zsize):
self.type = type
self.xsize = xsize
self.ysize = ysize
self.zsize = zsize
def create_base_grid(self):
return base_grid
def base_brep(self):
pass
def get_vertices(self):
return verts
def get_centroid(self):
return centroid
def calc_vec_from_centroid_vert(self):
return vec
def create_vert_plane(self):
return plane
def create_cutter_srf(self):
return cutter
def truncate(self):
return module
def tessellate(self):
return modules
|
<gh_stars>100-1000
export * from "./mockData";
export * from "./mockHttpClient";
export * from "./user"; |
<gh_stars>1-10
// Copyright (c) 2021 Terminus, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package marketProto
import (
"context"
"encoding/json"
"errors"
"fmt"
"strconv"
"github.com/erda-project/erda-infra/base/servicehub"
"github.com/erda-project/erda-infra/providers/component-protocol/cptype"
"github.com/erda-project/erda-infra/providers/component-protocol/utils/cputil"
"github.com/erda-project/erda/apistructs"
"github.com/erda-project/erda/bundle"
"github.com/erda-project/erda/modules/dop/component-protocol/components/auto-test-scenes/rightPage/fileDetail/fileConfig/scenesConfig/stagesOperations/apiEditorDrawer/apiEditorContainer/apiEditor"
"github.com/erda-project/erda/modules/dop/component-protocol/types"
"github.com/erda-project/erda/modules/openapi/component-protocol/components/base"
)
type MarketProto struct {
base.DefaultProvider
bdl *bundle.Bundle
sdk *cptype.SDK
}
// OperationData 解析OperationData
type OperationData struct {
Meta struct {
KeyWord string `json:"keyWord"`
APISpecID uint64 `json:"selectApiSpecId"`
} `json:"meta"`
}
func init() {
base.InitProviderWithCreator("auto-test-scenes", "marketProto",
func() servicehub.Provider { return &MarketProto{} })
}
func (mp *MarketProto) Render(ctx context.Context, c *cptype.Component, scenario cptype.Scenario, event cptype.ComponentEvent, gs *cptype.GlobalStateData) error {
// 塞市场接口的数据
tmpStepID, ok := c.State["stepId"]
if !ok {
// not exhibition if no stepId
return nil
}
// TODO: 类型要改
stepID, err := strconv.ParseUint(fmt.Sprintf("%v", tmpStepID), 10, 64)
if err != nil {
return err
}
if stepID == 0 {
return nil
}
mp.bdl = ctx.Value(types.GlobalCtxKeyBundle).(*bundle.Bundle)
mp.sdk = cputil.SDK(ctx)
userID := mp.sdk.Identity.UserID
orgIDStr := mp.sdk.Identity.OrgID
if orgIDStr == "" {
return errors.New("orgID is empty")
}
orgID, err := strconv.ParseUint(orgIDStr, 10, 64)
if err != nil {
return err
}
// var orgID uint64 = 1
var opreationData OperationData
odBytes, err := json.Marshal(event.OperationData)
if err != nil {
return err
}
if err := json.Unmarshal(odBytes, &opreationData); err != nil {
return err
}
if c.Data == nil {
c.Data = make(map[string]interface{}, 0)
}
c.State["apiSpecId"] = nil
switch event.Operation.String() {
case "searchAPISpec":
if opreationData.Meta.KeyWord == "" {
return nil
}
apis, err := mp.bdl.SearchAPIOperations(orgID, userID, opreationData.Meta.KeyWord)
if err != nil {
return err
}
c.Data["list"] = apis
return nil
case "changeAPISpec":
if opreationData.Meta.APISpecID == 0 {
// 切换成自定义的api
c.Data["list"] = []apistructs.APIOperationSummary{}
if _, ok := c.State["value"]; ok {
delete(c.State, "value")
}
c.State["apiSpecId"] = apiEditor.EmptySpecID
return nil
}
// 切换到api集市另一个api
apiSpec, err := mp.bdl.GetAPIOperation(orgID, userID, opreationData.Meta.APISpecID)
if err != nil {
return err
}
c.Data["list"] = []apistructs.APIOperationSummary{
{
ID: opreationData.Meta.APISpecID,
OperationID: apiSpec.OperationID,
Path: apiSpec.Path,
Version: apiSpec.Version,
Method: apiSpec.Method,
},
}
c.State["apiSpecId"] = opreationData.Meta.APISpecID
c.State["value"] = opreationData.Meta.APISpecID
return nil
}
// 渲染
step, err := mp.bdl.GetAutoTestSceneStep(apistructs.AutotestGetSceneStepReq{
ID: stepID,
UserID: userID,
})
if err != nil {
return err
}
var apiInfo apistructs.APIInfo
if step.Value == "" {
step.Value = "{}"
}
if err := json.Unmarshal([]byte(step.Value), &apiInfo); err != nil {
return err
}
if step.APISpecID != 0 {
apiSpec, err := mp.bdl.GetAPIOperation(orgID, userID, step.APISpecID)
if err != nil {
return err
}
c.Data["list"] = []apistructs.APIOperationSummary{
{
ID: step.APISpecID,
OperationID: apiSpec.OperationID,
Path: apiSpec.Path,
Version: apiSpec.Version,
Method: apiSpec.Method,
},
}
c.State["value"] = step.APISpecID
} else {
if _, ok := c.State["value"]; ok {
delete(c.State, "value")
}
}
return nil
}
|
Counselling: how should it be defined and evaluated?
Counselling is becoming an increasingly popular approach among nurses working with people with mental health problems. This paper explores some basic questions about counselling. What is it? How does it differ from other conversations and from psychotherapy? Does it actually work? If counselling is to become widely used in the nursing profession, these issues need to be addressed. |
<gh_stars>1-10
//------------------------------------------------------------------------------
// Copyright (c) 2016 by contributors. 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.
//------------------------------------------------------------------------------
/*
Author: <NAME> (<EMAIL>)
This file defines the Reader class that is responsible for sampling
data from data source.
*/
#ifndef F2M_READER_READER_H_
#define F2M_READER_READER_H_
#include <string>
#include <vector>
#include <thread>
#include "src/base/common.h"
#include "src/base/class_register.h"
#include "src/base/scoped_ptr.h"
#include "src/data/data_structure.h"
#include "src/reader/parser.h"
#include "src/thread/condition_variable.h"
#include "src/thread/mutex.h"
#include "src/thread/scoped_locker.h"
namespace f2m {
//------------------------------------------------------------------------------
// Reader is an abstract class which can be implemented in different way,
// such as the InmemReader, which samples data from memory buffer, and the
// OndiskReader, which samples data from disk file.
//
// We can use the Reader class like this (Pseudo code):
//
// #include "reader.h"
//
// Reader* reader = new OndiskReader(); // or new InmemReader();
//
// reader->Initialize(filename = "/tmp/testdata", // the data path
// num_samples = 100, // return N samples
// parser = libsvm_parser, // data format
// model_type = LR); // logistic regression
//
// Loop {
//
// int num_samples = reader->Samples(DMatrix);
//
// // use data samples to train model ...
//
// }
//
// The reader will return 0 when reaching the end of data source, and then
// we can invoke GoToHead() to return to the begining of data, or
// end reading.
//------------------------------------------------------------------------------
class Reader {
public:
Reader() { }
virtual ~Reader() { }
// We need to invoke this method before we sample data.
virtual void Initialize(const std::string& filename,
int num_samples,
Parser* parser,
ModelType type = LR) = 0;
// Sample data from disk or from memory buffer.
// Samples() return 0 indicates that we reach the end of the data source.
virtual int Samples(DMatrix* &matrix) = 0;
// Return to the begining of the data source.
virtual void GoToHead() = 0;
// Normalize data (only used in in-memory Reader)
virtual void Normalize(real_t max, real_t min) { }
protected:
std::string filename_; // Indicate the input file
int num_samples_; // Number of data samples in each samplling
FILE* file_ptr_; // Maintain current file pointer
DMatrix data_samples_; // Data sample
Parser* parser_; // Parse StringList to DMatrix
private:
DISALLOW_COPY_AND_ASSIGN(Reader);
};
//------------------------------------------------------------------------------
// Sampling data from memory buffer.
// At each begining of sample we random shuffle the data.
//------------------------------------------------------------------------------
class InmemReader : public Reader {
public:
InmemReader() { }
~InmemReader();
// Pre-load all the data into memory buffer.
virtual void Initialize(const std::string& filename,
int num_samples,
Parser* parser,
ModelType type = LR);
// Sample data from memory.
virtual int Samples(DMatrix* &matrix);
// Return to the begining of the data buffer.
virtual void GoToHead();
// Normalize
virtual void Normalize(real_t max, real_t min);
protected:
DMatrix data_buf_; // Data buffer
int pos_; // Position for samplling
std::vector<index_t> sampled_length;
//std::vector<index_t> order_; // Used in shuffle
private:
// Counting the '\n' character
int GetLineNumber(const char* buf, uint64 buf_size);
// Read every line from memory buffer
uint32 ReadLineFromMemory(char* line,
char* buf,
uint64 start_pos,
uint64 total_len);
DISALLOW_COPY_AND_ASSIGN(InmemReader);
};
//------------------------------------------------------------------------------
// Samplling data from disk file.
//------------------------------------------------------------------------------
/*class OndiskReader : public Reader {
public:
OndiskReader() { }
~OndiskReader();
virtual void Initialize(const std::string& filename,
int num_samples,
Parser* parser,
ModelType type = LR);
// Sample data from disk file.
virtual int Samples(DMatrix* &matrix);
// Return to the begining of the file.
virtual void GoToHead();
private:
DISALLOW_COPY_AND_ASSIGN(OndiskReader);
};*/
//------------------------------------------------------------------------------
// Class register
//------------------------------------------------------------------------------
CLASS_REGISTER_DEFINE_REGISTRY(f2m_reader_registry, Reader);
#define REGISTER_READER(format_name, reader_name) \
CLASS_REGISTER_OBJECT_CREATOR( \
f2m_reader_registry, \
Reader, \
format_name, \
reader_name)
#define CREATE_READER(format_name) \
CLASS_REGISTER_CREATE_OBJECT( \
f2m_reader_registry, \
format_name)
} // namespace f2m
#endif // F2M_READER_READER_H_
|
// HistorySetMaxlen sets the maximum length for the history.
// Truncate the current history if needed.
func (l *Linenoise) HistorySetMaxlen(n int) {
if n < 0 {
return
}
l.historyMaxlen = n
currentLength := len(l.history)
if currentLength > l.historyMaxlen {
l.history = l.history[currentLength-l.historyMaxlen:]
}
} |
The Reagan Revolution: That works until the 1980s. Then our debt dynamics changed.
What happens to change it? In 1980 we elect Ronald Reagan, the first of our non-depression peacetime deficit presidents.
When Reagan was governor of California from 1966 to 1974, he was very much a balanced budget governor: he thought it important that the government not overspend, that it not run big deficits. He believed in investment in the future, yes—funding the University of California and building infrastructure—but not in large-scale deficit spending.
As soon, however, as Reagan gets elected president he pushes for massive peacetime deficits, and the debt-to-GDP ratio rises quite rapidly during his terms and during his successor George H.W. Bush’s term. Then Bill Clinton gets elected in 1992. Clinton reverses course: he raises taxes and puts ceilings on spending growth. The debt-to-GDP ratio resumes its normal peacetime downward trajectory.
Then we elect—well, Justices Scalia, Rehnquist, Thomas, O’Conner, and Kennedy elect—George W. Bush. His vice president Richard Cheney believes that “Ronald Reagan showed that deficits don’t matter.” Lo and behold, the deficits starts up again and the debt-to-GDP ration rises. Then the financial crisis hits. We react as we usually do in a big downturn: spending money—albeit not enough money—to and keep the economy on an even keel.
Now the Obama administration and the Republican majority congress have cut the deficit substantially. They have done so even though, in my judgment, we are still far away from being out of our “depression economics” situation in which a bigger deficit is a positive good as a demand stimulus.
But suppose we eventually do get out of our current Lesser Depression, and reattain normal times in which it is sensible that the debt-to-GDP ratio be on a downward trajectory. When will that happen? And how are we then going to put the debt-to-GDP ratio on its normal peacetime non-depression downward trajectory?
As I look at the complexion of politics in Washington, putting the debt-to-GDP ratio on its normal downward trajectory appears a difficult task. Things have definitely changed. And that is scary.
There are two theories to why things appear to have changed around 1980—why our political system no longer generates the small government deficits and the downward debt-to-GDP trajectory that it used to.
The first theory is ideological: that something has gone very wrong with the minds of the Republican Party’s officeholders, apparatchiks, and their tame intellectuals.
From the end of the Civil War all the way up to 1980 the Republican Party tended to be a small-government balanced-budget party: its consensus was that the first priority was to balance the budget, and that if the budget was balanced the next priority was to cut spending. Since 1980 the Republican Party has been a large-government unbalanced-budget party: its first priority is to cut taxes, its second priority is to raise spending on national defense and spending and tax expenditures on programs of interest to lobbyists who fund Republican campaigns, and balancing the budget is a distant third priority—if it is there at all.
The second theory is structural: that we have changed the character of government spending.
It used to be that most of U.S. federal government spending was done through the appropriations process—spending that had to be decided upon and revoted year after year. The U.S. federal government spent on defense, on national parks, on building dams and ports, on building interstate highways, building canals. But that is not what the U.S. government spends on today: today the U.S. government spends on Medicare, Medicaid, and Social Security. Spending on those programs as a share of GDP goes up automatically as the population ages and as doctors and pharmacists become more inventive about how to treat people with diseases.
Projected Spending and Revenues as Percent of GDP for CBO’s Extended-Baseline Scenario
Health Care Spending and the Long-Term Budget Outlook: This particular chart here is by the Congressional Budget Office, an organization now directed by my friend Douglas Elmendorf. This is his take on the Long-Term Budget Outlook for the U.S. federal government’s spending and revenue—his guess of what will happen if Congress and the President more-or-less stick to current law, and to the extent that they do not keep additional spending and additional revenues in rough balance.
Now I think there is one big thing wrong with this graph and the calculations underlying it. Given current tax law, I see no way that payroll taxes as a share of GDP are going to flatline. The way I see it, as the excise tax levied on insurance companies that provide expensive employer-sponsored health insurance policies begins to bite in the 2020s and thereafter, employer-sponsored health benefits will become slimmer, money that employers would have paid to their insurance companies will be paid to workers instead, and that money will become part of the payroll tax base and so payroll taxes will rise. Unless I am missing something, the CBO is somewhat overstating what current law produces as far as the gap between federal spending and federal revenues are.
But it is only overstating it somewhat: the gap is there.
In this projection the U.S. government goes into and remains in increasingly-enormous deficit and the national debt as a share of annual GDP explodes. First, the government’s spending on health-care programs busts the budget as our doctors, hospitals, and pharmaceutical companies discover how to do more expensive things to keep us healthy and alive, and the government picks up the tab for many of them. Why? Because we think, at a deep level, that health care should go to all the sick and not just to the rich sick. Second, the interest on the debt piled up to finance past deficits further burdens the future.
The federal health spending programs: Medicare, Medicaid, the Children’s Health Insurance Program, the “exchange subsidies” part of our currently-being-implemented RomneyCare—oops, ObamaCare—system by which people are required to have or buy health insurance on but this requirement is eased by providing poor people with subsidies to make buying private insurance affordable.
The amount of money that these health care programs will cost is, if things continue as they have been, scheduled to grow from a total of 5.5% of GDP today to something like 8% of GDP in 2040 to 14% of GDP by 2090. These spending programs are on the books. The United States government has said that it will pay for them. For spending to grow less rapidly would require that congress vote, and the president sign, big changes in what categories of health spending the federal government will pay for. At the moment the federal government will pay for what your doctors and nurses say is medically appropriate. And Doug Elmendorf says that if he has learned anything from being a health economist over the past 30 years, it is that doctors are very good at figuring out new and expensive things to do that are “medically appropriate”.
And many of expensive things really are medically appropriate. Our revolutions in medicine and public health have doubled lifespan over the life of this country. And many of these things are expensive. Neither political party wants to make controlling the rate of growth of healthcare spending—changing the law so that Medicare will no longer pay for a kidney transplant for your grandma—its signature issue. The big Republican talking point year-after-year is that the Democratic Party’s promises to streamline Medicare to make it more efficient are really plans for huge Medicare cuts that mean that someday your grandma or you will have to go in front of a government “death panel” that will turn their thumbs down. We, the Republicans are saying, are going to repeal all of the Medicare cuts and the tax increases in the recently-passed ObamaCare—but we are going to keep all of the parts of ObamaCare that actually cost money. The big Democratic Party talking point is that the government will make health care affordable for everyone. |
#include <stdio.h>
int main()
{
int n,m,a,mxh,mih,yoko[1001][3];
int i,t,e;
for(scanf("%d%d%d",&n,&m,&a); n || m || a;scanf("%d%d%d",&n,&m,&a))
{
mxh=0,mih=1000;
for(i=1;i<=m;i++)
{
scanf("%d%d%d",&yoko[i][0],&yoko[i][1],&yoko[i][2]);
if(yoko[i][0]>mxh)mxh=yoko[i][0];
if(yoko[i][0]<mih)mih=yoko[i][0];
}
for(t=mxh;t>=mih;t--)
for(i=1;i<=m;i++)
{if(t==yoko[i][0] && (a==yoko[i][1] || a==yoko[i][2]))
a=a==yoko[i][1]?yoko[i][2]:yoko[i][1];}
printf("%d\n",a);
}
return 0;
}
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
module Luna.Prim.DynamicLinker (
loadLibrary
, loadSymbol
, closeLibrary
, Handle
) where
import Prologue hiding (throwM)
import qualified Data.EitherR as EitherR
import qualified Data.List as List
import qualified Data.Text as Text
import qualified Luna.Datafile.Stdlib as Stdlib
import qualified Luna.Package as Package
import qualified Luna.Path.Path as Path
import qualified Safe as Safe
import qualified Path as Path
import qualified Path.IO as Path
import qualified System.Environment as Env
import qualified System.FilePath as FP
import qualified System.Info as Info (os)
import qualified System.Process as Process
import Control.Exception.Safe (catchAny, throwM, tryAny)
import Control.Monad.Except (ExceptT(..), runExceptT)
import Data.Char (isSpace)
import Data.Maybe (maybeToList)
import Foreign (FunPtr)
import System.IO.Unsafe (unsafePerformIO)
import Path (Path, Abs, Rel, Dir, File, (</>))
#if mingw32_HOST_OS
import qualified System.Win32.DLL as Win32
import qualified System.Win32.Info as Win32
import qualified System.Win32.Types as Win32 (HINSTANCE)
import Foreign (nullPtr, castPtrToFunPtr)
#else
import qualified System.Posix.DynamicLinker as Unix
#endif
--------------------
-- === Handle === --
--------------------
#if mingw32_HOST_OS
type Handle = Win32.HINSTANCE
#else
type Handle = Unix.DL
#endif
-----------------
-- === API === --
-----------------
nativeLibs :: Path Rel Dir
nativeLibs = $(Path.mkRelDir "native_libs")
data NativeLibraryLoadingException =
NativeLibraryLoadingException String [String] deriving Show
instance Exception NativeLibraryLoadingException where
displayException (NativeLibraryLoadingException name details) =
"Native library " <> name <> " could not be loaded. Details:\n\n"
<> unlines details
findLocalNativeLibsDirs :: Path Abs Dir -> IO [Path Abs Dir]
findLocalNativeLibsDirs projectDir = do
let localDepsDir = projectDir </> $(Path.mkRelDir "local_libs")
localDeps <- tryAny $ Path.listDir localDepsDir
case localDeps of
Left _ -> pure []
Right (dirs, _) -> do
localNativeDirs <- for dirs $ \dir ->
findLocalNativeLibsDirs dir
pure $ fmap (\a -> a </> nativeLibs) dirs
<> concat localNativeDirs
findNativeLibsDirsForProject :: Path Abs Dir -> IO [Path Abs Dir]
findNativeLibsDirsForProject projectDir = do
let projectNativeDirs = projectDir </> nativeLibs
projectLocalDirs <- findLocalNativeLibsDirs projectDir
pure $ projectNativeDirs : projectLocalDirs
tryLoad :: Path Abs File -> IO (Either String Handle)
tryLoad path = do
loadRes <- tryAny $ nativeLoadLibrary path
let errorDetails exc =
"loading \"" <> (Path.fromAbsFile path) <> "\" failed with: "
<> displayException exc
pure $ EitherR.fmapL errorDetails loadRes
parseError :: [String] -> [String]
parseError e = if ((length $ snd partitioned) == 0) then
fst partitioned
else snd partitioned where
partitioned =
List.partition (List.isSuffixOf "No such file or directory)") e
loadLibrary :: String -> IO Handle
loadLibrary namePattern = do
stdlibPath <- Stdlib.findPath
projectDir <- Path.getCurrentDir
includedLibs <- map snd <$> Package.includedLibs stdlibPath
nativeDirs <- fmap concat $
mapM findNativeLibsDirsForProject (projectDir : includedLibs)
possibleNames <- mapM Path.parseRelFile
[ prefix <> namePattern <> extension
| prefix <- ["lib", ""]
, extension <- dynamicLibraryExtensions
]
let projectNativeDirectories =
[ nativeDir </> nativeLibraryProjectDir | nativeDir <- nativeDirs ]
let possiblePaths = [ dir </> name | dir <- projectNativeDirectories
, name <- possibleNames
]
let library = concat $
[ "lib" | not ("lib" `List.isPrefixOf` namePattern),
Info.os /= "mingw32"
]
<> [ namePattern ]
<> [ extension | extension <- dynamicLibraryExtensions,
not (null extension)
]
linkerCache <- maybeToList <$> nativeLoadFromCache library `catchAny`
const (pure Nothing)
extendedSearchPaths <- fmap concat . for nativeSearchPaths $ \path -> do
files <- (Path.listDir path >>= (pure . snd)) `catchAny` \_ -> pure []
let matchingFiles = filter
(Path.liftPredicate $ List.isInfixOf library) files
pure $ matchingFiles
result <- runExceptT . EitherR.runExceptRT $ do
let allPaths = possiblePaths <> linkerCache <> extendedSearchPaths
for allPaths $ \path ->
EitherR.ExceptRT . ExceptT $ tryLoad path
case result of
Left e -> throwM $ NativeLibraryLoadingException namePattern err where
err = parseError e
Right h -> pure h
loadSymbol :: Handle -> String -> IO (FunPtr a)
loadSymbol handle symbol = do
result <- tryAny $ nativeLoadSymbol handle symbol
case result of
Left e -> throwM $ NativeLibraryLoadingException symbol
[displayException e]
Right h -> pure h
closeLibrary :: Handle -> IO ()
closeLibrary _ = pure ()
#if mingw32_HOST_OS
nativeLoadLibrary :: Path Abs File -> IO Handle
nativeLoadLibrary library = Win32.loadLibraryEx
(Path.fromAbsFile library) Foreign.nullPtr
Win32.lOAD_WITH_ALTERED_SEARCH_PATH
nativeLoadSymbol :: Handle -> String -> IO (FunPtr a)
nativeLoadSymbol handle symbol = Foreign.castPtrToFunPtr
<$> Win32.getProcAddress handle symbol
dynamicLibraryExtensions :: [String]
dynamicLibraryExtensions = ["", ".dll"]
nativeLibraryProjectDir :: Path Rel Dir
nativeLibraryProjectDir = $(Path.mkRelDir "windows")
-- based on https://msdn.microsoft.com/en-us/library/windows/desktop/ms682586(v=vs.85).aspx
nativeSearchPaths :: [Path Abs Dir]
nativeSearchPaths = unsafePerformIO $ do
exeDirectory <- do
handle <- Win32.getModuleHandle Nothing
exe <- Win32.getModuleFileName handle >>= Path.parseAbsFile
pure $ Path.parent exe
systemDirectory <- Win32.getSystemDirectory >>= Path.parseAbsDir
windowsDirectory <- Win32.getWindowsDirectory >>= Path.parseAbsDir
currentDirectory <- Win32.getCurrentDirectory >>= Path.parseAbsDir
pathDirectories <- FP.getSearchPath >>= (mapM Path.parseAbsDir)
pure $ exeDirectory
: systemDirectory
: windowsDirectory
: currentDirectory
: pathDirectories
nativeLoadFromCache :: String -> IO (Maybe (Path Abs File))
nativeLoadFromCache _ = return Nothing
#else
-- TODO [JCM] : proposal : an invalid path throws an exception
lookupSearchPath :: String -> IO [Path Abs Dir]
lookupSearchPath env = do
val <- Env.lookupEnv env
case val of
Just envValue -> mapM Path.parseAbsDir $ FP.splitSearchPath envValue
Nothing -> pure []
nativeLoadLibrary :: Path Abs File -> IO Handle
nativeLoadLibrary library = Unix.dlopen
(Path.fromAbsFile library) [Unix.RTLD_NOW]
nativeLoadSymbol :: Handle -> String -> IO (FunPtr a)
nativeLoadSymbol = Unix.dlsym
dynamicLibraryExtensions :: [String]
nativeLibraryProjectDir :: Path Rel Dir
#if linux_HOST_OS
dynamicLibraryExtensions = [".so", ""]
nativeLibraryProjectDir = $(Path.mkRelDir "linux")
nativeSearchPaths :: [Path Abs Dir]
nativeSearchPaths = unsafePerformIO $ do
ldLibraryPathDirectories <- lookupSearchPath "LD_LIBRARY_PATH"
pure $ ldLibraryPathDirectories <>
[ $(Path.mkAbsDir "/lib")
, $(Path.mkAbsDir "/usr/lib")
, $(Path.mkAbsDir "/lib64")
, $(Path.mkAbsDir "/usr/lib64")
]
findBestSOFile :: String -> String -> Maybe (Path Abs File)
findBestSOFile (Text.pack -> namePattern) (Text.pack -> ldconfig) = do
let matchingLines = filter (Text.isInfixOf namePattern)
$ Text.lines ldconfig
chunks = map (Text.splitOn " => ") matchingLines
processSoFile = Text.takeWhile (not . isSpace) . Text.strip
extractFileAndPath line = case line of
[soFile, path] -> (processSoFile soFile, path)
_ -> error "Luna.Prim.DynamicLinker: ldconfig format"
matchingFiles = map extractFileAndPath chunks
bestMatches = List.sortOn (Text.length . fst) matchingFiles
bestMatch = Safe.headMay bestMatches
bestPath = fmap (Text.unpack . snd) bestMatch
bestPath >>= Path.parseAbsFile
-- uses /etc/ld.so.cache
nativeLoadFromCache :: String -> IO (Maybe (Path Abs File))
nativeLoadFromCache namePattern = do
ldconfigCache <- Process.readProcess "ldconfig" ["-p"] ""
pure $ findBestSOFile namePattern ldconfigCache
#elif darwin_HOST_OS
dynamicLibraryExtensions = [".dylib", ""]
nativeLibraryProjectDir = $(Path.mkRelDir "macos")
-- based on https://developer.apple.com/library/content/documentation/DeveloperTools/Conceptual/DynamicLibraries/100-Articles/UsingDynamicLibraries.html
nativeSearchPaths :: [Path Abs Dir]
nativeSearchPaths = unsafePerformIO $ do
ldLibraryPathDirectories <- lookupSearchPath "LD_LIBRARY_PATH"
dyLibraryPathDirectories <- lookupSearchPath "DYLD_LIBRARY_PATH"
currentDirectory <- Path.getCurrentDir
fallbackPathDirectories <- do
fallback <- Env.lookupEnv "DYLD_FALLBACK_LIBRARY_PATH"
case fallback of
Just val -> mapM Path.parseAbsDir $ FP.splitSearchPath val
_ -> do
home <- Env.getEnv "HOME"
pathPrefix <- Path.parseAbsDir home
pure $ (pathPrefix </> $(Path.mkRelDir "lib"))
: $(Path.mkAbsDir "/usr/local/lib")
: $(Path.mkAbsDir "/usr/lib")
: []
pure $ ldLibraryPathDirectories
<> dyLibraryPathDirectories
<> [currentDirectory]
<> fallbackPathDirectories
nativeLoadFromCache :: String -> IO (Maybe (Path Abs File))
nativeLoadFromCache _ = pure Nothing
#endif
#endif
|
<reponame>itsvinayak/cracking_the_codeing_interview
# Write a method to replace all spaces in a string with '%20'. You may assume that the string
# has sufficient space at the end to hold the additional characters, and that you are given the "true"
# length of the string. (Note: If implementing in Java, please use a character array so that you can
# perform this operation in place.)
# Maximum length of string after modifications.
MAX = 1000
# Replaces spaces with %20 in-place and returns
# new length of modified string. It returns -1
# if modified string cannot be stored in str[]
def replaceSpaces(string):
# Remove remove leading and trailing spaces
string = string.strip()
i = len(string)
# count spaces and find current length
space_count = string.count(" ")
# Find new length.
new_length = i + space_count * 2
# New length must be smaller than length
# of string provided.
if new_length > MAX:
return -1
# Start filling character from end
index = new_length - 1
string = list(string)
# Fill string array
for f in range(i - 2, new_length - 2):
string.append("0")
# Fill rest of the string from end
for j in range(i - 1, 0, -1):
# inserts %20 in place of space
if string[j] == " ":
string[index] = "0"
string[index - 1] = "2"
string[index - 2] = "%"
index = index - 3
else:
string[index] = string[j]
index -= 1
return "".join(string)
if __name__ == "__main__":
print(replaceSpaces(input()))
#########################################
# using replace keyword
# python way
# print(input().replace(' ',"%20"))
|
<filename>daemon/src/scope.rs<gh_stars>0
use futures_core::future::{Future, BoxFuture};
use futures_util::future::FutureExt;
use futures_util::stream::{Stream, FuturesUnordered};
use pin_project::{pin_project, pinned_drop};
use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::task::JoinHandle;
/// A scope to allow controlled spawning of non 'static
/// futures. Futures can be spawned using `spawn` or
/// `spawn_cancellable` methods.
///
/// # Safety
///
/// This type uses `Drop` implementation to guarantee
/// safety. It is not safe to forget this object unless it
/// is driven to completion.
#[pin_project(PinnedDrop)]
pub struct Scope<'a, T> {
done: bool,
len: usize,
remaining: usize,
#[pin]
futs: FuturesUnordered<JoinHandle<T>>,
// Future proof against variance changes
_marker: PhantomData<&'a mut &'a ()>,
}
impl<'a, T: Send + 'static> Scope<'a, T> {
/// Create a Scope object.
///
/// This function is unsafe as `futs` may hold futures
/// which have to be manually driven to completion.
pub unsafe fn create() -> Self {
Scope {
done: false,
len: 0,
remaining: 0,
futs: FuturesUnordered::new(),
_marker: PhantomData,
}
}
/// Spawn a future with `async_std::task::spawn`. The
/// future is expected to be driven to completion before
/// 'a expires.
pub fn spawn<F: Future<Output = T> + Send + 'a>(
&mut self,
f: F,
) {
let handle =
tokio::spawn(unsafe { std::mem::transmute::<_, BoxFuture<'static, T>>(f.boxed()) });
self.futs.push(handle);
self.len += 1;
self.remaining += 1;
}
}
impl<'a, T> Scope<'a, T> {
/// Total number of futures spawned in this scope.
#[inline]
#[allow(dead_code)]
pub fn len(&self) -> usize {
self.len
}
/// Number of futures remaining in this scope.
#[inline]
#[allow(dead_code)]
pub fn remaining(&self) -> usize {
self.remaining
}
/// A slighly optimized `collect` on the stream. Also
/// useful when we can not move out of self.
pub async fn collect(&mut self) -> Vec<T> {
let mut proc_outputs = Vec::with_capacity(self.remaining);
use futures_util::stream::StreamExt;
while let Some(item) = self.next().await {
proc_outputs.push(item);
}
proc_outputs
}
}
impl<'a, T> Stream for Scope<'a, T> {
type Item = T;
fn poll_next(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
let this = self.project();
let poll = this.futs.poll_next(cx);
if let Poll::Ready(None) = poll {
*this.done = true;
} else if poll.is_ready() {
*this.remaining -= 1;
}
poll.map(|t| t.map(|t| t.expect("task not driven to completion")))
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.remaining, Some(self.remaining))
}
}
#[pinned_drop]
impl<'a, T> PinnedDrop for Scope<'a, T> {
fn drop(mut self: Pin<&mut Self>) {
if !self.done {
futures_executor::block_on(async {
// self.cancel().await;
self.collect().await;
});
}
}
}
/// Creates a `Scope` to spawn non-'static futures. The
/// function is called with a block which takes an `&mut
/// Scope`. The `spawn` method on this arg. can be used to
/// spawn "local" futures.
///
/// # Returns
///
/// The function returns the created `Scope`, and the return
/// value of the block passed to it. The returned stream and
/// is expected to be driven completely before being
/// forgotten. Dropping this stream causes the stream to be
/// driven _while blocking the current thread_. The values
/// returned from the stream are the output of the futures
/// spawned.
///
/// # Safety
///
/// The returned stream is expected to be run to completion
/// before being forgotten. Dropping it is okay, but blocks
/// the current thread until all spawned futures complete.
pub unsafe fn scope<'a, T: Send + 'static, R, F: FnOnce(&mut Scope<'a, T>) -> R>(
f: F
) -> (Scope<'a, T>, R) {
let mut scope = Scope::create();
let op = f(&mut scope);
(scope, op)
}
/// A function that creates a scope and immediately awaits,
/// _blocking the current thread_ for spawned futures to
/// complete. The outputs of the futures are collected as a
/// `Vec` and returned along with the output of the block.
///
/// # Safety
///
/// This function is safe to the best of our understanding
/// as it blocks the current thread until the stream is
/// driven to completion, implying that all the spawned
/// futures have completed too. However, care must be taken
/// to ensure a recursive usage of this function doesn't
/// lead to deadlocks.
///
/// When scope is used recursively, you may also use the
/// unsafe `scope_and_*` functions as long as this function
/// is used at the top level. In this case, either the
/// recursively spawned should have the same lifetime as the
/// top-level scope, or there should not be any spurious
/// future cancellations within the top level scope.
#[allow(dead_code)]
pub fn scope_and_block<'a, T: Send + 'static, R, F: FnOnce(&mut Scope<'a, T>) -> R>(
f: F
) -> (R, Vec<T>) {
let (mut stream, block_output) = unsafe { scope(f) };
let proc_outputs = futures_executor::block_on(stream.collect());
(block_output, proc_outputs)
}
/// An asynchronous function that creates a scope and
/// immediately awaits the stream. The outputs of the
/// futures are collected as a `Vec` and returned along with
/// the output of the block.
///
/// # Safety
///
/// This function is _not completely safe_: please see
/// `cancellation_soundness` in [tests.rs][tests-src] for a
/// test-case that suggests how this can lead to invalid
/// memory access if not dealt with care.
///
/// The caller must ensure that the lifetime 'a is valid
/// until the returned future is fully driven. Dropping the
/// future is okay, but blocks the current thread until all
/// spawned futures complete.
///
/// [tests-src]: https://github.com/rmanoka/async-scoped/blob/master/src/tests.rs
#[allow(dead_code)]
pub async unsafe fn scope_and_collect<
'a,
T: Send + 'static,
R,
F: FnOnce(&mut Scope<'a, T>) -> R,
>(
f: F
) -> (R, Vec<T>) {
let (mut stream, block_output) = scope(f);
let proc_outputs = stream.collect().await;
(block_output, proc_outputs)
}
|
// CreateLoadBalancer creates loadbalancer by conf.
func (a *ALBClient) CreateLoadBalancer(albConf *ALB) (*ALB, error) {
var alb ALBArr
alb.Loadbalancer = *albConf
url := generateELBRoutePrefix(a.enableEPS, a.albClient.TenantId) + "/loadbalancers"
req := NewRequest(http.MethodPost, url, nil, &alb)
resp, err := DoRequest(a.albClient, a.throttler.GetThrottleByKey(ELB_INSTANCE_CREATE), req)
if err != nil {
return nil, err
}
var albResp ALBArr
err = DecodeBody(resp, &albResp)
if err != nil {
return nil, fmt.Errorf("Failed to CreateLoadalancer : %v", err)
}
return &(albResp.Loadbalancer), nil
} |
<filename>src/common/components/multiSelectCombobox/MultiSelectCombobox.tsx
import { useTranslation } from "next-i18next";
import { MultiSelectProps } from "hds-react";
import { Option } from "../../../types";
import Combobox from "../combobox/Combobox";
type Props = Omit<
MultiSelectProps<Option>,
| "value"
| "onChange"
| "toggleButtonAriaLabel"
| "selectedItemRemoveButtonAriaLabel"
| "clearButtonAriaLabel"
| "multiselect"
> & {
onChange: (values: string[]) => void;
id?: string;
name?: string;
value?: string[];
};
export default function MultiSelectCombobox({
onChange,
value = [],
...delegated
}: Props) {
const { t } = useTranslation("multi_select_combobox");
const handleOnChange = (options: Option[]) => {
const values = options.map((option) => option?.value);
onChange(values);
};
// Allows partial matches, e.g. töölö matches Etu-Töölö
const filterLogic = (options: Option[], search: string) => {
return options.filter((option) =>
option.label.toLowerCase().includes(search.toLowerCase())
);
};
const hydratedValues = delegated.options.filter((option) =>
value.includes(option.value)
);
return (
<Combobox
{...delegated}
multiselect
value={hydratedValues}
onChange={handleOnChange}
// The design asks for an icon, but HDS does not allow icons for the
// multiSelect variant of an combobox.
// icon={<IconLocation aria-hidden="true" />}
// The options list will break without this option because the data has
// duplicate labels.
virtualized
toggleButtonAriaLabel={t("toggle_button_aria_label")}
selectedItemRemoveButtonAriaLabel={t(
"selected_item_remove_button_aria_label"
)}
clearButtonAriaLabel={t("clear_button_aria_label")}
filter={filterLogic}
/>
);
}
|
class ProcessContextOptions:
"""
Used to store process context data.
Parameter Fields
----------------
request: Request
The request that is the cause of the process loop.
log: An acquisition log object
The acquisition log model object related to this submission.
Attribute Fields
results:
Mapping of package => class => agency => object => version =>
Submission
result:
The current result object
action: str
The default action to take on processing the artefacts
external_dependencies: str
The default external_dependencies when processing the artefacts
dsd: DataStructureSerializer
The DataStructureSerializer instance set when processing an
AttachmentConstraintSerializer
----------------
"""
request: Request
acquisition_obj: object
results: defaultdict = field(init=False, default_factory=default_results)
result: object = field(init=False)
action: str = field(init=False)
external_dependencies: bool = field(init=False)
dsd: object = field(init=False)
def get_or_add_result(self, submitted_structure):
r = self.results
ref = submitted_structure.maintainable_object.dref
try:
return r[ref.package][ref.cls][ref.agency_id][ref.object_id][ref.version]
except KeyError:
r[ref.package][ref.cls][ref.agency][
ref.object_id][ref.version] = submitted_structure
return submitted_structure
def generate_result(self):
for package, vp in self.results.items():
for cls, vc in vp.items():
for agency, va in vc.items():
for object_id, vo in va.items():
for version, result in vo.items():
yield result |
<filename>Baekjoon/Cpp/14648.cpp
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
ll arr[1001];
ll sm(ll s, ll e) {
ll su = 0;
for (ll i = s; i <= e; i++) {
su += arr[i];
}
return su;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
ll n, q, i, k, a, b, c, d, s;
cin >> n >> q;
for (i = 1; i <= n; i++) {
cin >> arr[i];
}
for (i = 0; i < q; i++) {
cin >> k >> a >> b;
s = sm(a, b);
if (k == 1) {
arr[a] ^= arr[b] ^= arr[a] ^= arr[b];
} else {
cin >> c >> d;
s -= sm(c, d);
}
cout << s << "\n";
}
return 0;
}
|
/*
SoftSerialParallelWrite.cpp - Library for parallel serial communication SoftSerialParallelWrite code.
Created by <NAME>, 2018.
Inspired by https://www.arduino.cc/en/Reference/SoftwareSerial
*/
// When set, _DEBUG co-opts pins 12 and 13 for debugging with an
// oscilloscope or logic analyzer. Beware: it also slightly modifies
// the bit times, so don't rely on it too much at high baud rates
#define _DEBUG 0
#define _DEBUG_PIN1 B010000
#define _DEBUG_PIN2 B100000
#include <Arduino.h>
#include <SoftSerialParallelWrite.h>
//
// Debugging
//
// This function generates a brief pulse
// for debugging or measuring on an oscilloscope.
#if _DEBUG
inline void DebugPulse(uint8_t pin, uint16_t count)
{
if (!( DDRB & pin ))
DDRB |= pin;
while (count--)
{
PORTB ^= pin;
if ((count & B1111) == B1111)
_delay_loop_2(2);
PORTB ^= pin;
}
}
#else
inline void DebugPulse(uint8_t, uint16_t) {}
#endif
// This functions is returns 3 and 4
void SoftSerialParallelWrite::delayCalc(uint16_t i) {
uint16_t x = 0, threes = 1, fours = 1;
if (i >= 7) {
i -= 7; //one cycles for both 3 and 4 is mandatory
} else {
i = 0;
}
// this logic is make sure we keep the accuracy above 6
if (i >= 6) {
x = i - 6;
fours += (x / 12) * 3;
x = (x % 12) + 6;
} else {
x = i;
}
switch (x) {
case 2:
++ threes;
break;
case 5:
threes += 2;
break;
case 4:
case 8:
case 12:
case 16:
case 20:
fours += x / 4;
break;
case 3:
case 6:
case 9:
case 15:
case 18:
threes += x / 3;
break;
case 7:
++ threes; ++fours;
break;
case 10:
threes += 2; ++fours;
break;
case 11:
++threes; fours += 2;
break;
case 13:
threes += 3; ++fours;
break;
case 14:
threes += 2; fours += 2;
break;
case 17:
threes += 3; fours += 2;
break;
case 19:
threes += 5; fours += 2;
break;
}
_tx_delay3 = threes;
_tx_delay4 = fours;
}
SoftSerialParallelWrite::SoftSerialParallelWrite(uint8_t pins) {
// calculate register, pin and port prefix masks
_reg = B00000000;
_pins = _MAX_PINS;
if (pins < _MAX_PINS)
_pins = pins;
for (uint8_t i = 0; i < _pins; ++i) {
_reg |= (1<<i);
}
DDRB |= _reg; // set up registers for output
}
void SoftSerialParallelWrite::begin(long speed, uint8_t frameSize) {
_frameSize = frameSize; // number of bits in one frame included start, data, parity and stop
// Pre-calculate the various delays, in number of 4-cycle and 3-cycle of delays
float tx_delay_map[6] = {32, 37, 44, 48, 54, 58}; // numbers of cycles required for a write loop
float cycles = (F_CPU / speed) - (tx_delay_map[_pins - 1]);
if (cycles < 0)
cycles = 0;
delayCalc( (int) cycles );
DebugPulse(_DEBUG_PIN2, (int) cycles);
DebugPulse(_DEBUG_PIN1, _tx_delay3);
DebugPulse(_DEBUG_PIN2, _tx_delay4);
// speed tweak. to save as many operation as possible in write loops
for (uint8_t i = 0; i < 16; ++i) {
_mask [i] = 1<<i;
}
PORTB |= _reg; // may not necessary since write(0x00, ..) would do the job;
}
bool SoftSerialParallelWrite::write(uint16_t d0) {
uint8_t newState; // holds current stat value and make possible one step register write operation
uint8_t i = 0;
uint8_t stop = _frameSize - 1;
uint8_t oldSREG = SREG;
_portPrefix = PORTB & ~_reg;
// turn off interrupts for a clean txmit
cli();
// do the actual transmission
for (; ; ++i) {
newState = _reg;
(d0 & _mask[i]) ? newState &= B111111 : newState &= B111110;
PORTB = _portPrefix | newState;
if (i == stop)
break; //delay does not happen after last bit
else
// delays happen all the time. and addition if condition would take longer than actual delay loop
_delay_loop_1(_tx_delay3);
_delay_loop_2(_tx_delay4);
}
SREG = oldSREG; // turn interrupts back on
}
bool SoftSerialParallelWrite::write(uint16_t d0, uint16_t d1) {
uint8_t newState;
uint8_t i = 0;
uint8_t stop = _frameSize - 1;
uint8_t oldSREG = SREG;
_portPrefix = PORTB & ~_reg;
cli();
for (; ; ++i) {
newState = _reg;
(d0 & _mask[i]) ? newState &= B111111 : newState &= B111110;
(d1 & _mask[i]) ? newState &= B111111 : newState &= B111101;
PORTB = _portPrefix | newState;
if (i == stop)
break;
else
_delay_loop_1(_tx_delay3);
_delay_loop_2(_tx_delay4);
}
SREG = oldSREG;
}
bool SoftSerialParallelWrite::write(uint16_t d0, uint16_t d1, uint16_t d2) {
uint8_t newState;
uint8_t i = 0;
uint8_t stop = _frameSize - 1;
uint8_t oldSREG = SREG;
_portPrefix = PORTB & ~_reg;
cli();
for (; ; ++i) {
newState = _reg;
(d0 & _mask[i]) ? newState &= B111111 : newState &= B111110;
(d1 & _mask[i]) ? newState &= B111111 : newState &= B111101;
(d2 & _mask[i]) ? newState &= B111111 : newState &= B111011;
PORTB = _portPrefix | newState;
if (i == stop)
break;
else
_delay_loop_1(_tx_delay3);
_delay_loop_2(_tx_delay4);
}
SREG = oldSREG;
}
bool SoftSerialParallelWrite::write(uint16_t d0, uint16_t d1, uint16_t d2, uint16_t d3) {
uint8_t newState;
uint8_t i = 0;
uint8_t stop = _frameSize - 1;
uint8_t oldSREG = SREG;
_portPrefix = PORTB & ~_reg;
cli();
for (; ; ++i) {
newState = _reg;
(d0 & _mask[i]) ? newState &= B111111 : newState &= B111110;
(d1 & _mask[i]) ? newState &= B111111 : newState &= B111101;
(d2 & _mask[i]) ? newState &= B111111 : newState &= B111011;
(d3 & _mask[i]) ? newState &= B111111 : newState &= B110111;
PORTB = _portPrefix | newState;
if (i == stop)
break;
else
_delay_loop_1(_tx_delay3);
_delay_loop_2(_tx_delay4);
}
SREG = oldSREG;
}
bool SoftSerialParallelWrite::write(uint16_t d0, uint16_t d1, uint16_t d2, uint16_t d3, uint16_t d4) {
uint8_t newState;
uint8_t i = 0;
uint8_t stop = _frameSize - 1;
uint8_t oldSREG = SREG;
_portPrefix = PORTB & ~_reg;
cli();
for (; ; ++i) {
newState = _reg;
(d0 & _mask[i]) ? newState &= B111111 : newState &= B111110;
(d1 & _mask[i]) ? newState &= B111111 : newState &= B111101;
(d2 & _mask[i]) ? newState &= B111111 : newState &= B111011;
(d3 & _mask[i]) ? newState &= B111111 : newState &= B110111;
(d4 & _mask[i]) ? newState &= B111111 : newState &= B101111;
PORTB = _portPrefix | newState;
if (i == stop)
break;
else
_delay_loop_1(_tx_delay3);
_delay_loop_2(_tx_delay4);
}
SREG = oldSREG;
}
bool SoftSerialParallelWrite::write(uint16_t d0, uint16_t d1, uint16_t d2, uint16_t d3, uint16_t d4, uint16_t d5) {
uint8_t newState;
uint8_t i = 0;
uint8_t stop = _frameSize - 1;
uint8_t oldSREG = SREG;
_portPrefix = PORTB & ~_reg;
cli();
for (; ; ++i) {
newState = _reg;
(d0 & _mask[i]) ? newState &= B111111 : newState &= B111110;
(d1 & _mask[i]) ? newState &= B111111 : newState &= B111101;
(d2 & _mask[i]) ? newState &= B111111 : newState &= B111011;
(d3 & _mask[i]) ? newState &= B111111 : newState &= B110111;
(d4 & _mask[i]) ? newState &= B111111 : newState &= B101111;
(d5 & _mask[i]) ? newState &= B111111 : newState &= B011111;
PORTB = _portPrefix | newState;
if (i == stop)
break;
else
_delay_loop_1(_tx_delay3);
_delay_loop_2(_tx_delay4);
}
SREG = oldSREG;
}
|
package com.hashmapinc.tempus.WitsmlObjects.v20;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* Location of the well by latitude and longitude.
*
* <p>Java class for GeodeticWellLocation complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="GeodeticWellLocation">
* <complexContent>
* <extension base="{http://www.energistics.org/energyml/data/witsmlv2}AbstractWellLocation">
* <sequence>
* <element name="Latitude" type="{http://www.energistics.org/energyml/data/commonv2}PlaneAngleMeasure"/>
* <element name="Longitude" type="{http://www.energistics.org/energyml/data/commonv2}PlaneAngleMeasure"/>
* <element name="Crs" type="{http://www.energistics.org/energyml/data/commonv2}AbstractGeodeticCrs"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "GeodeticWellLocation", namespace = "http://www.energistics.org/energyml/data/witsmlv2", propOrder = {
"latitude",
"longitude",
"crs"
})
public class GeodeticWellLocation
extends AbstractWellLocation
{
@XmlElement(name = "Latitude", required = true)
protected PlaneAngleMeasure latitude;
@XmlElement(name = "Longitude", required = true)
protected PlaneAngleMeasure longitude;
@XmlElement(name = "Crs", required = true)
protected AbstractGeodeticCrs crs;
/**
* Gets the value of the latitude property.
*
* @return
* possible object is
* {@link PlaneAngleMeasure }
*
*/
public PlaneAngleMeasure getLatitude() {
return latitude;
}
/**
* Sets the value of the latitude property.
*
* @param value
* allowed object is
* {@link PlaneAngleMeasure }
*
*/
public void setLatitude(PlaneAngleMeasure value) {
this.latitude = value;
}
/**
* Gets the value of the longitude property.
*
* @return
* possible object is
* {@link PlaneAngleMeasure }
*
*/
public PlaneAngleMeasure getLongitude() {
return longitude;
}
/**
* Sets the value of the longitude property.
*
* @param value
* allowed object is
* {@link PlaneAngleMeasure }
*
*/
public void setLongitude(PlaneAngleMeasure value) {
this.longitude = value;
}
/**
* Gets the value of the crs property.
*
* @return
* possible object is
* {@link AbstractGeodeticCrs }
*
*/
public AbstractGeodeticCrs getCrs() {
return crs;
}
/**
* Sets the value of the crs property.
*
* @param value
* allowed object is
* {@link AbstractGeodeticCrs }
*
*/
public void setCrs(AbstractGeodeticCrs value) {
this.crs = value;
}
}
|
// diffIDWithOpts compuates the digest of the Uncompressed layer content
func (rl *RawLayer) diffIDWithOpts(opts ...LayerOperationOption) (regv1.Hash, error) {
o := makeLayerOperationOpts(opts...)
hasher := sha256.New()
if o.Progress != nil {
desc, err := rl.Descriptor()
if err != nil {
return regv1.Hash{}, err
}
bar := o.Progress.NewBar(rl.volume.Name, "compute digest", int64(desc.Physical.Value))
hasher = &hashWithProgress{
Hash: hasher,
bar: bar,
}
}
err := rl.conn.StorageVolDownload(rl.volume, hasher, 0, 0, 0)
if err != nil {
return regv1.Hash{}, fmt.Errorf("failed to read volume '%s': %w", rl.volume.Name, err)
}
sum := hasher.Sum(nil)
return regv1.Hash{Algorithm: "sha256", Hex: hex.EncodeToString(sum)}, nil
} |
Mutations in Host Cell Factor 1 Separate Its Role in Cell Proliferation from Recruitment of VP16 and LZIP
ABSTRACT Host cell factor 1 (HCF-1) is a nuclear protein required for progression through G1 phase of the cell cycle and, via its association with VP16, transcriptional activation of the herpes simplex virus immediate-early genes. Both functions require a six-bladed β-propeller domain encoded by residues 1 to 380 of HCF-1 as well as an additional amino-terminal region. The β-propeller domain is well conserved in HCF homologues, consistent with a critical cellular function. To date, the only known cellular target of the β-propeller is a bZIP transcription factor known as LZIP or Luman. Whether the interaction between HCF-1 and LZIP is required for cell proliferation remains to be determined. In this study, we used directed mutations to show that all six blades of the HCF-1 β-propeller contribute to VP16-induced complex assembly, association with LZIP, and cell cycle progression. Although LZIP and VP16 share a common tetrapeptide HCF-binding motif, our results reveal profound differences in their interaction with HCF-1. Importantly, with several of the mutants we observe a poor correlation between the ability to associate with LZIP and promote cell proliferation in the context of the full HCF-1 amino terminus, arguing that the HCF-1 β-propeller domain must target other cellular transcription factors in order to contribute to G1progression. |
/**
* Encapsulates an input request.
*
* @since Ant 1.5
*/
public class MultipleChoiceInputRequest extends InputRequest {
private final LinkedHashSet<String> choices;
/**
* @param prompt The prompt to show to the user. Must not be null.
* @param choices holds all input values that are allowed.
* Must not be null.
*/
public MultipleChoiceInputRequest(String prompt, Vector<String> choices) {
super(prompt);
if (choices == null) {
throw new IllegalArgumentException("choices must not be null");
}
this.choices = new LinkedHashSet<String>(choices);
}
/**
* @return The possible values.
*/
public Vector<String> getChoices() {
return new Vector<String>(choices);
}
/**
* @return true if the input is one of the allowed values.
*/
public boolean isInputValid() {
return choices.contains(getInput()) || ("".equals(getInput()) && getDefaultValue() != null);
}
} |
// ClearedFields returns all nullable fields that were cleared during this
// mutation.
func (m *ChunkMutation) ClearedFields() []string {
var fields []string
if m.FieldCleared(chunk.FieldLeaseExpiresAt) {
fields = append(fields, chunk.FieldLeaseExpiresAt)
}
if m.FieldCleared(chunk.FieldSizeInput) {
fields = append(fields, chunk.FieldSizeInput)
}
if m.FieldCleared(chunk.FieldSizeContent) {
fields = append(fields, chunk.FieldSizeContent)
}
if m.FieldCleared(chunk.FieldSizeOutput) {
fields = append(fields, chunk.FieldSizeOutput)
}
if m.FieldCleared(chunk.FieldSha256Input) {
fields = append(fields, chunk.FieldSha256Input)
}
if m.FieldCleared(chunk.FieldSha256Content) {
fields = append(fields, chunk.FieldSha256Content)
}
if m.FieldCleared(chunk.FieldSha256Output) {
fields = append(fields, chunk.FieldSha256Output)
}
return fields
} |
Open source software maintenance process framework
To identify the Open Source maintenance process two well known Open Source projects Apache HTTP server and Mozilla web browser were studied. The Open Source software maintenance process is formal even anyone can submit modifications or defect reports to Open Source software projects. We assume that the Open Source maintenance process is similar to the maintenance process defined by the ISO/IEC. In the case studies. four activities were found similar to the activities of the ISO/IEC Maintenance process. This paper presents the Open Source maintenance process framework. The framework is exemplified with the ISO/IEC Maintenance process framework. |
<filename>com.sabre.tn.redapp.example.workflow/web-src/com-sabre-tn-redapp-example-showcase-mod/src/code/views/cmdHelperForm/CmdHelperButton.ts
import {CssClass} from 'sabre-ngv-core/decorators/classes/view/CssClass';
import {Initial} from 'sabre-ngv-core/decorators/classes/Initial';
import AbstractBootstrapPopoverButton from 'sabre-ngv-UIComponents/commandHelperButton/components/AbstractBootstrapPopoverButton';
import {ChildComponentContent} from 'sabre-ngv-UIComponents/commandHelperButton/interfaces/ChildComponentContent';
import StatefulComponentWithSaga from "sabre-ngv-UIComponents/baseComponent/components/StatefulComponentWithSaga"
import {rootReducer} from './reducers';
import rootSaga from './sagas';
import {Form} from './Form';
@CssClass('com_sabre_tn_redapp_example_workflow btn btn-default')
@Initial<any>({
caption: '<i class="fa fa-search"></i> <span class="hidden-xs dn-x-hidden-0-8">DB Query</span>',
type: 'default'
})
export default class CmdHelperButton extends AbstractBootstrapPopoverButton {
private content = new StatefulComponentWithSaga(
{
componentName: 'SamplePopover',
rootReducer,
rootSaga,
rootReactComponent: Form,
parentEventBus: this.eventBus
}
);
protected getContent(): ChildComponentContent {
return (this.content as ChildComponentContent);
}
/**
* Initialize Button
*/
initialize(options: any): void {
super.initialize(options);
this.registerContentEvents();
}
/**
* An example event handler to demonstrate proper side effect handling in React layer.
*
* We implement here child(React) => parent(app) communication pattern
* with Redux-Saga middleware triggering an event on parent's event bus
* when given Redux Action gets dispatched.
*/
private registerContentEvents() {
this.eventBus.on('close-form', this.handleCloseEvent.bind(this));
}
private handleCloseEvent(): void {
this.content.unmount();
this.togglePopover();
this.content.dispose();
}
}
|
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
from ...asn1crypto.pem import unarmor
from ...asn1crypto.x509 import TrustedCertificate, Certificate
from .._errors import pretty_message
__all__ = [
'extract_from_system',
'system_path',
]
def system_path():
"""
Tries to find a CA certs bundle in common locations
:raises:
OSError - when no valid CA certs bundle was found on the filesystem
:return:
The full filesystem path to a CA certs bundle file
"""
ca_path = None
# Common CA cert paths
paths = [
'/usr/lib/ssl/certs/ca-certificates.crt',
'/etc/ssl/certs/ca-certificates.crt',
'/etc/ssl/certs/ca-bundle.crt',
'/etc/pki/tls/certs/ca-bundle.crt',
'/etc/ssl/ca-bundle.pem',
'/usr/local/share/certs/ca-root-nss.crt',
'/etc/ssl/cert.pem'
]
# First try SSL_CERT_FILE
if 'SSL_CERT_FILE' in os.environ:
paths.insert(0, os.environ['SSL_CERT_FILE'])
for path in paths:
if os.path.exists(path) and os.path.getsize(path) > 0:
ca_path = path
break
if not ca_path:
raise OSError(pretty_message(
'''
Unable to find a CA certs bundle in common locations - try
setting the SSL_CERT_FILE environmental variable
'''
))
return ca_path
def extract_from_system(cert_callback=None, callback_only_on_failure=False):
"""
Extracts trusted CA certs from the system CA cert bundle
:param cert_callback:
A callback that is called once for each certificate in the trust store.
It should accept two parameters: an asn1crypto.x509.Certificate object,
and a reason. The reason will be None if the certificate is being
exported, otherwise it will be a unicode string of the reason it won't.
:param callback_only_on_failure:
A boolean - if the callback should only be called when a certificate is
not exported.
:return:
A list of 3-element tuples:
- 0: a byte string of a DER-encoded certificate
- 1: a set of unicode strings that are OIDs of purposes to trust the
certificate for
- 2: a set of unicode strings that are OIDs of purposes to reject the
certificate for
"""
all_purposes = '2.5.29.37.0'
ca_path = system_path()
output = []
with open(ca_path, 'rb') as f:
for armor_type, _, cert_bytes in unarmor(f.read(), multiple=True):
# Without more info, a certificate is trusted for all purposes
if armor_type == 'CERTIFICATE':
if cert_callback:
cert_callback(Certificate.load(cert_bytes), None)
output.append((cert_bytes, set(), set()))
# The OpenSSL TRUSTED CERTIFICATE construct adds OIDs for trusted
# and rejected purposes, so we extract that info.
elif armor_type == 'TRUSTED CERTIFICATE':
cert, aux = TrustedCertificate.load(cert_bytes)
reject_all = False
trust_oids = set()
reject_oids = set()
for purpose in aux['trust']:
if purpose.dotted == all_purposes:
trust_oids = set([purpose.dotted])
break
trust_oids.add(purpose.dotted)
for purpose in aux['reject']:
if purpose.dotted == all_purposes:
reject_all = True
break
reject_oids.add(purpose.dotted)
if reject_all:
if cert_callback:
cert_callback(cert, 'explicitly distrusted')
continue
if cert_callback and not callback_only_on_failure:
cert_callback(cert, None)
output.append((cert.dump(), trust_oids, reject_oids))
return output
|
<reponame>vanadium/core
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package security
import (
"fmt"
"time"
"v.io/v23/naming"
"v.io/v23/vdl"
)
// NewCall creates a Call.
func NewCall(params *CallParams) Call {
ctx := &ctxImpl{*params}
if params.Timestamp.IsZero() {
ctx.params.Timestamp = time.Now()
}
return ctx
}
// CallParams is used to create Call objects using the NewCall
// function.
type CallParams struct {
Timestamp time.Time // Time at which the authorization is to be checked.
Method string // Method being invoked.
MethodTags []*vdl.Value // Method tags, typically specified in VDL.
Suffix string // Object suffix on which the method is being invoked.
LocalPrincipal Principal // Principal at the local end of a request.
LocalBlessings Blessings // Blessings presented to the remote end.
LocalEndpoint naming.Endpoint // Endpoint of local end of communication.
RemoteBlessings Blessings // Blessings presented by the remote end.
RemoteDischarges map[string]Discharge // Map of third-party caveat identifiers to corresponding discharges shared by the remote end.
LocalDischarges map[string]Discharge // Map of third-party caveat identifiers to corresponding discharges shared by the local end.
RemoteEndpoint naming.Endpoint // Endpoint of the remote end of communication (as seen by the local end)
}
// Copy fills in p with a copy of the values in c.
func (p *CallParams) Copy(c Call) {
p.Timestamp = c.Timestamp()
p.Method = c.Method()
if tagslen := len(c.MethodTags()); tagslen == 0 {
p.MethodTags = nil
} else {
p.MethodTags = make([]*vdl.Value, tagslen)
for ix, tag := range c.MethodTags() {
p.MethodTags[ix] = vdl.CopyValue(tag)
}
}
p.Suffix = c.Suffix()
p.LocalPrincipal = c.LocalPrincipal()
p.LocalBlessings = c.LocalBlessings()
p.LocalEndpoint = c.LocalEndpoint()
p.RemoteBlessings = c.RemoteBlessings()
// TODO(ataly, suharshs): Is the copying of discharge maps
// really needed?
p.LocalDischarges = copyDischargeMap(c.LocalDischarges())
p.RemoteDischarges = copyDischargeMap(c.RemoteDischarges())
p.RemoteEndpoint = c.RemoteEndpoint()
}
func copyDischargeMap(discharges map[string]Discharge) map[string]Discharge {
// avoid unnecessary allocation.
if len(discharges) == 0 {
return nil
}
ret := make(map[string]Discharge, len(discharges))
for id, d := range discharges {
ret[id] = d
}
return ret
}
type ctxImpl struct{ params CallParams }
func (c *ctxImpl) Timestamp() time.Time { return c.params.Timestamp }
func (c *ctxImpl) Method() string { return c.params.Method }
func (c *ctxImpl) MethodTags() []*vdl.Value { return c.params.MethodTags }
func (c *ctxImpl) Suffix() string { return c.params.Suffix }
func (c *ctxImpl) LocalPrincipal() Principal { return c.params.LocalPrincipal }
func (c *ctxImpl) LocalBlessings() Blessings { return c.params.LocalBlessings }
func (c *ctxImpl) RemoteBlessings() Blessings { return c.params.RemoteBlessings }
func (c *ctxImpl) LocalEndpoint() naming.Endpoint { return c.params.LocalEndpoint }
func (c *ctxImpl) RemoteEndpoint() naming.Endpoint { return c.params.RemoteEndpoint }
func (c *ctxImpl) LocalDischarges() map[string]Discharge { return c.params.LocalDischarges }
func (c *ctxImpl) RemoteDischarges() map[string]Discharge { return c.params.RemoteDischarges }
func (c *ctxImpl) String() string { return fmt.Sprintf("%+v", c.params) }
|
/* Union returns a new set with elements from the set and the other set. */
func (s *Set) Union(other SetInterface) (SetInterface, error) {
output, err := s.Copy()
if err != nil {
return nil, err
}
output.Combine(other)
return output, nil
} |
/*
* The Clear BSD License
* Copyright 2016-2017 NXP
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted (subject to the limitations in the
* disclaimer below) provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE
* GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @defgroup g_mac_vs_data MAC layer Service Access Point (SAP)
*/
#ifndef _mac_vs_data_h_
#define _mac_vs_data_h_
/*!
\file mac_vs_sap.h
\brief MAC shim layer to provide PDU manager i/f to NWK layer
*/
#ifdef __cplusplus
extern "C" {
#endif
/***********************/
/**** INCLUDE FILES ****/
/***********************/
#include "jendefs.h"
#include <pdum_nwk.h>
#include "mac_sap.h"
#ifndef CPU_MKW41Z512VHT4
#include "mac_pib.h"
#include "AppApi.h"
#include "tsv_pub.h"
#endif
/************************/
/**** MACROS/DEFINES ****/
/************************/
#define MAC_MCPS_VS_TYPE_OFFSET 0x80
/**************************/
/**** TYPE DEFINITIONS ****/
/**************************/
/**********************/
/**** MCPS Request ****/
/**********************/
/**
* @defgroup g_mac_sap_mcps_req MCPS Request objects
* @ingroup g_mac_sap_mcps
*
* These are passed in a call to MAC_vHandleMcpsReqRsp.
* Confirms to a Request will either be passed back synchronously on the function return,
* or a special 'deferred' confirm will come back asynchronously via the
* Deferred Confirm/Indication callback.
* Responses have no effective confirmation of sending as they are in response to
* an Indication; this will be indicated in the synchronous Confirm passed back.
*/
/**
* @defgroup g_mac_sap_mcps_req_15_4 MCPS Request 802.15.4 specification parameters
* @ingroup g_mac_sap_mcps_req
*
* @{
*/
/**
* @brief Structure for MCPS-DATA.request
*
* Data transmit request. Use type MAC_MCPS_REQ_DATA
*/
typedef struct
{
MAC_Addr_s sSrcAddr; /**< Source address */
MAC_Addr_s sDstAddr; /**< Destination address */
uint8 u8TxOptions; /**< Transmit options */
uint8 u8Handle; /**< MAC handle */
uint8 u8Free; /**< Whether NPDU is freed or not */
PDUM_thNPdu hNPdu; /**< NPDU handle */
} MAC_tsMcpsVsReqData;
/**
* @brief Structure for MCPS-PURGE.request
*
* Purge request. Use type MAC_MCPS_REQ_PURGE
*/
typedef struct
{
uint8 u8Handle; /**< Handle of request to purge from queue */
} MAC_tsMcpsVsReqPurge;
/* @} */
/**********************/
/**** MCPS Confirm ****/
/**********************/
/**
* @defgroup g_mac_sap_mcps_cfm MCPS Confirm objects
* @ingroup g_mac_sap_mcps
*
* These come back synchronously as a returned parameter in the Request/Response call.
* They can also be deferred and asynchronously posted via the Deferred Confirm/Indication callback.
*/
/**
* @defgroup g_mac_sap_mcps_cfm_15_4 MCPS Confirm 802.15.4 specification parameters
* @ingroup g_mac_sap_mcps_cfm
*
* @{
*/
/**
* @brief Structure for MCPS-DATA.confirm
*
* Data transmit confirm. Use type MAC_MCPS_CFM_DATA
*/
typedef struct
{
uint8 u8Status; /**< Status of request @sa MAC_Enum_e */
uint8 u8Handle; /**< Handle matching associated request */
} MAC_tsMcpsVsCfmData;
/**
* @brief Structure for MCPS-PURGE.confirm
*
* Data transmit confirm. Use type MAC_MCPS_CFM_PURGE
*/
typedef struct
{
uint8 u8Status; /**< Status of request @sa MAC_Enum_e */
uint8 u8Handle; /**< Handle matching associated request */
} MAC_tsMcpsVsCfmPurge;
/* @} */
typedef struct
{
tsTxFrameFormat sTxFrame;
TSV_Timer_s sTimer;
uint8 u8HigherLayerRetryCount;
} tsHigherLayerTxFrame;
/*************************/
/**** MCPS Indication ****/
/*************************/
/**
* @defgroup g_mac_sap_mcps_ind MCPS Indication Object
* @ingroup g_mac_sap_mcps
*
* These are sent asynchronously via the registered Deferred Confirm/Indication callback
*/
/**
* @defgroup g_mac_sap_mcps_ind_15_4 MCPS Indication 802.15.4 specification parameters
* @ingroup g_mac_sap_mcps_ind
*
* @{
*/
/**
* @brief Structure for MCPS-DATA.indication
*
* Data received indication. Uses type MAC_MCPS_IND_DATA
*/
typedef struct
{
MAC_Addr_s sSrcAddr; /**< Source address */
MAC_Addr_s sDstAddr; /**< Destination address */
uint8 u8LinkQuality; /**< Link quality of received frame */
uint8 u8SecurityUse; /**< True if security was used */
uint8 u8AclEntry; /**< Security suite used */
uint8 u8SeqNum; /**< sequence number */
uint32 u32ArrivalTime; /**< Arrival time */
PDUM_thNPdu hNPdu; /**< NPDU handle */
bool_t bFramePending; /*Frame pending set*/
} MAC_tsMcpsVsIndData;
/* @} */
/*****************************************/
/**** MCPS Request/Response Interface ****/
/*****************************************/
/**
* @defgroup g_mac_sap_mcps_req_rsp_if MCPS Request/Response interface
* @ingroup g_mac_sap_mcps g_mac_VS
*
* The interface for the client to issue an MCPS Request or Response
* is via a function call to MAC_vHandleMcpsReqRsp.
* @li Request/Response parameters are passed in via psMcpsReqRsp
* @li Synchronous Confirm parameters are passed out via psMcpsSyncCfm
* @li Deferred Confirms are posted back asynchronously via the
* Deferred Confirm/Indication callback.
* @note There are currently no MCPS Responses specified
*
* @{
*/
/**
* @brief MAC MCPS Request/Response enumeration.
*
* Enumeration of MAC MCPS Request/Response
* @note Must not exceed 256 entries
*/
typedef enum
{
MAC_MCPS_VS_REQ_DATA = MAC_MCPS_VS_TYPE_OFFSET, /**< Use with MAC_tsMcpsVsReqRsp */
MAC_MCPS_VS_REQ_PURGE, /**< Use with MAC_tsMcpsVsReqPurge */
} MAC_teMcpsVsReqRspType;
#define NUM_MAC_MCPS_VS_REQ 1
/**
* @brief MCPS Request/Response Parameter union
*
* Union of all the possible MCPS Requests and Responses
* @note There are no Responses currently specified
*/
typedef union
{
MAC_tsMcpsVsReqData sVsReqData; /**< Data request */
MAC_tsMcpsVsReqPurge sVsReqPurge; /**< Purge request */
} MAC_tuMcpsVsReqRspParam;
/**
* @brief MCPS Request/Response object
*
* The object passed to MAC_vHandleMcpsReqRsp containing the request/response
*/
typedef struct
{
uint8 u8Type; /**< Request type (@sa MAC_teMcpsReqRspVsType) */
uint8 u8ParamLength; /**< Parameter length in following union */
uint16 u16Pad; /**< Padding to force alignment */
MAC_tuMcpsVsReqRspParam uParam; /**< Union of all possible Requests */
} MAC_tsMcpsVsReqRsp;
/**
* @brief MCPS Synchronouse Confirm Parameter union
*
* Union of all the possible MCPS Synchronous Confirms
*/
typedef union
{
MAC_tsMcpsVsCfmData sVsCfmData;
MAC_tsMcpsVsCfmData sVsCfmPurge;
} MAC_tuMcpsVsSyncCfmParam;
/**
* @brief MCPS Synchronous Confirm
*
* The object returned by MAC_vHandleMcpsReqRsp containing the synchronous confirm.
* The confirm type is implied as corresponding to the request
* @note All Confirms may also be sent asynchronously via the registered Deferred Confirm/Indication callback;
* this is notified by returning MAC_MCPS_CFM_DEFERRED.
*/
typedef struct
{
uint8 u8Status; /**< Confirm status (@sa MAC_teMcpsSyncCfmVsStatus) */
uint8 u8ParamLength; /**< Parameter length in following union */
uint16 u16Pad; /**< Padding to force alignment */
MAC_tuMcpsVsSyncCfmParam uParam; /**< Union of all possible Confirms */
} MAC_tsMcpsVsSyncCfm;
/* @} */
/****************************************************/
/**** MCPS Deferred Confirm/Indication Interface ****/
/****************************************************/
/**
* @defgroup g_mac_sap_mcps_dcfm_ind_if MCPS Deferred Confirm/Indication Interface
* @ingroup g_mac_sap_mcps g_mac_VS
*
* The interface for the client to receive an MCPS Deferred Confirm or Indication
* is via a function callback to the function registered using MAC_vMcpsDcfmIndRegister
*
* @{
*/
/**
* @brief Deferred Confirm/Indication type
*
* Indicates the type of deferred confirm or indication
* @note NB Must not exceed 256 entries
*/
typedef enum
{
MAC_MCPS_VS_DCFM_DATA = MAC_MCPS_VS_TYPE_OFFSET,
MAC_MCPS_VS_DCFM_PURGE,
MAC_MCPS_VS_IND_DATA
} MAC_teMcpsVsDcfmIndType;
#define NUM_MAC_MCPS_VS_DCFM_IND 3
/**
* @brief MCPS Deferred Confirm/Indication Parameter union
*
* Union of all the possible MCPS Deferred Confirms or Indications
*/
typedef union
{
MAC_tsMcpsVsCfmData sVsDcfmData; /**< Deferred transmit data confirm */
MAC_tsMcpsVsCfmPurge sVsDcfmPurge; /**< Deferred purge confirm */
MAC_tsMcpsVsIndData sVsIndData; /**< Received data indication */
} MAC_tuMcpsVsDcfmIndParam;
/**
* @brief MCPS Deferred Confirm/Indication
*
* The object passed in the MCPS Deferred Confirm/Indication callback
*/
typedef struct
{
uint8 u8Type; /**< Indication type (@sa MAC_teMcpsVsDcfmIndType) */
uint8 u8ParamLength; /**< Parameter length in following union */
uint16 u16Pad; /**< Padding to force alignment */
MAC_tuMcpsVsDcfmIndParam uParam; /**< Union of all possible Indications */
} MAC_tsMcpsVsDcfmInd;
/* @} */
/**
* @defgroup g_mac_sap_gen Generic headers
* @ingroup g_mac_sap
*
* Generic headers which abstract the parameter interfaces to the function calls.
* The headers reflect the common structure at the head of the derived structures
* for MLME/MCPS
*
* @{
*/
#define MAC_MAX_ZBP_BEACON_PAYLOAD_LEN 15
typedef struct
{
uint8 u8Status; /**< Status of scan request @sa MAC_Enum_e */
uint8 u8ScanType; /**< Scan type */
uint8 u8ResultListSize; /**< Size of scan results list */
uint8 u8Pad; /**< Padding to show alignment */
uint32 u32UnscannedChannels; /**< Bitmap of unscanned channels */
uint8 au8EnergyDetect[MAC_MAX_SCAN_CHANNELS];
} MAC_tsMlmeVsCfmScan;
typedef struct
{
MAC_PanDescr_s sPANdescriptor; /**< PAN descriptor */
uint8 u8BSN; /**< Beacon sequence number */
uint8 au8BeaconPayload[MAC_MAX_ZBP_BEACON_PAYLOAD_LEN]; /**< Beacon payload */
} MAC_tsMlmeVsIndBeacon;
typedef union
{
MAC_tsMlmeVsCfmScan sVsDcfmScan;
MAC_MlmeCfmAssociate_s sDcfmAssociate;
MAC_MlmeCfmDisassociate_s sDcfmDisassociate;
MAC_MlmeCfmPoll_s sDcfmPoll;
MAC_MlmeCfmRxEnable_s sDcfmRxEnable;
MAC_MlmeIndAssociate_s sIndAssociate;
MAC_MlmeIndDisassociate_s sIndDisassociate;
MAC_MlmeIndGts_s sIndGts;
MAC_tsMlmeVsIndBeacon sVsIndBeacon;
MAC_MlmeIndSyncLoss_s sIndSyncLoss;
MAC_MlmeIndCommStatus_s sIndCommStatus;
MAC_MlmeIndOrphan_s sIndOrphan;
#if defined(DEBUG) && defined(EMBEDDED)
MAC_MlmeIndVsDebug_s sIndVsDebug;
#endif /* defined(DEBUG) && defined(EMBEDDED) */
} MAC_tuMlmeVsDcfmIndParam;
typedef struct
{
uint8 u8Type; /**< Deferred Confirm/Indication type @sa MAC_MlmeDcfmIndType_e */
uint8 u8ParamLength; /**< Parameter length in following union */
uint16 u16Pad; /**< Padding to force alignment */
MAC_tuMlmeVsDcfmIndParam uParam; /**< Union of all possible Deferred Confirms/Indications */
} MAC_tsMlmeVsDcfmInd;
typedef void (*pfnMacVsDataRequest) (uint16 u16Pan, uint16 u16Short);
/****************************/
/**** EXPORTED VARIABLES ****/
/****************************/
/****************************/
/**** EXPORTED FUNCTIONS ****/
/****************************/
PUBLIC void MAC_vRegisterDataRequest(pfnMacVsDataRequest pfn);
PUBLIC void MAC_vSetMutex(void* hMacMutex);
PUBLIC void ZPS_vMacHandleMcpsVsReqRsp(
void* pvMac,
MAC_tsMcpsVsReqRsp *psMcpsVsReqRsp,
MAC_tsMcpsVsSyncCfm *psMcpsVsSyncCfm);
PUBLIC void ZPS_vMacHandleMlmeVsReqRsp(
void* pvMac,
MAC_MlmeReqRsp_s *psMlmeReqRsp,
MAC_MlmeSyncCfm_s *psMlmeSyncCfm);
PUBLIC void ZPS_vMacRegisterDataRequest(pfnMacVsDataRequest pfn);
PUBLIC void ZPS_vMacHandleMlmeVsReqRsp(
void *pvMac,
MAC_MlmeReqRsp_s *psMlmeReqRsp,
MAC_MlmeSyncCfm_s *psMlmeSyncCfm);
/****************************************************************************/
/*** ZPS MAC SHIM EXPORTS (Called by Zigbee Pro Stack directly ***/
/****************************************************************************/
#define MAX_TIMERS 7
#define TIMER_INTERVAL 64
#define u32SymbolsToTicks(A) (((A) + TIMER_INTERVAL - 1) / TIMER_INTERVAL)
PUBLIC uint32 ZPS_eMiniMacSetTxBuffers (uint8 u8MaxTxBuffers);
PUBLIC void
ZPS_MAC_vShimInit(PR_GET_BUFFER prMlmeGetBuffer,
PR_POST_CALLBACK prMlmeCallback,
PR_GET_BUFFER prMcpsGetBuffer,
PR_POST_CALLBACK prMcpsCallback,
void *pfGetVsBuffer,
void *pfVsCallback,
void *pvApl,
void *pvNwk,
void *pvMac);
PUBLIC void ZPS_vMacSetFilterStorage (uint16* pu16FilterTable,uint8* pu8LinkQualityTable, uint16 u16MaxTableNumAddrs);
PUBLIC uint32 ZPS_eMacFilterAddAccept(uint16 u16Addr, uint8 u8LinkQuality);
PUBLIC void ZPS_vMacModifyForZgp(bool_t bStopCca, uint8 u8SeqNo);
PUBLIC void ZPS_vNwkHandleMcpsDcfmInd (void *pvNwk,
MAC_DcfmIndHdr_s *psDcfmIndHdr);
PUBLIC uint32 ZPS_u32MacSetTxBuffers(uint8 u8MaxTxBuffers);
PUBLIC void ZPS_vPhyInterruptHandler(void);
PUBLIC void ZPS_vMacInterruptHandler(void);
/* ZPS MAC PIB Get Functions */
PUBLIC uint16 ZPS_u16MacPibGetCoordShortAddress(void);
PUBLIC uint16 ZPS_u16MacPibGetMaxFrameTotalWaitTime(void);
PUBLIC uint16 ZPS_u16MacPibGetTransactionPersistenceTime(void);
PUBLIC uint8 ZPS_u8MacPibGetMaxFrameRetries(void);
PUBLIC uint8 ZPS_u8MacPibGetResponseWaitTime(void);
PUBLIC uint16 ZPS_u16MacPibGetPanId(void);
PUBLIC uint16 ZPS_u16MacPibGetShortAddr(void);
PUBLIC uint8 ZPS_u8MacPibGetMinBe(void);
PUBLIC uint8 ZPS_u8MacPibGetMaxBe(void);
PUBLIC uint8 ZPS_u8MacPibGetMaxCsmaBackoffs(void);
PUBLIC bool_t ZPS_bMacPibGetRxOnWhenIdle(void);
PUBLIC tsExtAddr ZPS_sMacPibGetCoordExtAddr(void);
PUBLIC uint32 ZPS_u32MacPibGetMacFrameCounter(void);
PUBLIC bool_t ZPS_bMacPibGetAssociationPermit(void);
PUBLIC uint8 ZPS_u8MacPibGetBeaconPayloadLength(void);
PUBLIC uint8 ZPS_u8MacPibGetBeaconPayload(uint8 *pu8Payload);
PUBLIC uint8 ZPS_u8MacPibGetBsn(void);
PUBLIC uint8 ZPS_u8MacPibGetDsn(void);
PUBLIC bool_t ZPS_bMacPibGetPanCoordinator(void);
PUBLIC uint8 ZPS_u8MacPibGetBeaconRequestLqiThreshold(void);
PUBLIC uint8 ZPS_u8MacPibGetMaxMaxConcurrentAssocResponses(void);
PUBLIC tsExtAddr ZPS_sMacPibGetExtAddr(void);
PUBLIC uint8 ZPS_u8MacPibGetEBsn(void);
PUBLIC bool_t ZPS_bMacPibGetEBFilteringEnable(void);
PUBLIC uint8 ZPS_u8MacPibGetEBR_PayloadLength(void);
PUBLIC uint8 ZPS_u8MacPibGetEBR_Payload(uint8 *pu8EBRPayload);
/* ZPS MAC PIB Set Functions */
PUBLIC void ZPS_vMacPibSetCoordShortAddress(uint16 u16CoordShortAddr);
PUBLIC void ZPS_vMacPibSetMaxFrameTotalWaitTime(uint16 u16MaxFrameTotalWaitTime);
PUBLIC void ZPS_vMacPibSetTransactionPersistenceTime(uint16 u16TransactionPersistenceTime);
PUBLIC void ZPS_vMacPibSetMaxFrameRetries(uint8 u8MaxFrameRetries);
PUBLIC void ZPS_vMacPibSetResponseWaitTime(uint8 u8ResponseWaitTime);
PUBLIC void ZPS_vMacPibSetPanId(uint16 u16PanID);
PUBLIC void ZPS_vMacPibSetShortAddr(uint16 u16ShortAddr);
PUBLIC void ZPS_vMacPibSetMinBe(uint8 u8MinBe);
PUBLIC void ZPS_vMacPibSetMaxBe(uint8 u8MaxBe);
PUBLIC void ZPS_vMacPibSetMaxCsmaBackoffs(uint8 u8MaxCsmaBackoffs);
PUBLIC void ZPS_vMacPibSetRxOnWhenIdle(bool_t bNewState, bool_t bInReset);
PUBLIC void ZPS_vMacPibSetCoordExtAddr(tsExtAddr sCoordExtAddr);
PUBLIC void ZPS_vMacPibSetMacFrameCounter(uint32 u32MacFrameCounter);
PUBLIC void ZPS_vMacPibSetAssociationPermit(bool_t bAssociatePermit);
PUBLIC void ZPS_vMacPibSetBeaconPayloadLength(uint8 u8BeaconPayloadLen);
PUBLIC void ZPS_vMacPibSetBeaconPayload(const uint8* pu8Payload, uint8 u8Len);
PUBLIC void ZPS_vMacPibSetBsn(uint8 u8Bsn);
PUBLIC void ZPS_vMacPibSetDsn(uint8 u8Dsn);
PUBLIC void ZPS_vMacPibSetPanCoordinator(bool_t bPanCoordinator);
PUBLIC void ZPS_vMacPibSetBeaconRequestLqiThreshold(uint8 u8LqiThreshold);
PUBLIC void ZPS_vMacPibSetMaxMaxConcurrentAssocResponses(uint8 u8Max);
PUBLIC void ZPS_vMacPibSetExtAddr(tsExtAddr *psExtAddr);
PUBLIC void ZPS_vMacPibSetRxInCca(bool_t bEnable);
PUBLIC void ZPS_vMacPibSetEBsn(uint8 u8EBsn);
PUBLIC void ZPS_vMacPibSetEBFilteringEnable(bool_t bEBFilteringEnabled);
PUBLIC void ZPS_vMacPibSetEBR_PayloadLength(uint8 u8EBRPayloadLen);
PUBLIC void ZPS_vMacPibSetEBR_Payload(const uint8* pu8EBRPayload, uint8 u8EBRPayloadLen);
PUBLIC void ZPS_vMacSetVsOUIBytes(uint8 *pu8VsOUIBytes);
/****************************************************************************/
/*** ZPS SOC MAC EXPORTS (Called by ZPS MAC SHIM directly ***/
/****************************************************************************/
#ifdef JENNIC_MAC_MiniMacShim
PUBLIC void SOC_MAC_vShimInit(PR_GET_BUFFER prMlmeGetBuffer,
PR_POST_CALLBACK prMlmeCallback,
PR_GET_BUFFER prMcpsGetBuffer,
PR_POST_CALLBACK prMcpsCallback,
void *pfGetVsBuffer,
void *pfVsCallback,
void *pvApl,
void *pvNwk,
void *pvMac);
#endif
PUBLIC void SOC_MAC_vHandleMcpsVsReqRsp(void* pvMac,
MAC_tsMcpsVsReqRsp *psMcpsVsReqRsp,
MAC_tsMcpsVsSyncCfm *psMcpsVsSyncCfm);
PUBLIC void SOC_MAC_vHandleMlmeVsReqRsp(void* pvMac,
MAC_MlmeReqRsp_s *psMlmeReqRsp,
MAC_MlmeSyncCfm_s *psMlmeSyncCfm);
PUBLIC void vMiniMac_InterruptHandler(void);
PUBLIC void SOC_MAC_vSetFilterStorage (uint16* pu16FilterTable,uint8* pu8LinkQualityTable, uint16 u16MaxTableNumAddrs);
PUBLIC uint32 SOC_MAC_eMacFilterAddAccept(uint16 u16Addr, uint8 u8LinkQuality);
PUBLIC void SOC_ZPS_vMacModifyForZgp(bool_t bStopCca, uint8 u8SeqNo);
PUBLIC void SOC_ZPS_vNwkHandleMcpsDcfmInd (void *pvNwk,
MAC_DcfmIndHdr_s *psDcfmIndHdr);
PUBLIC void SOC_ZPS_vSetMacAddrLocation(void* pu64MacAddress);
PUBLIC void* SOC_ZPS_pvGetMacAddrLocation(void);
/* ZPS MAC PIB Get Functions */
PUBLIC uint16 SOC_ZPS_u16MacPibGetCoordShortAddress(void);
PUBLIC uint16 SOC_ZPS_u16MacPibGetMaxFrameTotalWaitTime(void);
PUBLIC uint16 SOC_ZPS_u16MacPibGetTransactionPersistenceTime(void);
PUBLIC uint8 SOC_ZPS_u8MacPibGetMaxFrameRetries(void);
PUBLIC uint8 SOC_ZPS_u8MacPibGetResponseWaitTime(void);
PUBLIC uint16 SOC_ZPS_u16MacPibGetPanId(void);
PUBLIC uint8 SOC_ZPS_u8MacPibGetChannel(void);
PUBLIC uint16 SOC_ZPS_u16MacPibGetShortAddr(void);
PUBLIC uint8 SOC_ZPS_u8MacPibGetMinBe(void);
PUBLIC uint8 SOC_ZPS_u8MacPibGetMaxBe(void);
PUBLIC uint8 SOC_ZPS_u8MacPibGetMaxCsmaBackoffs(void);
PUBLIC bool_t SOC_ZPS_bMacPibGetRxOnWhenIdle(void);
PUBLIC tsExtAddr SOC_ZPS_sMacPibGetCoordExtAddr(void);
PUBLIC uint32 SOC_ZPS_u32MacPibGetMacFrameCounter(void);
PUBLIC bool_t SOC_ZPS_bMacPibGetAssociationPermit(void);
PUBLIC uint8 SOC_ZPS_u8MacPibGetBeaconPayloadLength(void);
PUBLIC uint8 SOC_ZPS_u8MacPibGetBeaconPayload(uint8 *pu8Payload);
PUBLIC uint8 SOC_ZPS_u8MacPibGetBsn(void);
PUBLIC uint8 SOC_ZPS_u8MacPibGetDsn(void);
PUBLIC bool_t SOC_ZPS_bMacPibGetPanCoordinator(void);
PUBLIC uint8 SOC_ZPS_u8MacPibGetBeaconRequestLqiThreshold(void);
PUBLIC uint8 SOC_ZPS_u8MacPibGetMaxMaxConcurrentAssocResponses(void);
PUBLIC tsExtAddr SOC_ZPS_sMacPibGetExtAddr(void);
PUBLIC uint8 SOC_ZPS_u8MacPibGetEBsn(void);
PUBLIC bool_t SOC_ZPS_bMacPibGetEBFilteringEnable(void);
PUBLIC uint8 SOC_ZPS_u8MacPibGetEBR_PayloadLength(void);
PUBLIC uint8 SOC_ZPS_u8MacPibGetEBR_Payload(uint8 *pu8EBRPayload);
/* ZPS MAC PIB Set Functions */
PUBLIC void SOC_ZPS_vMacPibSetCoordShortAddress(uint16 u16CoordShortAddr);
PUBLIC void SOC_ZPS_vMacPibSetMaxFrameTotalWaitTime(uint16 u16MaxFrameTotalWaitTime);
PUBLIC void SOC_ZPS_vMacPibSetTransactionPersistenceTime(uint16 u16TransactionPersistenceTime);
PUBLIC void SOC_ZPS_vMacPibSetMaxFrameRetries(uint8 u8MaxFrameRetries);
PUBLIC void SOC_ZPS_vMacPibSetResponseWaitTime(uint8 u8ResponseWaitTime);
PUBLIC void SOC_ZPS_vMacPibSetPanId(uint16 u16PanID);
PUBLIC void SOC_ZPS_vMacPibSetChannel(uint8_t u8Channel);
PUBLIC void SOC_ZPS_vMacPibSetShortAddr(uint16 u16ShortAddr);
PUBLIC void SOC_ZPS_vMacPibSetMinBe(uint8 u8MinBe);
PUBLIC void SOC_ZPS_vMacPibSetMaxBe(uint8 u8MaxBe);
PUBLIC void SOC_ZPS_vMacPibSetMaxCsmaBackoffs(uint8 u8MaxCsmaBackoffs);
PUBLIC void SOC_ZPS_vMacPibSetRxOnWhenIdle(bool_t bNewState, bool_t bInReset);
PUBLIC void SOC_ZPS_vMacPibSetCoordExtAddr(tsExtAddr sCoordExtAddr);
PUBLIC void SOC_ZPS_vMacPibSetMacFrameCounter(uint32 u32MacFrameCounter);
PUBLIC void SOC_ZPS_vMacPibSetAssociationPermit(bool_t bAssociatePermit);
PUBLIC void SOC_ZPS_vMacPibSetBeaconPayloadLength(uint8 u8BeaconPayloadLen);
PUBLIC void SOC_ZPS_vMacPibSetBeaconPayload(const uint8* pu8Payload, uint8 u8Len);
PUBLIC void SOC_ZPS_vMacPibSetBsn(uint8 u8Bsn);
PUBLIC void SOC_ZPS_vMacPibSetDsn(uint8 u8Dsn);
PUBLIC void SOC_ZPS_vMacPibSetPanCoordinator(bool_t bPanCoordinator);
PUBLIC void SOC_ZPS_vMacPibSetBeaconRequestLqiThreshold(uint8 u8LqiThreshold);
PUBLIC void SOC_ZPS_vMacPibSetMaxMaxConcurrentAssocResponses(uint8 u8Max);
PUBLIC void SOC_ZPS_vMacPibSetExtAddr(tsExtAddr *psExtAddr);
PUBLIC void SOC_ZPS_vMacPibSetRxInCca(bool_t bEnable);
PUBLIC void SOC_ZPS_vMacPibSetEBsn(uint8 u8EBsn);
PUBLIC void SOC_ZPS_vMacPibSetEBFilteringEnable(bool_t bEBFilteringEnabled);
PUBLIC void SOC_ZPS_vMacPibSetEBR_PayloadLength(uint8 u8EBRPayloadLen);
PUBLIC void SOC_ZPS_vMacPibSetEBR_Payload(const uint8* pu8EBRPayload, uint8 u8EBRPayloadLen);
/****************************************************************************/
/*** ZPS SERIAL MAC EXPORTS (Called by ZPS MAC SHIM directly ***/
/****************************************************************************/
#ifdef JENNIC_MAC_MiniMacShim
PUBLIC void SERIAL_MAC_vShimInit(PR_GET_BUFFER prMlmeGetBuffer,
PR_POST_CALLBACK prMlmeCallback,
PR_GET_BUFFER prMcpsGetBuffer,
PR_POST_CALLBACK prMcpsCallback,
void *pfGetVsBuffer,
void *pfVsCallback,
void *pvApl,
void *pvNwk,
void *pvMac);
#endif
PUBLIC void SERIAL_MAC_vHandleMcpsVsReqRsp(void* pvMac,
MAC_tsMcpsVsReqRsp *psMcpsVsReqRsp,
MAC_tsMcpsVsSyncCfm *psMcpsVsSyncCfm);
PUBLIC void SERIAL_MAC_vHandleMlmeVsReqRsp(void* pvMac,
MAC_MlmeReqRsp_s *psMlmeReqRsp,
MAC_MlmeSyncCfm_s *psMlmeSyncCfm);
PUBLIC void vSerialMac_InterruptHandler(void);
PUBLIC void SERIAL_ZPS_vMacModifyForZgp(bool_t bStopCca, uint8 u8SeqNo);
PUBLIC void SERIAL_ZPS_vNwkHandleMcpsDcfmInd (void *pvNwk,
MAC_DcfmIndHdr_s *psDcfmIndHdr);
PUBLIC void SERIAL_ZPS_vSetMacAddrLocation(void* pu64MacAddress);
PUBLIC void* SERIAL_ZPS_pvGetMacAddrLocation(void);
/* ZPS MAC PIB Get Functions */
PUBLIC uint16 SERIAL_ZPS_u16MacPibGetCoordShortAddress(void);
PUBLIC uint16 SERIAL_ZPS_u16MacPibGetMaxFrameTotalWaitTime(void);
PUBLIC uint16 SERIAL_ZPS_u16MacPibGetTransactionPersistenceTime(void);
PUBLIC uint8 SERIAL_ZPS_u8MacPibGetMaxFrameRetries(void);
PUBLIC uint8 SERIAL_ZPS_u8MacPibGetResponseWaitTime(void);
PUBLIC uint16 SERIAL_ZPS_u16MacPibGetPanId(void);
PUBLIC uint16 SERIAL_ZPS_u16MacPibGetShortAddr(void);
PUBLIC uint8 SERIAL_ZPS_u8MacPibGetMinBe(void);
PUBLIC uint8 SERIAL_ZPS_u8MacPibGetMaxBe(void);
PUBLIC uint8 SERIAL_ZPS_u8MacPibGetMaxCsmaBackoffs(void);
PUBLIC bool_t SERIAL_ZPS_bMacPibGetRxOnWhenIdle(void);
PUBLIC tsExtAddr SERIAL_ZPS_sMacPibGetCoordExtAddr(void);
PUBLIC uint32 SERIAL_ZPS_u32MacPibGetMacFrameCounter(void);
PUBLIC bool_t SERIAL_ZPS_bMacPibGetAssociationPermit(void);
PUBLIC uint8 SERIAL_ZPS_u8MacPibGetBeaconPayloadLength(void);
PUBLIC uint8 SERIAL_ZPS_u8MacPibGetBeaconPayload(uint8 *pu8Payload);
PUBLIC uint8 SERIAL_ZPS_u8MacPibGetBsn(void);
PUBLIC uint8 SERIAL_ZPS_u8MacPibGetDsn(void);
PUBLIC bool_t SERIAL_ZPS_bMacPibGetPanCoordinator(void);
PUBLIC uint8 SERIAL_ZPS_u8MacPibGetBeaconRequestLqiThreshold(void);
PUBLIC uint8 SERIAL_ZPS_u8MacPibGetMaxMaxConcurrentAssocResponses(void);
PUBLIC tsExtAddr SERIAL_ZPS_sMacPibGetExtAddr(void);
PUBLIC uint8 SERIAL_ZPS_u8MacPibGetEBsn(void);
PUBLIC bool_t SERIAL_ZPS_bMacPibGetEBFilteringEnable(void);
PUBLIC uint8 SERIAL_ZPS_u8MacPibGetEBR_PayloadLength(void);
PUBLIC uint8 SERIAL_ZPS_u8MacPibGetEBR_Payload(uint8 *pu8EBRPayload);
/* ZPS MAC PIB Set Functions */
PUBLIC void SERIAL_ZPS_vMacPibSetCoordShortAddress(uint16 u16CoordShortAddr);
PUBLIC void SERIAL_ZPS_vMacPibSetMaxFrameTotalWaitTime(uint16 u16MaxFrameTotalWaitTime);
PUBLIC void SERIAL_ZPS_vMacPibSetTransactionPersistenceTime(uint16 u16TransactionPersistenceTime);
PUBLIC void SERIAL_ZPS_vMacPibSetMaxFrameRetries(uint8 u8MaxFrameRetries);
PUBLIC void SERIAL_ZPS_vMacPibSetResponseWaitTime(uint8 u8ResponseWaitTime);
PUBLIC void SERIAL_ZPS_vMacPibSetPanId(uint16 u16PanID);
PUBLIC void SERIAL_ZPS_vMacPibSetShortAddr(uint16 u16ShortAddr);
PUBLIC void SERIAL_ZPS_vMacPibSetMinBe(uint8 u8MinBe);
PUBLIC void SERIAL_ZPS_vMacPibSetMaxBe(uint8 u8MaxBe);
PUBLIC void SERIAL_ZPS_vMacPibSetMaxCsmaBackoffs(uint8 u8MaxCsmaBackoffs);
PUBLIC void SERIAL_ZPS_vMacPibSetRxOnWhenIdle(bool_t bNewState, bool_t bInReset);
PUBLIC void SERIAL_ZPS_vMacPibSetCoordExtAddr(tsExtAddr sCoordExtAddr);
PUBLIC void SERIAL_ZPS_vMacPibSetMacFrameCounter(uint32 u32MacFrameCounter);
PUBLIC void SERIAL_ZPS_vMacPibSetAssociationPermit(bool_t bAssociatePermit);
PUBLIC void SERIAL_ZPS_vMacPibSetBeaconPayloadLength(uint8 u8BeaconPayloadLen);
PUBLIC void SERIAL_ZPS_vMacPibSetBeaconPayload(const uint8* pu8Payload, uint8 u8Len);
PUBLIC void SERIAL_ZPS_vMacPibSetBsn(uint8 u8Bsn);
PUBLIC void SERIAL_ZPS_vMacPibSetDsn(uint8 u8Dsn);
PUBLIC void SERIAL_ZPS_vMacPibSetPanCoordinator(bool_t bPanCoordinator);
PUBLIC void SERIAL_ZPS_vMacPibSetBeaconRequestLqiThreshold(uint8 u8LqiThreshold);
PUBLIC void SERIAL_ZPS_vMacPibSetMaxMaxConcurrentAssocResponses(uint8 u8Max);
PUBLIC void SERIAL_ZPS_vMacPibSetExtAddr(tsExtAddr *psExtAddr);
PUBLIC void SERIAL_ZPS_vMacPibSetRxInCca(bool_t bEnable);
PUBLIC void SERIAL_ZPS_vMacPibSetEBsn(uint8 u8EBsn);
PUBLIC void SERIAL_ZPS_vMacPibSetEBFilteringEnable(bool_t bEBFilteringEnabled);
PUBLIC void SERIAL_ZPS_vMacPibSetEBR_PayloadLength(uint8 u8EBRPayloadLen);
PUBLIC void SERIAL_ZPS_vMacPibSetEBR_Payload(const uint8* pu8EBRPayload, uint8 u8EBRPayloadLen);
#ifdef __cplusplus
};
#endif
#endif /* _mac_vs_data_h_ */
|
<filename>src/input.c
#include "Hosebase/input.h"
#include "Hosebase/os.h"
#define INPUT_TEXT_SIZE 20
typedef struct {
b8 any;
InputState keys[Key_MaxEnum];
InputState mouse_buttons[MouseButton_MaxEnum];
char text[INPUT_TEXT_SIZE];
TextCommand text_commands[INPUT_TEXT_SIZE];
u32 text_command_count;
v2 mouse_position;
v2 mouse_last_position;
v2 mouse_dragging;
f32 mouse_wheel;
Key release_keys[Key_MaxEnum];
u32 release_key_count;
Key release_mouse_buttons[MouseButton_MaxEnum];
u32 release_mouse_button_count;
} InputData;
static InputData* input = NULL;
static b8 validate_input_state(InputState actual, InputState input_state)
{
if (input_state == InputState_Any) {
return actual == InputState_Pressed || actual == InputState_Hold || actual == InputState_Released;
}
else return actual == input_state;
}
b8 input_any()
{
return input->any;
}
b8 input_key(Key key, InputState input_state)
{
InputState actual = input->keys[key];
return validate_input_state(actual, input_state);
}
b8 input_mouse_button(MouseButton mouse_button, InputState input_state)
{
InputState actual = input->mouse_buttons[mouse_button];
return validate_input_state(actual, input_state);
}
f32 input_mouse_wheel()
{
return input->mouse_wheel;
}
v2 input_mouse_position()
{
return input->mouse_position;
}
v2 input_mouse_dragging()
{
return input->mouse_dragging;
}
const char* input_text()
{
return input->text;
}
u32 input_text_command_count()
{
return input->text_command_count;
}
TextCommand input_text_command(u32 index)
{
if (index >= input->text_command_count)
return TextCommand_Null;
return input->text_commands[index];
}
b8 _input_initialize()
{
input = memory_allocate(sizeof(InputData));
return TRUE;
}
void _input_close()
{
if (input) {
memory_free(input);
}
}
void _input_update()
{
input->any = FALSE;
foreach(i, Key_MaxEnum) {
InputState* state = input->keys + i;
if (*state == InputState_Pressed) {
*state = InputState_Hold;
input->any = TRUE;
}
else if (*state == InputState_Hold) {
input->any = TRUE;
if (!key_async(i))
*state = InputState_Released;
}
else if (*state == InputState_Released) {
*state = InputState_None;
}
}
foreach(i, input->release_key_count) {
Key key = input->release_keys[i];
input->keys[key] = InputState_Released;
}
input->release_key_count = 0;
foreach(i, MouseButton_MaxEnum) {
InputState* state = input->mouse_buttons + i;
if (*state == InputState_Pressed) {
*state = InputState_Hold;
input->any = TRUE;
}
else if (*state == InputState_Hold) {
input->any = TRUE;
if (!mouse_button_async(i))
*state = InputState_Released;
}
else if (*state == InputState_Released) {
*state = InputState_None;
}
}
foreach(i, input->release_mouse_button_count) {
MouseButton button = input->release_mouse_buttons[i];
input->mouse_buttons[button] = InputState_Released;
}
input->release_mouse_button_count = 0;
input->mouse_last_position = input->mouse_position;
input->text[0] = '\0';
input->text_command_count = 0;
input->mouse_wheel = 0.f;
}
void _input_key_set_pressed(Key key)
{
input->keys[key] = InputState_Pressed;
input->any = TRUE;
}
void _input_key_set_released(Key key)
{
if (input->keys[key] == InputState_Pressed && input->release_key_count < Key_MaxEnum) {
input->release_keys[input->release_key_count++] = key;
}
else input->keys[key] = InputState_Released;
input->any = TRUE;
}
void _input_mouse_button_set_pressed(MouseButton mouse_button)
{
input->mouse_buttons[mouse_button] = InputState_Pressed;
input->any = TRUE;
}
void _input_mouse_button_set_released(MouseButton mouse_button)
{
if (input->mouse_buttons[mouse_button] == InputState_Pressed && input->release_mouse_button_count < MouseButton_MaxEnum) {
input->release_mouse_buttons[input->release_mouse_button_count++] = mouse_button;
}
else input->mouse_buttons[mouse_button] = InputState_Released;
input->any = TRUE;
}
void _input_text_command_add(TextCommand text_command)
{
if (input->text_command_count >= SV_ARRAY_SIZE(input->text_commands))
{
assert_title(FALSE, "Input text command buffer overflow");
return;
}
input->text_commands[input->text_command_count++] = text_command;
input->any = TRUE;
}
void _input_text_add(char c)
{
char str[2];
str[0] = c;
str[1] = '\0';
string_append(input->text, str, INPUT_TEXT_SIZE);
input->any = TRUE;
}
void _input_mouse_wheel_set(f32 value)
{
input->mouse_wheel = value;
input->any = TRUE;
}
void _input_mouse_position_set(v2 value)
{
input->mouse_position = value;
}
void _input_mouse_dragging_set(v2 value)
{
input->mouse_dragging = value;
if (fabs(value.x) > 0.0001f || fabs(value.y) > 0.0001f)
input->any = TRUE;
} |
#include<stdio.h>
int steviloDni(int mesec, int leto){
if(mesec == 4 || mesec == 6 || mesec == 9 || mesec == 11) {
return 30;
}
else if(mesec == 2) {
if((leto % 4 == 0 && leto % 100 != 0) || (leto % 100 == 0 && leto % 400 == 0)) {
return 29;
}
return 28;
}
return 31;
}
int main() {
int i,j,x,dnevi;
int steviloNedelj = 0;
int dan = 1;
for(i = 1901; i <= 2000; i++) {
for(j = 1; j <= 12; j++) {
dnevi = steviloDni(j,i);
for(x = 1; x <= dnevi; x++) {
dan++;
if(dan % 7 == 0 && x == 1) {
steviloNedelj++;
}
}
}
}
printf("Number of sundays from 1 Jan 1901 to 31 Dec 2000 is:\n");
printf("%d\n", steviloNedelj);
return 0;
} |
def invoke_server(self, request, _context):
message = request.msg
result = f'Sample server has started and received message {message} from client'
result = {
"msg":result,
"rcvd":True,
}
return pb2.FetchResponse(**result) |
"""Test coils."""
from mpf.platforms.interfaces.driver_platform_interface import PulseSettings, HoldSettings
from mpf.tests.MpfTestCase import MpfTestCase
from unittest.mock import MagicMock
class TestDeviceDriver(MpfTestCase):
def get_config_file(self):
return 'config.yaml'
def get_machine_path(self):
return 'tests/machine_files/device/'
def get_platform(self):
return 'smart_virtual'
def testBasicFunctions(self):
# Make sure hardware devices have been configured for tests
self.assertIn('coil_01', self.machine.coils)
self.assertIn('coil_02', self.machine.coils)
# Setup platform function mock to test coil
self.machine.coils["coil_01"].hw_driver.disable = MagicMock()
self.machine.coils["coil_01"].hw_driver.enable = MagicMock()
self.machine.coils["coil_01"].hw_driver.pulse = MagicMock()
self.machine.coils["coil_01"].enable()
self.machine.coils["coil_01"].hw_driver.enable.assert_called_with(PulseSettings(power=1.0, duration=30),
HoldSettings(power=1.0))
self.machine.coils["coil_01"].pulse(100)
self.machine.coils["coil_01"].hw_driver.pulse.assert_called_with(PulseSettings(power=1.0, duration=100))
self.machine.coils["coil_01"].disable()
self.machine.coils["coil_01"].hw_driver.disable.assert_called_with()
self.machine.coils["coil_03"].hw_driver.disable = MagicMock()
self.machine.coils["coil_03"].hw_driver.enable = MagicMock()
self.machine.coils["coil_03"].hw_driver.pulse = MagicMock()
# test default pulse_ms
self.machine.config['mpf']['default_pulse_ms'] = 23
self.machine.coils["coil_03"].pulse()
self.machine.coils["coil_03"].hw_driver.pulse.assert_called_with(PulseSettings(power=1.0, duration=23))
# test power
self.machine.config['mpf']['default_pulse_ms'] = 40
self.machine.coils["coil_03"].pulse(pulse_power=1.0)
self.machine.coils["coil_03"].hw_driver.pulse.assert_called_with(PulseSettings(power=1.0, duration=40))
self.machine.coils["coil_03"].pulse(pulse_power=0.5)
self.machine.coils["coil_03"].hw_driver.pulse.assert_called_with(PulseSettings(power=0.5, duration=40))
self.machine.coils["coil_01"].enable(pulse_power=0.7, hold_power=0.3)
self.machine.coils["coil_01"].hw_driver.enable.assert_called_with(PulseSettings(power=0.7, duration=30),
HoldSettings(power=0.3))
# test long pulse with delay
self.machine.coils["coil_03"].hw_driver.pulse = MagicMock()
self.machine.coils["coil_03"].hw_driver.enable = MagicMock()
self.machine.coils["coil_03"].hw_driver.disable = MagicMock()
self.machine.coils["coil_03"].pulse(pulse_ms=500)
self.machine.coils["coil_03"].hw_driver.enable.assert_called_with(PulseSettings(power=1.0, duration=0),
HoldSettings(power=1.0))
self.machine.coils["coil_03"].hw_driver.pulse.assert_not_called()
self.advance_time_and_run(.5)
self.machine.coils["coil_03"].hw_driver.disable.assert_called_with()
|
<gh_stars>100-1000
from collections import OrderedDict
import torch
import torch.nn as nn
from .bn import ABN
class DenseModule(nn.Module):
def __init__(self, in_chns, squeeze_ratio, out_chns, n_layers, dilate_sec=(1, 2, 4, 8, 16), norm_act=ABN):
super(DenseModule, self).__init__()
self.n_layers = n_layers
self.mid_out = int(in_chns * squeeze_ratio)
self.convs1 = nn.ModuleList()
self.convs3 = nn.ModuleList()
for idx in range(self.n_layers):
dilate = dilate_sec[idx % len(dilate_sec)]
self.last_channel = in_chns + idx * out_chns
"""
self.convs1.append(nn.Sequential(OrderedDict([
("bn", norm_act(self.last_channel)),
("conv", nn.Conv2d(self.last_channel, self.mid_out, 1, bias=False))
])))
"""
self.convs3.append(nn.Sequential(OrderedDict([
("bn", norm_act(self.last_channel)),
("conv", nn.Conv2d(self.last_channel, out_chns, kernel_size=3, stride=1,
padding=dilate, dilation=dilate, bias=False))
])))
@property
def out_channels(self):
return self.last_channel + 1
def forward(self, x):
inputs = [x]
for i in range(self.n_layers):
x = torch.cat(inputs, dim=1)
# x = self.convs1[i](x)
x = self.convs3[i](x)
inputs += [x]
return torch.cat(inputs, dim=1)
class DPDenseModule(nn.Module):
def __init__(self, in_chns, squeeze_ratio, out_chns, n_layers, dilate_sec=(1, 2, 4, 8, 16), norm_act=ABN):
super(DPDenseModule, self).__init__()
self.n_layers = n_layers
self.convs3 = nn.ModuleList()
for idx in range(self.n_layers):
dilate = dilate_sec[idx % len(dilate_sec)]
self.last_channel = in_chns + idx * out_chns
mid_out = int(self.last_channel * squeeze_ratio)
self.convs3.append(nn.Sequential(OrderedDict([("bn.1", norm_act(self.last_channel)),
("conv_up", nn.Conv2d(self.last_channel, mid_out,
kernel_size=1, stride=1, padding=0,
bias=False)),
("bn.2", norm_act(mid_out)),
("dconv", nn.Conv2d(mid_out, mid_out,
kernel_size=3, stride=1, padding=dilate,
groups=mid_out, dilation=dilate,
bias=False)),
("pconv", nn.Conv2d(mid_out, out_chns,
kernel_size=1, stride=1, padding=0,
bias=False)),
("dropout", nn.Dropout2d(p=0.2, inplace=True))])))
"""
self.convs3.append(nn.Sequential(OrderedDict([("bn.1", norm_act(self.last_channel)),
("dconv", nn.Conv2d(self.last_channel, self.last_channel,
kernel_size=3, stride=1, padding=dilate,
groups=self.last_channel, dilation=dilate,
bias=False)),
("pconv", nn.Conv2d(self.last_channel, out_chns,
kernel_size=1, stride=1, padding=0,
bias=False)),
("dropout", nn.Dropout2d(p=0.2, inplace=True))])))
"""
@property
def out_channels(self):
return self.last_channel + 1
def forward(self, x):
inputs = [x]
for i in range(self.n_layers):
x = torch.cat(inputs, dim=1)
x = self.convs3[i](x)
inputs += [x]
return torch.cat(inputs, dim=1)
|
Comment on R.T. Cook's Review of If A, Then B: How the World Discovered Logic
PrefaceIntroduction: What Is Logic?1. The Dawn of Logic2. Aristotle: Greatest of the Greek Logicians3. Aristotle's System: The Logic of Classification4. Chrysippus and the Stoics: A World of Interlocking Structures5. Logic Versus Antilogic: The Laws of Contradiction and Excluded Middle6. Logical Fanatics7. Will the Future Resemble the Past? Inductive Logic and Scientific Method8. Rhetorical Frauds and Sophistical Ploys: Ten Classic Tricks9. Symbolic Logic and the Digital Future10. Faith and the Limits of Logic: The Last Unanswered QuestionAppendix: Further FallaciesNotesBibliographyIndex |
<gh_stars>100-1000
import * as React from 'react';
import { BaseIconProps, iconDefaultProps } from '../../utils/types';
const IconUserRoundWarning: React.FC<BaseIconProps> = ({ size, fill, ...props }) => (
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" {...props}>
<path
d="M15.767 10.5a5.22 5.22 0 00-2.907.885 5.246 5.246 0 00-1.927 2.356 5.267 5.267 0 001.135 5.721A5.227 5.227 0 0017.77 20.6a5.237 5.237 0 002.348-1.933 5.263 5.263 0 00-.65-6.63 5.224 5.224 0 00-3.7-1.537zm-.06 8.25a.746.746 0 01-.69-.463.753.753 0 01.545-1.023.745.745 0 01.893.736.751.751 0 01-.747.75zm.748-3a.751.751 0 01-.747.75.746.746 0 01-.748-.75V13.5a.751.751 0 01.748-.75.746.746 0 01.747.75v2.25zM10.475 10.5a3.744 3.744 0 003.738-3.75A3.744 3.744 0 0010.475 3a3.744 3.744 0 00-3.737 3.75 3.744 3.744 0 003.737 3.75zM3 15.75v1.5c0 .597.236 1.169.657 1.591.42.422.99.659 1.586.659h4.94a6.713 6.713 0 010-7.5H6.739c-.992 0-1.942.395-2.643 1.098A3.756 3.756 0 003 15.75z"
fill={fill}
/>
</svg>
);
IconUserRoundWarning.defaultProps = {
...iconDefaultProps,
};
export default IconUserRoundWarning;
|
package customersvc
import (
"context"
"github.com/go-kit/kit/endpoint"
"github.com/google/uuid"
)
// Endpoints are the actions we would like to offer to the outside world.
// Because we implement a RESTful API on top of a CRUD service, our endpoints
// look similar to our service. This does not always need to be the case.
// Endpoints take a request, call service method(s), and return a result.
// Note that creating client endpoints is out-of-scope for this sample.
// CustomerEndpoints is a collection of all endpoints that we offer
type CustomerEndpoints struct {
GetCustomersEndpoint endpoint.Endpoint
GetCustomerEndpoint endpoint.Endpoint
AddCustomerEndpoint endpoint.Endpoint
DeleteCustomerEndpoint endpoint.Endpoint
PatchCustomerEndpoint endpoint.Endpoint
}
// MakeCustomerServerEndpoints creates endpoints for a given service
func MakeCustomerServerEndpoints(s CustomerService) CustomerEndpoints {
return CustomerEndpoints{
GetCustomersEndpoint: MakeGetCustomersEndpoint(s),
GetCustomerEndpoint: MakeGetCustomerEndpoint(s),
AddCustomerEndpoint: MakeAddCustomerEndpoint(s),
DeleteCustomerEndpoint: MakeDeleteCustomerEndpoint(s),
PatchCustomerEndpoint: MakePatchCustomerEndpoint(s),
}
}
// MakeGetCustomersEndpoint creates an endpoint for the "get customers" operation
func MakeGetCustomersEndpoint(s CustomerService) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
req := request.(getCustomersRequest)
c, e := s.GetCustomers(ctx, req.OrderBy)
return getCustomersResponse{Customers: c, Err: e}, nil
}
}
// MakeGetCustomerEndpoint creates an endpoint for the "get customer" operation
func MakeGetCustomerEndpoint(s CustomerService) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
req := request.(customerIDRequest)
c, e := s.GetCustomer(ctx, req.ID)
return customerResponse{Customer: c, Err: e}, nil
}
}
// MakeAddCustomerEndpoint creates an endpoint for the "add customer" operation
func MakeAddCustomerEndpoint(s CustomerService) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
req := request.(customerRequest)
c, e := s.AddCustomer(ctx, req.Customer)
return customerResponse{Customer: c, Err: e}, nil
}
}
// MakeDeleteCustomerEndpoint creates an endpoint for the "delete customer" operation
func MakeDeleteCustomerEndpoint(s CustomerService) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
req := request.(customerIDRequest)
e := s.DeleteCustomer(ctx, req.ID)
return deleteCustomerResponse{Err: e}, nil
}
}
// MakePatchCustomerEndpoint creates an endpoint for the "patch customer" operation
func MakePatchCustomerEndpoint(s CustomerService) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
req := request.(patchCustomerRequest)
c, e := s.PatchCustomer(ctx, req.CustomerID, req.Customer)
return customerResponse{Customer: c, Err: e}, nil
}
}
// Request and response types
type getCustomersRequest struct {
OrderBy string
}
type getCustomersResponse struct {
Customers []Customer `json:"customers,omitempty"`
Err error `json:"err,omitempty"`
}
type patchCustomerRequest struct {
CustomerID uuid.UUID
Customer Customer
}
// For the sake of brevity, we combine requests and responses with identical
// input/output parameters. Typically, every operation receives/responds with
// a unique set of parameters. Therefore, each endpoint often has its own
// request and response struct.
type customerIDRequest struct {
ID uuid.UUID
}
type customerResponse struct {
Customer Customer `json:"customer,omitempty"`
Err error `json:"err,omitempty"`
}
type customerRequest struct {
Customer Customer
}
type deleteCustomerResponse struct {
Err error `json:"err,omitempty"`
}
|
package com.imademethink_webautomation.UtilGeneral;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.PixelGrabber;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import javax.imageio.ImageIO;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ClsGeneralInitTerminateAndOtherUtil extends ClsGeneralConstants {
public void initilize_General_Supporting_Items(String strOther) {
//System.out.println("INFO: Initilize other supporting items");
// calling few mandatory init
init_Current_YearMonthDay_inNumbers();
switch (strOther) {
case "all":
// DB init
//System.out.println("DEBUG: Initilize DB handler");
// Init SQL database
// Connect to particular DB
// Excel or Apache POI handler
//System.out.println("DEBUG: Initilize excel or apache POI handler");
// Excel CSV file handler
//System.out.println("DEBUG: Initilize csv handler");
// Property file handler
//System.out.println("DEBUG: Initilize property file handler");
objPropMngr = new ClsPropertyManager();
objPropMngr.init_Property_File_Handler();
//strSinglePropertyValue = objPropMngr.single_Property_Getter("nWebsiteLoadTime");
//objPropMngr.single_Property_Setter("nWebsiteLoadTime", "25");
break;
case "DB":
// DB init
//System.out.println("DEBUG: Initilize DB handler");
// Init SQL database
// Connect to particular DB
break;
case "excel_apache_POI":
// Excel or Apache POI handler
//System.out.println("DEBUG: Initilize excel or apache POI handler");
break;
case "csv":
// CSV file handler
//System.out.println("DEBUG: Initilize csv handler");
break;
case "property_file_handler":
// Property file handler
//System.out.println("DEBUG: Initilize property file handler");
objPropMngr = new ClsPropertyManager();
objPropMngr.init_Property_File_Handler();
//strSinglePropertyValue = objPropMngr.single_Property_Getter("nWebsiteLoadTime");
//objPropMngr.single_Property_Setter("nWebsiteLoadTime", "25");
break;
default:
System.out.println("ERROR: Unsupported supporting item to initilise");
break;
}
}
public void terminate_General_Supporting_Items(String strOther) {
//System.out.println("INFO: Terminate other supporting items");
switch (strOther) {
case "all":
// DB terminate
//System.out.println("DEBUG: Terminate DB handler");
// terminate SQL database
// Disconnect to particular DB
// Excel or Apache POI handler terminate
//System.out.println("DEBUG: Terminate excel or apache POI handler");
// Excel CSV file handler terminate
//System.out.println("DEBUG: Terminate csv handler");
// Property file handler terminate
//System.out.println("DEBUG: Terminate property file handler");
objPropMngr = null;
break;
case "DB":
// DB terminate
//System.out.println("DEBUG: Terminate DB handler");
// terminate SQL database
// Disconnect to particular DB
break;
case "excel_apache_POI":
// Excel or Apache POI handler terminate
//System.out.println("DEBUG: Terminate excel or apache POI handler");
break;
case "csv":
// CSV file handler terminate
//System.out.println("DEBUG: Terminate csv handler");
break;
case "property_file_handler":
// Property file handler
//System.out.println("DEBUG: Terminate property file handler");
objPropMngr = null;
default:
System.out.println("ERROR: Unsupported supporting item to terminate");
break;
}
// terminating mandatory objects used for general purpose - in the same sequence if init
objSoftAssert = null;
}
// general helper methods
public static int getPositiveRandomNumberBetweenRange(int nMin, int nMax){
// for example nMin=0 and nMax=7 then it will return only following values i.e. 0, 1, 2, 3, 4, 5, 6, 7
if (nMin<0 || nMax<=0) return 0;
if (nMin > nMax) return nMin;
return nMin + new Random().nextInt(nMax - nMin + 1);
}
public static String getRandomString(int uExpected_NonZero_non_Negative_MaxStringLength){
if(uExpected_NonZero_non_Negative_MaxStringLength <=0) return "";
Random objRandom = new SecureRandom();
String strAlphabets = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
String strRandomString = "";
for (int i=0; i<uExpected_NonZero_non_Negative_MaxStringLength; i++)
{
int nRandomIndex = (int)(objRandom.nextDouble() * strAlphabets.length());
strRandomString += strAlphabets.charAt(nRandomIndex);
}
return strRandomString;
}
private static String getRandomNumericString(int uExpected_NonZero_non_Negative_MaxStringLength){
if(uExpected_NonZero_non_Negative_MaxStringLength <=0) return "";
Random objRandom = new SecureRandom();
String strNumericals = "012346789";
String strRandomString = "";
for (int i=0; i<uExpected_NonZero_non_Negative_MaxStringLength; i++)
{
int nRandomIndex = (int)(objRandom.nextDouble() * strNumericals.length());
strRandomString += strNumericals.charAt(nRandomIndex);
}
return strRandomString;
}
public static String getRandomFirstName(){
String strRandomFirstName = getRandomString(10);
strRandomFirstName = Character.toUpperCase(strRandomFirstName.charAt(0)) + strRandomFirstName.substring(1);
return strRandomFirstName;
}
public static String getRandomSecondName(){
String strRandomSecondName = getRandomString(10);
strRandomSecondName = Character.toUpperCase(strRandomSecondName.charAt(0)) + strRandomSecondName.substring(1);
return strRandomSecondName;
}
public static String getRandomAddress_IN(){
String strAddress_Part1 = "Flat No. " + getRandomNumericString(2) + " "; //e.g. Flat No. 22
String strAddress_Part2 = getRandomString(3) + " colony "; //e.g. abc colony
String strAddress_Part3 = getRandomString(4) + " district "; //e.g. xyzw
return strAddress_Part1 + strAddress_Part2 + strAddress_Part3;
}
public static String getRandomDrivingLicenceValue_IN(){
String strRandomDrivingLicenceValue = "DL-" + getRandomString(5) + getRandomNumericString(5) + getRandomString(5);
return strRandomDrivingLicenceValue;
}
public static String getRandomEmailId(){
String strEmailId_Part1 = getRandomString(4); //e.g. abcd
String strEmailId_Part2 = getRandomNumericString(6); //e.g. 01012010
String strEmailId_Part3 = getRandomString(4); //e.g. xyzw
String strEmailId_Part4 = "@"; // @
String strEmailId_Part5 = getRandomString(3); //e.g. gmail
String strEmailId_Part6 = ".com"; // .com
return strEmailId_Part1 + strEmailId_Part2 + strEmailId_Part3 + strEmailId_Part4 + strEmailId_Part5 + strEmailId_Part6;
}
public static String getRandomPassword(){
// most passsword patterns are more than 6 letterss, should contan - number, capital and small char, special character
String strPassword_Part1 = getRandomString(3); //e.g. abc
String strPassword_Part2 = getRandomNumericString(2); //e.g. 75
String strPassword_Part3 = "!"; //
String strPassword_Part4 = getRandomString(3); //e.g. xy
String strPassword = strPassword_Part1 + strPassword_Part2 + strPassword_Part3 + strPassword_Part4;
// make first letter uppercase
strPassword = Character.toUpperCase(strPassword.charAt(0)) + strPassword.substring(1);
return strPassword;
}
public static String getRandomBirthDate(){
// min 1 max is 28 fo all months
return Integer.toString(ClsGeneralInitTerminateAndOtherUtil.getPositiveRandomNumberBetweenRange(1,28));
}
public static String getRandomBirthMonth(){
// min 1 max 12
return Integer.toString(ClsGeneralInitTerminateAndOtherUtil.getPositiveRandomNumberBetweenRange(1,12));
}
public static String getRandomBirthYear_Infant(){
// min 1 max 2
return Integer.toString(nCurrentYear_YYYY - getPositiveRandomNumberBetweenRange(1,2));
}
public static String getRandomBirthYear_Child(){
// min 5 max 10
return Integer.toString(nCurrentYear_YYYY - getPositiveRandomNumberBetweenRange(5,10));
}
public static String getRandomBirthYear_Adult(){
// min 20 max 55
return Integer.toString(nCurrentYear_YYYY - getPositiveRandomNumberBetweenRange(20,55));
}
public static String getRandomAge_Adult(){
// min 20 max 55
return Integer.toString(getPositiveRandomNumberBetweenRange(20,55));
}
public static String getRandomMobileNumber_IN(){
String[] strArrRandomMobileNumber = {
"9211567079","7418171234","8144649589","9841131209","9760828535",
"9884145636","9543575185","9937903333","7092335544","9900093523",
"8087473557","9822012345","9869012345","9996243333","9166007251",
"7812056277","9940300951","8882099318"};
return strArrRandomMobileNumber[getPositiveRandomNumberBetweenRange(0,(strArrRandomMobileNumber.length -1))];
}
private static int[] init_Current_YearMonthDay_inNumbers(){
//System.out.println("DEBUG: Initilize mandatory date handler");
int[] nArr_Current_YearMonthDay= {-1,-1,-1};
Date objDateLocal = new Date();
Calendar objCalendarLocal = Calendar.getInstance();
objCalendarLocal.setTime(objDateLocal);
// int number_date = objCalendarLocal.get(Calendar.DATE);
// int number_month = objCalendarLocal.get(Calendar.MONTH);
// int number_year = objCalendarLocal.get(Calendar.YEAR);
nArr_Current_YearMonthDay[0] = Math.abs(objCalendarLocal.get(Calendar.YEAR));
nArr_Current_YearMonthDay[1] = Math.abs(objCalendarLocal.get(Calendar.MONTH)) + 1; // due to Java implementation need to add +1 to months count
nArr_Current_YearMonthDay[2] = Math.abs(objCalendarLocal.get(Calendar.DATE));
nCurrentYear_YYYY = nArr_Current_YearMonthDay[0];
nCurrentMonth_MM = nArr_Current_YearMonthDay[1] + 1; // due to Java implementation need to add +1 to months count
nCurrentDate_DD = nArr_Current_YearMonthDay[2];
objDateLocal = null;
objCalendarLocal = null;
return nArr_Current_YearMonthDay;
}
public int[] get_Current_YearMonthDay_integerArray(){
int[] nArr_Current_YearMonthDay= {nCurrentYear_YYYY,nCurrentMonth_MM,nCurrentDate_DD};
return nArr_Current_YearMonthDay;
}
@SuppressWarnings("deprecation")
public int[] get_UpdatedDate_YearMonthDay_integerArray(int nYeartoAdd,int nMonthtoAdd,int nDatetoAdd){
nYeartoAdd = Math.abs(nYeartoAdd);
nMonthtoAdd = Math.abs(nMonthtoAdd);
nDatetoAdd = Math.abs(nDatetoAdd);
Date objDateLocal = new Date();
Calendar objCalendarLocal = Calendar.getInstance();
objCalendarLocal.setTime(objDateLocal);
// update date - which will auto update date and month and year
objDateLocal.setDate(nCurrentDate_DD + nDatetoAdd);
objCalendarLocal.setTime(objDateLocal);
// update month - which will auto update month and year
objDateLocal.setMonth(nCurrentMonth_MM + nMonthtoAdd);
objCalendarLocal.setTime(objDateLocal);
// update year - which will auto update year
objDateLocal.setYear(nCurrentYear_YYYY + nYeartoAdd);
objCalendarLocal.setTime(objDateLocal);
int[] nArr_Current_YearMonthDay= {
objCalendarLocal.get(Calendar.YEAR),
objCalendarLocal.get(Calendar.MONTH),
objCalendarLocal.get(Calendar.DATE) };
return nArr_Current_YearMonthDay;
}
@SuppressWarnings({ "deprecation" })
public static int[] get_NextFriday_YearMonthDay_integerArray(){
Date objDateLocal = new Date();
Calendar objCalendarLocal = Calendar.getInstance();
int nLocal_DD = 0;
int nLocal_MM = 0;
objCalendarLocal.setTime(objDateLocal);
nLocal_DD = objCalendarLocal.get(Calendar.DATE);
nLocal_MM = objCalendarLocal.get(Calendar.MONTH);
int nLocal_MaxDayCount = objCalendarLocal.getActualMaximum(Calendar.DAY_OF_MONTH);
if(nLocal_MM == 1 ){ // Feb is actually 1
if(nLocal_DD > 23){
objCalendarLocal.set(Calendar.MONTH, Calendar.MONTH + 1);
objDateLocal.setMonth(objCalendarLocal.get(Calendar.MONTH));}
}else{
if(nLocal_DD > 25 && nLocal_MaxDayCount == 31){
objCalendarLocal.set(Calendar.MONTH, Calendar.MONTH + 1);
objDateLocal.setMonth(objCalendarLocal.get(Calendar.MONTH));
nLocal_MM = objDateLocal.getMonth();
if(nLocal_MM > 11){
objCalendarLocal.set(Calendar.YEAR, Calendar.YEAR+ 1);
objDateLocal.setYear(objCalendarLocal.get(Calendar.YEAR));}
}
if(nLocal_DD > 24 && nLocal_MaxDayCount == 30){
objCalendarLocal.set(Calendar.MONTH, Calendar.MONTH + 1);
objDateLocal.setMonth(objCalendarLocal.get(Calendar.MONTH));}
}
objCalendarLocal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
objDateLocal.setDate(objCalendarLocal.get(Calendar.DATE) + 7);
objCalendarLocal.setTime(objDateLocal);
int[] nArr_Current_YearMonthDay= {
objCalendarLocal.get(Calendar.YEAR),
objCalendarLocal.get(Calendar.MONTH) + 1, // due to Java implementation need to add +1 to months count
objCalendarLocal.get(Calendar.DATE) };
return nArr_Current_YearMonthDay;
}
@SuppressWarnings("deprecation")
public static int[] get_NextSunday_YearMonthDay_integerArray(){
Date objDateLocal = new Date();
Calendar objCalendarLocal = Calendar.getInstance();
int nLocal_DD = 0;
int nLocal_MM = 0;
objCalendarLocal.setTime(objDateLocal);
nLocal_DD = objCalendarLocal.get(Calendar.DATE);
nLocal_MM = objCalendarLocal.get(Calendar.MONTH);
int nLocal_MaxDayCount = objCalendarLocal.getActualMaximum(Calendar.DAY_OF_MONTH);
if(nLocal_MM == 1 ){ // Feb is actually 1
if(nLocal_DD > 23){
objCalendarLocal.set(Calendar.MONTH, Calendar.MONTH + 1);
objDateLocal.setMonth(objCalendarLocal.get(Calendar.MONTH));}
}else{
if(nLocal_DD > 25 && nLocal_MaxDayCount == 31){
objCalendarLocal.set(Calendar.MONTH, Calendar.MONTH + 1);
objDateLocal.setMonth(objCalendarLocal.get(Calendar.MONTH));
nLocal_MM = objDateLocal.getMonth();
if(nLocal_MM > 11){
objCalendarLocal.set(Calendar.YEAR, Calendar.YEAR+ 1);
objDateLocal.setYear(objCalendarLocal.get(Calendar.YEAR));}
}
if(nLocal_DD > 24 && nLocal_MaxDayCount == 30){
objCalendarLocal.set(Calendar.MONTH, Calendar.MONTH + 1);
objDateLocal.setMonth(objCalendarLocal.get(Calendar.MONTH));}
}
objCalendarLocal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
objDateLocal.setDate(objCalendarLocal.get(Calendar.DATE) + 9);
objCalendarLocal.setTime(objDateLocal);
int[] nArr_Current_YearMonthDay= {
objCalendarLocal.get(Calendar.YEAR),
objCalendarLocal.get(Calendar.MONTH) + 1, // due to Java implementation need to add +1 to months count
objCalendarLocal.get(Calendar.DATE) };
return nArr_Current_YearMonthDay;
}
@SuppressWarnings("deprecation")
public static String[] get_NextFriday_YearMonthDay_stringArray(){
Date objDateLocal = new Date();
Calendar objCalendarLocal = Calendar.getInstance();
int nLocal_DD = 0;
int nLocal_MM = 0;
objCalendarLocal.setTime(objDateLocal);
nLocal_DD = objCalendarLocal.get(Calendar.DATE);
nLocal_MM = objCalendarLocal.get(Calendar.MONTH);
int nLocal_MaxDayCount = objCalendarLocal.getActualMaximum(Calendar.DAY_OF_MONTH);
if(nLocal_MM == 2 ){
if(nLocal_DD > 23){
objCalendarLocal.set(Calendar.MONTH, Calendar.MONTH + 1);
objDateLocal.setMonth(objCalendarLocal.get(Calendar.MONTH));}
}else{
if(nLocal_DD > 25 && nLocal_MaxDayCount == 31){
objCalendarLocal.set(Calendar.MONTH, Calendar.MONTH + 1);
objDateLocal.setMonth(objCalendarLocal.get(Calendar.MONTH));
nLocal_MM = objDateLocal.getMonth();
if(nLocal_MM > 11){
objCalendarLocal.set(Calendar.YEAR, Calendar.YEAR+ 1);
objDateLocal.setYear(objCalendarLocal.get(Calendar.YEAR));}
}
if(nLocal_DD > 24 && nLocal_MaxDayCount == 30){
objCalendarLocal.set(Calendar.MONTH, Calendar.MONTH + 1);
objDateLocal.setMonth(objCalendarLocal.get(Calendar.MONTH));}
}
objCalendarLocal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
objDateLocal.setDate(objCalendarLocal.get(Calendar.DATE) + 7);
objCalendarLocal.setTime(objDateLocal);
String[] strArr_Current_YearMonthDay= {
Integer.toString(objCalendarLocal.get(Calendar.YEAR)),
// due to Java implementation need to add +1 to months count but it's weird hee
objCalendarLocal.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault()),
Integer.toString(objCalendarLocal.get(Calendar.DATE)) };
return strArr_Current_YearMonthDay;
}
@SuppressWarnings("deprecation")
public static String[] get_NextSunday_YearMonthDay_stringArray(){
Date objDateLocal = new Date();
Calendar objCalendarLocal = Calendar.getInstance();
int nLocal_DD = 0;
int nLocal_MM = 0;
objCalendarLocal.setTime(objDateLocal);
nLocal_DD = objCalendarLocal.get(Calendar.DATE);
nLocal_MM = objCalendarLocal.get(Calendar.MONTH);
int nLocal_MaxDayCount = objCalendarLocal.getActualMaximum(Calendar.DAY_OF_MONTH);
if(nLocal_MM == 2 ){
if(nLocal_DD > 23){
objCalendarLocal.set(Calendar.MONTH, Calendar.MONTH + 1);
objDateLocal.setMonth(objCalendarLocal.get(Calendar.MONTH));}
}else{
if(nLocal_DD > 25 && nLocal_MaxDayCount == 31){
objCalendarLocal.set(Calendar.MONTH, Calendar.MONTH + 1);
objDateLocal.setMonth(objCalendarLocal.get(Calendar.MONTH));
nLocal_MM = objDateLocal.getMonth();
if(nLocal_MM > 11){
objCalendarLocal.set(Calendar.YEAR, Calendar.YEAR+ 1);
objDateLocal.setYear(objCalendarLocal.get(Calendar.YEAR));}
}
if(nLocal_DD > 24 && nLocal_MaxDayCount == 30){
objCalendarLocal.set(Calendar.MONTH, Calendar.MONTH + 1);
objDateLocal.setMonth(objCalendarLocal.get(Calendar.MONTH));}
}
objCalendarLocal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
objDateLocal.setDate(objCalendarLocal.get(Calendar.DATE) + 9);
objCalendarLocal.setTime(objDateLocal);
String[] strArr_Current_YearMonthDay= {
Integer.toString(objCalendarLocal.get(Calendar.YEAR)),
// due to Java implementation need to add +1 to months count but it's weird hee
objCalendarLocal.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault()),
Integer.toString(objCalendarLocal.get(Calendar.DATE)) };
return strArr_Current_YearMonthDay;
}
public boolean checkStringContains(String strSrc, String strDst) {
if (strSrc.contains(strDst)) { return true;}
else{ return false;}
}
public static String[] splitThisString(String strInput, String splitPattern) {
String[] strArySplitedListLocal = strInput.trim().split(splitPattern);
return strArySplitedListLocal;
}
public static List<Object> process_Images_to_Compare(String strImageNameContains, URL objURLMainPageLogo){
List<Object> lstGeneralObjectsLocal = new ArrayList<Object>();
lstGeneralObjectsLocal.add(false); // overall status
lstGeneralObjectsLocal.add(null); // strRefImagePath
lstGeneralObjectsLocal.add(null); // strActualImagePath
String strImageFormat = null;
String strRefImagePath = null;
String strActualImagePath = null;
String strCleanAbsolutePath = new File(".").getAbsolutePath().replace(".","");
String strRefImagePathTemp = strCleanAbsolutePath +
objPropMngr.single_Property_Getter("strReferenceImagesRelativePath") +
strCurrentWebsiteUnderTest +
strImageNameContains;
if( new File(strRefImagePathTemp+".png").exists() && ! new File(strRefImagePathTemp+".png").isDirectory()) {
strImageFormat="png"; // File exists with .png extension
}else if(new File(strRefImagePathTemp+".jpg").exists() && ! new File(strRefImagePathTemp+".jpg").isDirectory()) {
strImageFormat="jpg"; // File exists with .jpg extension
}else{
// no valid file exists or not from supported format png, jpg, gif
System.out.println("ERROR: Reference home page image file not found or not from supported format png, jpg, gif");
return lstGeneralObjectsLocal;
}
strRefImagePath = strRefImagePathTemp + "." + strImageFormat;
strActualImagePath = strRefImagePath.replace("reference_", "actual_");
// read main page logo image into a buffer
BufferedImage objBufferedImg= null;
try {objBufferedImg = ImageIO.read(objURLMainPageLogo);}
catch (MalformedURLException e) {System.out.println("ERROR: Unable to read main page image into image buffer MalformedURLException"); return lstGeneralObjectsLocal;}
catch (IOException e) {System.out.println("ERROR: Unable to read main page image into image buffer"); return lstGeneralObjectsLocal;}
catch (Exception e) {System.out.println("ERROR: Unable to read main page image"); return lstGeneralObjectsLocal;}
// dump actual image in folder
try {ImageIO.write(objBufferedImg, strImageFormat, new File(strActualImagePath));}
catch (IOException e) {System.out.println("ERROR: Unable to write main page image into image buffer IOException"); return lstGeneralObjectsLocal;}
catch (Exception e) {System.out.println("ERROR: Unable to write main page image into image buffer other exception"); return lstGeneralObjectsLocal;}
lstGeneralObjectsLocal.set(0, true);
lstGeneralObjectsLocal.set(1, strRefImagePath); // strRefImagePath
lstGeneralObjectsLocal.set(2, strActualImagePath); // strActualImagePath
return lstGeneralObjectsLocal;
}
public static boolean utility_ImageCompare(String strRefImagePath, String strNewImagePath) {
Image image1 = Toolkit.getDefaultToolkit().getImage(strRefImagePath);
Image image2 = Toolkit.getDefaultToolkit().getImage(strNewImagePath);
if (null==image1) {System.out.println("ERROR: First image is either not present or invalid"); return false;}
else if (null==image2){System.out.println("ERROR: Second image is either not present or invalid"); return false;}
try {
PixelGrabber grab1 =new PixelGrabber(image1, 0, 0, -1, -1, false);
PixelGrabber grab2 =new PixelGrabber(image2, 0, 0, -1, -1, false);
int[] data1 = null;
if (grab1.grabPixels()) {
int width = grab1.getWidth();
int height = grab1.getHeight();
data1 = new int[width * height];
data1 = (int[]) grab1.getPixels();
}
int[] data2 = null;
if (grab2.grabPixels()) {
int width = grab2.getWidth();
int height = grab2.getHeight();
data2 = new int[width * height];
data2 = (int[]) grab2.getPixels();
}
if (java.util.Arrays.equals(data1, data2)){ System.out.println("DEBUG: Reference and actual both images are identical"); return true;}
else{ System.out.println("ERROR: Reference and actual both images are NOT identical"); return false;}
}
catch (InterruptedException e1) { System.out.println("ERROR: InterruptedException generated while comparing both images"); return false;}
catch (Exception e1) { System.out.println("ERROR: Exception generated while comparing both images"); return false;}
}
public static void utilgeneral_GetScreenshot(FirefoxDriver RINwebdriver_ffTemp, String strScreenshotSavingPathTemp) {
String strdateANDtime = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
String strScreenshotSavingPathTempFull = strScreenshotSavingPathTemp + "/screenshot_" + strdateANDtime + ".png";
System.out.println("----Screenshot procedure initiated.");
File scrFile = ((TakesScreenshot)RINwebdriver_ffTemp).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(scrFile, new File(strScreenshotSavingPathTempFull));
} catch (IOException e) {System.out.println("-----Exception while saving the sceenshot file");}
System.out.println("----Screenshot is saved at following path: " + strScreenshotSavingPathTempFull);
}
public static void JUST_________________________________________SLEEP(int nnMilliSeconds){
try {
Thread.sleep(nnMilliSeconds);
} catch (InterruptedException e) {}
}
}
|
from fastapi import Depends, Response
from fastapi.routing import APIRouter
from pydantic import BaseModel # pylint: disable=E0611
from sqlmodel import Session, select
from starlette.responses import JSONResponse
from fastapi_server.database.database import get_session
from fastapi_server.models.user import User
login_router = APIRouter()
class LoginModel(BaseModel):
email: str
password: str
# TODO: Replace /login endpoint when Response is available in strawberry query info-context
@login_router.post('/login')
async def login(login_data: LoginModel, session: Session = Depends(get_session)) -> Response:
statement = select(User).where(User.email == login_data.email, User.password_hashed == login_data.password)
user = session.exec(statement).first()
if user is None:
raise FileNotFoundError('Email and password do not match')
# Set message and cookies in frontend
content = {'message': 'Come to the dark side, we have cookies'}
response = JSONResponse(content=content)
response.set_cookie(key='fakesession', value='fake-cookie-session-value', httponly=True, secure=True, expires=3600)
return response
|
I loved my Grandpa Jack. He smoked. He drank. He enjoyed his coffee. And….he was perhaps the best Mormon I have ever known. He didn’t go to church. I never really had any long conversation with him. But, I knew the stories. He was a man’s man. Hardworking and generous.
Today, I had a conversation with a Facebook friend. He shared a story about his grandpa. It brought tears as I realized that the character of his grandfather had a lot in common with my Grandpa Jack.
My friend’s name is Ben Jarvis and here’s his grandpa’s story.
Twenty-two years ago, when I was talking to my 84 year-old, hard scrabble grandpa about being gay. He said he didn’t raise his kids or grandkids to be second class citizens. He expected me to fight for my rights, and when that was done, go fight for the rights of others…and to take on the world! He was quite progressive for a man from SLC and the Uintah Basin.
Grandpa was very active in his ward, but he took the church on his own terms and always asserted his individuality and had strong sense of right and wrong. He once clocked the stake president for stealing water out of turn. When the stake president came to, he had a shovel blade on his neck, with my grandfather, then an angry 12-year old, telling him the farm relied on water and he didn’t take kindly to water thieves. That would have been around 1921 or 1922.
In 1991, Gramp and I were working in his garden. He started in on the church and about how some people get caught up in the temple or the idea they need to go somewhere to find God. He then talked about the miracle of life and how he planted seeds that magically grew. “I don’t need to go to the temple to be with God. God is right here in the dirt.” Those were the words of a lifelong farmer.
My family got a lot of things right. I had the good fortune to come out to three of my grandparents; my maternal grandfather passed away before I came out. My parents were big proponents of being honest about who we are, and encouraged LGBT people to come out and be visible. When my nephew learned to speak and began presenting as female, mom and dad, along with my sister, embraced her and accepted her transition. My niece is now five years old. Mom passed away last year, her granddaughter will grow up knowing her nana knew her, loved her, and was thrilled to have her as a granddaughter. We aren’t talking tolerance or tepid accommodation. We are talking about unbridled love, acceptance, and the anticipation of a life filled with adventure, just like any of mom and dad’s other grandchildren.
I still can’t read this story without tearing up at the beauty of this whole family. ‘Fight for your rights and then go fight for the rights of others.’ What an amazing legacy from Grandpa Jarvis. A great man who found God in the dirt.
Ben, thank you, my friend, for sharing. |
import React from 'react';
import { mount } from 'enzyme';
import { act } from 'react-dom/test-utils';
import mountTest from '../../../tests/mountTest';
import componentConfigTest from '../../../tests/componentConfigTest';
import Comment from '..';
import Avatar from '../../Avatar';
import Button from '../../Button';
mountTest(Comment);
componentConfigTest(Comment, 'Comment');
describe('Comment', () => {
it('render basic Comment', () => {
const actions = new Array(5).fill(5).map((_, index) => (
<Button key={index} className="customer-actions">
{index}
</Button>
));
const wrapper = mount(
<Comment
actions={actions}
author="Socrates"
avatar={
<Avatar>
<img
alt="avatar"
src="//p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/5ee428f1389b4291b1f9bbd82b24105d~tplv-uwbnlip3yd-image.image"
/>
</Avatar>
}
content={<div>Comment body content.</div>}
datetime="1 hour"
/>
);
expect(wrapper.find('Avatar')).toHaveLength(1);
expect(wrapper.find('.arco-comment-actions').find('Button')).toHaveLength(5);
expect(wrapper.find('.arco-comment-datetime').text()).toEqual('1 hour');
expect(wrapper.find('.arco-comment-content').text()).toEqual('Comment body content.');
});
it('render align right actions', () => {
const wrapper = mount(
<Comment
actions={[<Button key={1}>actions</Button>]}
content={<div>Comment body content.</div>}
datetime="1 hour"
/>
);
expect(
wrapper.find('.arco-comment-actions').hasClass('arco-comment-actions-align-left')
).toBeTruthy();
expect(
wrapper.find('.arco-comment-title').hasClass('arco-comment-title-align-left')
).toBeTruthy();
act(() => {
wrapper.setProps({
align: {
datetime: 'right',
},
});
});
expect(wrapper.find('.arco-comment-title-align-right')).toHaveLength(1);
act(() => {
wrapper.setProps({
align: 'right',
});
});
expect(wrapper.find('.arco-comment-actions-align-right')).toHaveLength(1);
});
it('render children Node correctly', () => {
const wrapper = mount(
<Comment>
<Comment>
<Comment />
</Comment>
</Comment>
);
expect(wrapper.find('.arco-comment-inner-content')).toHaveLength(3);
});
});
|
import numpy as np
H,W = map(int,input().split())
N = int(input())
lsa = list(map(int,input().split()))
ls2 = []
for i in range(N):
ls2 += [i+1]*lsa[i]
arr = np.array(ls2)
arr = arr.reshape(H,W).tolist()
arr2 = []
for i in range(H):
if i % 2 == 0:
arr2.append(arr[i])
else:
arr[i].reverse()
arr2.append(arr[i])
for i in range(H):
arr2[i] = [str(j) for j in arr2[i]]
print(' '.join(arr2[i])) |
package com.revature.controllers;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import com.google.gson.Gson;
import com.revature.entities.Appointment;
import com.revature.entities.Doctor;
import com.revature.entities.Patient;
import com.revature.entities.Practice;
import com.revature.entities.Specialty;
import com.revature.services.AppointmentServ;
import com.revature.services.AvailabilityServ;
import com.revature.services.DoctorServ;
import com.revature.services.PatientServ;
@AutoConfigureMockMvc
@SpringBootTest(classes = com.revature.demo.Project2DfApplication.class)
public class AppointmentControllerTests {
@MockBean
AppointmentServ as;
@MockBean
AvailabilityServ avs;
@MockBean
DoctorServ ds;
@MockBean
PatientServ ps;
@Autowired
MockMvc mvc;
Gson gson = new Gson();
@Test
void loadAppointments() throws Exception {
Specialty spec= new Specialty(10, "Neurologist");
Practice prac = new Practice(101,"0800","2200","Address","London","Co",80037);
Doctor doc = new Doctor(1, "<EMAIL>", "Scott", "Reisdorf", "password", 12, "Very Good", "SCTCC", spec, prac);
List<Appointment> appts = new ArrayList();
appts.add(new Appointment());
Mockito.when(ds.getDoctorById(1)).thenReturn(doc);
Mockito.when(as.getAllAppointmentsByDocId(doc)).thenReturn(appts);
ResultActions ra = mvc.perform(get("/loadAppointments/1"));
ra.andExpect(status().isOk());
}
@Test
void loadPatientAppointments() throws Exception {
Patient p = new Patient("A", "K", "email","password", "<PASSWORD>");
List<Appointment> appts = new ArrayList();
appts.add(new Appointment());
Mockito.when(ps.getPatientById(1)).thenReturn(p);
Mockito.when(as.getAllAppointmentsByPatientId(p)).thenReturn(appts);
ResultActions ra = mvc.perform(get("/loadPatientAppt/1"));
ra.andExpect(status().isOk());
}
// @Test
// void bookAppointment() throws Exception {
// Patient p = new Patient("A", "K", "email","password", "<PASSWORD>");
// Specialty spec= new Specialty(10, "Neurologist");
// Practice prac = new Practice(101,"0800","2200","Address","London","Co",80037);
// Doctor doc = new Doctor(1, "<EMAIL>", "Scott", "Reisdorf", "password", 12, "Very Good", "SCTCC", spec, prac);
// Appointment a = new Appointment(1, LocalDateTime.now(), LocalDateTime.now(), doc, p, "looks good", "Available");
// Mockito.when(as.bookAppointment(a)).thenReturn(a);
// Mockito.when(avs.cancelAvailibity("1")).thenReturn(true);
//
// ResultActions ra = mvc.perform(post("/bookAppointment").contentType(MediaType.APPLICATION_JSON).content(gson.toJson(a)).queryParam("id", "1"));
// ra.andExpect(status().isOk());
// }
@Test
void deleteAppointment() throws Exception {
Mockito.when(as.deleteAppointment(1)).thenReturn(true);
ResultActions ra = mvc.perform(delete("/deleteappointment/1"));
ra.andExpect(status().isOk());
}
}
|
<reponame>ricardoekm/SandDance
// Copyright (c) 2015 - 2017 Uber Technologies, Inc.
//
// 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.
import { min3dDepth, minPixelSize } from '../defaults';
export default `\
#define SHADER_NAME cube-layer-vertex-shader
attribute vec3 positions;
attribute vec3 normals;
attribute vec3 instancePositions;
attribute vec3 instancePositions64Low;
attribute vec3 instanceSizes;
attribute vec4 instanceColors;
attribute vec3 instancePickingColors;
// Custom uniforms
uniform float lightingMix;
// Result
varying vec4 vColor;
void main(void) {
float x = instanceSizes.x > 0.0 ? max(instanceSizes.x, ${minPixelSize.toFixed(1)}) : 0.0;
float y = instanceSizes.y > 0.0 ? max(instanceSizes.y, ${minPixelSize.toFixed(1)}) : 0.0;
// if alpha == 0.0, do not render element
float noRender = float(instanceColors.a == 0.0);
float finalXScale = project_size(x) * mix(1.0, 0.0, noRender);
float finalYScale = project_size(y) * mix(1.0, 0.0, noRender);
float finalZScale = project_size(instanceSizes.z) * mix(1.0, 0.0, noRender);
// cube geometry vertics are between -1 to 1, scale and transform it to between 0, 1
vec3 offset = vec3(
(positions.x + 1.0) / 2.0 * finalXScale,
(positions.y + 1.0) / 2.0 * finalYScale,
(positions.z + 1.0) / 2.0 * finalZScale);
// extrude positions
vec4 position_worldspace;
gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset, position_worldspace);
vec3 lightColor = lighting_getLightColor(instanceColors.rgb, project_uCameraPosition, position_worldspace.xyz, project_normal(normals));
vec3 mixedLight = mix(instanceColors.rgb, lightColor, lightingMix);
vec4 color = vec4(mixedLight, instanceColors.a) / 255.0;
vColor = color;
// Set color to be rendered to picking fbo (also used to check for selection highlight).
picking_setPickingColor(instancePickingColors);
}
`;
|
<filename>src/main/java/de/uni_leipzig/digital_text_forensics/preprocessing/DBLPXMLConstants.java
package de.uni_leipzig.digital_text_forensics.preprocessing;
public class DBLPXMLConstants {
public static final String ARTICLE = "article";
public static final String AUTHOR = "author";
public static final String TITLE = "title";
public static final String PAGES = "pages";
public static final String JOURNAL = "journal";
public static final String YEAR = "year";
public static final String EE = "ee";
} |
import os
import numpy as np
import sys
import vtk
import utils
import label_io
class Geometry(object):
def __init__(self, vtk_poly, edge_size=1.):
self.poly = vtk_poly
self.edge_size = edge_size
def getVolume(self):
return utils.getPolydataVolume(self.poly)
def writeSurfaceMesh(self, fn):
label_io.writeVTKPolyData(self.poly, fn)
def writeVolumeMesh(self, fn):
label_io.writeVTUFile(self.ug, fn)
def splitRegion(self, region_id, attr='ModelFaceID'):
return utils.thresholdPolyData(self.poly, attr, (region_id, region_id))
def remesh(self, edge_size, fn, poly_fn=None, ug_fn=None, mmg=True):
from sv import Repository
import meshing
self.edge_size = edge_size
if mmg:
Repository.ImportVtkPd(self.poly, "mmg_poly")
meshing.remeshPolyData("mmg_poly", "mmg_poly_remesh", 1.,1.5, fn)
self.writeSurfaceMesh(fn)
# generate volumetric mesh:
mesh_ops = {
'SurfaceMeshFlag': True,
'VolumeMeshFlag': True,
'GlobalEdgeSize': edge_size,
'MeshWallFirst': True,
'NoMerge':True,
'NoBisect': True,
'Epsilon': 1e-8,
'Optimization': 3,
'QualityRatio': 1.4
}
if poly_fn is None:
mesh_ops['SurfaceMeshFlag']=False
if ug_fn is None:
mesh_ops['VolumeMeshFlag']=False
meshing.meshPolyData(fn, (poly_fn, ug_fn), mesh_ops)
if poly_fn is not None:
self.poly = Repository.ExportToVtk(poly_fn)
if ug_fn is not None:
self.ug = Repository.ExportToVtk(ug_fn)
return poly_fn, ug_fn
def writeMeshComplete(self, path):
pass
class leftHeart(Geometry):
def __init__(self, vtk_poly, edge_size=1.):
super(leftHeart, self).__init__(vtk_poly, edge_size)
self.wall_processed = False
self.cap_processed = False
self.cap_pts_ids = None
def processWall(self, aa_cutter, aa_plane):
if self.wall_processed:
print("Left heart wall has been processed!")
return
self.poly = utils.cutPolyDataWithAnother(self.poly, aa_cutter,aa_plane)
self.poly = utils.fillHole(self.poly, size=25.)
id_lists,boundaries = utils.getPointIdsOnBoundaries(self.poly)
for idx, (ids, boundary) in enumerate(zip(id_lists, boundaries)):
boundary = utils.smoothVTKPolyline(boundary, 5)
self.poly = utils.projectOpeningToFitPlane(self.poly, ids, boundary.GetPoints(), self.edge_size)
# Remove the free cells and update the point lists
self.poly, id_lists[idx] = utils.removeFreeCells(self.poly, [idx for sub_l in id_lists for idx in sub_l])
self.poly = utils.smoothVTKPolydata(utils.cleanPolyData(self.poly, 0.), iteration=50)
self.wall_processed = True
return
def processCap(self, edge_size):
if self.cap_processed:
print("Caps have been processed!")
return
self.poly = utils.capPolyDataOpenings(self.poly, edge_size)
self.cap_processed = True
return
class leftVentricle(Geometry):
def __init__(self, vtk_poly, edge_size=1.):
super(leftVentricle, self).__init__(vtk_poly, edge_size)
self.wall_processed = False
self.cap_processed = False
self.cap_pts_ids = None
def processWall(self, la_cutter, la_plane, aa_cutter, aa_plane):
if self.wall_processed:
print("Left ventricle wall has been processed!")
return
# cut with la and aorta cutter:
self.poly = utils.cutPolyDataWithAnother(self.poly, la_cutter, la_plane)
self.poly = utils.cutPolyDataWithAnother(self.poly, aa_cutter, aa_plane)
#fill small cutting artifacts:
self.poly = utils.fillHole(self.poly, size=15.)
#improve valve opening geometry
id_lists,boundaries = utils.getPointIdsOnBoundaries(self.poly)
for idx, (ids, boundary) in enumerate(zip(id_lists, boundaries)):
boundary = utils.smoothVTKPolyline(boundary, 5)
self.poly = utils.projectOpeningToFitPlane(self.poly, ids, boundary.GetPoints(), self.edge_size)
# Remove the free cells and update the point lists
self.poly, id_lists[idx] = utils.removeFreeCells(self.poly, [idx for sub_l in id_lists for idx in sub_l])
self.poly = utils.smoothVTKPolydata(utils.cleanPolyData(self.poly, 0.), iteration=50)
self.wall_processed = True
return
def processCap(self, edge_size):
if self.cap_processed:
print("Caps have been processed!")
return
self.poly = utils.capPolyDataOpenings(self.poly, edge_size)
self.cap_processed = True
return
def getCapIds(self):
self.cap_pts_ids = list()
# good to assume region id mitral=2, aortic=3
for cap_id in (2,3):
self.cap_pts_ids.append(utils.findPointCorrespondence(self.poly, self.splitRegion(cap_id).GetPoints()))
def update(self, new_model):
if self.cap_pts_ids is None:
self.getCapIds()
# Project the cap points so that they are co-planar
for pt_ids in self.cap_pts_ids:
pts = utils.getPolyDataPointCoordinatesFromIDs(new_model, pt_ids)
new_model = utils.projectOpeningToFitPlane(new_model, pt_ids, pts, self.edge_size)
return new_model
def writeMeshComplete(self, path):
"""
Args:
path: path to the output folder
"""
if (self.poly is None) or (self.ug is None):
raise RuntimeError("No volume mesh has been generated.")
return
try:
os.makedirs(os.path.join(path))
except Exception as e: print(e)
fn_poly = os.path.join(path, 'mesh-complete.exterior.vtp')
fn_vol = os.path.join(path, 'mesh-complete.mesh.vtu')
self.writeVolumeMesh(fn_vol)
self.writeSurfaceMesh(fn_poly)
fn_wall = os.path.join(path, 'walls_combined.vtp')
label_io.writeVTKPolyData(self.splitRegion(1),fn_wall)
try:
os.makedirs(os.path.join(path, 'mesh-surfaces'))
except Exception as e: print(e)
for i in range(3):
face = self.splitRegion(i+1)
face_fn = os.path.join(path,'mesh-surfaces','noname_%d.vtp' % (i+1))
label_io.writeVTKPolyData(face, face_fn)
return
|
<reponame>icedevml/webcrypto-rsa-login
from flask import Flask, render_template
from redis import Redis
from redis_session import RedisSessionInterface
from cryptoauth_blueprint import signature_login_poc
class PublicKeyStorage:
def __init__(self, redis):
self.redis = redis
def fetch_user_pem(self, username):
return self.redis.get('user:{}:public_key'.format(username))
def store_user_pem(self, username, public_key_pem):
self.redis.set('user:{}:public_key'.format(username), public_key_pem)
app = Flask(__name__)
app.config.from_pyfile('config.py')
redis = Redis(**app.config['REDIS_CONFIG'])
app.extensions['public_keys'] = PublicKeyStorage(redis)
app.session_interface = RedisSessionInterface(redis)
app.debug = True
app.register_blueprint(signature_login_poc)
@app.after_request
def add_csp(response):
response.headers['Content-Security-Policy'] = app.config['CSP_HEADER']
return response
@app.route('/')
def main():
return render_template('main.html')
if __name__ == '__main__':
app.run()
|
This week, Drs. Thomas Frieden and Anthony Fauci, director of the Centers for Disease Control and Prevention and director of the National Institute of Infectious Diseases respectively, doubled down on their propaganda, illogic and misrepresentations regarding the procedures for handling the Ebola virus and the dynamics of contagion.
On Fox News’ “The Kelly File” Tuesday, Frieden gave nebulous assurances that all possible precautions were being taken to combat the spread of Ebola in the U.S., and stated that “we’ve been treating Ebola for decades.”
Yes, they have – but all of this experience has been restricted to the African continent, where conditions are so abysmal that absolute containment has been the norm. This has included quarantines, travel bans, martial law and the burning of entire villages after outbreaks. As far as treatment goes, the only thing anyone has been able to do for Ebola patients to date is to make them as comfortable as possible until they either recover or die.
The exposure to Westerners working in these areas during this decades-long learning curve has also been extremely limited.
The same evening, Dr. Fauci told Fox’s Greta Van Susteren that Americans shouldn’t worry about terrorists using Ebola as a bioterror weapon because it would be “ineffective” as such. Ebola is classified as a Category A bioterrorism agent by the Centers for Disease Control and Prevention. This means that the CDC believes Ebola has the potential to be weaponized for use in biological warfare – so I don’t know how Fauci gets off repeatedly making this claim.
One phenomenon that aroused my suspicions is the extent of the current Ebola outbreak in West Africa. Let me explain.
Dr. Frieden said on Fox that the international medical community had been treating people with Ebola “for decades.” Leaving aside his demonstrably fallacious attendant statements, this would tend to suggest that the international medical community would have been able to address the most recent outbreak more effectively, rather than less effectively.
Yet the numbers say otherwise. According to the World Health Organization (WHO), the first known outbreak of Ebola was in the early summer of 1976 in Sudan. The outbreak infected nearly 300 people and killed 151. The second occurred in August of 1976 in the Democratic Republic of the Congo; this one killed 280 people. Another outbreak occurred in 1995, again in the Democratic Republic of Congo. It sickened 315 and killed 254. An outbreak in Uganda in 2000 killed 224. In 2003 there was another outbreak in the Republic of Congo that killed 128.
In August of 2007, yet another outbreak in the Congo killed 187 individuals; in November of the same year, 37 people died during an outbreak in Uganda. Then, in 2012, several smaller outbreaks in the Congo resulted in the deaths of 50 people.
As one can see, the numbers were trending downward with each of the Ebola outbreaks in later years. This is in keeping with the increased knowledge of how the disease spreads and methods of containment.
In December of 2013, however, the World Health Organization reported the beginnings of the most recent outbreak in Guinea. After the disease spread to the neighboring countries of Liberia and Sierra Leone, the WHO declared the epidemic to be an international public health emergency.
To date, over 8,300 suspected cases and over 4,050 deaths from Ebola have been reported worldwide from this outbreak alone, with the WHO saying that these numbers may be vastly underestimated. The WHO also stated this week that that there could be up to 10,000 new cases a week within two months.
My question then became: Why were only 1,528 people killed by Ebola during the 36 year period between 1976 and 2012, yet over 4,000 have died from Ebola in the last 11 months alone?
At this point, I can only speculate as far as the answer to this question, but I believe it is one every American should be asking, because it suggests that something besides the disease itself is driving this epidemic.
Common sense dictates that since scientists and regulators working for the federal government quite literally wrote the book on Level 4 biocontainment protocols, they know how dangerous Ebola truly is. Thus, their refusal to prudently address the threat leads to one of two conclusions:
1. They have determined that political expedience trumps public health concerns, or
2. They want Ebola to spread in the United States.
Given how manifestly diabolical I know this president and his administration to be, I don’t doubt that the latter is a possibility. It certainly would fall within the scope of concerns some analysts have expressed pertaining to various escalating crises in America being orchestrated by the White House in order to ultimately “legitimize” a declaration of martial law in America.
It would also be child’s play for a determined group of individuals, terrorists – or even a government – to “help along” an epidemic of such a virulent disease.
In the interest of constructive remediation, I would recommend that Americans vigorously demand proper containment procedures. This would amount to an immediate travel ban from West African nations in which Ebola is now raging, mandatory quarantining of individuals suspected of having been exposed to the virus and the initiation of BSL-4 biocontainment procedures for all personnel interacting with Ebola patients.
Because as it stands now, they had better biocontainment procedures in the movie “E.T. The Extra-Terrestrial” for a fictional, rubber spaceman than we currently have for Ebola.
Media wishing to interview Erik Rush, please contact [email protected]. |
/**
*
* @author Valdiney V GOMES
*/
@Service
public class JobBuildGraphService {
private final JobBuildRepository jobBuildRepository;
private final AuditorService auditorService;
@Autowired
public JobBuildGraphService(JobBuildRepository jobBuildRepository, AuditorService auditorService) {
this.jobBuildRepository = jobBuildRepository;
this.auditorService = auditorService;
}
/**
* Find job build count by hour.
*
* @param phase Phase
* @param startDate Start Date
* @param endDate End Date
*
* @return Job build count by hour list.
*/
@Cacheable(value = "jobBuildByHour", key = "{#phase, #startDate, #endDate}")
public List<JobBuildMetric> findJobBuildCountByHour(
Phase phase,
Date startDate,
Date endDate) {
Date initialDate = new DateTime(startDate)
.withTimeAtStartOfDay()
.toDate();
Date finalDate = new DateTime(endDate)
.withTimeAtStartOfDay()
.plusHours(23)
.plusMinutes(59)
.plusSeconds(59)
.toDate();
return jobBuildRepository.findJobBuildCountByHour(phase, initialDate, finalDate);
}
/**
* Get the job build summary by job and hour in a 24 hours window.
*
* @param phase Phase
* @param dateFrom Date From
* @param dateTo Date To
* @return Job build summary by job and hour.
*/
public Map<Job, Long[]> getJobBuildDetail(
Phase phase,
Date dateFrom,
Date dateTo) {
Map<Job, Long[]> summary = new HashMap();
List<JobBuildMetric> builds = this.findJobBuildCountByHour(phase, dateFrom, dateTo);
builds.stream().forEach((data) -> {
Job key = data.getJob();
Long[] value = summary.containsKey(key) ? summary.get(key) : new Long[24];
value[data.getHour()] = data.getBuild();
summary.put(key, value);
});
return summary;
}
/**
* Get the job build total by job and hour in a 24 hours window.
*
* @param phase Phase
* @param dateFrom Date From
* @param dateTo Date To
* @return Job build summary summary by job and hour.
*/
public Long[] getJobBuildTotal(
Phase phase,
Date dateFrom,
Date dateTo) {
Long[] value = new Long[24];
List<JobBuildMetric> builds = this.findJobBuildCountByHour(phase, dateFrom, dateTo);
builds.stream().forEach((data) -> {
Long build = value[data.getHour()];
if (build == null) {
value[data.getHour()] = data.getBuild();
} else {
value[data.getHour()] += data.getBuild();
}
});
for (int i = 0; i < value.length; i++) {
if (value[i] == null) {
value[i] = 0L;
}
}
return value;
}
/**
* Find job build history
*
* @param job Job
* @param startDate Start Date
* @param endDate End Date
* @return job time by phase and nunber
*/
public List<JobBuildMetric> findBuildHistory(
List<Job> job,
Date startDate,
Date endDate) {
List<JobBuildMetric> metrics = new ArrayList();
if (job != null && !job.isEmpty()) {
metrics = jobBuildRepository.findBuildHistory(job, startDate, endDate);
}
return metrics;
}
/**
* Get the gantt graph data.
*
* @param jobs Job
* @param dateFrom Date from
* @param dateTo Date to
* @return Gantt
*/
public List getDHTMLXGanttData(
List<Job> jobs,
Date dateFrom,
Date dateTo) {
auditorService.publish("GANTT_RUN");
Long surrogateID = 0L;
List<DHTMLXGantt> data = new ArrayList();
//Add all parents to gantt.
if (jobs != null) {
List<JobBuildMetric> metrics = this.findBuildHistory(jobs, dateFrom, dateTo);
for (Job job : jobs) {
for (JobBuildMetric metric : metrics) {
if (job.getId().equals(metric.getJob().getId())) {
data.add(new DHTMLXGantt(
metric.getJob().getId().toString(),
metric.getJob().getDisplayName(),
metric.getQueueDate().toString(),
0L,
1.0,
true,
"",
"#D6DBE1",
""
));
break;
}
}
}
//Add all children in the gantt.
for (JobBuildMetric metric : metrics) {
surrogateID++;
data.add(new DHTMLXGantt(
surrogateID + "_",
metric.getQueueDate().toString().substring(0, 16) + " - " + metric.getFinishDate().toString().substring(0, 16),
metric.getQueueDate().toString(),
metric.getDurationTimeInMinutes(),
metric.getQueuePercentage(),
true,
metric.getJob().getId().toString(),
metric.isSuccess() ? "#3DB9D3" : "#DD424A",
"#E5E8EC"
));
}
}
return data;
}
/**
* DHTMLXGantt data format.
*/
class DHTMLXGantt {
private String id;
private String text;
private String start_date;
private Long duration;
private Double progress;
private boolean open;
private String parent;
private String color;
private String progressColor;
public DHTMLXGantt(
String id,
String text,
String start_date,
Long duration,
Double progress,
boolean open,
String parent,
String color,
String progressColor) {
this.id = id;
this.text = text;
this.start_date = start_date;
this.duration = duration;
this.progress = progress;
this.open = open;
this.parent = parent;
this.color = color;
this.progressColor = progressColor;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getStart_date() {
return start_date;
}
public void setStart_date(String start_date) {
this.start_date = start_date;
}
public Long getDuration() {
return duration;
}
public void setDuration(Long duration) {
this.duration = duration;
}
public Double getProgress() {
return progress;
}
public void setProgress(Double progress) {
this.progress = progress;
}
public boolean isOpen() {
return open;
}
public void setOpen(boolean open) {
this.open = open;
}
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getProgressColor() {
return progressColor;
}
public void setProgressColor(String progressColor) {
this.progressColor = progressColor;
}
}
} |
The National Hockey League has chosen the team of William Foley and the Maloof family as the owners of a Las Vegas expansion team, The Post has learned.
The league has not determined a timetable for expansion, but two western US cities are expected to be selected for new franchises, according to reports.
One of those cities — if approved by NHL owners — will be Las Vegas, sources said.
The franchise fee will be about $400 million, a source said.
NHL Deputy Commissioner Bill Daly said Monday he met with a potential Las Vegas ownership group, and was intrigued by the idea of bringing the first major-league sports franchise to the desert city.
He did not identify the group but sources close to the situation said it was Foley, a billionaire businessman, and the Maloof family, former owners of the NBA Sacramento Kings.
The Maloofs are influential in Las Vegas and known also for such ventures as producing movies and running the Palms Casino Resort.
The NHL is not expected to decide on expansion until its settles on a second city — as there are two more Eastern Division teams than Western Division teams, a hockey source said.
A $400 million franchise fee would be five times higher than the $80 million fee charged both the Minnesota Wild and Columbus Blue Jackets in 2000, the last time the league expanded.
“If you believe the Islanders just sold for $485 million, that is the fee I would want if I were the league,” a sports business source said.
Foley declined comment, and the Maloofs did not return calls. |
package com.beltraoluis.intrachat.connection;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Date;
/**
*
* @author beltraoluis
*/
public class TcpClient {
public static Socket start() {
try {
Socket client = new Socket("127.0.0.1",5555);
ObjectOutputStream saida = new ObjectOutputStream(client.getOutputStream());
saida.flush();
saida.writeObject("isso foi a menssagem");
saida.close();
return client;
}
catch(IOException e) {
System.out.println("Erro: " + e.getMessage());
}
return null;
}
}
|
<reponame>breedloj/aws-toolkit-vscode
/*!
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
import * as fs from 'fs'
import { getLogger, Logger } from '../../../shared/logger'
/**
* @param {string} uniqueIdentifier - unique identifier of state machine
* @param {string} templatePath - path for the template.json file
*
* @returns the escaped ASL Json definition string of the state machine construct
*/
export function getStateMachineDefinitionFromCfnTemplate(uniqueIdentifier: string, templatePath: string): string {
const logger: Logger = getLogger()
try {
const data = fs.readFileSync(templatePath, 'utf8')
const jsonObj = JSON.parse(data)
const resources = jsonObj?.Resources
if (!resources) {
return ''
}
let matchingKey: string
const matchingKeyList: string[] = []
for (const key of Object.keys(resources)) {
//the resources list always contains 'CDKMetadata'
if (key === 'CDKMetadata') {
continue
}
if (key.substring(0, uniqueIdentifier.length) === uniqueIdentifier) {
matchingKeyList.push(key)
}
}
if (matchingKeyList.length === 0) {
return ''
} else {
//return minimum length key in matchingKeyList
matchingKey = matchingKeyList.reduce((a, b) => (a.length <= b.length ? a : b))
}
const definitionString = jsonObj.Resources[matchingKey].Properties.DefinitionString
return !definitionString ? '' : definitionString
} catch (err) {
logger.debug('Unable to extract state machine definition string from template.json file.')
logger.error(err as Error)
return ''
}
}
/**
* @param {string} escapedAslJsonStr - json state machine construct definition
* @returns unescaped json state machine construct definition in asl.json
*/
export function toUnescapedAslJsonString(
escapedAslJsonStr:
| string
| {
'Fn::Join': any[]
}
): string {
if (typeof escapedAslJsonStr === 'string') {
return escapedAslJsonStr
}
const definitionStringWithPlaceholders: any[] = escapedAslJsonStr['Fn::Join'][1]
const definitionStringSegments: string[] = definitionStringWithPlaceholders.filter(
segment => typeof segment === 'string'
)
return definitionStringSegments.join('')
}
|
<filename>gpc-web/src/locales/lang/pl.ts
import { genMessage } from '../helper';
import antdLocale from 'ant-design-vue/es/locale/pl_PL';
// import momentLocale from 'moment/dist/locale/pl';
const modules = import.meta.globEager('./pl/**/*.ts');
export default {
message: {
...genMessage(modules, 'pl'),
antdLocale,
},
// momentLocale,
momentLocaleName: 'pl',
};
|
export class Tweet {
public _id: string
public description: string
public user: string
public images?: string[]
public likes?: string[]
public parent?: string
public retweets?: string[]
public replies?: string
public timezone?: string
public thread?: string[]
public username?: string
public name?: string
public retweet?: string
public createdAt: number
public updatedAt: number
public static fromJSON(obj: Object): Tweet {
let item: Tweet = Object.assign(new Tweet(), obj)
return item
}
}
|
Possibilities for VDD = 0.1V logic using carbon-based tunneling field effect transistors
A systematic evaluation of the possibilities of low-voltage logic using carbon-based tunneling field effect transistors (TFET) is performed using the non-equilibrium green function (NEGF) formalism for device simulation and ring-oscillator and load-driven inverter circuits. We found that the on-current is severely limited by quantum mechanical reflections due to wavefunction mismatch. The lower bound of subthreshold swing (SS) is limited by tunneling through the channel. Although the projected performance is well-below that of a recent prediction, we show that digital logic at VDD = 0.1 V is possible. Finally, we compare the TFET with its MOSFET counterpart and show that for VDD=0.1 V, the TFET out-performs the MOSFET. |
CRISPR/Cas9-Based Genome Editing in the Filamentous Fungus Fusarium fujikuroi and Its Application in Strain Engineering for Gibberellic Acid Production.
The filamentous fungus Fusarium fujikuroi is well-known for its production of natural plant growth hormones: a series of gibberellic acids (GAs). Some GAs, including GA1, GA3, GA4, and GA7, are biologically active and have been widely applied in agriculture. However, the low efficiency of traditional genetic tools limits the further research toward making this fungus more efficient and able to produce tailor-made GAs. Here, we established an efficient CRISPR/Cas9-based genome editing tool for F. fujikuroi. First, we compared three different nuclear localization signals (NLS) and selected an efficient NLS from histone H2B (HTBNLS) to enable the import of the Cas9 protein into the fungal nucleus. Then, different sgRNA expression strategies, both in vitro and different promoter-based in vivo strategies, were explored. The promoters of the U6 small nuclear RNA and 5S rRNA, which were identified in F. fujikuroi, had the highest editing efficiency. The 5S rRNA-promoter-driven genome editing efficiency reached up to 79.2%. What's more, multigene editing was also explored and showed good results. Finally, we used the developed genome editing tool to engineer the metabolic pathways responsible for the accumulation of a series GAs in the filamentous fungus F. fujikuroi, and successfully changed its GA product profile, from GA3 to tailor-made GA4 and GA7 mixtures. Since these mixtures are more efficient for agricultural use, especially for fruit growth, the developed strains will greatly improve industrial GA production. |
/**
* Replace one child with another at the same position. The parent of the
* child is not changed
*
* @param child
* the old child
* @param newChild
* the new child
*/
public void replaceChild(Operator<? extends Serializable> child,
Operator<? extends Serializable> newChild) {
int childIndex = childOperators.indexOf(child);
assert childIndex != -1;
childOperators.set(childIndex, newChild);
} |
def _iref_and_ad_on_states(self, internal_ref_on, ad_on):
INTERNAL_REF_ON_BIT = 0x08
AD_CONVERTER_ON_BIT = 0x04
INTERNAL_REF_ON_BIT = 0x00 if not internal_ref_on else INTERNAL_REF_ON_BIT
AD_CONVERTER_ON_BIT = 0x00 if not ad_on else AD_CONVERTER_ON_BIT
return INTERNAL_REF_ON_BIT | AD_CONVERTER_ON_BIT |
// Copyright 2017 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.
package common_test
import (
"fmt"
"chromium.googlesource.com/enterprise/cel/go/common"
)
// Example of basic Trie usage.
func ExampleTrie_basic() {
var t common.Trie
ref, _ := common.RefPathFromString("a.b.c")
t.Set(ref, "hello", false)
v, _ := t.Get(ref)
fmt.Printf("Value at %s is %s", ref.String(), v.(string))
// Output: Value at a.b.c is hello
}
// Example of visiting a subtree.
func ExampleTrie_visit() {
var t common.Trie
t.Set(common.RefPathMust("a.b.c"), "hello", false)
t.Set(common.RefPathMust("a.b.d"), "world", false)
t.Set(common.RefPathMust("x.y.z"), "not visited", false)
t.VisitFrom(common.RefPathMust("a.b"), func(p common.RefPath, v interface{}) bool {
fmt.Printf("Value at %s is %s\n", p, v)
return true
})
// Unordered output:
// Value at a.b.c is hello
// Value at a.b.d is world
}
|
/**
* The JVehicleCommander application class. When instantiated, this class creates
* a JFrame and opens it with a JMap and other controls.
*
* Main frame GUI code goes in this class. If it's not GUI code, consider putting
* it in another class.
*/
public class VehicleCommanderJFrame extends javax.swing.JFrame
implements IdentifyListener, AppConfigListener {
@SuppressWarnings("serial")
private class ChemLightButton extends ToolbarToggleButton {
private final Color color;
public ChemLightButton(Color color) {
super();
setUnselectButton(jToggleButton_deactivateAllTools);
setMapController(mapController);
this.color = color;
}
@Override
protected void toggled(boolean selected) {
if (selected) {
new Thread() {
@Override
public void run() {
/**
* Sleep for a few millis so that any existing component's call to
* cancelTrackAsync can finish first.
* TODO this depends on a race condition; it's probably fine but we
* might want to clean this up in the future.
*/
try {
Thread.sleep(15);
} catch (InterruptedException ex) {
Logger.getLogger(VehicleCommanderJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
mapController.trackAsync(new MapOverlayAdapter() {
@Override
public void mouseClicked(MouseEvent event) {
Point pt = mapController.toMapPointObject(event.getX(), event.getY());
chemLightController.sendChemLight(pt.getX(), pt.getY(), mapController.getSpatialReference().getID(), color.getRGB());
}
}, MapController.EVENT_MOUSE_CLICKED);
}
}.start();
} else {
mapController.cancelTrackAsync();
}
}
}
private static final long serialVersionUID = -4694556823082813076L;
private static final String KEY_FRAME_EXTENDED_STATE = VehicleCommanderJFrame.class.getSimpleName() + "frameExtendedState";
private static final String KEY_FRAME_WIDTH = VehicleCommanderJFrame.class.getSimpleName() + "frameWidth";
private static final String KEY_FRAME_HEIGHT = VehicleCommanderJFrame.class.getSimpleName() + "frameHeight";
private static final String KEY_FRAME_LOCATION_X = VehicleCommanderJFrame.class.getSimpleName() + "frameLocationX";
private static final String KEY_FRAME_LOCATION_Y = VehicleCommanderJFrame.class.getSimpleName() + "frameLocationY";
public static final String LICENSE_NOT_SET = "NOT SET (insert license string here)";
public static final String BUILT_IN_LICENSE_STRING = LICENSE_NOT_SET; // TODO: (insert license string here)
public static final String BUILT_IN_EXTS_STRING = LICENSE_NOT_SET; // TODO: (insert extension license string(s) here)
public static final String BUILT_IN_CLIENT_ID = LICENSE_NOT_SET; // TODO: (insert client ID here)
private final MainMenuJPanel mainMenu;
private final BasemapsJPanel basemapsPanel;
private final IdentifyResultsJPanel identifyPanel;
private final ViewshedJPanel viewshedPanel;
private final RouteJPanel routePanel;
private final MapController mapController;
private final ChemLightController chemLightController;
private final AppConfigController appConfigController;
private final MessageController messageController;
private final VehicleStatusController vehicleStatusController;
private final PositionReportController positionReportController;
private final ViewshedController viewshedController;
private final RouteController routeController;
private final String mapConfigFilename;
private MapConfig mapConfig;
private String licenseString;
private String[] extsStrings;
private String clientId;
private AdvancedSymbolController symbolController;
private final MapOverlay stopFollowMeOverlay;
private final Timer updateTimeDisplayTimer;
/**
* Creates a new VehicleCommanderJFrame, which in turn creates and opens the application
* frame and its contents. This default constructor assumes that a map configuration
* file called mapconfig.xml is found in the working directory.
*/
public VehicleCommanderJFrame() {
this("./mapconfig.xml", null, null, null);
}
/**
* Creates a new JVehicleCommanderJFrame, which in turn creates and opens the application
* frame and its contents. This constructor loads mapConfigFilename as a map
* configuration file.
* @param mapConfigFilename the name of the map configuration file to load.
* @param licenseString the ArcGIS Runtime license string, or the name of a
* file that contains an ArcGIS Runtime license string.
* @param extsString the ArcGIS Runtime extension license strings, separated
* by semicolons, or the name of a file that contains the
* ArcGIS Runtime extension license strings separated by semicolons.
* @param clientId the ArcGIS client ID for this app, or the name of a file that
* contains the ArcGIS client ID for this app.
* @throws IOException
* @throws ParserConfigurationException
* @throws SAXException
*/
@SuppressWarnings("LeakingThisInConstructor")
public VehicleCommanderJFrame(String mapConfigFilename, String licenseString, String extsString, String clientId) {
if (null == mapConfigFilename || !new File(mapConfigFilename).exists()) {
mapConfigFilename = "./mapconfig.xml";
}
this.mapConfigFilename = mapConfigFilename;
setLicenseString((null != licenseString) ? licenseString : BUILT_IN_LICENSE_STRING);
setExtensionLicensesString((null != extsString) ? extsString : BUILT_IN_EXTS_STRING);
setClientId((null != clientId) ? clientId : BUILT_IN_CLIENT_ID);
if (LICENSE_NOT_SET.equals(this.clientId) || LICENSE_NOT_SET.equals(this.licenseString) || LICENSE_NOT_SET.equals(this.extsStrings[0])) {
System.out.println("Warning: LICENSE NOT SET - this must be run on a Development License machine");
} else {
ArcGISRuntime.setClientID(this.clientId);
ArcGISRuntime.License.setLicense(this.licenseString, this.extsStrings);
}
ArcGISRuntime.initialize();
appConfigController = new AppConfigController();
appConfigController.addListener(this);
initComponents();
getLayeredPane().add(floatingPanel);
addToolbarButton((ToolbarToggleButton) jToggleButton_viewshed);
addToolbarButton((ToolbarToggleButton) jToggleButton_route);
messageController = new MessageController(appConfigController.getPort(), appConfigController.getUsername());
appConfigController.setMessageController(messageController);
chemLightController = new ChemLightController(messageController, appConfigController.getUsername());
mapController = new MapController(map, this, appConfigController, chemLightController);
new Timer(1000 / 24, new ActionListener() {
public void actionPerformed(ActionEvent e) {
((RotatableImagePanel) rotatableImagePanel_northArrow).setRotation(Math.toRadians(mapController.getRotation()));
}
}).start();
//Window location and size
Preferences prefs = Preferences.userNodeForPackage(getClass());
int windowState = prefs.getInt(KEY_FRAME_EXTENDED_STATE, -1) & (Frame.ICONIFIED ^ 0xffffffff);
if (-1 < windowState) {
int width = prefs.getInt(KEY_FRAME_WIDTH, getWidth());
int height = prefs.getInt(KEY_FRAME_HEIGHT, getHeight());
int locationX = prefs.getInt(KEY_FRAME_LOCATION_X, 0);
int locationY = prefs.getInt(KEY_FRAME_LOCATION_Y, 0);
java.awt.Point location = new java.awt.Point(locationX, locationY);
Rectangle bounds = new Rectangle(locationX, locationY, width, height);
//Verify that the location is on a valid screen
boolean onValidScreen = false;
GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] screenDevices = genv.getScreenDevices();
for (GraphicsDevice dev : screenDevices) {
if (dev.getDefaultConfiguration().getBounds().intersects(bounds)) {
onValidScreen = true;
break;
}
}
if (!onValidScreen) {
location = screenDevices[0].getDefaultConfiguration().getBounds().getLocation();
}
//Only set the size if not maximized
if (0 == (windowState & Frame.MAXIMIZED_BOTH)) {
setSize(width, height);
}
setLocation(location);
setExtendedState(windowState);
}
identifyPanel = new IdentifyResultsJPanel(mapController);
identifyPanel.setVisible(false);
getLayeredPane().add(identifyPanel, JLayeredPane.MODAL_LAYER);
viewshedController = new ViewshedController(mapController);
viewshedController.addGPListener(new GPAdapter() {
@Override
public void gpEnabled() {
jToggleButton_viewshed.setEnabled(true);
}
@Override
public void gpDisbled() {
jToggleButton_viewshed.setEnabled(false);
}
});
routeController = new RouteController(mapController);
routeController.addGPListener(new GPAdapter() {
@Override
public void gpEnabled() {
jToggleButton_route.setEnabled(true);
}
@Override
public void gpDisbled() {
jToggleButton_route.setEnabled(false);
}
});
basemapsPanel = new BasemapsJPanel();
basemapsPanel.setVisible(false);
getLayeredPane().add(basemapsPanel, JLayeredPane.MODAL_LAYER);
basemapsPanel.addComponentListener(new ComponentAdapter() {
@Override
public void componentHidden(ComponentEvent e) {
jToggleButton_openBasemapPanel.setSelected(false);
}
});
resetMapConfig();
//Set up extensions
List<Map<String, String>> toolbarItems = mapConfig.getToolbarItems();
for (Map<String, String> item : toolbarItems) {
try {
if (item.containsKey("class")) {
if (item.containsKey("jar")) {
String jar = item.get("jar");
try {
Utilities.loadJar(jar);
} catch (Exception ex) {
Logger.getLogger(VehicleCommanderJFrame.class.getName()).log(Level.SEVERE, null, ex);
//Swallow this exception. Who knows--we might be able
//to load this item without the JAR.
}
}
String className = item.get("class");
Class<?> targetClass = Class.forName(className);
if (ToolbarToggleButton.class.isAssignableFrom(targetClass)) {
Constructor<?> ctor = targetClass.getDeclaredConstructor();
ToolbarToggleButton button = (ToolbarToggleButton) ctor.newInstance();
button.setUnselectButton(jToggleButton_deactivateAllTools);
if (button instanceof ToolbarToggleButton) {
ToolbarToggleButton ttButton = (ToolbarToggleButton) button;
ttButton.setProperties(item);
ttButton.setMapController(mapController);
if (button instanceof ComponentShowingButton) {
((ComponentShowingButton) button).setComponentParent(getLayeredPane());
}
}
addToolbarButton(button);
} else if (JButton.class.isAssignableFrom(targetClass)) {
Constructor<?> ctor = targetClass.getDeclaredConstructor();
JButton button = (JButton) ctor.newInstance();
addToolbarButton(button);
}
}
} catch (Exception ex) {
Logger.getLogger(VehicleCommanderJFrame.class.getName()).log(Level.SEVERE, null, ex);
continue;
}
}
LocationController locationController = null;
try {
locationController = mapController.getLocationController();
locationController.setMode(appConfigController.getLocationMode(), false);
double speedMultiplier = appConfigController.getSpeedMultiplier();
if (0 < speedMultiplier) {
locationController.setSpeedMultiplier(speedMultiplier);
}
locationController.addListener(identifyPanel);
if (locationController instanceof com.esri.vehiclecommander.controller.LocationController) {
appConfigController.setLocationController((com.esri.vehiclecommander.controller.LocationController) locationController);
}
locationController.addListener(new LocationListener() {
public void onLocationChanged(Location location) {
if (null != location) {
updatePosition(GeometryEngine.project(location.getLongitude(), location.getLatitude(), mapController.getSpatialReference()), location.getHeading());
}
}
public void onStateChanged(LocationProvider.LocationProviderState state) {
}
});
locationController.start();
} catch (Throwable t) {
Logger.getLogger(VehicleCommanderJFrame.class.getName()).log(Level.SEVERE, null, t);
Utilities.showGPSErrorMessage(t.getMessage());
}
messageController.addListener(symbolController);
messageController.startReceiving();
positionReportController = new PositionReportController(
mapController.getLocationController(),
messageController,
appConfigController.getUsername(),
appConfigController.getVehicleType(),
appConfigController.getUniqueId(),
appConfigController.getSic());
positionReportController.setPeriod(appConfigController.getPositionMessageInterval());
positionReportController.setEnabled(true);
vehicleStatusController = new VehicleStatusController(appConfigController, messageController);
//Key listener for application-wide key events
ApplicationKeyListener keyListener = new ApplicationKeyListener(this, mapController);
addKeyListener(keyListener);
map.addKeyListener(keyListener);
mainMenu = new MainMenuJPanel(this, mapController, appConfigController,
symbolController, routeController, positionReportController);
routeController.addRouteListener(mainMenu);
mainMenu.setVisible(false);
getLayeredPane().add(mainMenu, JLayeredPane.MODAL_LAYER);
mainMenu.addComponentListener(new ComponentAdapter() {
@Override
public void componentHidden(ComponentEvent e) {
jToggleButton_mainMenu.setSelected(false);
}
});
viewshedPanel = new ViewshedJPanel(this, mapController, viewshedController);
viewshedPanel.setVisible(false);
((ComponentShowingButton) jToggleButton_viewshed).setComponentParent(getLayeredPane());
((ComponentShowingButton) jToggleButton_viewshed).setComponent(viewshedPanel);
routePanel = new RouteJPanel(this, mapController, routeController);
routePanel.setVisible(false);
((ComponentShowingButton) jToggleButton_route).setComponentParent(getLayeredPane());
((ComponentShowingButton) jToggleButton_route).setComponent(routePanel);
stopFollowMeOverlay = new MapOverlay() {
@Override
public void onMouseDragged(MouseEvent event) {
cancelFollowMe();
super.onMouseDragged(event);
}
};
map.addMapOverlay(stopFollowMeOverlay);
updateTimeDisplayTimer = new Timer(1000 / 24, new ActionListener() {
public void actionPerformed(ActionEvent e) {
DateFormat dateFormat = appConfigController.isShowLocalTimeZone() ?
Utilities.DATE_FORMAT_MILITARY_LOCAL :
Utilities.DATE_FORMAT_MILITARY_ZULU;
jLabel_time.setText(dateFormat.format(new Date()));
}
});
updateTimeDisplayTimer.start();
}
/**
* Initializes or resets the map configuration, according to the contents of
* the mapconfig.xml file that provided to the constructor, or ./mapconfig.xml
* if none was provided to the constructor.
*/
public final void resetMapConfig() {
mapController.removeAllLayers();
//Read XML config file
try {
mapConfig = MapConfigReader.readMapConfig(
new File(mapConfigFilename),
mapController,
appConfigController,
viewshedController);
basemapsPanel.setBasemapLayers(mapConfig.getBasemapLayers());
} catch (Throwable t) {
//If anything goes wrong, we just have to create a blank MapConfig
mapConfig = new MapConfig();
JOptionPane.showMessageDialog(this, "There was a problem loading "
+ mapConfigFilename + ". This could be a problem with the XML file or with one of the layers.\n\nError details:\n\n"
+ t.getMessage());
}
try {
symbolController = new AdvancedSymbolController(mapController,
ImageIO.read(getClass().getResourceAsStream("/com/esri/vehiclecommander/resources/spot_report.png")),
messageController, appConfigController);
mapController.setAdvancedSymbolController(symbolController);
new Thread() {
@Override
public void run() {
try {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Image iconImage = VehicleCommanderJFrame.this.getIconImage();
final int width;
final int height;
if (null != iconImage) {
width = iconImage.getWidth(null);
height = iconImage.getHeight(null);
} else {
width = height = 16;
}
setIconImage(symbolController.getSymbolImage("Ground Vehicle F", width, height));
}
});
//First search is sometimes slow, so fire off the first search right here
symbolController.findSymbols("ATM Hostile");
} catch (IOException ex) {
Logger.getLogger(VehicleCommanderJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}.start();
} catch (IOException ex) {
Logger.getLogger(VehicleCommanderJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void cancelFollowMe() {
mapController.setAutoPan(false);
jToggleButton_followMe.setSelected(false);
}
/**
* Sets the ArcGIS Runtime license string to use, or the filename of a text file
* containing the license string.
* @param licenseString the ArcGIS Runtime license string to use, or the filename
* of a text file containing the license string.
*/
private void setLicenseString(String licenseString) {
if (null != licenseString) {
this.licenseString = readFileIntoStringOrReturnString(licenseString);
}
}
private void setExtensionLicensesString(String exts) {
if (null != exts) {
String extsStr = readFileIntoStringOrReturnString(exts);
//Parse the extension strings into an array
StringTokenizer tok = new StringTokenizer(extsStr, ";");
extsStrings = new String[tok.countTokens()];
for (int i = 0; i < extsStrings.length; i++) {
extsStrings[i] = tok.nextToken();
}
}
}
private void setClientId(String clientId) {
if (null != clientId) {
this.clientId = readFileIntoStringOrReturnString(clientId);
}
}
/**
* This method is called from within the constructor to
* initialize the form.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
buttonGroup_tools = new javax.swing.ButtonGroup();
jToggleButton_deactivateAllTools = new javax.swing.JToggleButton();
jToggleButton_viewshed = new ComponentShowingButton();
((ComponentShowingButton) jToggleButton_viewshed).setUnselectButton(jToggleButton_deactivateAllTools);
jToggleButton_route = new ComponentShowingButton();
((ComponentShowingButton) jToggleButton_route).setUnselectButton(jToggleButton_deactivateAllTools);
buttonGroup_navigationModes = new javax.swing.ButtonGroup();
floatingPanel = new javax.swing.JPanel();
jPanel_header = new javax.swing.JPanel();
jPanel_classification = new javax.swing.JPanel();
jLabel_classification = new javax.swing.JLabel();
jToggleButton_openBasemapPanel = new javax.swing.JToggleButton();
jToggleButton_openAnalysisToolbar = new javax.swing.JToggleButton();
jPanel_left = new javax.swing.JPanel();
jPanel_toolButtons = new javax.swing.JPanel();
jToggleButton_chemLightRed = new ChemLightButton(Color.RED);
jToggleButton_chemLightYellow = new ChemLightButton(Color.YELLOW);
jToggleButton_chemLightGreen = new ChemLightButton(Color.GREEN);
jToggleButton_chemLightBlue = new ChemLightButton(Color.BLUE);
jToggleButton_mainMenu = new javax.swing.JToggleButton();
jToggleButton_grid = new javax.swing.JToggleButton();
jToggleButton_911 = new javax.swing.JToggleButton();
jPanel_navigation = new javax.swing.JPanel();
URL resource = getClass().getResource("/com/esri/vehiclecommander/resources/North-Arrow.png");
Image image = Toolkit.getDefaultToolkit().getImage(resource);
rotatableImagePanel_northArrow = new RotatableImagePanel(image);
jToggleButton_followMe = new javax.swing.JToggleButton();
jButton_zoomIn = new javax.swing.JButton();
jButton_panUp = new javax.swing.JButton();
jButton_panLeft = new javax.swing.JButton();
jButton_panRight = new javax.swing.JButton();
jButton_panDown = new javax.swing.JButton();
jButton_zoomOut = new javax.swing.JButton();
jToggleButton_northUp = new javax.swing.JToggleButton();
jToggleButton_trackUp = new javax.swing.JToggleButton();
jToggleButton_waypointUp = new javax.swing.JToggleButton();
jSeparator1 = new javax.swing.JSeparator();
jPanel_footer = new javax.swing.JPanel();
jPanel_position = new javax.swing.JPanel();
jLabel_locationLabel = new javax.swing.JLabel();
jLabel_location = new javax.swing.JLabel();
jLabel_timeLabel = new javax.swing.JLabel();
jLabel_time = new javax.swing.JLabel();
filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(10, 0), new java.awt.Dimension(10, 0), new java.awt.Dimension(10, 0));
jLabel_headingLabel = new javax.swing.JLabel();
jLabel_heading = new javax.swing.JLabel();
jPanel_mainToolbar = new javax.swing.JPanel();
jPanel_subToolbar = new javax.swing.JPanel();
jPanel_subToolbar.setVisible(false);
jButton_clearMessages = new javax.swing.JButton();
map = new com.esri.map.JMap();
map.setShowingEsriLogo(false);
buttonGroup_tools.add(jToggleButton_deactivateAllTools);
jToggleButton_deactivateAllTools.setText("jToggleButton1");
buttonGroup_tools.add(jToggleButton_viewshed);
jToggleButton_viewshed.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/Viewshed-Normal.png"))); // NOI18N
jToggleButton_viewshed.setBorderPainted(false);
jToggleButton_viewshed.setContentAreaFilled(false);
jToggleButton_viewshed.setFocusable(false);
jToggleButton_viewshed.setMargin(new java.awt.Insets(0, 0, 0, 0));
jToggleButton_viewshed.setMaximumSize(new java.awt.Dimension(50, 50));
jToggleButton_viewshed.setMinimumSize(new java.awt.Dimension(50, 50));
jToggleButton_viewshed.setPreferredSize(new java.awt.Dimension(50, 50));
jToggleButton_viewshed.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/Viewshed-Pressed.png"))); // NOI18N
buttonGroup_tools.add(jToggleButton_route);
jToggleButton_route.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/OpenRoutePanel-Normal.png"))); // NOI18N
jToggleButton_route.setBorderPainted(false);
jToggleButton_route.setContentAreaFilled(false);
jToggleButton_route.setFocusable(false);
jToggleButton_route.setMargin(new java.awt.Insets(0, 0, 0, 0));
jToggleButton_route.setMaximumSize(new java.awt.Dimension(50, 50));
jToggleButton_route.setMinimumSize(new java.awt.Dimension(50, 50));
jToggleButton_route.setPreferredSize(new java.awt.Dimension(50, 50));
jToggleButton_route.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/OpenRoutePanel-Pressed.png"))); // NOI18N
floatingPanel.setOpaque(false);
jPanel_header.setBackground(new java.awt.Color(0, 0, 0));
jPanel_header.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 5, 0));
jPanel_classification.setBackground(new java.awt.Color(0, 204, 0));
jPanel_classification.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 5, 0));
jLabel_classification.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N
jLabel_classification.setText("Unclassified");
jPanel_classification.add(jLabel_classification);
jPanel_header.add(jPanel_classification);
jToggleButton_openBasemapPanel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/Basemap-Normal.png"))); // NOI18N
jToggleButton_openBasemapPanel.setBorderPainted(false);
jToggleButton_openBasemapPanel.setContentAreaFilled(false);
jToggleButton_openBasemapPanel.setFocusable(false);
jToggleButton_openBasemapPanel.setMargin(new java.awt.Insets(0, 0, 0, 0));
jToggleButton_openBasemapPanel.setMaximumSize(new java.awt.Dimension(50, 50));
jToggleButton_openBasemapPanel.setMinimumSize(new java.awt.Dimension(50, 50));
jToggleButton_openBasemapPanel.setPreferredSize(new java.awt.Dimension(50, 50));
jToggleButton_openBasemapPanel.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/Basemap-Pressed.png"))); // NOI18N
jToggleButton_openBasemapPanel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton_openBasemapPanelActionPerformed(evt);
}
});
jToggleButton_openAnalysisToolbar.setBackground(new java.awt.Color(216, 216, 216));
jToggleButton_openAnalysisToolbar.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N
jToggleButton_openAnalysisToolbar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/Tools-Normal.png"))); // NOI18N
jToggleButton_openAnalysisToolbar.setBorder(null);
jToggleButton_openAnalysisToolbar.setBorderPainted(false);
jToggleButton_openAnalysisToolbar.setContentAreaFilled(false);
jToggleButton_openAnalysisToolbar.setFocusable(false);
jToggleButton_openAnalysisToolbar.setMargin(new java.awt.Insets(0, 0, 0, 0));
jToggleButton_openAnalysisToolbar.setMaximumSize(new java.awt.Dimension(50, 50));
jToggleButton_openAnalysisToolbar.setMinimumSize(new java.awt.Dimension(50, 50));
jToggleButton_openAnalysisToolbar.setPreferredSize(new java.awt.Dimension(50, 50));
jToggleButton_openAnalysisToolbar.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/Tools-Pressed.png"))); // NOI18N
jToggleButton_openAnalysisToolbar.setRolloverEnabled(false);
jToggleButton_openAnalysisToolbar.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/Tools-Pressed.png"))); // NOI18N
jToggleButton_openAnalysisToolbar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton_openAnalysisToolbarActionPerformed(evt);
}
});
jPanel_left.setOpaque(false);
jPanel_left.setLayout(new java.awt.GridBagLayout());
jPanel_toolButtons.setMaximumSize(new java.awt.Dimension(50, 218));
jPanel_toolButtons.setMinimumSize(new java.awt.Dimension(50, 218));
jPanel_toolButtons.setOpaque(false);
jPanel_toolButtons.setPreferredSize(new java.awt.Dimension(50, 218));
buttonGroup_tools.add(jToggleButton_chemLightRed);
jToggleButton_chemLightRed.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/ChemLights-Red-Normal.png"))); // NOI18N
jToggleButton_chemLightRed.setBorderPainted(false);
jToggleButton_chemLightRed.setContentAreaFilled(false);
jToggleButton_chemLightRed.setFocusable(false);
jToggleButton_chemLightRed.setMargin(new java.awt.Insets(0, 0, 0, 0));
jToggleButton_chemLightRed.setMaximumSize(new java.awt.Dimension(50, 50));
jToggleButton_chemLightRed.setMinimumSize(new java.awt.Dimension(50, 50));
jToggleButton_chemLightRed.setPreferredSize(new java.awt.Dimension(50, 50));
jToggleButton_chemLightRed.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/ChemLights-Red-Pressed.png"))); // NOI18N
buttonGroup_tools.add(jToggleButton_chemLightYellow);
jToggleButton_chemLightYellow.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/ChemLights-Yellow-Normal.png"))); // NOI18N
jToggleButton_chemLightYellow.setBorderPainted(false);
jToggleButton_chemLightYellow.setContentAreaFilled(false);
jToggleButton_chemLightYellow.setFocusable(false);
jToggleButton_chemLightYellow.setMargin(new java.awt.Insets(0, 0, 0, 0));
jToggleButton_chemLightYellow.setMaximumSize(new java.awt.Dimension(50, 50));
jToggleButton_chemLightYellow.setMinimumSize(new java.awt.Dimension(50, 50));
jToggleButton_chemLightYellow.setPreferredSize(new java.awt.Dimension(50, 50));
jToggleButton_chemLightYellow.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/ChemLights-Yellow-Pressed.png"))); // NOI18N
buttonGroup_tools.add(jToggleButton_chemLightGreen);
jToggleButton_chemLightGreen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/ChemLights-Green-Normal.png"))); // NOI18N
jToggleButton_chemLightGreen.setBorderPainted(false);
jToggleButton_chemLightGreen.setContentAreaFilled(false);
jToggleButton_chemLightGreen.setFocusable(false);
jToggleButton_chemLightGreen.setMargin(new java.awt.Insets(0, 0, 0, 0));
jToggleButton_chemLightGreen.setMaximumSize(new java.awt.Dimension(50, 50));
jToggleButton_chemLightGreen.setMinimumSize(new java.awt.Dimension(50, 50));
jToggleButton_chemLightGreen.setPreferredSize(new java.awt.Dimension(50, 50));
jToggleButton_chemLightGreen.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/ChemLights-Green-Pressed.png"))); // NOI18N
buttonGroup_tools.add(jToggleButton_chemLightBlue);
jToggleButton_chemLightBlue.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/ChemLights-Blue-Normal.png"))); // NOI18N
jToggleButton_chemLightBlue.setBorderPainted(false);
jToggleButton_chemLightBlue.setContentAreaFilled(false);
jToggleButton_chemLightBlue.setFocusable(false);
jToggleButton_chemLightBlue.setMargin(new java.awt.Insets(0, 0, 0, 0));
jToggleButton_chemLightBlue.setMaximumSize(new java.awt.Dimension(50, 50));
jToggleButton_chemLightBlue.setMinimumSize(new java.awt.Dimension(50, 50));
jToggleButton_chemLightBlue.setPreferredSize(new java.awt.Dimension(50, 50));
jToggleButton_chemLightBlue.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/ChemLights-Blue-Pressed.png"))); // NOI18N
javax.swing.GroupLayout jPanel_toolButtonsLayout = new javax.swing.GroupLayout(jPanel_toolButtons);
jPanel_toolButtons.setLayout(jPanel_toolButtonsLayout);
jPanel_toolButtonsLayout.setHorizontalGroup(
jPanel_toolButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jToggleButton_chemLightRed, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jToggleButton_chemLightYellow, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jToggleButton_chemLightGreen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jToggleButton_chemLightBlue, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
);
jPanel_toolButtonsLayout.setVerticalGroup(
jPanel_toolButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel_toolButtonsLayout.createSequentialGroup()
.addComponent(jToggleButton_chemLightRed, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jToggleButton_chemLightYellow, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jToggleButton_chemLightGreen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jToggleButton_chemLightBlue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanel_left.add(jPanel_toolButtons, new java.awt.GridBagConstraints());
jToggleButton_mainMenu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/Menu-Normal.png"))); // NOI18N
jToggleButton_mainMenu.setBorderPainted(false);
jToggleButton_mainMenu.setContentAreaFilled(false);
jToggleButton_mainMenu.setFocusable(false);
jToggleButton_mainMenu.setMargin(new java.awt.Insets(0, 0, 0, 0));
jToggleButton_mainMenu.setMaximumSize(new java.awt.Dimension(50, 50));
jToggleButton_mainMenu.setMinimumSize(new java.awt.Dimension(50, 50));
jToggleButton_mainMenu.setPreferredSize(new java.awt.Dimension(50, 50));
jToggleButton_mainMenu.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/Menu-Pressed.png"))); // NOI18N
jToggleButton_mainMenu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton_mainMenuActionPerformed(evt);
}
});
jToggleButton_grid.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/Grid-Normal.png"))); // NOI18N
jToggleButton_grid.setSelected(appConfigController.isShowMgrsGrid());
jToggleButton_grid.setBorderPainted(false);
jToggleButton_grid.setContentAreaFilled(false);
jToggleButton_grid.setFocusable(false);
jToggleButton_grid.setMargin(new java.awt.Insets(0, 0, 0, 0));
jToggleButton_grid.setMaximumSize(new java.awt.Dimension(50, 50));
jToggleButton_grid.setMinimumSize(new java.awt.Dimension(50, 50));
jToggleButton_grid.setPreferredSize(new java.awt.Dimension(50, 50));
jToggleButton_grid.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/Grid-Pressed.png"))); // NOI18N
jToggleButton_grid.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton_gridActionPerformed(evt);
}
});
jToggleButton_911.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/911-Normal.png"))); // NOI18N
jToggleButton_911.setBorderPainted(false);
jToggleButton_911.setContentAreaFilled(false);
jToggleButton_911.setFocusable(false);
jToggleButton_911.setMargin(new java.awt.Insets(0, 0, 0, 0));
jToggleButton_911.setMaximumSize(new java.awt.Dimension(50, 50));
jToggleButton_911.setMinimumSize(new java.awt.Dimension(50, 50));
jToggleButton_911.setPreferredSize(new java.awt.Dimension(50, 50));
jToggleButton_911.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/911-Pressed.png"))); // NOI18N
jToggleButton_911.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton_911ActionPerformed(evt);
}
});
jPanel_navigation.setOpaque(false);
jPanel_navigation.setLayout(new java.awt.GridBagLayout());
rotatableImagePanel_northArrow.setMaximumSize(new java.awt.Dimension(60, 60));
rotatableImagePanel_northArrow.setMinimumSize(new java.awt.Dimension(60, 60));
rotatableImagePanel_northArrow.setOpaque(false);
rotatableImagePanel_northArrow.setPreferredSize(new java.awt.Dimension(60, 60));
javax.swing.GroupLayout rotatableImagePanel_northArrowLayout = new javax.swing.GroupLayout(rotatableImagePanel_northArrow);
rotatableImagePanel_northArrow.setLayout(rotatableImagePanel_northArrowLayout);
rotatableImagePanel_northArrowLayout.setHorizontalGroup(
rotatableImagePanel_northArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 60, Short.MAX_VALUE)
);
rotatableImagePanel_northArrowLayout.setVerticalGroup(
rotatableImagePanel_northArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 60, Short.MAX_VALUE)
);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
jPanel_navigation.add(rotatableImagePanel_northArrow, gridBagConstraints);
jToggleButton_followMe.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/FollowMe-Normal.png"))); // NOI18N
jToggleButton_followMe.setBorderPainted(false);
jToggleButton_followMe.setContentAreaFilled(false);
jToggleButton_followMe.setFocusable(false);
jToggleButton_followMe.setMargin(new java.awt.Insets(0, 0, 0, 0));
jToggleButton_followMe.setMaximumSize(new java.awt.Dimension(50, 50));
jToggleButton_followMe.setMinimumSize(new java.awt.Dimension(50, 50));
jToggleButton_followMe.setPreferredSize(new java.awt.Dimension(50, 50));
jToggleButton_followMe.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/FollowMe-Pressed.png"))); // NOI18N
jToggleButton_followMe.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/FollowMe-Pressed.png"))); // NOI18N
jToggleButton_followMe.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton_followMeActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridheight = 2;
jPanel_navigation.add(jToggleButton_followMe, gridBagConstraints);
jButton_zoomIn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/Nav-Controls-Plus-Normal.png"))); // NOI18N
jButton_zoomIn.setBorderPainted(false);
jButton_zoomIn.setContentAreaFilled(false);
jButton_zoomIn.setFocusable(false);
jButton_zoomIn.setMargin(new java.awt.Insets(0, 0, 0, 0));
jButton_zoomIn.setMaximumSize(new java.awt.Dimension(50, 50));
jButton_zoomIn.setMinimumSize(new java.awt.Dimension(50, 50));
jButton_zoomIn.setPreferredSize(new java.awt.Dimension(50, 50));
jButton_zoomIn.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/Nav-Controls-Plus-Pressed.png"))); // NOI18N
jButton_zoomIn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_zoomInActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
jPanel_navigation.add(jButton_zoomIn, gridBagConstraints);
jButton_panUp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/Nav-Controls-North-Normal.png"))); // NOI18N
jButton_panUp.setBorderPainted(false);
jButton_panUp.setContentAreaFilled(false);
jButton_panUp.setFocusable(false);
jButton_panUp.setMargin(new java.awt.Insets(0, 0, 0, 0));
jButton_panUp.setMaximumSize(new java.awt.Dimension(50, 50));
jButton_panUp.setMinimumSize(new java.awt.Dimension(50, 50));
jButton_panUp.setPreferredSize(new java.awt.Dimension(50, 50));
jButton_panUp.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/Nav-Controls-North-Pressed.png"))); // NOI18N
jButton_panUp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_panUpActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 2;
jPanel_navigation.add(jButton_panUp, gridBagConstraints);
jButton_panLeft.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/Nav-Controls-West-Normal.png"))); // NOI18N
jButton_panLeft.setBorderPainted(false);
jButton_panLeft.setContentAreaFilled(false);
jButton_panLeft.setFocusable(false);
jButton_panLeft.setMargin(new java.awt.Insets(0, 0, 0, 0));
jButton_panLeft.setMaximumSize(new java.awt.Dimension(50, 50));
jButton_panLeft.setMinimumSize(new java.awt.Dimension(50, 50));
jButton_panLeft.setPreferredSize(new java.awt.Dimension(50, 50));
jButton_panLeft.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/Nav-Controls-West-Pressed.png"))); // NOI18N
jButton_panLeft.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_panLeftActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 3;
jPanel_navigation.add(jButton_panLeft, gridBagConstraints);
jButton_panRight.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/Nav-Controls-East-Normal.png"))); // NOI18N
jButton_panRight.setBorderPainted(false);
jButton_panRight.setContentAreaFilled(false);
jButton_panRight.setFocusable(false);
jButton_panRight.setMargin(new java.awt.Insets(0, 0, 0, 0));
jButton_panRight.setMaximumSize(new java.awt.Dimension(50, 50));
jButton_panRight.setMinimumSize(new java.awt.Dimension(50, 50));
jButton_panRight.setPreferredSize(new java.awt.Dimension(50, 50));
jButton_panRight.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/Nav-Controls-East-Pressed.png"))); // NOI18N
jButton_panRight.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_panRightActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 3;
jPanel_navigation.add(jButton_panRight, gridBagConstraints);
jButton_panDown.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/Nav-Controls-South-Normal.png"))); // NOI18N
jButton_panDown.setBorderPainted(false);
jButton_panDown.setContentAreaFilled(false);
jButton_panDown.setFocusable(false);
jButton_panDown.setMargin(new java.awt.Insets(0, 0, 0, 0));
jButton_panDown.setMaximumSize(new java.awt.Dimension(50, 50));
jButton_panDown.setMinimumSize(new java.awt.Dimension(50, 50));
jButton_panDown.setPreferredSize(new java.awt.Dimension(50, 50));
jButton_panDown.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/Nav-Controls-South-Pressed.png"))); // NOI18N
jButton_panDown.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_panDownActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = 2;
jPanel_navigation.add(jButton_panDown, gridBagConstraints);
jButton_zoomOut.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/Nav-Controls-Minus-Normal.png"))); // NOI18N
jButton_zoomOut.setBorderPainted(false);
jButton_zoomOut.setContentAreaFilled(false);
jButton_zoomOut.setFocusable(false);
jButton_zoomOut.setMargin(new java.awt.Insets(0, 0, 0, 0));
jButton_zoomOut.setMaximumSize(new java.awt.Dimension(50, 50));
jButton_zoomOut.setMinimumSize(new java.awt.Dimension(50, 50));
jButton_zoomOut.setPreferredSize(new java.awt.Dimension(50, 50));
jButton_zoomOut.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/Nav-Controls-Minus-Pressed.png"))); // NOI18N
jButton_zoomOut.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_zoomOutActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTH;
jPanel_navigation.add(jButton_zoomOut, gridBagConstraints);
buttonGroup_navigationModes.add(jToggleButton_northUp);
jToggleButton_northUp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/RotateMapNorth-Normal.png"))); // NOI18N
jToggleButton_northUp.setSelected(true);
jToggleButton_northUp.setBorderPainted(false);
jToggleButton_northUp.setContentAreaFilled(false);
jToggleButton_northUp.setFocusable(false);
jToggleButton_northUp.setMargin(new java.awt.Insets(0, 0, 0, 0));
jToggleButton_northUp.setMaximumSize(new java.awt.Dimension(50, 50));
jToggleButton_northUp.setMinimumSize(new java.awt.Dimension(50, 50));
jToggleButton_northUp.setPreferredSize(new java.awt.Dimension(50, 50));
jToggleButton_northUp.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/RotateMapNorth-Pressed.png"))); // NOI18N
jToggleButton_northUp.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/RotateMapNorth-Pressed.png"))); // NOI18N
jToggleButton_northUp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton_northUpActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
jPanel_navigation.add(jToggleButton_northUp, gridBagConstraints);
buttonGroup_navigationModes.add(jToggleButton_trackUp);
jToggleButton_trackUp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/RotateMapToMovement-Normal.png"))); // NOI18N
jToggleButton_trackUp.setBorderPainted(false);
jToggleButton_trackUp.setContentAreaFilled(false);
jToggleButton_trackUp.setFocusable(false);
jToggleButton_trackUp.setMargin(new java.awt.Insets(0, 0, 0, 0));
jToggleButton_trackUp.setMaximumSize(new java.awt.Dimension(50, 50));
jToggleButton_trackUp.setMinimumSize(new java.awt.Dimension(50, 50));
jToggleButton_trackUp.setPreferredSize(new java.awt.Dimension(50, 50));
jToggleButton_trackUp.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/RotateMapToMovement-Pressed.png"))); // NOI18N
jToggleButton_trackUp.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/RotateMapToMovement-Pressed.png"))); // NOI18N
jToggleButton_trackUp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton_trackUpActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
jPanel_navigation.add(jToggleButton_trackUp, gridBagConstraints);
buttonGroup_navigationModes.add(jToggleButton_waypointUp);
jToggleButton_waypointUp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/RotateMapToWaypoint-Normal.png"))); // NOI18N
jToggleButton_waypointUp.setBorderPainted(false);
jToggleButton_waypointUp.setContentAreaFilled(false);
jToggleButton_waypointUp.setFocusable(false);
jToggleButton_waypointUp.setMargin(new java.awt.Insets(0, 0, 0, 0));
jToggleButton_waypointUp.setMaximumSize(new java.awt.Dimension(50, 50));
jToggleButton_waypointUp.setMinimumSize(new java.awt.Dimension(50, 50));
jToggleButton_waypointUp.setPreferredSize(new java.awt.Dimension(50, 50));
jToggleButton_waypointUp.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/RotateMapToWaypoint-Pressed.png"))); // NOI18N
jToggleButton_waypointUp.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/RotateMapToWaypoint-Pressed.png"))); // NOI18N
jToggleButton_waypointUp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton_waypointUpActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
jPanel_navigation.add(jToggleButton_waypointUp, gridBagConstraints);
jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator1.setMaximumSize(new java.awt.Dimension(8, 32767));
jSeparator1.setMinimumSize(new java.awt.Dimension(8, 0));
jSeparator1.setPreferredSize(new java.awt.Dimension(8, 2));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridheight = 5;
jPanel_navigation.add(jSeparator1, gridBagConstraints);
jPanel_footer.setOpaque(false);
jPanel_position.setBackground(new java.awt.Color(216, 216, 216));
jPanel_position.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
jPanel_position.setLayout(new java.awt.GridBagLayout());
jLabel_locationLabel.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jLabel_locationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel_locationLabel.setText("Location: ");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 0);
jPanel_position.add(jLabel_locationLabel, gridBagConstraints);
jLabel_location.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jLabel_location.setText("N/A");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(2, 0, 2, 2);
jPanel_position.add(jLabel_location, gridBagConstraints);
jLabel_timeLabel.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jLabel_timeLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel_timeLabel.setText("Time: ");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
jPanel_position.add(jLabel_timeLabel, gridBagConstraints);
jLabel_time.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jLabel_time.setText("N/A");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
jPanel_position.add(jLabel_time, gridBagConstraints);
jPanel_position.add(filler1, new java.awt.GridBagConstraints());
jLabel_headingLabel.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jLabel_headingLabel.setText("Heading: ");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 0);
jPanel_position.add(jLabel_headingLabel, gridBagConstraints);
jLabel_heading.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jLabel_heading.setText("N/A");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(2, 0, 2, 2);
jPanel_position.add(jLabel_heading, gridBagConstraints);
jPanel_footer.add(jPanel_position);
jPanel_mainToolbar.setFocusable(false);
jPanel_mainToolbar.setOpaque(false);
jPanel_mainToolbar.setLayout(new javax.swing.BoxLayout(jPanel_mainToolbar, javax.swing.BoxLayout.X_AXIS));
jPanel_mainToolbar.setVisible(false);
jPanel_subToolbar.setFocusable(false);
jPanel_subToolbar.setOpaque(false);
jPanel_subToolbar.setLayout(new javax.swing.BoxLayout(jPanel_subToolbar, javax.swing.BoxLayout.LINE_AXIS));
jButton_clearMessages.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/Discard-Normal.png"))); // NOI18N
jButton_clearMessages.setBorderPainted(false);
jButton_clearMessages.setContentAreaFilled(false);
jButton_clearMessages.setFocusable(false);
jButton_clearMessages.setMargin(new java.awt.Insets(0, 0, 0, 0));
jButton_clearMessages.setMaximumSize(new java.awt.Dimension(50, 50));
jButton_clearMessages.setMinimumSize(new java.awt.Dimension(50, 50));
jButton_clearMessages.setPreferredSize(new java.awt.Dimension(50, 50));
jButton_clearMessages.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/com/esri/vehiclecommander/resources/Discard-Pressed.png"))); // NOI18N
jButton_clearMessages.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_clearMessagesActionPerformed(evt);
}
});
javax.swing.GroupLayout floatingPanelLayout = new javax.swing.GroupLayout(floatingPanel);
floatingPanel.setLayout(floatingPanelLayout);
floatingPanelLayout.setHorizontalGroup(
floatingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(floatingPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(floatingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(floatingPanelLayout.createSequentialGroup()
.addComponent(jToggleButton_mainMenu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jToggleButton_grid, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(86, 86, 86)
.addComponent(jPanel_footer, javax.swing.GroupLayout.DEFAULT_SIZE, 476, Short.MAX_VALUE))
.addGroup(floatingPanelLayout.createSequentialGroup()
.addGroup(floatingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanel_left, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jToggleButton_openBasemapPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(floatingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(floatingPanelLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jToggleButton_openAnalysisToolbar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel_mainToolbar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(floatingPanelLayout.createSequentialGroup()
.addGap(70, 70, 70)
.addComponent(jPanel_subToolbar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(floatingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(floatingPanelLayout.createSequentialGroup()
.addComponent(jButton_clearMessages, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jToggleButton_911, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel_navigation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(10, 10, 10))
.addComponent(jPanel_header, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
floatingPanelLayout.setVerticalGroup(
floatingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(floatingPanelLayout.createSequentialGroup()
.addComponent(jPanel_header, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addGroup(floatingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(floatingPanelLayout.createSequentialGroup()
.addGroup(floatingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jToggleButton_openAnalysisToolbar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jToggleButton_openBasemapPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel_mainToolbar, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(floatingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel_left, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(floatingPanelLayout.createSequentialGroup()
.addComponent(jPanel_subToolbar, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(floatingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jToggleButton_mainMenu, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel_footer, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jToggleButton_grid, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(floatingPanelLayout.createSequentialGroup()
.addGroup(floatingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jToggleButton_911, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton_clearMessages, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel_navigation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(11, 11, 11))
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Vehicle Commander");
setUndecorated(!appConfigController.isDecorated());
setPreferredSize(new java.awt.Dimension(1024, 708));
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
map.addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
mapComponentResized(evt);
}
});
javax.swing.GroupLayout mapLayout = new javax.swing.GroupLayout(map);
map.setLayout(mapLayout);
mapLayout.setHorizontalGroup(
mapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 842, Short.MAX_VALUE)
);
mapLayout.setVerticalGroup(
mapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 405, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(map, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(map, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton_zoomInActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_zoomInActionPerformed
mapController.zoomIn();
}//GEN-LAST:event_jButton_zoomInActionPerformed
private void jButton_zoomOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_zoomOutActionPerformed
mapController.zoomOut();
}//GEN-LAST:event_jButton_zoomOutActionPerformed
private void jButton_panUpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_panUpActionPerformed
cancelFollowMe();
mapController.pan(MapController.PanDirection.UP);
}//GEN-LAST:event_jButton_panUpActionPerformed
private void jButton_panDownActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_panDownActionPerformed
cancelFollowMe();
mapController.pan(MapController.PanDirection.DOWN);
}//GEN-LAST:event_jButton_panDownActionPerformed
private void jButton_panLeftActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_panLeftActionPerformed
cancelFollowMe();
mapController.pan(MapController.PanDirection.LEFT);
}//GEN-LAST:event_jButton_panLeftActionPerformed
private void jButton_panRightActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_panRightActionPerformed
cancelFollowMe();
mapController.pan(MapController.PanDirection.RIGHT);
}//GEN-LAST:event_jButton_panRightActionPerformed
private void jToggleButton_mainMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton_mainMenuActionPerformed
if (jToggleButton_mainMenu.isSelected()) {
int menuWidth = getWidth() / 5;
if (300 > menuWidth) {
menuWidth = 300;
}
mainMenu.setSize(menuWidth, jToggleButton_mainMenu.getLocation().y - 5 - jToggleButton_openBasemapPanel.getLocation().y);
mainMenu.setLocation(jToggleButton_openBasemapPanel.getLocation());
mainMenu.setVisible(true);
} else {
mainMenu.setVisible(false);
mainMenu.resetMenu();
}
}//GEN-LAST:event_jToggleButton_mainMenuActionPerformed
private void jToggleButton_911ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton_911ActionPerformed
positionReportController.setStatus911(jToggleButton_911.isSelected());
}//GEN-LAST:event_jToggleButton_911ActionPerformed
private void jToggleButton_followMeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton_followMeActionPerformed
mapController.setAutoPan(jToggleButton_followMe.isSelected());
}//GEN-LAST:event_jToggleButton_followMeActionPerformed
private void jToggleButton_gridActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton_gridActionPerformed
mapController.setGridVisible(jToggleButton_grid.isSelected());
appConfigController.setShowMgrsGrid(jToggleButton_grid.isSelected());
}//GEN-LAST:event_jToggleButton_gridActionPerformed
private void jToggleButton_openAnalysisToolbarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton_openAnalysisToolbarActionPerformed
boolean visible = jToggleButton_openAnalysisToolbar.isSelected();
jPanel_mainToolbar.setVisible(visible);
if (!visible) {
//See if one of the tools in this bar is active. If so, deactivate it.
Component[] components = jPanel_mainToolbar.getComponents();
for (Component c : components) {
if (c instanceof JToggleButton) {
JToggleButton button = (JToggleButton) c;
if (button.isSelected()) {
jToggleButton_deactivateAllTools.setSelected(true);
break;
}
}
}
}
}//GEN-LAST:event_jToggleButton_openAnalysisToolbarActionPerformed
private void jToggleButton_openBasemapPanelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton_openBasemapPanelActionPerformed
if (jToggleButton_openBasemapPanel.isSelected()) {
java.awt.Point loc = (java.awt.Point) jToggleButton_openBasemapPanel.getLocation().clone();
loc.y += jToggleButton_openBasemapPanel.getHeight();
basemapsPanel.setLocation(loc);
basemapsPanel.setVisible(true);
} else {
basemapsPanel.setVisible(false);
}
}//GEN-LAST:event_jToggleButton_openBasemapPanelActionPerformed
private void jToggleButton_trackUpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton_trackUpActionPerformed
mapController.getLocationController().setNavigationMode(NavigationMode.TRACK_UP);
}//GEN-LAST:event_jToggleButton_trackUpActionPerformed
private void jToggleButton_northUpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton_northUpActionPerformed
mapController.getLocationController().setNavigationMode(NavigationMode.NORTH_UP);
mapController.setRotation(0);
}//GEN-LAST:event_jToggleButton_northUpActionPerformed
private void jToggleButton_waypointUpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton_waypointUpActionPerformed
mapController.getLocationController().setNavigationMode(NavigationMode.WAYPOINT_UP);
}//GEN-LAST:event_jToggleButton_waypointUpActionPerformed
private void mapComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_mapComponentResized
floatingPanel.setSize(map.getSize());
}//GEN-LAST:event_mapComponentResized
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
map.dispose();
//Store window location and size
Preferences prefs = Preferences.userNodeForPackage(getClass());
prefs.putInt(KEY_FRAME_EXTENDED_STATE, getExtendedState());
Dimension size = getSize();
prefs.putInt(KEY_FRAME_WIDTH, size.width);
prefs.putInt(KEY_FRAME_HEIGHT, size.height);
java.awt.Point location = getLocation();
prefs.putInt(KEY_FRAME_LOCATION_X, (int) Math.round(location.getX()));
prefs.putInt(KEY_FRAME_LOCATION_Y, (int) Math.round(location.getY()));
}//GEN-LAST:event_formWindowClosing
private void jButton_clearMessagesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_clearMessagesActionPerformed
ArrayList<String> layerNames = new ArrayList<>();
String[] messageLayerNames = symbolController.getMessageLayerNames();
for (String layerName : messageLayerNames) {
layerNames.add(layerName);
}
ClearMessagesDialog dialog = ClearMessagesDialog.getInstance(this, false, layerNames, symbolController);
java.awt.Point buttonLocation = jButton_clearMessages.getLocationOnScreen();
dialog.setLocation(buttonLocation.x - dialog.getWidth() + jButton_clearMessages.getWidth(), buttonLocation.y + jButton_clearMessages.getHeight());
dialog.setVisible(true);
}//GEN-LAST:event_jButton_clearMessagesActionPerformed
/**
* Updates the position panel with the specified location and heading.
* @param mapLocation the location to display.
* @param headingDegrees the compass heading to display, in degrees.
*/
public void updatePosition(Point mapLocation, Double headingDegrees) {
if (null != mapLocation) {
try {
String locationString;
if (appConfigController.isShowMgrs()) {
locationString = mapController.pointToMgrs(mapLocation, mapController.getSpatialReference());
} else {
SpatialReference mapSr = mapController.getSpatialReference();
if (!mapSr.isWGS84()) {
double[] coords = mapController.projectPoint(mapLocation.getX(), mapLocation.getY(), mapSr.getID(), Utilities.WGS84.getID());
mapLocation = new Point(coords[0], coords[1]);
}
locationString = String.format("%06f", mapLocation.getY()) + " " + String.format("%05f", mapLocation.getX());
}
jLabel_location.setText(locationString);
} catch (RuntimeException re) {
/**
* This probably means the map is not yet initialized, so we don't
* yet have a valid spatial reference.
*/
Logger.getLogger(getClass().getName()).log(Level.FINE, "Couldn't update position text (probably the map is not yet initialized)", re);
}
} else {
jLabel_location.setText("N/A");
}
if (null != headingDegrees) {
AngularUnit destUnit = Utilities.getAngularUnit(appConfigController.getHeadingUnits());
AngularUnit degreesUnit = Utilities.getAngularUnit(AngularUnit.Code.DEGREE);
double headingInDestUnit = headingDegrees * degreesUnit.getConversionFactor(destUnit);
jLabel_heading.setText(Long.toString(Math.round(headingInDestUnit))
+ destUnit.getAbbreviation());
} else {
jLabel_heading.setText("N/A");
}
}
/**
* Indicates whether the unit is engaged, or in other words, whether the 911
* button is depressed.
* @return true if the 911 button is depressed, and false otherwise.
*/
public boolean isEngaged() {
return jToggleButton_911.isSelected();
}
/**
* If the parameter is a valid filename, reads the file and returns the contents
* as a string; otherwise, returns the string.
* @return the file contents, if the parameter is a file; otherwise, the parameter
* itself.
*/
private static String readFileIntoStringOrReturnString(String filenameOrString) {
File licenseFile = new File(filenameOrString);
if (licenseFile.exists() && licenseFile.isFile()) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(licenseFile));
String firstLine = reader.readLine();
if (null != firstLine) {
filenameOrString = firstLine.trim();
}
reader.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(VehicleCommanderJFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ioe) {
Logger.getLogger(VehicleCommanderJFrame.class.getName()).log(Level.SEVERE, null, ioe);
} finally {
try {
reader.close();
} catch (IOException ex) {
Logger.getLogger(VehicleCommanderJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return filenameOrString;
}
/**
* Runs the application.
* @param args the command line arguments. Valid arguments:
* <ul>
* <li>-mapconfig <map configuration XML filename></li>
* <li>-license <license string or file></li>
* <li>-exts <extensions license filename> OR <extension license string 1>;<ext license 2>;...;<ext license n></li>
* <li>-clientid <client ID or file></li>
* </ul>
*/
public static void main(String args[]) {
String mapConfig = null;
String license = null;
String exts = null;
String clientId = null;
for (int i = 0; i < args.length; i++) {
if ("-mapconfig".equals(args[i]) && i < (args.length - 1)) {
mapConfig = args[++i];
} else if ("-license".equals(args[i]) && i < (args.length - 1)) {
license = readFileIntoStringOrReturnString(args[++i]);
} else if ("-exts".equals(args[i]) && i < (args.length - 1)) {
exts = readFileIntoStringOrReturnString(args[++i]);
} else if ("-clientid".equalsIgnoreCase(args[i]) && i < (args.length - 1)) {
clientId = readFileIntoStringOrReturnString(args[++i]);
}
}
final String finalMapConfig = mapConfig;
final String finalLicense = license;
final String finalExts = exts;
final String finalClientId = clientId;
String jarName = "<JAR file name>";
try {
File jarFile = new File(VehicleCommanderJFrame.class.getProtectionDomain().getCodeSource().getLocation().toURI());
jarName = jarFile.getName();
if (!jarName.endsWith(".jar")) {
jarName = "<JAR file name>";
}
} catch (URISyntaxException ex) {
}
System.out.println("Vehicle Commander " + Utilities.APP_VERSION);
System.out.println("Usage: java -jar " + jarName + "\n"
+ "\t-mapconfig \"<map config XML filename>\" (optional)\n"
+ "\t-license \"<ArcGIS Runtime license string or filename>\" (optional)\n"
+ "\t-exts \"<extensions license filename>\" OR \"<extension license string 1>;<ext license 2>;...;<ext license n>\" (optional)");
System.out.println("Starting Vehicle Commander with these parameters:");
System.out.println("\tMap configuration XML file: " + (null == finalMapConfig ? "<default>" : finalMapConfig));
System.out.println("\tArcGIS license string or file: " + (null == finalLicense ? "<default>" : finalLicense));
System.out.println("\tArcGIS extension license string or file: " + (null == finalExts ? "<default>" : finalExts));
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new VehicleCommanderJFrame(finalMapConfig, finalLicense, finalExts, finalClientId).setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup_navigationModes;
private javax.swing.ButtonGroup buttonGroup_tools;
private javax.swing.Box.Filler filler1;
private javax.swing.JPanel floatingPanel;
private javax.swing.JButton jButton_clearMessages;
private javax.swing.JButton jButton_panDown;
private javax.swing.JButton jButton_panLeft;
private javax.swing.JButton jButton_panRight;
private javax.swing.JButton jButton_panUp;
private javax.swing.JButton jButton_zoomIn;
private javax.swing.JButton jButton_zoomOut;
private javax.swing.JLabel jLabel_classification;
private javax.swing.JLabel jLabel_heading;
private javax.swing.JLabel jLabel_headingLabel;
private javax.swing.JLabel jLabel_location;
private javax.swing.JLabel jLabel_locationLabel;
private javax.swing.JLabel jLabel_time;
private javax.swing.JLabel jLabel_timeLabel;
private javax.swing.JPanel jPanel_classification;
private javax.swing.JPanel jPanel_footer;
private javax.swing.JPanel jPanel_header;
private javax.swing.JPanel jPanel_left;
private javax.swing.JPanel jPanel_mainToolbar;
private javax.swing.JPanel jPanel_navigation;
private javax.swing.JPanel jPanel_position;
private javax.swing.JPanel jPanel_subToolbar;
private javax.swing.JPanel jPanel_toolButtons;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JToggleButton jToggleButton_911;
private javax.swing.JToggleButton jToggleButton_chemLightBlue;
private javax.swing.JToggleButton jToggleButton_chemLightGreen;
private javax.swing.JToggleButton jToggleButton_chemLightRed;
private javax.swing.JToggleButton jToggleButton_chemLightYellow;
private javax.swing.JToggleButton jToggleButton_deactivateAllTools;
private javax.swing.JToggleButton jToggleButton_followMe;
private javax.swing.JToggleButton jToggleButton_grid;
private javax.swing.JToggleButton jToggleButton_mainMenu;
private javax.swing.JToggleButton jToggleButton_northUp;
private javax.swing.JToggleButton jToggleButton_openAnalysisToolbar;
private javax.swing.JToggleButton jToggleButton_openBasemapPanel;
private javax.swing.JToggleButton jToggleButton_route;
private javax.swing.JToggleButton jToggleButton_trackUp;
private javax.swing.JToggleButton jToggleButton_viewshed;
private javax.swing.JToggleButton jToggleButton_waypointUp;
private com.esri.map.JMap map;
private javax.swing.JPanel rotatableImagePanel_northArrow;
// End of variables declaration//GEN-END:variables
/**
* Called when an identify operation completes.
* @see IdentifyListener
* @param identifyPoint the point used to run the identify operation.
* @param results the identify results.
* @param resultToLayer a map of results to the layer from which each result comes.
*/
public void identifyComplete(Point identifyPoint, IdentifiedItem[] results, Map<IdentifiedItem, Layer> resultToLayer) {
if (0 < results.length) {
identifyPanel.setIdentifyPoint(identifyPoint);
identifyPanel.setResults(results, resultToLayer);
int panelWidth = getWidth() / 5;
if (300 > panelWidth) {
panelWidth = 300;
}
identifyPanel.setSize(panelWidth,
jPanel_navigation.getLocation().y + jPanel_navigation.getSize().height - jToggleButton_911.getLocation().y);
identifyPanel.setLocation(
jPanel_navigation.getLocation().x + jPanel_navigation.getWidth() - identifyPanel.getWidth(),
jToggleButton_911.getLocation().y);
identifyPanel.setVisible(true);
}
}
public void decoratedChanged(boolean isDecorated) {
if (isUndecorated() == isDecorated) {
JOptionPane.showMessageDialog(this, "You must restart the application to "
+ (isDecorated ? "add" : "remove") + " the title bar.");
}
}
public void showMessageLabelsChanged(boolean showMessageLabels) {
if (null != symbolController) {
symbolController.setShowLabels(showMessageLabels);
}
}
/**
* Adds an action button to the main toolbar.
* @param button the button to add.
*/
public void addToolbarButton(JButton button) {
jPanel_mainToolbar.add(button);
}
/**
* Adds a toggle button to the main toolbar.
* @param button the button to add.
*/
public final void addToolbarButton(ToolbarToggleButton button) {
if (button instanceof ComponentShowingButton) {
buttonGroup_tools.add(button);
}
jPanel_mainToolbar.add(button);
}
} |
/**
* Password-based decrypter of {@link JWEObject JWE objects}.
* Expects a password.
*
* <p>See RFC 7518
* <a href="https://tools.ietf.org/html/rfc7518#section-4.8">section 4.8</a>
* for more information.
*
* <p>This class is thread-safe.
*
* <p>Supports the following key management algorithms:
*
* <ul>
* <li>{@link JWEAlgorithm#PBES2_HS256_A128KW}
* <li>{@link JWEAlgorithm#PBES2_HS384_A192KW}
* <li>{@link JWEAlgorithm#PBES2_HS512_A256KW}
* </ul>
*
* <p>Supports the following content encryption algorithms:
*
* <ul>
* <li>{@link EncryptionMethod#A128CBC_HS256}
* <li>{@link EncryptionMethod#A192CBC_HS384}
* <li>{@link EncryptionMethod#A256CBC_HS512}
* <li>{@link EncryptionMethod#A128GCM}
* <li>{@link EncryptionMethod#A192GCM}
* <li>{@link EncryptionMethod#A256GCM}
* </ul>
*
* Based on code by Vladimir Dzhuvinov
*/
public class PasswordBasedDecrypter extends PasswordBasedCryptoProvider implements JWEDecrypter {
/**
* The critical header policy.
*/
private final CriticalHeaderParamsDeferral critPolicy = new CriticalHeaderParamsDeferral();
/**
* Creates a new password-based decrypter.
*
* @param secretKey The Key to use for the encryption
* {@code null}.
*/
public PasswordBasedDecrypter(SecretKey secretKey) {
super(secretKey);
}
public Set<String> getProcessedCriticalHeaderParams() {
return critPolicy.getProcessedCriticalHeaderParams();
}
public Set<String> getDeferredCriticalHeaderParams() {
return critPolicy.getProcessedCriticalHeaderParams();
}
@Override
public byte[] decrypt(JWEHeader header,
Base64URLValue encryptedKey,
Base64URLValue iv,
Base64URLValue cipherText,
Base64URLValue authTag) {
// Validate required JWE parts
if (encryptedKey == null) {
throw new JOSEException("Missing JWE encrypted key");
}
if (iv == null) {
throw new JOSEException("Missing JWE initialization vector (IV)");
}
if (authTag == null) {
throw new JOSEException("Missing JWE authentication tag");
}
if (header.getPBES2Salt() == null) {
throw new JOSEException("Missing JWE \"p2s\" header parameter");
}
if (header.getPBES2Count() < 1) {
throw new JOSEException("Missing JWE \"p2c\" header parameter");
}
critPolicy.ensureHeaderPasses(header);
SecretKey cek = AESKW.unwrapCEK(secretKey, encryptedKey.decode());
return ContentCryptoProvider.decrypt(header, iv, cipherText, authTag, cek);
}
} |
"""Implementation of sample attack."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import warnings
import numpy as np
import tensorflow as tf
from tensorflow.contrib.slim.nets import inception
from PIL import Image
from cleverhans.attacks import FastGradientMethod
slim = tf.contrib.slim
tf.flags.DEFINE_string("master", "", "The address of the TensorFlow master to use.")
tf.flags.DEFINE_string(
"checkpoint_path", "", "Path to checkpoint for inception network."
)
tf.flags.DEFINE_string("input_dir", "", "Input directory with images.")
tf.flags.DEFINE_string("output_dir", "", "Output directory with images.")
tf.flags.DEFINE_float("max_epsilon", 16.0, "Maximum size of adversarial perturbation.")
tf.flags.DEFINE_integer("image_width", 299, "Width of each input images.")
tf.flags.DEFINE_integer("image_height", 299, "Height of each input images.")
tf.flags.DEFINE_integer("batch_size", 16, "How many images process at one time.")
FLAGS = tf.flags.FLAGS
def load_images(input_dir, batch_shape):
"""Read png images from input directory in batches.
Args:
input_dir: input directory
batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3]
Yields:
filenames: list file names without path of each image
Lenght of this list could be less than batch_size, in this case only
first few images of the result are elements of the minibatch.
images: array with all images from this batch
"""
images = np.zeros(batch_shape)
filenames = []
idx = 0
batch_size = batch_shape[0]
for filepath in tf.gfile.Glob(os.path.join(input_dir, "*.png")):
with tf.gfile.Open(filepath) as f:
image = np.array(Image.open(f).convert("RGB")).astype(np.float) / 255.0
# Images for inception classifier are normalized to be in [-1, 1] interval.
images[idx, :, :, :] = image * 2.0 - 1.0
filenames.append(os.path.basename(filepath))
idx += 1
if idx == batch_size:
yield filenames, images
filenames = []
images = np.zeros(batch_shape)
idx = 0
if idx > 0:
yield filenames, images
def save_images(images, filenames, output_dir):
"""Saves images to the output directory.
Args:
images: array with minibatch of images
filenames: list of filenames without path
If number of file names in this list less than number of images in
the minibatch then only first len(filenames) images will be saved.
output_dir: directory where to save images
"""
for i, filename in enumerate(filenames):
# Images for inception classifier are normalized to be in [-1, 1] interval,
# so rescale them back to [0, 1].
with tf.gfile.Open(os.path.join(output_dir, filename), "w") as f:
img = (((images[i, :, :, :] + 1.0) * 0.5) * 255.0).astype(np.uint8)
Image.fromarray(img).save(f, format="PNG")
class InceptionModel(object):
"""Model class for CleverHans library."""
def __init__(self, nb_classes=None, num_classes=None):
if num_classes is not None:
if nb_classes is not None:
raise ValueError(
"Should not specify both nb_classes and its deprecated"
" alias, num_classes"
)
warnings.warn(
"`num_classes` is deprecated. Switch to `nb_classes`."
" `num_classes` may be removed on or after 2019-04-23."
)
nb_classes = num_classes
del num_classes
self.nb_classes = nb_classes
self.built = False
def __call__(self, x_input):
"""Constructs model and return probabilities for given input."""
reuse = True if self.built else None
with slim.arg_scope(inception.inception_v3_arg_scope()):
_, end_points = inception.inception_v3(
x_input, num_classes=self.nb_classes, is_training=False, reuse=reuse
)
self.built = True
output = end_points["Predictions"]
# Strip off the extra reshape op at the output
probs = output.op.inputs[0]
return probs
def main(_):
"""Run the sample attack"""
# Images for inception classifier are normalized to be in [-1, 1] interval,
# eps is a difference between pixels so it should be in [0, 2] interval.
# Renormalizing epsilon from [0, 255] to [0, 2].
eps = 2.0 * FLAGS.max_epsilon / 255.0
batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3]
nb_classes = 1001
tf.logging.set_verbosity(tf.logging.INFO)
with tf.Graph().as_default():
# Prepare graph
x_input = tf.placeholder(tf.float32, shape=batch_shape)
model = InceptionModel(nb_classes)
fgsm = FastGradientMethod(model)
x_adv = fgsm.generate(x_input, eps=eps, clip_min=-1.0, clip_max=1.0)
# Run computation
saver = tf.train.Saver(slim.get_model_variables())
session_creator = tf.train.ChiefSessionCreator(
scaffold=tf.train.Scaffold(saver=saver),
checkpoint_filename_with_path=FLAGS.checkpoint_path,
master=FLAGS.master,
)
with tf.train.MonitoredSession(session_creator=session_creator) as sess:
for filenames, images in load_images(FLAGS.input_dir, batch_shape):
adv_images = sess.run(x_adv, feed_dict={x_input: images})
save_images(adv_images, filenames, FLAGS.output_dir)
if __name__ == "__main__":
tf.app.run()
|
/** Removes the group and optionally the contacts of the specified contacts */
public void RemoveGroup(boolean deleteContacts, TreeMap<String, String> contacts)
{
CommandRemoveGroup cmdRemoveGroup = new CommandRemoveGroup();
cmdRemoveGroup.deleteContacts = deleteContacts;
cmdRemoveGroup.Contacts = contacts;
_conn.Send(cmdRemoveGroup);
} |
<reponame>dineshkummarc/ttdashboard<filename>server/gatherer/add_room.py
from ids import FALSE_IDS
import psycopg2
from settings import *
import sys
import random
def main():
if len(sys.argv) < 2:
print "Not enought params."
return
conn = psycopg2.connect("dbname='%s' user='%s' host='%s' password='%s'" % (PG_DBNAME, PG_USER, PG_HOST, PG_PASSW))
conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
pc = conn.cursor()
roomid = sys.argv[1]
if len(roomid) < 24:
print "Roomid invalid."
pc.close()
conn.close()
return
pc.execute("SELECT * FROM bots WHERE roomid=%s", (roomid,))
rows = pc.fetchall()
if len(rows) > 0:
print "Room already on the table."
pc.close()
conn.close()
return
find = False
while not find:
userid, auth = random.choice(FALSE_IDS)
pc.execute("SELECT * FROM bots WHERE userid=%s", (userid,))
rows = pc.fetchall()
if len(rows) == 0: find = True
pc.execute("INSERT INTO bots (userid, auth, roomid) VALUES (%s, %s, %s)", (userid, auth, roomid))
print "room added"
pc.close()
conn.close()
if __name__ == '__main__':
main()
|
The Prince of Wales said it was "more important than ever" to encourage young people to become entrepreneurs.
Launching the latest campaign of his youth charity, The Prince's Trust, he said businesses should also do more to help reduce the number of young people out of work.
Small firms are the "bedrock" of any economy, he said, and setting up a company was a way to avoid unemployment at a time of job cuts.
More than a million people aged 16 to 24 do not have a job, though the national figure has fallen to its lowest level for almost a year.
Writing in The Times , Prince Charles said: "By equipping unemployed young people with the skills, confidence and motivation to move into jobs or self-employment, we can all share in the rewards of economic growth.”
He said self-employment was "an increasingly important route out of joblessness."
A YouGov poll for the charity found, two thirds of young people believe it is harder than ever to find a job. One in five said they were not looking forward to the future.
This week, the TUC warned young people faced the toughest outlook since 1994.
The union said one in five people between 16 and 24 years old were out of work and worried about the impact of unemployment on their future.
Martina Milburn, the chief executive of The Prince’s Trust, said: “It remains a difficult time for the young unemployed and the longer they are out of work the more likely they are to sink into a spiral of disappointment and depression.
“Setting up in business can be an escape route out of the dole queue for these young people — and a route to success.” |
// AllocRules allocate the match, nonmatch rule state in correspondence with the src state
func (ps *State) AllocRules() {
nlines := ps.Src.NLines()
if nlines == 0 {
return
}
if len(ps.Src.Lexs) != nlines {
return
}
ps.Matches = make([][]MatchStack, nlines)
ntot := 0
for ln := 0; ln < nlines; ln++ {
sz := len(ps.Src.Lexs[ln])
if sz > 0 {
ps.Matches[ln] = make([]MatchStack, sz)
ntot += sz
}
}
ps.NonMatches = make(ScopeRuleSet, ntot*10)
} |
// Test that sending sendResponse with an empty body and request
// against malformed URL fails.
func TestSendResponse(t *testing.T) {
req := &Request{
ResponseURL: `h\t\t\p:\//wron.com?this=wrong?=this`,
}
if err := req.sendResponse(nil, 500); err != nil {
if err.Error() != "Body of response can't be empty" {
t.Errorf("%s", err.Error())
}
}
if err := req.sendResponse([]byte("{}"), 500); err != nil {
if err.Error() != `Couldn't create request for s3-presigned-url. Error parse h\t\t\p:\//wron.com?this=wrong?=this: first path segment in URL cannot contain colon` {
t.Errorf("%s", err.Error())
}
}
} |
/// Will read result set and write pending result into `self` (if any).
pub(crate) async fn read_result_set<P>(&mut self) -> Result<()>
where
P: Protocol,
{
let packet = self.read_packet().await?;
match packet.get(0) {
Some(0x00) => self.set_pending_result(Some(P::result_set_meta(Arc::from(
Vec::new().into_boxed_slice(),
)))),
Some(0xFB) => self.handle_local_infile::<P>(&*packet).await?,
_ => self.handle_result_set::<P>(&*packet).await?,
}
Ok(())
} |
/**
* Implements the Graphical User Interface for the
* Mediaplayer component
*
* @author Chris Veigl [ [email protected]}
* Date: 30.7.2013
*/
public class GUI extends JPanel
{
private JPanel guiPanel;
private Dimension guiPanelSize;
private final MediaPlayerInstance owner;
private String actMediaFile = "";
private boolean playerCreated=false;
private boolean positionOutputRunning=false;
// The size does NOT need to match the mediaPlayer size - it's the size that
// the media will be scaled to
// Matching the native size will be faster of course
/**
* Image to render the video frame data.
*/
private MediaPlayerFactory mediaPlayerFactory;
private EmbeddedMediaPlayer mediaPlayer;
private WindowsCanvas canvas;
/**
* The class constructor, initialises the GUI
* @param owner the Slider instance
*/
public GUI(final MediaPlayerInstance owner, final Dimension space)
{
super();
System.out.println("In Constructor");
this.owner=owner;
this.setPreferredSize(new Dimension (space.width, space.height));
if (new File(owner.propPathToVLC).exists())
NativeLibrary.addSearchPath("libvlc", owner.propPathToVLC);
else if (new File("C:\\Program Files (x86)\\VideoLAN\\VLC").exists())
NativeLibrary.addSearchPath("libvlc", "C:\\Program Files (x86)\\VideoLAN\\VLC");
else if (new File("C:\\Program Files\\VideoLAN\\VLC").exists())
NativeLibrary.addSearchPath("libvlc", "C:\\Program Files\\VideoLAN\\VLC");
else
{
int n = JOptionPane.showConfirmDialog(
null, "The VLC installation could not be found in C:\\Program Files\\VideoLan or C:\\Program Files (x86)\\VideoLan .. \n please install VLC player (32 bit version).",
"VLC native library not found !",
JOptionPane.CLOSED_OPTION);
}
design (space.width, space.height);
createPlayer();
}
/**
* set up the panel and its elements for the given size
* @param width
* @param height
*/
private void design (int width, int height)
{
System.out.println("In Design");
//Create Panels
guiPanel = new JPanel ();
guiPanelSize = new Dimension (width, height);
guiPanel.setMaximumSize(guiPanelSize);
guiPanel.setPreferredSize(guiPanelSize);
guiPanel.setVisible(owner.propDisplayGui);
/*
JButton openFile = new JButton( "Open file to play" );
openFile.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
openFile();
createPlayer();
}
});
guiPanel.add (openFile,BorderLayout.PAGE_START);
*/
canvas = new WindowsCanvas();
canvas.setSize(width,height);
canvas.setVisible(owner.propDisplayGui);
guiPanel.add(canvas);
guiPanel.revalidate();
guiPanel.repaint();
this.setLayout(new BorderLayout());
add (guiPanel,BorderLayout.PAGE_START);
}
/*
private void openFile()
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
int result = fileChooser.showOpenDialog( this );
// user clicked Cancel button on dialog
if ( result == JFileChooser.CANCEL_OPTION )
file = null;
else
file = fileChooser.getSelectedFile();
}
*/
private void createPlayer()
{
//Creation a media player :
System.out.println("Creating Player");
mediaPlayerFactory = new MediaPlayerFactory();
mediaPlayer = mediaPlayerFactory.newEmbeddedMediaPlayer();
CanvasVideoSurface videoSurface = mediaPlayerFactory.newVideoSurface(canvas);
if (owner.propDisplayGui == true)
mediaPlayer.setVideoSurface(videoSurface);
playerCreated=true;
owner.playerActive=true;
}
public void play(String mediafile)
{
System.out.println("Play method called !!");
positionOutputRunning=false;
if (!actMediaFile.equals(mediafile)) stop();
if (playerCreated==false) createPlayer();
if (playerCreated==true)
{
if (mediaPlayer.getMediaPlayerState().toString().equals("libvlc_Ended"))
mediaPlayer.stop();
if (!actMediaFile.equals(mediafile))
{
//System.out.println("Trying to open and play file:"+ mediafile);
mediaPlayer.playMedia(mediafile);
actMediaFile=mediafile;
}
else
{
//System.out.println("Trying to play mediafile");
mediaPlayer.play();
}
AstericsThreadPool.instance.execute(new Runnable() {
public void run()
{
positionOutputRunning=true;
System.out.println("Started Position Report Thread");
while (positionOutputRunning)
{
try
{
Thread.sleep(250);
}
catch (InterruptedException e) {}
if (positionOutputRunning==true)
owner.opActPos.sendData(ConversionUtils.doubleToBytes(mediaPlayer.getPosition()*100));
}
System.out.println("Ended Position Report Thread ");
}
}
);
}
}
public void pause()
{
System.out.println("Pause");
if (playerCreated==true)
{
mediaPlayer.pause();
}
}
public void stop()
{
System.out.println("Stop");
positionOutputRunning=false;
if (playerCreated==true)
{
System.out.println("Sending Stop to player");
mediaPlayer.stop();
}
}
public void disposePlayer()
{
System.out.println("Dispose Player");
owner.playerActive=false;
if (mediaPlayer!=null)
{
mediaPlayer.stop();
mediaPlayer.release();
}
playerCreated=false;
actMediaFile="";
}
public void setRate(double rate)
{
if (playerCreated==true)
{
mediaPlayer.setRate((float)(rate/100));
}
}
public void setPosition(double position)
{
System.out.println("Setposition");
if (playerCreated==true)
{
// System.out.println(mediaPlayer.getMediaPlayerState().toString());
if (mediaPlayer.getMediaPlayerState().toString().equals("libvlc_Paused"))
{ mediaPlayer.setPosition((float) position/100); }
else
if (mediaPlayer.getMediaPlayerState().toString().equals("libvlc_Ended"))
{ mediaPlayer.stop(); mediaPlayer.play();}
else
if (mediaPlayer.getMediaPlayerState().toString().equals("libvlc_Playing"))
{ mediaPlayer.pause(); }
}
}
} |
/**
* Ignite benchmark that performs query operations.
*/
public class IgniteSqlQueryBenchmark extends IgniteCacheAbstractBenchmark<Integer, Object> {
/** Last salary. */
private static final String LAST_SALARY = "LAST_SALARY";
/** Salary step. */
private static final int SALARY_STEP = 1000;
/** */
private static final int SALARY_RANGE = 10 * SALARY_STEP;
/** {@inheritDoc} */
@Override public void setUp(BenchmarkConfiguration cfg) throws Exception {
super.setUp(cfg);
loadCachesData();
}
/** {@inheritDoc} */
@Override protected void loadCacheData(String cacheName) {
try (IgniteDataStreamer<Integer, Person> dataLdr = ignite().dataStreamer(cacheName)) {
for (int i = 0; i < args.range(); i++) {
if (i % 100 == 0 && Thread.currentThread().isInterrupted())
break;
dataLdr.addData(i, new Person(i, "firstName" + i, "lastName" + i, i * SALARY_STEP));
if (i % 100000 == 0)
println(cfg, "Populated persons: " + i);
}
}
}
/** {@inheritDoc} */
@Override public boolean test(Map<Object, Object> ctx) throws Exception {
double minSalary = (double)ctx.getOrDefault(LAST_SALARY, 0.0);
double maxSalary = minSalary + SALARY_RANGE;
List<List<?>> rows = executeQuery(minSalary, maxSalary);
for (List<?> row : rows) {
double salary = (Double)row.get(0);
if (salary < minSalary || salary > maxSalary)
throw new Exception("Invalid person retrieved [min=" + minSalary + ", max=" + maxSalary +
", salary=" + salary + ']');
}
double newMinSalary = maxSalary - SALARY_RANGE * 1.0 / 2;
if (newMinSalary + SALARY_RANGE > args.range() * SALARY_STEP)
newMinSalary = 0.0;
ctx.put(LAST_SALARY, newMinSalary);
return true;
}
/**
* @param minSalary Min salary.
* @param maxSalary Max salary.
* @return Query result.
* @throws Exception If failed.
*/
private List<List<?>> executeQuery(double minSalary, double maxSalary) {
IgniteCache<Integer, Object> cache = cacheForOperation(true);
SqlFieldsQuery qry = new SqlFieldsQuery("select salary, id, firstName, lastName from Person where salary >= ? and salary <= ?");
qry.setArgs(minSalary, maxSalary);
return cache.query(qry).getAll();
}
/** {@inheritDoc} */
@Override protected IgniteCache<Integer, Object> cache() {
return ignite().cache("query");
}
} |
def validate(self):
if not self.expression:
raise ScheduleError("Task is missing a schedule")
if self.expression.startswith("cron(") and self.expression.endswith(")"):
self.expression = self._validate_cron()
elif self.expression == "delete":
pass
else:
raise ScheduleError(
f'invalid schedule {self.expression}. Use a cron() schedule or "delete" to remove a schedule that already exists'
)
if self._configuration_errors:
raise ScheduleError(".".join(self._configuration_errors)) |
<gh_stars>0
package serp.bytecode;
import serp.bytecode.visitor.BCVisitor;
import serp.util.Strings;
/**
* A conversion opcode such as <code>i2l, f2i</code>, etc.
* Changing the types of the instruction will automatically
* update the underlying opcode. Converting from one type to the same
* type will result in a <code>nop</code>.
*
* @author <NAME>
*/
public class ConvertInstruction extends TypedInstruction {
private static final Class<?>[][] _mappings = new Class[][] {
{ boolean.class, int.class },
{ void.class, int.class },
{ Object.class, int.class },
};
private static final Class<?>[][] _fromMappings = new Class[][] {
{ boolean.class, int.class },
{ void.class, int.class },
{ Object.class, int.class },
{ byte.class, int.class },
{ char.class, int.class },
{ short.class, int.class },
};
String _toType = null;
String _fromType = null;
ConvertInstruction(Code owner) {
super(owner);
}
ConvertInstruction(Code owner, int opcode) {
super(owner, opcode);
}
public int getLogicalStackChange() {
return 0;
}
public int getStackChange() {
switch (getOpcode()) {
case Constants.I2L:
case Constants.I2D:
case Constants.F2L:
case Constants.F2D:
return 1;
case Constants.L2I:
case Constants.L2F:
case Constants.D2I:
case Constants.D2F:
return -1;
default:
return 0;
}
}
public String getTypeName() {
switch (getOpcode()) {
case Constants.L2I:
case Constants.F2I:
case Constants.D2I:
return int.class.getName();
case Constants.I2L:
case Constants.F2L:
case Constants.D2L:
return long.class.getName();
case Constants.I2F:
case Constants.L2F:
case Constants.D2F:
return float.class.getName();
case Constants.I2D:
case Constants.L2D:
case Constants.F2D:
return double.class.getName();
case Constants.I2B:
return byte.class.getName();
case Constants.I2C:
return char.class.getName();
case Constants.I2S:
return short.class.getName();
default:
return _toType;
}
}
public TypedInstruction setType(String type) {
String toType = mapType(type, _mappings, true);
String fromType = getFromTypeName();
// if no valid opcode, remember current types in case they reset one
// to create a valid opcode
if (toType == null || fromType == null || toType.equals(fromType)) {
_toType = toType;
_fromType = fromType;
return (TypedInstruction) setOpcode(Constants.NOP);
}
// ok, valid conversion possible, forget saved types
_toType = null;
_fromType = null;
char to = toType.charAt(0);
char from = fromType.charAt(0);
switch (to) {
case 'i':
switch (from) {
case 'l':
return (TypedInstruction) setOpcode(Constants.L2I);
case 'f':
return (TypedInstruction) setOpcode(Constants.F2I);
case 'd':
return (TypedInstruction) setOpcode(Constants.D2I);
}
case 'l':
switch (from) {
case 'i':
return (TypedInstruction) setOpcode(Constants.I2L);
case 'f':
return (TypedInstruction) setOpcode(Constants.F2L);
case 'd':
return (TypedInstruction) setOpcode(Constants.D2L);
}
case 'f':
switch (from) {
case 'i':
return (TypedInstruction) setOpcode(Constants.I2F);
case 'l':
return (TypedInstruction) setOpcode(Constants.L2F);
case 'd':
return (TypedInstruction) setOpcode(Constants.D2F);
}
case 'd':
switch (from) {
case 'i':
return (TypedInstruction) setOpcode(Constants.I2D);
case 'l':
return (TypedInstruction) setOpcode(Constants.L2D);
case 'f':
return (TypedInstruction) setOpcode(Constants.F2D);
}
case 'b':
if (from == 'i')
return (TypedInstruction) setOpcode(Constants.I2B);
case 'C':
if (from == 'i')
return (TypedInstruction) setOpcode(Constants.I2C);
case 'S':
if (from == 'i')
return (TypedInstruction) setOpcode(Constants.I2S);
default:
throw new IllegalStateException();
}
}
/**
* Return the name of the type being converted from.
* If neither type has been set, this method will return null.
*
* @return the name of the type being converted from
*/
public String getFromTypeName() {
switch (getOpcode()) {
case Constants.I2L:
case Constants.I2F:
case Constants.I2D:
case Constants.I2B:
case Constants.I2S:
case Constants.I2C:
return int.class.getName();
case Constants.L2I:
case Constants.L2F:
case Constants.L2D:
return long.class.getName();
case Constants.F2I:
case Constants.F2L:
case Constants.F2D:
return float.class.getName();
case Constants.D2I:
case Constants.D2L:
case Constants.D2F:
return double.class.getName();
default:
return _fromType;
}
}
/**
* Return the {@link Class} of the type being converted from.
* If neither type has been set, this method will return null.
*
* @return the {@link Class} of the type being converted from
*/
public Class<?> getFromType() {
String type = getFromTypeName();
if (type == null)
return null;
return Strings.toClass(type, getClassLoader());
}
/**
* Return the bytecode of the type being converted from.
* If neither type has been set, this method will return null.
*
* @return the bytecode of the type being converted from
*/
public BCClass getFromTypeBC() {
String type = getFromTypeName();
if (type == null)
return null;
return getProject().loadClass(type, getClassLoader());
}
/**
* Set the type being converted from. Types that have no direct
* support will be converted accordingly.
*
* @param type the type to set
* @return this instruction, for method chaining
*/
public ConvertInstruction setFromType(String type) {
String fromType = mapType(type, _fromMappings, true);
String toType = getTypeName();
// if no valid opcode, remember current types in case they reset one
// to create a valid opcode
if ((toType == null) || (fromType == null) || toType.equals(fromType)) {
_toType = toType;
_fromType = fromType;
return (ConvertInstruction) setOpcode(Constants.NOP);
}
// ok, valid conversion possible, forget saved types
_toType = null;
_fromType = null;
char to = toType.charAt(0);
char from = fromType.charAt(0);
switch (from) {
case 'i':
switch (to) {
case 'l':
return (ConvertInstruction) setOpcode(Constants.I2L);
case 'f':
return (ConvertInstruction) setOpcode(Constants.I2F);
case 'd':
return (ConvertInstruction) setOpcode(Constants.I2D);
case 'b':
return (ConvertInstruction) setOpcode(Constants.I2B);
case 'c':
return (ConvertInstruction) setOpcode(Constants.I2C);
case 's':
return (ConvertInstruction) setOpcode(Constants.I2S);
}
case 'l':
switch (to) {
case 'i':
return (ConvertInstruction) setOpcode(Constants.L2I);
case 'f':
return (ConvertInstruction) setOpcode(Constants.L2F);
case 'd':
return (ConvertInstruction) setOpcode(Constants.L2D);
}
case 'f':
switch (to) {
case 'i':
return (ConvertInstruction) setOpcode(Constants.F2I);
case 'l':
return (ConvertInstruction) setOpcode(Constants.F2L);
case 'd':
return (ConvertInstruction) setOpcode(Constants.F2D);
}
case 'd':
switch (to) {
case 'i':
return (ConvertInstruction) setOpcode(Constants.D2I);
case 'l':
return (ConvertInstruction) setOpcode(Constants.D2L);
case 'f':
return (ConvertInstruction) setOpcode(Constants.D2F);
}
default:
throw new IllegalStateException();
}
}
/**
* Set the type being converted from. Types that have no direct
* support will be converted accordingly.
*
* @param type the type to set
* @return this instruction, for method chaining
*/
public ConvertInstruction setFromType(Class<?> type) {
if (type == null)
return setFromType((String) null);
return setFromType(type.getName());
}
/**
* Set the type being converted from. Types that have no direct
* support will be converted accordingly.
*
* @param type the type to set
* @return this instruction, for method chaining
*/
public ConvertInstruction setFromType(BCClass type) {
if (type == null)
return setFromType((String) null);
return setFromType(type.getName());
}
/**
* ConvertInstructions are equal if the types they convert between are either
* equal or unset.
*
* @param other the instruction to compare
* @return true if equals or unset
*/
public boolean equalsInstruction(Instruction other) {
if (other == this)
return true;
if (!(other instanceof ConvertInstruction))
return false;
ConvertInstruction ins = (ConvertInstruction) other;
if (getOpcode() != Constants.NOP && getOpcode() == ins.getOpcode())
return true;
String type = getTypeName();
String otherType = ins.getTypeName();
if (!(type == null || otherType == null || type.equals(otherType)))
return false;
type = getFromTypeName();
otherType = ins.getFromTypeName();
return type == null || otherType == null || type.equals(otherType);
}
public void acceptVisit(BCVisitor visit) {
visit.enterConvertInstruction(this);
visit.exitConvertInstruction(this);
}
void read(Instruction orig) {
super.read(orig);
ConvertInstruction ins = (ConvertInstruction) orig;
_toType = ins._toType;
_fromType = ins._fromType;
}
}
|
import pytest
from helpers.client import QueryRuntimeException
from helpers.cluster import ClickHouseCluster
from helpers.test_tools import assert_eq_with_retry
cluster = ClickHouseCluster(__file__)
node1 = cluster.add_instance(
"node1",
main_configs=["configs/config.d/clusters.xml"],
user_configs=["configs/users.d/default_with_password.xml"],
with_zookeeper=True,
)
node2 = cluster.add_instance(
"node2",
main_configs=["configs/config.d/clusters.xml"],
user_configs=["configs/users.d/default_with_password.xml"],
with_zookeeper=True,
)
node3 = cluster.add_instance(
"node3",
main_configs=["configs/config.d/clusters.xml"],
user_configs=["configs/users.d/default_with_password.xml"],
with_zookeeper=True,
)
node4 = cluster.add_instance(
"node4",
main_configs=["configs/config.d/clusters.xml"],
user_configs=["configs/users.d/default_with_password.xml"],
with_zookeeper=True,
)
node5 = cluster.add_instance(
"node5",
main_configs=["configs/config.d/clusters.xml"],
user_configs=["configs/users.d/default_with_password.xml"],
with_zookeeper=True,
)
node6 = cluster.add_instance(
"node6",
main_configs=["configs/config.d/clusters.xml"],
user_configs=["configs/users.d/default_with_password.xml"],
with_zookeeper=True,
)
@pytest.fixture(scope="module")
def start_cluster():
try:
cluster.start()
for node, shard in [
(node1, 1),
(node2, 1),
(node3, 2),
(node4, 2),
(node5, 3),
(node6, 3),
]:
node.query(
"""
CREATE TABLE test_table(date Date, id UInt32, dummy UInt32)
ENGINE = ReplicatedMergeTree('/clickhouse/tables/test{shard}/replicated', '{replica}')
PARTITION BY date
ORDER BY id
""".format(
shard=shard, replica=node.name
),
settings={"password": "<PASSWORD>"},
)
yield cluster
finally:
cluster.shutdown()
def test_truncate(start_cluster):
node1.query(
"insert into test_table values ('2019-02-15', 1, 2), ('2019-02-15', 2, 3), ('2019-02-15', 3, 4)",
settings={"password": "<PASSWORD>"},
)
assert (
node1.query(
"select count(*) from test_table", settings={"password": "<PASSWORD>"}
)
== "3\n"
)
node2.query("system sync replica test_table", settings={"password": "<PASSWORD>"})
assert (
node2.query(
"select count(*) from test_table", settings={"password": "<PASSWORD>"}
)
== "3\n"
)
node3.query(
"insert into test_table values ('2019-02-16', 1, 2), ('2019-02-16', 2, 3), ('2019-02-16', 3, 4)",
settings={"password": "<PASSWORD>"},
)
assert (
node3.query(
"select count(*) from test_table", settings={"password": "<PASSWORD>"}
)
== "3\n"
)
node4.query("system sync replica test_table", settings={"password": "<PASSWORD>"})
assert (
node4.query(
"select count(*) from test_table", settings={"password": "<PASSWORD>"}
)
== "3\n"
)
node3.query(
"truncate table test_table on cluster 'awesome_cluster'",
settings={"password": "<PASSWORD>"},
)
for node in [node1, node2, node3, node4]:
assert_eq_with_retry(
node,
"select count(*) from test_table",
"0",
settings={"password": "<PASSWORD>"},
)
node2.query(
"drop table test_table on cluster 'awesome_cluster'",
settings={"password": "<PASSWORD>"},
)
for node in [node1, node2, node3, node4]:
assert_eq_with_retry(
node,
"select count(*) from system.tables where name='test_table'",
"0",
settings={"password": "<PASSWORD>"},
)
def test_alter(start_cluster):
node5.query(
"insert into test_table values ('2019-02-15', 1, 2), ('2019-02-15', 2, 3), ('2019-02-15', 3, 4)",
settings={"password": "<PASSWORD>"},
)
node6.query(
"insert into test_table values ('2019-02-15', 4, 2), ('2019-02-15', 5, 3), ('2019-02-15', 6, 4)",
settings={"password": "<PASSWORD>"},
)
node5.query("SYSTEM SYNC REPLICA test_table", settings={"password": "<PASSWORD>"})
node6.query("SYSTEM SYNC REPLICA test_table", settings={"password": "<PASSWORD>"})
assert_eq_with_retry(
node5,
"select count(*) from test_table",
"6",
settings={"password": "<PASSWORD>"},
)
assert_eq_with_retry(
node6,
"select count(*) from test_table",
"6",
settings={"password": "<PASSWORD>"},
)
node6.query(
"OPTIMIZE TABLE test_table ON CLUSTER 'simple_cluster' FINAL",
settings={"password": "<PASSWORD>"},
)
node5.query("SYSTEM SYNC REPLICA test_table", settings={"password": "<PASSWORD>"})
node6.query("SYSTEM SYNC REPLICA test_table", settings={"password": "<PASSWORD>"})
assert_eq_with_retry(
node5,
"select count(*) from test_table",
"6",
settings={"password": "<PASSWORD>"},
)
assert_eq_with_retry(
node6,
"select count(*) from test_table",
"6",
settings={"password": "<PASSWORD>"},
)
node6.query(
"ALTER TABLE test_table ON CLUSTER 'simple_cluster' DETACH PARTITION '2019-02-15'",
settings={"password": "<PASSWORD>"},
)
assert_eq_with_retry(
node5,
"select count(*) from test_table",
"0",
settings={"password": "<PASSWORD>"},
)
assert_eq_with_retry(
node6,
"select count(*) from test_table",
"0",
settings={"password": "<PASSWORD>"},
)
with pytest.raises(QueryRuntimeException):
node6.query(
"ALTER TABLE test_table ON CLUSTER 'simple_cluster' ATTACH PARTITION '2019-02-15'",
settings={"password": "<PASSWORD>"},
)
node5.query(
"ALTER TABLE test_table ATTACH PARTITION '2019-02-15'",
settings={"password": "<PASSWORD>"},
)
assert_eq_with_retry(
node5,
"select count(*) from test_table",
"6",
settings={"password": "<PASSWORD>"},
)
assert_eq_with_retry(
node6,
"select count(*) from test_table",
"6",
settings={"password": "<PASSWORD>"},
)
node5.query(
"ALTER TABLE test_table ON CLUSTER 'simple_cluster' MODIFY COLUMN dummy String",
settings={"password": "<PASSWORD>"},
)
assert_eq_with_retry(
node5,
"select length(dummy) from test_table ORDER BY dummy LIMIT 1",
"1",
settings={"password": "<PASSWORD>"},
)
assert_eq_with_retry(
node6,
"select length(dummy) from test_table ORDER BY dummy LIMIT 1",
"1",
settings={"password": "<PASSWORD>"},
)
node6.query(
"ALTER TABLE test_table ON CLUSTER 'simple_cluster' DROP PARTITION '2019-02-15'",
settings={"password": "<PASSWORD>"},
)
assert_eq_with_retry(
node5,
"select count(*) from test_table",
"0",
settings={"password": "<PASSWORD>"},
)
assert_eq_with_retry(
node6,
"select count(*) from test_table",
"0",
settings={"password": "<PASSWORD>"},
)
|
package com.quancheng.saluki.domain;
import java.util.Set;
import org.apache.commons.lang3.tuple.Pair;
import com.google.common.collect.Sets;
public class ApplicationDependcy {
private String appName;
private Set<SalukiAppDependcyParent> dependcyApps;
public ApplicationDependcy(String appName){
this.appName = appName;
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public Set<SalukiAppDependcyParent> getDependcyApps() {
return dependcyApps;
}
public void setDependcyApps(Set<SalukiAppDependcyParent> dependcyApps) {
this.dependcyApps = dependcyApps;
}
public void addDependcyApps(SalukiAppDependcyParent dependcyApp) {
if (this.dependcyApps == null) {
this.dependcyApps = Sets.newHashSet();
}
this.dependcyApps.add(dependcyApp);
}
public void addDependcyService(String parentApp, Pair<String, Integer> serviceCallCount) {
if (this.dependcyApps == null) {
this.dependcyApps = Sets.newHashSet();
}
SalukiAppDependcyParent parentToAdd = null;
for (SalukiAppDependcyParent parent : this.dependcyApps) {
if (parentApp.equals(parent.getAppName())) {
parentToAdd = parent;
}
}
if (parentToAdd == null) {
parentToAdd = new SalukiAppDependcyParent();
parentToAdd.setAppName(parentApp);
}
parentToAdd.addDependcyService(serviceCallCount);
this.dependcyApps.add(parentToAdd);
}
public static class SalukiAppDependcyParent {
private String appName;
private Set<SalukiServiceDependcy> dependcyServices;
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public Set<SalukiServiceDependcy> getDependcyServices() {
return dependcyServices;
}
public void setDependcyServices(Set<SalukiServiceDependcy> dependcyServices) {
this.dependcyServices = dependcyServices;
}
public void addDependcyService(Pair<String, Integer> serviceCallCount) {
if (this.dependcyServices == null) {
this.dependcyServices = Sets.newHashSet();
}
this.dependcyServices.add(new SalukiServiceDependcy(serviceCallCount.getLeft(),
serviceCallCount.getRight()));
}
}
public static class SalukiServiceDependcy {
private String serviceName;
private Integer callCount;
public SalukiServiceDependcy(String serviceName, Integer callCount){
this.serviceName = serviceName;
this.callCount = callCount;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public Integer getCallCount() {
return callCount;
}
public void setCallCount(Integer callCount) {
this.callCount = callCount;
}
}
}
|
import React, { lazy, Suspense } from "react";
import { ThemeProvider } from "styled-components";
import { Reset } from "styled-reset";
import { theme } from "@template-barista/theme";
import { StyledGlobal } from "./styles/global.styled";
import { Loading } from "./Loading";
const LazyApp = lazy(
() => import("@template-barista/application/components/App")
);
export function App() {
return (
<React.Fragment>
<ThemeProvider theme={theme}>
<Reset />
<StyledGlobal />
<Suspense fallback={Loading}>
<LazyApp />
</Suspense>
</ThemeProvider>
</React.Fragment>
);
}
|
World Bulletin/News Desk
Ankara will not accept the European Parliament decision on a resolution on a dispute between Turkey and the Greek Cypriot administration, Turkey's EU chief said on Thursday.
The European Parliament is set to vote on a resolution Thursday on current tensions between Turkey and the Greek Cypriot administration over oil and gas exploration in the island’s waters.
The draft resolution demands that Turkish vessels operating in waters in and around what the Greek Cypriot administration and the EU deem to be an "exclusive economic zone" be withdrawn immediately.
"It has no validity for us," said Turkey’s Minister of EU affairs and chief negotiator Volkan Bozkir, in reference to the resolution, during a meeting with Hungary's minister of foreign affairs and trade in Ankara.
"Although Turkey is respectful towards the European Parliament’s decision, this draft resolution is likely to end up like many other resolutions," said Bozkir, implying that it will have little or no consequences.
The draft resolution, which says Turkish vessel exploration in the island is "illegal" and "provocative,” is expected to be approved by the parliament.
"Turkish vessels should be retrieved from Cyprus' Exclusive Economic Zone," the draft says.
Negotiations between Turkish Cypriots and Greek Cypriots resumed after a two-year pause in February 2013. The previous round of talks had collapsed partly because of the eurozone debt crisis impact on the government in the Greek Cypriot administration’s capital of Nicosia.
The Greek Cypriot administration suspended the most recent talks on October 7 after Turkey sent a ship to monitor an oil and gas exploration mission off the island’s coast.
Turkey and the government of the Turkish Republic of Northern Cyprus have strongly opposed any unilateral move by the Greek Cypriot administration to explore hydrocarbon resources around the island, saying its natural resources should be exploited in a fair manner under a united Cyprus.
In 1974, an attempt was made by Greek Cypriots to forcibly join the island to Athens through "enosis" (union) via a coup attempt. This was resisted by an armed Turkish peace mission in accordance with the 1960 Treaty of Guarantee. Consequently, Turkish Cypriots set up their own state in the north of the island in 1983, recognized by Turkey.
The Greek Cypriot administration is a member of the EU and internationally recognized.
Last Mod: 13 Kasım 2014, 12:52 |
package ch.heigvd.res.labs.roulette.net.client;
import ch.heigvd.res.labs.roulette.data.EmptyStoreException;
import ch.heigvd.res.labs.roulette.data.Student;
import ch.heigvd.res.labs.roulette.net.protocol.RouletteV1Protocol;
import ch.heigvd.schoolpulse.TestAuthor;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.Rule;
import org.junit.rules.ExpectedException;
/**
* This class contains automated tests to validate the client and the server
* implementation of the Roulette Protocol (version 1)
*
* @author <NAME>
*/
public class RouletteV1jermoretTest {
@Rule
public ExpectedException exception = ExpectedException.none();
@Rule
public EphemeralClientServerPair roulettePair = new EphemeralClientServerPair(RouletteV1Protocol.VERSION);
@Test
@TestAuthor(githubId = "jermoret")
public void noOneShouldBeAddedIfAnEmptyListIsPassed() throws IOException {
IRouletteV1Client client = roulettePair.getClient();
client.loadStudents(new LinkedList<Student>());
assertEquals(0, client.getNumberOfStudents());
}
@Test
@TestAuthor(githubId = "jermoret")
public void theClientShouldBeAbleToDisconnect() throws IOException {
int port = roulettePair.getServer().getPort();
IRouletteV1Client client = new RouletteV1ClientImpl();
client.connect("localhost", port);
client.disconnect();
assertFalse(client.isConnected());
}
@Test
@TestAuthor(githubId = "jermoret")
public void theClientMustBeAbleToAddStudents() throws IOException {
IRouletteV1Client client = roulettePair.getClient();
List<Student> list = new LinkedList<>();
list.add(new Student("Jerome"));
list.add(new Student("Mario"));
client.loadStudents(list);
assertEquals(2, client.getNumberOfStudents());
}
@Test
@TestAuthor(githubId = "jermoret")
public void theServerShouldntSendAnErrorWhenRandomIsCallWithStudentsInStore() throws IOException, EmptyStoreException {
try {
IRouletteV1Client client = roulettePair.getClient();
client.loadStudent("student");
client.pickRandomStudent();
} catch (EmptyStoreException ex) {
fail("Expected that EmptyStoreException would not be thrown");
}
}
@Test
@TestAuthor(githubId = "jermoret")
public void twoClientCouldBeConnectedSimultaneously() throws IOException, EmptyStoreException {
int port = roulettePair.getServer().getPort();
IRouletteV1Client client1 = new RouletteV1ClientImpl();
IRouletteV1Client client2 = new RouletteV1ClientImpl();
client1.connect("localhost", port);
client2.connect("localhost", port);
assertTrue(client1.isConnected());
assertTrue(client2.isConnected());
}
@Test
@TestAuthor(githubId = "jermoret")
public void theClient2MustHaveStudentsInsertedByTheClient1() throws IOException, EmptyStoreException {
int port = roulettePair.getServer().getPort();
IRouletteV1Client client1 = new RouletteV1ClientImpl();
IRouletteV1Client client2 = new RouletteV1ClientImpl();
client1.connect("localhost", port);
client2.connect("localhost", port);
client1.loadStudent("Jerome");
client1.loadStudent("Mario");
assertEquals(2, client2.getNumberOfStudents());
}
}
|
// RemoveLoginEventForUser removes one loginevents corresponding to id
func (s *Doc) RemoveLoginEventForUser(ctx context.Context, eppn string) error {
filter := bson.M{
"eppn": eppn,
}
_, err := s.loginEventsCollection.DeleteMany(ctx, filter)
if err != nil {
return err
}
return nil
} |
<reponame>pierreavn/angular-tabler-icons
export const IconMapPins = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path stroke="none" d="M0 0h24v24H0z" fill="none"/>
<path d="M10.828 9.828a4 4 0 1 0 -5.656 0l2.828 2.829l2.828 -2.829z" />
<line x1="8" y1="7" x2="8" y2="7.01" />
<path d="M18.828 17.828a4 4 0 1 0 -5.656 0l2.828 2.829l2.828 -2.829z" />
<line x1="16" y1="15" x2="16" y2="15.01" />
</svg>
` |
import fire
import praw
from config import config
from tqdm import tqdm
import time
class AutoPublisher(object):
"""A simple publisher for reddit and hackernews"""
def __init__(self):
self.reddit = praw.Reddit(client_id=config['redditAuth']['client_id'],
client_secret=config['redditAuth']['client_secret'],
user_agent=config['redditAuth']['user_agent'],
username=config['redditAuth']['username'],
password=config['redditAuth']['password'])
def submitUrl(self, title, url):
assert title, 'No title given'
assert url, 'No url given'
for subreddit in tqdm(config['subreddits']):
self.reddit.subreddit(subreddit).submit(title, url=url).mod.distinguish(sticky=True)
time.sleep(60 * 10) # Sleep for 10 min
if __name__ == '__main__':
fire.Fire(AutoPublisher)
|
/**
* This implementation uses strong references to the elements.
* <p/>
*
* @author bennidi
* Date: 2/12/12
*/
public class StrongConcurrentSet<T> extends AbstractConcurrentSet<T>{
public StrongConcurrentSet() {
super(new HashMap<T, ISetEntry<T>>());
}
public Iterator<T> iterator() {
return new Iterator<T>() {
private ISetEntry<T> current = head;
public boolean hasNext() {
return current != null;
}
public T next() {
if (current == null) {
return null;
}
else {
T value = current.getValue();
current = current.next();
return value;
}
}
public void remove() {
if (current == null) {
return;
}
ISetEntry<T> newCurrent = current.next();
StrongConcurrentSet.this.remove(current.getValue());
current = newCurrent;
}
};
}
@Override
protected Entry<T> createEntry(T value, Entry<T> next) {
return next != null ? new StrongEntry<T>(value, next) : new StrongEntry<T>(value);
}
public static class StrongEntry<T> extends Entry<T> {
private T value;
private StrongEntry(T value, Entry<T> next) {
super(next);
this.value = value;
}
private StrongEntry(T value) {
super();
this.value = value;
}
@Override
public T getValue() {
return value;
}
}
} |
Ant McPartlin, one half of presenting duo Ant and Dec, has checked himself into rehab for a prescription drug and alcohol problem, according to The Sun on Sunday.
The TV star says he has been going through a "difficult time" and the newspaper says he will now spend a couple of months getting treatment.
"The first step is to admit to yourself you need help," Ant said.
"I feel like I have let a lot of people down and for that I am truly sorry."
According to the newspaper some of Ant's problems began with a knee injury that didn't heal properly, leaving him in pain.
It's thought the medication he took to deal with that pain, then became an issue for him.
"I want to thank my wife, family and closest friends for helping me through this really difficult time," said Ant.
"I've spoken out because I think it's important that people ask for help if they're going through a rough time and get the proper treatment to help their recovery."
Ant and hosting partner Declan Donnelly, first appeared together as teenagers in BBC children's show Byker Grove and went on to have a brief pop career.
They've since gone on to host a variety of entertainment shows, including Britain's Got Talent, Ant and Dec's Saturday Night Takeaway and I'm a Celebrity... Get Me Out of Here.
Last month they won a Bafta for best live event for fronting The Queen's 90th Birthday Celebration in May 2016.
Ant has been married to Lisa Armstrong, who he first met in his teens, for more than a decade.
A spokesperson for Ant told Newsbeat there would be no further comment at this time.
Find us on Instagram at BBCNewsbeat and follow us on Snapchat, search for bbc_newsbeat |
import { useCallback, useRef } from 'react';
import { createPxth, deepGet, isInnerPxth, Pxth, samePxth } from 'pxth';
import invariant from 'tiny-invariant';
import { BatchUpdate, Observer } from '../typings';
import { PxthMap } from '../typings/PxthMap';
import { ObserverArray, ObserverKey } from '../utils/ObserverArray';
import { useLazyRef } from '../utils/useLazyRef';
export type ObserversControl<T> = {
/** Watch stock value. Returns cleanup function. */
watch: <V>(path: Pxth<V>, observer: Observer<V>) => () => void;
/** Watch all stock values. Returns cleanup function. */
watchAll: (observer: Observer<T>) => () => void;
/** Check if value is observed or not. */
isObserved: <V>(path: Pxth<V>) => boolean;
/** Notify all observers, which are children of specified path */
notifySubTree: <V>(path: Pxth<V>, values: T) => void;
/** Notify all observers */
notifyAll: (values: T) => void;
/** "stocked" updates values in batches, so you can subscribe to batch updates. Returns cleanup. */
watchBatchUpdates: (observer: Observer<BatchUpdate<T>>) => () => void;
};
/** Hook, wraps functionality of observers storage (add, remove, notify tree of observers, etc.) */
export const useObservers = <T>(): ObserversControl<T> => {
const observersMap = useRef<PxthMap<ObserverArray<unknown>>>(new PxthMap());
const batchUpdateObservers = useLazyRef<ObserverArray<BatchUpdate<T>>>(() => new ObserverArray());
const batchUpdate = useCallback(
(update: BatchUpdate<T>) => {
batchUpdateObservers.current.call(update);
},
[batchUpdateObservers]
);
const observeBatchUpdates = useCallback(
(observer: Observer<BatchUpdate<T>>) => batchUpdateObservers.current.add(observer),
[batchUpdateObservers]
);
const stopObservingBatchUpdates = useCallback(
(key: ObserverKey) => batchUpdateObservers.current.remove(key),
[batchUpdateObservers]
);
const observe = useCallback(<V>(path: Pxth<V>, observer: Observer<V>) => {
if (!observersMap.current.has(path)) {
observersMap.current.set(path, new ObserverArray());
}
return observersMap.current.get(path).add(observer as Observer<unknown>);
}, []);
const stopObserving = useCallback(<V>(path: Pxth<V>, observerKey: ObserverKey) => {
const currentObservers = observersMap.current.get(path);
invariant(currentObservers, 'Cannot remove observer from value, which is not observing');
currentObservers.remove(observerKey);
if (currentObservers.isEmpty()) {
observersMap.current.remove(path);
}
}, []);
const watch = useCallback(
<V>(path: Pxth<V>, observer: Observer<V>) => {
const key = observe(path, observer);
return () => stopObserving(path, key);
},
[observe, stopObserving]
);
const watchAll = useCallback((observer: Observer<T>) => watch(createPxth<T>([]), observer), [watch]);
const watchBatchUpdates = useCallback(
(observer: Observer<BatchUpdate<T>>) => {
const key = observeBatchUpdates(observer);
return () => stopObservingBatchUpdates(key);
},
[observeBatchUpdates, stopObservingBatchUpdates]
);
const isObserved = useCallback(<V>(path: Pxth<V>) => observersMap.current.has(path), []);
const notifyPaths = useCallback(
(origin: Pxth<unknown>, paths: Pxth<unknown>[], values: T) => {
batchUpdate({ paths, origin, values });
paths.forEach(path => {
const observer = observersMap.current.get(path);
const subValue = deepGet(values, path);
observer.call(subValue);
});
},
[batchUpdate]
);
const notifySubTree = useCallback(
<V>(path: Pxth<V>, values: T) => {
const subPaths = observersMap.current
.keys()
.filter(
tempPath =>
isInnerPxth(path as Pxth<unknown>, tempPath) ||
samePxth(path as Pxth<unknown>, tempPath) ||
isInnerPxth(tempPath, path as Pxth<unknown>)
);
notifyPaths(path as Pxth<unknown>, subPaths, values);
},
[notifyPaths]
);
const notifyAll = useCallback(
(values: T) => notifyPaths(createPxth([]), observersMap.current.keys(), values),
[notifyPaths]
);
return {
watch,
watchAll,
watchBatchUpdates,
isObserved,
notifySubTree,
notifyAll,
};
};
|
/**
* The Notification class is used to store the notifications that appear in the interface.
* The only reason it is not in its own file is because it is dependent on NotificationClearTimerTask.
*/
class Notification{
private int area;
private String sNotice;
private Color cNoticeColor;
private long lDuration;
private ProgressTimer NoticeTimer;
public Notification(int area, String sNotice, Color cNoticeColor, long lDuration){
this.area = area;
this.sNotice = sNotice;
this.cNoticeColor = cNoticeColor;
this.lDuration = lDuration;
this.NoticeTimer = new ProgressTimer(new NotificationClearTimerTask(area, this), lDuration);
}
public void clear(){
this.NoticeTimer.cancel();
this.NoticeTimer.purge();
}
public int getArea() {return area;}
public String getNotice() {return sNotice;}
public Color getColor() {return cNoticeColor;}
public long getDuration() {return lDuration;}
public ProgressTimer getTimer() {return NoticeTimer;}
} |
/**
* Manage elasticsearch index settings
* @author David Pilato
*/
public class ElasticsearchIndexUpdater {
private static final Logger logger = LoggerFactory.getLogger(ElasticsearchIndexUpdater.class);
/**
* Create a new index in Elasticsearch. Read also _settings.json if exists.
* @param client Elasticsearch client
* @param root dir within the classpath
* @param index Index name
* @param force Remove index if exists (Warning: remove all data)
* @throws Exception if the elasticsearch API call is failing
*/
@Deprecated
public static void createIndex(Client client, String root, String index, boolean force) throws Exception {
String json = getJsonContent(root, index, SettingsFinder.Defaults.IndexSettingsFileName);
createIndexWithSettings(client, index, json, force);
}
/**
* Create a new index in Elasticsearch
* @param client Elasticsearch client
* @param index Index name
* @param settings Settings if any, null if no specific settings
* @param force Remove index if exists (Warning: remove all data)
* @throws Exception if the elasticsearch API call is failing
*/
@Deprecated
public static void createIndexWithSettings(Client client, String index, String settings, boolean force) throws Exception {
if (force && isIndexExist(client, index)) {
logger.debug("Index [{}] already exists but force set to true. Removing all data!", index);
removeIndexInElasticsearch(client, index);
}
if (force || !isIndexExist(client, index)) {
logger.debug("Index [{}] doesn't exist. Creating it.", index);
createIndexWithSettingsInElasticsearch(client, index, settings);
} else {
logger.debug("Index [{}] already exists.", index);
}
}
/**
* Remove a new index in Elasticsearch
* @param client Elasticsearch client
* @param index Index name
* @throws Exception if the elasticsearch API call is failing
*/
@Deprecated
public static void removeIndexInElasticsearch(Client client, String index) throws Exception {
logger.trace("removeIndex([{}])", index);
assert client != null;
assert index != null;
try {
AcknowledgedResponse response = client.admin().indices().prepareDelete(index).get();
if (!response.isAcknowledged()) {
logger.warn("Could not delete index [{}]", index);
throw new Exception("Could not delete index ["+index+"].");
}
} catch (IndexNotFoundException e) {
// This is expected
}
logger.trace("/removeIndex([{}])", index);
}
/**
* Create a new index in Elasticsearch
* @param client Elasticsearch client
* @param index Index name
* @param settings Settings if any, null if no specific settings
* @throws Exception if the elasticsearch API call is failing
*/
@Deprecated
private static void createIndexWithSettingsInElasticsearch(Client client, String index, String settings) throws Exception {
logger.trace("createIndex([{}])", index);
assert client != null;
assert index != null;
CreateIndexRequestBuilder cirb = client.admin().indices().prepareCreate(index);
// If there are settings for this index, we use it. If not, using Elasticsearch defaults.
if (settings != null) {
logger.trace("Found settings for index [{}]: [{}]", index, settings);
cirb.setSource(settings, XContentType.JSON);
}
CreateIndexResponse createIndexResponse = cirb.execute().actionGet();
if (!createIndexResponse.isAcknowledged()) {
logger.warn("Could not create index [{}]", index);
throw new Exception("Could not create index ["+index+"].");
}
logger.trace("/createIndex([{}])", index);
}
/**
* Update settings in Elasticsearch
* @param client Elasticsearch client
* @param index Index name
* @param settings Settings if any, null if no update settings
*/
@Deprecated
private static void updateIndexWithSettingsInElasticsearch(Client client, String index, String settings) {
logger.trace("updateIndex([{}])", index);
assert client != null;
assert index != null;
if (settings != null) {
logger.trace("Found update settings for index [{}]: [{}]", index, settings);
logger.debug("updating settings for index [{}]", index);
client.admin().indices().prepareUpdateSettings(index).setSettings(settings, XContentType.JSON).get();
}
logger.trace("/updateIndex([{}])", index);
}
/**
* Update mapping in Elasticsearch
* @param client Elasticsearch client
* @param index Index name
* @param mapping Mapping if any, null if no update mapping
*/
@Deprecated
private static void updateMappingInElasticsearch(Client client, String index, String mapping) {
logger.trace("updateMapping([{}])", index);
assert client != null;
assert index != null;
if (mapping != null) {
logger.trace("Found update mapping for index [{}]: [{}]", index, mapping);
logger.debug("updating mapping for index [{}]", index);
client.admin().indices().preparePutMapping(index).setType("_doc").setSource(mapping, XContentType.JSON).get();
}
logger.trace("/updateMapping([{}])", index);
}
/**
* Check if an index already exists
* @param client Elasticsearch client
* @param index Index name
* @return true if index already exists
*/
@Deprecated
public static boolean isIndexExist(Client client, String index) {
return client.admin().indices().prepareExists(index).get().isExists();
}
/**
* Update index settings in Elasticsearch. Read also _update_settings.json if exists.
* @param client Elasticsearch client
* @param root dir within the classpath
* @param index Index name
*/
@Deprecated
public static void updateSettings(Client client, String root, String index) throws IOException {
String json = getJsonContent(root, index, SettingsFinder.Defaults.UpdateIndexSettingsFileName);
updateIndexWithSettingsInElasticsearch(client, index, json);
}
/**
* Update index mapping in Elasticsearch. Read also _update_mapping.json if exists.
* @param client Elasticsearch client
* @param root dir within the classpath
* @param index Index name
*/
@Deprecated
public static void updateMapping(Client client, String root, String index) throws IOException {
String json = getJsonContent(root, index, SettingsFinder.Defaults.UpdateIndexMappingFileName);
updateMappingInElasticsearch(client, index, json);
}
/**
* Create a new index in Elasticsearch. Read also _settings.json if exists.
* @param client Elasticsearch client
* @param root dir within the classpath
* @param index Index name
* @param force Remove index if exists (Warning: remove all data)
* @throws Exception if the elasticsearch API call is failing
*/
public static void createIndex(RestClient client, String root, String index, boolean force) throws Exception {
String json = getJsonContent(root, index, SettingsFinder.Defaults.IndexSettingsFileName);
createIndexWithSettings(client, index, json, force);
}
/**
* Create a new index in Elasticsearch
* @param client Elasticsearch client
* @param index Index name
* @param settings Settings if any, null if no specific settings
* @param force Remove index if exists (Warning: remove all data)
* @throws Exception if the elasticsearch API call is failing
*/
public static void createIndexWithSettings(RestClient client, String index, String settings, boolean force) throws Exception {
if (force && isIndexExist(client, index)) {
logger.debug("Index [{}] already exists but force set to true. Removing all data!", index);
removeIndexInElasticsearch(client, index);
}
if (force || !isIndexExist(client, index)) {
logger.debug("Index [{}] doesn't exist. Creating it.", index);
createIndexWithSettingsInElasticsearch(client, index, settings);
} else {
logger.debug("Index [{}] already exists.", index);
}
}
/**
* Remove a new index in Elasticsearch
* @param client Elasticsearch client
* @param index Index name
* @throws Exception if the elasticsearch API call is failing
*/
public static void removeIndexInElasticsearch(RestClient client, String index) throws Exception {
logger.trace("removeIndex([{}])", index);
assert client != null;
assert index != null;
int statusCode;
try {
Response response = client.performRequest(new Request("DELETE", "/" + index));
statusCode = response.getStatusLine().getStatusCode();
} catch (ResponseException e) {
statusCode = e.getResponse().getStatusLine().getStatusCode();
}
if (statusCode != 200 && statusCode != 404) {
logger.warn("Could not delete index [{}]", index);
throw new Exception("Could not delete index ["+index+"].");
}
logger.trace("/removeIndex([{}])", index);
}
/**
* Create a new index in Elasticsearch
* @param client Elasticsearch client
* @param index Index name
* @param settings Settings if any, null if no specific settings
* @throws Exception if the elasticsearch API call is failing
*/
private static void createIndexWithSettingsInElasticsearch(RestClient client, String index, String settings) throws Exception {
logger.trace("createIndex([{}])", index);
assert client != null;
assert index != null;
Request request = new Request("PUT", "/" + index);
// If there are settings for this index, we use it. If not, using Elasticsearch defaults.
if (settings != null) {
logger.trace("Found settings for index [{}]: [{}]", index, settings);
request.setJsonEntity(settings);
}
Response response = client.performRequest(request);
if (response.getStatusLine().getStatusCode() != 200) {
logger.warn("Could not create index [{}]", index);
throw new Exception("Could not create index ["+index+"].");
}
logger.trace("/createIndex([{}])", index);
}
/**
* Update settings in Elasticsearch
* @param client Elasticsearch client
* @param index Index name
* @param settings Settings if any, null if no update settings
* @throws Exception if the elasticsearch API call is failing
*/
private static void updateIndexWithSettingsInElasticsearch(RestClient client, String index, String settings) throws Exception {
logger.trace("updateIndex([{}])", index);
assert client != null;
assert index != null;
if (settings != null) {
logger.trace("Found update settings for index [{}]: [{}]", index, settings);
logger.debug("updating settings for index [{}]", index);
Request request = new Request("PUT", "/" + index + "/_settings");
request.setJsonEntity(settings);
client.performRequest(request);
}
logger.trace("/updateIndex([{}])", index);
}
/**
* Update mapping in Elasticsearch
* @param client Elasticsearch client
* @param index Index name
* @param mapping Mapping if any, null if no update mapping
* @throws Exception if the elasticsearch API call is failing
*/
private static void updateMappingInElasticsearch(RestClient client, String index, String mapping) throws Exception {
logger.trace("updateMapping([{}])", index);
assert client != null;
assert index != null;
if (mapping != null) {
logger.trace("Found update mapping for index [{}]: [{}]", index, mapping);
logger.debug("updating mapping for index [{}]", index);
Request request = new Request("PUT", "/" + index + "/_mapping");
request.setJsonEntity(mapping);
client.performRequest(request);
}
logger.trace("/updateMapping([{}])", index);
}
/**
* Check if an index already exists
* @param client Elasticsearch client
* @param index Index name
* @return true if index already exists
* @throws Exception if the elasticsearch API call is failing
*/
public static boolean isIndexExist(RestClient client, String index) throws Exception {
Response response = client.performRequest(new Request("HEAD", "/" + index));
return response.getStatusLine().getStatusCode() == 200;
}
/**
* Update index settings in Elasticsearch. Read also _update_settings.json if exists.
* @param client Elasticsearch client
* @param root dir within the classpath
* @param index Index name
* @throws Exception if the elasticsearch API call is failing
*/
public static void updateSettings(RestClient client, String root, String index) throws Exception {
String json = getJsonContent(root, index, SettingsFinder.Defaults.UpdateIndexSettingsFileName);
updateIndexWithSettingsInElasticsearch(client, index, json);
}
/**
* Update index mapping in Elasticsearch. Read also _update_mapping.json if exists.
* @param client Elasticsearch client
* @param root dir within the classpath
* @param index Index name
* @throws Exception if the elasticsearch API call is failing
*/
public static void updateMapping(RestClient client, String root, String index) throws Exception {
String json = getJsonContent(root, index, SettingsFinder.Defaults.UpdateIndexMappingFileName);
updateMappingInElasticsearch(client, index, json);
}
} |
An upgrade to neutral was all it took to send shares of Advanced Micro Devices Inc. surging in active trade Monday.
Macquarie analyst Srini Pajjuri, who turned bearish on AMD’s AMD, -2.02% stock in May, wrote Monday that expectations for the company now look more reasonable. While he predicts headwinds for AMD’s cryptocurrency business going forward, he also sees opportunities for the company to boost average selling prices (ASPs) for its graphics processor units (GPUs) and generate some momentum for its server business.
In upgrading AMD’s stock, Pajjuri raised his price target on shares to $11, from $10. AMD’s stock rose 6.7% in Monday trade, to close just shy of the new target. The stock was the second biggest gainer in the S&P 500 index, and was the third-most active on the Nasdaq exchange with volume of 62.8 million shares.
AMD’s Vega chip is used in Apple Inc.’s AAPL, +0.06% new iMac Pro, and the firm is working with Intel Corp. INTC, +0.24% on a new laptop chip to power gaming notebooks. Pajjuri believes these arrangements can help AMD boost ASPs, noting that while the company may have lost share of the GPU market in units during the latest quarter, he believes the company picked up revenue share. In general, he sees the company benefitting from a shift toward more expensive products.
Looking forward, he thinks that PC and GPU revenue can rise “at a high-single-digit pace in 2018 despite potential crypto-related headwinds.” There could also be “incremental opportunities” in discrete GPUs, even with Nvidia Corp.’s NVDA, -1.00% new Volta chip.
AMD CEO Lisa Su called out Hewlett Packard Enterprise Co. HPE, +0.24% as a customer for the company’s new Epyc server processor and said that HPE was now “shipping volumes” of its DL385 server. Microsoft Corp. MSFT, +0.69% and Baidu Inc. BIDU, -1.83% have also said in recent months that they would use the Epyc processor. Pajjuri sees these relationships as “encouraging” and believes they will help AMD slowly pick up some share of the server market.
“We expect a gradual revenue ramp, and won’t be surprised to see AMD gain 5 – 10% unit share in the next one to two years,” Pajjuri wrote. “Additional gains will depend on the company’s future roadmap and execution, and we believe it’s too soon to give the company the benefit of the doubt given Intel’s strong product portfolio and entrenched position.”
A better business mix and the “wins” for AMD’s server business help “limit downside” for the stock, Pajjuri added.
Shares of AMD have fallen 3.2% so far in 2017. The S&P 500 Index SPX, -0.08% is up 20% this year, while the Philadelphia Semiconductor Index SOX, -0.68% has gained 41%.
Get the top tech stories of the day delivered to your inbox. Subscribe to MarketWatch's free Tech Daily newsletter. Sign up here. |
import React from 'react';
import styled from 'styled-components';
import Tag from '../Tag';
const StyledTag = styled(Tag).attrs({
className: 'tag--destructive',
})`
--t-tag-color: ${({ theme }) => theme.colors?.tagDestructiveColor};
--t-tag-background-color: ${({ theme }) => theme.colors?.tagDestructiveBackgroundColor};
`;
export default React.memo(StyledTag);
|
Time dependence of moments of an exactly solvable Verhulst model under random perturbations
Explicit expressions for one point moments corresponding to stochastic Verhulst model driven by Markovian coloured dichotomous noise are presented. It is shown that the moments are the given functions of a decreasing exponent. The asymptotic behavior (for large time) of the moments is described by a single decreasing exponent.
Introduction
There are a lot of papers devoted to description of the temporary evolution of moments with exactly solvable nonlinear stochastic equations. In we gave some general procedure to explicitly solve the master equations of hyperbolic type corresponding to nonlinear stochastic equations driven by dichotomous noise. The method is based on a generalization of Laplace factorization method . As an example we have considered complete exact nonstationary solution of the master equations for probability distribution corresponding to stochastic Verhulst model.
In this paper we calculate one points moments of arbitrary degree and discuss its time evolution. Let us consider nonlinear stochastic dynamical systemẋ where x(t) is the dynamical variable, p(x), q(x) are given functions of x, α(t) is the random function with known statistical characteristics. The model (1) arises in different applications (see for example and bibliography therein). An important application of this model consists in study of noiseinduced transitions in physics, chemistry and biology. The functions p(x), q(x) are often taken polynomial. For example, if we set p(x) = p 1 x + p 2 x 2 , q(x) = q 2 x 2 , p 1 > 0, p 2 < 0, |p 2 | > q 2 > 0, then the equation (1) describes the population dynamics when resources (nutrition) fluctuate (Verhulst model).
In the following we will assume α(t) to be binary (dichotomic) noise α(t) = ±1 with switching frequency 2ν > 0. As one can show (see ), the averages W (x, t) = W (x, t) and W 1 (x, t) = α(t) W (x, t) for the probability density W (x, t) in the space of possible trajectories x(t) of the dynamical system (1) satisfy a system (also called "master equations"): We suppose that the initial condition W (x, 0) = W 0 (x) for the probability distribution is nonrandom. This implies that the initial condition for W 1 (x, t) at t = 0 is zero: should be nonnegative and normalized for all t: In we have obtained the following explicit form of the complete solution of the system (2) for probability distribution W (x, t): where τ = νt is the dimensionless time and x * is an initial value for (1), Here we set that ν = 1 . The function W (x, τ ) is in fact a conditional probability distribution, that is W (x, τ )∆x ≡ W (x, τ | x * , τ = 0)∆x is the probability that at the time τ the dynamical variable x belongs to interval (x, x + ∆x) under condition that at some previous initial time τ = 0 the variable x is equal to x * .
From the equation (1) follows that the dynamical variable has three stationary points: It is convenient to use the definition x 1 and x 2 for transformation of the expression (3) to the form:
Calculation of one point moments
The one point conditional moments of n-th order one defines as where (D) is the support of the probability distribution. Further we consider the case (D) = (x 1 , x 2 ). After simple calculations one obtains where Let τ → 0, then β(τ ) → x * x 2 and γ(τ ) → x * x 1 . In this limit from (6) one has κ n (τ ) → x n * . Let us consider another asymptotic τ → ∞. From (6) one obtains for n = 1 the following stationary value of the moment (ln x 2 − ln x 1 ), and for n = 1 stationary values of moments are equal to Generally the moments κ n (τ ) are given functions depending on the decreasing exponent e −τ and can be represented by a series over the powers of e −τ . In a similar representation was found for the stochastic Verhulst model with fluctuating coefficient at the first degree of the dynamical variable x. In the limit for large τ ≫ 1 the time behavior of κ n (τ ) can be described by a single exponent. Important role is played by the first two initial moments (n = 1, 2). Let us consider the moment of first order. In this case In the asymptotics τ → ∞ from (7) in first order over the infinitesimal exp(−τ ), one has It is interesting that there exists the initial value x * = 2x 1 x 2 x 1 +x 2 ≡ 1 |p 2 | . In this case the coefficient at exp(−τ ) is equal to zero. Therefore we should take into account the next order, i.e. exp(−2τ ). Physically it means that in point x * = 1 |p 2 | the correlation of variable x(τ ) with the given initial value of variable x (x(0) = x * ) decreases more rapidly at τ → ∞. When x * = 1 |p 2 | the correlations tends to stationary level as exp(−τ ).
Here we give also an explicit expression for the case n = 2: 3 Concluding remarks We have considered the time evolution of one point moments of dynamical variable corresponding to the stochastic Verhulst model. The explicit form of the moments shows that the moments are the functions of exp(−τ ). In it was shown for Verhulst model when parameter fluctuates at dynamical variable x (not x 2 ), that the exact solution for one point moments is presented by a series over powers of exp(−τ ). From formulae obtained here one can write the moments κ n (τ ) in the same form. It should be noted that in this communication we have obtained an explicit form of the solution. Under the condition τ → ∞ the moments decrease in time as single exponential function. It is shown that the time dependence of the moment κ 1 (τ ) which physically describes the correlation between the value of the dynamical variable x at the time τ with its given (nonrandom value x * ) at the initial time τ = 0 changes. This time behavior depends on the choice of the initial value x * . The critical value is x * = 1/|p 2 |. For this value of x * in the limit τ → ∞ the correlations decrease as exp(−2τ ), not as exp(−τ ). It should be noticed that the one-point moments for some special type of the dynamical system (1) with polynomial functions p(x) and q(x) Gaussian white noise fluctuation coefficient at the first power of x were considered in , where it was shown that the asymptotic behavior of the moments is described by a power function. |
/**
* This method creates and adds the AuditCluster to the Global AuditErrorMap.
*/
@SuppressWarnings("unchecked")
protected void reportAndCreateAuditCluster() {
if (auditErrors.size() > 0) {
KNSGlobalVariables.getAuditErrorMap().put(CONTACTS_AUDIT_ERRORS, new AuditCluster(Constants.CONTACTS_PANEL_NAME,
auditErrors, Constants.AUDIT_ERRORS));
}
if (auditWarnings.size() > 0) {
KNSGlobalVariables.getAuditErrorMap().put(CONTACTS_AUDIT_WARNINGS, new AuditCluster(Constants.CONTACTS_PANEL_NAME,
auditWarnings, Constants.AUDIT_WARNINGS));
}
} |
/**
* @author Bassam Al-Sarori Base class representation for executing filters. For
* executing user saved filter, the filter id should be set in
* {@link FilterRequestRepresentation#filterId} property. For executing
* dynamic filter, the filter representation should be set in
* {@link FilterRequestRepresentation#filter} property. Only
* {@link FilterRequestRepresentation#filter} or
* {@link FilterRequestRepresentation#filterId} should be set. The class
* includes parameters not included in filter, such as
* {@link FilterRequestRepresentation#page},
* {@link FilterRequestRepresentation#size}, and,
* {@link FilterRequestRepresentation#}. Subclasses can include
* additional parameters.
*/
public class FilterRequestRepresentation<T extends FilterRepresentation>
{
public static final int DEFAULT_SIZE = 50;
protected int page = 0;
protected int size = DEFAULT_SIZE;
protected Long appDefinitionId;
protected Long filterId;
protected T filter;
public int getPage()
{
return page;
}
public void setPage(int page)
{
this.page = page;
}
public int getSize()
{
return size;
}
public void setSize(int size)
{
this.size = size;
}
public Long getAppDefinitionId()
{
return appDefinitionId;
}
public void setAppDefinitionId(Long appDefinitionId)
{
this.appDefinitionId = appDefinitionId;
}
public Long getFilterId()
{
return filterId;
}
public void setFilterId(Long filterId)
{
this.filterId = filterId;
}
public T getFilter()
{
return filter;
}
public void setFilter(T filter)
{
this.filter = filter;
}
} |
from . import BaseComponent
from ..constants import Method, Notification, PromptState
from ..helpers import prepare_collect_params, prepare_media_list
from ...event import Event
from .decorators import stoppable, has_volume_control
@stoppable
@has_volume_control
class Prompt(BaseComponent):
def __init__(self, call, prompt_type, play, **kwargs):
super().__init__(call)
self._collect = prepare_collect_params(prompt_type, kwargs)
self.play = prepare_media_list(play)
self.volume_value = kwargs.get('volume', None)
self.prompt_type = prompt_type
self.confidence = None
self.input = None
self.terminator = None
@property
def event_type(self):
return Notification.COLLECT
@property
def method(self):
return Method.PLAY_AND_COLLECT
@property
def payload(self):
tmp = {
'node_id': self.call.node_id,
'call_id': self.call.id,
'control_id': self.control_id,
'play': self.play,
'collect': self._collect,
}
if self.volume_value is not None:
tmp['volume'] = float(self.volume_value)
return tmp
def notification_handler(self, params):
self.completed = True
self.unregister()
result = params['result']
if result['type'] == PromptState.SPEECH:
self.state = 'successful'
self.successful = True
self.input = result['params']['text']
self.confidence = result['params']['confidence']
elif result['type'] == PromptState.DIGIT:
self.state = 'successful'
self.successful = True
self.input = result['params']['digits']
self.terminator = result['params']['terminator']
else:
self.state = result['type']
self.successful = False
self.prompt_type = result['type']
self.event = Event(self.prompt_type, result)
if self.has_future():
self._future.set_result(True)
|
Evaluation of sleep in women with menopause: results of the Pittsburg Sleep Quality Index and polysomnography.
OBJECTIVE
To investigate subjective sleep quality among women in the menopausal period and to confirm and diagnose the possible sleep disturbances with polysomnographic (PSG) evaluation objectively.
MATERIAL AND METHODS
Sixty-seven women with menopause were enrolled in the study. Sociodemographic characteristics and the features of menopause were recorded. We assessed subjective sleep quality with Pittsburg Sleep Quality Index (PSQI). To confirm sleep disturbances and further diagnose the underlying cause, PSG evaluation was performed to women with PSQI scores of >5 who gave their approval.
RESULTS
Mean PSQI score of women with normal PSG evaluation was 12.00±3.16, while it was 11.00±2.32 in women with abnormal PSG evaluation (p=0.466); 59.7% (n=40) of women had poor sleep quality. Among these, 11 (64.7%) had abnormal results in the PSG evaluation and were diagnosed with obstructive sleep apnea syndrome (OSAS); 54.5% had mild OSAS, 27.3% had moderate, and 18.2% had severe OSAS.
CONCLUSION
PSQI and PSG evaluations would give a chance to demonstrate sleep problems and shed a light on treatment options according to the underlying causes of sleep disturbances in menopause. |
#!/usr/bin/env python
import sys
import os
import json
import urllib2
import caffe
import contextlib
import numpy as np
import classify_nsfw
def make_transformer(nsfw_net):
# Note that the parameters are hard-coded for best results
transformer = caffe.io.Transformer({'data': nsfw_net.blobs['data'].data.shape})
transformer.set_transpose('data', (2, 0, 1)) # move image channels to outermost
transformer.set_mean('data', np.array([104, 117, 123])) # subtract the dataset-mean value in each channel
transformer.set_raw_scale('data', 255) # rescale from [0, 1] to [0, 255]
transformer.set_channel_swap('data', (2, 1, 0)) # swap channels from RGB to BGR
return transformer
nsfw_net = caffe.Net(
"/opt/open_nsfw/nsfw_model/deploy.prototxt",
"/opt/open_nsfw/nsfw_model/resnet_50_1by2_nsfw.caffemodel",
caffe.TEST
)
caffe_transformer = make_transformer(nsfw_net)
def classify_from_url(image_entry, nsfw_net):
image_entry = image_entry.strip()
headers = {'User-agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5'}
result = {}
try:
req = urllib2.Request(image_entry, None, headers)
with contextlib.closing(urllib2.urlopen(req)) as stream:
score = classify(stream.read(), nsfw_net)
result = {"sfw_score": score[0], "nsfw_score": score[1]}
except urllib2.HTTPError as e:
result = {"error_reason": e.reason}
except urllib2.URLError as e:
result = {"error_reason": str(e.reason)}
except Exception as e:
result = {"error_reason": str(e)}
print(json.dumps(result))
def classify(image_data, nsfw_net):
# disable stdout
null_fds = [os.open(os.devnull, os.O_RDWR) for x in range(2)]
save = os.dup(1), os.dup(2)
os.dup2(null_fds[0], 1)
os.dup2(null_fds[1], 2)
scores = classify_nsfw.caffe_preprocess_and_compute(
image_data,
caffe_transformer=caffe_transformer,
caffe_net=nsfw_net,
output_layers=['prob']
)
# enable stdout
os.dup2(save[0], 1)
os.dup2(save[1], 2)
os.close(null_fds[0])
os.close(null_fds[1])
return scores
def main(argv):
url = sys.argv[1]
classify_from_url(url, nsfw_net)
if __name__ == "__main__":
main(sys.argv)
|
def dataset_factory(type, id):
if type == "strds":
sp = SpaceTimeRasterDataset(id)
elif type == "str3ds":
sp = SpaceTimeRaster3DDataset(id)
elif type == "stvds":
sp = SpaceTimeVectorDataset(id)
elif type == "rast" or type == "raster":
sp = RasterDataset(id)
elif type == "raster_3d" or type == "rast3d" or type == "raster3d":
sp = Raster3DDataset(id)
elif type == "vect" or type == "vector":
sp = VectorDataset(id)
else:
msgr = get_tgis_message_interface()
msgr.error(_("Unknown dataset type: %s") % type)
return None
return sp |
<reponame>rlong/browser.app.vlc-control
import {Router} from '@angular/router';
export class PageTestRoute {
// public static readonly PATH = 'test';
//
// static navigate( router: Router ) {
//
// router.navigate( [`/${PageTestRoute.PATH}`]);
// }
}
|
/**
* Assist function for removing blocks from the set, where this function
* checks the neighboring block from the insert position of the block to
* remove to see if the low neighbor needs to be decimated.
*
* @param blockToRemove - the block to decimate with
* @param locIndex - the location index to start the decimation with.
* @return true if the set was changed by this decimation.
*/
private boolean decimateLowNeighbor(RangeLongBlock blockToRemove, int locIndex)
{
boolean setWasChanged = false;
RangeLongBlock lowNeighbor = myBlockList.get(locIndex - 1);
RangeRelationType relation = lowNeighbor.getRelation(blockToRemove);
if (relation == RangeRelationType.OVERLAPS_BACK_EDGE)
{
lowNeighbor.setRange(lowNeighbor.getStart(), blockToRemove.getStart() - 1);
setWasChanged = true;
}
else if (relation == RangeRelationType.SUBSET)
{
if (blockToRemove.getEnd() == lowNeighbor.getEnd())
{
lowNeighbor.setRange(lowNeighbor.getStart(), blockToRemove.getStart() - 1);
}
else
{
long oldStart = lowNeighbor.getStart();
long oldEnd = lowNeighbor.getEnd();
lowNeighbor.setRange(oldStart, blockToRemove.getStart() - 1);
RangeLongBlock anteriorPart = new RangeLongBlock(blockToRemove.getEnd() + 1, oldEnd);
myBlockList.add(locIndex, anteriorPart);
}
setWasChanged = true;
}
return setWasChanged;
} |
package com.visitor.shop.service.impl;
import java.util.List;
import com.visitor.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.visitor.shop.mapper.MTeamMapper;
import com.visitor.shop.domain.MTeam;
import com.visitor.shop.service.IMTeamService;
import com.visitor.common.core.text.Convert;
/**
* 队伍Service业务层处理
*
* @author visitor
* @date 2019-09-06
*/
@Service
public class MTeamServiceImpl implements IMTeamService
{
@Autowired
private MTeamMapper mTeamMapper;
/**
* 查询队伍
*
* @param teamId 队伍ID
* @return 队伍
*/
@Override
public MTeam selectMTeamById(Integer teamId)
{
return mTeamMapper.selectMTeamById(teamId);
}
/**
* 查询队伍列表
*
* @param mTeam 队伍
* @return 队伍
*/
@Override
public List<MTeam> selectMTeamList(MTeam mTeam)
{
return mTeamMapper.selectMTeamList(mTeam);
}
/**
* 新增队伍
*
* @param mTeam 队伍
* @return 结果
*/
@Override
public int insertMTeam(MTeam mTeam)
{
mTeam.setCreateTime(DateUtils.getNowDate());
return mTeamMapper.insertMTeam(mTeam);
}
/**
* 修改队伍
*
* @param mTeam 队伍
* @return 结果
*/
@Override
public int updateMTeam(MTeam mTeam)
{
mTeam.setUpdateTime(DateUtils.getNowDate());
return mTeamMapper.updateMTeam(mTeam);
}
/**
* 删除队伍对象
*
* @param ids 需要删除的数据ID
* @return 结果
*/
@Override
public int deleteMTeamByIds(String ids)
{
return mTeamMapper.deleteMTeamByIds(Convert.toStrArray(ids));
}
/**
* 删除队伍信息
*
* @param teamId 队伍ID
* @return 结果
*/
public int deleteMTeamById(Integer teamId)
{
return mTeamMapper.deleteMTeamById(teamId);
}
}
|
import 'firebase/auth'
export const mapUserData = async (user) => {
const { uid, email } = user
const token = await user.getIdToken(true)
const result = await user.getIdTokenResult(true)
const isAdmin: boolean = result.claims.admin ? true : false
const isVerified: boolean = user.emailVerified
return {
id: uid,
email: email,
token: token,
verified: isVerified,
admin: isAdmin
}
}
|
<filename>qt-app/main.py
import sys
# modify the search path so we can import files from multiple directories
sys.path.insert(0, './views')
sys.path.insert(0, './models')
from patientview import *
from patientrepository import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
if __name__ == '__main__':
# create the main application widget
app = QApplication(sys.argv)
app.setWindowIcon(QIcon("img/logo.png"))
# create the main window & give it a default size, position & title
mainWin = QMainWindow()
mainWin.setGeometry(200, 100, 1000, 600)
mainWin.setWindowTitle("AIris")
# create the main toolbar
toolBar = QToolBar(mainWin)
toolBar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
mainWin.addToolBar(toolBar)
# create the main content widget & use BoxLayout to make
# sure its content stretch to max size
layout = QHBoxLayout()
centralWidget = QWidget (mainWin)
centralWidget.setLayout(layout)
mainWin.setCentralWidget(centralWidget)
# create fake patientRepository
patientRepository = PatientRepositoryStub()
# create view on patientRepository & show its contents
patientRepoView = RepoView(centralWidget, layout, toolBar, patientRepository)
patientRepoView.create()
patientRepoView.show()
# show the main window & run the app
mainWin.show()
sys.exit(app.exec_())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.