All posts by A

Permission denied while getting drive credentials from BigQuery table in Cloud Functions via SQL

If you have a BigQuery external table which uses for example a Google Sheets file as source, AND you try to read / join this table in BigQuery SQL you may get the error in BigQuery job failure log:

google.api_core.exceptions.Forbidden: 403 Access Denied: BigQuery BigQuery: Permission denied while getting Drive credentials.

Seems like no drive scope is the default, so BQ clients that need these scopes should be passing it in via the client_options.

So in this original solution post: https://github.com/googleapis/google-auth-library-python/issues/1204

This is the solution which worked for me too:

EricSeastrand commented on May 27, 2024• 
For anyone else facing this, here's the exact code that worked for me:

from google.cloud import bigquery
client = bigquery.Client(client_options={
    "scopes": ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/cloud-platform']
})
results = client.query_and_wait(sql)

During the bigquery.Client connection I had to pass the above scopes and there is no problem with authorizations in Sheets/Drive access anymore.

Some day I may post more on the topic …..

Google Cloud scheduler call to Cloud functions 401 error

I used to run some functions developed and deployed on Google Cloud Run Functions.

Some of them are scheduled to run via Cloud Scheduler.

Last time I decided to copy the definition of the Cloud Scheduler job from bot 2 to my new bot3 function. And I started to get 401 unauthenticated errors for bot3, but the same definition was working fine for bot2.

The error looks like below:

debugInfo: "URL_ERROR-ERROR_AUTHENTICATION. Original HTTP response code number = 401"
jobName: "projects/....../locations/europe-west6/jobs/......"
status: "UNAUTHENTICATED"
targetType: "HTTP"

and in the Cloud Function log is the misleading:

The request was not authorized to invoke this service. Read more at https://cloud.google.com/run/docs/securing/authenticating Additional troubleshooting documentation can be found at: https://cloud.google.com/run/docs/troubleshooting#401

BUT – actually the problem is that during the copy of the scheduler job definition, the “Audience” value IS NOT updated with the new function URL (in my case bot3), but the old function URL is kept. It seems like it was autofilled in bot2 definition though and I didn’t noticed it. So be sure that URL and Audience are properly set!

If you fix this the 401 error is solved and gone!!!

I hope I saved you some time. Post one thanks in comments if so …

A1 / М-тел / А1 – спиране на рекламни СМС-и

При преподписване на договор с A1 (2024 година) започнаха да пращат на потърпевшите абонати реклами за гледане на мачове, резултати и т.н.

За да се спре този тормоз трябва да се изпрати на номер 1516 SMS със съдържание: СТОП 

И при успешно изпълнена заявка би трябвало до няколко минути да върне, че е спряна услугата. Както практиката показва може да получите още 1-2 съобщения в следващите минути и след това спират.

Extend VL06 transaction adding new field in output layout – SAP ECC

A good article and OSS note if you need to extend the standard ABAP SAP ECC transaction VL06 to display outbound deliveries details.

VL06: Insert fields to LIPOV

https://community.sap.com/t5/enterprise-resource-planning-blogs-by-members/vl06-insert-fields-to-lipov/ba-p/13289341

and

OSS Note 128150: https://me.sap.com/notes/128150

Mainly:

Extend LIPOVZ structure with your append structure and fields.

LIPOVZ is included in LIPOV structure which is used in report VL06.

If the name of the new fields are the same as in LIKP / LIPS, then the values will be auto populated.

But if you want to get values from other fields (like SO VBAK, or VBKD table), then you have to implement user-exit (extension name) via transaction SMOD assigning: V50Q0001

And in function module EXIT_SAPLV50Q_001 you have to create include ZXV50QU01 in which to put your code. Loop at CT_POSTAB and determine the value and change the field in the item of this internal table. Note: this exit is called for all items at once!

Sometimes you need to reset the buffers:
Note : BALVBUFDEL program must be run with SE38 for deletion of last buffer . Details on oss note 122975.

Gmail.com – more info on how ids work and two tricks

1st: You can append a plus “+” sign after your name

So adding any text after “+” sign still get the emails to your inbox, but you can filter based on this additional email id. E.g.:

your.email@gmail.com and your.email+subscription1@gmail.com and your.email+bank1@gmail.com

will both deliver the emails to your.email@gmail.com !

2nd: Gmail DOES NOT recognize the dots “.” in the email ID.

So your.email@gmail.com is the same as youremail@gmail.com or y.o.u.r.e.m.a.i.l@gmail.com

Original article is here: 2 hidden ways to get more from your Gmail address

https://gmail.googleblog.com/2008/03/2-hidden-ways-to-get-more-from-your.html

S/4HANA material segmentation, Country of Origin (CoO) in MIGO

SAP ERP doesn’t directly capture the country of origin during a MIGO goods receipt for a newly created batch. However, you can achieve this through implementing a User Exit.

Additional batch data, such as the country of origin, region of origin, and freely available date fields, can be changed only in user exits. To create a new batch for the goods movement, use the exit EXIT_SAPMM07M_003.

MCHA-HERKL is not automatically updated based on the purchase order during a goods receipt. You must use user exit EXIT_SAPMM07M_003

The user-exit EXIT_SAPMM07M_003 is in
Enhancement: “MBCFC003” – Maintenance of batch master data for goods movements”
(Use transaction: CMOD to activate the exit and assign enhancement).

Question: Why is the user exit EXIT_SAPMM07M_003 processed for some batches but not for others?

Answer: The user exit EXIT_SAPMM07M_003 is processed only if the batch is newly created by the goods movement. This may have different consequences depending on the batch definition level.

To determine the country of origin (CoO) you can use proper setup of segmentation field. Documentation here:

SAP docs on segmentation functionality:

https://help.sap.com/docs/SAP_S4HANA_ON-PREMISE/25a41481f62e469ba0e61015a0d39d20/50d69e52c406215ce10000000a44538d.html?version=1809.000

https://community.sap.com/t5/technology-blogs-by-members/use-of-segmentation-in-s-4-hana-for-product-revisions/ba-p/13410110

https://help.sap.com/docs/SAP_S4HANA_ON-PREMISE/9905622a5c1f49ba84e9076fc83a9c2c/027ca7527218912ee10000000a44538d.html

https://learning.sap.com/learning-journeys/explore-fashion-functions-and-business-processes-in-sap-s-4hana-for-fashion-and-vertical-business/explaining-segmentation_fc861c54-b5aa-4b8c-b08a-e90d23d7325b

Segmentation (LO_SEGMENTATION) is a new SAP ERP component, integrated into:

  • LO Material Master
  • SD Sales
  • MM Purchasing

SGT_CATS – ABAP table: Segmentation Structure Fields Table

SGT_CSEGSCON – ABAP table with segmentation rules defined

SGT_VALS – ABAP table with Segmentation-Valid Combinations

Continue reading S/4HANA material segmentation, Country of Origin (CoO) in MIGO

Principle 80:20 in human body -water, microbiome and more… Принципът 80:20 и в човешкото тяло

60% water in adult human body…

Up to 60% of the human adult body is water. According to Mitchell and others (1945), the brain and heart are composed of 73% water, and the lungs are about 83% water. The skin contains 64% water, muscles and kidneys are 79%, and even the bones are watery: 31%.

a от останалите 40% – 50% са чужди… (and in the left 40% more than 50% are not “human” cells):

In an article by the Scientific American (which has published articles by over 200 Nobel Prize winners) revealed that only 47% of our cells are human.

What about the other 53%?

Well, they’re made up of the bacteria, fungi and viruses living within us collectively known as your microbiome.

And it’s the newest discoveries about the microbiome, specifically in your gut, that scientists are calling “the most exciting prospect in medicine since the discovery of DNA.”

https://www.bbc.com/news/health-43674270

Мани стана като БГ изборите – 20% определят останалите 80% (So it sound like the result of the recent Bulgarian elections – 20% determines the result).

Артур Шопенхауер

Артур Шопенхауер е германски философ.

https://bg.m.wikiquote.org/wiki/Артур_Шопенхауер

https://cao.bg/artur-shopenhauer-zheni-lyubov-brak/

Богатството наподобява морската вода, от която жаждата ти се увеличава, колкото повече пиеш.

Здравето не е всичко, но без здраве всичко е нищо.

Който критикува придирчиво другите, работи над своето самоусъвършенствуване.

Който не обича самотата – той не обича и свободата.

От гледна точка на младостта живота е безкрайно бъдеще; от гледна точка на старостта – много кратко минало.

Повечето хора са толкова субективни, че всъщност не се интересуват от нищо освен от самите себе си.

Моята философия не ми донесе нищо, но ми спести много.

Чрез цитати изтъкваш ерудицията си и жертваш оригиналността си.

Човек, който пише за глупаци, винаги може да разчита на широк кръг от читатели.

Да страдаш, че някога вече няма да те има, е също тъй нелепо, както да страдаш за това, че някога още не те е имало.

Сполетялото ни нещастие не ни измъчва толкова, колкото мисълта за обстоятелствата, при които би могло да бъде избегнато.

Хората са общителни само поради своята неспособност да понасят самотата, тоест себе си.

Всяка нация се присмива на другите – и всичките имат право.

Инвестиции в акции – опит, идеи, полезни страници

Добра идея и предложение:

Как искам да се променят законите за ДДС за да се премахне парадокса “ДДС за инвеститори” или когато

https://redtapepayments.blogspot.com/2021/12/blog-post.html

tinyurl.com/vatbg

Защото “облагаем” оборот за регистрация не значи оборот, който се облага с ДДС. “Облагаемият” оборот за регистрация не се облага с ДДС, но го наричат облагаем, защото така са си го дефинирали в закона.

Това е подигравка.

Това е все едно да наричат котките кучета и да карат хората да попълват декларация за притежание на куче, въпреки че притежават котка.

По принцип много полезен и редовно актуализиран блог е този на Валентин Стойков:

ФИНАНСОВИТЕ УСЛУГИ И ЧЕРВЕНАТА ЛЕНТА

https://redtapepayments.blogspot.com/

Google Drive API v3 (googleapiclient.errors.HttpError 404 File not found)

If you try to upload a file in a shared drive (in Google Drive) you may get the above error.

This is my experience and solution as of February 2024 using Python 3.10.

from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from google.oauth2 import service_account

from io import BytesIO
from googleapiclient.http import MediaIoBaseUpload
from google.cloud import translate_v2 as translate

## Credentials of service account
credentials = service_account.Credentials.from_service_account_info(service_account_info, scopes=['https://www.googleapis.com/auth/drive'])

## API Client Service
service = build("drive", "v3", credentials=credentials)

# buffer_memory=BytesIO(b"some initial binary data: \x00\x01") # BytesIO() new_body
buffer_memory=BytesIO() # BytesIO() new_body
buffer_memory.write(new_body.encode('utf-8'))

## Prepare the file in memory (you can upload local file too with MediaBase Upload)
media_body = MediaIoBaseUpload(buffer_memory, mimetype='text/html', 
        chunksize=1024*1024, resumable=False)
                body = {
                        'title': file_name,
                        "name": file_name,
                        "mimeType": "application/vnd.google-apps.document",
                        "driveId": "0APee............PVA",
                        "parents": ['0APe.............PVA'],
                    }

## Upload file
returned_fields="id, name, mimeType, size, webViewLink, exportLinks"
upload_response=service.files().create( body=body,                                                            
   media_body=media_body,
   supportsAllDrives=True,
   fields=returned_fields).execute()

## Share the created file with user
user_permission = {
                    "type": "user",
                    "role": "writer",
                    "emailAddress": share_user,
                }
                perm_response = service.permissions().create(
                    fileId=uploaded_file_id,
                    body=user_permission,
                    fields="id"
                ).execute()
   

The important difference between uploading in private Google drive is that you have to use the following parameters for Shared Drives:

supportsAllDrives=True
driveId -> Id of Shared Drive
parents -> Folder or Shared Drive

Mime Types: List of the supported Mime type here

Tip:

If you want to convert the uploaded file to Google Drive native format use the following parameter:

"mimeType": "application/vnd.google-apps.document",

Google documentation: https://developers.google.com/drive/api/guides/manage-uploads

And this article on StackOverflow as well helped to find the solution although some parameters are wrong or deprecated already: https://stackoverflow.com/questions/67622131/google-drive-api-v3-googleapiclient-errors-httperror-404-file-not-found