Tuesday, July 20, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


media preview for ios swift

Posted: 20 Jul 2021 08:16 AM PDT

i want to preview media directly from url for example if i give it video display video preview if i give it image show it if i give it pdf show file preview and when press on it show the file content and so on

our media will be (images, videos, audios, pdfs, xlsx, docx)

so please if you have any information about aby framework or plugin please five me details

i have trying LPLinkView but it is showing metadata i dont want to show it but there is no options to hide metadata view

so please if you have any idea for that tell me please

looking forward for your help guys

thanks

Quarkus native get the value of an annotation

Posted: 20 Jul 2021 08:16 AM PDT

I am trying to acces the value inside of an annotation when I compile my code to quarkus native using the command ./mvnw package -Pnative. I am trying to use Cucumber cli to execute to execute my code like this: Main.run("-g", "com.hellocucumber", "file:/hellocucumber.feature"). I have made some modifications to the source code to get it to work with Quarkus native compilation. My main problem is that there's this block of code Method expressionMethod = annotation.getClass().getMethod("value"); inside of the io.cucumber.java.GlueAdaptor which fails with the error java.lang.IllegalStateException: java.lang.NoSuchMethodException: io.cucumber.java.en.Given$$ProxyImpl.value() because we are trying to access the value of the annotation defined in the StepDefinition class. Here is my step definition class, as well as my feature file.

public class StepDefinitions {      @Given("today is Sunday")      public void today_is_Sunday() {          //Print a message      }        @When("I ask whether it's Friday yet")      public void i_ask_whether_it_s_Friday_yet() {          //Print a message      }            @Then("I should be told {string}")      public void i_should_be_told(String expectedAnswer) {          //Print a message      }      }    Scenario: Sunday isn't Friday      Given today is Sunday      When I ask whether it's Friday yet      Then I should be told Nope  

I have tried to add the annotation classes (io.cucumber.java.en.Given, io.cucumber.java.en.And, etc) to the reflect.json and provide it to the native compilation as follows: quarkus.native.additional-build-args=-H:DynamicProxyConfigurationResources=reflect-config.json, this doesn't seem to work. I have also moved all the code I modified into an extension and tried to modify the annotations like this:

@BuildStep      void addProxies(CombinedIndexBuildItem combinedIndexBuildItem,                      BuildProducer<NativeImageProxyDefinitionBuildItem> proxies) {          proxies.produce(new NativeImageProxyDefinitionBuildItem(StepDefinitionAnnotation.class.getName()));          proxies.produce(new NativeImageProxyDefinitionBuildItem(Given.class.getName()));          proxies.produce(new NativeImageProxyDefinitionBuildItem(When.class.getName()));          proxies.produce(new NativeImageProxyDefinitionBuildItem(Then.class.getName()));          proxies.produce(new NativeImageProxyDefinitionBuildItem(And.class.getName()));          proxies.produce(new NativeImageProxyDefinitionBuildItem(But.class.getName()));      }  

This didn't work either, so finally I tried this:

@BuildStep  void transformAnnotations(BuildProducer<AnnotationsTransformerBuildItem> transformers) {          transformers.produce(new AnnotationsTransformerBuildItem(new AnnotationsTransformer() {          @Override          public boolean appliesTo(AnnotationTarget.Kind kind) {              return kind == AnnotationTarget.Kind.METHOD;          }            @Override          public void transform(TransformationContext ctx) {              AnnotationTarget target = ctx.getTarget();              MethodInfo methodInfo = target.asMethod();              ClassInfo classInfo = methodInfo.declaringClass();                AnnotationInstance annotation = methodInfo.annotation(GIVEN_ANNOTATION);              if (annotation == null) {                  return;              }               ctx.transform()                      .add(create(                              CDI_NAMED_ANNOTATION,                              annotation.target(),                              List.of(AnnotationValue.createStringValue("value", annotation.value().toString()))))                      .done();          }      }));  }  

This didn't work either. When I try to print out the method annotations, I only see the annotation class name, no values. When i execute this block of code:

Method[] method = StepDefinitions.class.getMethods();      for (int j = 0; j < method.length; j++) {          LOGGER.info("Method annotations: {}", method[j].getAnnotations().length);          Annotation[] annos = method[j].getAnnotations();          for (int i = 0; i < annos.length; i++) {              LOGGER.info("Annotation: {}", annos[i]);          }      }  

In quarkus dev mode, it prints:

  • Method annotations: 1
  • Annotation: @io.cucumber.java.en.Given(value="today is Sunday")

In quarkus native it prints this:

  • Method annotations: 1
  • Annotation: @io.cucumber.java.en.Given

At this point I have run out ideas on what to try, I am new to the quarkus ecosystem and I'm not sure if this is the right path to take or if there are better alternatives, I am open to any and all suggestions.

Can't "extern reference" C++ "anonymous namespace" variables from C

Posted: 20 Jul 2021 08:16 AM PDT

I was trying to do something like..

extern int _ZN12_GLOBAL__N_19numApplesE;  struct apple_t  {  };  extern apple_t* _ZN12_GLOBAL__N_16applesE;  

.. (i.e. for testing if code in a library is exploitable).

The test(s) I wrote in C (and the library in C++), but the compiler (gcc) outputs the errors..

c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: test_apples.o:test_apples.c:(.rdata$.refptr._ZN12_GLOBAL__N_16applesE[.refptr._ZN12_GLOBAL__N_16applesE]+0x0): undefined reference to `(anonymous namespace)::apples'  

c:/programdata/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: test_apples.o:test_apples.c:(.rdata$.refptr._ZN12_GLOBAL__N_19numApplesE[.refptr._ZN12_GLOBAL__N_19numApplesE]+0x0): undefined reference to `(anonymous namespace)::numApples'

I wonder how this is not possible (i.e. is this a manual check in gcc that prevents variables with this "naming scheme" from being linked..?).

matrix : process exited with code 139 interrupted with signal 11: SEGSEGV

Posted: 20 Jul 2021 08:15 AM PDT

I have a project for my collage, work with matrix.

I want to test the program so enter a 2*2 matrix, choose option 1('+') and the program close !!

the '+' operation works perfect but problem is '=' operation

when the program wants to save the result by '=' operation the Error occurs .

process exited with code 139 interrupted with signal 11: SEGSEGV

class Matrix  {  public:      Matrix(int x, int y);        void input();        void print();        Matrix operator=(const Matrix* m);        Matrix *operator+(const Matrix m);        Matrix *operator-(const Matrix m);        Matrix *operator*(const Matrix m);    private:      int d1, d2;      int **matrix;  };    Matrix::Matrix(int x, int y)  {      d1 = x;      d2 = y;      matrix = new int *[x];      for(int i = 0; i < x; i++)      {          matrix[i] = new int[y];      }  }    Matrix Matrix::operator=(const Matrix* m)  {        for(int i = 0; i < d1; i++)      {          for(int j = 0; j < d2; j++)          {              matrix[i][j] = m->matrix[i][j];          }      }  }    Matrix *Matrix::operator+(const Matrix m)  {      if(m.d1 == d1 && m.d2 == d2)      {          Matrix result(d1, d2);          for(int i = 0; i < d1; i++)          {              for(int j = 0; j < d2; j++)              {                  result.matrix[i][j] = matrix[i][j] + m.matrix[i][j];              }          }          return &result;      }      return this;  }      

model.predict() output is wrong

Posted: 20 Jul 2021 08:15 AM PDT

model.predict() should output something like [0.6,0.2] for two classes if I understand it right but it's only outputting [0.,1.], [1.,0.], or some really small decimal. I tried similar code with different data and batch size, epochs but I still got the similar predictions so I think it's the model/predicting that's broken.

This is the model:

#Train DL model for given food images  def train(epochs, train, validate): #Epoch count, model ID #, training image # PER CLASS, validation image # PER CLASS        #Image diemensions      img_width, img_height = 180, 180        #Model parameters      train_data_dir = "faceimages/Train"     #Directory for training image folder      validation_data_dir = "faceimages/Val"     #Directory for validation image folder      nb_train_samples = train #Training image count      nb_validation_samples = validate #Validation image count      batch_size = 50        #Image validation      if K.image_data_format() == "channels_first":          input_shape = (3, img_width, img_height)      else:          input_shape = (img_width, img_height, 3)        #Model layers      model = Sequential()      model.add(Conv2D(32,3,padding="same", activation="relu", input_shape=input_shape))      model.add(MaxPool2D())        model.add(Conv2D(32,3,padding="same", activation="relu", input_shape=input_shape))      model.add(MaxPool2D())        model.add(Conv2D(64, 3, padding="same", activation="relu"))      model.add(MaxPool2D())      model.add(Dropout(0.5))        model.add(Flatten())      model.add(Dense(128,activation="relu"))      model.add(Dense(2, activation="softmax"))        #Model conifguration for compilation      model.compile(loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), optimizer = "adam", metrics = ["accuracy"])        #Image generation      train_datagen = image.ImageDataGenerator(rescale = 1. / 255, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True)      test_datagen = image.ImageDataGenerator(rescale = 1. / 255)      train_generator = train_datagen.flow_from_directory(train_data_dir, target_size = (img_width, img_height), batch_size = batch_size, class_mode = "binary")      validation_generator = test_datagen.flow_from_directory(validation_data_dir, target_size = (img_width, img_height), batch_size = batch_size, class_mode = "binary")        #Model fitting      model.fit(train_generator, steps_per_epoch = nb_train_samples // batch_size, epochs = epochs, validation_data = validation_generator, validation_steps = nb_validation_samples // batch_size)        #Model saving      model.save("face.h5")      print("Model Saved")  

This is the predicting:

#Identify given image via DL model  def identify(imgName): #Image file name INCLUDING EXTENSIONS, model file name INCLUDING EXTENSIONS      imgPath = "C:/Users/Michelle.LAPTOP-ATBIJMCK/Desktop/Faces/faceimages/Test/"+imgName        #image diemensions      img_width, img_height = 180, 180        #image preperation      img = image.load_img(imgPath, target_size = (img_width, img_height))      x = image.img_to_array(img)      x = np.expand_dims(x, axis = 0)        #image prediction      images = np.vstack([x])      classes = model.predict_classes(images, batch_size = 50)        prediction = model.predict(images)            #return results      if classes == 0:          return ["Fake",prediction]      elif classes == 1:          return ["Original",prediction]    model = load_model("face.h5")  for img in os.listdir("faceimages/Test"):      print(img+str(identify(img)))  

And the output looks like this:

fake (14).png['Original', array([[0., 1.]], dtype=float32)]  fake (15).png['Original', array([[2.3021823e-17, 1.0000000e+00]], dtype=float32)]  fake (16).png['Original', array([[6.4440906e-29, 1.0000000e+00]], dtype=float32)]  fake (17).png['Fake', array([[1.0000000e+00, 2.7556268e-38]], dtype=float32)]  fake (18).png['Fake', array([[1., 0.]], dtype=float32)]  fake (19).png['Original', array([[0.19068162, 0.8093183 ]], dtype=float32)]  fake (2).png['Original', array([[0., 1.]], dtype=float32)]  fake (7).png['Fake', array([[1., 0.]], dtype=float32)]  fake (70).png['Fake', array([[1., 0.]], dtype=float32)]  fake (71).png['Fake', array([[1., 0.]], dtype=float32)]  

I'm really confused. Appreciate any help!

WiFi randomly disconnecting, "Connected, no Internet". When using new HostAPD version 2.9

Posted: 20 Jul 2021 08:15 AM PDT

I have an embedded project where I built hostAPD v2.9 to update it from v2.3, using yocto toolchain. WiFi and Internet is working, however I get constant disconnects where I lose Internet access with the new version.

WiFi stays connected but no Internet. When that happens this is seen in the hostapd_log:

2021-07-15T15:50:19.217955+00:00 <local3.info> hostapd: 1626364219.216166: nl80211: Drv Event 20 (NL80211_CMD_DEL_STATION) received for wlan0  2021-07-15T15:50:19.218000+00:00 <local3.info> hostapd: 1626364219.216265: nl80211: Delete station 00:e9:3a:59:cc:c1  2021-07-15T15:50:19.218034+00:00 <local3.info> hostapd: 1626364219.216322: wlan0: Event DISASSOC (1) received  2021-07-15T15:50:19.218066+00:00 <local3.info> hostapd: 1626364219.216368: 1626364219.216377: wlan0: STA 00:e9:3a:59:cc:c1 IEEE 802.11: disassociated  2021-07-15T15:50:19.218106+00:00 <local3.info> hostapd: 1626364219.216533: wlan0: AP-STA-DISCONNECTED 00:e9:3a:59:cc:c1  2021-07-15T15:50:19.218137+00:00 <local3.info> hostapd: 1626364219.216576: 1626364219.216585: wlan0: STA 00:e9:3a:59:cc:c1 WPA: event 2 notification  2021-07-15T15:50:19.218167+00:00 <local3.info> hostapd: 1626364219.216712: wpa_driver_nl80211_set_key: ifindex=13 (wlan0) alg=0 addr=0xb8f20 key_idx=0 set_tx=1 seq_len=0 key_len=0  2021-07-15T15:50:19.218196+00:00 <local3.info> hostapd: 1626364219.216761: addr=00:e9:3a:59:cc:c1  2021-07-15T15:50:19.218224+00:00 <local3.info> hostapd: 1626364219.216930: WPA: 00:e9:3a:59:cc:c1 WPA_PTK entering state DISCONNECTED  2021-07-15T15:50:19.218252+00:00 <local3.info> hostapd: 1626364219.217020: WPA: 00:e9:3a:59:cc:c1 WPA_PTK entering state INITIALIZE  2021-07-15T15:50:19.222274+00:00 <local3.info> hostapd: 1626364219.217091: wpa_driver_nl80211_set_key: ifindex=13 (wlan0) alg=0 addr=0xb8f20 key_idx=0 set_tx=1 seq_len=0 key_len=0  2021-07-15T15:50:19.222395+00:00 <local3.info> hostapd: 1626364219.217124: addr=00:e9:3a:59:cc:c1  2021-07-15T15:50:19.222439+00:00 <local3.info> hostapd: 1626364219.217219: nl80211: Set STA flags - ifname=wlan0 addr=00:e9:3a:59:cc:c1 total_flags=0x0 flags_or=0x0 flags_and=0xfffffffe authorized=0  2021-07-15T15:50:19.222476+00:00 <local3.info> hostapd: 1626364219.217370: 1626364219.217379: wlan0: STA 00:e9:3a:59:cc:c1 IEEE 802.1X: unauthorizing port  2021-07-15T15:50:19.222507+00:00 <local3.info> hostapd: 1626364219.217554: nl80211: sta_remove -> DEL_STATION wlan0 00:e9:3a:59:cc:c1 --> -2 (No such file or directory)  2021-07-15T15:50:19.222536+00:00 <local3.info> hostapd: 1626364219.217584: ap_free_sta: cancel ap_handle_timer for 00:e9:3a:59:cc:c1  2021-07-15T15:50:19.223767+00:00 <local3.info> hostapd: 1626364219.223263: RTM_NEWLINK: ifi_index=13 ifname=wlan0 wext ifi_family=0 ifi_flags=0x11043 ([UP][RUNNING][LOWER_UP])  

I don't know where the Event 20 (DISASSOC) is coming from, or what is causing this.

I have searched on the Internet and I have found some people suggesting it may be WPA TKIP that when switching to CCMP it doesn't disconnect suddenly anymore. But it didn't work for me.

Any suggestions?

Does anyone know of any way to get firmware for touch screen displays?

Posted: 20 Jul 2021 08:15 AM PDT

Recently, my old ipad stoped working correctly and i'm thinking about turing it into a touch screen display for my pc running windows 10 but I can't find any firmware for it, I can't use anything like Duet because it crashes the ipad so I need to replace the os completely, if anyone knows a way to do so it would be much apreciated.

Angular APP_INITIALIZER with useClass

Posted: 20 Jul 2021 08:15 AM PDT

I need some API data before application startup and am doing it currently with APP_INITIALIZER and useFactory. Now I want to separate all the code from app.module.ts for better structure:

app.module.ts

import { NgModule} from '@angular/core';  import { BrowserModule } from '@angular/platform-browser';  import { BrowserAnimationsModule } from '@angular/platform-browser/animations';  import { HttpClientModule } from '@angular/common/http';    import { AppRoutingModule } from './app-routing.module';  import { AppComponent } from './app.component';  import { httpInterceptorProvider, appInitProvider } from '@core';    @NgModule({      declarations: [          AppComponent      ],      imports: [          BrowserModule,          BrowserAnimationsModule,          AppRoutingModule,          HttpClientModule      ],      providers: [          httpInterceptorProvider,          appInitProvider      ],      bootstrap: [AppComponent]  })    export class AppModule { }  

@core/init/index.ts

import { APP_INITIALIZER } from '@angular/core';  import { InitService } from './init.service';    export const appInitProvider = [      { provide: APP_INITIALIZER, useClass: InitService, multi: true }    ];  

@core/init/init.service.ts

import { Injectable } from '@angular/core';  import { HttpClient } from "@angular/common/http";  import { SettingsService } from "@core";    @Injectable()  export class InitService implements Resolve<any> {          constructor(          private _http: HttpClient,          private settings: SettingsService,      ) {}        resolve() {          const promise = this._http.get("/API")          .toPromise()          .then((data: any) => {              this.settings.setSettings(data);              return data;          });          return promise;      }    }  

When doing this I get the angular error

TypeError: this.appInits[i] is not a function at ApplicationInitStatus.runInitializers

I have the same setup for the http interceptor and there it is working without any problems.

Deep copy an object in javascript with function reference [duplicate]

Posted: 20 Jul 2021 08:16 AM PDT

I went through the deep copy methods, but I don't have jQuery plugin, neither wanna use lodash or recursive function. Note: I have function calls to in the obj. Here is the kind of object I wanna deep copy:

const obj = {  a:[{k1:v1},{k2:v2}],  b:[{k1:v1},{k3:v3}],  ...  }  

Any suggestions?

The referred link so far What is the most efficient way to deep clone an object in JavaScript?

Normal Mapping vs Reduce

Posted: 20 Jul 2021 08:16 AM PDT

I'm trying to convert an object into single array with just key and value. I tried two different ways. Though I succeeded in my first attempt but using reduce I am unable to get the result. Please kindly let me know if there is/are better ways of achieving the same. Thank you.

  var demoArr = [              {                  "results": [                  {                      "listing_id": 10544193                  },                  {                      "listing_id": 4535435                  }                  ],                  "results1": [                      {                          "listing_id": 1054419363                      },                      {                          "listing_id": 432535435                      }                  ]              }          ];          let aaa = [];  //          demoArr.map(x => {   (previously)              demoArr.forEach(x => {  //Edited              let ss = Object.values(x);              ss.map(y => {                  y.forEach(k => {                      aaa.push({"listing_id" : k.listing_id});                  })                               });           });  

Resulted in the following.

[{"listing_id":10544193},{"listing_id":4535435},{"listing_id":1054419363},{"listing_id":432535435}]  

Is there a better way to achieve the above? Maybe by using reduce? I tried but failed to get the result.

         var ds = demoArr.reduce((a,value) => {              a[value.listing_id] = a[value.listing_id] ? a[value.listing_id] : value              return a           },{});  

Why this data push to an array disappear after the forEach loop in the useEffect hooks?

Posted: 20 Jul 2021 08:16 AM PDT

Here is my code

const Tabs = ({data, scrollX}) => {    const [measures, setMeasures] = useState([]);    const containerRef = useRef({});    let measureMentArray = [];    useEffect(() => {      data &&        data.forEach(item =>  {          item.ref.current.measureLayout(            containerRef.current,            (x, y, width, height) => {              measureMentArray.push({x, y, width, height});              // console.log(measureMentArray)            },          );        });      console.log(measureMentArray);      // setMeasures(measureMentArray);    }, []);  

As you can see in my code. There is 2 console.log When I try to console measureMentArray in the first place the array will return 4 items. Its correct since data got 4 items.

But outside the forEach Loop, in the second console.log when I console measureMentArray The array is empty.

Is it because this is inside useEffect hooks? What can I do to set State after the loop end.

C# JQuery/Javascript

Posted: 20 Jul 2021 08:16 AM PDT

Working in Visual Studio 2019. I have an aspx page with contact details for a user. Multiple contacts can be added. There is a Javascript function which compares the data saved in our local database with a third-party database. Fields which do not match should be highlighted.

The div ID for each contact contains the GUID of the contact as saved in our local database. There is also a hidden field within the div containing the GUID. The message coming back from the function includes this GUID to identify which contact it's referring to. The GUID is at the very end of the error message so I'm using a substring to grab it.

How can I highlight the correct input field based on the specified contact?

The code below is the page that displays the currently selected user along with all of their contacts. We pass the user ID (uId) to the function which returns a List containing a message for each contact field that does not match. e.g. "Contact First Name does not match FD1B0124-5B86-49BD-9D89-F9DF973844D5" "Contact First Name does not match 07653F31-91BA-4E96-B601-C8544D623FAC" "Contact Email Address does not match DF80891A-F14C-4938-9A53-997301BD551C" etc., etc.

.aspx:

<div id="ContactInfoSection">      <div id="Contact" class="width-100">          <label id="ContactLabel" for="Contact">Contact:</label>      </div>      <% for (int i = 0; i < Model.CurrentUser.UserContacts.Count; i++)         {             var contactId = Model.CurrentUser.UserContacts[i].Id;             var contactParentDivId = string.IsNullOrEmpty(contactId) ? i.ToString() : contactId;      %>          <div class="contact-parent-div" id='<%: "contact-parent-div-id-" + contactParentDivId %>'>          <% Html.RenderPartial("UserContact", Model.CurrentUser.UserContacts[i], new ViewDataDictionary{{"ContactParentDivId", contactParentDivId}, {"UserActiveStatus", Model.CurrentUser.IsActive.ToString()}}); %>          </div>      <% } %>  </div>  

UserContact.ascx:

<div class="contact-info">      <div class="width-100 display-inline-block">          <%: Html.TextBox("ContactUserGUID", Model.UserContactDetail.Id, new {hidden="true"}) %>          <div class="inputgroup">              <label for="ContactFirstName"><span class="req"><span class="icon required"></span></span>Contact First Name</label>              <div class="editor-fields contact-firstname">                  <%: Html.TextBox("ContactFirstName", Model.UserContactDetail.FirstName) %>                  <%: Html.ValidationMessage("ContactFirstName", "*") %>              </div>          </div>          <div class="inputgroup">              <label for="ContactLastName"><span class="req"><span class="icon required"></span></span>Contact Last Name</label>              <div class="editor-fields contact-lastname">                  <%: Html.TextBox("ContactLastName", Model.UserContactDetail.LastName) %>                  <%: Html.ValidationMessage("ContactLastName", "*") %>              </div>          </div>      </div>      <div class="width-100 display-inline-block">          <div class="inputgroup">              <label for="ContactEmail"><span class="req"><span class="icon required"></span></span>Contact Email Address</label>              <div class="editor-fields contact-email" id='<%: "contact-email-id-"+Model.Id %>'>                  <%: Html.TextBox("ContactEmail", Model.UserContactDetail.EmailAddress, new {maxlength="50",                           onchange = "loadContactInfo(value, "+ parentDivId +")"}) %>                  <%: Html.ValidationMessage("ContactEmail", "*") %>              </div>          </div>          <div class="inputgroup">              <label for="ContactPhone"><span class="req"><span class="icon required"></span></span>Contact Home #</label>              <div id="ContactPhone" class="editor-fields contact-phone">                  <%:Html.TextBox("ContactPhone",  Model.UserContactDetail.PhoneNumber)%>                  <%:Html.ValidationMessage("ContactPhone", "*")%>              </div>          </div>      </div>  </div>  

.js:

function checkData() {      var requestData = { userId: uId };      $.ajax({          url: urlCheckData,          type: "POST",          data: requestData,          success: function (registerResult) {              var data = registerResult;              if (data.Success) {                  sMessagePopup("Check Data", data.SuccessMessage, "OK");                  return false;              } else {                  if (data.Errors && data.Errors.length > 0) {                      $.each(data.Errors, function (index, value) {                      var contactId = value.subString(24);                          if (value.startsWith('Contact Email Address')) {                              $("#ContactEmail :input").addClass("errorInputHighlight");                          }                            if (value.startsWith('Contact First Name')) {                              $("#ContactFirstName :input").addClass("errorInputHighlight");                          }                            if (value.startsWith('Contact Last Name')) {                              $("#ContactLastName :input").addClass("errorInputHighlight");                          }                            if (value.startsWith('Contact Phone #')) {                              $("#ContactPhone :input").addClass("errorInputHighlight");                          }                                                });                      return false;                  }                   return false;              }          }      });      return false;  }  

Convert two strings to float (JavaScript)

Posted: 20 Jul 2021 08:16 AM PDT

I have some object that contains two string properties:

const obj = {    a = '6',    b = '2',  }  

I want to get float 6.2. What is the best and simple way? Thanks in advance!

hello someone help me with this problem: What went wrong: Execution failed for task ':compileJava' [closed]

Posted: 20 Jul 2021 08:15 AM PDT

This is error

Task :compileJava FAILED D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\CommandsManager.java:52: error: ')' expected if (sender instanceof Player player) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\CommandsManager.java:52: error: not a statement if (sender instanceof Player player) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\CommandsManager.java:52: error: ';' expected if (sender instanceof Player player) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\CommandsManager.java:56: error: 'else' without 'if' } else ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:38: error: ')' expected if (sender instanceof Player player) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:38: error: not a statement if (sender instanceof Player player) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:38: error: ';' expected if (sender instanceof Player player) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:54: error: 'else' without 'if' } else ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:66: error: ')' expected if (sender instanceof Player player) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:66: error: not a statement if (sender instanceof Player player) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:66: error: ';' expected if (sender instanceof Player player) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:72: error: 'else' without 'if' } else ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:81: error: ')' expected if (sender instanceof Player player) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:81: error: not a statement if (sender instanceof Player player) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:81: error: ';' expected if (sender instanceof Player player) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:84: error: 'else' without 'if' } else ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:93: error: ')' expected if (sender instanceof Player player) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:93: error: not a statement if (sender instanceof Player player) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:93: error: ';' expected if (sender instanceof Player player) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:96: error: 'else' without 'if' } else ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:107: error: ')' expected if (sender instanceof Player player) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:107: error: not a statement if (sender instanceof Player player) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:107: error: ';' expected if (sender instanceof Player player) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:110: error: ')' expected if (recipe instanceof FurnaceBuilder furnace) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:110: error: not a statement if (recipe instanceof FurnaceBuilder furnace) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:110: error: ';' expected if (recipe instanceof FurnaceBuilder furnace) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:115: error: 'else' without 'if' } else ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:125: error: ')' expected if (sender instanceof Player player) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:125: error: not a statement if (sender instanceof Player player) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:125: error: ';' expected if (sender instanceof Player player) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:133: error: 'else' without 'if' } else ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:23: error: : expected case "ITEMS" -> reloadItems(sender); ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:23: error: illegal start of expression case "ITEMS" -> reloadItems(sender); ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:23: error: ';' expected case "ITEMS" -> reloadItems(sender); ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:23: error: not a statement case "ITEMS" -> reloadItems(sender); ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:23: error: ';' expected case "ITEMS" -> reloadItems(sender); ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:24: error: : expected case "PACK" -> reloadPack(OraxenPlugin.get(), sender); ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:24: error: illegal start of expression case "PACK" -> reloadPack(OraxenPlugin.get(), sender); ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:24: error: ';' expected case "PACK" -> reloadPack(OraxenPlugin.get(), sender); ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:24: error: ';' expected case "PACK" -> reloadPack(OraxenPlugin.get(), sender); ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:24: error: not a statement case "PACK" -> reloadPack(OraxenPlugin.get(), sender); ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:24: error: ';' expected case "PACK" -> reloadPack(OraxenPlugin.get(), sender); ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:25: error: : expected case "RECIPES" -> RecipesManager.reload(OraxenPlugin.get()); ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:25: error: illegal start of expression case "RECIPES" -> RecipesManager.reload(OraxenPlugin.get()); ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:25: error: ';' expected case "RECIPES" -> RecipesManager.reload(OraxenPlugin.get()); ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:26: error: : expected case "CONFIGS" -> OraxenPlugin.get().reloadConfigs(); ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:26: error: illegal start of expression case "CONFIGS" -> OraxenPlugin.get().reloadConfigs(); ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:26: error: ';' expected case "CONFIGS" -> OraxenPlugin.get().reloadConfigs(); ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:27: error: : expected default -> { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:27: error: illegal start of expression default -> { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:27: error: ';' expected default -> { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:34: error: ')' expected } ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:35: error: illegal start of expression }); ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RepairCommand.java:27: error: ')' expected if (sender instanceof Player player) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RepairCommand.java:27: error: not a statement if (sender instanceof Player player) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RepairCommand.java:27: error: ';' expected if (sender instanceof Player player) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RepairCommand.java:55: error: 'else' without 'if' } else { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RepairCommand.java:65: error: ')' expected if (!(itemMeta instanceof Damageable damageable)) ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RepairCommand.java:65: error: illegal start of expression if (!(itemMeta instanceof Damageable damageable)) ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RepairCommand.java:65: error: ';' expected if (!(itemMeta instanceof Damageable damageable)) ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\font\Glyph.java:8: error: class, interface, or enum expected public record Glyph(String name, char character, String texture, int ascent, ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\font\Glyph.java:11: error: class, interface, or enum expected public JsonObject toJson() { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\font\Glyph.java:13: error: class, interface, or enum expected JsonArray chars = new JsonArray(); ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\font\Glyph.java:14: error: class, interface, or enum expected chars.add(String.valueOf(character)); ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\font\Glyph.java:15: error: class, interface, or enum expected output.add("chars", chars); ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\font\Glyph.java:16: error: class, interface, or enum expected output.addProperty("file", texture); ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\font\Glyph.java:17: error: class, interface, or enum expected output.addProperty("ascent", 8); ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\font\Glyph.java:18: error: class, interface, or enum expected output.addProperty("height", height); ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\font\Glyph.java:19: error: class, interface, or enum expected output.addProperty("type", "bitmap"); ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\font\Glyph.java:20: error: class, interface, or enum expected return output; ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\font\Glyph.java:21: error: class, interface, or enum expected } ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\font\Glyph.java:23: error: class, interface, or enum expected public boolean hasPermission(Player player) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\font\Glyph.java:25: error: class, interface, or enum expected } ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:71: error: ')' expected if (itemMeta instanceof PotionMeta potionMeta) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:71: error: not a statement if (itemMeta instanceof PotionMeta potionMeta) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:71: error: ';' expected if (itemMeta instanceof PotionMeta potionMeta) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:80: error: ')' expected if (itemMeta instanceof TropicalFishBucketMeta tropicalFishBucketMeta) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:80: error: not a statement if (itemMeta instanceof TropicalFishBucketMeta tropicalFishBucketMeta) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:80: error: ';' expected if (itemMeta instanceof TropicalFishBucketMeta tropicalFishBucketMeta) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:280: error: ')' expected if (itemMeta instanceof Damageable damageable) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:280: error: not a statement if (itemMeta instanceof Damageable damageable) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:280: error: ';' expected if (itemMeta instanceof Damageable damageable) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:287: error: ')' expected if (itemMeta instanceof LeatherArmorMeta leatherArmorMeta) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:287: error: not a statement if (itemMeta instanceof LeatherArmorMeta leatherArmorMeta) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:287: error: ';' expected if (itemMeta instanceof LeatherArmorMeta leatherArmorMeta) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:294: error: ')' expected if (itemMeta instanceof PotionMeta potionMeta) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:294: error: not a statement if (itemMeta instanceof PotionMeta potionMeta) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:294: error: ';' expected if (itemMeta instanceof PotionMeta potionMeta) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:309: error: ')' expected if (itemMeta instanceof SkullMeta skullMeta) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:309: error: not a statement if (itemMeta instanceof SkullMeta skullMeta) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:309: error: ';' expected if (itemMeta instanceof SkullMeta skullMeta) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:317: error: ')' expected if (itemMeta instanceof TropicalFishBucketMeta tropicalFishBucketMeta) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:317: error: not a statement if (itemMeta instanceof TropicalFishBucketMeta tropicalFishBucketMeta) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:317: error: ';' expected if (itemMeta instanceof TropicalFishBucketMeta tropicalFishBucketMeta) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\mechanics\provided\custom\CustomMechanicAction.java:17: error: illegal start of expression CustomAction action = switch (params[0]) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\mechanics\provided\custom\CustomMechanicAction.java:17: error: not a statement CustomAction action = switch (params[0]) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\mechanics\provided\custom\CustomMechanicAction.java:17: error: ';' expected CustomAction action = switch (params[0]) { ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\mechanics\provided\custom\CustomMechanicAction.java:18: error: orphaned case case "command" -> new CommandAction(params); ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\mechanics\provided\custom\CustomMechanicAction.java:18: error: : expected case "command" -> new CommandAction(params); ^ D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\mechanics\provided\custom\CustomMechanicAction.java:18: error: illegal start of expression case "command" -> new CommandAction(params); ^ 100 errors

FAILURE: Build failed with an exception.

  • What went wrong: Execution failed for task ':compileJava'.

Compilation failed; see the compiler error output for details.

  • Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

  • Get more help at https://help.gradle.org

BUILD FAILED in 1s 2 actionable tasks: 2 executed

Function to write multiple Excel files with multiple sheets based on data frame variables

Posted: 20 Jul 2021 08:15 AM PDT

Teaching myself functions, and trying to implement here but stuck.

Here is a simplistic example of what I am trying to do.

I have a list of 2 tibbles. Each is a different type of output, but each also has an "Agency" column. I want to generate an Excel workbook for each Agency, and each workbook should have two sheets. Each sheet will only contain the data for that Agency from the two tibbles.

rm(list = ls())    library(openxlsx)    Agency <- c("Agency1", "Agency2", "Agency3", "Agency3")  Value1.1 <- c(1, 4, 4, 5)  Value1.2 <- c(22,44,11,22)    Numbers <- tibble(Agency, Value1.1, Value1.2)    Value2.1 <- c("abc", "sif", "hwr", "yyd")  Value2.2 <- c("as", "is", "on", "for")    Letters <- tibble(Agency, Value2.1, Value2.2)    agency_name <- split(Numbers, str_sub(Numbers$Agency, 1, 30))    sheet_name = list("Numbers", "Letters")    lapply(seq_along(agency_name),          function(x) {           openxlsx::write.xlsx(             sheet_name,             file = paste0("output/test/", names(Agency[x]), '.xlsx'),             row.names = FALSE           )         })  

Agency1.xlsx file would look like this.

enter image description here

Need help fulfilling certain conditions in nested loop [closed]

Posted: 20 Jul 2021 08:16 AM PDT

I am stuck at a question which requires me to have a point system, and run through map1(which can be changed), with a few conditions in mind.

HSE alone do not get any points.

If HSE is beside a FAC, HSE scores 1 point.

HSE scores +1 point per HSE or SHP adjacent to it.

HSE scores +2 points for each adjacent BCH.

my though process for the current code was to find the position for the HSE one by one and add it into a list, (suppousedly: HSE_list = [(0,0), (1,2), (2,2)] and then run conditions where I do +1 -1 in the position which that certain house was in.

HSE_point = 0  map1 = [ ['HSE', 'FAC', '   ', '   '],\           ['   ', '   ', 'SHP', '   '],\           ['   ', 'HSE', 'HSE', '   '],\           ['   ', 'BCH', '   ', '   '] ]      HSE_list = []    if 'HSE' in x:       y = (map1.index(x), x.index('HSE'))       HSE_list.append(y)         for count in HSE_list:            if x[count[0]+1][count[1]+1] or x[count[0]-1][count[1]-1] == 'FAC'                  return True                                                 print('Total points = ', HSE_point)  

in the case from map1 above, map1[0][0]'s house scores 1 point, map1[1][2]'s house scores 3 points, and map[2][2]'s house scores 2 points.

Thus the supposed answer for total points earned would be >>Total points = 6

But after running into an error(index out of range),which I am aware that it was caused by if x[count[0]+1][count[1]+1] or x[count[0]-1][count[1]-1] == 'FAC'; I am unsure of how to fulfill the conditions which was stated.

Is there any other ways to check if HSE is next to another string in the list?

What is an efficient way to get e.g. a specific member of a class by its id in C++?

Posted: 20 Jul 2021 08:16 AM PDT

I need help understanding how I setup my programme correctly. I have a class that stores "Customers". I read those customers from a file into the programme as class members. Now at a different part of my programme I want to get the corresponding data of the customer (e.g.: age, city) by the customers unique id.

class Customers {         const int customerid;         std::string name;         int age;         std::string city;  }    

How can I get access to my class member where customerid = 3?

Right now I was successful putting all the data from my file into an std::vector and by searching the std::vector with find_if. Is there an easier way to archive this?

I remember from php that I was just simply using a multi-array, where the key was the unique customerid.

$customers= array (    1=>array("name"=>"John", "age"=> 22, "city" > "New York"),    2=>array("name"=>"Peter", "age"=> 58, "city" > "London"),    3=>array("name"=>"Jason", "age"=> 25, "city" > "Melbourne")  );    

I got my relevant information, for example the city of customerid = 3, this way:

echo $customers[3]["city"];  

So what is the best way to do this in C++?

Google Apps Scripts - Add Timestamp to multiple cells when updated

Posted: 20 Jul 2021 08:16 AM PDT

I'm trying to update the code in this tutorial to add a timestamp when I update them. So far it's working for the first cell but not all of them when copying values to a whole range.

Could someone take a look and help adapt this so that all cells are updated with a timestamp rather than just the first?

Thanks!

function onEdit(event)  {     var timezone = "GMT+1";    var timestamp_format = "dd/MM/yyyy HH:mm:ss"; // Timestamp Format.     var updateColName = "Message";    var timeStampColName = "Timestamp";    var sheet = event.source.getSheetByName('Sheet1'); //Name of the sheet where you want to run this script.        var actRng = event.source.getActiveRange();    var editColumn = actRng.getColumn();    var index = actRng.getRowIndex();    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();    var dateCol = headers[0].indexOf(timeStampColName);    var updateCol = headers[0].indexOf(updateColName); updateCol = updateCol+1;    if (dateCol > -1 && index > 1 && editColumn == updateCol) { // only timestamp if 'Last Updated' header exists, but not in the header row itself!      var cell = sheet.getRange(index, dateCol + 1);      var date = Utilities.formatDate(new Date(), timezone, timestamp_format);      cell.setValue(date);    }  }

Cassandra CQL - Convert the release_version column in system.local table to an int

Posted: 20 Jul 2021 08:16 AM PDT

I am writing a query in cql that checks if the release version of Cassandra is greater than or equal to 3.11.10.

select * from system.local where release_version >= '3.11.10'  

As the release_version is data type text this will not work and I cannot find a way to get a substring of this value or get a way to cast the value to an int.

I am unable to create a function for this as I cannot create a function on system tables. I am also unable to use Java/Python etc it has to be done in cql.

I have also tried in clause in where statement but I cannot seem to put in more than one value in the in without an error:

IN predicates on non-primary-key columns (release_version) is not yet supported

Would anyone know of a way to this or a workaround on how to get this to execute?

Run function on button click in file from Qt doesn't work

Posted: 20 Jul 2021 08:16 AM PDT

I am making an application for drawing graphs. I do it according to the instructions:

  1. Made the application in Qt designer
  2. List item file.ui translated to file.py
  3. write the code in the body of file.py
class Ui_Dialog(object):      def write_plot(self):          year = [1950, 1975, 2000, 2018]           population = [2.12, 3.681, 5.312, 6.981]           plt.plot(year, population)          plt.show()      def run_plot(self):          self.pushButton.clicked.connect(self.write_plot)  

when the button is pressed, the graph should be loaded, but it does not work. How can you fix it?

MyBatis is not returning duplicate entries

Posted: 20 Jul 2021 08:15 AM PDT

The Problem

My Front-End needs to retrieve data from the database. Since it's a lot of records, we paginated the query. MyBatis correctly retrieves x results (depending on how much the Front-End asks for it) but, instead, returns less values as it finds "duplicates". MyBatis, apparently, "magically" removes those duplicates.

Stack

What I've been using:

  1. Java 8
  2. Spring 4.0.6
  3. MyBatis 3.5.0
  4. MyBatis Spring 2.0.0
  5. Oracle DB 12g

The Implementation

I've implemented the SQL query in the following way

<select id="getListAnagraficheCruscotto" resultMap="DatiContoCruscotto">      SELECT d.*,      b.CODICE AS PROFESSIONI_CODICE,      TRIM(b.DESCRIZIONE) AS PROFESSIONI_DESCRIZIONE,      c.CODICE AS ATTIVITA_CODICE,      TRIM(c.DESCRIZIONE) AS ATTIVITA_DESCRIZIONE,      e.CODICE AS RAPPORTO_PB_CODICE,      TRIM(e.DESCRIZIONE) AS RAPPORTO_PB_DESCRIZIONE,      f.CODICE AS PERIODICITA_CODICE,      TRIM(f.DESCRIZIONE) AS PERIODICITA_DESCRIZIONE,      g.CODICE AS FORMATO_CODICE,      TRIM(g.DESCRIZIONE) AS FORMATO_DESCRIZIONE,      h.FLAG_CAI AS FLAG_CAI,      h.FLAG_BPRESS AS FLAG_BPRESS,      h.FLAG_CERVED AS FLAG_CERVED,      h.FLAG_BLACK_LIST AS FLAG_BLACK_LIST,      i.GUID AS GUID_DOSSIER,      p.NOME_COGNOME_PB AS NOME_COGNOME_PB_APERTURA_CONTO,      inizComm.CODICE AS CODICE_INIZ_COMM,      inizComm.DESCRIZIONE AS DESCRIZIONE_INIZ_COMM,      adesInizComm.STATO AS STATO_INIZ_COMM ,      t.ID_TRASFERIMENTO_FONDI AS ID_TRASFERIMENTO_FONDI        FROM T_DATI_APERTURA_CONTO d      LEFT OUTER JOIN T_ANAGRAFICA a ON d.CODICE_FISCALE_PRINCIPALE = a.CODICE_FISCALE_PRINCIPALE      LEFT OUTER JOIN T_PROFESSIONI b ON a.AV_FK_PROFESSIONI = b.CODICE      LEFT OUTER JOIN T_ATTIVITA c ON a.AV_FK_COD_ATTIVITA_TAE = c.CODICE      LEFT OUTER JOIN T_RAPPORTO_PB e ON d.FK_RAPPORTO_PB = e.CODICE      LEFT OUTER JOIN T_PERIODICITA f ON d.FK_PERIODICITA_ESTRATTO_CONTO = f.CODICE      LEFT OUTER JOIN T_FORMATO g ON d.FK_FORMATO_ESTRATTO_CONTO = g.CODICE      LEFT OUTER JOIN T_VERIFICHE h ON (TO_CHAR(d.ID)) = h.ID_PRATICA      LEFT OUTER JOIN T_MINI_QAV p ON (TO_CHAR(p.CODICE_FISCALE_PRINCIPALE) = TO_CHAR(d.ID))      LEFT OUTER JOIN T_SUPERPRATICA i ON i.COD_FISCALE = TO_CHAR(d.ID)      LEFT OUTER JOIN TIC_ADESIONI_CLIENTI adesInizComm on adesInizComm.CODICE_FISCALE = d.CODICE_FISCALE_PRINCIPALE      LEFT OUTER JOIN TIC_INIZ_COMM inizComm on inizComm.CODICE = adesInizComm.CODICE_INIZ_COMM      LEFT OUTER JOIN T_TRASFERIMENTO_FONDI t ON TO_CHAR(a.ID) = t.ID_PRATICA        WHERE 1=1      AND (d.STATO_PRATICA = '5' OR d.STATO_PRATICA = '6' OR d.STATO_PRATICA = '7' OR (d.MATRICOLA_ASSEGNATARIO IS NULL AND d.STATO_PRATICA =      '4'))        <if test="codiceFiliale!= null and codiceFiliale!= '' ">          AND d.CODICE_FILIALE = #{codiceFiliale}      </if>      <if test="sportello!= null and sportello!= '' ">          AND d.SPORTELLO = #{sportello}      </if>      <if test="tipoPratica!= null and tipoPratica!= '' ">          AND a.TIPO_PRATICA = #{tipoPratica}      </if>        AND ( adesInizComm.STATO IS NULL OR adesInizComm.STATO = '2' OR adesInizComm.STATO= '3' )        <if test="filter!= null and filter!='' and filter!='%%'">          AND (          d.IBAN LIKE(#{filter})          OR d.CODICE_MODULO LIKE(#{filter})          OR d.MATRICOLA_ASSEGNATARIO LIKE(#{filter})          OR d.NOME_COGNOME_ASSEGNATARIO LIKE(#{filter})          OR d.MATRICOLA_PB LIKE(#{filter})          OR p.NOME_COGNOME_PB LIKE(#{filter})          OR d.CODICE_FISCALE_PRINCIPALE LIKE(#{filter})          OR d.CODICE_FISCALE_2 LIKE(#{filter})          OR d.CODICE_FISCALE_3 LIKE(#{filter})          OR d.CODICE_FISCALE_4 LIKE(#{filter})          OR CONCAT(CONCAT(d.NOME_1,' '), d.COGNOME_1) LIKE(#{filter})          OR CONCAT(CONCAT(d.COGNOME_1,' '), d.NOME_1) LIKE(#{filter})          OR CONCAT(CONCAT(d.NOME_2,' '), d.COGNOME_2) LIKE(#{filter})          OR CONCAT(CONCAT(d.COGNOME_2,' '), d.NOME_2) LIKE(#{filter})          OR CONCAT(CONCAT(d.NOME_3,' '), d.COGNOME_3) LIKE(#{filter})          OR CONCAT(CONCAT(d.COGNOME_3,' '), d.NOME_3) LIKE(#{filter})          OR CONCAT(CONCAT(d.NOME_4,' '), d.COGNOME_4) LIKE(#{filter})          OR CONCAT(CONCAT(d.COGNOME_4,' '), d.NOME_4) LIKE(#{filter})          )      </if>      ORDER BY d.DATA_INSERIMENTO DESC        <if test="page!=null and page!=''">          OFFSET #{page} ROWS      </if>      <if test="limit!=null and limit!='' ">          FETCH NEXT #{limit} ROWS ONLY      </if>        </select>  

By relying on the FETCH NEXT / OFFSET approach, I'm able to deliver a decent UX in terms of paginated query.
The problem, though, occurs when that query intercepts in the result set something like this

ID   |CODICE_FISCALE_PRINCIPALE|NOME_1|COGNOME_1|CODICE  -----+-------------------------+------+---------+------  14838|Value1                   |TGN   |CVG      | eee       14837|Value2                   |TWG   |CCR      | aaaa       14835|Value3                   |mARIE |MARIE    | rrrr       14832|Value4                   |HBZ   |CHT      | ddff       14832|Value4                   |HBZ   |CHT      | asda       14832|Value4                   |HBZ   |CHT      | sa12     14832|Value4                   |HBZ   |CHT      | asdad       14832|Value4                   |HBZ   |CHT      | gwrew       14832|Value4                   |HBZ   |CHT      | cvbvc       14822|Value4                   |VPY   |MZV      | bvcbcv  

For simplicity, I've omitted some values from the result set. As you can see, it might seem that I have duplicates starting from row 4 to 10, but these actually diverge for the last column: they hold, in fact, a specific value for each row. This is the Java implementation of the mapper

public interface DatiAperturaContoMapper {            public List<DatiContoCruscotto> getListAnagraficheCruscotto(DatiContoCruscotto datiContoCruscotto);        }  

My Tests

What happens is that MyBatis is actually gathering 10 rows in executing the query. I've seen this by enabling the debug logs of the library. But then, when gathering the Result Set in the requested list, it magically lose 6 of these!
What I'm assuming is that the library has some kind of logic that erases these duplicates, since if I try to alter on purpose one of the duplicate record's ID, it appears in my result set.

Does anybody have any clues on how to solve this?

Also adding the ResultMap implementation

   <resultMap id="DatiContoCruscotto" type="fideuram.reply.it.db.model.DatiContoCruscotto">          <result property="id" column="ID"/>          <result property="codiceFiscalePrincipale" column="CODICE_FISCALE_PRINCIPALE"/>          <result property="nome1" column="NOME_1"/>          <result property="cognome1" column="COGNOME_1"/>          <result property="codiceFiscale2" column="CODICE_FISCALE_2"/>          <result property="nome2" column="NOME_2"/>          <result property="cognome2" column="COGNOME_2"/>          <result property="codiceFiscale3" column="CODICE_FISCALE_3"/>          <result property="nome3" column="NOME_3"/>          <result property="cognome3" column="COGNOME_3"/>          <result property="codiceFiscale4" column="CODICE_FISCALE_4"/>          <result property="nome4" column="NOME_4"/>          <result property="cognome4" column="COGNOME_4"/>          <result property="indirizzoDiContratto" column="INDIRIZZO_DI_CONTRATTO"/>          <result property="indirizzoDiContrattoToponimo" column="INDIRIZZO_DI_CONTRATTO_TOPON"/>          <result property="indirizzoDiContrattoVia" column="INDIRIZZO_DI_CONTRATTO_VIA"/>          <result property="indirizzoDiContrattoCivico" column="INDIRIZZO_DI_CONTRATTO_CIVICO"/>          <result property="indirizzoDiContrattoFrazione" column="INDIRIZZO_DI_CONTRATTO_FRAZ"/>          <result property="localita" column="LOCALITA"/>          <result property="cap" column="CAP"/>          <result property="provincia" column="PROVINCIA"/>          <result property="nazione" column="NAZIONE"/>          <result property="presso" column="PRESSO"/>          <result property="fkCategoriaCondizioni" column="FK_CATEGORIA_CONDIZIONI"/>          <result property="fkCategoriaCliente" column="FK_CATEGORIA_CLIENTE"/>          <result property="flagServiziOnline1" column="FLAG_SERVIZI_ONLINE_1"/>          <result property="flagServiziOnline2" column="FLAG_SERVIZI_ONLINE_2"/>          <result property="flagServiziOnline3" column="FLAG_SERVIZI_ONLINE_3"/>          <result property="flagServiziOnline4" column="FLAG_SERVIZI_ONLINE_4"/>          <result property="numeroCellulare1" column="NUMERO_CELLULARE_1"/>          <result property="numeroCellulare2" column="NUMERO_CELLULARE_2"/>          <result property="numeroCellulare3" column="NUMERO_CELLULARE_3"/>          <result property="numeroCellulare4" column="NUMERO_CELLULARE_4"/>          <result property="operatoreTelefonico1" column="OPERATORE_TELEFONICO_1"/>          <result property="operatoreTelefonico2" column="OPERATORE_TELEFONICO_2"/>          <result property="operatoreTelefonico3" column="OPERATORE_TELEFONICO_3"/>          <result property="operatoreTelefonico4" column="OPERATORE_TELEFONICO_4"/>          <result property="flagRilascioBancocard" column="FLAG_RILASCIO_BANCOCARD"/>          <result property="modalitaDiSpedizione" column="MODALITA_DI_SPEDIZIONE"/>          <result property="rilascioBancocardIntestatari" column="RILASCIO_BANCOCARD_INTESTATARI"/>          <result property="flagServizioSmsBancocard" column="FLAG_SERVIZIO_SMS_BANCOCARD"/>          <result property="smsBancocardIntestatari" column="SMS_BANCOCARD_INTESTATARI"/>          <result property="numeroCellulareSms1" column="NUMERO_CELLULARE_SMS_1"/>          <result property="numeroCellulareSms2" column="NUMERO_CELLULARE_SMS_2"/>          <result property="numeroCellulareSms3" column="NUMERO_CELLULARE_SMS_3"/>          <result property="numeroCellulareSms4" column="NUMERO_CELLULARE_SMS_4"/>          <result property="operatoreTelefonicoSms1" column="OPERATORE_TELEFONICO_SMS_1"/>          <result property="operatoreTelefonicoSms2" column="OPERATORE_TELEFONICO_SMS_2"/>          <result property="operatoreTelefonicoSms3" column="OPERATORE_TELEFONICO_SMS_3"/>          <result property="operatoreTelefonicoSms4" column="OPERATORE_TELEFONICO_SMS_4"/>          <result property="fkPeriodicitaEstrattoConto" column="FK_PERIODICITA_ESTRATTO_CONTO"/>          <result property="fkFormatoEstrattoConto" column="FK_FORMATO_ESTRATTO_CONTO"/>          <result property="rilascioLibrettoAssegni" column="RILASCIO_LIBRETTO_ASSEGNI"/>          <result property="fkRapportoPb" column="FK_RAPPORTO_PB"/>          <result property="nomeReferal" column="NOME_REFERAL"/>          <result property="indirizzoConsegna" column="INDIRIZZO_CONSEGNA"/>          <result property="flagAutorizBanca" column="FLAG_AUTORIZ_BANCA"/>          <result property="flagAutorizAddebitoBanca" column="FLAG_AUTORIZ_ADDEBITO_BANCA"/>          <result property="statoPratica" column="STATO_PRATICA"/>          <result property="filiale" column="FILIALE"/>          <result property="matricolaPb" column="MATRICOLA_PB"/>          <result property="matricolaSottoutenza" column="MATRICOLA_SOTTOUTENZA"/>          <result property="tipoSottoutenza" column="TIPO_SOTTOUTENZA"/>          <result property="sportello" column="SPORTELLO"/>          <result property="dataInserimento" column="DATA_INSERIMENTO"/>          <result property="dataUpdate" column="DATA_UPDATE"/>          <result property="matricolaAssegnatario" column="MATRICOLA_ASSEGNATARIO"/>          <result property="codiceModulo95" column="CODICE_MODULO"/>          <result property="nomeCognomePbAperturaConto" column="NOME_COGNOME_PB_APERTURA_CONTO"/>          <result property="nomeCognomeAssegnatario" column="NOME_COGNOME_ASSEGNATARIO"/>          <result property="flagStatoEnroll1" column="FLAG_STATO_ENROLL_1"/>          <result property="flagStatoEnroll2" column="FLAG_STATO_ENROLL_2"/>          <result property="flagStatoEnroll3" column="FLAG_STATO_ENROLL_3"/>          <result property="flagStatoEnroll4" column="FLAG_STATO_ENROLL_4"/>          <result property="flagStatoCo1" column="FLAG_STATO_CO_1"/>          <result property="flagStatoCo2" column="FLAG_STATO_CO_2"/>          <result property="flagStatoCo3" column="FLAG_STATO_CO_3"/>          <result property="flagStatoCo4" column="FLAG_STATO_CO_4"/>          <result property="UOG" column="UOG"/>          <result property="codiceFiliale" column="CODICE_FILIALE"/>          <result property="codiceModulo" column="CODICE_MODULO"/>          <result property="iban" column="IBAN"/>          <result property="dataInvioIban" column="DATA_INVIO_IBAN"/>          <result property="tipoPratica" column="TIPO_PRATICA"/>          <result property="dataFirma" column="DATA_FIRMA"/>          <result property="nominativoDenominazione" column="NOMINATIVO_DENOMINAZIONE"/>          <result property="servizioOkey1" column="SERVIZIO_OKEY_1"/>          <result property="servizioOkey2" column="SERVIZIO_OKEY_2"/>          <result property="servizioOkey3" column="SERVIZIO_OKEY_3"/>          <result property="servizioOkey4" column="SERVIZIO_OKEY_4"/>          <result property="dispositivoOkey1" column="DISPOSITIVO_OKEY_1"/>          <result property="dispositivoOkey2" column="DISPOSITIVO_OKEY_2"/>          <result property="dispositivoOkey3" column="DISPOSITIVO_OKEY_3"/>          <result property="dispositivoOkey4" column="DISPOSITIVO_OKEY_4"/>            <result property="codiceInizComm" column="CODICE_INIZ_COMM"/>          <result property="descInizComm" column="DESCRIZIONE_INIZ_COMM"/>          <result property="statoInizComm" column="STATO_INIZ_COMM"/>          <result property="canaleAcquisizione" column="CANALE_ACQUISIZIONE"/>          <result property="statoNagAdp" column="STATO_NAG_ADP"/>          <result property="codiceErroreAdp" column="CODICE_ERRORE_ADP"/>          <result property="messaggioErroreAdp" column="MESSAGGIO_ERRORE_ADP"/>          <result property="respintoEsito" column="RESPINTO_ESITO"/>          <result property="flagCarnetCruscotto" column="FLAG_CARNET_CRUSCOTTO"/>          <result property="rimescolamento" column="RIMESCOLAMENTO"/>          <result property="nuovoNdg" column="NUOVO_NDG"/>          <result property="idTrasferimentoFondi" column="ID_TRASFERIMENTO_FONDI"/>            <result property="sospeso" column="SOSPESO"/>          <result property="flagPortabilita" column="FLAG_PORTABILITA" javaType="java.lang.Boolean" jdbcType="VARCHAR"                  typeHandler="fideuram.reply.it.db.handler.YesOrNoHandler"/>          <result property="preNag" column="IS_PRE_NAG"/>            <result property="ndgPratica" column="NDG_PRATICA"/>          <result property="ndgDelegato1" column="NDG_DELEGATO1"/>          <result property="ndgDelegato2" column="NDG_DELEGATO2"/>          <result property="ndgDelegato3" column="NDG_DELEGATO3"/>          <result property="ndgDelegato4" column="NDG_DELEGATO4"/>          <result property="indirizzoAlternativo" column="CODICE_INDIRIZZO_ALTERNATIVO"/>          <result property="codiceAutorizzativo" column="CODICE_AUTORIZZATIVO"/>            <association property="professioni" resultMap="professioniResult"/>          <association property="attivita" resultMap="attivitaResult"/>          <association property="rapportoPb" resultMap="rapportoPbResult"/>          <association property="periodicita" resultMap="periodicitaResult"/>          <association property="formato" resultMap="formatoResult"/>          <association property="verifiche" resultMap="verificheResult"/>            <association property="superPratica" resultMap="superPraticaResult"/>          </resultMap>  

Excel sheet downloaded from google drive via asp.net core code is not in correct format

Posted: 20 Jul 2021 08:16 AM PDT

I want to download an Excel sheet from Google Drive using ASP.NET Core. The code is working, but the downloaded file doesn't have the same formatting than it has on Drive.

Here is the code:

public async Task<byte[]> DownloadFile(string fileId)  {      using var ms = new MemoryStream();      var url = $"https://docs.google.com/spreadsheets/d/{fileId}";        var scopes = new string[] { DriveService.Scope.Drive, DriveService.Scope.DriveFile, };      //Using Desktop client Approach      var clientId = "my client id";      var clientSecret = "my client secret";      var secrets = new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret };        try      {          var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(secrets, scopes, "CIS Test Server", CancellationToken.None, new FileDataStore("MyAppsToken")).ConfigureAwait(true);            using var _service = new DriveService(new BaseClientService.Initializer()          {              HttpClientInitializer = credential,              ApplicationName = "Demo App"          });            var file = _service.Files.Get(fileId);          file.MediaDownloader.Download(url, ms);      }      catch (Exception ex)      {          //log exception      }        return ms.ToArray();  }  

Here is the required formatting:

Required Format

Here is what we're getting:

Format we are getting

Also, there is a message shown when we open the downloaded file:

Javascript is not enabled on your browser so this file can't be opened enable and reload.

How to wrap VictoryBar with the container?

Posted: 20 Jul 2021 08:15 AM PDT

Is it possible to wrap each VictoryBar with the container?

Code: https://codesandbox.io/s/funny-cloud-gyt8i

enter image description here

I want to see something like this: enter image description here

And also be able to add some elements inside this container.

P.S. I also opened the same issue on GitHub: https://github.com/FormidableLabs/victory/issues/1904

Power Automate Flows - Filter Query not working as expected with multiple AND's

Posted: 20 Jul 2021 08:16 AM PDT

The filter query in this flow doesn't appear to be working as expected. I know for certain that the items it emails out afterwards have the first two toggles set to false. Is there something in the syntax that I'm missing? Or possibly in the date/time comparisons? This is my first dive into Power Automate, and its with someone elses flow. So any insight is greatly appreciated.

Filter Query

This is an example of what it looks like after running, and getting items where Confirmed = false.

Thank_x0020_You_x0020_Sent eq 'false' and Confirmed eq 'true' and EventDate lt  '2021-07-20T00:00:00.0000000' and EventDate ge '2021-07-19'  

If/else if on a text column in R

Posted: 20 Jul 2021 08:16 AM PDT

I'm a new to R and need help with the following.

Have Need
Male_18_24_pn 18_24
Male_25_39_pn 25_39
Male_40_64_pn 40_64
Male_65_84_pn 65_84
Male_85_plus_pn 85_plus
Female_18_24_pn 18_24

I need to create the "Need" column using the "Have" column, wondering how I can achieve this in R. As a initial effort, I tried the following code to test but got warning message and every cell of "Need" populated with "18_24":

if (str_detect(pe_1P_new$Have,"18_24")) {pe_1P_new$Need= "18_24"}  Warning message:  In if (str_detect(pe_1P_new$Have, "18_24")) { :    the condition has length > 1 and only the first element will be used  

Your help is greatly appreciated. Thanks in advance!

Configure nest-cli.json to include non TS file into the dist folder

Posted: 20 Jul 2021 08:15 AM PDT

I'm looking for a solution for several hours now:

I'm creating an email service with nestJS and nest mailer. Everything work find until I want to include a template with my mail. Those templates are hbs files located in src/mail/templates I know that nest doesn't include non TS files when compile so:

I tried to configure the nest-cli.json, following this link added :

    "compilerOptions": {  "assets":["**/*.hbs"],  "watchAssets": true,  }   

OR

"assets": [    { "include": "**/*.hbs","watchAssets": true },  ]  

My nest-cli.json file looks like this:

{    "collection": "@nestjs/schematics",    "sourceRoot": "src",    "compilerOptions": {    "assets": [        { "include": "**/*.hbs","watchAssets": true },      ]  }    }  

But nothing is copied into the dist folder. So I solve this with a modification of the package.json, added a cp command to do it manually but I don't think this is the right way do do it... Is anyone figured out include some non TS files with the assets

PS: hbs is for handlebar (mail templating)

Thanks for your help :)

Jest messageParent can only be used inside a worker

Posted: 20 Jul 2021 08:15 AM PDT

Is there a way to get a proper error message?

when i do

$npm test

and I intentionally break my code(cough cough remove a line of code) I get this message

src/redux/drivers/driver.saga.spec.js     Test suite failed to run        "messageParent" can only be used inside a worker          at messageParent (node_modules/jest-worker/build/workers/messageParent.js:46:11)  

I believe this is a meaningless error message and it would be nice to have something meaningful (=.

Here's my test

describe("DriverSocketFlow failed REASON:\n", () => {    let socket;    beforeEach(() => {      socket = new MockedSocket();      io.mockReturnValue(socket);    });    afterEach(() => {      jest.restoreAllMocks();    });    const mockGeneratorPayload = { payload: { name: "Royal Palms" } };    const generator = DriverSocketFlow(mockGeneratorPayload);      test("Checking if DriverSocketFlow was called with it's methods and disconnected gracefully", () => {      expect(generator.next(socket).value).toEqual(        call(connect, mockGeneratorPayload.payload.name)      );      expect(generator.next(socket).value).toEqual(        call(socketbug, mockGeneratorPayload.payload.name)      );      //disconnect gracefully      expect(generator.next(socket).value).toEqual(        fork(Read_Emit_Or_Write_Emit, socket)      );      expect(generator.next().value).toEqual(        take(DriversActionTypes.DRIVERS_SOCKET_OFF)      );      expect(generator.next(socket).value).toEqual(call(disconnect, socket));      expect(generator.next(socket).value).toEqual(call(disconnect, socket));        expect(generator.next().value).toEqual(cancel());    });  });  

It should say

DriverSocketFlow failed REASON:

Checking if DriverSocketFlow generator function was called and disconnected gracefully

Thanks! for looking!

.... So i think i figured it out! here's my new test

test("1. Connected to the socket successfully", () => {      expect(generator.next(socket).value).toEqual(        call(Connect_To_Socket, mockGeneratorPayload.payload.name)      );      expect(generator.next(socket).value).toEqual(        call(socketbug, mockGeneratorPayload.payload.name)      );    });    test("2. Read_Emit_Or_Write_Emit generator function operations for socket.on and emit", () => {      expect(generator.next(socket).value.payload.fn).toEqual(        fork(Read_Emit_Or_Write_Emit, socket).payload.fn      );    });  

but i think it's bug within npm test Don't know why it does it, but if you stop watch in npm test within package.json script tag and restart the test...It should work.....

"scripts": {      "test": "react-scripts test --watchAll=false",          },  

and also....! don't know if this step helped but i added jest.config.js within the root directory and removed it then all of a sudden it worked... " <- cough cough it probably doesn't do anything just keep restarting it ¯_(ツ)_/¯.... it worked for me"

Here's the full code

driver.saga.spec.js

FOR JSON PATH results in SSMS truncated to 2033 characters

Posted: 20 Jul 2021 08:15 AM PDT

I'm concatenating strings together using "for JSON path('')".

I have set the Tools->Options->SQL Server->Results to Grid options to max.

I have set the Tools->Options->SQL Server->Results to Text options to max.

Executing the query in Grid mode and copying the one row/one column results, I see the return value is limited to 2033 characters.

How can I ensure the returned value isn't truncated?

sqlanydb windows could not load dbcapi

Posted: 20 Jul 2021 08:16 AM PDT

I am trying to connect to a SQL Anywhere database via python. I have created the DSN and I can use command prompt to connect to the database using dbisql - c "DNS=myDSN". When I try to connect through python using con = sqlanydb.connect(DSN= "myDSN") I get

`Traceback (most recent call last):    File "<pyshell#5>", line 1, in <module>      con = sqlanydb.connect(DSN= "RPS Integration")    File "C:\Python27\lib\site-packages\sqlanydb.py", line 522, in connect      return Connection(args, kwargs)    File "C:\Python27\lib\site-packages\sqlanydb.py", line 538, in __init__      parent = Connection.cls_parent = Root("PYTHON")    File "C:\Python27\lib\site-packages\sqlanydb.py", line 464, in __init__      'libdbcapi_r.dylib')    File "C:\Python27\lib\site-packages\sqlanydb.py", line 456, in load_library      raise InterfaceError("Could not load dbcapi.  Tried: " + ','.join(map(str, names)))  InterfaceError: (u'Could not load dbcapi.  Tried: None,dbcapi.dll,libdbcapi_r.so,libdbcapi_r.dylib', 0)`  

Inverting a Hash's Key and Values in Perl

Posted: 20 Jul 2021 08:16 AM PDT

I would like to make the value the key, and the key the value. What is the best way to go about doing this?

No comments:

Post a Comment