Tuesday, June 22, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Should Google analytics tracking ID kept secret or can I embed it into the build

Posted: 22 Jun 2021 10:53 AM PDT

Is it safe to use Google's analytics tracking id in production. I'm assuming it's not a secret and I can do something like:

const location = useLocation();      useEffect(() => {      ReactGA.initialize("UA-MY-GA-ID"); // Analytics tracking ID      ReactGA.ga('send', 'pageview', location.pathname);    }, [location]);  

Google denied update due Remediation for Implicit PendingIntent Vulnerability

Posted: 22 Jun 2021 10:53 AM PDT

When i'm trying to update my app - i got error during review process. Remediation for Implicit PendingIntent Vulnerability - https://support.google.com/faqs/answer/10437428. In my app there is on place, where i'm creating PendingIntent - for Firebase push notifications:

Inside class FCMService extends FirebaseMessagingService

@Override      public void onMessageReceived(@NotNull RemoteMessage remoteMessage) {          super.onMessageReceived(remoteMessage);            Intent intent = new Intent(this, ApplicationActivity.class);          intent.setAction("com.google.firebase.MESSAGING_EVENT");          intent.setPackage(getApplicationContext().getPackageName());            Map<String, String> data = remoteMessage.getData();          for (Map.Entry<String, String> entry : data.entrySet()) {              String value = entry.getValue();              String key = entry.getKey();              if (key.equals(ApplicationActivity.LINK_URL) ||                      key.equals(ApplicationActivity.FLOCKTORY_LINK_URL)) {                  intent.putExtra(ApplicationActivity.FLOCKTORY_LINK_URL, value);                  if (remoteMessage.getNotification() != null && remoteMessage.getNotification().getTitle() != null) {                      intent.putExtra(ApplicationActivity.HMS_PUSH_TITLE, remoteMessage.getNotification().getTitle());                  }              }          }            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);            RemoteMessage.Notification notification = remoteMessage.getNotification();          NotificationCompat.Builder builder = new NotificationCompat.Builder(this, getString(R.string.channel_id))                  .setSmallIcon(R.drawable.ic_launcher_notification)                  .setColor(getResources().getColor(R.color.colorNotification))                  .setContentTitle(notification == null ? "" : notification.getTitle())                  .setContentText(notification == null ? "" : notification.getBody())                  .setPriority(NotificationCompat.PRIORITY_DEFAULT)                  .setContentIntent(pendingIntent)                  .setAutoCancel(true);            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);          notificationManager.notify(new Random(UUID.randomUUID().getLeastSignificantBits()).nextInt(), builder.build());  

In Manifest:

<service              android:name="ru.svyaznoy.shop.domain.FCMService"              android:exported="false">              <intent-filter>                  <action android:name="com.google.firebase.MESSAGING_EVENT" />              </intent-filter>          </service>  

implementation "com.google.firebase:firebase-messaging:22.0.0"

minSdkVersion 24 targetSdkVersion 30

I just cant figure out what's wrong with this code - i pass explicit Intent with all required fields set. My head is blowing - this update is very important. Does anyone had similar issue?

Is there an R function for creating a new dataframe using two columns from existing dataframe?

Posted: 22 Jun 2021 10:53 AM PDT

Let's say I have a dataframe called cupcakes. I have three columns - one called filling, one called cake flavor, and one called sprinkle color. I want to create a new dataframe extracting just the filling and cake flavors where it counts the amount of items with each possible combination (e.g., there are 5 cupcakes I sold where there's cream filling and chocolate cake, so it prints 5 in that cell).

I would like filling to be my rows and cake flavor to be my columns. How do I accomplish this?

I tried converting the columns to a table, but it does not make one variable a column and one a row. This was my code: cakestrim <- as.data.frame(table(cakes$filling,cakes$flavor)).

Any help would be appreciated!

Trouble displaying screen in MouseListener method

Posted: 22 Jun 2021 10:53 AM PDT

I am coding a game in Java. The first screen is the begin screen. On a mouse click, the screen is supposed to switch to a screen that lets you choose a character. Then, the next screen is the first game question. The character choosing screen isn't coming. It is just going to the first question. drawq is the boolean that determines if the question has been drawn. I had initialized it to false in the beginning of my code. Here is my mouselistener method, please help me find a way to get the screen that displays "Choose your character" and the image of the girl.

public void mouseReleased(MouseEvent e) {                  // TODO Auto-generated method stub                  //background image                  g.drawImage(theme.getImage(),0,0,WIDTH,HEIGHT,null);                  //Choosing character screen                  g.drawString("Choose your character", WIDTH-1550, HEIGHT/6);                  g.drawImage(girl.getImage(),WIDTH-1550,HEIGHT/2,237,338,null);                  //switching drawq to false                  drawq=true;                  //draw next question on mouse click                  if(drawq==true) {                       questions[whichquestion].draw(g);                       drawq=false;                       repaint();                  }  

First row of a DF as column names

Posted: 22 Jun 2021 10:53 AM PDT

How I do a make this first row as my column names instead of x1, x2....xn?

Thanks

DataFrame

How can I combine 2 associative arrays with different keys and how to get the result array in the input to give order in PHP?

Posted: 22 Jun 2021 10:52 AM PDT

I have 2 arrays like:

$arr1 =  [230] => Array          (              [itemid] => 230              [name] => test1              [category] => toy              [price] => 10.00          )        [240] => Array          (              [itemid] => 240              [name] => test2              [category] => toy              [price] => 8.00          )       [245] => Array          (              [itemid] => 245              [name] => test3              [category] => pen              [price] => 5.00          )  )  $arr2 =  [220] => Array          (              [itemid] => 220              [name] => test4              [category] => toy              [price] => 20.00          )        [225] => Array          (              [itemid] => 225              [name] => test5              [category] => battery              [price] => 4.00          )       [248] => Array          (              [itemid] => 248              [name] => test6              [category] => book              [price] => 3.00          )       [236] => Array          (              [itemid] => 236              [name] => test7              [category] => pen              [price] => 2.00          )  )  

I need the result like :

$arr3 =  [230] => Array          (              [itemid] => 230              [name] => test1              [category] => toy              [price] => 10.00          )        [240] => Array          (              [itemid] => 240              [name] => test2              [category] => toy              [price] => 8.00          )       [245] => Array          (              [itemid] => 245              [name] => test3              [category] => pen              [price] => 5.00          )      [220] => Array          (              [itemid] => 220              [name] => test4              [category] => toy              [price] => 20.00          )        [225] => Array          (              [itemid] => 225              [name] => test5              [category] => battery              [price] => 4.00          )       [248] => Array          (              [itemid] => 248              [name] => test6              [category] => book              [price] => 3.00          )       [236] => Array          (              [itemid] => 236              [name] => test7              [category] => pen              [price] => 2.00          )  )  

For this I simply using array_merge

 $arr3= $arr1+ $arr2;  

But after that I got the result like:

$arr3 =  [230] => Array          (              [itemid] => 230              [name] => test1              [category] => toy              [price] => 10.00          )        [240] => Array          (              [itemid] => 240              [name] => test2              [category] => toy              [price] => 8.00          )             [220] => Array          (              [itemid] => 220              [name] => test4              [category] => toy              [price] => 20.00          )        [225] => Array          (              [itemid] => 225              [name] => test5              [category] => battery              [price] => 4.00          )       [248] => Array          (              [itemid] => 248              [name] => test6              [category] => book              [price] => 3.00          )         [245] => Array          (              [itemid] => 245              [name] => test3              [category] => pen              [price] => 5.00          )       [236] => Array          (              [itemid] => 236              [name] => test7              [category] => pen              [price] => 2.00          )  )  

My issue is after merging 2 associative arrays with different keys, I got the first array and second array mixed which means I need the result like the first three array elements of the first array, after that 4 array elements of the second array.
Can you anyone help me, please, It will be helpful for me

Node multiple apps in the same folder

Posted: 22 Jun 2021 10:52 AM PDT

Is there any problem doing this :

My app structure

-my_app
-- node_modules
-- server1.js (express server running on port 3000)
-- server2.js (express server running on port 3001)
-- mymodule.js (exports some database functions)
-- package.js (express,mysql depentancies etc.)

Those apps will both use mymodule.js [const module = require('./mymodule)] and will call functions from inside(database requests)
Now if i spawn 2 process node server1.js and node server2.js
is there going to be any conflict/access problem for my 2 apps, or any other problem?

undefined argument passed to a fn in custom react hook

Posted: 22 Jun 2021 10:52 AM PDT

I'm using a custom hook to open a modal which will perform different actions.

To open and close the modal im using the custom hook useSongUtils methods openModal and closeModal:

export const useSongUtils = () => {    const [isEditing, setIsEditing] = useState(false);      const openModal = ({ cellData }) => {      // outputs undefined      console.log('cell data is', cellData);      setIsEditing(true);    };      const closeModal = () => {      setIsEditing(false);    };      return {      closeModal, isEditing, setIsEditing, openModal,    };  };  

And then importing the returned object into my component, where I have a method for a VirtualTable that renders some action links.

The cell data is an id and it is displayed correctly in the optionsRender method (both links work - I get the id). However, the idea is that clicking the Button element, calls the openModal method from usesongUtils and sets isEditing to true. That works.

However I'm also trying to get the cellData arguments in openModal method and it is not working. I'm getting undefined if I try to console.log.

  // SongList.js      const optionsRender = ({ cellData }) => (      <div className='songs-list__options'>        <Link to={`/songs/${cellData}/edit`}>          <Icon name='edit' style={{ margin: '0 .2rem .2rem 0' }} />        </Link>        <a rel='noreferrer' target='_blank' href={`localhost/client/song/${cellData}`}>          <Icon name='play' style={{ margin: '0 .2rem' }} />        </a>        {cellData} // I can see the data!!        // im trying to pass cellData to openModal         <Button size='tiny' className='ui button' fluid icon='setting' circular onClick={() => openModal(cellData)} />      </div>    );      const {      closeModal, isEditing, openModal,    } = useSongUtils();  

Sorting files in bash

Posted: 22 Jun 2021 10:52 AM PDT

I wiil appreciate your help.

I have files:

V0.1__file_a.sql  V0.2__file_b.sql  V0__file_c.sql  V1.1__file_a.sql  V1.2__b.sql  V1.3__c.sql  V1.4__d.sql  V1.5__e.sql  V1.6__f.sql  V1__file_g.sql  

I would like to use sort command to sort them in next way

V0__file_c.sql  V0.1__file_a.sql  V0.2__file_b.sql  V1__file_g.sql  V1.1__file_a.sql  V1.2__b.sql  V1.3__c.sql  V1.4__d.sql  V1.5__e.sql  V1.6__f.sql    

flags -n, -g do not help me with this.

And i seem to broke my brain solving this

Could someone to help with that?

Thanks!

How to create list of n variables?

Posted: 22 Jun 2021 10:52 AM PDT

Number of variables changes depending on game level.

I want to create list of variables in loop, for example if i = 4 I need variables: size1, size2, size3, size4. Creating names is also problematic for me, like how to create sizen variables?

Thank you in advance

JSON data web scraping

Posted: 22 Jun 2021 10:52 AM PDT

I am attempting to scrape Job titles from here.

First page of this site contains 50 job titles. Using requests I have tried to scrape Job Titles from the first page. I am getting only 10 Job titles. I am not able to scrape all the 50 Job titles from the first page. Using the Developertool > network I understood content type is JSON.

from bs4 import BeautifulSoup  import requests  import json    s = requests.Session()    headers = {      'Connection': 'keep-alive',      'Pragma': 'no-cache',      'Cache-Control': 'no-cache',      'sec-ch-ua': '^\\^',      'Accept': 'application/json, text/javascript, */*; q=0.01',      'sec-ch-ua-mobile': '?0',      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36',      'Origin': 'https://jobs.porsche.com',      'Sec-Fetch-Site': 'same-site',      'Sec-Fetch-Mode': 'cors',      'Sec-Fetch-Dest': 'empty',      'Referer': 'https://jobs.porsche.com/',      'Accept-Language': 'en-US,en;q=0.9',  }    r1 = s.get('https://api-jobs.porsche.com/search/?data=^%^7B^%^22LanguageCode^%^22^%^3A^%^22DE^%^22^%^2C^%^22SearchParameters^%^22^%^3A^%^7B^%^22FirstItem^%^22^%^3A1^%^2C^%^22CountItem^%^22^%^3A50^%^2C^%^22Sort^%^22^%^3A^%^5B^%^7B^%^22Criterion^%^22^%^3A^%^22PublicationStartDate^%^22^%^2C^%^22Direction^%^22^%^3A^%^22DESC^%^22^%^7D^%^5D^%^2C^%^22MatchedObjectDescriptor^%^22^%^3A^%^5B^%^22ID^%^22^%^2C^%^22PositionTitle^%^22^%^2C^%^22PositionURI^%^22^%^2C^%^22PositionLocation.CountryName^%^22^%^2C^%^22PositionLocation.CityName^%^22^%^2C^%^22PositionLocation.Longitude^%^22^%^2C^%^22PositionLocation.Latitude^%^22^%^2C^%^22PositionLocation.PostalCode^%^22^%^2C^%^22PositionLocation.StreetName^%^22^%^2C^%^22PositionLocation.BuildingNumber^%^22^%^2C^%^22PositionLocation.Distance^%^22^%^2C^%^22JobCategory.Name^%^22^%^2C^%^22PublicationStartDate^%^22^%^2C^%^22ParentOrganizationName^%^22^%^2C^%^22ParentOrganization^%^22^%^2C^%^22OrganizationShortName^%^22^%^2C^%^22CareerLevel.Name^%^22^%^2C^%^22JobSector.Name^%^22^%^2C^%^22PositionIndustry.Name^%^22^%^2C^%^22PublicationCode^%^22^%^2C^%^22PublicationChannel.Id^%^22^%^5D^%^7D^%^2C^%^22SearchCriteria^%^22^%^3A^%^5B^%^7B^%^22CriterionName^%^22^%^3A^%^22PublicationChannel.Code^%^22^%^2C^%^22CriterionValue^%^22^%^3A^%^5B^%^2212^%^22^%^5D^%^7D^%^2C^%^7B^%^22CriterionName^%^22^%^3A^%^22PublicationChannel.Code^%^22^%^2C^%^22CriterionValue^%^22^%^3A^%^5B^%^2212^%^22^%^5D^%^7D^%^5D^%^7D', headers=headers).json()    data1 = json.dumps(r1)  print(data1)  d1 = json.loads(data1)  #print(d1.keys)  for x in d1.keys():      print(x)  

Would really appreciate any help on this.

I am unfortunately currently limited to using only requests or another popular python library. Thanks in advance.

getting permission denied publickey when git push from computer to vps server

Posted: 22 Jun 2021 10:53 AM PDT

I'm trying to git push my app's files, from my computer, to a VPS server running on Ubunto.

On my computer(windows 10) I did: git init git add -A git commit -m "......"

On the server(in the app's directory): git init --bare

next did on my computer: git remote add origin fruitos@ and when I try git push or git pull I get Permission denied(publickey) fatal: Could not read from remote repository

I've tried many things so far to solve it but still no solution. any ideas?

The main goal is to upload the app's file straight from my computer(windows) to the vps server(Ubuntu) using the git push command.

Url.Action always add controller name

Posted: 22 Jun 2021 10:53 AM PDT

When I call:

  onclick="window.location = '@Url.Action("images",             String.Empty,new { id = category.CategoryId})';"  

I get:

 https://localhost:44307/Home/images/1  

But I want to get:

 https://localhost:44307/images/1  

without the controller name

Query Help TSQL

Posted: 22 Jun 2021 10:53 AM PDT

create table ProductEmployee  (    ProductID int,    EmployeeName nvarchar(300)  );    insert into ProductEmployee (ProductID, EmployeeName) values  (1, 'E1'),  (2, 'E2'),  (3, 'E3'),  (4, 'E4'),  (5, 'E5')    create table ProductGroup  (    ProductID int,    GroupName nvarchar(30)  );      insert into ProductGroup (ProductID, GroupName) values  (1, 'G1'),  (2, 'G1'),  (3, 'G1'),  (4, 'G2'),  (5, 'G2')    Select * from ProductEmployee    ProductID   EmployeeName  1           E1  2           E2  3           E3  4           E4  5           E5    select * from ProductGroup    ProductID   GroupName  1           G1  2           G1  3           G1  4           G2  5           G2  

Need to Write a query which provide all the Products in the Productgroup of a product associated with an employee. Example - In table ProductEmployee for employee E2 the ProductID related is 2. The GroupName for Productid 2 is G1 in ProductGroup table. so I need all the ProductId associated with Group G1.Please help.

Expected query Result for the above scenario:    Eg : Employee ProductID  GroupName       E2       1          G1       E2       2          G1       E2       3          G1    Expected Result for all records in the table:    Eg : Employee ProductID  GroupName       E1       1          G1       E1       2          G1       E1       3          G1       E2       1          G1       E2       2          G1       E2       3          G1       E3       1          G1       E3       2          G1       E3       3          G1       E4       4          G2       E4       5          G2       E5       4          G2       E5       5          G2  

Laravel Eloquent request to get products with most categories in common

Posted: 22 Jun 2021 10:53 AM PDT

Each Product can have several Category

On each product page, I need to display 10 "related products".

To that end, I would like to create a function on the Product model, that would return other products that have the most Category in common, and that would go like so:

public function related_products()  {    return Product::with('categories')->whereHas('categories',function($query) {      $query->whereIn('id',$this->category_ids);    })->take(10)->get();  }  

But this would only give me the first 10 products that have at least one category in common.

How can I get the 10 products that have the highest number of categories in common in decreasing order?

The closest I got was this in the internal query:

  $query->whereIn('id',$this->category_ids)    ->orderByRaw('COUNT(id) desc');  

Which isn't working.

Strange return in LINQ function c#

Posted: 22 Jun 2021 10:52 AM PDT

Hello I'm trying to get data of the type Datetime from the database but when returns the data it returns some strange ( photo 1 )

int idf = Convert.ToInt32(Iidfilho.Value);                    var IDADE =                      from d in basedados.Pessoa.OfType<Filho>()                      where d.IdPessoa == idf                      select d.DataNascimento;                    label6.Text = Convert.ToString(IDADE);  

enter image description here

enter image description here

Why are primitives not needed for haskell data constructors?

Posted: 22 Jun 2021 10:52 AM PDT

I'm new to haskell prpogramming and learning about the type system and am having trouble grasping what underlies a nullary data constructor..

Take for example the following:

data Color = Red | Green | Blue | Indigo | Violet deriving Show    genColor:: Color  genColor = Red   

From my understanding, Red, Green, Blue.. are nullary data constructors that when used construct a "Color".

What I'm having trouble grasping is, in traditional OOP languages you'd have to specify the primitive underlying the type -- for ex. whether a color is a string, an int, float etc.

In Haskell, the code above runs perfectly fine so why is this not needed? What is the rationale behind structuring the type system like this? Thanks and all help would be appreciated :)

JavaScript why is map not returning all the indexes?

Posted: 22 Jun 2021 10:52 AM PDT

I dont know but this seems like a bug with javascript or it has to be my machine or something this map is not returning all indexes

const words = [];  let array = [      {        id:"h2j3x33",        author:"Zindril",        body:"Glad to help. Hope it helps you clear even faster next reset!",        permalink:"zindi.page",        utc:1624278978,        replies:""      },      {        id:"33",        author:"highperson",        body:"Im a the best!",        permalink:"thebest.com",        utc: 054,        replies: ""      },      {        id:"43",        author:"charizard",        body:"fire burn",        permalink:"dragon.com",        utc:342342,        replies: {id: 324, author: "Ash", body: "Skinny", permalink: "pokemon.com", utc: 1, replies: ""}      }  ]  
words.push(array)  console.log(words)  console.log(words.length) // this says the length is 1 so the index will be 0  
let whyOnlyFor1Obj = words.map((word, idx, arr) => word[idx]) // word[idx] only returns the first object if I try forEach i get undefined  console.log(whyOnlyFor1Obj)   

The funny thing is when I do

let whyOnlyFor1Obj = words.map((word, idx, arr) => word[2]) // or word[1] I get the other Objects   console.log(whyOnlyFor1Obj)   

Is it me or what is wrong with JS on this?

Display dynamic image in VueJs with Laravel

Posted: 22 Jun 2021 10:53 AM PDT

I am trying to display image stored in storage/app/public/images folder with VueJS but somehow the image is not displayed in vue file

 <img v-bind:src="img" />     export default {      data(){      return{          img:'',      };  },     mounted() {          axios.get('/api/image')          .then(res => {              this.img = res.data          })          .catch(error => console.log(error))      },  

The path returned is correct, however the image is not shown.

Kindly help

Excel VBA - Loop a specific column in structured table and get corresponding cells values from other columns

Posted: 22 Jun 2021 10:52 AM PDT

I start using structured table with VBA code, but here I face a problem which I do not manage by myself.
I have a structured table in which I loop through 1 column and need to get values from other columns depending on some criteria:

  • if the cells value is "Finished"
  • then I take 3 dates (dateScheduled, dateRelease and dateReady) from 3 other columns and perform some calculations and tests based on these dates

the problem is that I can get the values of the date columns (they are well formatted and have values in it), so none of the next actions triggered by the first if is working.

Here is part of the whole code of my macro, I hope this is sufficient to figure out what is wrong.

For Each valCell In Range("thisIsMyTable[Task Status]").Cells      If valCell = "Finished" Then          dateScheduled = Range("thisIsMyTable[End Date]").Cells          dateRelease = Range("thisIsMyTable[Release Date]").Cells          dateReady = Range("thisIsMyTable[Date Ready]").Cells          totalFinishCat = totalFinishCat + 1          daysToFinished = daysToFinished + DateDiff("d", dateReady, dateRelease)          If Range("thisIsMyTable[Time Spent]").Cells = "" Then              timeTotalFinished = timeTotalFinished + Range("thisIsMyTable[Time estimate]").Cells + Range("thisIsMyTable[Extra hours]").Cells          Else              timeTotalFinished = timeTotalFinished + Range("thisIsMyTable[Time Spent]").Cells          End If                    If dateRelease >= dateStartReport Then              monthFinished = monthFinished + 1              timeMonthFinished = timeMonthFinished + Range("thisIsMyTable[Time Spent]").Cells              daysToFinishedMonth = daysToFinishedMonth + DateDiff("d", dateReady, dateRelease)              If dateRelease > dateScheduled Then                  afterDue = afterDue + 1                  diff = DateDiff("d", dateScheduled, dateRelease)                  afterDay = afterDay + diff              Else                  beforeDue = beforeDue + 1                  diff = DateDiff("d", dateRelease, dateScheduled)                  beforeDay = beforeDay + diff              End If          End If      End If  Next valCell  

I have tried out by adding .value or .value2 like so:

dateScheduled = Range("thisIsMyTable[End Date]").Cells.value  

or

dateScheduled = Range("thisIsMyTable[End Date]").Cells.value2  

but it does not work better. I have checked by adding .select like so:

dateScheduled = Range("thisIsMyTable[End Date]").Cells.select  

and this will select the entire column, not the cells as I expect. So it appears that my method to just get the cells value is not appropriate.

Any help is welcome

AWS EMR with Task Nodes only for S3/EMRFS-only processing and 1 Core Node

Posted: 22 Jun 2021 10:52 AM PDT

Given that AWS with EMR provide you with their optimized Spark experience, then:

  • If I am planning to only use S3 / EMRFS for both directly reading and directly writing and not using s3DistCP,
    • Why do I need at least 1 Core Node?

My suspicion is that at least 1 Core Node is needed to get around the issue of Spark shuffle files due to yarn dynamic resource allocation being lost in the past when Core Nodes could be deallocated with scaling.

Converting multibyte array to Unicode

Posted: 22 Jun 2021 10:53 AM PDT

I'm creating an FTP downloader using WinInet in a Univeral Windows program with Visual Studio 2019.

Visual Studio 2019 doesn't give an option to change the character set in the properties configuration tab.

I need to convert the following, which is in multibyte format, to Unicode:

CHAR * szHead[] = "Accept: */*\r\n\r\n";  

The overall code comes from a previous older project using a compiler that had multi-byte character set options, and works fine as is. Unfortunately, I need to make this work in a compiler that has Windows Store support, which only has Unicode.

if (!(hConnect = InternetOpenUrlW(hOpen, szUrl, szHead, strlen(szHead), INTERNET_FLAG_DONT_CACHE, 0)))  

I get the following errors:

Error (active)  E0520   initialization with '{...}' expected for aggregate object     Error   C2440   'initializing': cannot convert from 'const wchar_t [16]' to 'LPCTSTR []'      Error   C2664   'size_t strlen(const char *)': cannot convert argument 1 from 'LPCTSTR []' to 'const char *'      

From other research, these errors are arising because the compiler is expecting Unicode but is getting multibyte.

Modify single value in pandas DataFrame with integer row and label column

Posted: 22 Jun 2021 10:53 AM PDT

I want to modify a single value in a DataFrame. The typical suggestion for doing this is to use df.at[] and reference the position as the index label and the column label, or to use df.iat[] and reference the position as the integer row and the integer column. But I want to reference the position as the integer row and the column label.

Assume this DataFrame:

dateindex apples oranges bananas
2021-01-01 14:00:01.384624 1 X 3
2021-01-05 13:43:26.203773 4 5 6
2021-01-31 08:23:29.837238 7 8 9
2021-02-08 10:23:09.095632 0 1 2

I want to change the value "X" to "2". I don't know the exact time; I just know that it's the first row. But I do know that I want to change the "oranges" column.

I want to do something like df.at[0,'oranges'], but I can't do that; I get a KeyError.

The best thing that I can figure out is to do df.at[df.index[0],'oranges'], but that seems so awkward when they've gone out of their way to provide both by-label and by-integer-offset interfaces. Is that the best thing?


code to create DataFrame:

data = [{'apples':1, 'oranges':'X', 'bananas':3},          {'apples':4, 'oranges':5,   'bananas': 6},          {'apples':7, 'oranges':8,   'bananas':9},          {'apples':0, 'oranges':1,   'bananas':2}]  indexes = [pd.to_datetime('2021-01-01 14:00:01.384624'),             pd.to_datetime('2021-01-05 13:43:26.203773'),             pd.to_datetime('2021-01-31 08:23:29.837238'),             pd.to_datetime('2021-02-08 10:23:09.095632')]  idx = pd.Index(indexes, name='dateindex')  df = pd.DataFrame(data, index=idx)  

Modifying the registry value in x32 and x64 in Wix Installer by executing a batch command

Posted: 22 Jun 2021 10:53 AM PDT

I am looking for a way to execute a command in Wix installer that can modify the registry values at the following locations:

  • HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows (32-bit)
  • HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows NT\CurrentVersion\Windows (64-bit)

The name of the Registry Key is as follows:
Name: USERProcessHandleQuota'
Value: 10000

I want to update this value to 15000. I have been able to modify this value using the following PowerShell script:

Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows' -Name 'USERProcessHandleQuota' -Value '15000'  Set-ItemProperty -Path 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows NT\CurrentVersion\Windows' -Name 'USERProcessHandleQuota' -Value '15000'  

However, I cannot find a way to execute this PowerShell script directly in the Wix installer. I have also tried to find a way to do the same using the command prompt, but I have been unsuccessful.

I found a way to execute a command directly in Wix as suggested here:

<CustomAction Id="ExecPortOpen" Directory="INSTALLFOLDER" Execute="commit" Impersonate="no" ExeCommand="cmd.exe /c &quot;netsh http add urlacl url=http://+:1234/ user=Everyone&quot;" Return="check" />    <InstallExecuteSequence>       <Custom Action="ExecPortOpen" After="InstallInitialize" />  </InstallExecuteSequence>  

This way, I don't have to include any additional files in the installer. However, I cannot find a command using which I can update the registry values.

Furthermore, I know we can update the registry values as suggested here:

<Component Feature="MainApplication">    <RegistryValue Root="HKLM" Key="SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION" Name="MY_REG_ENTRY" Value="11000" Type="integer" KeyPath="yes"/>  </Component>  

However, this only updates registry at 32-bit location. It does not update at the 64-bit location. If I use the following code to update at 64-bit location, the installer does not build since my application is not 64-bit application. It's a 32-bit application.

<Component Feature="MainApplication" Win64="yes">  

Add signature timestamp after the signing

Posted: 22 Jun 2021 10:52 AM PDT

How to add the timestamp for the signatures for the following case?

A third party signing service, signing the hash of the document and then returns the CMS container. The service also exposes the TSP endpoint. So, what needs to be done in order to add the timestamp for signatures? I'm using iText7 to perform the operations with documents.

how to add sample run mode for package installation

Posted: 22 Jun 2021 10:53 AM PDT

I want to install a package (mypackage-1.0-local.zip) only for local environment. This package should not be installed in any other environments.Same as OOTB 'samplecontent'/'nosamplecontent' runmodes. So for this I do not know how to achieve this. If I start AEM server with 'local' runmode then how package manager service will know whether to install this package or not based on runmode?

MacOS update raised EXC_BAD_ACCESS (SIGSEGV)

Posted: 22 Jun 2021 10:53 AM PDT

I'm developing an react-native application on M1 Mac.

I recently updated my mac os to beta version Monterey(version 12.0 beta)

After installing the beta version of the mac os i also installed the Xcode(13.0 beta)

Now my app is installed to the iPad simulator but when i open the app, i get the following error.

error log

Can someone help me.

Thanks in advance!

How do I deep clone an object in React?

Posted: 22 Jun 2021 10:52 AM PDT

let oldMessages = Object.assign({}, this.state.messages);  // this.state.messages[0].id = 718    console.log(oldMessages[0].id);  // Prints 718    oldMessages[0].id = 123;    console.log(this.state.messages[0].id);  // Prints 123  

How can I prevent oldMessages to be a reference, I want to change the value of oldMessages without changing the value of state.messages

Draw an ASCII diamond in a frame

Posted: 22 Jun 2021 10:53 AM PDT

I am trying to draw out a diamond in a frame. I figured my way through the top half, but when I come to the 2nd half I had attempted to invert the loops and problems came up. I played around switching operators just to see the result, but still nothing works. Please help. What am I not seeing.

// 1st Half of Diamond    // Creates Lines  for (int i = 1; i <= 3; i++) {      if (i == 1) {          System.out.print("+");          for (int h = 1; h <= 8; h++) {              System.out.print("-");          }          System.out.print("+" + "\n");      }      System.out.print("|");        // Nested Loop Creates Spaces Left Side      for (int j = 4; j > i; j--) {          System.out.print(" ");      }      System.out.print("/");        // Nested Loop Creates Values Inside      for (int j = 1; j < i; j++) {          if (i % 2 == 0) {              System.out.print("--");          } else if (i == 1) {              System.out.print("\\");          } else {              System.out.print("==");          }      }      System.out.print("\\");        // Nested Loop Creates Spaces Right Side      for (int j = 4; j > i; j--) {          System.out.print(" ");      }      System.out.print("|");      System.out.print("\n");  }    // Midpoint of Diamond  System.out.print("|<------>|" + "\n");    //============================  //****HERE PROBLEMS ARISE****    // 2nd Half of Diamond    // Creates Lines  for (int i = 1; i <= 3; i++) {      System.out.print("|");        // Nested Loop Creates Spaces Left Side      for (int j = 1; j <= i; j++) {          System.out.print(" ");      }      System.out.println("\\");        // Nested Loop Creates Values Inside      for (int j = 1; j < 2; j++) {          System.out.print("+");          for (int h = 1; h <= 8; h++) {              System.out.print("-");          }          System.out.print("+" + "\n");          if (i % 2 == 0) {              System.out.print("-");          } else if (i == 3) {              System.out.print("/");          } else {              System.out.print("=");          }      }  }  

Flask and pdf viewer (pdf.js)

Posted: 22 Jun 2021 10:52 AM PDT

I am trying to solve the following problem: I need to display a .pdf document on a web page using pdf.js plug-in. When I embed the following line in a Flask app:

iframe src = "/path/to/test.pdf" width = "30%" height = "30%"></iframe>  

it returns 404 error, but a pdf file is displayed in pdf.js when I use the same line in a regular .html file.

No comments:

Post a Comment