Friday, March 26, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


JPQL TypedQuery - setParamer does not work

Posted: 26 Mar 2021 08:22 AM PDT

I am trying to fetch an entity which has a one-to-one relation using a named Query. My "where" condition is on the relation entity. I am giving a named parameter. When I execute the query it ignores the parameter passed and giving me all the records. I tried with positional parameter, it too didn't work.

Query @NamedQuery(name = "country.by.region", query = " select c from Country c join Region r on r.id = :regid")

Country Entity

public class Country {    @Id  @Column(name = "COUNTRY_ID")  private String id;  @Column(name = "COUNTRY_NAME")  private String name;  @OneToOne(targetEntity = Region.class, cascade = CascadeType.ALL)  @JoinColumn(name = "REGION_ID")  private Region region;...}  

Region Entity

public class Region {    @Id  @Column(name = "REGION_ID")  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "regSeq")  private int id;  @Column(name = "REGION_NAME")  private String name;...}  

DAO Impl

    @Override  public List<Country> findBy(Region region) {      TypedQuery<Country> query = getEntityManager().createNamedQuery("country.by.region", Country.class);      query.setParameter("regid", region.getId());      query.setMaxResults(30);      return query.getResultList();  }  

OptaPlanner - Create a good, initial solution by hand

Posted: 26 Mar 2021 08:22 AM PDT

Is there a way to create an initial solution for OptaPlanner by hand, in Java code?

I know that I can write the constructionHeuristic in the config XML to create a good initial solution.

But if I can write a better initial solution than OptaPlanner founds, is there a way to start the planning from my solution?

Thanks, Vilmos

"IndexError: list assignment index out of range" error

Posted: 26 Mar 2021 08:22 AM PDT

sub_marks = [] for i in range(5): print(i) sub_marks[i] = int(input("Enter marks in sub"+str(i+1)+" "))

avg_marks = (sub_marks[0]+sub_marks[1]+sub_marks[2]+sub_marks[3]++sub_marks[4])/100 print(sub_marks)

This is showing "IndexError: list assignment index out of range" error. Can somebody plz point out the error?

Gulp : SyntaxError: missing ) after argument list

Posted: 26 Mar 2021 08:22 AM PDT

I have a project which builds successfully on an Apple Mac but produces the following error when trying to run a gulp task on Windows:

project\node_modules\.bin\gulp:2  basedir=$(dirname $(echo "$0" | sed -e 's,\\,/,g'))          ^^^^^^^    SyntaxError: missing ) after argument list      at wrapSafe (internal/modules/cjs/loader.js:979:16)      at Module._compile (internal/modules/cjs/loader.js:1027:27)      at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)      at Module.load (internal/modules/cjs/loader.js:928:32)      at Function.Module._load (internal/modules/cjs/loader.js:769:14)      at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)      at internal/main/run_main_module.js:17:47  

package.json

"scripts": {      "gulp": "node node_modules/.bin/gulp",      "build-local": "npm run gulp build-local",  },  "devDependencies": {      "gulp": "3.9.1",      "gulp-angular-templatecache": "~2.0.x",      "gulp-autoprefixer": "^4.0.0",      "gulp-concat": "~2.6.x",      "gulp-live-server": "^0.0.31",      "gulp-minify-html": "~1.0.x",      "gulp-sass": "^3.1.0",      "gulp-sourcemaps": "~2.5.x",      "gulp-stylelint": "^5.0.0",      "gulp-uglify": "~2.1.x",  

It it helps I'm using an old version of Node (10.0.0) because the project is quite dated

How to find sum of a field by finding chronological order in another field in R?

Posted: 26 Mar 2021 08:22 AM PDT

I have an excel file with below columns

enter image description here

I want to add duration field for each member (A and B) date wise.

In here I want data like:

UserName Date Duration

A 22-07-2019 2

B 22-07-2019 1

I tried below code but results are not as desired. The date field is sorted like text field (not chronological). Ex: 01-01-2020 then 01-02-2020 instead 01-01-202 then 02-01-2020

Static IP for OTA update of ESP32 through web server

Posted: 26 Mar 2021 08:22 AM PDT

Is there any way to create a header file with static IP for OTA update of ESP32 through web server? I am working on a code which already uses wifi and API key to send data to ASKsensors cloud. Now I want to make it OTA capable. So that I can update the firmware remotely. For this project, the module will be kept far away and in different network. I found that it will be required to give a static IP. Can I make a static IP permanently so that it will not be required to include the code in all versions?

HOC : Type 'Element' is not assignable to type 'FC<P>'

Posted: 26 Mar 2021 08:21 AM PDT

I have an HOC which work great when used on the component export directly, such as export default RequireAuth(Home). However, I am trying to extract my Authentication Logic from my component and to use it in the routes definition. It would be easier to test the components this way. I need to return a FC to match with our Route interface. We have a route object, which is an array of the Route Interface.

The Route interface :

export type Route = {    name: string    path: string    component: React.FC // I need to match this    subroutes?: Route[]    permissions?: PermissionType[]  }  

This array of Route interface is used in our Switch like this :

<Switch>    {routes.map((route, index) => {      return <Route exact {...route} key={index} />    })}  </Switch>  

The RequireAuth HOC :

interface WrappedComponentProps {    [key: string]: any //eslint-disable-line    children: React.FC  }    export function RequireAuth<P extends WrappedComponentProps>(    WrappedComponent: ComponentType<P>  ) {    return function Comp({ children, ...props }: P): React.FC<P> {      const [hasGroup, setHasGroup] = useState<boolean>()      const { authUser } = useContext(UserContext)      const history = useHistory()      const location = useLocation()        useEffect(() => {        if (!authUser) {          history.push('/login')        } else {          //Do stuff      }, [authUser, hasGroup])        const isAuthorized = authUser && hasGroup        if (!isAuthorized) {        return <Fragment></Fragment> // TODO        //Type 'Element' is not assignable to type 'FC<P>'.      }        //https://stackoverflow.com/questions/54580435/react-typescript-hocs-why-i-get-type-is-not-assignable-to-type-p      /* Starting with 3.2 the behaviour of the spread operator for generics has changed. Apparently the type of props       gets erased as a negative side effect, but you can work around that by casting it back to P using {...props as P}       when spreading back into the wrapped component. */      return <WrappedComponent {...(props as P)}>{children}</WrappedComponent>      //Type 'Element' is not assignable to type 'FC<P>'.    }  }  

The error I am getting in my browser :

Type 'Element' is not assignable to type 'FC<P>'.    Type 'Element' provides no match for the signature '(props: PropsWithChildren<P>, context?: any): ReactElement<any, any> | null'.  

CodeMirror markdown mode get all used languages to load modes dynamically

Posted: 26 Mar 2021 08:21 AM PDT

I have a CodeMirror instance where i do not load all the possible modes upfront, i would like to load them dynamically for the languages that are used in the fenced code blocks in markdown.

Is there somehow a (built-in) possibility to get all the languages that are used in markdown, so that i can load them when needed?

Generate a list of unique values from a list if another cell has a value

Posted: 26 Mar 2021 08:21 AM PDT

I hope I can explain this correctly; I am fairly good with excel, new to VBA but I have a solid understanding to put some functions together but I am stuck on one issue. I have pulled together from my research this formula but it is not quite there.

Table 1 is pulling from another worksheet a list of data for trailer loads that are destined for a specified location. This works perfectly.

Table 2 is a list of trailers that are not found in Table 1 from the list that is on another worksheet.

The column on the right as this formula to determine if it already exists in Table 1. Problem I am having is I want it to also validate if the trailer has a destination assigned to that trailer; if there is no destination assigned, the trailer is empty and I don't want to include that trailer in my list. I need the formula to continue validating what trailers have a destination assigned to that trailer number, validate that it doesn't exist in Table 1, then generate that trainer #.

Here is my formula: =IFERROR(IF('Trailers On Hand'!B2<>" ",INDEX('Trailers On Hand'!$C$2:$C$836, SMALL(IF(COUNTIF($B$4:$AO$87, 'Trailers On Hand'!$C$2:$C$836)=0, MATCH(ROW('Trailers On Hand'!$C$2:$C$836), ROW('Trailers On Hand'!$C$2:$C$836)),""), ROWS($A$1:A1))),""),"")

enter image description here

Dependening on legacy jar in Java 9 Module System library using gradle

Posted: 26 Mar 2021 08:21 AM PDT

Problem

How do you create a java library jar that both:

  • is java module (has module-info)
  • has a depending legacy (non-module) jar. (like commons-exec)?

The dependency is an implementation detail - should not be exported.

Sources

Having the following build.gradle (using gradle-6.8):

plugins {      id 'java-library'  }    group = 'test'  version = '0.0.1-SNAPSHOT'  sourceCompatibility = '15'    repositories {      mavenCentral()  }  java {      modularity.inferModulePath = true  }    dependencies {      implementation 'org.apache.commons:commons-exec:1.3'  }  

and the following module-info.java:

module test.module {      requires commons.exec;  }  

Errors

I'm getting the following compile error:

module-info.java:2: error: module not found: commons.exec      requires commons.exec;                      ^  

If I don't include requires commons.exec then the error becomes:

error: package org.apache.commons.exec is not visible  import org.apache.commons.exec.CommandLine;                           ^    (package org.apache.commons.exec is declared in the unnamed module,     but module test.module does not read it)  

commons.exec module name?

Running jar --file=commons-exec-1.3.jar --describe-module does output:

No module descriptor found. Derived automatic module.    commons.exec@1.3 automatic  requires java.base mandated  contains org.apache.commons.exec  contains org.apache.commons.exec.environment  contains org.apache.commons.exec.launcher  contains org.apache.commons.exec.util  

So commons.exec looks like a valid module name for commons-exec-1.3.jar. Intelij Idea seem to agree and does auto-complete it in module-info.java. Though it fails at build time.

Union Results of Multiple OPENJSON calls

Posted: 26 Mar 2021 08:21 AM PDT

I have a table that stores 1 json object per row, I want to call OPENJSON on the json object stored in each row and union together all of the results. I don't know the number of rows I will have ahead of time.

Here some example data to reference

    DROP TABLE #tmp_json_tbl    DECLARE @json1 NVARCHAR(2048) = N'{      "members": [          {              "name": "bob",              "status": "subscribed"          },          {              "name": "larry",              "status": "unsubscribed"          }      ]  }';    SELECT @json1 as json_obj,1 as jid into #tmp_json_tbl     INSERT into #tmp_json_tbl  VALUES ( N'{      "members": [          {              "name": "bob",              "status": "subscribed"          },          {              "name": "larry",              "status": "unsubscribed"          }      ]  }',2 );    SELECT * from #tmp_json_tbl      --how can i recursively union together results for all values of jid?  -- I could use a cursor but I would rather figure out a way to do it using a recursive cte  SELECT * FROM OpenJson((SELECT json_obj from #tmp_json_tbl where jid=1), '$.members')  WITH (                  name   VARCHAR(80)   '$.name',                 mstatus  varchar(100)       '$.status'       )```  

When Reloading by Browser[F5] then,a state always will be undefined

Posted: 26 Mar 2021 08:21 AM PDT

state.firebase.profile always is undefine when I reload by browser. Somehow, it goes well except for F5 as far as I can see.

I check by using. console.log("TEST HERE"+ JSON.stringify(this.props.profile.name));

enter image description here

Where should I modify it...

class ReagtTagSample extends Component {    constructor(props) {      super(props);      this.state = {        porco:""        tags: [{ id: 'Yugoslavia', text: 'Yugoslavia' }, { id: 'India', text: 'India' }],        suggestions: [          { id: "England", text: "England" },          { id: "Mexico", text: "Mexico" },        ],      };    componentDidMount=()=>{      console.log("TEST HERE"+ JSON.stringify(this.props.profile.name));    }      handleAddition(tag) {      this.setState((state) => ({ tags: [...state.tags, tag] }));    }      handleDrag(tag, currPos, newPos) {      const tags = [...this.state.tags];      const newTags = tags.slice();        newTags.splice(currPos, 1);      newTags.splice(newPos, 0, tag);      this.setState({ tags: newTags });    }  //ommit    render() {      const { auth, authError, profile } = this.props;      return (  //ommit  const mapStateToProps = (state) => {    return {      auth: state.firebase.auth,      authError: state.auth.authError,      profile: state.firebase.profile,    };  };    const mapDispatchToProps = (dispatch) => {    return {      profileUpdate: (user) => dispatch(Update(user)),    };  };    export default connect(mapStateToProps, mapDispatchToProps)(Update);  
Update= (user) => {      return (dispatch, getState, { getFirebase, getFirestore }) => {          const firestore = getFirestore();           const firebase = getFirebase();          const profile = getState().firebase.profile;          const authorId = getState().firebase.auth.uid;          firestore.collection('users').doc(authorId).set({                  name: user.userName,                  tags:user.tags,              }).then(() => {              dispatch({ type: 'PROFILE_UPDATE_SUCCESS' })          }).catch(err => {              dispatch({ type: 'PROFILE_UPDATE_ERROR', err })          })      }  }  

I would like to use profile.name as default input name...

          <div className="input-field">              <label htmlFor="userName">DisplayName</label>              <input                type="text"                id="userName"                value={this.state.userName}                onChange={this.handleChange}              />  

How to scroll to current time without any event in CalendarKit Swift

Posted: 26 Mar 2021 08:21 AM PDT

I'm not created any event and need to scroll current time like scroll working for first event.

how to late bind various applications in outlook

Posted: 26 Mar 2021 08:20 AM PDT

I have a complex vba macro that uses the following references. I don't know how to late bind all of these properly to the different objects I use. How can I research what is the proper late binding convention?

  • Outlook 16.0
  • Word 16.0
  • Regular Expressions 5.5

For example, I am declaring the following variables in my macro using early binding, how can I find the equivalent late binding convention?

  • dim myNameSpace as outlook.namespace --> set myNameSpace = Application.GetNamespace("MAPI")
  • dim myInbox as outlook.folder --> set myInbox = myNameSpace.Folders("name of folder")
  • dim myItems as outlook.items --> set myItems = myInbox.Items
  • dim wrdDoc as word.document
  • dim regExp as new RegExp --> regExp.Pattern = "pattern"

Any help or guidance would be appreciated!

thank you!

Find the smallest integer greater than n whose digits are all different from all digits of n

Posted: 26 Mar 2021 08:20 AM PDT

I recently came across the following problem, while practicing my coding skills: "Find the smallest integer greater than n whose digits are all different from all digits of n". For example:

  • 2 -> 3
  • 958 -> 1000
  • 901 -> 2222
  • 654321 -> 700000

A fairly obvious shortcut is that if n has a single digit, then the result is always n + 1, but I can't get much insights on the general case. I think it might be useful to extract all the digits of n and to consider only the other available digits to build the results, but I don't know where to go from here.

Does anyone have any idea? C++ is the language of choice but I'm more interested in the algorithm itself.

Receipt on dev c++ from food menu

Posted: 26 Mar 2021 08:21 AM PDT

hi im a beginner in coding and need a little bit help on my homework. Please be nice to me huhu. Im writing a code for a menu and need to display receipt of the choice. the problem is that i dont know how to display the code for food as a whole in the receipt for example code M as meatball in the receipt. this are my code.

#include <iostream>  #include <vector>  #include <string>  #include <fstream>  #include <iomanip>  using namespace std;    int num;  int main(void);  void calcPrice();  void addItem();  float Meatball = 8.00, Chickenslice = 7.50, Pepperoni = 7.00, Tuna = 6.50, E = 1.50;  float price;  float tax;  float totalprice;  float receipt;  char answer = 'y';    int main()  {      char choice = ' ';        cout << "    SANDWICH    CODE    PRICE(RM)    ADDITIONAL CHEESE(RM)                  \n ";          cout           << " +============================================================+                  \n " << endl;          cout           << "     Meatball    M       " << setprecision(2) << fixed << Meatball           << "\n" << endl;      cout << "Chicken slice    C       " << Chickenslice << "         " << E << " each\n" << endl;      cout << "    Pepperoni    P       " << Pepperoni << "\n" << endl;      cout << "         Tuna    T       " << Tuna << "    \n    " << endl;        calcPrice();        cout << "Quantity :" << endl;      cin >> num;        addItem();        ofstream outputFile;      outputFile.open("BiteMeReceipt.txt");      cout << "Bill was printed to BiteMeReceipt.txt " << endl;      outputFile << "BiteMe Receipt" << endl;      outputFile << "================" << endl;      outputFile << "Sandwich:" << choice << endl;      outputFile << "Add Cheese:" << answer << endl;      outputFile << "Total Price :RM" << totalprice << endl;      outputFile << "New Price + Gov Tax :RM" << receipt << endl;      outputFile << "Thank you and please come again.\n" << endl;      outputFile.close();  }    void calcPrice()  {        char choice = ' ';        cout << "Choose available sandwich code (M/C/P/T) :" << endl;      cin >> choice;        switch (choice) {        case 'M':          price = price + Meatball;          break;        case 'C':          price = price + Chickenslice;          break;        case 'P':          price = price + Pepperoni;          break;        case 'T':          price = price + Tuna;          break;        default:          calcPrice();          break;      }  }    void addItem()  {      cout << "Additional Cheese ? (y/n):" << endl;      cin >> answer;        if (answer == 'Y' || answer == 'y')          cout << "Add RM1.50 for each" << endl;      totalprice = (price * num) + (num * E);        if (answer == 'N' || answer == 'n')          totalprice = (price * num);        tax = 0.06 * totalprice;      receipt = tax + totalprice;        cout << "Total Price (RM):" << totalprice << endl;      cout << "New price + Gov tax (6%):RM" << receipt << endl;  }  

i should get an example of receipt like sandwich : Tuna for choice but it does not display anything

How to free char 3D array?

Posted: 26 Mar 2021 08:22 AM PDT

How to free memory in such a string array?

char** test[5];  for(int i=0;i< 5;i++)          test[i] = malloc(sizeof(char*) * 4);  for(int i=0;i< 4;i++){          test[0][i] = malloc(sizeof(char) * 50);          test[1][i] = malloc(sizeof(char) * 50);          test[2][i] = malloc(sizeof(char) * 50);          test[3][i] = malloc(sizeof(char) * 50);          test[4][i] = malloc(sizeof(char) * 50);  }  

Cuz I do something like that and I have memory leaks

for (int i = 0; i <4; i++)                  {                      free(test[0][i]);                      free(test[1][i]);                      free(test[2][i]);                      free(test[3][i]);                      free(test[4][i]);                    }  

HTML button not calling the function

Posted: 26 Mar 2021 08:22 AM PDT

I am quite new to JavaScript so I don't know a lot about it. I have been trying to call a function using a button, but nothing happens when I click on it. I would really appreciate your help :) Here is my code:

.  .  .  .  <button type="button" id="button2" class="btn btn-secondary" Secondary rows="5"            *ngIf="!name.valid || birthday.valueAsDate>todayDate || !validGender || !birthday">Add Horse    </button>    .  .  .  .  <script language="javascript" type="text/javascript">      function createErrorString() {        var errorText = "empty";        var name = document.getElementById('name');      if (!name.valid) {        errorText = errorText + '\n' + "Please enter a name.";      }        var birthday = document.getElementById('birthday');      if (!birthday) {        errorText + '\n' + "Enter a birthdate that is not in the future.";      }      var gender = document.getElementById('gender');      if (gender.selectedIndex <= 0) {        errorText = errorText + '\n' + "Select a gender.";        validGender = false;      }      alert("Horse could not be added. Please meet the following requirements: " + errorText);    }      var btn = document.getElementById("button2");    btn.addEventListener("click", createErrorString);    </script>  

How to access methods after Instantiating a player prefab in GameManager?

Posted: 26 Mar 2021 08:21 AM PDT

I am fairly new to unity and am trying to make a game based on mapbox location based game. Right now I have an welcome scene where they choose a name and a character (male or female), which works perfectly fine and they chosen character shows on the map.

Now, I have three scripts: GameManager, Player & BonusXP. In the GameManager I am instantiating the chosen player and place them on the map.

In the player script I have certain variables such as xp and level and methods like AddXP().

In the bonusXP script which I attached to a random object, when that one is clicked there needs to be added a certain amount of XP to the player. In this example I used 10. Now I had it working fine until I added the choose a character functionality. Before I would drag the player into the GameManager serialised field and stuff worked. Now that that one is gone. It stopped working. How do I add XP to a instantiated Player chosen by the user?

The Gamemanager script:  using System.Collections;  using System.Collections.Generic;  using UnityEngine;    public class GameManager : Singleton<GameManager> {        public GameObject[] players;      public Transform spawnPoint;      private void Awake() {          int selectedC = PlayerPrefs.GetInt("selectedcharacter");          GameObject prefab = players[selectedC];          GameObject clone = Instantiate(prefab, spawnPoint.position, Quaternion.identity);          clone.AddComponent<Player>(); //attaches player script to the clone      }    //  public Player CurrentPlayer {  //      get  //      {  //          if (currentPlayer == null) {  //          }  //          return currentPlayer;  //      }  //  }      }  `  

The BonusXP Script:

using System.Collections;  using System.Collections.Generic;  using UnityEngine;    public class XPBonus : MonoBehaviour {        [SerializeField] private int bonus = 10;        private void OnMouseDown() {          GameManager.Instance.CurrentPlayer.AddXp(bonus);          Destroy(gameObject);      }  }  

The necessary parts of player script:

public class Player : MonoBehaviour {        [SerializeField] private int xp = 0;      [SerializeField] private int requiredXp = 100;      [SerializeField] private int levelBase = 100;      public void AddXp(int xp) {          this.xp += Mathf.Max(0, xp);      }  }  

How to display data in form of json?

Posted: 26 Mar 2021 08:22 AM PDT

I want to display my data in the form of json. I used an array to save my object and echo json_encode($myArr); . But I got nothing. Anyone can help me pls!!; Here is my PHP code:

<?php  $connect= mysqli_connect("localhost","dinh","","thietbi");  $query="SELECT * FROM loaisanpham";  $result=mysqli_query($connect,$query);  $myArr=[];  while ($row= mysqli_fetch_array($result)) {     array_push($myArr,new LoaiSp(      $row["id"],      $row["tenloaisanpham"],      $row["hinhanhloaisanpham"]));        }  echo json_encode($myArr);  class LoaiSp{      function LoaiSp($id,$tenloaisp,$hinhanhloaisp){          $this->id =  $id;          $this->tenloaisanpham = $tenloaisanpham;          $this->hinhanhloaisanpham =  $hinhanhloaisp;      }  }  ?>  

The result when I follow this link http://localhost/server/getdata.php is: [{},{}]

Is it possible to use same hostname with two multiple Ingress resources running in different namespaces?

Posted: 26 Mar 2021 08:21 AM PDT

I want to use the same hostname let's say example.com with multiple Ingress resources running in different namespaces i.e monitoring and myapp. I'm using Kubernetes nginx-ingress controller.

haproxy-ingress.yaml

apiVersion: networking.k8s.io/v1  kind: Ingress  metadata:    name: haproxy-ingress    namespace: myapp    annotations:      kubernetes.io/ingress.class: "nginx"    spec:    tls:    - hosts:      # fill in host here      - example.com          rules:      - host: example.com        http:          paths:            - path: /              pathType: Prefix              backend:                service:                  name: haproxy                  port:                    number: 80    

grafana-ingress.yaml

apiVersion: networking.k8s.io/v1  kind: Ingress  metadata:    name: grafana-ingress    namespace: monitoring    annotations:      nginx.ingress.kubernetes.io/use-regex: "true"  spec:    tls:    - hosts:      - example.com          rules:      - host: example.com        http:          paths:            # only match /grafana and paths under /grafana/            - path: /grafana(/|$)(.*)              pathType: Prefix              backend:                service:                  name: grafana                  port:                    number: 3000    

When I'm doing curl example.com then it is redirecting me to the deployment running in namespace one(as expected) but when I'm doing curl example.com/grafana then still it is redirecting me to namespace one deployment.

Please help.

Parsing and Modifying local HTML with Node.js

Posted: 26 Mar 2021 08:22 AM PDT

I kind of have a weird question that's probably very basic. I'm pretty new to web development and front-end stuff in general.

Premise First of all, my only real other experience with JS is using node.js to make a discord bot, as well as use D3 to make some basic GUI stuff. I'm trying to make a GitHub pages wiki for a game I play. In the game, there are units, which I've encoded as JSON files, as well as a folder of images. All I really want is a basic index.html page with links to HTML pages for all the units. But since units are constantly being added, I am constantly updating the JSON so I want to be able to generate the HTML files for the units as well as updating index.html automatically.

The Method Since all I really know is node.js, I've been trying to use that to make the HTML files. What I'm trying to do right now is this hacky thing of using fs to read in the HTML files, then use jsdom to parse them into something I can use jquery to edit. After that I just want to serialize the jsdom into a string and use fs to write to the file. Right now I can successfully deserialize with jsdom and serialize the html back with fs. But I'm having trouble editing the actual HTML.

Question First of all, I have no idea whether this is a good way to do what I've described at all, I'm still in the very early stages, so I'm welcome to suggestions on other libraries or just completely redoing the project. The closest thing I've found that's similar to what I want to do is this GitHub snippet from 10 years ago, unfortunately, I'm sure a lot of it is outdated and my puny knowledge is not able to adapt to this to modern js: https://gist.github.com/clarkdave/959811. I was wondering whether someone could do that for me, or suggest a better way of doing what I'm trying to do. You can see what I'm currently trying to do here: https://github.com/aayu3/ATBotJSONDependencies

Identify duplicated values in the same columns across undefined sheets using Apps Script

Posted: 26 Mar 2021 08:21 AM PDT

I have a spreadsheet that is growing undefined in number of sheets. I want to highlight duplicated values in the same columns across all undefined sheets. I can do it with conditional formating, but as the number of sheets will grow a lot, this approach isn't valid.

I tried something like:

var ss = SpreadsheetApp.getActiveSpreadsheet();  var sheet = ss.getActiveSheet();  var lastRow = sheet.getLastRow();  var lastColumn = sheet.getLastColumn();    function readSheetData() {    var rowRange = sheet.getRange(1, 1, lastRow, lastColumn);    var rangeArray = rowRange.getValues();    // Convert to a one dimensional array    rangeArray = [].concat.apply([], rangeArray);    return rangeArray;  }    // Creates an array with data from a chosen column  function readColumnData(column) {    var columnRange = sheet.getRange(1, column, lastRow);    var rangeArray = columnRange.getValues();    // Convert to one dimensional array    rangeArray = [].concat.apply([], rangeArray);    return rangeArray;  }    // Creates an array with data from a chosen row  function readRowData(row) {    var rowRange = sheet.getRange(row, 1, 1, lastColumn);    var rangeArray = rowRange.getValues();    // Convert to one dimensional array    rangeArray = [].concat.apply([], rangeArray);    Logger.log(rangeArray);    return rangeArray;  }    // Sort data and find duplicates  function findDuplicates(data) {    var sortedData = data.slice().sort();    var duplicates = [];    for (var i = 0; i < sortedData.length - 1; i++) {      if (sortedData[i + 1] == sortedData[i] && sortedData[i] != "") {        duplicates.push(sortedData[i]);      }    }    return duplicates;  }    // Find locations of all duplicates  function getIndexes(data, duplicates) {    var column = 2;    var indexes = [];    i = -1;    // Loop through duplicates to find their indexes    for (var n = 0; n < duplicates.length; n++) {      while ((i = data.indexOf(duplicates[n], i + 1)) != -1) {        indexes.push(i);      }    }    return indexes;  }    // Highlight all instances of duplicate values in a sheet  function highlightSheetDuplicates(indexes) {    var row;    for (n = 0; n < indexes.length; n++) {      row = 1;      if (indexes[n] > lastColumn) {        row = Math.floor(indexes[n] / lastColumn);        indexes[n] = indexes[n] - lastColumn * row;        row++;      }      sheet.getRange(row, indexes[n] + 1).setBackground("red");    }  }      // Highlight all instances of duplicate values in a column  function highlightColumnDuplicates(column, indexes) {    for (n = 0; n < indexes.length; n++) {      sheet.getRange(indexes[n] + 1, column).setBackground("red");    }  }    // Highlight all instances of duplicate values in a row  function highlightRowDuplicates(row, indexes) {    for (n = 0; n < indexes.length; n++) {      sheet.getRange(row, indexes[n] + 1).setBackground("red");    }  }    //----------- Main -------------    function sheetMain() {    var data = readSheetData();    var duplicates = findDuplicates(data);    var indexes = getIndexes(data, duplicates);    highlightSheetDuplicates(indexes);  }    function columnMain(column) {    var data = readColumnData(column);    var duplicates = findDuplicates(data);    var indexes = getIndexes(data, duplicates);    highlightColumnDuplicates(column, indexes);  }    function rowMain(row) {    var data = readRowData(row);    var duplicates = findDuplicates(data);    var indexes = getIndexes(data, duplicates);    highlightRowDuplicates(row, indexes);  }    // ---------- Menu ----------  function onOpen() {    var ui = SpreadsheetApp.getUi();    ui.createMenu('DUPLICATED')      .addItem('Sheet', 'sheetMain')      .addItem('Row', 'showRowPrompt')      .addItem('Column', 'showColumnPrompt')      .addToUi();  }    // ---------- Prompt ----------  function showColumnPrompt() {    var ui = SpreadsheetApp.getUi();    var response = ui.prompt(      'Find Duplicates',      'Enter letter of column to search:',      ui.ButtonSet.OK_CANCEL);    // Get user response, run main    var button = response.getSelectedButton();    var text = response.getResponseText();    if (button == ui.Button.OK) {      text = sheet.getRange(text + "1");      text = text.getColumn();      columnMain(text);    }  }    function showRowPrompt() {    var ui = SpreadsheetApp.getUi();    var response = ui.prompt(      'Find Duplicates',      'Enter number of row to search:',      ui.ButtonSet.OK_CANCEL);    // Get user response, run main    var button = response.getSelectedButton();    var text = response.getResponseText();    if (button == ui.Button.OK) {      rowMain(text);    }  }  

But it only works in columns/rows of the active sheet. It also enables a trigger menu that is quite usefull.

The expected result:

  1. Run script from the menu
  2. Highlight with red background cells in Sheet_1 A:A, Sheet_2 A:A, Sheet_3 A:A... that have the same values.
  3. Do the same with values in Sheet_1 D:D, Sheet_2 D:D, Sheet_3 D:D
  4. Do the same with values in Sheet_1 J:J, Sheet_2 J:J, Sheet_3 J:J
  5. Delete manually some highlighted rows
  6. Run script again
  7. Breath deep and drink some tea

P.S. I don't want to look for duplicates in the first row (fixed header)

I will be super grateful if someone can help me with this problem that I've been working for three days without finding the right solution, I have tried different ways but I cannot find the ideal solution.

Thanks! 👨‍💻

Issue with Python tkinter / pypdftk / subprocess(?)

Posted: 26 Mar 2021 08:21 AM PDT

I have been using this whole script flawlessly on my PC. I attempted to put it on my coworkers PC, but this particular part doesn't seem to work. I am using a tkinter interface to take data from psql and fill a premade fillable PDF using pypdftk, then either saving it using asksaveasfilename and opening it with subprocess.Popen or not saving it and opening it as a temp file using subprocess.run. On my PC both work great. On coworkers PC, neither work.

On my coworkers PC, the save option opens the save dialog with all the correct info as far as I can tell, and lets me go through the process of saving a file as it normally would, but then the file just doesn't save and never actually appears. If I open as a temp file, it throws the exception.

import tkinter as tk  from tkinter import *  from tkinter.ttk import *  import tkinter.messagebox  import pypdftk  from tkinter.filedialog import asksaveasfilename  import os.path  import os  import subprocess  from pathlib import Path    def file_handler(form_path, data, fname):      try:          tl2 = tk.Toplevel()          tl2.wm_title('File Handler')          w = 340          h = 55          ws = tl2.winfo_screenwidth()          hs = tl2.winfo_screenheight()          x = (ws/2) - (w/2)          y = (hs/2) - (h/2)          tl2.geometry('%dx%d+%d+%d' % (w, h, x, y))          def save_and_open():              savefile = asksaveasfilename(defaultextension=".pdf", initialdir="C:\\Desktop", filetypes=[('pdf file', '*.pdf')], initialfile=fname)              generated_pdf = pypdftk.fill_form(form_path, data, savefile)              subprocess.Popen(generated_pdf,shell=True)          def open_without_save():              try:                  generated_pdf = pypdftk.fill_form(form_path, data)                  os.rename(generated_pdf, generated_pdf+".pdf")                  generated_pdf = generated_pdf+".pdf"                  subprocess.run(generated_pdf,shell=True)              except:                  tk.messagebox.showerror("Unable to open", "An error has occurred.  Please try again.")              else:                  tl2.destroy()              finally:                  if os.path.exists(generated_pdf):                      os.remove(generated_pdf)                      print("Successfully removed temp file.")          save = tk.Button(tl2,text='Save and Open', width=20, command=save_and_open)          nosave = tk.Button(tl2,text='Open without saving', width=20,command=open_without_save)          save.grid(row=0, columnspan=2, sticky='NESW', padx=5, pady=10, ipadx=5, ipady=5)          nosave.grid(row=0, column=2, columnspan=2, sticky='NESW', padx=5, pady=10, ipadx=5, ipady=5)          tl2.mainloop()      except:          tk.messagebox.showerror("Unable to open", "An error has occurred.  Please try again.")  

As far as I can tell, everything works until you get into the save_and_open and open_without_save functions. I left in all the libraries I believe are relevant.

I should also mention, I am quite a novice at python. So if any of this is ugly coding, feel free to shame me for it.

update:

I now believe the problem to be here in the pypdftk.py file:

if os.getenv('PDFTK_PATH'):    PDFTK_PATH = os.getenv('PDFTK_PATH')  else:    PDFTK_PATH = '/usr/bin/pdftk'    if not os.path.isfile(PDFTK_PATH):      PDFTK_PATH = 'pdftk'  

My error states pdftk is not a known command. My guess is that there is no environment variable, then it looks to the /usr/bin and cannot find the pdftk file, so it's just making "pdftk" a string? I don't know much about /usr/bin, but is there a way to check that?

AWS IoT Core sql query rule - Comparing 2 object arrays returns null/undefined?

Posted: 26 Mar 2021 08:21 AM PDT

I'm trying to compare 2 arrays in a sql query. Everything seems to work fine while getting data from dynamodb and MQTT broker server. But if I try to compare both arrays, doesn't return anything or its undefined.

My sql query:

SELECT ts, objects, (SELECT id FROM get_dynamodb('table', 'key_name', 'key_value', 'rolearn').ids) AS db, (SELECT id from objects) as obj_ids  FROM 'subscribed/topic'  WHERE objects <> []  

Result:

{     "ts": 1615807935588,     "objects": [        {           "id": 1,           "planet": "jupiter"        },        {           "id": 2,           "planet": "mars"        },     ],     "db": [        {           "id": 2        },        {           "id": 3        }     ],     "obj_ids": [        {           "id": 1        },        {           "id": 2        }     ]  }  

So far it's ok, now all I want to do is compare if "obj_ids" and "db" arrays are different (obj_ids <> db), and by the aws documentation https://docs.aws.amazon.com/iot/latest/developerguide/iot-sql-operators.html#iot-sql-operators-not-eq I can compare both arrays.

So if I do:

SELECT ts, objects, (SELECT id FROM get_dynamodb('table', 'key_name', 'key_value', 'rolearn').ids) AS db, (SELECT id from objects) as obj_ids  FROM 'subscribed/topic'  WHERE objects <> []  AND obj_ids <> db  

The code doesn't return anything. I've already tested comparing 2 objects arrays hardcoded into the query and it works just has I intended.

SELECT ([{"id": 1},{"id": 2}] <> [{"id": 1}]) as result  FROM 'subscribed/topic'  

Result:

{     "result": true  }  

Any response will be appretiated. Thanks!

SFML RenderWindow taking a long time to open a window

Posted: 26 Mar 2021 08:21 AM PDT

I know this is essentially a duplicate, but this wasn't ever answered. I'd like to mention that I have followed the tutorial for using SFML along with Visual Studio, and I'm running a 64-bit project with 64-bit SFML. The window loaded instantly a few times, and now consistently takes 40 seconds to open on new builds/debugs. I also have the downloading of debug symbols off. My graphics drivers are up to date and my HDD is fine. This is the code:

 #include <SFML/Graphics.hpp>    int main()  {  sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");//This one  sf::CircleShape shape(100.f);  shape.setFillColor(sf::Color::Green);    while (window.isOpen())  {      sf::Event event;      while (window.pollEvent(event))      {          if (event.type == sf::Event::Closed)              window.close();      }        window.clear();      window.draw(shape);      window.display();  }    return 0;  }  

Everything runs at normal speed, except for RenderWindow, which again, takes exactly 40 seconds every time. Does anyone know how I could fix this? I've been having this issue for a few weeks now.

e: Could it be my CPU? It's not the best but I can still run most games just fine as I have a 1050ti. My current CPU is an i5-2500k, although I believe I got the same issue on an A10-5800k.

Alternative to the pandas negation operator

Posted: 26 Mar 2021 08:21 AM PDT

I'm trying to use the pandas negation operator ~ in one of my jinja2 templates but I believe its conflicting with their special operator ~.

{% for row in df.loc[ ~(df['is_test_result_pass']) , : ].itertuples() %}  

yields the following exception...

jinja2.exceptions.TemplateSyntaxError, unexpected '~'  

I could do the operation on the python side and pass another variable with the negated selection but what's the method name equivalent that the ~ operator maps to that I could invoke in the template.

Maven Failsafe Plugin is always skipping integration tests

Posted: 26 Mar 2021 08:22 AM PDT

I am attempting to configure my Maven project to have unit tests and integration tests. The unit tests are already working fine using the Maven Surefire plugin and are named according to the pattern *Test.java.

After adding the Failsafe plugin, like so:

         <plugin>              <groupId>org.apache.maven.plugins</groupId>              <artifactId>maven-failsafe-plugin</artifactId>              <version>2.18.1</version>              <dependencies>                <dependency>                  <groupId>org.apache.maven.surefire</groupId>                  <artifactId>surefire-junit47</artifactId>                  <version>2.18.1</version>                </dependency>              </dependencies>              <configuration>                  <includes>                      <include>**/*IT.java</include>                  </includes>              </configuration>              <executions>                <execution>                  <id>integration-test</id>                  <goals>                    <goal>integration-test</goal>                  </goals>                </execution>              </executions>            </plugin>  

I added an integration test named SomeTestIT.java. However, when I run:

mvn failsafe:integration-test  

I get the following:

[INFO] Scanning for projects...  [INFO]                                                                           [INFO] ------------------------------------------------------------------------  [INFO] Building MyApp 1.0  [INFO] ------------------------------------------------------------------------  [INFO]   [INFO] --- maven-failsafe-plugin:2.18.1:integration-test (default-cli) @ MyApp ---  [INFO] Tests are skipped.  [INFO] ------------------------------------------------------------------------  [INFO] BUILD SUCCESS  [INFO] ------------------------------------------------------------------------  [INFO] Total time: 1.368 s  [INFO] Finished at: 2015-03-04T14:43:50-06:00  [INFO] Final Memory: 11M/219M  [INFO] ------------------------------------------------------------------------  

My test class (buried a few package levels deep beneath the test hierarchy) looks something like:

package com.example.my.package;    import org.junit.Test;  import org.junit.Assert;  import com.example.my.package.SomeService;    import org.junit.runner.RunWith;  import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  import org.springframework.beans.factory.annotation.Autowired;    @RunWith(SpringJUnit4ClassRunner.class)  public class SomeTestIT  {      @Autowired      private SomeService target;        @Test      public void testTest()      {          Assert.assertTrue(false);      }        @Test      public void basicListTest()      {          Assert.assertNotNull(target);      }  }  

Where the tests are stubs to make sure that I have the Maven integration working.

I have ensured that:

  • My POM includes a direct, test scoped dependency on JUnit.
  • I have tried the plugin configuration both with and without an explicit test runner dependency.
  • I have tried the configuration above both with and without an explicit include pattern (on the assumption that my class ought to have been picked up by the defaults).

Nonetheless, the tests never actually run. Is there anything else necessary to get the integration tests running?

PHP Function to return string

Posted: 26 Mar 2021 08:20 AM PDT

I am fairly new to PHP. I have a function which checks the cost of price. I want to return the variable from this function to be used globally:

<?  function getDeliveryPrice($qew){      if ($qew=="1"){          $deliveryPrice="60";      } else {          $deliveryPrice="20";      }      return $deliveryPrice;                            }  // Assuming these two next lines are on external pages..  getDeliveryPrice(12);  echo $deliveryPrice; // It should return 20    ?>  

Zoom in on a point (using scale and translate)

Posted: 26 Mar 2021 08:21 AM PDT

I want to be able to zoom in on the point under the mouse in an HTML 5 canvas, like zooming on Google Maps. How can I achieve that?

No comments:

Post a Comment