Thursday, July 7, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


EFC6 Updating object tries to insert FK into to related table

Posted: 07 Jul 2022 03:42 PM PDT

For a class with a FK/Navigation property, I'm trying to update a FK value. When the EFC Save triggers, it tries to insert the related FK, but it already exists.

var ticketToSave = await _context.Ticket.FindAsync(ticket.Id);   ticketToSave.TicketTypeId = 3;  

As expected, the Change Tracker shows the FK modified.

Ticket {Id: 20002} Unchanged    Id: 20002 PK    TicketTypeId: 3 FK Originally 1    TicketType: <not found>  

The TicketType is not found because that TicketType has not yet been used by the context.

var rowsAffected = await _context.SaveChangesAsync();  

This returns an error. It is trying to insert the TicketType into the table even though the record already exists.

Violation of PRIMARY KEY constraint 'PK_TicketType'. Cannot insert duplicate key in object 'TicketType'. The duplicate key value is (3).  

I don't want to have to load every possible value for every related property just so I can use the ones that I need.

How do I tell EFC to save the Ticket FK update to the database, without dealing with the untracked navigation property?

rc-table - background-color table row

Posted: 07 Jul 2022 03:41 PM PDT

I'm using rc-table - https://www.npmjs.com/package/rc-table For rendering tables in react.

And when I'm tring to use background-color this is the result - enter image description here

And that's the result I want - enter image description here

How can I fill the gaps?

The code -

HTML -

<Table      className={classes['secretsWrapper__table']}  />  

CSS -

&__table {      tr:nth-child(even) {          background: #e7e7e7;      }  }  

How to unit test Angular's Meta service?

Posted: 07 Jul 2022 03:41 PM PDT

My Component is using Angular's Meta service to update a meta tag during ngOnInit. I'm using my RegionService to get an app-id and set it with Meta's updateTag method via a template literal. But my unit test is having problems getting the value set by my RegionService in the template literal. The test returns the following error:

Expected spy Meta.updateTag to have been called with:    [ Object({ name: 'apple-itunes-app', content: 'app-id=0123456789' }) ]  but actual calls were:    [ Object({ name: 'apple-itunes-app', content: 'app-id=undefined' }) ].  

How can I modify my test so that it knows the value of my template literal ${this.regionService.getAppId()} ?


my.component.ts

import { Component, OnInit } from '@angular/core';  import { RegionService } from 'src/services/region.service';  import { Meta } from '@angular/platform-browser';    export class MyComponent implements OnInit {      constructor(      private regionService: RegionService,      private meta: Meta    ) {      }        ngOnInit() {      this.meta.updateTag({name: 'apple-itunes-app', content: `app-id=${this.regionService.getAppId()}`});    }    }  

my.component.spec.ts

import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';  import { NO_ERRORS_SCHEMA } from '@angular/core';  import { MyComponent } from './my.component';  import { RegionService } from 'src/services/region.service';  import { Meta } from '@angular/platform-browser';  import { RouterTestingModule } from '@angular/router/testing';    describe('MyComponent', () => {    let component: MyComponent;    let fixture: ComponentFixture<MyComponent>;    let regionServiceSpy: jasmine.SpyObj<RegionService>;    let metaServiceSpy: jasmine.SpyObj<any>;      beforeEach(      waitForAsync(() => {        const regionServiceSpyObj = jasmine.createSpyObj('RegionService', ['getAppId', 'retrieveABCRegions', 'retrieveDEFRegions']);        const metaServiceSpyObj = jasmine.createSpyObj('Meta', ['updateTag']);          TestBed.configureTestingModule({          declarations: [MyComponent],          imports: [RouterTestingModule],          providers: [            { provide: RegionService, useValue: regionServiceSpyObj },            { provide: Meta, useValue: metaServiceSpyObj },          ],          schemas: [NO_ERRORS_SCHEMA],        }).compileComponents();        regionServiceSpy = TestBed.inject(RegionService) as jasmine.SpyObj<RegionService>;      metaServiceSpy = TestBed.inject(Meta) as jasmine.SpyObj<Meta>;      }),    );      beforeEach(() => {      fixture = TestBed.createComponent(MyComponent);      component = fixture.componentInstance;      fixture.detectChanges();    });        it('should set app-id to 0123456789 if selectedRegion is FR', () => {      // arrange        // act      regionServiceSpy.selectedRegion = 'FR';              // assert      expect(metaServiceSpy.updateTag).toHaveBeenCalledWith({name: 'apple-itunes-app', content: 'app-id=0123456789'});      });    });  

region.service.ts

import { retrieveABCRegions, retrieveDEFRegions} from 'src/regionCodes';    @Injectable({    providedIn: 'root',  })  export class RegionService {      selectedRegion: Region;      getAppId(): string {      if (retrieveABCRegions().includes(this.selectedRegion)) {        return '111111111';       } else if (retrieveDEFRegions().includes(this.selectedRegion)) {        return '0123456789';      } else {        return;      }    }  }  

how to change table cell text on hover and return it back

Posted: 07 Jul 2022 03:41 PM PDT

I have a table including a Courses ID's and I want when hover the cell change the Course id to course name.

how can I do this if I have lot of courses? I am using HTML / CSS / JS

GETTING SOME ERROR TO FETCH THE MODEL DETECTION finding solution for this asap

Posted: 07 Jul 2022 03:40 PM PDT

import python libraries      import cv2    #configure tenserflow cvfile       config_file = 'ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt'      frozen_model = 'frozen_inference_graph.pb'    image identification      img = cv2.imread('trash1.jpg')      plt.imshow(img)    getting error in this part      **ClassIndex, confidence, bbox = model.detect(img, confThreshold=0.5)**  

error: OpenCV(4.1.2) /io/opencv/modules/dnn/src/dnn.cpp:525: error: (-2:Unspecified error) Can't create layer "FeatureExtractor/MobilenetV3/Conv/BatchNorm/FusedBatchNormV3" of type "FusedBatchNormV3" in function 'getLayerInstance'

 font_scale = 3      font = cv2.FONT_HERSHEY_PLAIN      for ClassInd, conf, boxes in zip(ClassIndex.flatten(), confidence.flatten(), bbox):          cv2.rectangle(img, boxes, (255, 0, 0), 2)          cv2.putText(img, classlabels[ClassInd-1], (boxes[0]+10, boxes[1]+40), font, fontScale=font_scale, color=(0, 255, 0), thickness=3)    for real time garbage detection using webcam.      cap = cv2.VideoCapture("20170703_175807.mp4")              if not cap.isOpened():          cap = cv2.VideoCapture(0)      if not cap.isOpened():          raise IOError("Cannot Open Video")             font_scale = 3      font = cv2.FONT_HERSHEY_PLAIN              while True:          ret,frame = cap.read()                 **ClassIndex, confidece, bbox = model.detect(frame,confThreshold=0.55)**                 print(ClassIndex)      if (len(ClassIndex)!=0):          for ClassInd, conf, boxes in zip(ClassIndex.flatten(), confidece.flatten(), bbox):              if (ClassInd<=80):                  cv2.rectangle(frame,boxes,(255, 0, 0), 2)                  cv2.putText(frame,classLabels[ClassInd-1],(boxes[0]+10,boxes[1]+40), font,                   fontScale=font_scale,color=(0, 255, 0))              cv2.imshow('Object Detection Tutorial',frame)                                  if cv2.waitkey(2) & 0xFF == ord('q'):                  break                        cap.release()  cv2.destroyAllWindows()  

How to filter an aggregation based on the values of top hits?

Posted: 07 Jul 2022 03:40 PM PDT

The mapping of the elastic search documents are as follows:

{      "mappings": {          "properties": {              "vote_id": {                  "type": "keyword"              },              "user_id": {                  "type": "text"              },              "song_id": {                  "type": "text"              },              "type": {                  "type": "byte"              },              "timestamp": {                  "type": "date"              }          }      }  }  

I want to aggregate these votes such that it returns songs that you AND your friends like.

So far, I have buckets of songs that you and your friends like, but some buckets may be songs that only your friends like.

{      "query": {          "bool": {              "must": {                  %s              }          }      },      "aggs": {          "songs": {              "terms": {                  "field": "song_id"              },              "aggs": {                  "docs": {                      "top_hits": {                          "size": %d,                          "_source": %s                      }                  },                  "more_than_one": {                      "bucket_selector": {                          "buckets_path": {                              "count": "_count"                          },                          "script": "params.count > 1"                      }                  }              },                        }      }  }  

Always valid domain model and ubiquitous language

Posted: 07 Jul 2022 03:40 PM PDT

The principle of always valid domain model dictates that value object and entities should be self validating to never be in an invalid state.

This requires creating some kind of wrapper, sometimes, for primitive values. However it seem to me that this might break the ubiquitous language.

For instance say I have 2 entities: Hotel and House. Each of those entities has images associated with it which respect the following rules:

  • Hotels must have at least 5 images and no more than 20
  • Houses must have at least 1 image and no more than 10

This to me entails the following classes

class House {    HouseImages images;    // ...  }  class Hotel {    HotelImages images;  }    class HouseImage {    final List<Image> images;    HouseImage(this.images) : assert(images.length >= 1),                               assert(images.length <= 10);  }    class HotelImage {    final List<Image> images;    HotelImage(this.images) : assert(images.length >= 5),                               assert(images.length <= 20);  }  

Doesn't that break the ubiquitous languages a bit ? It just feels a bit off to have all those classes that are essentially prefixed (HotelName vs HouseName, HotelImages vs HouseImages, and so on).

Cuda Async MemCpy behavior when 'lapping' itself

Posted: 07 Jul 2022 03:39 PM PDT

Say you have a fairly typical sequence of async compute:

  1. Generate data on host, do other CPU stuff
  2. Put data in async stream to device (via pinned memory)
  3. compute data in (same) async stream

Now if you're running in a loop, the host will loop back to step 1 as 2&3 are non-blocking for the host.

The question is: "What happens for the host if it gets to step 2 again and the system isn't yet done transferring data to the device?"

  • Does the host MemCpyAsync block until the previous copy is complete?

  • Does it get launched like normal with the outbound data being put in a buffer?

If the latter, presumably this buffer can run out of space if your host is running too fast wrt the device operations?

I'm aware that modern devices have multiple copy engines, but I'm not sure if those would be useful for multiple copies on the same stream and to the same place.

I get that a system that ran into this wouldn't be a well designed one - asking as a point of knowledge.

This isn't something I have encountered in code yet - looking for any pointers to documentation on how this behavior is supposed to work. Already looked at the API page for the copy function and async behavior and didn't see anything I could recognize as relevant.

Adding Ocelot to web API breaks SignalR

Posted: 07 Jul 2022 03:39 PM PDT

I have a web API project where I use SignalR. Recently I added and configured Ocelot to be my gateway towards another web API. Ocelot routes the requests correctly but has messed up my SignalR configuration somehow.

Program.cs:

builder.Services.AddOcelot();       var app = builder.Build();    app.UseCors("AllowAllApps");    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();    app.UseAuthentication();  app.UseAuthorization();    app.UseMvc();  app.UseOcelot().Wait();    app.MapHub<MyHub>("/myHub");    app.Run();  

Client-side code:

// url = "http://localhost:5001/myHub"    connect(url: string, accessToken: string, debug: boolean): Promise<void> {    this.connection = new signalR.HubConnectionBuilder()      .withUrl(url, { accessTokenFactory: () => accessToken })      .configureLogging(debug ? signalR.LogLevel.Information : signalR.LogLevel.Error)      .withAutomaticReconnect()      .build();      return this.connection.start();  }  

Ocelot.json

{    "Routes": [      {        "DownstreamPathTemplate": "/{route}",        "DownstreamScheme": "http",        "DownstreamHostAndPorts": [          {            "Host": "myotherapi",            "Port": 80          }        ],        "UpstreamPathTemplate": "/myotherapi/{route}",        "UpstreamHttpMethod": [ "Post" ],        "AuthenticationOptions": {          "AuthenticationProviderKey": "Bearer",          "AllowedScopes": []        },        "AddHeadersToRequest": {          "UserId": "Claims[sub] > value"        }      }    ],    "GlobalConfiguration": {      "BaseUrl": "http://localhost:5001"    }  }  

I need Ocelot only for HTTP requests. It shouldn't affect websocket connections with this configuration as far as I understand.

If I comment out the Ocelot lines in my Program.cs SignalR works. If I leave it there my POST request to http://localhost:5001/myHub/negotiate?negotiateVersion=1 fails with 404.

Is it something to do with the order of the middleware that is causing the issue? I have tried multiple different orderings but to no avail.

This is a .NET 6 project with Ocelot version 18.0. Both projects are containerized with Docker.

Error in using InputPath to select parts of input in a Step Functions workflow

Posted: 07 Jul 2022 03:39 PM PDT

I am creating a Step Functions workflow which has various steps. I am referring to this topic in their documentation [InputPath, ResultPath and OutputPath Examples][1]. I am trying to check the identity and address of a person in my workflow as they've shown in their document. I'm passing the input for this step within the state machine definition inside Parameters. My workflow looks like this.

Note: But when I run this, am getting the error -> An error occurred while executing the state 'Verify identity' (entered at the event id #19). Invalid path '$.identity' : Property ['identity'] not found in path $

What am I doing wrong here? Can someone please explain?

  "Comment": "A description of my state machine",    "StartAt": "Step1",    "States": {      "Step1": {        "Type": "Task",        "Resource": "arn:aws:states:::lambda:invoke",        "OutputPath": "$.Payload",        "Parameters": {          "FunctionName": "{Lambda ARN}"        },        "Retry": [          {            "ErrorEquals": [              "Lambda.ServiceException",              "Lambda.AWSLambdaException",              "Lambda.SdkClientException"            ],            "IntervalSeconds": 2,            "MaxAttempts": 2,            "BackoffRate": 2          }        ],        "Next": "Step2"      },      "Step2": {        "Type": "Choice",        "Choices": [          Do something...        ],        "Default": "Step3.1"      },      "Step3.1": {        "Type": "Task",        "Resource": "arn:aws:states:::sns:publish.waitForTaskToken",        "Parameters": {          "TopicArn": "{SNS ARN}",          "Message": {            "TaskToken.$": "$$.Task.Token"          }        },        "Next": "Step3.3"      },      "Step 3.2": {        "Type": "Pass",        "Next": "Step4",        "OutputPath": "$"      },      "Step3.3": {        "Type": "Pass",        "Next": "Step4"      },      "Step4": {        "Type": "Parallel",        "Branches": [          {            "StartAt": "Verify identity",            "States": {              "Verify identity": {                "Type": "Task",                "Resource": "arn:aws:states:::lambda:invoke",                "InputPath": "$.identity",                "Parameters": {                  "Payload": {                    "identity": {                      "email": "jdoe@example.com",                      "ssn": "123-45-6789"                    },                    "firstName": "Jane",                    "lastName": "Doe"                  },                  "FunctionName": "{Lambda ARN}"                },                "Retry": [                  {                    "ErrorEquals": [                      "Lambda.ServiceException",                      "Lambda.AWSLambdaException",                      "Lambda.SdkClientException"                    ],                    "IntervalSeconds": 2,                    "MaxAttempts": 2,                    "BackoffRate": 2                  }                ],                "End": true              }            }          },          {            "StartAt": "Verify address",            "States": {              "Verify address": {                "Type": "Task",                "Resource": "arn:aws:states:::lambda:invoke",                "Parameters": {                  "Payload": {                    "street": "123 Main St",                    "city": "Columbus",                    "state": "OH",                    "zip": "43219"                  },                  "FunctionName": "{Lambda ARN}"                },                "Retry": [                  {                    "ErrorEquals": [                      "Lambda.ServiceException",                      "Lambda.AWSLambdaException",                      "Lambda.SdkClientException"                    ],                    "IntervalSeconds": 2,                    "MaxAttempts": 2,                    "BackoffRate": 2                  }                ],                "End": true              }            }          }        ],        "Next": "Step5"      },      "Step5": {        "Type": "Task",        "Parameters": {          something...        },        "End": true        }  }```            [1]: https://docs.aws.amazon.com/step-functions/latest/dg/input-output-example.html  

Jenkins pipeline with multiple triggers not triggering correctly

Posted: 07 Jul 2022 03:38 PM PDT

I have a jenkins pipleine which has two triggers one for pollSCM and the other is a cron job to run every Tuesday and Thursday at 6 pm EST. I configured it as follows

triggers {          pollSCM('H/5 * * * *')          cron('00 18 * * 2,4')      }  

I followed the document here to set up the trigger. The pollSCM trigger works correctly. But the cron trigger, instead of triggering the build at 6 pm EST. Its trigerring at 2 pm EST. Why is this happening?

Jenkins image

How to access response object from mode task in chainlink job?

Posted: 07 Jul 2022 03:38 PM PDT

Im trying to access the response object of the mode task in a chainlink job.

The response: { "results": [ 2, "foo" ], "occurrences": 3 }

If I tried to get the first index of "results", but the job allways failed.

I tried two differnt solutions:

  1. With json parse mode
schemaVersion = 1  name = "xxxxxxx"  contractAddress = "0x..."  maxTaskDuration = "0s"  observationSource = """      decode_log   [type=ethabidecodelog                    abi="OracleRequest(bytes32 indexed specId, address requester, bytes32 requestId, uint256 payment, address callbackAddr, bytes4 callbackFunctionId, uint256 cancelExpiration, uint256 dataVersion, bytes data)"                    data="$(jobRun.logData)"                    topics="$(jobRun.logTopics)"]        decode_cbor  [type=cborparse data="$(decode_log.data)"]      fetch_1        [type=bridge name="bridgeTwo" requestData="{\\"id\\": $(jobSpec.externalJobID), \\"data\\": { \\"txh\\": $(decode_cbor.txh)}}"]      parse_1        [type=jsonparse path="result" data="$(fetch_1)"]      fetch_2        [type=bridge name="Test1" requestData="{\\"id\\": $(jobSpec.externalJobID), \\"data\\": { \\"txh\\": $(decode_cbor.txh)}}"]      parse_2        [type=jsonparse path="result" data="$(fetch_2)"]      fetch_3        [type=bridge name="Test2" requestData="{\\"id\\": $(jobSpec.externalJobID), \\"data\\": { \\"txh\\": $(decode_cbor.txh)}}"]      parse_3        [type=jsonparse path="result" data="$(fetch_3)"]      fetch_4        [type=bridge name="Test3" requestData="{\\"id\\": $(jobSpec.externalJobID), \\"data\\": { \\"txh\\": $(decode_cbor.txh)}}"]      parse_4        [type=jsonparse path="result" data="$(fetch_4)"]      fetch_5        [type=bridge name="Test4" requestData="{\\"id\\": $(jobSpec.externalJobID), \\"data\\": { \\"txh\\": $(decode_cbor.txh)}}"]      parse_5        [type=jsonparse path="result" data="$(fetch_5)"]      my_median_task [type="mode"                  values=<[ $(parse_1), $(parse_2), $(parse_3), $(parse_4), $(parse_5) ]>                  allowedFaults=2]      parse_mode   [type=jsonparse path="result,0" data="$(my_median_task)"]      encode_data  [type=ethabiencode                   abi="(bytes value)"                   data="{ \\"value\\": $(parse_mode) }"]      encode_tx    [type=ethabiencode                    abi="fulfillOracleRequest(bytes32 requestId, uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 expiration, bytes calldata data)"                    data="{\\"requestId\\": $(decode_log.requestId), \\"payment\\": $(decode_log.payment), \\"callbackAddress\\": $(decode_log.callbackAddr), \\"callbackFunctionId\\": $(decode_log.callbackFunctionId), \\"expiration\\": $(decode_log.cancelExpiration), \\"data\\": $(encode_data)}"                   ]      submit_tx    [type=ethtx to="0x327A92FBb7D7c96D349B4207603B910d3c40c9F5" data="$(encode_tx)"]        decode_log -> decode_cbor -> fetch_1 -> parse_1 -> fetch_2 -> parse_2 -> fetch_3 -> parse_3 -> fetch_4 -> parse_4 -> fetch_5 -> parse_5 -> my_median_task -> encode_data -> encode_tx -> submit_tx  """  externalJobID = "ab58325c-1d12-4360-a15d-c656eca27dc0"  
  1. without json parse
schemaVersion = 1  name = "xxx"  contractAddress = "0x...."  maxTaskDuration = "0s"  observationSource = """      decode_log   [type=ethabidecodelog                    abi="OracleRequest(bytes32 indexed specId, address requester, bytes32 requestId, uint256 payment, address callbackAddr, bytes4 callbackFunctionId, uint256 cancelExpiration, uint256 dataVersion, bytes data)"                    data="$(jobRun.logData)"                    topics="$(jobRun.logTopics)"]        decode_cbor  [type=cborparse data="$(decode_log.data)"]      fetch_1        [type=bridge name="bridgeTwo" requestData="{\\"id\\": $(jobSpec.externalJobID), \\"data\\": { \\"txh\\": $(decode_cbor.txh)}}"]      parse_1        [type=jsonparse path="result" data="$(fetch_1)"]      fetch_2        [type=bridge name="Test1" requestData="{\\"id\\": $(jobSpec.externalJobID), \\"data\\": { \\"txh\\": $(decode_cbor.txh)}}"]      parse_2        [type=jsonparse path="result" data="$(fetch_2)"]      fetch_3        [type=bridge name="Test2" requestData="{\\"id\\": $(jobSpec.externalJobID), \\"data\\": { \\"txh\\": $(decode_cbor.txh)}}"]      parse_3        [type=jsonparse path="result" data="$(fetch_3)"]      fetch_4        [type=bridge name="Test3" requestData="{\\"id\\": $(jobSpec.externalJobID), \\"data\\": { \\"txh\\": $(decode_cbor.txh)}}"]      parse_4        [type=jsonparse path="result" data="$(fetch_4)"]      fetch_5        [type=bridge name="Test4" requestData="{\\"id\\": $(jobSpec.externalJobID), \\"data\\": { \\"txh\\": $(decode_cbor.txh)}}"]      parse_5        [type=jsonparse path="result" data="$(fetch_5)"]      my_median_task [type="mode"                  values=<[ $(parse_1), $(parse_2), $(parse_3), $(parse_4), $(parse_5) ]>                  allowedFaults=2]      parse_mode   [type=jsonparse path="my_median_task,result,0" data="$(my_median_task)"]      encode_data  [type=ethabiencode                   abi="(bytes value)"                   data="{ \\"value\\": $(result,0) }"]      encode_tx    [type=ethabiencode                    abi="fulfillOracleRequest(bytes32 requestId, uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 expiration, bytes calldata data)"                    data="{\\"requestId\\": $(decode_log.requestId), \\"payment\\": $(decode_log.payment), \\"callbackAddress\\": $(decode_log.callbackAddr), \\"callbackFunctionId\\": $(decode_log.callbackFunctionId), \\"expiration\\": $(decode_log.cancelExpiration), \\"data\\": $(encode_data)}"                   ]      submit_tx    [type=ethtx to="0x327A92FBb7D7c96D349B4207603B910d3c40c9F5" data="$(encode_tx)"]        decode_log -> decode_cbor -> fetch_1 -> parse_1 -> fetch_2 -> parse_2 -> fetch_3 -> parse_3 -> fetch_4 -> parse_4 -> fetch_5 -> parse_5 -> my_median_task -> encode_data -> encode_tx -> submit_tx  """  externalJobID = "ab58325c-1d12-4360-a15d-c656eca27dc0"   

How I'll be able to get the result of the mode task?

This is the link to the Chainlink docs of the mode task: https://docs.chain.link/docs/jobs/task-types/mode/

Regex for matching Italian accented letters working in browser console but not in my code

Posted: 07 Jul 2022 03:42 PM PDT

I have created this regex /[:'\/\\^~\sèéàùìò]/gi for matching some special characters as well as Italian accented letters. It is working in the browser console but not in the code and can't figure it out why.

console result

When written in my program gives false here's the code snippet:

if(new RegExp(/[:'\/\\^~\sèéàùìò]/gi).test(folderNewName)){              showErrorAlertMsg('Presenti caratteri non consentiti')//showing custom alert              $('#smGlobalFolders').jstree(true).refresh();              return          }   

where folderNewName is a String.

debug code debug result

note line 1502 in the console in the last image giving false. I'm using Chrome 103.0.5060.114 to debug this. Any help would be great, also if you have suggestions on how to make this regex better, would be nice. Thanks, everyone.

Create views by joining 3 tables

Posted: 07 Jul 2022 03:41 PM PDT

I'm creating SQL views join of 3 tables, orders,products,purchases by below code.

 CREATE VIEW full_inventory_details   AS   SELECT orders.*,   products.ProductName,products.PartNumber,products.ProductLabel,products.StartingInventory,   products.InventoryReceived,products.InventoryShipped,products.InventoryOnHand,products.MinimumRequired,purchases.id   FROM(( orders INNER JOIN products ON orders.ProductId=products.id)   INNER JOIN purchases ON orders.ProductId=purchases.ProductId);  

Everything looks good, still not getting anything updated. I'm not getting new views. Kindly looking for help. Thanks.

SQLAlchemy many to may relationships, how to properly set up?

Posted: 07 Jul 2022 03:41 PM PDT

The documentation naturally is too vague to be any help. I have an app with users, applications, and sections.

Users can have any number of applications associated with them. Users can have sections associated with them, but each section is unique to that user.

So essentially im trying to create a model for this: each user can have a number of named sections, each with apps.

I cant seem to figure out how this is setup in SQLAlchemy.

For users, I have:

class User(UserMixin, db.Model):      id = db.Column(db.Integer, primary_key=True)      name = db.Column(db.String(40), nullable=False)      username = db.Column(db.String(20), nullable=False, unique=True)      password = db.Column(db.String(90), nullable=False)    class Application(db.Model):      id = db.Column(db.Integer, primary_key=True)      name = db.Column(db.String(40), nullable=False)      users = db.relationship(          'User',          secondary='user_app'      )    user_app = db.Table(      'user_app',      db.Column(          'user_id',          db.Integer,          db.ForeignKey('user.id'),          primary_key=True      ),      db.Column(          'application_id',          db.Integer,          db.ForeignKey('application.id'),          primary_key=True      ),      db.Column(          'last_used_time',          db.DateTime,          nullable=True      )  )  

And in the code, I can do:

app = Application.query.filter_by(id=app_id).first()  app.users.append(user)  db.session.add(app)  db.session.commit()  

which will properly associate.

But I cannot seem to wrap my head around how to handle integrating sections, users, and applications altogther. It seems way easier to just create another table, but according to the poorly written docs, I should use relationship tables.

Can someone give me some advice?

Difference of code result using step by step vs and running normally Python

Posted: 07 Jul 2022 03:40 PM PDT

Hello I try to get some data from a web page with selenium. But some weird things happen that I doesn't understand. When I run my programm step by step it works but running normaly it doesn't. I haven't seen any post related on python or selenium on the internet. Here is my code :

import undetected_chromedriver as uc  from selenium.webdriver.common.keys import Keys  from selenium.webdriver.common.by import By      if __name__ == '__main__':      L=[]      PATH="C:\Program Files (x86)\chromedriver.exe"        options=uc.ChromeOptions()      pref={"download.default_directory" : r"C:\Users\Dimitri\Documents\Programme C++\clis\extraction+sql\ressources"}      options.add_experimental_option("prefs",pref)      options.headless=True      driver=uc.Chrome(excutable_path=PATH,options=options)      driver.get("https://framagenda.org/login?redirect_url=/apps/calendar/dayGridMonth/now")      user = driver.find_element("id","user")      user.send_keys("user@gmail.com")      mdp=driver.find_element("id","password")      mdp.send_keys("test123")      mdp.send_keys(Keys.RETURN)      print(driver.title)                        list=driver.find_elements(By.CLASS_NAME,"app-navigation-entry__title")      for l in list:          L.append(l.text)          print(L)          for l in L:          driver.get("https://framagenda.org/remote.php/dav/calendars/Dimitri%20L./"+l.lower()+"/?export")  

Note that i doesn't understand the first if of the problem i put it here for fixing an error that i've seen on this forum

When the code is running normally the line :" list=driver.find_elements(By.CLASS_NAME,"app-navigation-entry__title")" seems not to be executed Have you any idea of what's going wrong ?

Thank you for your help

CHAI - See if two objects are the same where one attribute has a different order

Posted: 07 Jul 2022 03:38 PM PDT

I have two object arrays:

array1 = [     { name: 'Kitty, Hello',      otherNames: [ '(1) One', '(2) Two' ]     },    { name: 'Cat, Garfield',      otherNames: [ '(3) Three' ]     }   ];    array2 = [     { name: 'Kitty, Hello',      otherNames: [ '(2) Two', '(1) One' ]     },    { name: 'Cat, Garfield',       otherNames: [ '(3) Three' ]      }   ]

I am trying to use chai to see if they are equal, despite the order of otherNmaes for the first object in array1.

I have tried

array1.to.be.eql(array2) //false array1.to.have.deep.members(array2) //false

But it keeps returning false. Is this even possible? I have tried looking at similar questions, but I could only find questions where "name" and "otherNames" were in different order.

Creating new column in a Pandas df, where each row's value depends on the value of a different column in the row immediately above it

Posted: 07 Jul 2022 03:39 PM PDT

Assume the following Pandas df:

# Import dependency.  import pandas as pd    # Create data for df.  data = {'Value': [1000, 1020, 1011, 1010, 1030, 950, 1001, 1100, 1121, 1131],          'Dummy_Variable': [0,0,1,0,0,0,1,0,1,1]         }    # Create DataFrame  df = pd.DataFrame(data)  display(df)  

I want to add a new column to the df called 'Placeholder.' The value of Placeholder would be based on the 'Dummy_Variable' column based on the following rules:

  • If all previous rows had a 'Dummy_Variable' value of 0, then the 'Placeholder' value for that row would be equal to the 'Value' for that row.
  • If the 'Dummy_Variable' value for a row equals 1, then the 'Placeholder' value for that row would be equal to the 'Value' for that row.
  • If the 'Dummy_Variable' value for a row equals 0 but the 'Placeholder' value for the row immediately above it is >0, then the 'Placeholder' value for the row would be equal to the 'Placeholder' value for the row immediately above it.

The desired result is a df with new 'Placeholder' column that looks like the df generated by running the code below:

desired_data = {'Value': [1000, 1020, 1011, 1010, 1030, 950, 1001, 1100, 1121, 1131],          'Dummy_Variable': [0,0,1,0,0,0,1,0,1,1],          'Placeholder': [1000,1020,1011,1011,1011,1011,1001,1001,1121,1131]}    df1 = pd.DataFrame(desired_data)  display(df1)  

I can do this easily in Excel, but I cannot figure out how to do it in Pandas without using a loop. Any help is greatly appreciated. Thanks!

Transmit data to an adress stm32CubeIde

Posted: 07 Jul 2022 03:41 PM PDT

I am newly working on Stm32CubeIde and I am trying to understand how it works. I would like to transmit data to a specific address using the UART port and I don't know how to do it. So far I have been able to transmit using these three methods:

using the poll —> HAL_UART_Transmit

using the interrupt —> HAL_UART_Transmit_IT

using DMA —> HAL_UART_Transmit_DMA

but none of them in their implementation refer to transmitting to a specific address. Can someone help me ?

How to change name of columns if it contains specific text

Posted: 07 Jul 2022 03:41 PM PDT

How do I go about changing the text in columns? for e.g instead of MAC000306_Std_E_Affluent, it'll be affluent. I would like to change all the names to the last name. So ideally I'd end up with columns printing Affluent, Comfortable, enter image description hereand Adversity.

how could I create an array of the last marked value from an index array

Posted: 07 Jul 2022 03:40 PM PDT

I'm kind of new to python and not really used to a lot of the syntax yet. I would like to know how to get an array of the last value that has been marked as a 1 from an index array. For example for

idx = [1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1]    values = [23, 45, 78, 37, 15, 172, 45, 8, 16, 99, 55]  

The desired array would look like

[23, 23, 23, 37, 37, 37, 37, 8, 16, 16, 55]  

The sample code I'm working with uses xarray to create the index array, so maybe it could also be used to get the final array. Thanks for any help or suggestions

Edit: the length of both arrays will be the same, and if the index array starts with a 0, the output should be 0 until there is a 1 in the idx array

Extract part of the strings with specific format

Posted: 07 Jul 2022 03:41 PM PDT

I am currently trying to crack the seemingly simple problem in R but somehow I am unable to find a way to do it with gsub, str_match() or some other rgex-related functions. Can anyone please help me crack this problem?

Problem Assuming that I have a column vector of certain length (say, 100). Each element in a vector has the form of [string]_[string+number]_[someinfo]. Now, I want to extract only the very first part of each element, namely the [string]_[string+number]. The potential upper bound on the number of characters in [string]_[string+number], not including _, could be anywhere between 8 and 20, but there is no fixed length. How can I use some types of rgex expression to do this in R?

x = c('XY_ABCD101_12_ACE', 'XZ_ACC122_100_BAN', 'XT_AAEEE100_12345_ABC', 'XKY_BBAAUUU124_100')  

Desired output.

x1 = c('XY_ABCD101', 'XZ_ACC122', 'XT_AAEEE100', 'XKY_BBAAUUU124')  

Why is this causing a connection reset?

Posted: 07 Jul 2022 03:41 PM PDT

I'm experimenting with a simple HTTP server here in Kotlin in order to try and reproduce a more complex problem where content seems to get cut off if it's one byte above a certain number which causes a net::ERR_CONTENT_LENGTH_MISMATCH 200 (OK) error in browsers.

That number depends whether it's deployed locally or on AWS or running in IntelliJ.

In the following example, I start a simple blocking HTTP server which prints out 50,000 hashes in the browser without any problems.

fun main() {        val len = 50_000        val server =          AsynchronousServerSocketChannel.open().bind(InetSocketAddress(5555))        while (true) {          val channel = server.accept().get()          channel.use {              val data = """              HTTP/1.1 200 OK              server: Cloud Auctioneers              content-type: text/plain              content-length: $len                ${"#".repeat(len)}          """.trimIndent()              it.write(ByteBuffer.wrap(data.toByteArray()))          }      }  }  

enter image description here

Now when I increase that 50_000 to 150_000, I run into a net::ERR_CONNECTION_RESET

enter image description here

If I put a Thread.sleep in there at the end of the use { } (or similarly, converting the whole thing to coroutines and putting a delay in there), then it renders the number of elements correctly without the net::ERR_CONNECTION_RESET

fun main() {        val len = 250_000        val server =          AsynchronousServerSocketChannel.open().bind(InetSocketAddress(5555))        while (true) {          val channel = server.accept().get()          channel.use {              val data = """              HTTP/1.1 200 OK              server: Cloud Auctioneers              content-type: text/plain              content-length: $len                ${"#".repeat(len)}          """.trimIndent()              it.write(ByteBuffer.wrap(data.toByteArray()))                Thread.sleep(1_000)            }      }  }  

enter image description here

I thought that maybe a CompletionHandler will give me a guarantee that writing is done before closing the channel, ...

fun main() {        val len = 250_000        val server =          AsynchronousServerSocketChannel.open().bind(InetSocketAddress(5555))        while (true) {          val channel = server.accept().get()          try {              val data = """              HTTP/1.1 200 OK              server: Cloud Auctioneers              content-type: text/plain              content-length: $len                ${"#".repeat(len)}          """.trimIndent()              channel.write(ByteBuffer.wrap(data.toByteArray()), 10L, TimeUnit.SECONDS, null, object : CompletionHandler<Int?, String?> {                  override fun completed(result: Int?, attachment: String?) {                      channel.close()                  }                  override fun failed(exc: Throwable?, attachment: String?) {                      channel.close()                  }              })            } catch (e: Throwable) {              e.printStackTrace()          }      }  }  

... but this doesn't seem to be the case, without the timer in the CompletionHandler callbacks, I'm still getting net::ERR_CONNECTION_RESET 200 (OK)

What or when is the correct way / time to handle the closing of the AsynchronousServerSocketChannel?

The documentation mentions calling channel.shutdownOutput() and I'm assuming channel.shutdownInput() should be called too, but does this actually close the channel completely?

How to allow HTTP webServiceURL in apple wallet's pass.json file

Posted: 07 Jul 2022 03:41 PM PDT

I'm creating a web service for automatic updates to a pass, just for testing purposes. According to apple's documentation: "Your web service must use an HTTPS connection for production, but you can use an HTTP connection during testing." However, it seems that I can't actually use HTTP for testing because if I put webServiceURL in pass.json as http, the pkpass file cannot open. Is there a way to force allow an HTTP webServiceURL in pass.json?

*Note: if I change my web service to https with an SSL certificate, the pass downloads, but I don't get any post requests from Apple's service to my endpoint to register the pass. I could be doing this wrong but I'm not familiar enough with the https process (or how apple actually calls my endpoint) to know how to fix it. I can post more details about this if that would be a better approach.

Any help would be greatly appreciated!

Google Drive API - application/vnd.google-apps.spreadsheet

Posted: 07 Jul 2022 03:40 PM PDT

Does the Google Drive API mime type application/vnd.google-apps.spreadsheet still work? I am using Freshservice's Workflow Automator paired with the Google Drive API to create a file in Google Drive. When using the mime type of application/vnd.google-apps.spreadsheet, the file does not get created. When using the mime type of application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, I am able to create the document with the API.

Was there an update to the mime types that no longer allows application/vnd.google-apps.spreadsheet?

Convert string to 2 decimal Number in 1 line

Posted: 07 Jul 2022 03:41 PM PDT

I have a string 123.4567 that I want to convert to a Number with two decimals and I want to do this in 1 short line in Javascript.

const x = "123.4567";    // this works but seems way too cumbersome  const y = parseFloat((parseFloat(x)).toFixed(2))  console.log(typeof(y) + " / " + y)      //Prints: number / 123.45    // this I expected to work but it doesn't  const z = (parseFloat(x)).toFixed(2)  console.log(typeof(z) + " / " + z)      //Prints: string / 123.45

pkpass not downloading on physical iOS device

Posted: 07 Jul 2022 03:38 PM PDT

Background: I'm learning Apple Wallet by creating a barebones sample app and am trying to automatically update a pass. In order to do so, I understand I need to run a web server that sends push notifications to the device when it's time for the pass to update. I'm using Apple's sample code and running their Ruby webserver via localhost. It correctly generates a .pkpass file, which I can add to Apple Wallet in the simulator by visiting the localhost site or by dragging in the .pkpass file.

Problem: This process doesn't work on my physical iPhone. When I go to the localhost on my iPhone, it shows a 200 response code but comes with the popup "Safari cannot download this file." Even if I try just emailing the generated .pkpass file to myself, it won't open in Wallet.

HCW - hybrid configuration wizard modern - InternalUrl_Duplicate

Posted: 07 Jul 2022 03:39 PM PDT

Unable to get through the Hybrid Configuration Wizard in Modern mode. This is necessary because we want to migrate mailboxes. Classic mode works.

It knows that there is a Hybrid Agent, but I can't successfully install with either path of using existing or adding a new one. In Azure there is an App Proxy registration which appears to have the incorrect IP for the route to on-prem. This was due to a misconfiguration of our outgoing firewall. However after the firewall configuration was fixed, the App Proxy still has the old return IP, and there is no way in Azure to remove this record.

I've removed the app proxy components on the server, and let the HCW install again but this record is not updated or removed. Also have gone through 'Classic' path which according to community posts is supposed to remove the App Proxy record, but it doesn't.

According to what I've read, if the record is inactive for 10 days, it will be removed, but I'd rather resolve this without waiting for 10 days.

I've tried patching the record using Graph but it doesn't work.

enter image description here

2022.01.31 22:09:59.707 10333 [Client=UX, fn=SendAsync, Thread=15] FINISH Time=2170.2ms Results=BadRequest {"error":{"code":"InternalUrl_Duplicate","message":"Internal url 'https://LOCALFQDNSERVER/' is invalid since it is already in use","innerError":{"date":"2022-01-31T22:09:58","request-id":"d5c4dfe0-096d-4382-9da0-9559f45e0217","client-request-id":"d5c4dfe0-096d-4382-9da0-9559f45e0217"}}}

Python SMTP function sending .txt file as .bin file-type

Posted: 07 Jul 2022 03:39 PM PDT

When calling the below SMTP function, the message is sent to my mailbox, but the log file is attached as .bin file-type. When opened, the .bin file reads as it would if it were a .txt file-type, but I cannot open .bin files on my mobile device, which is a huge problem for me. Is there any way to attach this file to the message using its original file-type? Any feedback is very much appreciated.

Edit: The file is sent with its original file-type (.txt) when I run this from a Windows machine, but the file-type is mishandled when I run it from a Linux machine. I have tested this with both Outlook (preferred) and Gmail. Outlook recognizes the file as .bin file-type while Gmail does not recognize a file-type at all.

from pathlib import Path  data_folder = Path("path/to/working/directory")  log_file = Path(data_folder / "log.txt")    def sendmail():        maildate = str(datetime.now().strftime("%m" + "/" + "%d" + "/" + "%Y"))      subjectdate = str("Subject - " + maildate)            import smtplib      from email.mime.base import MIMEBase      from email.mime.multipart import MIMEMultipart      from email import encoders        msg = MIMEMultipart()      msg['Subject'] = subjectdate      msg['From'] = 'from@from.com'      msg['To'] = 'to@to.com'        attachment = MIMEBase('application', "octet-stream")      attachment.set_payload(open(log_file, "r").read())      encoders.encode_base64(attachment)      attachment.add_header('Content-Disposition', 'attachment, filename=log_file')        msg.attach(attachment)        s = smtplib.SMTP('sender@sender.com')      s.send_message(msg)      s.quit()  

How do i stop drag select on wpf data grid

Posted: 07 Jul 2022 03:42 PM PDT

Hi all this might sound trivial but I want to stop drag select on WPF DataGrid

I have a simple grid like

<DataGrid ItemsSource="{Binding Items}" SelectionMode="Extended">              <DataGrid.Columns>                  <DataGridTextColumn Binding="{Binding .}"/>              </DataGrid.Columns>  </DataGrid>  

how can I stop multiple selection on click drag but and have multiple selection by Shift and Ctrl.

thanks

No comments:

Post a Comment