text:
---
title: Microsoft React Native Windows Team
date: 2019-10-17
time: 1-2pm PT / 8-9PM GMT
location: Q&A Channel Reactiflux
description: "Eric, Harini, and Paul are engineers @ Microsoft. They will be on to discuss their work on [React Native for Windows](https://github.com/microsoft/react-native-windows)"
people: "[@EricRozell](https://twitter.com/EricRozell) & [@Harini_Kannan](https://twitter.com/Harini_Kannan) & [@pag3rd](https://twitter.com/pag3rd)"
---

## Follow the team

- [@Harini_Kannan](https://twitter.com/Harini_Kannan) (harinik)
- [@EricRozell](https://twitter.com/EricRozell) (rozele)
- [@pag3rd](https://twitter.com/pag3rd) (pag3)
- Andrew Coates (not on twitter) (acoates)

# **Q:** How do you plan to pitch the idea of React Native to existing Windows developers? – orta

**A:** Great question. I don't know that we're planning to 'pitch' RN to existing Windows developers per se, so much as ensure it's a really terrific and first-class way to develop apps for Windows, and let developers pick what works best for them where they're coming from.

– pag3

---

# **Q:** Hi guys! What's the masterplan for [RNW][react-native-windows]? Merge it into react-native itself, so [RNW][react-native-windows] comes out of the box with the react-native-cli? Or every time I would want to support Windows, I'll need to bring in [RNW][react-native-windows] manually? – Hantar

**A:** The master plan is to be part of React Native in the same way iOS/Android are. Yes, we want to become part of react-native-cli out of the box etc., in the long term.

– harinik

---

# **Q:** Do you guys use only TypeScript or plain old JavaScript for complete projects? – JustEscaped

**A:** Internally we use mostly TypeScript.

– rozele

---

# **Q:** Why not use [Silverlight](https://www.microsoft.com/silverlight/)? Why move to React? – Ahmed

**A:** We have a lot of .NET/C# offerings for cross-platform like [Xamarin][xamarin]. We are trying to go where developers are and participating in the React world helps us bring our native Windows stack to the web development community in addition.

– harinik

---

# **Q:** Does [Hermes](https://engineering.fb.com/android/hermes/) seem like a good fit for [RNW][react-native-windows]? – Jeremy

**A:** Yes we have it running internally and hope to have it available in the public builds as an option soon.

– acoates

---

# **Q:** Why is Microsoft using React Native (Windows) for their applications? Hasn't Microsoft invested in Universal Windows Platform for a long time as a cross platform application framework? Microsoft also has [Xamarin][xamarin], right? What has been special about React Native vs these others? Also, hi! 😄 – EliWhite

**A:** As you can imagine, a large company like Microsoft (and Facebook I'm sure, too) uses many different technologies to build our apps and experiences. React Native has taken on a lot of momentum lately because it hits a real sweet spot for teams that have a lot of JavaScript experience and want to enjoy the benefits of agile, web-like development model yet be able to achieve highly polished native experiences for their customers, especially as Microsoft focuses on bringing our experiences across the entire "Intelligent Edge" (as Satya calls it).

– pag3

---

# **Q:** What other tools and frameworks do you guys use? – JustEscaped

**A:** Microsoft is a big place, across all of our teams, probably all of them 🙂.

– rozele

---

# **Q:** Will you be supporting [react-native-navigation](https://wix.github.io/react-native-navigation/#/) by Wix. They're the only one with native navigation. And how is Microsoft planning to catch up/integrate with other current existing libraries for RN? – Hantar

**A:** We would like to, hearing a lot of chatter about this module. We have it in our backlog (https://github.com/microsoft/react-native-windows/issues/2546) to add support for.

– harinik

---

# **Q:** Could you tell me what advantages could [RNW][react-native-windows] have over [Electron][electron]? – humarkx

**A:** [RNW][react-native-windows] uses much less memory than [Electron][electron], and should generally be more performant. And the UI is fully native so you can take full advantage of the native platform including the acrylic effect that you see in a lot of Windows UI. It can be embedded in existing native apps. And it can use existing native controls.

– acoates

---

# **Q:** What possibilities for [RNWindows][react-native-windows] are you most excited about React Native "Fabric" opening up? – empyrical

**A:** Component libraries, theming and other high value controls/utilities. React Native "Fabric" really helps us round out offerings in this space not limited to the core.

– harinik

---

# **Q:** Hi, do you guys have some plans for doing such thing for other desktop platforms? Or you will leave this for other guys not from Microsoft? 🙂 – Alexandrit_T

**A:** We have the beginnings of a react-native-macOS started. We are focusing on Windows for now. Would love to hear if supporting macOS would be interesting to the community as a broader "desktop" target.

– harinik

---

# **Q:** When can we expect parity with iOS. We have a RN application, and some big customers are not willing to buy iPads in their stores, its too big of an investment. We need to port the application quickly to desktop/Windows. What do you recommend? – Christian Mokbel

**A:** We're very close to "lean core" parity in [React Native for Windows][react-native-windows] and expect to be there this quarter! In terms of the ecosystem of community modules that people use we're starting to engage in ensuring more and more of those have React Native for Windows built-in by default. We welcome feedback or asks on specific community ecosystem modules you'd like to see us prioritize.

– pag3

---

# **Q:** What are the limitations of [React Native Windows][react-native-windows]? When it is not recommended for Windows development? Do we need to use Visual Studio for it or is VS Code enough? – gamingumar

**A:** -- We are building some full enterprise level apps with [RNW][react-native-windows], so there are not too many limitations. One of the great things about React Native is that you can always add additional nativemodule and native controls. -- So there are not many limitations. As far as the base platform is concerned we are filling out the core functionality as required for our needs, so it should get filled in pretty quick.

– acoates

At this time you will need VS as well. We are trying to improve the developer experience to see if we can enable just VS Code.

– harinik

---

# **Q:** Which products are using [React Native Windows][react-native-windows] at Microsoft? – EliWhite

**A:** Several apps and experiences in Office (Outlook, Mail, Calendar, Word, Excel, Powerpoint) are using [React Native for Windows][react-native-windows]. There are a lot more coming up soon. 🤐 😉

– harinik

---

# **Q:** Will RNWindows continue to support [WPF][wpf]? – empyrical

**A:** Our teams in Microsoft have always depended on community contributors for [WPF][wpf] support, and we had some tremendous partners at BlueJeans to create and maintain that offering in the solution. Moving forward, we hope that [XAML Islands][xaml-islands] will address the needs of [WPF][wpf] users.

– rozele

---

# **Q:** Are the Microsoft apps you mentioned are fully(or mostly) using [React Native Windows][react-native-windows] or is it part of it? – Alireza Ghamkhar

**A:** Some of both. We have some apps which we are looking at complete UI rewrites, but we also have embedded scenarios within some apps. -- That's the beauty of the flexibility of RN.

– acoates

---

# **Q:** How are you guys able to keep up with the in terms of release cycles? It seems that you guys are pretty fast to catch up! How many people are working on this project? – Hantar

**A:** It's an effort - and does take a lot of work. But its important both for the community, and so that we are up to date enough to be able to contribute back to RN. We have a dedicated team working on [RNW][react-native-windows], and also since we have so many teams using the platform we also get some help from app teams too. There are probably around 30 people who work on [RNW][react-native-windows].

– acoates

---

# **Q:** I am using [React Native Windows][react-native-windows] for [WPF][wpf] app currently. With new vnext changes, [WPF][wpf] will not be supported, then what options I have? – godpranay

**A:** There is an example in the vnext repo that shows how to consume [react-native-windows][react-native-windows]@vnext in WPF through [XAML Islands][xaml-islands]. Check it out! https://github.com/microsoft/react-native-windows-samples/tree/master/samples/TodosFeed

– rozele

---

# **Q:** Why do you rewrite your apps with [RNW][react-native-windows]? Isn't it less performant? – Дикийборщ

**A:** [React Native for Windows][react-native-windows] layers on top of the modern, hardware-accelerated Windows UI ("[WinUI][winui]") stack and in many cases it's runtime performance and experience is superior to that of how apps were previously written using older generation UI technologies. In addition, using [React Native for Windows][react-native-windows] makes it more sustainable to deliver coherent experiences across native client platforms and the web as code can be shared and updated with greater agility.

– pag3

---

# **Q:** Where can we share all the dependencies that we would want ported to [RNW][react-native-windows]? – Christian Mokbel

**A:** Great question! We are tracking several that we know of in our repo (see Extensions project- https://github.com/microsoft/react-native-windows/projects/6) If you can file new issues for dependencies you would like to see supported, that would be great!

– harinik

---

# **Q:** When will vnext become the "current" version? It seems like it is significantly better and faster! – EliWhite

**A:** 😃 Very soon. We plan to have most API parity with react-native and native modules/view manager authoring stories at par with the "current" version before the end of the year at which time vnext will replace current. You can see our prospective roadmap here - https://github.com/microsoft/react-native-windows/blob/master/blog/Roadmap2019.md.

– harinik

---

# **Q:** We've heard before with [WPF][wpf], [Silverlight](https://www.microsoft.com/silverlight/), [WinRT](https://docs.microsoft.com/en-us/windows/uwp/cpp-and-winrt-apis/), and [UWP][uwp], that support would continue, how can we trust this time Microsoft is fully invested in [RNW][react-native-windows]? – Mark "Elsewhere" Lynch

**A:** You missed [WinJS](https://github.com/winjs/winjs). 😉 All kidding aside, I think a general rule of thumb in trusting whether any given technology company is going to support a technology long term and how durable it is for you to build on: are they eating their own dogfood and using it themselves? If so, it makes it harder for them to abandon it without incurring the cost of rewriting their own experiences. So instead of listening to what companies and their marketing say, see what they do.

I think you can look at the list of technologies you mentioned and think about which ones has Microsoft actually used to build their own key experiences and which ones were primarily marketed to third party developers but not really used by Microsoft itself. [WinRT](https://docs.microsoft.com/en-us/windows/uwp/cpp-and-winrt-apis/)/[UWP][uwp] are good examples of technologies that Microsoft has deeply invested in building the Windows, Xbox, and tons of app experiences on top of so it'd be quite an expensive and complex undertaking for Microsoft not to continue to invest in those. [React Native for Windows][react-native-windows] layers on top of that whole technology stack and you can see some of the experiences we've already talked about building using that.

– pag3

---

# **Q:** With vnext [RNW][react-native-windows], to customize UI Component or write my own native UI component, I will have to know C++. Is it correct? – godpranay

**A:** No; We wrote the core of [RNW][react-native-windows] in C++ for the best performance, but we plan to fully support writing native modules or native views in C# or C++. -- Community modules will likely want to be in C++ so that you dont require other apps to load the CLR. We are just starting to get examples of custom native modules and view managers in the repo.

– acoates

---

# **Q:** What changes in React Native are you most excited about and why? – EliWhite

**A:** Hermes is a big one - we all like better perf. Turbo modules is probably next, and we hope that will allow our native modules story to better align with the rest of the platforms in the future (as well as the obvious perf improvements). And then finally fabric is exciting, for basically the same reasons as people want it for the other platforms.

– acoates

---

# **Q:** How does this project relate to [ReactXP](https://microsoft.github.io/reactxp/)? – metamarcdw

**A:** [ReactXP](https://microsoft.github.io/reactxp/) is a layer on top of ReactNative to try to get a more write once experience when targeting multiple platforms. [ReactXP](https://microsoft.github.io/reactxp/) should work on top of [react-native-windows][react-native-windows].

– acoates

[ReactXP](https://microsoft.github.io/reactxp/) is an abstraction layer over react-native and react-dom to enable you to write common UI code for either Web clients or React Native clients, including [react-native-windows][react-native-windows]!

– rozele

---

# **Q:** What's the debugging story like between managed .NET code and Javascript code? Assuming there is some interop layer, does a developer have to have two debugger instances attached to see how data is flowing between the two? – dustinsoftware

**A:** You would indeed need two debugger instances, my typical debugging work flow is to launch the app from Visual Studio in debug mode to debug native behaviors and spin up VS Code to attach to the JS runtime. Often I'm debugging either one or the other, so it's rare that I'm actually debugging both, but nothing would stop me from doing that.

– rozele

---

# **Q:** Are there any community uses of [RNW][react-native-windows] you'd like to give a shoutout? – empyrical

**A:** BlueJeans was a tremendous partner and early adopter, and even though they only originally targeted [WPF][wpf], they always tried to ensure their contributions moved the needle for both [UWP][uwp] and [WPF][wpf].

We've also received some great issues and feedback from teams at Axsy, apparel21, and I'm sure a number of other companies and individual contributors that I'm forgetting (and I'm so sorry 🙂).

In terms of react-native community members that helped us along the way that we'd love to call out: our friends at Facebook have been tremendously supportive, and community members like @grabbou and his work to enable third-party integrations in the CLI (as well as rapidly shipping bug fixes when we needed them) have been invaluable as well.

– rozele

---

# **Q:** Any plans to rebuild Skype for Windows using [RNW][react-native-windows] (instead of Electron)? – shergin

**A:** Don't know the answer to this, sorry.

– harinik

---

# **Q:** Do you think VSCode, or even full VS itself might see some pieces of [RNWindows][react-native-windows] in it in the future? – empyrical

**A:** Unfortunately one of the issues with [Atom](https://atom.io/)/[Electron][electron] is that its hard to mix in native UI. So it would be hard for VSCode to start using [RNWindows][react-native-windows]. I dont know of any current plans for full VS to use [RNW][react-native-windows], but I can think of some shared experiences that are starting to use RNW which might eventually make it there.

– acoates

---

# **Q:** My Windows app is [WPF][wpf] app and supports Windows 7, and we are using [RNW][react-native-windows] 0.57. Will we be able to upgrade to 0.60 and beyond as [RNW][react-native-windows] is re-written? – godpranay

**A:** We are not investing in the [WPF][wpf] implementation at this time. As @rozele mentioned earlier, the way forward would be to use [RNW][react-native-windows] vNext + [XamlIslands][xaml-islands] for [WPF][wpf] apps. Here is an example of how to do this - https://github.com/microsoft/react-native-windows-samples/tree/master/samples/TodosFeed.

– harinik

---

# **Q:** Is there a feature you would like to see in RN core that might make things easier for [RNWindows][react-native-windows]? – empyrical

**A:** Lean core helps, long term I'd love if we could get more of the RN core code to be in CxxCommon, as shared C++ code rather than having separate code for android, ios and windows (and other platforms). Fabric probably helps with this. I'd like it if more of the instance management stuff could get there too.

– acoates

We have several proposals our team members have put up on https://github.com/react-native-community/discussions-and-proposals for features we've brought to [React Native Windows][react-native-windows] that we think would make sense to bring to RN core including around accessibility, keyboarding, light/dark theme, etc. Our intention is to work with the community to bring our knowledge/expertise to RN core and make it better for everyone.

For examples see https://github.com/react-native-community/discussions-and-proposals/pull/146 and https://github.com/microsoft/react-native-windows-specs/blob/harinikmsft-keyboardapis/proposals/0000-keyboard-apis.md.

– pag3

---

# **Q:** Hey guys will we have any native file system API? – Reacted Boy

**A:** There is a popular community module for fs (https://github.com/itinance/react-native-fs) and also an [Expo](https://expo.io) module (https://docs.expo.io/versions/latest/sdk/filesystem/). We would love to have these supported for Windows as well. May not be able to get to everything ourselves, would love the community's help!

– harinik

---

# **Q:** What are the best [RNW][react-native-windows] example apps to take a look at? – humarkx

**A:** Check out https://github.com/microsoft/react-native-windows-samples!

– rozele

---

# **Q:** Is React Native coming on Windows 10 also? Didn't know. – Reacted Boy

**A:** 😃 Now you know!

– harinik

---

# **Q:** What's the security model like? As in, can JavaScript dependencies be run in some sort of hardened context so that a third party dependency could not overwrite things like String.prototype? Are there any restrictions on the JS context (the thread that runs v8 or whatever) so that it can't access private native or managed APIs (such as spawning a process or writing to an arbitrary file...)? – dustinsoftware

**A:** The JS code can generally only call APIs that are exposed through native modules. The native modules run as part of your apps process, so generally the security model is the same as any other app. Third party JS code runs in the same JS engine instance as the rest of your code, so in that respect its trusted as much as the rest of your app. -- Which is generally the case with any OSS / 3rd party code you use in an app. -- This the same as RN on Android and iOS.

– acoates

---

# **Q:** What technology is used for Microsoft Teams implementation? – godpranay

**A:** Teams uses several technologies including React Native in some scenarios.

– harinik

---

# **Q:** So can all of the React Native apps be converted into Windows 10 apps? – Reacted Boy

**A:** It depends - if you're using a lot of third-party modules with platform-specific code, then you might need to do a bit of work to get things up and running on Windows 10. If you're mostly just using lean core modules, you shouldn't have any problems!

– rozele

---

# **Q:** Does [React Native for Windows][react-native-windows] only let you reach desktop computers? What about Xbox and HoloLens? – EliWhite

**A:** Really good question. Since React Native for Windows layers on top of [UWP][uwp]/[WinUI][winui] it actually lets you reach not just Windows PCs but also XBox, HoloLens, Surface Hubs, the (newly announced) Surface Neo etc. Since the native platform has built in support for using things like game controller (on Xbox) and gaze (on HoloLens) and so forth, you get those behaviors and capabilities for free using React Native for Windows.

– pag3

---

# **Q:** This is so cool. Is there even a platform where you can't use React Native now after this? – KremBanan

**A:** There is a Mac and a Linux version as well 😉. Anywhere you can run JS, you should be able to run RN.

– harinik

---

# **Q:** Are there any apps made which we can test? – Reacted Boy

**A:** We have published a couple of samples here - https://github.com/microsoft/react-native-windows-samples/tree/master/samples with more to come.

– harinik

---

# **Q:** How do you guys at Microsoft handle performance? Is there any kind of specific steps you do? – KnivesQ

**A:** That's a big question. Much of the answer is going to be similar to RN on other platforms. there was a good talk by Ram at chain react for some basic steps. On the platform we are looking at how to make the primitive components as fast as possible, as well as working with the Hermes team to optimize Hermes for windows. We also have the advantage of the fact that the primary team owning RNW also owns the native UI platform, so we are looking at what changes can be made in the native UI platform to make [RNW][react-native-windows] even faster.

– acoates

[electron]: https://electronjs.org/
[react-native-windows]: https://github.com/microsoft/react-native-windows
[uwp]: https://docs.microsoft.com/en-us/windows/uwp/
[winui]: https://github.com/microsoft/microsoft-ui-xaml
[wpf]: https://docs.microsoft.com/en-us/dotnet/framework/wpf/
[xamarin]: https://dotnet.microsoft.com/apps/xamarin
[xaml-islands]: https://docs.microsoft.com/en-us/windows/apps/desktop/modernize/xaml-islands


text:
# Authority

Authority helps you authorize actions in your Ruby app. It's **ORM-neutral** and has very little fancy syntax; just group your models under one or more Authorizer classes and write plain Ruby methods on them.

Authority will work fine with a standalone app or a single sign-on system. You can check roles in a database or permissions in a YAML file. It doesn't care! What it **does** do is give you an easy way to organize your logic and handle unauthorized actions.

If you're using it with Rails controllers, it requires that you already have some kind of user object in your application, accessible via a method like `current_user` (configurable).

[![Gem Version](https://badge.fury.io/rb/authority.png)](https://rubygems.org/gems/searchlight)
[![Build Status](https://secure.travis-ci.org/nathanl/authority.png?branch=master)](http://travis-ci.org/nathanl/authority)
[![Code Climate](https://codeclimate.com/github/nathanl/authority.png)](https://codeclimate.com/github/nathanl/authority)
[![Dependency Status](https://gemnasium.com/nathanl/authority.png)](https://gemnasium.com/nathanl/authority)
[![Join the chat at https://gitter.im/nathanl/authority](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/nathanl/authority?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

## Contents

Overview

The flow of Authority

Installation

Defining Your Abilities

Wiring It Together

Users

Models

Authorizers

Passing Options

Default methods

Testing Authorizers

Controllers

Views

The Generic `can?`

Security Violations & Logging

Credits

Contributing

## Overview

Using Authority, you have:

- Broad, **class-level** rules. Examples:
  - "Basic users cannot delete any Widget."
  - "Only admin users can create Offices."
- Fine-grained, **instance-level** rules. Examples:
  - "Management users can only edit schedules with date ranges in the future."
  - "Users can't create playlists more than 20 songs long unless they've paid."
- A clear syntax for permissions-based views. Examples:
  - `link_to 'Edit Widget', edit_widget_path(@widget) if current_user.can_update?(@widget)`
  - `link_to 'Keelhaul Scallywag', keelhaul_scallywag_path(@scallywag) if current_user.can_keelhaul?(@scallywag)`
- Graceful handling of access violations: by default, it displays a "you can't do that" screen and logs the violation.
- Minimal effort and mess.

Most importantly, you have **total flexibility**: Authority does not constrain you into using a particular scheme of roles and/or permissions.

Authority lets you control access based on:

- Roles in your app's database ([rolify](http://github.com/EppO/rolify) makes this easy)
- Roles in a separate, single-sign-on app
- Users' points (like StackOverflow)
- Time and date
- Weather, stock prices, vowels in the user's name, or **anything else you can check with Ruby**

All you have to do is define the methods you need on your authorizers. You have all the flexibility of normal Ruby classes.

**You** make the rules; Authority enforces them.

## The flow of Authority

Authority encapsulates all authorization logic in `Authorizer` classes. Want to do something with a model? **Ask its authorizer**.

You can specify a model's authorizer one of two ways:

- specify the class itself: `authorizer = SomeAuthorizer`
- specify the class's name: `authorizer_name = 'SomeAuthorizer'` (useful if the constant isn't yet loaded)

If you don't specify an authorizer, the model will:

- Look for an authorizer with its name. Eg, `Comment` will look for `CommentAuthorizer`.
- If that's not found, it will use `ApplicationAuthorizer`.

**Models that have the same authorization rules should use the same authorizer**. In other words, if you would write the exact same methods on two models to determine who can create them, who can edit them, etc, then they should use the same authorizer.

Some example groupings:

         Simplest case                Logical groups                                 Most granular

      ApplicationAuthorizer        ApplicationAuthorizer                         ApplicationAuthorizer
               +                             +                                             +
               |                    +--------+-------+                 +-------------------+-------------------+
               |                    +                +                 +                   +                   +
               |             BasicAuthorizer   AdminAuthorizer  CommentAuthorizer  ArticleAuthorizer  EditionAuthorizer
               |                    +                +                 +                   +                   +
       +-------+-------+            +-+       +------+                 |                   |                   |
       +       +       +              +       +      +                 +                   +                   +
    Comment Article Edition        Comment Article Edition          Comment             Article             Edition

The authorization process generally flows like this:

                   current_user.can_create?(Article)                 # You ask this question, and the user
                               +                                     # automatically asks the model...
                               |
                               v
                 Article.creatable_by?(current_user)                 # The model automatically asks
                               +                                     # its authorizer...
                               |
                               v
               AdminAuthorizer.creatable_by?(current_user)           # *You define this method.*
                               +                                     # If you don't, the inherited one
                               |                                     # calls `default`...
                               v
        AdminAuthorizer.default(:creatable, current_user)            # *You define this method.*
                                                                     # If you don't, it will use the one
                                                                     # inherited from ApplicationAuthorizer.
                                                                     # (Its parent, Authority::Authorizer,
                                                                     # defines the method as `return false`.)

If the answer is `false` and the original caller was a controller, this is treated as a `SecurityViolation`. If it was a view, maybe you just don't show a link.

The authorization process for instances is different in that it calls the instance's `default` method before calling the class `default` method. This allows you to define default behaviour that requires access to the model instance to be determined (eg, assume any action on a blog post is allowed if that post is marked 'wiki').

(Diagrams made with [AsciiFlow](http://asciiflow.com))

## Installation

Starting from a clean commit status, add `authority` to your Gemfile, then `bundle`.

If you're using Rails, run `rails g authority:install`. Otherwise, pass a block to `Authority.configure` with [configuration options](https://github.com/nathanl/authority/blob/master/lib/generators/templates/authority_initializer.rb) somewhere when your application boots up.

## Defining Your Abilities

Edit `config/initializers/authority.rb`. That file documents all your options, but one of particular interest is `config.abilities`, which defines the verbs and corresponding adjectives in your app. The defaults are:

```ruby
config.abilities =  {
  :create => 'creatable',
  :read   => 'readable',
  :update => 'updatable',
  :delete => 'deletable'
}
```

This option determines what methods are added to your users, models and authorizers. If you need to ask `user.can_deactivate?(Satellite)` and `@satellite.deactivatable_by?(user)`, add `:deactivate => 'deactivatable'` to the hash.

## Wiring It Together

### Users

```ruby
# Whatever class represents a logged-in user in your app
class User
  # Adds `can_create?(resource)`, etc
  include Authority::UserAbilities
...
end
```

### Models

```ruby
class Article
  # Adds `creatable_by?(user)`, etc
  include Authority::Abilities

  # Without this, 'ArticleAuthorizer' is assumed;
  # if that doesn't exist, 'ApplicationAuthorizer'
  self.authorizer_name = 'AdminAuthorizer'
  ...
end
```

### Authorizers

Add your authorizers under `app/authorizers`, subclassing the generated `ApplicationAuthorizer`.

These are where your actual authorization logic goes. Here's how it works:

- Instance methods answer questions about model instances, like "can this user update this **particular** widget?" (Within an instance method, you can get the model instance with `resource`).
  - Any instance method you don't define (for example, if you didn't make a `def deletable_by?(user)`) will fall back to the corresponding class method. In other words, if you haven't said whether a user can update **this particular** widget, we'll decide by checking whether they can update **any** widget.
- Class methods answer questions about model classes, like "is it **ever** permissible for this user to update a Widget?"
  - Any class method you don't define (for example, if you didn't make a `def self.updatable_by?(user)`) will call that authorizer's `default` method.

For example:

```ruby
# app/authorizers/schedule_authorizer.rb
class ScheduleAuthorizer < ApplicationAuthorizer
  # Class method: can this user at least sometimes create a Schedule?
  def self.creatable_by?(user)
    user.manager?
  end

  # Instance method: can this user delete this particular schedule?
  def deletable_by?(user)
    resource.in_future? && user.manager? && resource.department == user.department
  end
end

# undefined; calls `ScheduleAuthorizer.default(:updatable, user)`
ScheduleAuthorizer.updatable_by?(user)
```

As you can see, you can specify different logic for every method on every model, if necessary. On the other extreme, you could simply supply a [default method](#default_methods) that covers all your use cases.

#### Passing Options

Any options you pass when checking permissions will be passed right up the chain. One use case for this would be if you needed an associated instance in order to do a class-level check. For example:

```ruby
# I don't have a comment instance to check, but I need to know
# which post the user wants to comment on
user.can_create?(Comment, :for => @post)
```

This would ultimately call `creatable_by?` on the designated authorizer with two arguments: the user and `{:for => @post}`. If you've defined that method yourself, you'd need to ensure that it accepts the options hash before doing this, or you'd get a "wrong number of arguments" error.

There's nothing special about the hash key `:for`; I just think it reads well in this case. You can pass any options that make sense in your case.

If you **don't** pass options, none will be passed to your authorizer, either.

And you could always handle the case above without options if you don't mind creating an extra model instance:

```ruby
user.can_create?(Comment.new(:post => @post))
```

#### Default Methods

Any class method you don't define on an authorizer will call the `default` method on that authorizer. This method is defined on `Authority::Authorizer` to simply return false. This is a 'whitelisting' approach; any permission you haven't specified (which falls back to the default method) is considered forbidden.

You can override this method in your `ApplicationAuthorizer` and/or per authorizer. For example, you might want one that looks up the user's roles and correlates them with permissions:

```ruby
# app/authorizers/application_authorizer.rb
class ApplicationAuthorizer < Authority::Authorizer

  # Example call: `default(:creatable, current_user)`
  def self.default(able, user)
    has_role_granting?(user, able) || user.admin?
  end

  protected

  def has_role_granting?(user, able)
    # Does the user have any of the roles which give this permission?
    (roles_which_grant(able) & user.roles).any?
  end

  def roles_which_grant(able)
    # Look up roles for the current authorizer and `able`
    ...
  end
end
```

If your system is uniform enough, **this method alone might handle all the logic you need**.

#### Testing Authorizers

One nice thing about putting your authorization logic in authorizers is the ease of testing. Here's a brief example.

```ruby
# An authorizer shared by several admin-only models
describe AdminAuthorizer do

  before :each do
    @user  = FactoryGirl.build(:user)
    @admin = FactoryGirl.build(:admin)
  end

  describe "class" do
    it "lets admins update" do
      expect(AdminAuthorizer).to be_updatable_by(@admin)
    end

    it "doesn't let users update" do
      expect(AdminAuthorizer).not_to be_updatable_by(@user)
    end
  end

  describe "instances" do

    before :each do
      # A mock model that uses AdminAuthorizer
      @admin_resource_instance = mock_admin_resource
    end

    it "lets admins delete" do
      expect(@admin_resource_instance.authorizer).to be_deletable_by(@admin)
    end

    it "doesn't let users delete" do
      expect(@admin_resource_instance.authorizer).not_to be_deletable_by(@user)
    end

  end

end
```

### Controllers

If you're using Rails, ActionController support will be loaded in through a Railtie. Otherwise, you'll want to integrate it into your framework yourself. [Authority's controller](https://github.com/nathanl/authority/blob/master/lib/authority/controller.rb) is an excellent starting point.

You can check authorization in your controllers in one of two ways:

- `authorize_actions_for Llama` protects multiple controller actions with a `before_filter`, which performs a **class-level** check. If the current user is never allowed to delete a `Llama`, they'll never even get to the controller's `destroy` method.
- `authorize_action_for @llama` can be called inside a single controller action, and performs an **instance-level** check. If called inside `update`, it will check whether the current user is allowed to update this particular `@llama` instance.

If either method finds a user attempting something they're not authorized to do, a [Security Violation](#security_violations_and_logging) will result.

How does `authorize_actions_for` know to check `deletable_by?` before the controller's `destroy` action? It checks your configuration. These mappings are configurable globally from the initializer file. Defaults are as follows:

```ruby
config.controller_action_map = {
 :index   => 'read',    # `index` controller action will check `readable_by?`
 :show    => 'read',
 :new     => 'create',  # `new` controller action will check `creatable_by?`
 :create  => 'create',  # ...etc
 :edit    => 'update',
 :update  => 'update',
 :destroy => 'delete'
}
```

They are also configurable per controller, as follows:

```ruby
class LlamasController < ApplicationController

  # Check class-level authorizations before all actions except :create
  # Also, to authorize this controller's 'neuter' action, ask whether `current_user.can_update?(Llama)`
  authorize_actions_for Llama, :except => :create, :actions => {:neuter => :update},

  # To authorize this controller's 'breed' action, ask whether `current_user.can_create?(Llama)`
  # To authorize its 'vaporize' action, ask whether `current_user.can_delete?(Llama)`
  authority_actions :breed => 'create', :vaporize => 'delete'

  ...

  def edit
    @llama = Llama.find(params[:id])
    authorize_action_for(@llama)        # Check to see if you're allowed to edit this llama. failure == SecurityViolation
  end

  def update
    @llama = Llama.find(params[:id])
    authorize_action_for(@llama)        # Check to see if you're allowed to edit this llama.
    @llama.attributes = params[:llama]  # Don't save the attributes before authorizing
    authorize_action_for(@llama)        # Check again, to see if the changes are allowed.
    if @llama.save?
    # etc
  end

end
```

As with other authorization checks, you can also pass options here, and they'll be sent along to your authorization method: `authorize_action_for(@llama, :sporting => @hat_style)`. Generally, though, your authorization will depend on some attribute or association of the model instance, so the authorizer can check<EMAIL_ADDRESS>and<EMAIL_ADDRESS>etc, without needing any additional information.

Note that you can also call `authority_actions` as many times as you like, so you can specify one mapping at a time if you prefer:

```ruby
class LlamasController < ApplicationController
  def breed
    # some code
  end
  authority_actions :breed => 'create'

  def vaporize
    # some code
  end
  authority_actions :vaporize => 'delete'
end
```

If you have a controller that dynamically determines the class it's working with, you can pass the name of a controller instance method to `authorize_actions_for` instead of a class, and the class will be looked up when a request is made.

```ruby
class LlamasController < ApplicationController

  authorize_actions_for :llama_class

  def llama_class
    # This method can simply return a class...
    [StandardLlama, LludicrousLlama].sample

    # ... or an array with a class and some options
    [OptionLladenLlama, {country: 'Peru'}]
  end
end
```

If you want to authorize all actions the same way, use the special `all_actions` hash key. For instance, if you have nested resources, you might say "you're allowed to do anything you like with an employee if you're allowed to update their organization".

```ruby
class EmployeesController < ApplicationController
  authorize_actions_for :parent_resource, all_actions: :update
  private
  def parent_resource
    Employer.find(params[:employer_id])
  end
end
```

Finally, you can enforce that every controller action runs an authorization check using the class method `ensure_authorization_performed`, which sets up an `after_filter` to raise an exception if it wasn't. Any `only` or `except` arguments will be passed to `after_filter`. You can also use `if` or `unless` to specify the name of a controller method which determines whether it's necessary.

Since this runs in an `after_filter`, it obviously doesn't prevent the action, it just alerts you that no authorization was performed. Therefore, it's most useful in development. An example usage might be:

```ruby
class ApplicationController < ActionController::Base
  ensure_authorization_performed :except => [:index, :search], :if => :auditing_security?, :unless => :devise_controller?

  def auditing_security?
    Rails.env != 'production'
  end
end
```

If you want a skippable filter, you can roll your own using the instance method, also called `ensure_authorization_performed`.

### Views

Assuming your user object is available in your views, you can do all kinds of conditional rendering. For example:

```ruby
link_to 'Edit Widget', edit_widget_path(@widget) if current_user.can_update?(@widget)
```

If the user isn't allowed to edit widgets, they won't see the link. If they're nosy and try to hit the URL directly, they'll get a [Security Violation](#security_violations_and_logging) from the controller.

## The Generic `can?`

Authority is organized around protecting resources. But **occasionally** you **may** need to authorize something that has no particular resource. For that, it provides the generic `can?` method. It works like this:

```ruby
current_user.can?(:view_stats_dashboard) # calls `ApplicationAuthorizer.authorizes_to_view_stats_dashboard?`
current_user.can?(:view_stats_dashboard, :on => :tuesdays, :with => :tea) # same, passing the options

# application_authorizer.rb
class ApplicationAuthorizer < Authority::Authorizer
  # ...
  def self.authorizes_to_view_stats_dashboard?(user, options = {})
    user.has_role?(:manager) # or whatever
  end
end
```

Use this very sparingly, and consider it a [code smell](http://en.wikipedia.org/wiki/Code_smell). Overuse will turn your `ApplicationAuthorizer` into a junk drawer of methods. Ask yourself, "am I sure I don't have a resource for this? Should I have one?"

## Security Violations & Logging

If you're using Authority's `ActiveController` integration or have used it as a template for your own, your application will handle unauthorized requests with `403 Forbidden` automatically.

If you use Authority to [conditionally render links](#security_violations_and_logging), users will only see links for actions they're authorized to take. If a user deliberately tries to access a restricted resource (for instance, by typing the URL directly), Authority raises and rescues an `Authority::SecurityViolation`.

When it rescues the exception, Authority calls whatever controller method is specified by your `security_violation_handler` option, handing it the exception. The default handler is `authority_forbidden`, which Authority mixes in to your `ApplicationController`. It does the following:

- Renders `public/403.html`
- Logs the violation to whatever logger you configured.

You can define your own `authority_forbidden` method on `ApplicationController` and/or any other controller. For example:

```ruby
# Send 'em back where they came from with a slap on the wrist
def authority_forbidden(error)
  Authority.logger.warn(error.message)
  redirect_to request.referrer.presence || root_path, :alert => 'You are not authorized to complete that action.'
end
```

Your method will be handed the `SecurityViolation`, which has a `message` method. In case you want to build your own message, it also exposes `user`, `action` and `resource`.

## Credits, AKA 'Shout-Outs'

- [adamhunter](https://github.com/adamhunter) for pairing with me on this gem. The only thing faster than his typing is his brain.
- [kevmoo](https://github.com/kevmoo), [MP211](https://github.com/MP211), and [scottmartin](https://github.com/scottmartin) for pitching in.
- [nkallen](https://github.com/nkallen) for writing [a lovely blog post on access control](http://pivotallabs.com/users/nick/blog/articles/272-access-control-permissions-in-rails) when he worked at Pivotal Labs. I cried sweet tears of joy when I read that a couple of years ago. I was like, "Zee access code, she is so BEEUTY-FUL!"
- [jnunemaker](https://github.com/jnunemaker) for later creating [Canable](http://github.com/jnunemaker/canable), another inspiration for Authority.
- [TMA](http://www.tma1.com) for employing me and letting me open source some of our code.

## Responses, AKA 'Hollaback'

Do you like Authority? Has it cleaned up your code, made you more personable, and taught you the Secret to True Happiness? Awesome! I'd **love** to get email from you - see my Github profile for the address.

## Contributing

How can you contribute? Let me count the ways.

### 1. Publicity

If you like Authority, tell people! Blog, tweet, comment, or even... [shudder]... talk with people *in person*. If you feel up to it, I mean. It's OK if you don't.

### 2. Documentation

Add examples to the [wiki](http://github.com/nathanl/authority/wiki) to help others solve problems like yours.

### 3. Issues

Tell me your problems and/or ideas.

### 4. Code or documentation

1. Have an idea. If you don't have one, check the TODO file or grep the project for 'TODO' comments.
2. Open an issue so we can talk it over.
3. Fork this project
4. Create your feature branch (`git checkout -b my-new-feature`)
5. `bundle install` to get all dependencies
6. `rspec spec` to run all tests.
7. Update/add tests for your changes and code until they pass.
8. Commit your changes (`git commit -am 'Added some feature'`)
9. Push to the branch (`git push origin my-new-feature`)
10. Create a new Pull Request

license: MIT

repository: Besermenji/Table-Reservation

branch_name: refs/heads/master

extension: markdown

license_type: permissive

repo_name: Besermenji/Table-Reservation


text:
# IMS - Inventory Management System

IMS is an application developed in Java/MySQL which provides CRUD (Create/Read/Update/Delete) functionalities relating to an ordering system.
This application allows the user to perform a variety of tasks with Customers, Products and Orders.

## Getting Started

These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. See deployment for notes on how to deploy the project on a live system.

### Prerequisites

In order to succesfully execute this program, there are a number of dependencies which will need to be installed. These are:

```
1. Programming IDE (this is developed in Eclipse)
2. JDK version 14
3. MySQL database running on localhost
4. Maven Dependency (if not using Eclipse as IDE)
```

### Installing

This is a step by step guide on how to get the project up and running on your local machine for development and testing.

1. Navigate to the folder in which you would like to set up the project.
2. Clone the repository using this command:

```
git clone https://github.com/hamzapQA/ims-demo.git
```

3. Import the project into your IDE. For Eclipse,
```
 a) Select File, then Import
 b) When the Import window appears, select Maven then Existing Maven Projects
 c) Now select Browse and navigate to the folder the repo has been cloned.
 d) Click finish, done!
 ```
 ## Project Functionality

 This section provides a brief description on the functionality of the application.

 When the program is started, it will ask for a username and password. These are the credentials for your SQL database.

Once logged in, you will be provided with options such as Customer, Order, Orderline and Stop.

When selecting any of the options, you will be provided with (Create/Read/Update/Delete) options. These can be selected by typing the corresponding command.

Download the JAR, and change to the working directory and run the following command:

```
java -jar HamzaIMS-0.0.1-SNAPSHOT-jar-with-dependencies.jar
```

Once the program loads it will ask for a username and password, these are your MySQL database credentials.

```
What is your username
> root
What is your password
> root
```
After the credentials have been entered, the menu will appear:

```
Welcome to IMS! Please type an option?
CUSTOMER: Information about customers
ITEM: Individual Items
ORDER: Generate an Order
ORDERLINE: Add items and total order
STOP: To close the application
```
## Running the tests

The project comes with automated tests which make use of JUnit and Mockito. Tests are organised into classes to test functionality. Test files are stored in src/test/java instead of an individual test class.

### Unit Tests

Unit tests are used to ensure code works correctly and to protect against bugs. This makes use of JUnit and tests the functionality of the  Customer, Item and Order classes as well as functionality of some of the DAO classes.

Here is an example of a Unit Test:

	@Test
	public void setFirstNameTest() {
		Customer customer = new Customer("John", "Jones");
		customer.setFirstName("John");
		assertTrue(customer.getFirstName().equals("John"));
	}

To run the tests, right click on the project folder - "Run As JUnit Test"

### Integration Tests
Integration Tests make use of Mockito and aure used to test functionality of classes and controllers, domain and actions. Here is an example of a integration test to test the functionality of the create() method in CustomerController:
```
	@Test
	public void testCreate() {
		final String F_NAME = "john", L_NAME = "jones";
		final Customer created = new Customer(F_NAME, L_NAME);

		Mockito.when(utils.getString()).thenReturn(F_NAME, L_NAME);
		Mockito.when(dao.create(created)).thenReturn(created);

		assertEquals(created, controller.create());

		Mockito.verify(utils, Mockito.times(2)).getString();
		Mockito.verify(dao, Mockito.times(1)).create(created);
	}
```

## Deployment

To deploy this project on a live system, you can use the included jar file "HamzaIMS-0.0.1-SNAPSHOT-jar-with-dependencies.jar".

## Built With

* [Maven](https://maven.apache.org/) - Dependency Management

## Versioning

We use [SemVer](http://semver.org/) for versioning.

## Authors

* **Hamza Pervez** - *Project Completion* - [hamzapQA](https://github.com/hamzapQA)

* **RafSobolQAC** - *Initial work* - [RafSobolQAC](https://github.com/RafSobolQAC/ims-demo)

* **Chris Perrins** - *Initial work* - [christophperrins](https://github.com/christophperrins)

## License

This project is licensed under the MIT license - see the [LICENSE.md](LICENSE.md) file for details

*For help in [Choosing a license](https://choosealicense.com/)*

## Acknowledgments

* Nick, Aswene and Vinesh for amazing Java concepts, help and support.
* QA-Community
* Team Trap
* GitHub

repository: hamzapQA/ims-demo

extension: md

gha_license_id: MIT

repo_name: hamzapQA/ims-demo


text:
---
name: Fix
about: Provide a fix for this project
title: ''
labels: fix
assignees: ''

---

**Please describe your fix:**

A clear and concise description of what the pull request contains.

**Bug:**

If this fix is for an existing tracked issue, please link that here. If this is a fix for a bug
which has not yet been reported, please add a clear and concise description of what the bug this
pull request seeks to fix is.

**Testing:**

Per the [contributing guidelines][1], all pull requests should be accompanied by new tests. If you
have any problems understanding how testing works or need help testing your pull request, please
feel free to ask for clarification or help here (please also include information on what you've
tried so far).

**Checklist:**

- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my own code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation where necessary
- [ ] My changes generate no new warnings
- [ ] Any dependent changes have been merged and published in downstream modules
- [ ] I have split off unrelated changes into their own PRs and done my best to make this PR as
      focused as possible while still being useful

 [1]: https://github.com/pkmn/ps/blob/master/CONTRIBUTING.md


text:
# PHP Router

Minimum requirement PHP 7.1

### Installation:

`composer require sutija/php-router`

### Usage:

__Using as callback function:__

```php
<?php
$router = \Sutija\Router\Router::getInstance();

$routeArticles = new \Sutija\Router\Route();

$routeArticles
->setRoute('/articles/:alias')
->setAllowedMethods(['GET'])
->setCallback(function() use ($router) {
    // Get alias from route
    $alias = $router->getRouteData()->getData('alias');
    // Do something...
});

$router->addRoute($routeArticles);

$router->resolve();
```

__Using as class:__

```php
<?php
class ArticlesController {
    public function resolve() {
        $alias = \Sutija\Router\Router::getInstance()->getRouteData()->getData('alias');
        // Do something...
    }

    public function resolveGet() {
        $alias = \Sutija\Router\Router::getInstance()->getRouteData()->getData('alias');
        $otherParam = \Sutija\Router\Router::getInstance()->getRouteData()->getData('other_param');
        // Do something...
    }
}

$router = \Sutija\Router\Router::getInstance();

$routeArticles = new \Sutija\Router\Route();

$routeArticles
->setRoute('/articles/:alias/something/:other_param')
->setAllowedMethods(['GET', 'POST'])
->setCallback(new ArticlesController());

$router->addRoute($routeArticles);

$router->resolve();
```

In the above example when we do the request with __GET__ method router will try to find `resolveGet` method in ArticleController and try to execute it. In case that's not found it will try to execute `resolve` method.

__Using as static method:__

```php
<?php
class ArticlesController {
    public static function resolveGet() {
        $alias = \Sutija\Router\Router::getInstance()
        ->getRouteData()
        ->getData('alias');
        // Do something...
    }

    public static function resolvePost() {
        $alias = \Sutija\Router\Router::getInstance()
        ->getRouteData()
        ->getData('alias');
        // Do something...
    }
}

$router = \Sutija\Router\Router::getInstance();

$routeArticles = new \Sutija\Router\Route();

$routeArticles
->setRoute('/articles/:alias')
->setAllowedMethods(['GET', 'POST'])
->setCallback(ArticlesController::class);

$router->addRoute($routeArticles);

$router->resolve();
```

In the above example when we do the request with __GET__ method router will try to find static `resolveGet` method in ArticleController and try to execute it. In case that's not found it will try to execute static `resolve` method.

To access query params use:
```php
// GET /articles/rainbow/?colors=10&height=20
$queryParams = \Sutija\Router\Router::getInstance()->getRouteData()->getQueryParams();
// [color => 10, height => 20]

echo \Sutija\Router\Router::getInstance()->getRouteData()->getQueryParam('colors');
// 10
```

repository: sutija/php-router

gha_language: PHP

repo_name: sutija/php-router


text:
# Changing direction

## **page 1/11**

### Signalling or using the direction indicator

The approximate distances at which the direction indicator must be used are for:

- Motorways/motorroads outside the built-up area - 300 meters before the beginning of the deceleration lane
- Motorroads inside the built-up area - 100 meters before the beginning of the deceleration lane
- Roads inside the built-up area (50 km/h roads - 100 meters before the junction
- Roads outside the built-up area and 70 km/h roads - 150 meters before the junction
- Roads in residential areas (home/30 km/h zones) - 50 meters before the junction

### Using turning lanes (lanes with arrows)

- Once chosen, these arrows give you a direction that you must follow.

### Positioning lanes for ahead

These lanes can also be marked for ahead only

## **Page 2/11**

### Turning right

### Road position

- Where a suggested cycle lane, i.e. a lane with no painted cycle symbol on the road surface, is present you may take up a position on the road in that suggested cycle lane.

### Observation technique

- Look
- Indicate right - only signal when you are sure
- Look again
- Take up a position on the road

_No bromfietsen (mopeds) or brommobielen (mobility cars)_ on cycle lanes.

Bromfietsen and brommobielen must use the carriageway

when present, bromfietsen must use the combined cycle/moped paths (sign G12a).

### Speed on approach

## **page 3/11**

### Turning left

### Road position

- Position yourself as close to the centre of the road as is safe, so that other drivers can overtake on your right if there’s enough space.
- In a one-way street, where there is no vehicle contra-flow, move to the left-hand side of the road when appropriate.

### Observation technique

- Look
- Indicate left
- Look again
- Take up a position on the road

### Oncoming traffic

- You should give the right of way to traffic continuing straight ahead; this also means you have to give the right of way to those crossing the road that you are turning into, including pedestrians.

- when you are between the solid white lines or level with the directional arrows on the road surface you must not change direction anymore. These arrows give you a direction that you must then follow.

## **page 4/11**

### The advanced stop line (OFOS)

- Note that all other drivers, including bromfietsers (moped riders) and brommobielen (mobility cars), may not use this area but must stop at the first white, or yellow if temporary, line reached.

![Alt text](https://github.com/frhan/study/blob/master/images/h5_11.jpg)

## page 5/11

### The priority bends

- sub-plate the thick black bar represents the direction in which the priority continues and the smaller black bars represent the side roads leading into this priority bend.

- when driving on a priority road and reaching a junction or a crossing a tram approaching from your right or left must give way to you!

- a tram approaching you from your front or rear - i.e. also travelling on the priority road - and turning to its left or right does have priority.

## NTK

- when pulling caravans/trailers with a maximum authorized mass (MAM) of less than 3500 kg, the maximum speed is 90 km/h; if the MAM is more than 3500 kg, the maximum speed is 80 km/h.

- When performing a special manoeuvre, e.g. stopping, parking, turning round, pulling off etc., you may not impede any other road users in the immediate vicinity

- remember that trams may be overtaken on either side. Normally a tram will be overtaken on the right, but when and where this is not possible or suitable overtaking on the left is allowed

- When passengers are still boarding a bus, the bus must remain stationary and cannot drive off; to avoid stemming the flow of traffic you should drive past, i.e. overtake, this bus if there is sufficient room

- Drivers on the extreme right or left lane of their carriageway and closely following another driver, must not overtake that driver when he has made his intention to turn off known and has taken up a position to do so.

- Once you have positioned your vehicle in a lane and are level with the directional arrows showing the direction to be followed, you may not change lanes anymore and follow a different direction.

- You must not overtake any other vehicle at or near a VOP (Voetgangers Oversteek Plaats = pedestrian crossing).

- overtaking sight distance or overtaking vision is the minimum distance open to the vision of the driver of a vehicle intending to overtake a slow vehicle ahead safely against the traffic in the opposite direction. This distance is measured along the centre line of the road over which a driver with his eye level 1.2 m above the road surface can see the top of an object 1.2 m above the road surface.

- You should overtake other vehicles on the left. As there was sufficient space here for overtaking safely, it is allowed.

- drivers wanting to overtake a preceding vehicle that has a) indicated the intention to turn left, and b) also taken up a position on the road for this purpose must overtake that vehicle on the right only.

- When we talk about a filter traffic light, reference is made to a traffic light with an arrow for the direction into which you are turning; this means that you should not have to give the right of way to road users continuing ahead on the same road, even when they are at a pedestrian crossing!

- When either following or leaving a priority bend or a through carriageway it is advisable to use the direction indicator

repository: frhan/study

repo_name: frhan/study


text:
---
layout: post
categories: Security
tags: [RSA, Java]

---

### About RSA

> RSA is an algorithm used by modern computers to encrypt and decrypt messages.
It is an asymmetric cryptographic algorithm. Asymmetric means that there are two different keys.
This is also called public key cryptography, because one of them can be given to everyone.
The other key must be kept private. It is based on the fact that finding the factors of an integer
is hard (the factoring problem). RSA stands for Ron Rivest, Adi Shamir and Leonard Adleman,
who first publicly described it in 1978. - wikipedia

When using RSA to sign data, the private key is used to generate a signature of the data;
and the public key will be passed with the data and can be used by anyone to check the content
of the data was not changed.

### Generating key pair

Before we use the RSA algorithm, we need to generate a key pair or load a key pair from a
credential store file.

```
    public static KeyPair generateRSAKeyPair() {
        KeyPairGenerator generator = null;
        try {
            generator = KeyPairGenerator.getInstance("RSA");
            generator.initialize(2048, new SecureRandom());
            return generator.generateKeyPair();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static final String KEYSTORE_TYPE = "JCEKS";

    public static KeyPair loadRSAKeyPair(String keyStoreFilePath, String storePassword, String keyAlias, String keyPassword) {
        if (keyStoreFilePath == null || storePassword == null || keyAlias == null || keyPassword == null) {
            return;
        }

        try {
            InputStream inputStream = new FileInputStream(keyStoreFilePath);
            KeyStore keyStore = KeyStore.getInstance(KEYSTORE_TYPE);
            keyStore.load(inputStream, storePassword.toCharArray());

            KeyStore.PasswordProtection passwordProtection = new KeyStore.PasswordProtection(keyPassword.toCharArray());
            KeyStore.PrivateKeyEntry privateKeyEntry =
                    (KeyStore.PrivateKeyEntry) keyStore.getEntry(keyAlias, passwordProtection);
            Certificate certificate = keyStore.getCertificate(keyAlias);
            PublicKey publicKey = certificate.getPublicKey();
            PrivateKey privateKey = privateKeyEntry.getPrivateKey();
            this.keyPair = new KeyPair(publicKey, privateKey);
        } catch (Exception e) {
            log.error("Failed to load keystore file: " + keyStoreFilePath, e);
        }
    }
```

### Signing a message and verify the signature

Message signing is commonly used in API design. We can use the signature to check whether the message is tampered or not.
The public key will also be included in the message, so that we can verify the message was sent from a know creator or not.

```
    public static String generateSignature(final String strValue) {
        try {
            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initSign(keyPair.getPrivate());
            signature.update(strValue.getBytes(Constants.STRING_ENCODING));
            return Base64.encodeBase64String(signature.sign());
        } catch (Exception e) {
            log.error("Failed to sign oap token.", e);
        }
        return null;
    }
```

The `SHA256withRSA` algorithm calculates a SHA256 signature of the input and then uses the SHA256 signature to
calculate the RSA signature (more details in [RFC](https://tools.ietf.org/html/rfc3447#page-32)).

```
    private static boolean verifySignature(String strValue, String rsaSignature, PublicKey pubKey) {
        try {
            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.update((strValue.getBytes());
            return signature.verify(Base64.getDecoder().decode(rsaSignature));
        } catch (Exception e) {
            log.error("Failed to verify signature.", e);
        }
        return false;
    }
```

The public key will be encoded (in base64 format) within the message, before we verify the signature, we need to decode the string
and use the encoded public key to create the PublicKey object as follows:

```
    public static PublicKey getPublicKey(String publicKeyStr) {
        try {
            byte[] byteKey = Base64.getDecoder().decode(publicKeyStr.getBytes());
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(byteKey);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return  keyFactory.generatePublic(x509EncodedKeySpec);
        } catch(Exception e){
           log.error("Failed to create public key.", e);
        }

        return null;
    }
```

To encrypt (use public key) or decrypt (use private key) a message with RSA algorithm, we can use the `Cipher` class
in Java to get a `RSA` instance, and use the ENCRYPT_MODE or DECRYPT_MODE to encrypt
or decrypt the message.


text:
# AstronomyEngine

A mountable engine for the `astronomy` gem

![Screenshot](/screenshot/example.jpg?raw=true "Screenshot")

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'astronomy_engine'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install astronomy_engine

## Usage

Add the mount point for the engine in your rails app:

```ruby
Rails.application.routes.draw do
  ...
  mount AstronomyEngine::App => '/astronomy'
  ...
end
```

Request the list of categories:

```bash
curl {APPLICATION_ROOT}/astronomy/categories
```

Request all topics for a given category:

```bash
curl {APPLICATION_ROOT}/astronomy/categories/Star/topics
```

Search all topic names and descriptions:

```bash
curl {APPLICATION_ROOT}/astronomy/topics?q=cluster
```

## Contributing

1. Fork it ( https://github.com/[my-github-username]/astronomy_engine/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request

repository: nick-aschenbach/astronomy-engine

repo_name: nick-aschenbach/astronomy-engine


text:
# Apache Jena Examples
This are some examples which I collected/written down to easily demonstrate my ideas.

## Read and Type RDF Data
Shows how to extend a RDFStream to read typed RDF Data with a RDF-Schema.
See [here](typed-read)

## Shape Validation
Shows how easy RDF data can be validated with Shape Constraint Language (SHACL).
See [here](shape-validation)

## Shape Parsing
Shows how to parse Common Grid Exchange Standard (CGMES) schema files to Shape Constraint Language (SHACL) files.
See [here](shape-parse)

repository: MBoegers/jena-examples

gha_language: Java

repo_name: MBoegers/jena-examples


text:
# Safe Area

|Area|Submitted|Type|
|-|-|-|
Games: Graphics|11/14/2008|Code Sample
||||

## Description

This sample shows how to make an XNA Framework game display correctly on a wide range of televisions.

## Sample Overview

This sample and the associated document explain the problems you'll encounter in supporting a wide range of displays, and how to overcome them.

> All content and source code downloaded from this page are bound to the Microsoft Permissive License (Ms-PL).

Download | Size | Description
---|---|---|
[SafeAreaSample_4_0](https://github.com/simondarksidej/XNAGameStudio/tree/archive/Samples/SafeAreaSample_4_0) | 0.71MB | Source code and assets for the Safe Area Sample (XNA Game Studio 4.0).
[SafeAreaSample_4_0.zip](https://github.com/simondarksidej/XNAGameStudioZips/raw/zips/SafeAreaSample_4_0.zip) | 0.71MB | Source code and assets for the Safe Area Sample (XNA Game Studio 4.0).
||||

license: MS-PL

path: /Articles/Safe Area.md

filename: Safe Area.md


text:
# nbdev_learning
> Summary description here.

This file will become your README and also the index of your documentation.

## Install

`pip install nbdev_learning`

## How to use

Fill me in please! Don't forget code examples:

```python
say_hello("Rahul")
```

    'Hello Rahul!'

gha_language: Jupyter Notebook


text:
# Capstone Course Curriculum

## Summary

This curriculum is developed by [AppNexus](https://www.appnexus.com/en) as part of our contribution to the [Tech in Residence](http://www.techtalentpipeline.nyc/tech-in-residence-corps/) program. The course topics will introduce [Hunter College](http://www.hunter.cuny.edu/csci/curriculum) students enrolled in the computer science capstone course to a breadth of topics in modern, web-based software development. We will provide students with different modes of thinking, and highlight each topic with useful readings and case studies. We expect students to meaningfully apply what they have learned in each topic to their capstone projects and to take away a sense of the intellectual challenges we face in our software development careers.

## Curriculum

### Artifacts

Please see the current [syllabus](SYLLABUS.md) for course-specific information and up-to-date schedule

### Prerequisites

We expect student to have a working knowledge of [git](https://git-scm.com/) and understand the mechanics of a [distributed version control](https://en.wikipedia.org/wiki/Distributed_version_control) system.

### Topic Outline

The topics to be covered are as follows:

*  Agile Methodology
*  Product Thinking
*  Testing Thinking
*  Design & UX Thinking
*  UI Systems
*  Database Systems
*  Back-end Systems
*  Testing Methodologies
*  Security Thinking & IT Controls
*  Productionalization

repository: Bakainkorp/capstone-course

repo_name: Bakainkorp/capstone-course


text:
# Graphical Query Application

<img src="https://github.com/Alcampopiano/graphical_query_app/blob/master/img/ga.gif?raw=true" alt="drawing" width="1000"/>

---

This is an example of using the [Anvil App Server](https://pypi.org/project/anvil-app-server)
to build a web application using nothing but Python.

As shown above, this application allows you to select data based on a graphical-style query.

## Installation

```
$ pip install -r graphical_query_app/requirements.txt
```

## Running the app locally

After cloning this repository, run the following command to launch the app

```
$ anvil-app-server --app graphical_query_app
```

The app should now be running on http://localhost:3030.

## Using your own data

I have included some same data in the "example_data" directory. Feel free to load that into the
app to see how everything works. When you are ready to use your own data, make sure it is squeaky clean!
That is, don't have mixed types inside the same column. Numbers need to be able to be treated as numbers.
Also, best to keep your column names sane as well
(no spaces or special characters, or else the app may explode)

## Saving queries

To save your queries, simply click "save query" once you have one that you like.
A text area will appear asking you to give it a nice description. That's it!
Now you can reuse that query without having to construct it all over again.

Enjoy!


text:
[![LICENSE](https://img.shields.io/badge/license-Apache_2.0-lightgrey.svg)](https://github.com/borismus/keysocket/blob/master/COPYING)
[![Chrome Web Store](https://img.shields.io/chrome-web-store/users/fphfgdknbpakeedbaenojjdcdoajihik.svg)](https://chrome.google.com/webstore/detail/key-socket-media-keys/fphfgdknbpakeedbaenojjdcdoajihik)
[![Chrome Web Store](https://img.shields.io/chrome-web-store/rating-count/fphfgdknbpakeedbaenojjdcdoajihik.svg)](https://chrome.google.com/webstore/detail/key-socket-media-keys/fphfgdknbpakeedbaenojjdcdoajihik)
[![Chrome Web Store](https://img.shields.io/chrome-web-store/stars/fphfgdknbpakeedbaenojjdcdoajihik.svg)](https://chrome.google.com/webstore/detail/key-socket-media-keys/fphfgdknbpakeedbaenojjdcdoajihik)
[![github-stars-image](https://img.shields.io/github/stars/borismus/keysocket.svg?label=github%20stars)](https://github.com/borismus/keysocket)

Global keyboard bindings to control your Chrome-based music player.
Allows your keyboard media keys (play/pause, next, previous) to work
when you're listening to music on various streaming websites.

# Supported Sites

   * 163 Music
   * 8tracks
   * Amazon Cloud Player
   * Bandcamp
   * Birp
   * Bop
   * Brain.fm
   * Bugs Music
   * Castbox.fm
   * Chrome Built-In Player
   * Comcast/Xfinity
   * Coursera
   * Crunchyroll
   * Deezer
   * Digitally Imported (di.fm)
   * Gaana.com
   * Google Play Music
   * Groove Music
   * HearThis.at
   * Hype Machine
   * iloveradio.de
   * BBC iPlayer
   * Jamendo
   * Jamstash
   * Jango.com
   * Mixcloud
   * Zing MP3
   * Met Opera Season On-Demand
   * Music Choice (untested)
   * Myspace
   * Myzuka.fm
   * Napster
   * Naxos Music Library
   * Netflix
   * Noisli (only without account tested)
   * Noon Pacific (untested)
   * NRK Radio
   * Ok.ru
   * Openload.co
   * Overcast
   * Pandora
   * Phish Tracks
   * Picarto.tv
   * Plex
   * Pluralsight
   * Pocketcasts.com
   * Qobuz
   * Relax-Hub.com
   * Saavn.com
   * Showmax
   * Sirius XM Radio
   * Slacker
   * SomaFM
   * Soundcloud
   * Sowndhaus
   * Spotify
   * Spreaker
   * Streamsquid
   * Subsonic (and Madsonic)
   * Superplayer.fm (untested)
   * Supersport.com
   * Synology Audio Station v.5 (untested)
   * thesixtyone
   * Tidal (untested)
   * tunein.com
   * tver.jp
   * Twitch.tv
   * Ustream.tv
   * vk.com (Vkontakte)
   * Vimeo
   * XFINITY (untested)
   * Xiami Music
   * YouTube
   * YouTube Music
   * Zvooq
   * Яндекс.Музыка (Yandex.Music)
   * Яндекс.Радио (Yandex.Radio)
   * IbizaSonica.com

# Untested Sites (after latest changes)

   * Music Choice (account is needed)
   * Noon Pacific (account is needed)
   * Superplayer.fm (regional restrictions)
   * Synology (special environment is needed)
   * Tidal (regional restrictions)
   * XFINITY (account is needed)

# Usage

1. Install extension from the [chrome web store][crx].
2. Edit the `Keyboard shortcuts` to give Keysocket 'Global' permissions
    * Open a browser tab to [chrome://extensions](chrome://extensions)
    * Scroll to the bottom & click `Keyboard shortcuts`
    * Find `Keysocket Media Keys` and change each desired key to `Global`

# API

Keysocket also provides an API that websites can use to bind their
players without the need to wait for their PR to be accepted and
released in the Chrome Webstore extension.  Keysocket fires events
for each media key, which the website can add event listeners for.
Below is an example from http://www.relax-hub.com, written by the
current project maintainer, Feedbee:

```javascript
// Web Page Media Control API interaction (v0.4)
// https://github.com/feedbee/web-page-media-control-api-spec
// for Key Socket Media Keys Chrome extension
// https://chrome.google.com/webstore/detail/key-socket-media-keys/fphfgdknbpakeedbaenojjdcdoajihik?hl=en

document.addEventListener("MediaPlayPause", function () {
  playerCollection.send("toggle");
});
document.addEventListener("MediaStop", function () {
  playerCollection.send("stop");
});
document.addEventListener("MediaPrev", function () {
  var player = playerCollection.getPrevPlayer();
  if (player) {
      player.send("play");
  }
});
document.addEventListener("MediaNext", function () {
  var player = playerCollection.getNextPlayer();
  if (player) {
      player.send("play");
  }
});
```

Web Page Media Control API documentation is [available here](https://github.com/feedbee/web-page-media-control-api-spec).

# Please, contribute!

* Looking for plugins for other music players. Create Pull Requests to contribute. Create Issues to inform us about
broken sites (but PR is preferable).

Plugin creation is simple. If you have found a website with media content, that isn't supported by keysocket, just
write a plugin by yourself and create new Pull Request to share it with others. How to do it?

First of all, determine the fixed part of website's URL, where a media content is shown. In `extension/manifest.json`
add an item into `content_scripts` array like this:

```
    {
      "matches": ["*://example.com/player*"],
      "js": ["plugin-api.js", "keysocket-example-service-name.js"]
    },
```

Create new file into `extension` folder using the pattern `keysocket-example-service-name.js` (use your service name to
replace `example-service-name` part). Write plugin's code there. Check other plugins for examples.

Typically, plugin can interact with a player using either button press simulation or public API call. The second option
implies you writing custom JS code to talk to player, while the first one requires just to mention DOM selectors to
configure keysocket.

```javascript
keySocket.init('example-service-name', {
    "play-pause": '...',
    "prev": '...',
    "next": '...',
    "stop": '...'
});
```

In the code above two arguments were passed to `keySocket.init` function. The first argument is a plugin name, it used for
logging and can be anything you want. The second argument is a map used to bind keysocket events (which is caused by
user pressing control keys) to buttons or code, that handles this event. The events are `play-pause`, `prev`, `next`
and `stop`. Any of them can be omitted in the map.

So, passing a function as an event handler, you set the code, that will be called when event is thrown. Passing anything
else, which expected to be a string, you define DOM selector to look up for a DOM object to simulate click on it.

Different websites require different approaches to dial with them. So, make a research to find the best solution in
your case. Look through the other plugins (`extension/keysocket-*.js` files) for the reference.

[crx]: https://chrome.google.com/webstore/detail/fphfgdknbpakeedbaenojjdcdoajihik

repository: adamstirtan/keysocket

repo_name: adamstirtan/keysocket


text:
# MXNet - Julia API

See the [MXNet Julia Reference Manual](https://media.readthedocs.org/pdf/mxnet-test/latest/mxnet-test.pdf).

MXNet supports the Julia programming language. The MXNet Julia package brings flexible and efficient GPU
computing and the state-of-art deep learning to Julia.

- It enables you to write seamless tensor/matrix computation with multiple GPUs in Julia.
- It also enables you to construct and customize the state-of-art deep learning models in Julia,
  and apply them to tasks such as image classification and data science challenges.

## Julia API Reference
Julia documents are available at [http://dmlc.ml/MXNet.jl/latest/](http://dmlc.ml/MXNet.jl/latest/).

gha_language: Python


text:
---
layout: post
title:  '02. Episode 2: What if we need to find a free IP Range?'
categories:  ['PowerShell']
tags:  ['PowerShell']
date:  2018-07-19 05:57:27 +03:00
beginps: '

'
endps: '

'
---

Hello colleagues, we continue building our Enterprise-focused PowerShell module for Azure. And this time we will extend functionality of our IP management module.

# Some considerations

As you might recall we making a module, which will have the following functionality.

- Given a VNET range break it down to number of subnets based on a subnet size
- Given a list of IP ranges in use and  number of IP addresses needed find out a free slot for a VNET

Typically, when we need to provision an VM-based environment in Azure we need to have a network, to put our VMs into. To create such a network automatically, we need to know few things. First - we need to know IP Range for a VNET. Next is the subnet layout, like which subnets we want to create, what will be their IP ranges. Most commonly, however, we know which ranges are in use - this information can be extracted from a CMDB or directly form Azure. And we can also estimate sizes for our subnets. Having the list of sizes we now able to calculate a VNET layout using cmdlet we developed [last time](https://eosfor.github.io/2018/episode2-making-ipmgmt-module/). Now we need to develop something, that can find a proper slot for us, among all the VNETs we may already have.

## Assumptions

We will assume here, that we have some kind of an [IPAM](https://docs.microsoft.com/en-us/windows-server/networking/technologies/ipam/ipam-top) system in our infrastructure, and either can extract this date from it, or, it may be stored in CMDB. I'd recommend however, to build some automated mechanism, which will update CMDB or IPAM with new networks in Azure automatically, upon creation. We can, probably, look at this later and build a prototype. So, by now we assume that this data is available for us.

Typically, when an Enterprise builds a hybrid networking, few big chunks of IP address space are dedicated for regions in a cloud. For example if we have some workloads to run in the US, some in the EU, and some in Australia - we may have three different big IP ranges of, say, size "/16". In our terminology we going to call these - "base networks" or "base ranges". Each of these ranges will have some VNETs inside, so ur goal is to search through IP ranges under a base network, to find a free slot of the size we need.

# What it looks like

This is how it works, and now lets look at how we did it.

![how search works](/images/posts/2018-07-19-episode2-ip-range-search/searchDemo/searchDemo.gif)

# Implementation

Well, frankly speaking implementation looks pretty, mm, complex. But in fact it is not. Well, I'd say, I'd like someone with really strong programming background to look at this to point out what is wrong with this. But, well, now it more or less works and we used it a lot in Production and we haven't seen any problems. So, lets look at this closer and put scary things first:

{{ page.beginps }}
function Get-IPRanges {
    [cmdletbinding()]
    param(
        [Parameter(Mandatory = $true, ParameterSetName = "ByBaseNet")]
        $Networks,
        [Parameter(Mandatory = $true, ParameterSetName = "ByBaseNet")]
        [System.Net.IPNetwork] $BaseNet,
        [Parameter(Mandatory = $true, ParameterSetName = "ByBaseNet")]
        [ValidateRange(8, 30)]
        [int] $CIDR
    )
    function NextSubnet ($network, $newCIDR ) {
        $net = [System.Net.IPNetwork]::Parse($network)
        $netmask = [System.Net.IPNetwork]::ToNetmask($newCIDR, $net.AddressFamily)

        [bigint] $nextAddr = [System.Net.IPNetwork]::ToBigInteger($net.Broadcast) + 1
        [bigint] $mask = [System.Net.IPNetwork]::ToBigInteger($netmask)
        [bigint] $masked = $nextAddr -band $mask

        if ($masked -eq $nextAddr) {
            Write-Verbose "Masked"
            $next = $masked
        }
        else {
            Write-Verbose "Magic!"
            $next = $masked + [bigint]::Pow(2, 32 - $newCIDR)
        }

        $nextNetwork = [System.Net.IPNetwork]::ToIPAddress($next, [System.Net.Sockets.AddressFamily]::InterNetwork)
        $nextSubnet = [System.Net.IPNetwork]::Parse($nextNetwork, $netmask)
        $nextSubnet
    }
    function getIPRanges {
        for ($i = 0; $i -le ($outNets.Count - 1); $i++ ) {
            $n = $outNets[$i]
            $ns = NextSubnet $n $CIDR
            Write-Verbose "subnet is`: $n; next subnet is $ns"

            # test if 'next subnet' is a part of a base range
            if (-not [System.Net.IPNetwork]::Contains($BaseNet, $ns)) {
                Write-Verbose "$ns is not in a $BaseNet"
                # skip the network if it is not in a base range
                continue;
            }
            else {Write-Verbose "$ns is in a $BaseNet"}

            # test if 'next subnet' overlaps any of the existing below it in a sorted list
            $k = $i; $isoverlap = $false
            do {
                if ([System.Net.IPNetwork]::Overlap($outNets[$k], $ns)) {
                    Write-Verbose "$ns overlaps $($outNets[$k])"
                    # break this loop if there is an overlap
                    $isoverlap = $true
                    break
                }
                $k++
            } while ($k -lt ($outNets.Count))

            # when there were no overlaps -> output
            if (! $isoverlap) {
                Write-Verbose "$ns did not overlap"
                $ns
            }
        }
    }

    $calcNets = {
        # put all networks we've found to the out collection, sort them
        # for some reason sort cmdlet does not work well, so use Lists and internal comparer.
        $outNets = [System.Collections.Generic.List[System.Net.IPNetwork]]::new()
        $Networks | ForEach-Object {
            $outNets.add($_)
        }
        $outNets.Sort()

        # create a collection of unused nets
        $freeNets = [System.Collections.Generic.List[System.Net.IPNetwork]]::new()

        # mark all existing as 'used'
        $outNets | Add-Member -MemberType NoteProperty -Name IsFree -Value $false -Force

        # search for free ranges in between the items of the 'used' nets list and after the last one
        $n = getIPRanges
        Write-Verbose "ip ranges we've got`: $n"

        # if there is something - add them to 'unused' list
        # mark them as 'unused'
        if ($n.count -gt 0) {
            $n | ForEach-Object {
                $net = $_ | Add-Member -MemberType NoteProperty -Name IsFree -Value $true -Force -PassThru;
                $freeNets.add($net)
            }
        }

        # TODO: search networks in front of the provided set of used networks
        $firstFree = [System.Net.IPNetwork]::ToBigInteger($BaseNet.FirstUsable)
        $lastFree = [System.Net.IPNetwork]::ToBigInteger($outNets[0].FirstUsable)
        $diff = $lastFree - $firstFree
        if ($diff -gt 0) {
            Write-Verbose "there are addresses in front of occupied blocks, number is`: $diff"
            $frontNets = [System.Collections.Generic.List[System.Net.IPNetwork]]::new()
            $firstNetToTest = "$($BaseNet.FirstUsable.ToString())/$CIDR"
            $netToTest = [System.Net.IPNetwork]::Parse($firstNetToTest)

            while (-not [System.Net.IPNetwork]::Overlap($outNets[0], $netToTest)) {
                $netToTest | Add-Member -MemberType NoteProperty -Name IsFree -Value $true -Force
                $frontNets.Add($netToTest)
                $netToTest = NextSubnet $netToTest $CIDR
            }

            Write-Verbose "$frontNets"
            $freeNets.AddRange( $frontNets )
            $freeNets.Sort()
        }
        # join used and unused together to output them properly
        $outNets.AddRange( $freeNets )
        $outNets.Sort()

        # sometimes two consequent subnets may end up with the same next free subnet. selecting unique values to avoid confusion
        $outNets | Select-Object -Unique

    }

    & $calcNets
}
{{ page.endps }}

## Parameters

Based on our assumptions we take few parameters. First of all it is the base network or the base range, we want to use. In general this defines which global range will be used to pick a subnet from. Next - the list of ranges which are already in use. And the last one is the CIDR or length of the new range we are looking for. The commandlet will look for a first free subnet of the specified size inside of the specified base range keeping in mind all used blocks.

## Some implementation details

Well, in general we do the following, on the high level:

- All network ranges passed as "used" converted to ```[System.Net.IPNetwork]```, put to a ```List```, sorted and marked as "used". Add them to the output of the cmdlet
- Search the list for free slots of the required size
  - For each of the networks in the least calculate the "Next Range" of the required size
  - Test "Next Range" to be a part of the base network
  - Test "Next Range" not to overlap with other existing networks
  - If both chars are OK, put the range to the output
- Pick the output from the search procedure, mark all the things found as "unused" and put them to the output of the cmdlet
- Look if there is a free range in front of the set of all "used" networks. If it is, mark it accordingly and put to the output

So the "search" procedure is defined as a function in the scope of the cmdlet. Meaning that we declare this function inside of the body of the cmdlet (```getIPRanges```). In addition to this we have another such function - ```NextSubnet```, which basically represents operation of calculating the "Next Range".

Also, for troubleshooting purposes I added ```-Verbose``` parameter with excessive logging, so you can see what is happening live.

# Usage scenarios

Well, the first scenario we used this for was the following:

- Pick the request for network creation, which contained the Azure Region name to put the network to, and the VNET breakdown in a form of just set of sizes, like for example (<IP_ADDRESS>). Our default layout was static and consisted of four subnets.
- Automatically determine the base range from the CMDB, based on the Region provided
- Calculate a VNET size by just adding together VNET sized, requested by a user
- Search for a free slot based on the VNET size, base network and the list of networks in use from the CMDB
- Calculate VLSM breakdown for the free slot we just found
- Fire the ARM template, providing VNET range, Subnet ranges, Names etc.

Well, this, in general, how it worked. So I hope this will also help you with your automation!

gha_language: JavaScript


text:
# ps-quser
A PowerShell wrapper for QUSER, to query logged in users and return them as a usable PowerShell object

## Usage

```powershell
Get-LoggedOnUsers -server TERMINALSERVER01
```

repository: sysadmin-as-a-service/ps-quser

gha_language: PowerShell

repo_name: sysadmin-as-a-service/ps-quser


text:
---
layout: post
title:  "Links about Islam"
date:   2016-03-30 17:00:42 +0300
categories: jekyll update
---
Here is a list that provides more info on why Islam is incompatible with Western values:

* [USA TODAY article on the literal interpretation of islam (article)][usatoday]

* [A muslim (Mosab Hassan Yousef) that relized the truth speaks (video)][Yousef-Interviews] - [wikipedia][Yousef]

* [Saudi-Born Singer Shams Bandar speaks on the blame in Arab world (video)][Bandar]

* [Wafa Sultan speech (video)][Wafa] - [wikipedia][Wafa-wiki]

* [Colonel Allen West on islam (video)][Allen-West]

* [Kuwaiti Activist Nasser Dashti: Islamic Conquests Constitute Colonialism (video)][Nasser Dashti]

* [Quran on beating women][WomenBeating]

* [Islam myths][Islam Myths]

* [Mona Walter][Mona Walter]

* [Bill Warner][Bill Warner]

more will be added soon.

***

[usatoday]: http://www.usatoday.com/story/opinion/2016/03/22/radicalization-isil-islam-sacred-texts-literal-interpretation-column/81808560/
[Yousef]: https://en.wikipedia.org/wiki/Mosab_Hassan_Yousef
[Yousef-Interviews]: https://www.youtube.com/watch?v=Kvfn-RwTHbE
[Bandar]: https://www.youtube.com/watch?v=EfWqM1hMTho
[Wafa]: https://www.youtube.com/watch?v=-mK4r7gegw0
[Wafa-wiki]: https://en.wikipedia.org/wiki/Wafa_Sultan
[Allen-West]: https://www.youtube.com/watch?v=TkGQmCZjJ0k
[Nasser Dashti]:https://www.youtube.com/watch?v=S0B7kwCQdP4
[WomenBeating]:http://quran.com/4/34
[Islam myths]:http://www.thereligionofpeace.com/pages/myths/index.aspx
[Mona Walter]:https://www.youtube.com/watch?v=d4Q8bImiPCM
[Bill Warner]:https://www.youtube.com/watch?v=B3KmUGWzsu4


text:
# Operate your hydro dex

Admin api is used to change the states of hydro dex. You can use it to add markets, changes fees and so on.The admin api server should not be exposed and should be well protected. An easy way to keep it safe is never start the admin api server on `<IP_ADDRESS>`. Always run it on localhost and use admin cli to interative with it.

## Admin cli

### Step 0: Enter the admin docker container

```
docker-compose exec admin sh
```

### Step 1: run commands

Show help

```
hydro-dex-ctl help
```

Get dex status.

```
hydor-dex-ctl status
```

Manage markets

```
hydor-dex-ctl market help

hydor-dex-ctl market list

hydor-dex-ctl market new $marketID --baseTokenAddress=”” --quoteTokenAddress=””

hydor-dex-ctl market update $marketID --editableAttr=value

hydor-dex-ctl market publish $marketID

hydor-dex-ctl market unpublish $marketID

hydor-dex-ctl market changeFees $marketID "asMakerFee" "asTakerFee"
```

Get info about an address

```
hydor-dex-ctl address "address" --orders --balances --trades
```

Cancel a special order

```
hydor-dex-ctl order cancel "orderID"
```

Restart engine

```
hydor-dex-ctl engine restart
```

## Admin api

Beside the hydor-dex-ctl command, you can also use rest api to manage your dex.

See details at [here](./backend/admin/api/server.go).

repository: AntonioRossi/hydro-box-dex

repo_name: AntonioRossi/hydro-box-dex


text:
# Using a private Git host

> **🛑 Upgrade Advisory**
>
> This documentation is for Flux (v1) which has [reached its end-of-life in November 2022](https://fluxcd.io/blog/2022/10/september-2022-update/#flux-legacy-v1-retirement-plan).
>
> We strongly recommend you familiarise yourself with the newest Flux and [migrate as soon as possible](https://fluxcd.io/flux/migration/).
>
> For documentation regarding the latest Flux, please refer to [this section](https://fluxcd.io/flux/).

If you're using your own git host -- e.g., your own installation of
gitlab, or bitbucket server -- you will need to add its host key to
`~/.ssh/known_hosts` in the Flux daemon container.

First, run a check that you can clone the repo. The following assumes
that your git server's hostname (e.g., `githost`) is in `$GITHOST` and
the URL you'll use to access the repository (e.g.,
`user@githost:path/to/repo`) is in `$GITREPO`.

```sh
$ # Find the fluxd daemon pod:
$ kubectl get pods --all-namespaces -l name=flux
NAMESPACE   NAME                    READY     STATUS    RESTARTS   AGE
weave       flux-85cdc6cdfc-n2tgf   1/1       Running   0          1h

$ kubectl exec -n weave flux-85cdc6cdfc-n2tgf -ti -- \
    env GITHOST="$GITHOST" GITREPO="$GITREPO" PS1="container$ " /bin/sh

container$ git clone $GITREPO
Cloning into <repository name>...
No ECDSA host key is known for  <GITHOST> and you have requested strict checking.
Host key verification failed.
fatal: Could not read from remote repository

container$ # ^ that was expected. Now we'll try with a modified known_hosts
container$ ssh-keyscan $GITHOST >> ~/.ssh/known_hosts
container$ git clone $GITREPO
Cloning into '...'
...
```

If `git clone` doesn't succeed, you'll need to check that the SSH key
has been installed properly first, then come back. `ssh -vv $GITHOST`
from within the container may help debug it.

If it _did_ work, you will need to make it a more permanent
arrangement. Back in that shell, create a ConfigMap for the cluster. To
make sure the ConfigMap is created in the namespace of the Flux
deployment, the namespace is set explicitly:

```sh
container$ kubectl create configmap flux-ssh-config --from-file=$HOME/.ssh/known_hosts -n $(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace)
configmap "flux-ssh-config" created
```

To use the ConfigMap every time the Flux daemon restarts, you'll need
to mount it into the container. The example deployment manifest
includes an example of doing this, commented out. Uncomment those two blocks:

```yaml
      - name: ssh-config
        configMap:
          name: flux-ssh-config
```

```yaml
        - name: ssh-config
          mountPath: /root/.ssh
```

It assumes you used `flux-ssh-config` as name of the ConfigMap and then reapply the
manifest.

Another alternative is to create the ConfigMap from a template. This could be
something like:

```yaml
apiVersion: v1
data:
  known_hosts: |
    # github
    <IP_ADDRESS> ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==
    # github
    <IP_ADDRESS> ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==
    # private gitlab
    gitlab.________ ssh-rsa AAAAB3N...
kind: ConfigMap
metadata:
  name: flux-ssh-config
  namespace: <OPTIONAL NAMESPACE (if not default)>
```

You will need to explicitly tell `fluxd` to use that service account by
uncommenting and possible adapting the line `# serviceAccountName:
flux` in the file `flux-deployment.yaml` before applying it.

repository: fluxcd/flux

gha_language: Go

repo_name: fluxcd/flux