โŒ

Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

What can I do if I get error in pixela api?

My code and another person's code are exactly the same except the username id or token but mine gives an error: username doesn't exists or token is wrong.

Here is my code:

import requests

USERNAME = "khush69"
TOKEN = "hdlsshhieh4466ohs9w"

pixela_endpoint = "https://pixe.la/v1/users"

user_params = {
    "token": TOKEN,
    "username": USERNAME,
    "agreeTermsOfService": "yes",
    "notMinor": "yes"
}


graph_endoint = f"{pixela_endpoint}/{USERNAME}/graphs"

graph_config = {
    "id": "graph6969",
    "name": "Coding Learning Graph",
    "unit": "hour",
    "type": "float",
    "color": "shibafu"
}

headers = {
    "X-USER-TOKEN":TOKEN
}

response = requests.post(url=graph_endoint, json=graph_config, headers=headers)
print(response.text)

Elastic Bean Stalk API's issue

I have my environment running on elastic bean stalk and its deployed sucessfully also have enabled https on the environment and link is working fine but the issue is: I have my python backend hosted using elastic bean stalk but when accessing the API's only the root i.e. / is working rest all the API's i.e. /get_details for example is not working.

Any help would be appreciated, Thanks.

Tried testing on local, checked DynamoDB settings etc, its all good.

How to refresh CSRF token on login when using cookie authentication without identity in ASP .NET Core Web API

I have an ASP .NET Core 3.1 backend, with angular 9 frontend (based on dotnet angular template, just with updated angular to v9). I use cookie authentication (I know JWT is more suited for SPAs, take this as an experiment) and I also added support for CSRF protection on server side:

services.AddAntiforgery(options =>
{
   options.HeaderName = "X-XSRF-TOKEN"; // angular csrf header name
});

I have server side setup to automatically check CSRF using

options => options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute())

so GET requests are not checked against CSRF, but POST are.

At the very beginning, the angular app makes a GET request to api/init to get some initial data before bootstrapping. On server-side this action initializes CSRF as follows:

// init action body
var tokens = _antiForgery.GetAndStoreTokens(HttpContext);
Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions
{
   HttpOnly = false
});
// return some inital data DTO

This works as expected - the GET response contains 2 CSRF cookies - first being ASP .NET core default CSRF cookie .AspNetCore.Antiforgery... and second being XSRF-TOKEN that angular will read and put into X-XSRF-TOKEN header for subsequent requests.

If afterwards I do login (POST request containing credentials to api/auth/login) from the angular app, everything works - request is POSTed including X-XSRF-TOKEN header and CSRF validation passes, so if credentials are correct the user is logged in.

Now here is where the problems begin. The ASP .NET server app uses cookie authentication without identity as described here https://learn.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-3.1. In login action also CSRF token needs to be regenerated as with authentication the CSRF token starts including authenticated user identity. Therefore my login action looks like this:

public async Task<IActionResult> Login(CredentialsDto credentials)
{
   // fake user credentials check
   if (credentials.Login != "admin" || credentials.Password != "admin")
   {
      return Unauthorized();
   }

   var claimsIdentity = new ClaimsIdentity(new[]
   {
     new Claim(ClaimTypes.Name, "theAdmin"),
   }, CookieAuthenticationDefaults.AuthenticationScheme);

   var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
   await HttpContext.SignInAsync(claimsPrincipal); 

   // refresh antiforgery token on login (same code as in init action before)
   var tokens = _antiForgery.GetAndStoreTokens(HttpContext);
   Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions 
   {
       HttpOnly = false
   });

   return new JsonResult(new UserDto { Id = 1, Login = "theAdmin" });
}

This however does not work. The response contains the XSRF-TOKEN cookie, but subsequent POST request (in my case its logout = POST to api/auth/logout) fails with 400, despite angular correctly putting this cookie value into X-XSRF-TOKEN header. I believe the reason is that the dafault .AspNetCore.Antiforgery... cookie is not being set in the response for some reason, therefore retains the original value even after login and thus CSRF check fails as the values don't match,

How does one properly refresh the CSRF token is such scenario?

Select parent and only some fields from child in @OneToMany relationships using JPA and Criteria Builder

Implemented one to many relationship and select parent and child I have a onetomany relationship. Using criteria builder, i need to get parent and all related childs but selecting only some fields from each child.

@Entity
@Table(name="transaction_status")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class TransactionStatus implements Serializable {
@Id
@Column(name = "id")
@JsonProperty("id")
public String id;

@SerializedName("status")
public String status;

@Column(name="lastUpdatedDate")
@JsonProperty("lastUpdatedDate")
@SerializedName("lastUpdatedDate")
private Date lastUpdatedDate;

@JsonProperty("generatedAt")
@SerializedName("generatedAt")
@JsonIgnore
private Date generatedAt;

@JsonProperty("invoices")
@SerializedName("invoices")
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name="transactionstatusId",referencedColumnName = "xmlFilename")
private List<InvoiceTransaction> invoiceTransactions = new ArrayList<>();

}

@Entity
@Table(name="invoice_transaction")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor

public class InvoiceTransaction implements Serializable {
    @Column(name = "status", nullable = false)
    @JsonProperty("status")
    @SerializedName("status")
    private String status;
    @Column(name = "originalStatus", nullable = false)
    @JsonProperty("originalStatus")
    @SerializedName("originalStatus")
    private String originalStatus;
    
    @Column(name = "errorMessage")
    @JsonProperty("errorMessage")
    @SerializedName("errorMessage")
    private String errorMessage;

    @Column(name = "generatedAt" )
    @JsonProperty("generatedAt")
    @SerializedName("generatedAt")
    private Date generatedAt;
}

CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<TransactionStatus> cq = builder.createQuery(TransactionStatus.class);
Root<TransactionStatus> rootTrnStatus = cq.from(TransactionStatus.class);
List<TransactionStatus> resultList = entityManager.createQuery(cq).getResultList();

this implementation, gives me list of Transactionstatus objetc with list of its childs. what im seraching to get is: list of Transactionstatus object with list of its childs with olny status and errorMessage fileds. How can i get this result using Crtiteria builder? thank you

LangChain with OpenAI not return full products in RAG QnA

I used the Python LangChain UnstructuredURLLoader to retrieve all our products on the company website for RAG purposes. The products were on different pages in the company website.

UnstructuredURLLoader was able to retrieve the products in multiple Document objects before they were chunked, embedded and stored in the vector database.

With the OpenAI LLM and RAG module, I asked the AI, "How many products in the company A?" AI replied "There are 11 products. You should check the company website for more info..."

If I asked "Please list all the products in the company A", AI replied the list of the 11 products only.

The problem is, there are more than 11 products. Why can't LLM read and aggregate the products in the Documents to count and to return all of the products?

Is there any context hint or prompt to tell LLM to read and return all products? Is it because of the chunking process?

How to upload to google drive with service account and php

Down you can see my code and it uploads files to my google drive. Now I am trying to use service account to let the people to upload files to my Google drive without their google accounts (Visitors will submit html form with their file and my app will upload that file to my drive ). But I am stuck with it. Can not find even just one working example. Any ideas?

$client = new Google\Client();
$client->setAuthConfig('credentials.json');
$client->addScope(Google\Service\Drive::DRIVE);
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$client->setRedirectUri($redirect_uri);

if (isset($_GET['code'])) {
    $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
    $client->setAccessToken($token);

    // store in the session also
    $_SESSION['upload_token'] = $token;

    // redirect back to the example
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
if (!empty($_SESSION['upload_token'])) {
    $client->setAccessToken($_SESSION['upload_token']);
    if ($client->isAccessTokenExpired()) {
        unset($_SESSION['upload_token']);
    }
} else {
    $authUrl = $client->createAuthUrl();
}
echo $client->getAccessToken();
if ($_SERVER['REQUEST_METHOD'] == 'GET' && $client->getAccessToken()) {
    // We'll setup an empty 1MB file to upload.
    DEFINE("TESTFILE", 'test.jpg');
    if (!file_exists(TESTFILE)) {
        $fh = fopen(TESTFILE, 'w');
        fseek($fh, 1024 * 1024);
        fwrite($fh, "!", 1);
        fclose($fh);
    }

    // This is uploading a file directly, with no metadata associated.
    $file = new Google\Service\Drive\DriveFile();
    $service = new Google_Service_Drive($client);
    $file->setName("Hello World!");
    $result = $service->files->create(
        $file,
        [
            'data' => file_get_contents(TESTFILE),
            'mimeType' => 'application/octet-stream',
            'uploadType' => 'media'
        ]
    );
    $permissionService = new Google_Service_Drive_Permission();
    $permissionService->role = "reader";
    $permissionService->type = "anyone"; // anyone with the link can view the file
    $service->permissions->create($result->id, $permissionService);

Is it possible to retrieve default reports and its available columns via Microsoft advertising API?

Question 1

Here are 41 default reports provided by Microsoft Advertising. Is there a Microsoft Advertising API to get the name (or some other identifier) of these 41 default reports?

(I would like to build my own UI to select a report, but I do not want to hardcode the 41 options, that's why I am looking for an API approach)

enter image description here

Question 2

Below is one default report called Campaign

This report has 100+ columns to choose from. Is there a Microsoft Advertising API to get the name of the columns based on the report I choose?

enter image description here

WINAPI Esc key handling in Dialog

There had been written multiple posts on internet about the people annoyed by default ESC key handling in dialog boxes, but this is what I actually expect but cannot have. In shorts my dialog definition in resources

ID_DIALOG DIALOGEX 0, 0, 200, 200
STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
EXSTYLE WS_EX_TOOLWINDOW
CAPTION "Dialog"
FONT 8, "MS Sans Serif"
BEGIN
PUSHBUTTON "Cancel", ID_CUSTOM_CANCEL, 10, 10, 50, 14
END

I show this dialog by:

DialogBox(NULL, MAKEINTRESOURCE(ID_DIALOG), hwnd_main, DialogCallback);

When I click the button, dialog callback function is called with Message == WM_COMMAND and lParam==ID_CUSTOM_CANCEL.

When I click "close" button on dialog caption, dialog callback function is called with Message == WM_COMMAND and lParam==ID_CANCEL.

But when I press ESC key, dialog callback function is never called.

I know there are few methods to handle that in my code, but I expect Windows should have a kind native support as have ENTER key support for default pushbutton. I know I could handle same by WM_KEYDOWN or define accelerator keys, but is there any less "manual" way to handle that?

While testing different dialog behaviours I noticed if I add TEXT control and enter this control then ESC works like magic. I initially assumed the problem was with TABSTOP settings, as even in example above I did not add WS_TABSTOP to PUSHBUTTON, but then I found the TABSTOP does not work, until I manually select one control on the dialog. Following this path I found the solution of my problem. Somebody else had same problem with TABSTOP, and the root cause was missingreturn TRUE at the end of WM_INITDIALOG. Worked as charm for me, both ESC key and TABSTOP works now. It looks like dialog nomatter if it is on the top of everything on the screen, it has not have a kind of focus if WM_INITDIALOG has not been processed correctly.

How to prevent the duplicate result from previous frame in python object tracking

Currently, I work on Object detection, tracking and counting and I want to store the result from object detection ,tracking, and counting and whenever the vehicle cross the line, the result always give me duplicate. how can i prevent that

and here for the camera code

class Camera(BaseCamera): """ OpenCV video stream """ video_source = 0 start, end = Point(0, 500), Point(1280, 500) detector = Detector() tracker = ByteTrack() line_zone = LineZone(start=start, end=end) annotator = LineZoneAnnotator()

def __init__(self, enable_detection: bool = False):
    video_source = os.environ.get("VIDEO_SOURCE")
    try:
        video_source = int(video_source)
    except Exception as exp:    # pylint: disable=broad-except
        if not video_source:
            raise EnvironmentError("Cannot open the video source!") from exp
    finally:
        Camera.set_video_source(video_source)
    super().__init__()
    self.enable_detection = enable_detection

@staticmethod
def set_video_source(source):
    """Set video source"""
    Camera.video_source = source

@classmethod
def frames(cls):
    """
    Get video frame
    """
    camera = cv2.VideoCapture(Camera.video_source)
    if not camera.isOpened():
        raise RuntimeError("Could not start camera.")

    while True:
        # read current frame
        ret, img = camera.read()

        # Loop back
        if not ret:
            camera.set(cv2.CAP_PROP_POS_FRAMES, 0)
            continue

        # Object detection
        results = cls.detector(image=img)
        selected_classes = [ 2, 3]

        tensorflow_results = results.detections
        cls.annotator.annotate(img, cls.line_zone)
        if not tensorflow_results:
            yield cv2.imencode(".jpg", img)[1].tobytes()
            continue

        detections = Detections.from_tensorflow(tensorflow_results=tensorflow_results)

        detections = cls.tracker.update_with_detections(detections=detections)
        detections = detections[np.isin(detections.class_id, selected_classes)]
        
        result=cls.line_zone.trigger(detections)
        if type(result)!=type(None) and len(result)>=3:

            print(result[2])
            
        img = visualize(image=img, detections=detections)

        # encode as a jpeg image and return it
        yield cv2.imencode(".jpg", img)[1].tobytes()

Android Instagram login integration

I'm trying to perform social login via Instagram without Graph API and read all the necessary stuff related to it from the Instagram documentation and StackOverflow.

Following are the things I have done in my project till now:

  1. Login developer account of Instagram via my username password.

  2. Manage client > Register new client and add generated Client Id, Secret key and redirect URL in my constant file.

  3. And for the web view, my complete URL is: https://api.instagram.com/oauth/authorize/?client_id=af7efcca661e43459b1e502af7ddb689&redirect_url=https://instagram.com/&response_type=token&scope=basic+public_content

  4. When I enter the username and password in WebView rather than to navigate it on redirect URL it is continuously showing me error on WebView as: {"error_type": "OAuthException", "code": 400, "error_message": "You must include a valid client_id, response_type, and redirect_uri parameters"}

  5. I want to receive access_token but it is showing my error.

Below is my needed code:

MainActivity.java

public class MainActivity extends AppCompatActivity implements AuthenticationListener {

    private AuthenticationDialog authDialog;
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        context = this;
    }

    @Override
    public void onCodeReceived(String token) {
        if (token == null)
            return;
    }

    @OnClick(R.id.buttonLogin)
    public void loginClick() {
        authDialog = new AuthenticationDialog(this, this);
        authDialog.setCancelable(true);
        authDialog.getWindow().setLayout(((getWidth(context) / 100) * 90), LinearLayout.LayoutParams.MATCH_PARENT);
        authDialog.getWindow().setGravity(Gravity.CENTER);
        authDialog.show();
    }

    public static int getWidth(Context context) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        WindowManager windowmanager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        windowmanager.getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.widthPixels;
    }
}

AuthenticationDialog.java

public class AuthenticationDialog extends Dialog {
    private String TAG = AuthenticationDialog.class.getSimpleName();
    private AuthenticationListener listener;
    private Context context;
    private WebView webView;

    private final String url = Constants.BASE_URL + "oauth/authorize/?client_id=" +
            Constants.INSTAGRAM_CLIENT_ID
            + "&redirect_url="
            + Constants.REDIRECT_URL
            + "&response_type=token"
            + "&scope=basic+public_content";

    public AuthenticationDialog(@NonNull Context context, AuthenticationListener listener) {
        super(context);

        this.context = context;
        this.listener = listener;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.auth_dialog);
        initializeWebView();
    }

    private void initializeWebView() {
        webView = (WebView) findViewById(R.id.webView);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLoadWithOverviewMode(true);

        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl(url);
        Log.d(TAG, "url: " + url);
        //webView.loadUrl("http://api.instagram.com/");
        //webView.loadUrl("https://api.instagram.com/oauth/authorize/?client_id=af7efcca661e43459b1e502af7ddb689&redirect_uri=https://instagram.com/&response_type=token&scope=basic+public_content");
        webView.setWebViewClient(new WebViewClient() {

            String access_token;
            boolean authComplete;

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                Log.d(TAG, "onPageStarted called");
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                Log.d(TAG, "onPageFinished called");
                if (url.contains("#access_token=") && !authComplete) {
                    Log.d(TAG, " inside access_token");
                    Uri uri = Uri.parse(url);
                    access_token = uri.getEncodedFragment();
                    //get the whole token after "=" sign
                    access_token = access_token.substring(access_token.lastIndexOf("=") + 1);
                    Log.d(TAG, "token: " + access_token);
                    authComplete = true;
                    listener.onCodeReceived(access_token);
                    dismiss();
                } else if (url.contains("?error")) {
                    Log.d(TAG, "getting error fetching access token");
                    dismiss();
                } else {
                    Log.d(TAG, "outside both" + url.toString());
                }
            }
        });
    }
}

and according to logs the code is coming in last else "outside both" Also the WebView is showing the error which I mentioned in point no. 4.

Can anyone please help?

WorkAround for GitHub Rate Limit on powerbi Custom Query

I am a powerbi developer. my company has many organizations under their name and each organization have many repos (around 300+).

I was able to write 4 tables in power query powerbi Table 1. Get all organization and repo names.

I will use table 1 as reference to my next 3 table so I don't call the same code twice to get repos.

Table 2. Get issues of all states for each repo. Table 3. Get pulls of all states for each repo. Table 4. Get commits for each repo.

however, the data can never fully load because I always hit the 5000-rate limit hourly even though i limited the data since 2 months ago only.

is there a workaround? I am not abusing the Api for web scarping I want to analyse the performance of our developers. like maybe a custom connector, a different approach. i prefer keeping things free

i tried limiting dates, i tried reading GraphQL but i have no idea how to translate it to powerquery and i am no computer science guru. i only know python and m query as programming languages.

"Client Invalid Error" Discord API for OAuth2

I was coding a basic program in JavaScript using axios and express to learn more about how OAuth2 worked when my client All of the sudden gave an error.

This is the part of the code it errors on.

//^^^^^^^^^^
// defining web server

const formData = new url.URLSearchParams({
    client_id: webid,
    client_secret: websecret,
    grant_type: 'authorization_code',
    code: code.toString(),
    redirect_uri: redirect_uri,
});

const oauthInfo = await axios.post('https://discord.com/api/v10/oauth2/token',
    formData, {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        }
});

// below is starting everything           

Full code: https://pastebin.com/FbHVkKRi

Cannot read properties of undefined (reading 'choices') in React application using OpenAI API

Edit: Issue was solved

I'm working on a React application where I'm using the OpenAI API to communicate with the AI. In my application, I'm trying to send user input to the API and receive a response from the AI. However, I'm encountering the following error:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'choices')
    at sendMsgToOpenAI (openai.js:15:1)
    at async handleSend

Here's the relevant portion of my code:

App component (App.js)

import './App.css';
import AIlogo from './assets/chatgpt.svg';
import addBtn from './assets/add-30.png';
import msgIcon from './assets/message.svg';
import home from './assets/home.svg';
import saved from './assets/bookmark.svg';
import upgrade from './assets/rocket.svg';
import sendBtn from './assets/send.svg';
import userIcon from './assets/user.svg';
import AIchat from './assets/chatgptLogo.svg';
import { sendMsgToOpenAI } from './openai';
import { useState } from 'react';

function App() {

  const[input, setInput] = useState("");

const handleSend = async() => {

  const res = await sendMsgToOpenAI(input);
  console.log(res);
}

  return (
    <div className="App">
      <div className ="sideBar">
     <div className ="upperSide">
     
     <div className ="upperSideTop"><img src={AIlogo} alt="Logo" className="logo"/><span className="brand">Eclipse AI</span>  
     <button className="midBtn"><img src={addBtn} alt="" className="addBtn" />New Chat</button>
      
     <div className="upprtSideBottom">
      
    <button className="query"><img src={msgIcon} alt=""/> What is Programming ?</button>
    <button className="query"><img src={msgIcon} alt=""/> How to use an API ?</button>
    </div>
     </div>
     </div>


   
        
       <div className ="lowerSide">
       <div className ="listItems"><img src={home} alt="" className="listitemsImg" />Home</div>
       <div className ="listItems"><img src={saved} alt="" className="listitemsImg" />Saved</div>
       <div className ="listItems"><img src={upgrade} alt="" className="listitemsImg" />Upgrade to Pro</div>
       </div>
     </div>

     <div className ="main">
<div className="chats">

<div className="chat">
 <img src={AIchat} alt=""/><p className="txt">uncountable noun [usu with supp] You can use stuff to refer to things such as a substance, a collection of things, events, or ideas, or the contents of something in a general way without mentioning the thing itself by name.</p>
 <img src={userIcon} alt=""/><p className="txt">uncountable noun [usu with supp] You can use stuff to refer to things such as a substance, a collection of things, events, or ideas, or the contents of something in a general way without mentioning the thing itself by name.</p>
</div>
</div>
 



<div className="chatFooter">
  <div className="inp">
    <input type="text" placeholder='Message EclipseAI' value={input} onChange={(e)=>{setInput(e.target.value)}} /><button className="send" onClick={handleSend}><img src={sendBtn} alt="send-icon" /></button>

  </div>
  <p>This page of EclipseAI is still under development, including the user interface.</p>
</div>
     </div>
    </div>
  );
}

export default App;

OpenAI function (openai.js):

const OpenAI = require('openai');

const openai = new OpenAI({ apiKey: 'Key in here', dangerouslyAllowBrowser: true });

export async function sendMsgToOpenAI(message) {
    const res = await openai.completions.create({
        model: 'gpt-3.5-turbo-instruct',
        prompt: message,
        temperature: 0.7,
        max_tokens: 256,
        top_p: 1,
        frequency_penalty: 0,
        presence_penalty: 0
    });
    return res.data.choices[0].text;
}

The error occurs when I try to call the sendMsgToOpenAI function. Specifically, it happens when trying to access res.data.choices[0].text.

What I've tried:

Checked that the API key is correct and authorized for the model I'm using. Verified that I'm using the correct API endpoint.

Additional Information:

I'm using gpt-3.5-turbo-instruct as the model.

I was following a YouTube tutorial to set up this application, Link to tutorial: https://www.youtube.com/watch?v=EzkWAviyYgg&t=392s&ab_channel=GreatStack

Has anyone else encountered this error or know how to resolve it? Any help would be appreciated.

Solution:

Replacing return res.data.choices[0].text With return res.choices[0].text

How to Delay a Fetch Request in JavaScript Without Using setTimeout or setInterval?

I'm working on a JavaScript project where I need to delay a fetch request. However, due to some project constraints, I can't use setTimeout or setInterval. I'm aware that these are the usual methods for delaying execution in JavaScript, but I need an alternative approach because these functions have been overridden in our codebase.

I've considered using Promise or busy-waiting with a while loop, but these methods are not ideal as they either still use setTimeout under the hood or block the execution of other code.

Here's a basic example of the kind of operation I'm trying to perform:

async function delayedFetch(url, delayTime) {
  // Need to delay here without using setTimeout or setInterval
  const response = await fetch(url);
  const data = await response.json();
  return data;
}

delayedFetch('https://api.example.com/data', 2000)
  .then(data => console.log(data));

View Transitions API page scrolling up visibility problem

I have been exploring the new View Transitions API for MPAs (experimental for now). When I add the view transitions meta tag t pages it works okay, when using custom view transition names - eg. an image and a title move in place onto the new page - but in any other case (with the default crossfade) the old/current page scrolls up at the start of the transition visibly (a quick flash of page content) - which is a quite distracting visual bug - that ruins the whole animation for transitioning, and I can't seem to find what causes it.

I've tried to debug doing the following:

  • removed all javascript functions, the old (current) page scrolling up still appears
  • tried hiding the old or the new state while transitioning, still visible
  • tried removing all the css that was added to the new page after the view transition css rules, did nothing
  • find anything online, but its too new of an API that is still flagged experimental

I have no idea where to go next with it, I cant seem to grasp the concept of what could cause the page scrolling up when the page is stripped from every js function.

Does anybody else run into this issue before? Any solution maybe?

Google Drive to Google Sheets file details added on a or after a certain Date

I am trying to get a list of all files available in my google drive to google sheets. However if there are more than 500 files, i get exceeds time-out error. After searching the whole internet and stackoverflow i found that there is not definite solution to this. So I have came with an idea that can we check if the created date of the file is say less than 5 days old and get the data. I will use another sheet to manually copy the data periodically, where we will have a master list of all files in the drive.

The working code which extracts file details from google drive is here.

function getNewFileIds() {
  PropertiesService.getScriptProperties().setProperty("newids", "[]");
  getFileIds(DriveApp.getFolderById("folderid"));
  return JSON.parse(PropertiesService.getScriptProperties().getProperty("newids"))
}

function getFileIds(fldr) {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("SheetName");
  const curids = sh.getRange(2, 1, sh.getLastRow() - 1).getValues().flat();
  var newids = JSON.parse(PropertiesService.getScriptProperties().getProperty("newids"));
  let files = fldr.getFiles();
  while (files.hasNext()) {
    let f = files.next();
    let id = f.getId();
    if (!~curids.indexOf(id)) {
      newids.push(id)
      PropertiesService.getScriptProperties().setProperty("newids", JSON.stringify(newids));
    }
  }
  let fldrs = fldr.getFolders();
  while (fldrs.hasNext()) {
    let fdr = fldrs.next();
    PropertiesService.getScriptProperties().setProperty("newids", JSON.stringify(newids));
    getFileIds(fdr);
  }
}

function addFiles(newids) {
  var sh = SpreadsheetApp.getActiveSheet();
  var data = [];
  var idA = newids;
  idA.forEach(id => {
    let f = DriveApp.getFileById(id)
    data.push([f.getParents[0], f.getName(), f.getDateCreated(), f.getUrl(), f.getMimeType()])
  })
  sh.getRange(sh.getLastRow() + 1, 1, data.length,data[0].length).setValues(data);
}

What I want is can we have check to find out what all files were created 5 days before something to do with say f.getDateCreated() - (5 days from sysdate), but i am not at all a good techie.

If anyone has such idea please help. Thanks and regards, Ank

โŒ
โŒ