synchronization – Verification of atomic primitives using Petri Net Models

I want to verify semantics of a library of atomic primitives that I wrote. The idea is, only if the semantics of all the primitives are consistent with each other, an application that uses them could behave predictably.

For example, a composition of a primitive Fx(lck) which takes exclusive lock on an lck object could be –
Fx(Fx(lck)). But this could lead to a dead lock when operated on a single thread. This is a valid scenario if lck is a non-recursive lock.

I wonder if I could create a Petri Net model of my primitives to check if they are present a perfect synchronization tool.

You can also propose an alternate solution. mvc – Consulta con varias tablas en .net Framework MVC

Tengo 2 tablas, modelo en tabla marcas se encuentra(id_marca, nombre_marca) en la tabla modelos (“id_modelos, nombre_modelo, id_marca”).
Ya en mi código consulto la tabla modelos de esta manera:

           using (CrudEntities db= new CrudEntities())
               lst = (from d in db.modelos
                          select new ListTablaViewModel
                              Id = d.id_modelo,
                              Nombre = d.nombre_marca

Lo muestro en la vista asi:

<div class="row">
   <div class="col-md-12">
       <table class="table">
           @foreach (var oElemento in Model)
                       <a class="btn btn-default" href="~/Tabla/Editar/@oElemento.Id">Editar</a>
                       <a class="btn btn-danger" href="~/Tabla/Eliminar/@oElemento.Id">Eliminar</a>


Mi consulta es ¿Cómo puedo hacer para que me salga el nombre de la marca y no su id
Gracias de antemano

architecture – What is the proper way to handle Oauth Token caching in .Net Web API

When using RestFul web api in my app I have a requirement to handle token caching so that on the authorization(api side) It only needs to send this access token to the validation server once per hour or whenever the expiration is set at. The other subsequent calls up to that hour mark would see that it has been already validated and can allow the call to continue

So what is the correct flow for handling this type of caching?

Client gets Access Token on their side with their Id and Secret ->

Bearer AT is passed in header to my api and I validate it once ->

Api call is made and response is sent back along with AT and a Validated boolean value as true??? ->

All other client calls made to the api will attach Access Token and Bool Value in the header??? ->

Api reads bool value as true and allows passage???

This doesn’t seem the right way to handle it to me. So what is the proper way?

.net – ¿Cuál es el método más seguro para guardar JWT en ASP.NET MVC?

Tengo una API WEB ASP.NET, Y Quiero consumirla desde una cliente ASP.NET, ya estoy recuperando el TOKEN de JWT, pero no tengo mucha experiencia de como guardarlo y que sea seguro, ya que he leído, algunos post donde los guardan en cookies o session storage, tengo muchas dudas, si me podéis orientar, que camino seguir y por qué sería el más seguro?

c# – Como buscar lista de registros pela chave estrangeira em ASP NET?

Preciso retornar uma lista de projetos em formato JSON na minha API a partir da chave estrangeira que vem da tabela de cursos. No entanto, apenas há o retorno de um registro, não a lista inteira.

A classe de projeto:

    public class Project
        public int Id { get; set; }
        (Required(ErrorMessage = "Nome é obrigatório"))
        public string Name { get; set; }
        public string Image { get; set; }
        public string Why { get; set; }
        public string What { get; set; }
        public string WhatWillWeDo { get; set; }
        public ProjectStatus ProjStatus { get; set; }

        public Course Course { get; set; }

        public int CourseId { get; set; }

        public enum ProjectStatus
            development = 0,
            publicated = 1

O método de retorno a partir do ID do curso:

        public Project GetCourse(int id)
            return context.Project.Where(i => i.CourseId == id).Include("Course").FirstOrDefault();

O controller que chama o método:

       public ActionResult<Project> Get(int id)
                var project = _acess.GetCourse(id);
                return project;
            catch (DataException ex)
            return Ok();

Alguém pode me esclarecer de que maneira posso alterar este código para que ele me retorne todos os projetos que possuem determinado curso?

dnd 5e – Can a magical net be repaired and keep its properties?

I asked a similar question on the Adventurers League Dungeon Masters Facebook group, and the consensus seemed that when a magical object has hit points and receives enough damage to get to 0 HP, it is destroyed and looses its magic forever, without possibility to repair it. Here is a relevant extract from the AL FAQ (emphasis mine) :

Shatterspike can’t be used to destroy magic items, unless the item itself specifically provides an AC, hit points, etc. in its description. In that case, it’s hella good at destroying them. Take that, magic net!

Here, we can see that the AL FAQ hints that magic nets can be destroyed, not only broken. It continues :

Unless the conditions of an item’s destruction is specifically stated (talon card from deck of many things, ioun stone, +1 nets, etc.) permanent magic items can’t be destroyed, Items destroyed in such a manner follow the normal rules for intentional or unintentional destruction.

We can determine that a net’s destruction clause (AC 10, 5 HP) is intentional, and so the AL guidance states :

Some items have conditions that include the ability or potential to intentionally destroy the item. If destroyed, these items still count.

So, to summarize : a magical net that gets destroyed by having its HP reduced to 0 will lose its magic, and if repaired, will simply be a plain non-magical net. However, the magical net will still count towards the wielder’s Magic Item Count.

Still citing the AL rules, you could argue that a destroyed magic item is not necessarily rendered nonmagical, because of the following text :

Permanent Effects : Some items are destroyed or rendered nonmagical when used, (…)

If so, you could then say that a destroyed magic item could be repaired and keep its magic. I think there’s AL rules preventing that, but not quite sure at the moment (edit needed).

batch file – ‘net use’ , mapping network drive without stored credentials

Stack Exchange Network

Stack Exchange network consists of 176 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Visit Stack Exchange

image processing – how to implement training for UNET implementation on Wolfram Neural Net Repository?

My question is with reference to the U-NET implementation present on the Wolfram Neural Net Repository

The construction notebook present on the page (link: contains all the necessary functions for constructing the net. However, it does not contain the procedure for training the neural net.

I am trying to implement a simple training procedure so that I can firstly train the net myself on the same dataset which the net was initially trained on ( Thereafter, I would like to use a different dataset for training.

Please download the construction notebook before proceeding. The only code that I have added to the construction notebook is mentioned below:

(*loading the images, resizing them and augmenting them to produce the training dataset;
background labelled as 1 and cells in the foreground as 2.*)

fnamesimages = Import("C:\Users\aliha\Downloads\dataset\images\");
ordering = Ordering@Flatten@StringCases(fnamesimages, (p : DigitCharacter ..) ~~ ".tif" :> FromDigits@p);
fnamesimages = fnamesimages((ordering));

images = Import("C:\Users\aliha\Downloads\dataset\images\" <> #) &/@fnamesimages;
images = ImageResize(#, {388, 388}) & /@ images;
masks = Import("C:\Users\aliha\Downloads\dataset\segmentation\" <> #) &/@fnamesimages;
allmasks = Flatten@Table(ImageRotate(j, i), {j, masks}, {i, {0, Pi/2, Pi, 3/2 Pi}});
allmasks = Join(allmasks, ImageReflect /@ allmasks);
maskres = ImageResize(#, {388, 388}) & /@ allmasks;

m = ArrayComponents(ImageData@#, 2, {0. -> 1, n_ /; n != 0. -> 2}) &/@maskres;
allimages = Flatten@Table(ImageRotate(j, i), {j, images}, {i, {0, Pi/2, Pi, 3/2 Pi}});
allimages = Join(allimages, ImageReflect /@ allimages);

(* using a small subset of images and segmented images because of GPU memory crash*)
trained = NetTrain(unet, allimages((1 ;; 50)) -> m((1 ;; 50)), All, BatchSize -> 5, MaxTrainingRounds -> 1, TargetDevice -> "GPU");
trainedNet = trained("TrainedNet");

enter image description here

In addition I am using the code in the example notebook (present on the same page) to then evaluate the trained net on a test image.

netevaluate(img_, device_ : "CPU") :=
Block({net = trainedNet, dims = ImageDimensions(img), pads, mask},
pads = Map({Floor(#), Ceiling(#)} &, Mod(4 - dims, 16)/2);
mask = NetReplacePart(net,
  {"Input" -> 
    NetEncoder({"Image", Ceiling(dims - 4, 16) + 188, 
      ColorSpace -> "Grayscale"}),
   "Output" -> 
    NetDecoder({"Class", Range(2), "InputDepth" -> 3})})(
 ImagePad(ColorConvert(img, "Grayscale"), pads + 92, 
  Padding -> "Reversed"),
 TargetDevice -> device
Take(mask, {1, -1} Reverse(pads((2)) + 1), {1, -1} (pads((1)) + 1))

we can now load the test image and apply the net.

testimg = Import("C:\Users\aliha\Downloads\dataset\test image\t099.tif);

enter image description here

Unfortunately I do not get any segmentations back. I just get the background. Could someone kindly let me know where I may be having the issue? Thanks !

.net – How to get the relationship between an embedded document and its media file from Word using OpenXML

When a Word document contains an embedded Office document it creates a media file to display the name and logo of the document and it embeds the Office document. I am failing to relate the media file to the document using OpenXML.

I can get the embedded documents and media files using the following code, but I cannot see any relationship between the two from the class members.

Private Shared Function ExtractStream(source As Document, Stream As IO.Stream, format As DocumentDataFormat) As DocumentList
    Dim Documents As New DocumentList()
    Const embeddingPartString As String = "/word/embeddings/"
    Const mediaPartString As String = "/word/media/"
    Using WordDoc = WordprocessingDocument.Open(Stream, False)

        Dim intDocumentIndex As Int32 = 1
        ' EmbeddedPackagePart - These are the Office 2007+ type documents
        For Each pkgPart In WordDoc.MainDocumentPart.GetPartsOfType(Of EmbeddedPackagePart)
            If pkgPart.Uri.ToString.StartsWith(embeddingPartString) Then
                Dim fileName1 As String
                fileName1 = pkgPart.Uri.ToString.Remove(0, embeddingPartString.Length)
                Dim Doc As Document = ReadOffice(source, pkgPart, format, intDocumentIndex)
                If (Doc IsNot Nothing) Then
                    intDocumentIndex += 1

                End If
            End If

        For Each pkgPart In WordDoc.MainDocumentPart.GetPartsOfType(Of ImagePart)
            ' Media files
            If pkgPart.Uri.ToString.StartsWith(mediaPartString) Then
                Dim fileName1 As String
                fileName1 = pkgPart.Uri.ToString.Remove(0, mediaPartString.Length)
                Dim Doc As Document = ReadMedia(source, pkgPart, format, intDocumentIndex)
                If (Doc IsNot Nothing) Then
                    intDocumentIndex += 1
                End If

            End If
    End Using
    Return Documents

End Function

I can get relationships between a media file and an embedded Ole Object if I walk the child elements of the WordDoc.MainDocumentPart.Document class. When I find an Ole Object I look for a sibling Shape XmlElement in the parent’s ChildElements collection.

This is fine, except I cannot figure out how to get the embedded files from these classes.

    ' Start with the Document class.

Private Shared Sub LookForOleObjects(elem As DocumentFormat.OpenXml.OpenXmlElement)
    If elem Is Nothing Then Return

    Dim ole = TryCast(elem, DocumentFormat.OpenXml.Vml.Office.OleObject)
    If (ole IsNot Nothing) Then
        ' found one.
        Dim img = GetImageFile(ole)
        If img IsNot Nothing Then
            ' found the image for the ole object
        End If
    End If
    If (elem.ChildElements IsNot Nothing) Then
        For Each child In elem.ChildElements
    End If

End Sub

Private Shared Function GetImageFile(ole As OleObject) As DocumentFormat.OpenXml.Vml.ImageData
    Dim p As DocumentFormat.OpenXml.OpenXmlElement = ole.Parent
    For Each child In p.ChildElements
        Dim shape As DocumentFormat.OpenXml.Vml.Shape = TryCast(child, DocumentFormat.OpenXml.Vml.Shape)
        If shape IsNot Nothing Then
            Dim Img As DocumentFormat.OpenXml.Vml.ImageData = TryCast(shape.ChildElements(0), DocumentFormat.OpenXml.Vml.ImageData)
            If Img IsNot Nothing Then Return Img
        End If
    Return Nothing
End Function

I have two approach but each one is lacking. The first get the embedded document but not the relationships, and the second gets the relationships but not the embedded documents.
What am I Missing? How can get the embedded document and its related medial file using OpenXML?

c# – .NET MVC Core – SelectListItem pegando o ID de uma tabela, como passar o nome relacionado ao ID na VIEW de consulta?

estou criando um DropDownListFor que contem os Ranks disponíveis para escolha no cadastro de um novo jogador. Ele está funcionando perfeitamente, cadastrando tudo ok, porém, preciso exibir esse rank na tela de consulta de jogadores, mas confesso que meu cérebro deu um nó agora, pois no momento do cadastro ao selecionar o Rank do jogador, o que é cadastrado no banco é o Id do rank, que é uma foreign key referenciando outra tabela chamada “Elos”, onde nesta sim possui o Nome do rank que eu preciso que apareça na tela de consulta. Enfim, como posso fazer para que, na tela de consulta, ao invés de aparecer o ID do rank, apareça o Nome? Não sei nem qual código devo postar aqui para ajudar no entendimento da minha questão, então se me derem uma luz com a lógica que precisarei usar, já seria incrível
Qualquer ajuda é bem vinda