c # – Implementing the repository for thread security

I would need a revision of the code for the next implementation. Is this code safe? What can we improve?
The purpose of this code is for the study.

Public class Repository: IRepository, IDisposable
{
private IStorage _storage;
private list the entrees;

Public repository (IStorage storage)
{
_storage = storage;
_entries = storage.Load (). ToList ();
}

public void Create (input)
{
_entries.Add (entry);
}

public void Update (Enter)
{
existing var = _entries.Where (x => x.ID == entry.ID) .FirstOrDefault ();
existing name.name = entry.name;
existing.Number = entry.Number;
existing.Type = entry.Type;
}

public void Delete (Enter)
{
_entries = _entries.Where (x => x.ID! = entry.ID) .ToList ();
}

public entry GetEntry (Guid ID)
{
return _entries.FirstOrDefault (x => x.ID == ID);
}

public IEnumerable GetAlphabetically (Func support)
{
return _entries.OrderBy (x => prop (x));
}

public void Save ()
{
_storage.Persist (_entries);
}

private bool disposed = false;

public void Dispose ()
{
Eliminate (true);
GC.SuppressFinalize (this);
}

protected virtual empty Dispose (bool disposing)
{
if (! disposed)
{
if (dispose)
{
if (_entries! = null)
_entries = null;
}
willing = true;
}
}

~ Repository ()
{
Eliminate (false);
}
}

What are the steps to follow when implementing SEO?

Hello friends,

What are the steps to follow when implementing SEO?

c ++ – Implementing different types of light sources in a graphics project

I am working on an computer graphics project and have found a way to implement different types of light sources, which, in my opinion, is not ideal.

There are two types of light sources: parallel and point.

The point light source moves around the mesh and the parallel light source "can be imagined as a point light source located at infinity". In other words, a parallel light source has a constant direction throughout the mesh, while a point light source is illuminated in all directions, but has a position that affects the direction of light relative to on the surface it illuminates.

I have trouble finding the right abstraction for all these types. Here is my solution:
I have an abstract base class called Light source:

LightSource class: public IMovable, public IRotatable
{
protected:
glm :: vec4 color;
public:
...
// virtual setters
virtual void SetDirection (const glm :: vec4 & _direction) = 0;
virtual void SetLocation (const glm :: vec4 & _location) = 0;

// Virtual Getters
virtual const glm :: vec4 * GetDirection () const = 0;
virtual const glm :: vec4 * GetLocation () const = 0;

// inherited via IMovable
virtual void Move (direction const glm :: vec3) override = 0;

// Inherited via IRotatable
virtual void RotateX (constant floating angle) override = 0;
virtual void RotateY (constant angle of floating) override = 0;
virtual void RotateZ (constant flotation angle) override = 0;
};

and two derived classes:

PointLightSource class: public LightSource
{
private:
...
public:
// builders
...
// basic class
virtual const glm :: vec4 * GetDirection () const override {return nullptr; };
virtual const glm :: vec4 * GetLocation () const override {return & location; };

// basic class
virtual void SetDirection (const glm :: vec4 & _direction) override {return; }
virtual void SetLocation (const glm :: vec4 & _location) override {location = _location; }

// inherited via LightSource
virtual void Move (direction const glm :: vec3) override;
virtual void RotateX (constant floating angle) redefined {} // Spot light source emits light everywhere
virtual void RotateY (constant angle of floating) override {}
virtual removal RotateZ (constant floating angle) override {}
...
};

and:

ParallelLightSource class: public LightSource
{
private:
...
public:
...
// Setters
virtual void SetDirection (const glm :: vec4 & _direction) override {direction = glm :: normalize (_direction); }
virtual void SetLocation (const glm :: vec4 & _location) override {return; }

// Getters
virtual const glm :: vec4 * GetDirection () const override {return & direction; }
virtual const glm :: vec4 * GetLocation () const override {return nullptr; };

// inherited via LightSource
virtual removal of RotateX (constant floating angle);
virtual void RotateY (constant floating angle);
virtual removal of RotateZ (constant floating angle);

// Can not move a parallel light source
virtual void Move (const glm :: vec3 direction) override {}
...
};

Light source virtually implements two interfaces. we call each other IMovable and it is used for every object that moves around the mesh (be it a model, a camera or a light source).
another interface is called IRotatable, and it is used for objects that can rotate. Not all moving objects are rotatable and the point source of light is a good example. So I created two interfaces.

Essentially, what I want is it's power move spot light source but not rotate them, and turn Parallel light sources without moving them, and do all this without checking their real type due to polymorphism. The problem is that each Light source is, at the same time IMovable and IRotatable, so I can not distinguish the derived types.

My impractical solution was to have two virtual functions: GetLocation and GetDirection that return pointers to vectors. ParallelLightSource will return nullptr to GetLocation and PointLightSource will return nullptr to GetDirection.

In the code menus, I get a vector of Light source pointers and I want to display their appropriate menus. As you have guessed, there are two types of relevant menus here, one for IMovable objects and one for IRotatable objects.
I'm calling the GetLocation And getDirection functions and ignore the appropriate commands if the pointer that I got is a nullptr.

const glm :: vec4 * lightLocation = activeLight-> GetLocation ();
const glm :: vec4 * lightDirection = activeLight-> GetDirection ();

...
if (lightLocation! = nullptr)
{
moveObjectControls (activeLight, "Light");
}
if (lightDirection! = nullptr)
{
newDirection = * lightDirection;
xyzSliders (newDirection, "Direction", worldRadius);
}

Passing vector pointers rather than vectors by value is problematic. For example, now I really need ParallelLightSource to implement GetLocation and return a real value. I should either have a location class member who will always be equal to -direction * someLargeNumber, or refactor and have GetLocation and getDirection return values, which will create another mess in the menus because I do not want to see the controls that "move" a parallel light source or "rotate" a spot light source because it makes no sense, then I would have to check the derived types in a way that breaks the polymorphism.

One solution I thought of was having booleans to indicate if I wanted this light to show the IMovable/IRotatble menus, but that does not seem correct, because I do not think it is the responsibility of the light source to know how it is presented in the menus.

Another solution would be to hold a vector for parallel light sources and another for point light sources, but this does not seem intelligent because it is not very scalable and each time I implement a new type of light. source of light, I will have to change it. The menus.

I'm pretty new to programming (at least in OOP), so I'm wondering what's the ideal solution in a situation like this. Let me know if you also have other comments.

multithreading – Implementing a Collector Parallel to the Custom Java Stream API

I'm experimenting with the idea of ​​building a parallel collector for the Java Stream API (so that operations can run in parallel, not just on the common FJP).

A basic implementation is quite simple. However, once you try to implement a parallelism limitation, it becomes pretty tricky.

The simplest way to implement it would be to rely on a Semaphore example, but in my approach, the result is wrapped in CompletableFutureThus, the entire computation must be executed asynchronously to avoid generating a blocking future.

To do this, I created a queue of work managed by a single distributor thread (protected by a Semaphore example).

To comply with Collector API, in addition, I had to create a queue not yet completed CompletableFuture instances, so that you can retrieve them later and finish once the results are calculated.

I have tested it thoroughly and it seems to work, but I'm sure it must contain a lot of multithreading / simultaneous access bugs …

Please suggest improvements.

Here is the code:

AbstractParallelCollector which serves as a basis:

abstractParallelCollector abstract class <T, R1, R2 extends the collection>
implements Collector <T, List <CompletableFuture>, CompleteFuture> {

executor final executor;
final function surgery;
final supplier CollectionFactory;

AbstractParallelCollector (
A function surgery,
Provider collection,
Executor executor) {
this.executor = executor;
this.collectionFactory = collection;
this.operation = operation;
}

@Override
public Suppliers <List <CompletableFuture>> provider () {
return () -> synchronizedList (new ArrayList <> ());
}

@Override
public BiConsumer <List <CompleteFuture>, T> accumulator () {
return (processing, e) -> processing.add (supplyAsync () -> operation.apply (e), executor));
}

@Override
public BinaryOperator <List <CompleteFuture>> combinator () {
back (left, right) -> {
left.addAll (right);
turn left;
};
}

@Override
public Function <List <CompletableFuture>, CompleteFuture> finisher () {
return of futures -> futures.stream ()
.reduce (completedFuture (collectionFactory.get ()),
accumulationResults (),
mergingPartialResults ());
}

@Override
public abstract set characteristics();

private static <T1, R1 extends the collection> BinaryOperator <CompletableFuture> mergingPartialResults () {
return (f1, f2) -> f1.thenCombine (f2, (left, right) -> {
left.addAll (right);
turn left;
});
}

private static <T1, R1 extends the collection> BiFunction <CompleteFuture, CompleteFuture, CompleteFuture> accumatingResults () {
return (list, object) -> list.thenCombine (object, (left, right) -> {
left.add (right);
turn left;
});
}
}

A specific implementation limiting parallelism:

Throttling classParallelCollector <T, R, C Collection>
extends AbstractParallelCollector
  implements AutoCloseable {

private final ExecutorService dispatcher = newSingleThreadExecutor (new CustomThreadFactory ());

private final BlockingQueue <Vendor> taskQueue = new LinkedBlockingQueue <> ();
final final private ConcurrentLinkedQueue <CompletableFuture> pending = new ConcurrentLinkedQueue <> ();
private final semaphore license;

ThrottlingParallelCollector (
A function surgery,
Provider CollectionFactory,
Executor,
int parallelism) {
super (operation, collectionFactory, executor);
permit = new semaphore (parallelism);
dispatcher.execute (dispatcherThread ());
}

@Override
public BiConsumer <List <CompleteFuture>, T> accumulator () {
return (acc, e) -> {
CompletableFuture future = new CompleteFuture <> ();
waiting for (future);
acc.add (future);
taskQueue.add (() -> {
try {
return.apply (e) operation;
} finally {
permissions.release ();
}
});
};
}

@Override
public set characteristics() {
return EnumSet.of (Characteristics.UNORDERED);
}

@Override
public Function <List <CompletableFuture>, CompleteFuture> finisher () {
returns super.finisher ()
.etThen (f -> {
try {
returns f;
} finally {
dispatcher.shutdown ();
}
});
}

@Override
public void close () {
dispatcher.shutdown ();
}

private Runnable dispatcherThread () {
return () -> {
while (! Thread.currentThread (). isInterrupted ()) {
try {
permissions.acquire ();
runAsyncAndComplete (taskQueue.take ());
} catch (InterruptedException e) {
permissions.release ();
Thread.currentThread (). Interrupt ();
Pause;
} catch (Exception e) {
permissions.release ();
launch e;
}
}
};
}

runAsyncAndComplete (provider) task) {
supplyAsync (task, executor)
.thenAccept (result -> Objects.requireNonNull (waiting.poll ()). complete (result);
}

The Private CustomThreadFactory class implements ThreadFactory {
final final private defaultThreadFactory = Executors.defaultThreadFactory ();

@Override
Public topic newThread (executable task) {
Thread = defaultThreadFactory.newThread (task);
thread.setName ("parallel-executor-" + thread.getName ());
thread.setDaemon (true);
return of the wire;
}
}
}

A static factory method:

public static  Collector <T, List <CompletableFuture>, CompleteFuture <List>> inParallelToList (Function mapper, executor executor, int parallelism) {
requireNonNull (executor);
requireNonNull (mapper);
assertParallelismValid (parallelism);
returns the new ThrottlingParallelCollector <> (mapper, ArrayList :: new, executor, assertParallelismValid (parallelism));
}

And a super simple example:

CompleteFuture <List> result = Flow of (1, 2, 3)
.collect (inParallelToList (i -> foo (), executor, 2));

Implementing an AJAX POST API call in wordpress

I'm trying to make a POST request to an API. I have created a javascript file in my theme and have already tried two approaches:

Approach 1:

$ .ajax ({
headers: {
"Content-Type": "application / json"
}
The data: {
"command": "request",
"The data": {
"api_key": "my_api_key",
"api_username": "my_api_user",
"vendor_type": 2,
"from": {
"from_name": "",
"from_lat": "",
"from_long": "",
"from_description": ""
}
"at": {
"to_name": customerLocation,
"to_lat": cityLat,
"to_long": cityLng,
"to_description": ""
}
"receiver": {
"recepient_name": name,
"recepient_phone": phone,
"recepient_email": email,
"recepient_notes": ""
}
"delivery details": {
"pick_up_date": pickupdate,
"collect_payment": {
"status": false,
"pay_method": 0,
"amount": total amount
}
"return": true,
"note": "Sample note",
"note_status": true,
"request_type": "quote"
}
}
"request_token_id": requestToken
}
type: "POST",
url: "https://apitest.sendyit.com/v1/",
success: function (answer) {
console.log (& # 39;);
console.log (response);
}
error: function (answer) {
console.log (& # 39;) error;
console.log (response);
}
});

The above code will not return a response load from the API because any call will be blocked due to Cross-Origin Resource Sharing (CORS) resource sharing.

Approach 2

I then try to pass the end point to my functions.php file as follows:

// make api call to sendy
foo function ()
{
echo & # 39; https: //apitest.sendyit.com/v1/&#39 ;;
}
add_action (& # 39; wp_ajax_foo & # 39;; & # 39; foo & # 39;);
add_action (& # 39; wp_ajax_nopriv_foo & # 39;; & # 39; foo & # 39;);

I declare a ajaxUrl variable in the header.php file of my theme:


Then format my Ajax call as shown below:

$ .ajax ({
headers: {
"Content-Type": "application / json"
}
The data: {
"action": "foo",
"command": "request",
"The data": {
"api_key": "my_api_key",
"api_username": "my_api_user",
"vendor_type": 2,
"from": {
"from_name": "",
"from_lat": "",
"from_long": "",
"from_description": ""
}
"at": {
"to_name": customerLocation,
"to_lat": cityLat,
"to_long": cityLng,
"to_description": ""
}
"receiver": {
"recepient_name": name,
"recepient_phone": phone,
"recepient_email": email,
"recepient_notes": ""
}
"delivery details": {
"pick_up_date": pickupdate,
"collect_payment": {
"status": false,
"pay_method": 0,
"amount": total amount
}
"return": true,
"note": "Sample note",
"note_status": true,
"request_type": "quote"
}
}
"request_token_id": requestToken
}
type: "POST",
URL: ajaxurl,
success: function (answer) {
console.log (& # 39;);
console.log (response);
}
error: function (answer) {
console.log (& # 39;) error;
console.log (response);
}
});

But that gives me a 400 (bad request) Fault.

I must mention that I correctly configured my javascript file in the functions.php file:

wp_enqueue_script (& # 39; sendy & # 39 ;, get_template_directory_uri (). & # 39; /assets/js/sendy.js&#39 ;, array (& # 39; jquery & # 39;));
wp_localize_script ('sendy', 'wc_checkout_params', array ('ajaxurl' => admin_url ('admin-ajax.php')));

I would like to ask for help in configuring my POST client terminal.

beginner – Implementing getdelim

Note: I did not try to follow the existing getdelim signature exactly. I needed to add the use argument for a project I'm working on.

I am new enough to write C. It would be great to know if best practices are followed.

Some things I learned while writing this code (which could be points to improve)

  • Pointer arithmetic
  • FILE * error management
ssize_t read_until_diminator (char ** buffer, size_t * size, character delimiter,
FILE * file, bool consume)
{
char ch;
char * buffer_pos;

if (buffer == NULL || size == NULL || ferror (file)) {
errno = EINVAL;
return -1;
}

if (buffer == NULL || * size == 0) {
// empty buffer provided
* size = 128;
* buffer = malloc (* size);

if (* buffer == NULL) {
errno = ENOMEM;
return -1;
}
}

buffer_pos = * buffer;

for (;;) {
ch = getc (file);

if (ch == EOF) {
Pause;
}

if ((buffer_pos + 1) == (* buffer + * size)) {
// More space in the buffer
size_t new_size = * size * 2;
char * realloc_buffer = realloc (* buffer, new_size);

if (realloc_buffer == NULL) {
errno = ENOMEM;
return -1;
}

buffer_pos = realloc_buffer + (buffer_pos - * buffer);
* buffer = realloc_buffer;
* size = new_size;
}

* buffer_pos ++ = ch;

if (ch == deliminator) {
if (! consomme) {
// If you do not consume delimitation buffer
* buffer_pos--;
}

Pause;
}
}

if (ch == EOF && buffer_pos == * buffer) {
return -1;
}

* buffer_pos = & # 39;  0 & # 39 ;;

return buffer_pos - * buffer;
}

Minimum work example: https://repl.it/repls/SlimEarlyField

Implementing the OAuth server in Java

I want to write an authorization service using OAuth in Java without using any frame like Spring. Initially, I need to generate unencrypted tokens UUID so what JWT as a second step.
I could not find good and fundamental implementation of OAuth server in Java. Which library should I use? Can someone help!

logic – Simplifying SOPs: Implementing OR with NAND

I'm learning to implement basic logic gates with the help of NAND. I've learned that you can use De Morgan's theorem as such:

$ a + b = bar { bar a} + bar { bar b} = overline {( bar a * bar b)} ​​$

In other words, we would need two NOT gates (which are essentially NAND gates) and another NAND gate.

However, I want to practice the simplification of Boolean algebra. Using a truth table, I have formed the sum of products:

$ f (a, b) = ab + + a & # 39; b + ab $

I have mapped out several paths without success. I would appreciate that someone can point out the simplification steps or give me guidance on the laws to use to achieve this simplification. If there are any log errors I made, thank you for letting me know 🙂

c # – Implementing Xamarin.Forms and Prism NavigationParameters

I am developing a Xamarin Forms project and using Prism Library as a tool to implement the MvvM model.

I have two points of view:

  • PersonViewModel: Summary and a edit button
  • PersonEditViewModel: Details, and Cancel save and Wipe off buttons

The proposed concept: managing the result of the PersonEditViewModel returning to the PersonViewModel and make a decision based on the navigation settings.

My questions about the concept:

  • Is the way to handle the dialog results "ok" since I'm trying to follow the principles of MVM?
  • Do you make good use of the navigation features of the Prism library?

The sample code. I have omitted private fields, error handling, and so on. for readability.

Public enumeration ItemDialogResult
{
Saved = 1,
Canceled = 0,
Deleted = -1
}

Public class PersonViewModel: INavigationAware
{
private read only INavigationService _navigationService;

public PersonViewModel ()
{
EditCommand = new Command (async () => wait _navigationService.NavigateAsync ($ "PersonEditPage? Id = {Person.Id}");
}

public async void OnNavigatedTo (INavigationParameters parameters)
{
var navigationMode = parameters.GetNavigationMode ();

if (navigationMode == NavigationMode.Back)
{
// GetValueOrDefault is a custom extension that uses GetValue but returns a default value if it does not exist in the parameters.
// For example, when the hardware button is used to go back.
var result = parameters.GetValueOrDefault ("result", ItemDialogResult.Cancelled);

switch (result)
{
ItemDialogResult.Cancelled box:
// The person shown is still valid
return;

ItemDialogResult.Saved box:
// Continue and reload the person below
Pause;

case ItemDialogResult.Deleted:
// nobody has been deleted Return from the p
wait _navigationService.GoBackAsync ();
return;
}
}

Person = _personService.LoadPerson ();
}
}

Public class PersonEditViewModel: INavigationAware
{
private read only INavigationService _navigationService;

public PersonEditViewModel ()
{
CancelCommand = new Command (async () => wait GoBack (ItemDialogResult.Cancelled));
DeleteCommand = new Command (async () =>
{
_personService.Delete (_person);
wait GoBack (ItemDialogResult.Deleted);
});
SaveCommand = new Command (async () =>
{
_personService.SaveOrUpdate (_person);
wait for GoBack (ItemDialogResult.Saved);
});
}

GoBack private asynchronous task (ItemDialogResult result)
{
var parameters = new NavigationParameters
{
{"result", result}
};

wait _navigationService.GoBackAsync (parameters);
}
}