Sunday, May 9, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Regex Exclude Character Class | Treat Character Class as String

Posted: 09 May 2021 08:03 AM PDT

I want to make sure regex treat certain character class as string and not as character class while drawing railroad diagram.

C:\\Windows\System32  

enter image description here

C:\\Users\Downloads  

enter image description here

Instead I want to display \S and \D as regular string respectively.

I am getting them in Javascript as a variable value and passing it to https://jex.im/regulex/ for draining the diagram.

Want to replace the conflict with the one which display full string.

My code does not work as it does not return the answer depending on my value

Posted: 09 May 2021 08:03 AM PDT

I am trying to get 2 different type of return depending on my value however if i do the following my code apparently does not read the value inside. However if i try to just return user.gettest(); it returns the value. How do i do it that in a way it will work as what i want according to my code.

public String getAlert(Context context) {      BusinessEntity user =BC.presentUser;          if(user.gettest()=="Negative"){             return "You have no alert";          }     else if(user.gettest()=="Positive"){       return "Someone who has visited your business recently has been tested positive";          }  return null;        }  

This is a snippet of my sql query where i get my value.

 String query = "Select Alert.Tested from User_Data join Visit_History on User_Data.NRIC=Visit_History.NRIC  join Alert on Alert.NRIC = Visit_History.NRIC WHERE Business = '" + user.getName() + "'  And Alert.Acknowledge=0";          Cursor cursor = db.rawQuery(query,null);          if(cursor != null && cursor.moveToFirst()){              BusinessEntity data = new BusinessEntity();                    data.test = cursor.getString(0);                return data;              }  

Why are my Laravel projects redirecting / getting to Index of / name

Posted: 09 May 2021 08:02 AM PDT

My Laravel projects were working fine until today and now all my new and old projects get the index of / page when I try to view them locally. One of my old projects is hosted on a Public Web Server and it works fine but I only get this error when using it with Xampp Apache. Any idea on how to fix this?

NGX Bootstrap Typeahead, with multiple template at once

Posted: 09 May 2021 08:01 AM PDT

I am using ngx-bootstrap typeahead for auto-complete. Templates are populating if the response is an array. But I have a response as an object. My response is something like

{    "set1": [],    "set2": [],    "set3": [],  }  

Now I'm expecting to render different templates for each set of array.

    <input (typeaheadLoading)="changeTypeaheadLoadingAlbum($event)"                          (typeaheadOnSelect)="typeaheadOnSelectAlbum($event)" [class.is-invalid]="searchFailed"                          [isAnimated]="true" [typeaheadAsync]="true" [typeaheadScrollable]="true"                          [typeaheadMinLength]="2" [typeahead]="rsAlbum$ "                          [typeaheadItemTemplate]="albumItemCustomTemplate" class="form-control form-control-lg"                          formControlName="albumItem" id="typeahead-http" placeholder="Enter name of album to search..."                          type="text" />  
  <ng-template #albumItemCustomTemplate class="suggestions">        <!-- for set1 -->      <ng-template let-index="index" let-model="item">          <div class="_dropdown-item"> {{r}} {{ model.name }} </div>      </ng-template>        <!-- for set2 -->      <ng-template let-index="index" let-model="item">          <h5>This is: {{model | json}} Index: {{ index }}</h5>            <div class="_dropdown-item">              {{ model.name }}              <span *ngIf="model.year != 0" class="year">- ({{ model.year }})</span>          </div>        </ng-template>  </ng-template>  

Any enhacement that needs to be done in case to populate both the templates style in single call. I am getting error Typeahead options.slice is not a function. It works if response is simple array.

Comparing element of a List object

Posted: 09 May 2021 08:01 AM PDT

I have an Object of AccountInfo which is having String type phone number. I need to compare each phone number within the list and return true if all the phone numbers are the same and return false if any one of them is different.

Below is the code snippet, The problem is I am always getting true value even if phone numbers are different. I know it is pretty basic but any help would be highly appreciated.

import java.util.Objects;    public class AccountInfo {        String accountName;      String phoneNumber;        public AccountInfo( String accountName, String phoneNumber) {          this.accountName = accountName;          this.phoneNumber = phoneNumber;      }        public String getAccountName() {          return accountName;      }        public void setAccountName(String accountName) {          this.accountName = accountName;      }        public String getPhoneNumber() {          return phoneNumber;      }        public void setPhoneNumber(String phoneNumber) {          this.phoneNumber = phoneNumber;      }        @Override      public boolean equals(Object o) {          if (this == o) return true;          if (o == null || getClass() != o.getClass()) return false;          AccountInfo that = (AccountInfo) o;          return Objects.equals(accountName, that.accountName) && Objects.equals(phoneNumber, that.phoneNumber);      }        @Override      public int hashCode() {          return Objects.hash(accountName, phoneNumber);      }        @Override      public String toString() {          return "AccountInfo{" +                  "accountName='" + accountName + '\'' +                  ", phoneNumber='" + phoneNumber + '\'' +                  '}';      }  }  

And here is my main class

    import java.util.ArrayList;  import java.util.List;    public class TestMain {        public static void main(String[]args){       List<AccountInfo> accInfoList = new ArrayList<AccountInfo>();          List<AccountInfo> accountInfoList =populateList(accInfoList);            System.out.println(accountInfoList);          boolean flag = isSamePhoneNumber(accInfoList);          if(flag) {              System.out.println("All Phone numbers are same");          }          else{              System.out.println("Some of the phone numbers are different");          }        }        public static List<AccountInfo> populateList(List<AccountInfo> accountInfoList){          AccountInfo accountInfo1 = new AccountInfo("Rohit Sharma", "123456");          AccountInfo accountInfo2 = new AccountInfo("Mayank Singh", "123456");          AccountInfo accountInfo3 = new AccountInfo("Sam Singh", "12378456");          AccountInfo accountInfo4 = new AccountInfo("Rahul Sharma", "123456");          accountInfoList.add(accountInfo1);          accountInfoList.add(accountInfo2);          accountInfoList.add(accountInfo3);          accountInfoList.add(accountInfo4);          return accountInfoList;        }        public static boolean isSamePhoneNumber(List<AccountInfo> accountInfoList){             boolean isSamePhoneNumberFlag = false;          for (int i = 0; i < accountInfoList.size(); i++) {              for (int j = i+1; j < accountInfoList.size(); j++) {                  // compare list.get(i) and list.get(j)                  System.out.println("i "+accountInfoList.get(i).getPhoneNumber()+" "+"i+1 "+accountInfoList.get(i+1).getPhoneNumber());                  if(accountInfoList.get(i).getPhoneNumber() == accountInfoList.get(i+1).getPhoneNumber()){                      isSamePhoneNumberFlag = true;                  }              }          }          return isSamePhoneNumberFlag;      }    }  

Output:

[AccountInfo{accountName='Rohit Sharma', phoneNumber='123456'}, AccountInfo{accountName='Mayank Singh', phoneNumber='123456'}, AccountInfo{accountName='sam Singh', phoneNumber='12378456'}, AccountInfo{accountName='Rahul Sharma', phoneNumber='123456'}]  i 123456 i+1 123456  i 123456 i+1 123456  i 123456 i+1 123456  i 123456 i+1 12378456  i 123456 i+1 12378456  i 12378456 i+1 123456  All Phone numbers are same  

How does the compiler understand which exception to run below?

Posted: 09 May 2021 08:02 AM PDT

    try {          Image image = new Image("MyComputer/Documents/Photos/estambul.jpg");            try {              //...                image.print();                throw new NullPointerException();          } finally {              System.out.println("FINALLY");              image.close();              throw new IOException();          }      } catch (IOException ex){          System.out.println("IO_EXCEPTION");          System.out.println(ex.getMessage());      }        System.out.println("THREAD IS CONTINUE");  

NullPointerException is not thrown here. However, there is no catch block that catches it. It looks like IOException is squashing NullPointerException. What is your comment? I did not understand.

Property does not exist on type 'string'.ts(2339)

Posted: 09 May 2021 08:01 AM PDT

So here is my code and I have this error and I don't understand why. I need some help here... I don't know why is this happening : Property does not exist on type 'string'.ts(2339) at :return users.find(u => u.userName === user.userName && u.password === user.password) on u.userName and u.password . PLease help .

import { Injectable } from '@angular/core';    @Injectable({    providedIn: 'root'  })  export class AuthService {      constructor() { }      authUser(user: any) {      let users : string[] = [];      if(localStorage.getItem('Users')) {        users = JSON.parse(localStorage.getItem('Users') || '{}');      }      return users.find(u => u.userName === user.userName && u.password === user.password)    }  }  

extract values from a variable in c++

Posted: 09 May 2021 08:01 AM PDT

I am new to c++ and I have to call a function from a library that returns the eigenvalues and eigenvectors of a matrix G; This is the template of the function

std::array< std::pair< Number, Tensor< 1, dim, Number > >, std::integral_constant< int, dim >::value >   eigenvectors   (const SymmetricTensor< 2, dim, Number > &  T,  const SymmetricTensorEigenvectorMethod  method = SymmetricTensorEigenvectorMethod::ql_implicit_shifts);  

I declared the the output "eigs" in this way:

std::array< std::pair< double, Tensor< 1, dim, double >>, 3> eigs;  

and i call the function in this way:

eigs = eigenvectors(G);  

my question is: the output "eigs" is a matrix or a vector? because when i try to extract eigs[0][0] i have an error:

"no match for 'operator[]' (operand types are 'std::array<std::pair<double, dealii::Tensor<1, 3> >, 3>::value_type' {aka 'std::pair<double, dealii::Tensor<1, 3> >'} and 'int') cout << eigs[0][0];"  

Any help would be appreciated,

Lorenzo

Error using GCC Intel Assembly: invalid operands (.text and UND sections) for +

Posted: 09 May 2021 08:01 AM PDT

I am writing inline assembly and I came across a error that I don't know how to fix. This part of the code raises an error. It is supposed to add "i" to "source" and "array" addresses, and copy the contents of the byte at "source" to "array".

int main()  {      char* _source = new char [1];      _source[0] = 1;      char* array = new char[1];      unsigned int i = 0;      __asm(          "mov eax, $[source] \n\t"          "add eax, $[i] \n\t"          "mov bh, [eax] \n\t"          "mov ecx, $[array] \n\t"          "add ecx, $[i] \n\t"          "mov [ecx], bh \n\t"          :          : "r" "source" (_source), "r" "array" (array), "r" "i" (i)          : "eax", "bh", "ecx"      );  }  

This code is executed using gcc.

gcc -m32 -masm=intel -o test.cpp   

And the errors that show up

C:\Users\geish\AppData\Local\Temp\ccMCDck3.s:34: Error: invalid operands (.text and *UND* sections) for `+'  C:\Users\geish\AppData\Local\Temp\ccMCDck3.s:35: Error: invalid operands (.text and *UND* sections) for `+'  C:\Users\geish\AppData\Local\Temp\ccMCDck3.s:37: Error: invalid operands (.text and *UND* sections) for `+'  C:\Users\user\AppData\Local\Temp\ccMCDck3.s:38: Error: invalid operands (.text and *UND* sections) for `+'  C:\Users\user\AppData\Local\Temp\ccMCDck3.s:56: Error: invalid operands (.text and *UND* sections) for `+'  C:\Users\user\AppData\Local\Temp\ccMCDck3.s:57: Error: invalid operands (.text and *UND* sections) for `+'  C:\Users\user\AppData\Local\Temp\ccMCDck3.s:59: Error: invalid operands (.text and *UND* sections) for `+'  C:\Users\user\AppData\Local\Temp\ccMCDck3.s:60: Error: invalid operands (.text and *UND* sections) for `+'  

Wrong anotation : x =0 , y =0 , < 0 or >1 , file: My all .txt files

Posted: 09 May 2021 08:02 AM PDT

I am using Yolo V4 to train the Gun Dataset for gun Object detection I have marked my object using bbox_tool the format of my .txt looks like :

0 0.8170028818443803 1.2137931034482758 0.46974063400576366 0.7172413793103448  

Training yoloV4 give me error

Wrong anotation : x =0 , y =0 , < 0 or >1    

Error

for each .txt file

Removing extra files generated while creating a dll project in visual studio

Posted: 09 May 2021 08:03 AM PDT

While creating a dll project in VS17, I see multiple files were created on initialization.

enter image description here

But whichever project on C++ I work on, I don't see any such files in their environment. How can I get rid of these files in my environment. Is there any workaround to remove them entirely or reduce these 4 files to one file to reduce mess?

Also before VS17 we used to have stdafx.h, it is mandatory to include this header but in few projects I couldn't find this file, is there any way to remove these initial files entirely?

php and mysql search two tables

Posted: 09 May 2021 08:02 AM PDT


I have two tables in a mysql-database that I want to search trough a php-page.
The two tables are ;
**main_pages**
main_page_name_short
main_page_title
main_page_description
main_page_keyword
main_page_index
main_page_body

and

**sub_pages**
sub_page_name_short
sub_page_title
sub_page_description
sub_page_keyword
sub_page_index
sub_page_body

I would like to do a search in the fields main_page_title, main_page_description, main_page title, sub_page_title, sub_page_description and sub_page_body with a string based upon $_POST['sfelt'] field from a form and display the result looping trough and also contains some of the other fields.

I have tried all sorts of tutorials that I have found online, but it does not work.

Anyone that have any ideas and maybe some help?

The code I'm trying now is (it will only return 0 results):

{      if (isset($_POST['sfelt'])) {          $sokefeltside = $_GET['s'];          $searchword1 = htmlspecialchars($sokefeltside, ENT_QUOTES);      } else {          $sokefeltside = "";          $searchword1 = "";      }  }    $servername = "xxxx";  $username = "xxxx";  $password = "xxxx";  $dbname = "xxxx";    // Create connection  $conn = mysqli_connect($servername, $username, $password, $dbname);  // Check connection  if (!$conn) {      die("Connection failed: " . mysqli_connect_error());  }    $sql = "SELECT * FROM main_pages WHERE main_page_description='%$searchword1%'";    $result = mysqli_query($conn, $sql);    if (mysqli_num_rows($result) > 0) {  // output data of each row      while ($row = mysqli_fetch_assoc($result)) {          echo "" . $row["main_page_title"] . " " . $row["main_page_description"] . " " . $row["main_page_body"] . "";      }  } else {      echo "0 results";  }    mysqli_close($conn);  

laravel ignore return redirect()

Posted: 09 May 2021 08:03 AM PDT

hi guys i'm trying to redirect user to bank but laravel is ignoring my return redirect

in here

public function checkout()  {            $order = $this->makeOrder();        $this->makePayment($order);        $pal = resolve(zarinpal::class);        $pal -> pay($order);        $this->basket->clear();        return $order;  }  

i'm calling pay() in zarinpal class :

public function pay(Order $order)  {      $this->redirectToBank($order);  }    private function redirectToBank($order)  {      $zarinpal = zarinpal()          ->amount($order->amount_rial)          ->request()          ->callback('http://lanjani/payment/zarinpal/callback')          ->description($order->code)          ->mobile($order->phone_number)          ->send();        if (!$zarinpal->success()){          return $zarinpal->error()->message();      }        $authority=$zarinpal->authority();        $input = [          'authority' => $authority      ];        $orderItem = Order::find($order->id);        $orderItem -> update($input);        return redirect()->away('https://sandbox.zarinpal.com/pg/StartPay/'.$authority);    }  

at the end of redirectToBank() user must redirect to bank but it is ignoring redirect and is returning $order in cheackout()

how to escape special characters in c# and jquery?

Posted: 09 May 2021 08:02 AM PDT

i want to escpae a "<" for returning result ,it's a list containing id id object and in conditions i want to add a special characters "< "to be replaced by "<" for returning result:

public class FormatObject {        public int Id { get; set; }        public int IdObject { get; set; }        public string Conditions { get; set; }        public List<int> SelectedAttributesId { get; set; }        public override string ToString() {                    string result = "[" + Id + "," + IdObject + ", \"" +  Conditions + "\"";          if (SelectedAttributesId != null)              result += ", [" + string.Join(",", SelectedAttributesId.ToArray()) + "]";            return result + "]";                    }       }  

} jquery:

 obj.$el.find('select').addClass('select-sm').select2({ dropdownAutoWidth: 'true', width: 'resolve', tag: true }); //, width: '100%'              obj.$el.find('input:not(:checkbox)').addClass('input-sm');//it'sthe lline for escape special characters but no working for me              obj.$el.find('input:checkbox').addClass('checkbox');  

search/getsjsonforquery:

public JsonResult GetJsonForQuery(ObjectJson serializedJson) {                                          if (serializedJson.MainObjects ==null){                  JsonResult result = Json(new { updated = DateTime.UtcNow.ToString("o"), errorNoItemSelected = true  },JsonRequestBehavior.AllowGet);                  result.MaxJsonLength = Int32.MaxValue;                  System.Diagnostics.Debug.WriteLine(serializedJson.MainObjects);                   return result;                                }  

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML

Posted: 09 May 2021 08:01 AM PDT

I have a query and i want to order by CreatationDateTime form requestFolders But I get this error.

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.

my query is :

with requests as    (  select IRF.Id as Id,      P.Id as ProcessId,      N'Investment' as [ServiceType],      IRF.FolderNumber as FolderNumber,      P.[Name] as [TypeTitle],      S.CustomerDisplayInfo_CustomerTitle as [CurrentStatus],      S.CustomerDisplayInfo_CustomerOrder as [CurrentStatusOrder],      RH.OccuredDateTime as [CurrentStatusDate],      IRF.CreationDateTime as [RequestDate],      IRF.RequestedAmount as [Amount],      (case when A.Id is not Null and s.sidetype='CustomerSide' then 1 else 0 end)  as [HasAction],      rank() over ( partition by IRF.Id order by rh.OccuredDateTime desc) as rnk  from      [Investment].[dbo].[InvestmentRequestFolders] as IRF inner join      [Investment].[dbo].[RequestHistories] as RH on IRF.Id = RH.ObjectId inner join      [Investment].[dbo].[Processes] as P on P.Id = RH.ProcessId inner join      [Investment].[dbo].[Step] as S on S.Id = RH.ToStep left join      [Investment].[dbo].[Actions] as A on A.StepId = RH.ToStep    where IRF.Applicant_ApplicantId = '89669CD7-9914-4B3D-AFEA-61E3021EEC30'    -- the error is here  order by IRF.CreationDateTime    ) SELECT t.Id,      max(t.ProcessId) as [ProcessId],      t.[ServiceType] as [ServiceType],      isnull(max(t.TypeTitle), '-') as [TypeTitle],      isnull(max(t.FolderNumber), '-') as [RequestNumber],      isnull(max(t.CurrentStatus), '-') as [CurrentStatus],      isnull(max(t.CurrentStatusOrder), '-') as [CurrentStatusOrder],      max(t.CurrentStatusDate)as [CurrentStatusDate],      max(t.RequestDate) as [RequestDate],      max(t.HasAction) as [HasAction],      isnull(max(t.Amount), 0) as [Amount]  FROM requests as t    where t.rnk = 1    GROUP BY t.Id  

The error is on Msg 1033, Level 15, State 1, Line 24

Please help me.

Flutter: How to post user feedback from feed back form to the Firestore Database

Posted: 09 May 2021 08:02 AM PDT

I am new to Flutter and trying to capture user feedback from the feedback form below to Firestore Database and have it displayed on a separate screen that reads from the Database and displays user feedback a report?

class FeedbackScreen extends StatefulWidget {      static const String routeName = 'feedback_screen';        @override      _FeedbackScreenState createState() => _FeedbackScreenState();      }       class _FeedbackScreenState extends State<FeedbackScreen> {     List<String> _questions = [      'Question 1',      'Question 2 ',      'Question 3',      'Question 4'      ];      List<int> _feedbackValue = [];        List<bool> _isFormFieldComplete = [];        String additionalComments;        @override      void initState() {      super.initState();      for (int i = 0; i < _questions.length; ++i) {        _feedbackValue.add(-1);        _isFormFieldComplete.add(false);      }     }        @override     Widget build(BuildContext context) {      return Scaffold(        appBar: AppBar(          title: Text(            getTranslated(context, "feedback_screen"),          ),        ),        body: SingleChildScrollView(          child: Padding(            padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 20.0),            child: Column(              crossAxisAlignment: CrossAxisAlignment.start,              children: [                Text(                  'Please choose appropriate emoji icon for your response',                  style: kFeedbackFormFieldTextStyle,                  textAlign: TextAlign.center,                ),                SizedBox(                  height: 10.0,                ),                Text(                  getTranslated(context, "tons_emoji"),                  style: kFeedbackFormFieldTextStyle,                ),                SizedBox(                  height: 10.0,                ),                Text(                  getTranslated(context, "alot_emoji"),                  style: kFeedbackFormFieldTextStyle,                ),                SizedBox(                  height: 10.0,                ),                Text(                  getTranslated(context, "soso_emoji"),                  style: kFeedbackFormFieldTextStyle,                ),                SizedBox(                  height: 10.0,                ),                Text(                  getTranslated(context, "notgood_emoji"),                  style: kFeedbackFormFieldTextStyle,                ),                Divider(                  height: 25.0,                ),              ]                ..addAll(                  _questions.asMap().entries.map((entry) {                    return FeedbackFormField(                      id: entry.key + 1,                      question: entry.value,                      groupValue: _feedbackValue[entry.key],                      radioHandler: (int value) =>                          _handleRadioButton(entry.key, value),                      error: _isFormFieldComplete[entry.key]                          ? 'This is a required field'                          : null,                    );                  }),                )                ..addAll([                  SizedBox(                    height: 10.0,                  ),                  TextField(                    decoration: kFeedbackFormFieldDecoration.copyWith(                      hintText: 'Additional Comments (Optional)',                    ),                    maxLines: 5,                    onChanged: (value) => additionalComments = value,                  ),                  SizedBox(                    height: 20.0,                  ),                  Row(                    mainAxisAlignment: MainAxisAlignment.center,                    children: [                      CustomRaisedButton(                        save: handleSubmitFeedback,                        title: 'Submit',                      ),                    ],                  ),                ]),            ),          ),        ),      );      }      void _handleRadioButton(int group, int value) {      setState(() {        _feedbackValue[group] = value;        _isFormFieldComplete[group] = false;      });     }       void handleSubmitFeedback() {      bool complete = true;      for (int i = 0; i < _feedbackValue.length; ++i) {        if (_feedbackValue[i] == -1) {          complete = false;          _isFormFieldComplete[i] = true;        } else {          _isFormFieldComplete[i] = false;        }      }      setState(() {});      if (complete == true) {        print(_feedbackValue);        print(additionalComments);        Navigator.pushReplacementNamed(context, SessionTwoScreen.routeName);      }     }     }  

Insert a column in specified position in a excel sheet and fill it with NaN values

Posted: 09 May 2021 08:02 AM PDT

import pandas as pd  import numpy as np  df.insert(7, "Photo Order", np.nan)  print(df.head)   pd.to_excel(df)  

I use this code and it updates the whole excel file but I want to write a specific column name "Order" in excel file.

How to get google Authorization Code using POSTMAN

Posted: 09 May 2021 08:02 AM PDT

I want to get the Authorization code to generate ACCESS TOKEN and REFRESH TOKEN for my Application. I'm trying to get the job done using POSTMAN. But this seems not working. I'm attaching a screenshot of POSTMAN. Can you tell me what I am doing wrong? Any useful suggestion or alternative solution is appreciated.

enter image description here

How can I amend this M query to make PowerBI get all the pages concurrently from a rest API?

Posted: 09 May 2021 08:03 AM PDT

This is my current code. It of course only returns the first page:

let   url = "https://id.myapi.ac.uk/connect/token",   GetJson = Web.Contents(url,       [           Headers = [#"Content-Type"="application/x-www-form-urlencoded;"],           Content = Text.ToBinary("client_id=mechamp&client_secret=notthislol&grant_type=client_credentials&scope=myapi")        ]   ),   FormatAsJson = Json.Document(GetJson),   // Gets token from the Json response   AccessToken = FormatAsJson[access_token],   AccessTokenHeader = "bearer " & AccessToken,   // Uses the GET search method using the bearer token from the previous POST oauth2/token method   GetJsonQuery = Web.Contents("https://data.api.myapi.ac.uk/activities?recordState=0&pageSize=100",       [           Headers = [#"Authorization"=AccessTokenHeader,                      #"api-version"="2",                      #"Accept"="application/json"]       ]   ),   FormatAsJsonQuery = Json.Document(GetJsonQuery),  Name"})  in      FormatAsJsonQuery  

I previously implemented this in Excel, using a curl request wrapped in a batch file created by VBA. Omitting the parts that already work in M query the batch file looked like this:

rem ommiting getting the token and setting it as %token%  set pagenum=1  set pagesize=100    curl "{https://data.api.myapi.ac.uk/activities?&page=%pagenum%&pageSize=1&recordstate=0}" -G  --header "api-version: 2" --header "Authorization: Bearer %token%" --header "Accept: application/json" --trace-ascii %userprofile%\api\totalpages.txt    for /F "delims=" %%a in ('findstr /I "totalCount" %userprofile%\api\totalpages.txt') do set "totalrecords=%%a"    set totalrecords=%totalrecords:,"t=%  set totalrecords=%totalrecords:0000: X-Pagination: {"currentPage":1,"pageSize":1otalCount":=%  rem del %userprofile%\api\totalpages.txt  set /a totalpages = %totalrecords%/%pagesize%  set /a totalpages = %totalpages%+1    start "" /min curl "{https://data.api.heat.ac.uk/activities?&page=%pagenum%&pageSize=%pagesize%&recordstate=0&sort=-activityStartDate}" -G --data-urlencode "fields=%fields%" --header "api-version: 2" --header "Authorization: Bearer %token%" --header "Accept: application/xml" --output %userprofile%\api\file%pagenum%.txt    :loop  set /A pagenum=pagenum+1  start "" /min curl "{https://data.api.heat.ac.uk/activities?&page=%pagenum%&pageSize=%pagesize%&recordstate=0&sort=-activityStartDate}" -G --data-urlencode "fields=%fields%" --header "api-version: 2" --header "Authorization: Bearer %token%" --header "Accept: application/xml" --output %userprofile%\api\file%pagenum%.txt  if %pagenum% LSS %totalpages% (goto :loop)    rem omitting lines that copy all the destination files into one and format into into a valid single json  exit  

You can see it first makes a request and dumps the raw output into a file, including the headers which tell me how many records there are, which I can then use to work out how many pages there are. I googled how to get the headers in PowerBI, but in their unwisdom it seems that Microsoft have decided nobody needs them and would do bad things with them.

How can I find out how many pages there are and request them all at once?

Things that I couldn't make work: https://medium.com/@marktiedemann/how-to-do-pagination-in-power-query-430460c17c78 "@odata.count" was not found was the error I received, apparently not supported by this API.

There was a reference to something called WebMethod.Head, which sounds interesting, but no documentation is provided on how to use it: https://msdn.microsoft.com/en-us/query-bi/m/webmethod-head

I tried to recreate this exact script which claims to receive the response headers, but the syntax didn't work https://community.powerbi.com/t5/Desktop/Retrieve-API-response-headers/td-p/423704?lightbox-message-images-641107=151369i21A62C85FABC9F9C

enter image description here

Apparent for some apis it's as simple as

= try GetJsonQuery[next_page_url] otherwise null  

And for me it's null!

Odata.Feed tells me that there is no Odata at this endpoint.

GetJsonQuery = OData.Feed("https://data.api.heat.ac.uk/activities?recordState=0&pageSize=100",   [       #"Authorization"="bearer " & "AccessToken",                  #"api-version"="2",                  #"Accept"="application/json"          ], [IncludeMetadataAnnotations="*"]  )  in      GetJsonQuery  

Any ideas?

Live update list view when data changes in database

Posted: 09 May 2021 08:01 AM PDT

I am creating an application with the help of GetX package. Its home screen is a list view. Data is updated via MQTT messages. when data comes from MQTT it will be updated in SQFLite. When DB changes I want to update my list view accordingly.

Home page.dart

  class AssetListBuilder extends StatelessWidget{        final AssetController ctrl = Get.find();          @override        Widget build(BuildContext context) {                return  GetBuilder<AssetController>(              builder: (controller) {                return ListView.builder(                    itemCount: ctrl.assetList.length,                    itemBuilder: (context, position) {                      return getCardView(ctrl.assetList[position]);                    });              }          );        }  }    Controller file.dart    class AssetController extends GetxController{      LoginRepository _loginRepository = LoginRepository();      AssetRepo _assetRepo = AssetRepo();    var assetList = List<Asset>();    @override    void onInit() {      super.onInit();      _loginRepository.connectMQTT();      fetchAssets();    }      void fetchAssets() async {      print('started');      var productResult = await _assetRepo.queryAllAssets();        this.assetList = productResult;      update();      }  }  

When a MQTT message receives, it will updates the Sqlite db and calls the fetchAssets() function. It will updates the assetList also. But my UI doesn't rebuild. What's wrong with this code?

how to prevent chromedriver upgrade

Posted: 09 May 2021 08:02 AM PDT

Using webdrivermanager 4.0.0, this is production and chrome stays at 76 and we don't want the chrome driver upgraded because it's incompatible. I have looked at avoidReadReleaseRepository and resolution.properties. The properties date was changed to 2020 after I changed it to 2121. What is the best way to never upgrade?

EdgeDriverManager MAC can not parse correct version by WebDriverManager

Posted: 09 May 2021 08:01 AM PDT

I faced some issue downloading msedgedriver from https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/ by WebDriverManager.

For example my installed version - Microsoft Edge is up to date. Version 80.0.361.111 (Official build) (64-bit) on MAC OS, but it did not display on the page that was parsed.

My solution was to add my CustomEdgeDriver and add new property to wdm.edgeDriverUrl=https://msedgewebdriverstorage.blob.core.windows.net/edgewebdriver?comp=list this link displays all available versions for EDGE.

I would like to ask guys from WebDriverManger, may you please fix this issue. Would be just great! Your service is cool. Thank you.

Pushing new FormGroup into FormArray marks dynamic FormGroup as invalid

Posted: 09 May 2021 08:02 AM PDT

I'm not sure if this is a bug, almost 90% certain it's not, but I want to know the logic behind something like this occuring.

I have a component, where let's say I'm initializing a FormGroup on the initialization of the component.

export class FooComponent implements OnInit {    form!: FormGroup;    foos!: FormArray;    constructor(      private fb: FormBuilder    ) {}      ngOnInit(): void {      this.form = this.fb.group({        foos: this.fb.array([]),      });    }      createFoo(): FormGroup {      return this.fb.group({        name: ['', Validators.required],        details: ['', Validators.required]      });    }      addFoo(): void {      this.foos = this.form.get('foos') as FormArray;      this.foos.push(this.createFoo());    }  }  

Let's say the addFoo() function gets called on a button click (which is how it is in my current application). Why is the newly pushed FormGroup marked as pristine but invalid? Even if there is a solid reason for this, shouldn't one assume that if we're dynamically generating a new FormGroup with validators, it should be considered valid upon creation or push? Is there a way around this? I don't want to have my users click a button to generate a new group of fields to fill out that are already marked invalid when they haven't done anything to those fields themselves. Is this a bug? I don't feel like my implementation is incorrect since I've followed the Angular Material documentation for this. I've tried setting the Validators.required manually after the new foo is pushed into the FormArray but this yields the same result.

Any opinions and/or tips?

File being corrupt when upload using multer node js

Posted: 09 May 2021 08:03 AM PDT

I implemented the multer upload example on restful using express. The following code is the server code.

var storage = multer.diskStorage({          destination: function (req, file, cb) {            cb(null, './files/')          },          filename: function (req, file, cb) {            crypto.pseudoRandomBytes(16, function (err, raw) {              cb(null, raw.toString('hex') + Date.now() + '.xsd');            });          }  });    var cpUpload = multer({ storage: storage, limits: {fileSize: 1000000}}).single('schema-file');    var app = express();   app.use(function(req, res, next) {          res.header("Access-Control-Allow-Origin", "*");          res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");          res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');          next();  });    app.post('/ws-api-designer-upload-files', cpUpload, function (req, res, next) {            console.log("filepath " + req.file.filename);          cpUpload(req,res,function(err){                if(err){                  res.set('Content-Type', 'application/json');                  res.end(JSON.stringify({                      status: 'ERROR 1',                      description: err.message                  }));                  return;              }else{                  res.set('Content-Type', 'application/json');                  res.end(JSON.stringify({                      status: 'SUCCESS 1',                      description: 'success'                  }));                  return;                           }          });    });  

But when i call this service using postman, the file are uploaded but when i compare original file between uploaded file, the uploaded file corrupted. I'm struggling on this problem for almost 1 week, please help.

Note that this problem comes when code running on windows server 2008 r2. So when i run this server code on localhost there was no any problem like corrupted file. And I only upload a xsd file which is 173kb in size.

This one is uploaded file (corrupt) uploaded file

This one is original file original file

Visual studio keyboard shortcut to go to end of line in Windows

Posted: 09 May 2021 08:02 AM PDT

I'm using visual studio community 2017. I want to remap the keyboard shortcut that moves the caret to the end of line (since I'm working on a laptop without the "End" key).

I know how to remap visual studio keys, but I can't find the menu item for it. Do you know what is the menu/action name for it so I can change it?

I can't find the answer on the web though it was asked several times.

Get github username through primary email

Posted: 09 May 2021 08:01 AM PDT

I'm using the PyGithub library to invite new member to the organization. The issue I faced is the next: In the scenario, when I know only users primary email, how can I retrieve his username to proceed invite accordingly? I know it is possible through UI, but can't find the corresponding call through API. Please, assist!

How to use the gecko executable with Selenium

Posted: 09 May 2021 08:01 AM PDT

I'm using Firefox 47.0 with Selenium 2.53. Recently they have been a bug between Selenium and Firefox which make code not working. One of the solution is to use the Marionnette driver.

I followed the instruction of this site to use this new driver with a RemotWebDriver but I keep having the error :

WARN - Exception: Exception in thread "main" org.openqa.selenium.WebDriverException: The path to the driver executable must be set by the webdriver.gecko.driver system property; for more information, see https://github.com/jgraham/wires. The latest version can be downloaded from ....

The code i've tried so far is very simple :

public class Test {      static WebDriver driver;      static Wait<WebDriver> wait;      public static void main(String[] args) throws MalformedURLException {          System.setProperty("webdriver.gecko.driver", "C:\\Selenium\\geckodriver.exe");          DesiredCapabilities cap = DesiredCapabilities.firefox();          cap.setCapability("marionette", true);          cap.setBrowserName("firefox");          driver = new RemoteWebDriver(new URL("http://192.168.117.135:5555/wd/hub"), cap);//true to enable the JS          wait = new WebDriverWait(driver, 3000);          final String url = "https://www.google.com/";            JavascriptExecutor js = (JavascriptExecutor) driver;            try {              driver.navigate().to(url);          } finally {              driver.close();          }      }  }  

I'm sure that the path to the geckodriver.exe is right and i don't see where i did the mistake.

EDIT 1: I tried the following code :

public class Test {      static WebDriver driver;      static Wait<WebDriver> wait;      public static void main(String[] args) throws MalformedURLException {          System.setProperty("webdriver.gecko.driver", "C:\\Selenium\\geckodriver.exe");            driver = new MarionetteDriver();          wait = new WebDriverWait(driver, 3000);          final String url = "https://www.google.com/";            JavascriptExecutor js = (JavascriptExecutor) driver;            try {              driver.navigate().to(url);          } finally {              driver.close();          }      }  }  

and it's working it seems that the problem come from the RemoteWebDriver and the gecko driver, any of you have news on it ?

Android Studio - Failed to apply plugin [id 'com.android.application']

Posted: 09 May 2021 08:01 AM PDT

I am working on an app. In my app there is no error in code but when I try to run my project it gives following errors.

Error:(1, 1) A problem occurred evaluating project ':app'.

Failed to apply plugin [id 'com.android.application']

Could not create plugin of type 'AppPlugin'.

I try this also Gradle is issuing an error "Could not create plugin of type 'AppPlugin'"

and this also Gradle errors in Android Studio

Following is my build.gradle file

apply plugin: 'com.android.application'  apply plugin: 'com.google.gms.google-services'    android {        compileSdkVersion 23      buildToolsVersion "21.1.2"        defaultConfig {          applicationId "com.praval.healthfreak"          minSdkVersion 15          targetSdkVersion 23          versionCode 1          versionName "1.0"      }      buildTypes {          release {              minifyEnabled false              proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'          }      }  }  dependencies {      compile fileTree(dir: 'libs', include: ['*.jar'])      testCompile 'junit:junit:4.12'        compile 'com.android.support:appcompat-v7:23.2.1'      compile 'com.google.android.gms:play-services:8.3.0'      compile 'de.hdodenhof:circleimageview:1.3.0'      compile 'com.android.support:design:23.2.1'      compile files('libs/YouTubeAndroidPlayerApi.jar')    }  

Selenium on Windows 10 Edge Browser [closed]

Posted: 09 May 2021 08:01 AM PDT

I have to run automation on Windows 10 'Edge' browser. Please let me know how to launch Edge browser in windows 10 using Java Selenium Web Driver.

How to avoid embedded (inline) images when saving outlook email attachments

Posted: 09 May 2021 08:02 AM PDT

I have written a method to save outlook email attachments into hard disk and convert the file into Base64String. When I was saving the attachments, the embedded (inline) images also getting saved, even though they are not REAL attachments. I wanted to save only the real attachments. Then I modified the method as follows. But now I'm getting an error from the line of ".OfType()".

Here is my code:

private string GetBase64StringForAttachments(Outlook.MailItem mailItem)          {              StringBuilder builder = new StringBuilder();              Outlook.Attachments mailAttachments = mailItem.Attachments;                            try              {                                  if (mailAttachments != null)                  {                                          Regex reg = new Regex(@"<img .+?>", RegexOptions.Singleline | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);                      MatchCollection matches = reg.Matches(mailItem.HTMLBody);                        for (int i = 1; i <= mailAttachments.Count; i++)                      {                          Outlook.Attachment currentAttachment = mailAttachments[i];                            bool isMatch = matches                            .OfType<Match>()                            .Select(m => m.Value)                            .Where(s => s.IndexOf("cid:" + currentAttachment.FileName, StringComparison.InvariantCultureIgnoreCase) >= 0)                            .Any();                            MessageBox.Show(currentAttachment.FileName + ": " + (isMatch ? "Inline Image" : "Attached Image"));                            if (currentAttachment != null)                          {                                                            string date = DateTime.Now.ToString("yyyymmddhhmmss");                              string path = "C:\\test\\" + date + currentAttachment.FileName; //ToDo: Create Folder                              currentAttachment.SaveAsFile(path);                                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);                              byte[] filebytes = new byte[fs.Length];                              fs.Read(filebytes, 0, Convert.ToInt32(fs.Length));                              string encodedData = Convert.ToBase64String(filebytes, Base64FormattingOptions.InsertLineBreaks);                              builder.Append(encodedData).Append(",");                                Marshal.ReleaseComObject(currentAttachment);                          }                      }                        if (builder.Length > 0)                      {                                                  string encodedAttachments = builder.ToString().Remove(builder.ToString().Length-1);                          return builder.ToString();                      }                      else                          return "";                    }                  else return "";              }              catch (Exception ex)              {                  Debug.DebugMessage(2, "Error in GetBase64StringForAttachments : in AddinModule " + ex.Message);                  return "";              }              finally              {                  Marshal.ReleaseComObject(mailAttachments);                              }          }  

This is the Error Message:

'System.Text.RegularExpressions.MatchCollection' does not contain a definition for 'OfType' and no extension method 'OfType' accepting a first argument of type 'System.Text.RegularExpressions.MatchCollection' could be found (are you missing a using directive or an assembly reference?)

What I need:

  1. I am not a big fan of LINQ. So, can you please advice me on this

  2. Is there a better way of doing this?

    I already tried followed the suggested answers for these questions and they did not work for me

Saving only the REAL attachments of an Outlook MailItem

Don't save embed image that contain into attachements (like signature image)

  1. Is there a way to use Redemption for distinguishing the real attachments?

No comments:

Post a Comment