2022-07-31

How to get user info on a static page?

I'm hosting a static page/site on GCP App Engine (written in standard js/html/css), on a company domain ;

I know in localhost testing I can't get the user info in any way (which is fine, I'll hardcode dummy data).

But after using gcloud app deploy and running it on the engine, is there a way to obtain user info somehow? Name, email etc. Ideally just through the app somehow - or even by calling a google cloud function or something.

Nb. I have activated IAP so when hosted, the user does go through google auth on this site (all domain users are allowed in).



new line in textarea while looping with props

Given this snippet, how can I insert a new line at the specified position?

<div>
    <textarea>:  </textarea>
----------------------------------------------------------^
</div>

<br> and \n are printed as text inside textarea

Right now, I'm cheating like this

<div>
    <textarea>: 
</textarea>
</div>

This also works, but I get two new lines per loop and big indentation per line

<div>
    <textarea>
        
            : 
        
    </textarea>
</div>

I would like to maintain code readability like the first or last example



JOIN 2 tables based on req.query in a 3rd table

I have 3 tables (deals, deals_media, access_to_deals)

deals                     deals_media                     access (to deals)
name     pic_url          type   media_url  deal_id       customer_id       deal_id
deal1    http://blah      video  url.       1             1                 1
deal2    http://blah2     img    url2.      1             1                 2
deal3    http://blah3     video  url3.      2             2                 1

I'm sending an api get request with a customer_id query parameter.

I want to send back an array of objects with all the deals data the customer is eligible for and to join an array of matching deals_media to the deals.id

I'm using sequalize and await functions and my query looks like:

sync (req, res) => {
    try {
        const customerId = req.query.customer_id;
        let deals = await db.sequelize.query(
            'SELECT DISTINCT deals.* FROM deals \n' +
            'JOIN access ON deals.id = access.deals_id AND access.customerId=$1 \n' +
            'LEFT JOIN media ON deals.id = media.deals_id \n',
            { bind: [customerId], type: 'RAW' },
        );
        res.send(campaign[0]);
    } catch (err) {...}
};

my response data looks like:

   {
       "id":1,
       "deal_name": "deal1",
       "other data": "data,
       "media type": "video",
       "media URL": "https://www.......",
       "deals_id": 1
    },
    {
       "id":2,
       "deal_name": "deal1",
       "other data": "data,
       "media type": "picture",
       "media URL": "https://www.......",
       "deals_id": 1
    },
    {
       "id":3,
       "deal_name": "deal1",
       "other data": "data,
       "media type": "audio",
       "media URL": "https://www.......",
       "deals_id": 1
    }
]

and I'd prefer it came out as:

    {
       "id":1,
       "deal_name": "deal1",
       "other data": "data,
       "media": [
           {
                "media type": "video",
                "media URL": "https://www......."
           },
           {
                "media type": "picture",
                "media URL": "https://www......."
           },
           {
                "media type": "audio",
                "media URL": "https://www......."
           }
]

I've tried to change the last join to 'LEFT JOIN media ON deals.id = media.deals_id GROUP BY media.deals_id \n' however I get an error to include deals.id and media.id to the GROUP BY and then it produces the same incorrect query result as above. I'm relatively new to SQL so any direction is greatly appreciated. Many thanks for considering my request.



Access and Query tables in Datadog

We have a logs table in PostgreSQL and would like to visualize some metrics(table columns) on data dog. Is it possible to retrieve data using SQL from tables in datadog?



Debugging Perl scripts without interactive debugger

I've been tasked with understanding and debugging some legacy code written in Perl 5. The comments aren't great, and I have almost zero experience with the language (I'm a Python guy; some shell scripting experience). Basically, I need to understand it to the point where I can decide if it will be worth it to rewrite it in Python to match the rest of our code base and be more readable to those who aren't familiar with Perl's less obvious syntax (at least, to the uninitated...) or just leave it as is and do our best to make small changes as necessary despite having an incomplete understanding of what's going on.

Perl is being invoked to process some data from within a script in our organization's internal scripting language (which is used to interact with our proprietary hardware). The part written in the in the proprietary scripting language is similar to a shellscript in that every line sent to the interpreter will be written in the log, so while not as easy as debugging something like Python in a modern IDE, it's possible to figure out what's going on by checking the logs. But perl, as a programming language, only prints/logs what you tell it to. So as of right now, it's kind of a black box.

I looked at the Perl docs and saw that there is a command line option to launch the debugger -d, along with -Dtls to configure debugger behavior (those are the recommend options to "watch how perl executes your program"). But when I tried running that in the script, i got the following...warning? error?

Recompile perl with -DDEBUGGING to use -D switch (did you mean -d ?)

Because it's being called inside a proprietary-scripting langauge script, if this debugger is just an interactive shell, I don't think it will suit this purpose (because I can't send things to stdin while the proprietary-scripting langauge script is running). But if it's not interactive, adding a 2nd perl installation to the server for debugging wouldn't be out of the question, so if anyone has experience with this debugger mode, and options, I would appreciate some feedback about that.

I'm quite familiar with Python, so I know alot of tricks to log everything or to set up a debug environment to use the VS code debugger, but with Perl, I'm out of my comfort zone.

My question is: is there some sort of easy way (a flag or something) to call Perl in such a way where every command sent to the interpreter is written to the console/stdout/ or a logfile in the same way as a shell script? Or is there another good way to debug perl scripts (other than using the interactive debug shell)? Or do I have no better option than to take the time to go through this rather massive script and put print statements everywhere?

Thanks for reading a lengthy question.



2022-07-30

(MSWord VBA) Add " symbol to search string

I'm trying to get a simple macro to work in MS word. The macro is supposed find a definition in contracts. These are typically marked within quotes (e.g. "Definition"). Hence, I want to select a word that I want to search the definition for and execute a search for the selected term in quotes.

However, for some reason, I can't get it to work reliably. I've gone through the code debugging it, but the MySearchTrim variable ends up just containing

""selectiontext

while I would need it to be

"selectiontext"

I've tried it with inserting the quotes by adding the quotes through

&"""

but it only worked in 30% of the cases, which I find very confusing.

Can anyone help me spot the error?

Thanks!

Sub GehZuDefinition()

Dim MySearchterm
Dim MySearchTrim As String
Dim myWindow As Window
    
    MySearchterm = Selection.Text
    MySearchTrim = Chr(34) & Trim(MySearchterm) & Chr(34) ' trimming spaces after searchterm that are typically selected
    
    Selection.Find.ClearFormatting
    With Selection.Find
        .Text = MySearchTrim
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = True
        .MatchWholeWord = False
        .MatchKashida = False
        .MatchDiacritics = False
        .MatchAlefHamza = False
        .MatchControl = False
        .MatchByte = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute
    
End Sub


Why do g++ binaries have a significantly slower startup time than clang++?

Whenever I compile code using g++, I've noticed that when I run the binary repeatedly, it runs significantly slower than when I compile with clang++.

test.cpp

#include <iostream>

int main() {
    std::cout << "Hello World!" << '\n';
}

script.sh

for ((i=0; i<2000; ++i)); do
    ./a.out
done

Compiling using g++:
g++-11 -O2 test.cpp
time bash script.sh -> 10.32s user 5.37s system 88% cpu 17.751 total

Compiling using clang++:
clang++ -O2 test.cpp
time bash script.sh -> 1.42s user 1.50s system 69% cpu 4.223 total


This is extremely annoying as I need to use g++, but I also need to speed up the binary to make it easier to stress test my code, so an explanation or fix would be welcome.

Note: GCC (11.3, via homebrew), clang (13.1, apple/homebrew (both seem to be the same))



What happens with Azure Service Bus when the triggering function is spun down?

We have a regular problem every couple days where some messages we sent to ServiceBus suddenly and rapidly go to the DLQ. We have it configured to try 10 times and suddenly messages across several queues in the same Function Solution (.Net 6) all DLQ with 10 delivery failures very rapidly.

I understand that messages are locked and eventually released if not processed through and I understand how to configure our functions exponential retry policy on the ServiceBus trigger but in these cases what I see appears to be related to “cold start”.

Looking at when the message went to the DLQ in each queue I see that the central resource available memory drops to zero for about 2-3 minutes before picking back up which I believe is an indication of the functions being spun down for inactivity. However, if I stop the functions myself the messages just stay in the active queue. They don’t go straight to the DLQ.

So, if I’m right and this is related to inactivity shutdown and a typical cold start problem… why doesn’t this happen when I stop the functions myself and continue to send it messages?

Is this maybe because the functions had locked the messages right before being shutdown by Azure and while being spun down were in a state where Service Bus was continuing to deliver because it wasn’t yet aware that the functions were down?

If this is the case, what are my options? I know I can control the speed of delivery on the function trigger but if the function is shutting down how can I control the speed at which ServiceBus tried to deliver the message? I experimented with RetryExponential when creating the QueueClient on the send side but that didn’t slow down the delivery attempts or control the number of times it tried.

Edit: Here's a typical example of one that's DLQ'ing: (Names changed. IProcessor should be obvious enough from Processor.cs. The IMyHttpClient class is a class using the HttpClient pattern in startup: services.AddHttpClient(IMyHttpClient, HttpClient);

public class ProcessItem_ServiceBus
{
    private readonly IProcessor _processor;
    private readonly TelemetryClient _telemetry;

    public ProcessItem_ServiceBus(TelemetryConfiguration configuration, IProcessor processor)
    {
        this._telemetry = new TelemetryClient(configuration);
        _processor = processor;
    }

    [FunctionName("ProcessItem_ServiceBus")]
    public async Task Run([ServiceBusTrigger(Constants.ITEM_QUEUE, Connection = "ServiceBusConnectionString")] Message item, ILogger log)
    {
        Item itemToProcess =  null;
        try
        {
            itemToProcess = JsonConvert.DeserializeObject<Item>(Encoding.UTF8.GetString(item.Body), new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
        }
        catch (Exception ex)
        {
            log.LogError(ex, "Failed to process item");
            _telemetry.TrackEvent(Constants.ITEM_PROCESSING_FAILED);
            throw ex;
        }
        await _processor.ProcessItem(itemToProcess);
    }
}

public class Processor: IProcessor
{
    private readonly TelemetryClient _telemetry;
    private readonly ILogger<Processor> _logger;
    private readonly IMapper _autoMapper;
    private readonly IMyConfig _myConfig;
    private readonly IMyHttpClient _httpClient;
    private readonly IHttpClientConfig _httpClientConfig;

    public ProcessPaymentReceiptHelper(TelemetryConfiguration configuration,
        IMyHttpClient httpClient,
        IMyConfig myConfig, 
        IHttpClientConfig httpClientConfig, 
        IMapper autoMapper, 
        ILogger<Processor> logger
        )
    {
        _telemetry = new TelemetryClient(configuration);
        _httpClient = httClient;
        _myConfig = myConfig;
        _httpClientConfig = httpClientConfig;
        _autoMapper = autoMapper;
        _logger = logger;
    }

    public async Task ProcessItem(Item itemToProcess)
    {
        _telemetry.TrackEvent(Constants.ITEM_RECEIVED);

        var httpClientRequest = new HttpClientRequest
        {
            Source = Constants.APPLICATION_NAME,
            Channel = _httpClientConfig.Channel
        };

        _autoMapper.Map<Item, HttpClientRequest>(item, httpClientRequest);

        var response = await _httpClient.PostItem(httpClientRequest);
        _telemetry.TrackEvent(Constants.ITEM_POSTED);
    }
}

It's a pretty straight forward pattern. Most of the ones failing in this way are all using the HttpClient to post to different API's. Perhaps it's something in there but those are also very straight forward implementations.



Is there any way to programmatically set a break point then push the button "Export to Excel" in Visual Studio 2022, IEnumerable Visualizer?

Visual Studio 2022 has a feature called IEnumerable Visualizer that allows the user to view a list of objects in a tabular format during debug.

There is already a button which allows the user to "Export to Excel". This button is a very handy feature, and found myself wanting to programmatically "push the export button". I'm familiar with CsvHelpler and other libraries which make it easy to output lists of objects.

But I'm wondering if there is any way to programmatically press the "Export to Excel" button? (like when writing a C# console app)



Flutter/Firestore : How do I display data from doc in a ListTile?

I am new to Flutter/Firebase/Firestore etc.. so I am struggling a bit. I want to grab the data from the documents in my 'users' collection in Firestore and display it in my account information page. I have spent hours messing around with this and I am stuck. If anybody could help me out that would be wonderful!

Here are some samples of what my code, app, and firestore look like.

Code:

signup.dart - this is the page that creates the doc in Firebase on signup

class SignUp extends StatefulWidget {
  const SignUp({Key? key}) : super(key: key);

  @override
  State<SignUp> createState() => _SignUpState();
}

class _SignUpState extends State<SignUp> {
  var emailController = TextEditingController();
  var passwordController = TextEditingController();
  /* var docId = FirebaseFirestore.instance.collection('users').doc().id; */
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _phoneNumberController = TextEditingController();
  final TextEditingController _companyNameController = TextEditingController();
  final FirebaseAuth auth = FirebaseAuth.instance;

  @override
  Widget build(BuildContext context) {

    String docId;
    docId = emailController.text;

    final User? user = auth.currentUser;
    double w = MediaQuery.of(context).size.width;
    double h = MediaQuery.of(context).size.height;
    return Scaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: Colors.white,
      body: Column(
        children: [
          Container(
            width: w,
            height: h * 0.27,
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage("assets/loginsignupheader.png"),
                fit: BoxFit.fitWidth,
              ),
            ),
          ),
          Container(
            margin: const EdgeInsets.only(left: 30, right: 20),
            width: w,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                const Text(
                  'Sign up for an account',
                  style: TextStyle(fontSize: 25, color: Colors.grey),
                ),
                const SizedBox(height: 35),
                Container(
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(30),
                      boxShadow: [
                        BoxShadow(
                            blurRadius: 10,
                            spreadRadius: 7,
                            offset: const Offset(1, 1),
                            color: Colors.grey.withOpacity(0.2))
                      ]),
                  child: TextField(
                    controller: _usernameController,
                    decoration: InputDecoration(
                      hintText: 'Username',
                      prefixIcon: const Icon(Icons.person),
                      focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(30),
                          borderSide: const BorderSide(
                              color: Colors.white, width: 1.0)),
                      enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(30),
                          borderSide: const BorderSide(
                              color: Colors.white, width: 1.0)),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(30),
                      ),
                    ),
                  ),
                ),
                const SizedBox(height: 35),
                Container(
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(30),
                      boxShadow: [
                        BoxShadow(
                            blurRadius: 10,
                            spreadRadius: 7,
                            offset: const Offset(1, 1),
                            color: Colors.grey.withOpacity(0.2))
                      ]),
                  child: TextField(
                    controller: _companyNameController,
                    decoration: InputDecoration(
                      hintText: 'Company Name',
                      prefixIcon: const Icon(Icons.business_center),
                      focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(30),
                          borderSide: const BorderSide(
                              color: Colors.white, width: 1.0)),
                      enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(30),
                          borderSide: const BorderSide(
                              color: Colors.white, width: 1.0)),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(30),
                      ),
                    ),
                  ),
                ),
                const SizedBox(height: 35),
                Container(
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(30),
                      boxShadow: [
                        BoxShadow(
                            blurRadius: 10,
                            spreadRadius: 7,
                            offset: const Offset(1, 1),
                            color: Colors.grey.withOpacity(0.2))
                      ]),
                  child: TextField(
                    controller: _phoneNumberController,
                    decoration: InputDecoration(
                      hintText: 'Phone Number',
                      prefixIcon: const Icon(Icons.phone),
                      focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(30),
                          borderSide: const BorderSide(
                              color: Colors.white, width: 1.0)),
                      enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(30),
                          borderSide: const BorderSide(
                              color: Colors.white, width: 1.0)),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(30),
                      ),
                    ),
                  ),
                ),
                const SizedBox(height: 35),
                Container(
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(30),
                      boxShadow: [
                        BoxShadow(
                            blurRadius: 10,
                            spreadRadius: 7,
                            offset: const Offset(1, 1),
                            color: Colors.grey.withOpacity(0.2))
                      ]),
                  child: TextField(
                    controller: emailController,
                    decoration: InputDecoration(
                      hintText: 'Email',
                      prefixIcon: const Icon(Icons.email_outlined),
                      focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(30),
                          borderSide: const BorderSide(
                              color: Colors.white, width: 1.0)),
                      enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(30),
                          borderSide: const BorderSide(
                              color: Colors.white, width: 1.0)),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(30),
                      ),
                    ),
                  ),
                ),
                const SizedBox(height: 35),
                Container(
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(30),
                      boxShadow: [
                        BoxShadow(
                            blurRadius: 10,
                            spreadRadius: 7,
                            offset: const Offset(1, 1),
                            color: Colors.grey.withOpacity(0.2))
                      ]),
                  child: TextField(
                    controller: passwordController,
                    obscureText: true,
                    decoration: InputDecoration(
                      hintText: 'Password',
                      prefixIcon: const Icon(Icons.password),
                      focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(30),
                          borderSide: const BorderSide(
                              color: Colors.white, width: 1.0)),
                      enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(30),
                          borderSide: const BorderSide(
                              color: Colors.white, width: 1.0)),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(30),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(
            height: 50,
          ),
          GestureDetector(
            onTap: () async {
              AuthController.instance.register(
                  emailController.text.trim(), passwordController.text.trim());
              FirebaseFirestore.instance.collection('users').doc(docId).set({
                'username': _usernameController.text,
                'phone': _phoneNumberController.text,
                'company_name': _companyNameController.text,
                'email': emailController.text
              });
            },
            child: Container(
                width: w * .5,
                height: h * .06,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(30),
                  image: const DecorationImage(
                    image: AssetImage("assets/button.png"),
                    fit: BoxFit.cover,
                  ),
                ),
                child: const Center(
                  child: Text(
                    'Sign Up',
                    style: TextStyle(
                        fontSize: 30,
                        fontWeight: FontWeight.bold,
                        color: Colors.white),
                  ),
                )),
          ),
          SizedBox(height: w * 0.1),
          RichText(
              text: TextSpan(
                  text: "Already have an account?",
                  style: const TextStyle(color: Colors.grey, fontSize: 20),
                  children: [
                TextSpan(
                    text: "  Login",
                    style: const TextStyle(
                        color: Colors.grey,
                        fontSize: 20,
                        fontWeight: FontWeight.bold),
                    recognizer: TapGestureRecognizer()
                      ..onTap = () {
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => const Login()));
                      }),
              ])),
        ],
      ),
    );
  }
}

account.dart - this is the page I want to display my Firestore data on

class Account extends StatefulWidget {
const Account({Key? key}) : super(key: key);

  @override
  State<Account> createState() => _AccountState();
}

class _AccountState extends State<Account> {

@override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey.shade50,
      body: Stack(
        fit: StackFit.expand,
        children: [
          SingleChildScrollView(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                const SizedBox(height: 10),
                const Text(
                  'Account Settings & Info',
                  style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                      color: Colors.black),
                ),
                Card(
                  elevation: 2.0,
                  margin: const EdgeInsets.fromLTRB(16, 8.0, 16, 16.0),
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10)),
                  child: Column(
                    children: <Widget>[
                      const SizedBox(height: 20),
                      Container(
                        width: 75,
                        height: 75,
                        decoration: BoxDecoration(
                          color: Colors.grey[200],
                          borderRadius: BorderRadius.circular(15),
                          image: const DecorationImage(image: AssetImage('assets/tclogotransparent.png'), fit: BoxFit.cover)
                        ),
                      ),
                      const SizedBox(height: 20),
                      const BuildDivider(),
                      ListTile(
                        leading: const Icon(
                          Icons.person,
                          color: Colors.black,
                        ),
                        title: Text('Username: $username'),
                        trailing: const Icon(Icons.keyboard_arrow_right),
                        onTap: () {
                          Navigator.push(context, MaterialPageRoute(builder: (context) => const ChangeEmail()));
                        },
                      ),
                      const BuildDivider(),
                      ListTile(
                        leading: const Icon(
                          Icons.business_center,
                          color: Colors.black,
                        ),
                        title: Text('Company Name: $companyName'),
                        trailing: const Icon(Icons.keyboard_arrow_right),
                        onTap: () {
                          Navigator.push(context, MaterialPageRoute(builder: (context) => const ChangeEmail()));
                        },),
                      const BuildDivider(),
                      ListTile(
                        leading: const Icon(
                          Icons.phone,
                          color: Colors.black,
                        ),
                        title: Text('Phone Number: $phoneNumber'),
                        trailing: const Icon(Icons.keyboard_arrow_right),
                        onTap: () {
                          Navigator.push(context, MaterialPageRoute(builder: (context) => const ChangeEmail()));
                        },
                      ),
                      const BuildDivider(),
                      ListTile(
                        leading: const Icon(
                          Icons.email_outlined,
                          color: Colors.black,
                        ),
                        title: Text('E-Mail: $emailAddress'),
                        trailing: const Icon(Icons.keyboard_arrow_right),
                        onTap: () {
                          Navigator.push(context, MaterialPageRoute(builder: (context) => const ChangeEmail()));
                        },
                      ),
                      const BuildDivider(),
                      ListTile(
                        leading: const Icon(
                          Icons.key,
                          color: Colors.black,
                        ),
                        title: const Text('Change Password'),
                        trailing: const Icon(Icons.keyboard_arrow_right),
                        onTap: () {
                          Navigator.push(context, MaterialPageRoute(builder: (context) => const ChangePassword()));
                        },
                      ),
                      const BuildDivider(),
                      ListTile(
                        leading: const Icon(
                          Icons.upload,
                          color: Colors.black,
                        ),
                        title: const Text('Upload Profile Picture'),
                        trailing: const Icon(Icons.keyboard_arrow_right),
                        onTap: () {
                          
                        },
                      ),
                    ],
                  ),
                ),
                Card(
                  color: Colors.red[50],
                  elevation: 2.0,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10)),
                  margin: const EdgeInsets.all(16),
                  child: ListTile(
                    onTap: () {
                      AuthController.instance.signOut();
                    },
                    title: const Text('Log Out', style: TextStyle(fontWeight: FontWeight.bold, color: Colors.red),),
                    leading: const Icon(Icons.logout_outlined, color: Colors.red)
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

Firestore Docs - I want to take this data and display it in the account page shown below

Edit: I have the document ids being set as the users email, I wanted to try an easy way to recall the document per account. If this is wrong please let me know.

https://i.stack.imgur.com/53TOS.png

Account Page - These are the fields I want to fill with the data, they all say N/A because I have a separate temporary file that uses constants to set those values

https://i.stack.imgur.com/eoHUE.png

Edit: Edited account.dart throws a _CastError

https://i.stack.imgur.com/YRRz9.png



2022-07-29

CodePipeline Deployment error "Invalid argument @ rb_sysopen - C:\ProgramData/Amazon/CodeDeploy/xxxxxxxx/xxxxxx/deployment-archive\*.*"

I am struggling to troubleshoot my CodePipeline that fails in Install event of Deployment stage with the following error:

Invalid argument @ rb_sysopen - C:\ProgramData/Amazon/CodeDeploy/0df66877-d62c-49b0-81b6-a2b98509ed51/d-DC1Q553XH/deployment-archive*.*

enter image description here

I can see that all my app artifacts have been successfully dowloaded and unzipped from CodeBuild artifacts S3 bucket to my EC2 instance (Windows Server 2019) directory: enter image description here

All artifacts match to the latest CideBuild run output. I assume that the @ rb_sysopen argument is related to Ruby unzip program but am not too sure. Considering that the artifacts zip file has been already unzipped in the C:\ProgramData/Amazon/CodeDeploy/... direcory, the error seems weird. This is my appspec.yml file:

 version: 0.0 
 os: windows 
 files: 
    - source:\*.* 
      destination:C:\Webapps\TestWebAPIForCodeBuild

This is a fragment of CodeDeploy log file found in my target EC2 instance:

2022-07-28T03:48:35 DEBUG [codedeploy-agent(5272)]: InstanceAgent::Plugins::CodeDeployPlugin::Installer: generating instructions for copying \*.* to C:\Webapps\TestWebAPIForCodeBuild
2022-07-28T03:48:35 DEBUG [codedeploy-agent(5272)]: InstanceAgent::Plugins::CodeDeployPlugin::Installer: generating instructions for copying \*.* to C:\Webapps\TestWebAPIForCodeBuild
2022-07-28T03:48:35 DEBUG [codedeploy-agent(5272)]: InstanceAgent::Plugins::CodeDeployPlugin::Installer: generating instructions for copying \*.* to C:\Webapps\TestWebAPIForCodeBuild
2022-07-28T03:48:35 DEBUG [codedeploy-agent(5272)]: InstanceAgent::Plugins::CodeDeployPlugin::CommandBuilder: Copying C:\ProgramData/Amazon/CodeDeploy/0df66877-d62c-49b0-81b6-a2b98509ed51/d-DC1Q553XH/deployment-archive\*.* to C:/Webapps/TestWebAPIForCodeBuild/*.*
2022-07-28T03:48:35 DEBUG [codedeploy-agent(5272)]: InstanceAgent::Plugins::CodeDeployPlugin::CommandBuilder: Copying C:\ProgramData/Amazon/CodeDeploy/0df66877-d62c-49b0-81b6-a2b98509ed51/d-DC1Q553XH/deployment-archive\*.* to C:/Webapps/TestWebAPIForCodeBuild/*.*
2022-07-28T03:48:35 DEBUG [codedeploy-agent(5272)]: InstanceAgent::Plugins::CodeDeployPlugin::CommandPoller: Calling PutHostCommandComplete: "Code Error" 
2022-07-28T03:48:35 DEBUG [codedeploy-agent(5272)]: InstanceAgent::Plugins::CodeDeployPlugin::CommandPoller: Calling PutHostCommandComplete: "Code Error" 
2022-07-28T03:48:35 INFO  [codedeploy-agent(5272)]: Version file found in C:/ProgramData/Amazon/CodeDeploy/.version with agent version OFFICIAL_1.3.2.1902_msi.
2022-07-28T03:48:35 INFO  [codedeploy-agent(5272)]: Version file found in C:/ProgramData/Amazon/CodeDeploy/.version with agent version OFFICIAL_1.3.2.1902_msi.
2022-07-28T03:48:36 INFO  [codedeploy-agent(5272)]:[Aws::CodeDeployCommand::Client 200 0.065898 0 retries]   put_host_command_complete(command_status:"Failed",diagnostics:format:"JSON",payload:"\"error_code\":5,\"script_name\":\"\",\"message\":\"Invalid argument @ rb_sysopen - C:\\\\ProgramData/Amazon/CodeDeploy/0df66877-d62c-49b0-81b6-a2b98509ed51/d-DC1Q553XH/deployment-archive\\\\*.*\",\"log\":\"\"}"},host_command_identifier:"eyJiYXRjaElkIjoiN2MzMDJmY2U1YmIzNDVjYThjNGQ5YWI0MzMyMDhiMjkvcHVibGljMDA3IiwiZGVwbG95bWVudElkIjoiQ29kZURlcGxveS9hcC1zb3V0aGVhc3QtMi9wcm9kL29ycGhldXM6cHVibGljMDA1LzgwOTMyNTEwODEzMTpkLURDMVE1NTNYSCIsImhvc3RJZCI6ImFybjphd3M6ZWMyOmFwLXNvdXRoZWFzdC0yOjgwOTMyNTEwODEzMTppbnN0YW5jZS9pLTAxY2U5NmE0MDM2NDJiMzAyIiwiY29tbWFuZElkIjoiQXBvbGxvRGVwbG95Q29udHJvbFNlcnZpY2V8YXJuOmF3czplYzI6YXAtc291dGhlYXN0LTI6ODA5MzI1MTA4MTMxOmluc3RhbmNlL2ktMDFjZTk2YTQwMzY0MmIzMDJ8NHwwIiwiY29tbWFuZE5hbWUiOiJJbnN0YWxsIiwiY29tbWFuZEluZGV4Ijo0LCJhdHRlbXB0SW5kZXgiOjF9")  
2022-07-28T03:48:36 INFO  [codedeploy-agent(5272)]:[Aws::CodeDeployCommand::Client 200 0.065898 0 retries] put_host_command_complete(command_status:"Failed",diagnostics:{format:"JSON",payload:"{\"error_code\":5,\"script_name\":\"\",\"message\":\"Invalid argument @ rb_sysopen - C:\\\\ProgramData/Amazon/CodeDeploy/0df66877-d62c-49b0-81b6-a2b98509ed51/d-DC1Q553XH/deployment-archive\\\\*.*\",\"log\":\"\"}"},host_command_identifier:"eyJiYXRjaElkIjoiN2MzMDJmY2U1YmIzNDVjYThjNGQ5YWI0MzMyMDhiMjkvcHVibGljMDA3IiwiZGVwbG95bWVudElkIjoiQ29kZURlcGxveS9hcC1zb3V0aGVhc3QtMi9wcm9kL29ycGhldXM6cHVibGljMDA1LzgwOTMyNTEwODEzMTpkLURDMVE1NTNYSCIsImhvc3RJZCI6ImFybjphd3M6ZWMyOmFwLXNvdXRoZWFzdC0yOjgwOTMyNTEwODEzMTppbnN0YW5jZS9pLTAxY2U5NmE0MDM2NDJiMzAyIiwiY29tbWFuZElkIjoiQXBvbGxvRGVwbG95Q29udHJvbFNlcnZpY2V8YXJuOmF3czplYzI6YXAtc291dGhlYXN0LTI6ODA5MzI1MTA4MTMxOmluc3RhbmNlL2ktMDFjZTk2YTQwMzY0MmIzMDJ8NHwwIiwiY29tbWFuZE5hbWUiOiJJbnN0YWxsIiwiY29tbWFuZEluZGV4Ijo0LCJhdHRlbXB0SW5kZXgiOjF9")  

2022-07-28T03:48:36 ERROR [codedeploy-agent(5272)]: InstanceAgent::Plugins::CodeDeployPlugin::CommandPoller: Error during perform: Errno::EINVAL - Invalid argument @ rb_sysopen - C:\ProgramData/Amazon/CodeDeploy/0df66877-d62c-49b0-81b6-a2b98509ed51/d-DC1Q553XH/deployment-archive\*.* - C:/Windows/TEMP/ocrAF4E.tmp/lib/ruby/2.3.0/fileutils.rb:1392:in `initialize'
C:/Windows/TEMP/ocrAF4E.tmp/lib/ruby/2.3.0/fileutils.rb:1392:in `open'
C:/Windows/TEMP/ocrAF4E.tmp/lib/ruby/2.3.0/fileutils.rb:1392:in `copy_file'
C:/Windows/TEMP/ocrAF4E.tmp/lib/ruby/2.3.0/fileutils.rb:486:in `copy_file'
C:/Windows/TEMP/ocrAF4E.tmp/lib/ruby/2.3.0/fileutils.rb:403:in `block in cp'
C:/Windows/TEMP/ocrAF4E.tmp/lib/ruby/2.3.0/fileutils.rb:1571:in `block in fu_each_src_dest'
C:/Windows/TEMP/ocrAF4E.tmp/lib/ruby/2.3.0/fileutils.rb:1587:in `fu_each_src_dest0'
C:/Windows/TEMP/ocrAF4E.tmp/lib/ruby/2.3.0/fileutils.rb:1569:in `fu_each_src_dest'
C:/Windows/TEMP/ocrAF4E.tmp/lib/ruby/2.3.0/fileutils.rb:402:in `cp'
C:/Windows/TEMP/ocrAF4E.tmp/src/opt/codedeploy-agent/lib/instance_agent/plugins/codedeploy/install_instruction.rb:237:in `execute'
C:/Windows/TEMP/ocrAF4E.tmp/src/opt/codedeploy-agent/lib/instance_agent/plugins/codedeploy/installer.rb:49:in `block (2 levels) in install'
C:/Windows/TEMP/ocrAF4E.tmp/src/opt/codedeploy-agent/lib/instance_agent/plugins/codedeploy/installer.rb:48:in `each'
C:/Windows/TEMP/ocrAF4E.tmp/src/opt/codedeploy-agent/lib/instance_agent/plugins/codedeploy/installer.rb:48:in `block in install'
C:/Windows/TEMP/ocrAF4E.tmp/src/opt/codedeploy-agent/lib/instance_agent/plugins/codedeploy/installer.rb:47:in `open'
C:/Windows/TEMP/ocrAF4E.tmp/src/opt/codedeploy-agent/lib/instance_agent/plugins/codedeploy/installer.rb:47:in `install'
C:/Windows/TEMP/ocrAF4E.tmp/src/opt/codedeploy-agent/lib/instance_agent/plugins/codedeploy/command_executor.rb:138:in `block in <class:CommandExecutor>'
C:/Windows/TEMP/ocrAF4E.tmp/src/opt/codedeploy-agent/lib/instance_agent/plugins/codedeploy/command_executor.rb:70:in `execute_command'
C:/Windows/TEMP/ocrAF4E.tmp/src/opt/codedeploy-agent/lib/instance_agent/plugins/codedeploy/command_poller.rb:115:in `process_command'
C:/Windows/TEMP/ocrAF4E.tmp/src/opt/codedeploy-agent/lib/instance_agent/plugins/codedeploy/command_poller.rb:97:in `acknowledge_and_process_command'
C:/Windows/TEMP/ocrAF4E.tmp/src/opt/codedeploy-agent/lib/instance_agent/plugins/codedeploy/command_poller.rb:76:in `block in perform'
C:/Windows/Temp/ocrAF4E.tmp/gemhome/gems/concurrent-ruby-1.0.5/lib/concurrent/executor/ruby_thread_pool_executor.rb:348:in `run_task'
C:/Windows/Temp/ocrAF4E.tmp/gemhome/gems/concurrent-ruby-1.0.5/lib/concurrent/executor/ruby_thread_pool_executor.rb:337:in `block (3 levels) in create_worker'
C:/Windows/Temp/ocrAF4E.tmp/gemhome/gems/concurrent-ruby-1.0.5/lib/concurrent/executor/ruby_thread_pool_executor.rb:320:in `loop'
C:/Windows/Temp/ocrAF4E.tmp/gemhome/gems/concurrent-ruby-1.0.5/lib/concurrent/executor/ruby_thread_pool_executor.rb:320:in `block (2 levels) in create_worker'
C:/Windows/Temp/ocrAF4E.tmp/gemhome/gems/concurrent-ruby-1.0.5/lib/concurrent/executor/ruby_thread_pool_executor.rb:319:in `catch'
C:/Windows/Temp/ocrAF4E.tmp/gemhome/gems/concurrent-ruby-1.0.5/lib/concurrent/executor/ruby_thread_pool_executor.rb:319:in `block in create_worker'

Could anyone please help?



How is the better way for extract data this array con multiples objetcs with php

I have the following JSON response and I need to create an XML block for each sku and quantity data of each in the order. I include all the json response where I am pulling the data from.

Array
(
    [id] => 17
    [parent_id] => 0
    [status] => on-hold
    [currency] => MXN
    [version] => 6.7.0
    [prices_include_tax] => 
    [date_created] => 2022-07-27T05:02:25
    [date_modified] => 2022-07-27T05:02:26
    [discount_total] => 0.00
    [discount_tax] => 0.00
    [shipping_total] => 0.00
    [shipping_tax] => 0.00
    [cart_tax] => 0.00
    [total] => 3356.00
    [total_tax] => 0.00
    [customer_id] => 1
    [order_key] => wc_order_xakP1gXCne19m
    [billing] => Array
        (
            [first_name] => Nombre
            [last_name] => sjdjjje
            [company] => 
            [address_1] => Pruena
            [address_2] => Prueba
            [city] => hidalgo
            [state] => AG
            [postcode] => 85422
            [country] => MX
            [email] => tuempresaaswe@gmail.com
            [phone] => 5555555555
        )

    [shipping] => Array
        (
            [first_name] => Nombre
            [last_name] => sjdjjje
            [company] => 
            [address_1] => Pruena
            [address_2] => Prueba
            [city] => hidalgo
            [state] => AG
            [postcode] => 85422
            [country] => MX
            [phone] => 
        )

    [payment_method] => bacs
    [payment_method_title] => Direct bank transfer
    [transaction_id] => 
    [customer_ip_address] => 187.190.230.169
    [customer_user_agent] => Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36
    [created_via] => checkout
    [customer_note] => 
    [date_completed] => 
    [date_paid] => 
    [cart_hash] => 2aa27292dcdf8556b9443b1598c3eb3d
    [number] => 17
    [meta_data] => Array
        (
            [0] => Array
                (
                    [id] => 149
                    [key] => is_vat_exempt
                    [value] => no
                )

            [1] => Array
                (
                    [id] => 153
                    [key] => _new_order_email_sent
                    [value] => true
                )

            [2] => Array
                (
                    [id] => 154
                    [key] => _om_revenue_attribution_data
                    [value] => Array
                        (
                            [transaction_id] => 17
                            [value] => 3356.00
                        )

                )

        )

    [line_items] => Array
        (
            [0] => Array
                (
                    [id] => 4
                    [name] => Prueba 1
                    [product_id] => 11
                    [variation_id] => 0
                    [quantity] => 1
                    [tax_class] => 
                    [subtotal] => 122.00
                    [subtotal_tax] => 0.00
                    [total] => 122.00
                    [total_tax] => 0.00
                    [taxes] => Array
                        (
                        )

                    [meta_data] => Array
                        (
                            [0] => Array
                                (
                                    [id] => 51
                                    [key] => _reduced_stock
                                    [value] => 1
                                    [display_key] => _reduced_stock
                                    [display_value] => 1
                                )

                        )

                    [sku] => HDF-CS65
                    [price] => 122
                    [image] => Array
                        (
                            [id] => 
                            [src] => 
                        )

                    [parent_name] => 
                )

            [1] => Array
                (
                    [id] => 5
                    [name] => ramzilla
                    [product_id] => 12
                    [variation_id] => 0
                    [quantity] => 1
                    [tax_class] => 
                    [subtotal] => 3234.00
                    [subtotal_tax] => 0.00
                    [total] => 3234.00
                    [total_tax] => 0.00
                    [taxes] => Array
                        (
                        )

                    [meta_data] => Array
                        (
                            [0] => Array
                                (
                                    [id] => 52
                                    [key] => _reduced_stock
                                    [value] => 1
                                    [display_key] => _reduced_stock
                                    [display_value] => 1
                                )

                        )

                    [sku] => RAMZ-023
                    [price] => 3234
                    [image] => Array
                        (
                            [id] => 
                            [src] => 
                        )

                    [parent_name] => 
                )

        )

    [tax_lines] => Array
        (
        )

    [shipping_lines] => Array
        (
            [0] => Array
                (
                    [id] => 6
                    [method_title] => Free shipping
                    [method_id] => free_shipping
                    [instance_id] => 1
                    [total] => 0.00
                    [total_tax] => 0.00
                    [taxes] => Array
                        (
                        )

                    [meta_data] => Array
                        (
                            [0] => Array
                                (
                                    [id] => 50
                                    [key] => Items
                                    [value] => Prueba 1 &times; 1, ramzilla &times; 1
                                    [display_key] => Items
                                    [display_value] => Prueba 1 &times; 1, ramzilla &times; 1
                                )

                        )

                )

        )

    [fee_lines] => Array
        (
        )

    [coupon_lines] => Array
        (
        )

    [refunds] => Array
        (
        )

    [payment_url] => https://lucky.lab-sdma.link/checkout/order-pay/17/?pay_for_order=true&key=wc_order_xakP1gXCne19m
    [is_editable] => 1
    [needs_payment] => 
    [needs_processing] => 1
    [date_created_gmt] => 2022-07-27T05:02:25
    [date_modified_gmt] => 2022-07-27T05:02:26
    [date_completed_gmt] => 
    [date_paid_gmt] => 
    [currency_symbol] => $
    [_links] => Array
        (
            [self] => Array
                (
                    [0] => Array
                        (
                            [href] => https://lucky.lab-sdma.link/wp-json/wc/v3/orders/17
                        )

                )

            [collection] => Array
                (
                    [0] => Array
                        (
                            [href] => https://lucky.lab-sdma.link/wp-json/wc/v3/orders
                        )

                )

            [customer] => Array
                (
                    [0] => Array
                        (
                            [href] => https://lucky.lab-sdma.link/wp-json/wc/v3/customers/1
                        )

                )

        )

)

But I can't find how to do it since it only brings me the first value. Can you help me?

my code goes something like this

<?
         header('Content-Type: application/json; charset=utf-8');
    
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // fetch RAW input
   $json = file_get_contents('php://input');

    // decode json
    $object = json_decode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    //$respuestajson = json_encode ($object);

    // expecting valid json
    if (json_last_error() !== JSON_ERROR_NONE) {
        die(header('HTTP/1.0 415 Unsupported Media Type'));
    }

    /**
     * Do something with object, structure will be like:
     * $object->accountId
     * $object->details->items[0]['contactName']
     */
    // dump to file so you can see

$nombre = $object [billing][first_name];
$apellido = $object [billing][last_name];
$direccion = $object [shipping][address_1];
$direccion2 = $object [shipping][address_2];
$ciudad = $object [shipping][city];
$estado = $object [shipping][state];
$cp = $object [shipping][postcode];
$pais = $object [shipping][country];
$OC = $object [id];
$SKU = $object [line_items][0][sku];
$cantidad = $object [line_items][0][quantity];
$completa = [$nombre, $apellido, $direccion, $direccion2, $ciudad, $estado, $cp, $pais];
$contador = 0;

$datesku = [];
$datecantidad = [];
$i = 0;



$SKUbloque = '<CodigoProducto>'.$SKU.'</CodigoProductoAC>
              <Cantidad>'.$cantidad.'</Cantidad>';

file_put_contents('pruebadatos.json', print_r($completa, true));
    file_put_contents('callback.txt', print_r($object, true));
    file_put_contents('respuesta.json', print_r($object, true));

echo $completa;
echo $OC;

    $datos = '<data>
    <Usuario>xxxx</Usuario>
    <Contrasena>xxxx</Contrasena>
                    <OC>
                    <NumeroOC>'.$OC.'</NumeroOC>
                    <DireccionEntrega>'.$completa.'</DireccionEntrega>
                    <Paqueteria>000</Paqueteria>
                    <!--<CodigoSucursal>GDL</CodigoSucursal>-->
                    <CodigoSucursal>CEDIS</CodigoSucursal>
                    <FormaPago>Credito30</FormaPago>
                    <PedidoParcial>N</PedidoParcial>
                    <Observaciones>Cliente recoge</Observaciones>
                    <Productos>
                        <Producto>
                            <CodigoProductoAC>'.$SKU.'</CodigoProductoAC>
                            <Cantidad>'.$cantidad.'</Cantidad>
                        </Producto>
                    </Productos>
                </OC>
                   
              </data>';
    
    $Ejo = curl_init();
    $url = 'https://cxxxx';
    curl_setopt($Ejo, CURLOPT_URL, $url);
    curl_setopt($Ejo, CURLOPT_HTTPHEADER, array('Content-Type: application/xml','Accept: application/xml'));
    curl_setopt($Ejo, CURLOPT_POST, 1);
    curl_setopt($Ejo, CURLOPT_POSTFIELDS,$datos);
    curl_setopt($Ejo, CURLOPT_RETURNTRANSFER, true);
    $respuesta  = curl_exec($Ejo);
    
    if($respuesta === false){
        echo 'Curl error: ' . curl_error($Ejo);
        file_put_contents('respuestpedido.txt', print_r($respuesta, true));
    }
    else{
     
      echo "<pre> $respuesta";
      file_put_contents('respuestpedido.txt', print_r($respuesta, true));
      If (unlink('respuesta.json')) {
        echo "El archivo respuesta.json ha sido eliminado";
      } else {
        echo "Bro, se resistió, no pudimos eliminarlo";
      }
        
    
    
      }
    curl_close($Ejo); 
       
   

}
?>


CPU costs of Thread.sleep() and Thread.onSpinWait()

I'm running two benchmarks in order to compare costs of Thread.sleep() and Thread.onSpinWait():

@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class ThreadSleep2Benchmark {
  private final ExecutorService executor = Executors.newFixedThreadPool(1);
  volatile boolean run;

  @Param({"1", "5", "10", "50", "100"})
  long delay;

  @Setup(Level.Invocation)
  public void setUp() {
    run = true;
    startThread();
  }

  @TearDown(Level.Trial)
  public void tearDown() {
    executor.shutdown();
  }

  @Benchmark
  public int sleep() throws Exception {
    while (run) {
      Thread.sleep(1);
    }
    return hashCode();
  }

  private void startThread() {
    executor.submit(() -> {
      try {
        Thread.sleep(delay / 2);
        run = false;
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new RuntimeException(e);
      }
    });
  }
}

Then I run the one with Thread.onSpinWait():

@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class ThreadOnSpinWaitBenchmark {
  private final ExecutorService executor = Executors.newFixedThreadPool(1);
  volatile boolean run;

  @Param({"1", "5", "10", "50", "100"})
  long delay;

  @Setup(Level.Invocation)
  public void setUp() {
    run = true;
    startThread();
  }

  @TearDown(Level.Trial)
  public void tearDown() {
    executor.shutdown();
  }

  @Benchmark
  public int onSpinWait() {
    while (run) {
      Thread.onSpinWait();
    }
    return hashCode();
  }

  private void startThread() {
    executor.submit(() -> {
      try {
        Thread.sleep(delay / 2);
        run = false;
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new RuntimeException(e);
      }
    });
  }
}

Both demonstrate nearly same results for delay > 1 ms:

Benchmark                             (delay)  Mode  Cnt   Score    Error  Units

ThreadOnSpinWaitBenchmark.onSpinWait        1  avgt   20   0,003 ±  0,001  ms/op
ThreadOnSpinWaitBenchmark.onSpinWait        5  avgt   20   2,459 ±  0,027  ms/op
ThreadOnSpinWaitBenchmark.onSpinWait       10  avgt   20   5,957 ±  0,064  ms/op
ThreadOnSpinWaitBenchmark.onSpinWait       50  avgt   20  27,915 ±  0,225  ms/op
ThreadOnSpinWaitBenchmark.onSpinWait      100  avgt   20  53,112 ±  0,343  ms/op

ThreadSleep2Benchmark.sleep                 1  avgt   20   1,420 ±  0,043  ms/op
ThreadSleep2Benchmark.sleep                 5  avgt   20   3,183 ±  0,099  ms/op
ThreadSleep2Benchmark.sleep                10  avgt   20   6,723 ±  0,069  ms/op
ThreadSleep2Benchmark.sleep                50  avgt   20  29,697 ±  0,307  ms/op
ThreadSleep2Benchmark.sleep               100  avgt   20  54,730 ±  0,329  ms/op

This is quite expected.

I'd like however to measure CPU load of both approaches. I know that on Linux I can use LinuxPerfNormProfiler but I'm not sure which particular metric I should take to get reliable insight.



How to navigate from specific selected item RecyclerView Inside the Fragment, to 2 different Activity from same RecyclerView in Kotlin?

How to navigate from specific selested item RecyclerView Inside the Fragment, to 2 different Activity in Kotlin?

Basic Layout Wireframe, and guide of what I want to ask

i have the basic wireframe layout, who describe my question, because i don't know how to explain with good typing.

so here from the wireframe, i have 1 Activity with TabLayout, which is filled with Fragment and there is a RecyclerView in it. And then I have 2 more different Activities. for now, i've successfully implemented data parsing to "OtherActivity1" from RecyclerView inside the fragment TabLayout on MainActivity.

But now, i need to open "OtherActivity2" from the same RecyclerView on Main Activity, what i mean here is specifically only from "RecyclerView Item4" and without data parsing.

How To Doing That?

Anyone have a tutorial?, because i can't find any tutorials like on youtube for this case.

and this my sample code ( not exactly the same, but describing the same meaning) :

MainActivity.kt

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        setUpTabs() // Assign TabLayout

    } // End - OnCreate


    // Start - TabLayout
    private fun setUpTabs() {
        val adapter = ViewPagerAdapter(supportFragmentManager)
        adapter.addFragment(TAB1Fragment(), "TAB1")
        adapter.addFragment(TAB2Fragment(), "TAB2")
        adapter.addFragment(TAB3Fragment(), "TAB3")
        viewPager_tabLayout.adapter = adapter
        tabs.setupWithViewPager(viewPager_tabLayout)
    } // End - TabLayout

} // End Class

TAB1Fragment.kt

    class TAB1Fragment : Fragment() {
    
        lateinit var tab1Adapter: TAB1Adapter // Initialize Adapter
        private val sLM = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL) // Initialize LayoutManager
        val addTAB1ModelList: MutableList<TAB1Model> = ArrayList() // Initialize ListModel
    
    
        override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            return inflater.inflate(R.layout.fragment_tab1, container, false)
        } // End onCreateView
    
        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
    
            initViewTAB1() // Assign ListModel putExtras
            actionTAB1() // Assign Action putExtras
    
        } // End - OnViewCreated
    
    
        // Start - ListModel putExtras
        fun initViewTAB1() { 
    
            rv_tab1.layoutManager = sLM
            rv_tab1.setHasFixedSize(true)
            tab1Adapter = TAB1Adapter(requireActivity())
            rv_tab1.adapter = tab1Adapter
    
            addTAB1ModelList.add(TAB1Model("RecyclerView Item1", "Desc RecyclerView Item1", R.drawable.cv1))
            addTAB1ModelList.add(TAB1Model("RecyclerView Item2", "Desc RecyclerView Item1", R.drawable.cv2))
            addTAB1ModelList.add(TAB1Model("RecyclerView Item3", "Desc RecyclerView Item1", R.drawable.cv3))
            addTAB1ModelList.add(TAB1Model("RecyclerView Item4", "Desc RecyclerView Item1", R.drawable.cv4))
         
            tab1Adapter.setTAB1(addTAB1ModelList)
        }
        // End - ListModel putExtras
    
    
        // Start - Action putExtras
        fun actionTAB1() {
    
            tab1Adapter.setOnClickItemListenerTAB1(object : OnItemClickListener {
                override fun onItemClick(item: View, position: Int) {
                    var i = Intent(context, OtherActivity1::class.java)
                    i.putExtra("prodNameTAB1", tab1Adapter.getTAB1().get(position).getProdNameTAB1())
                    i.putExtra("prodPriceTAB1", tab1Adapter.getTAB1().get(position).getProdPriceTAB1())
                    i.putExtra("prodImgTAB1", tab1Adapter.getTAB1().get(position).getProdImgTAB1())
                    startActivity(i)
                }
            }) 
            // End - Action putExtras
    
    
        } // End - Class

TAB1Model.kt

class TAB1Model  {

private var prodNameTAB1: String // Initialize prodNameTAB1
private var prodPriceTAB1: String // Initialize prodPriceTAB1
private var prodImgTAB1: Int // Initialize prodImgTAB1

constructor (prodNameTAB1: String, prodPriceTAB1: String, prodImgTAB1: Int) {
    this.prodNameTAB1 = prodNameTAB1 // Assign prodNameTAB1
    this.prodPriceTAB1 = prodPriceTAB1 // Assign prodPriceTAB1
    this.prodImgTAB1 = prodImgTAB1 // Assign prodImgTAB1
}

// Start - ProdNameTAB1
fun getProdNameTAB1(): String {
    return prodNameTAB1
}

fun setProdNameTAB1(prodNameTAB1: String) {
    this.prodNameTAB1 = prodNameTAB1
}
// End - ProdNameTAB1

// Start - prodPriceTAB1
fun getProdPriceTAB1(): String {
    return prodPriceTAB1
}

fun setProdPriceTAB1(prodPriceTAB1: String) {
    this.prodPriceTAB1 = prodPriceTAB1
}
// End - prodPriceTAB1

// Start - prodImgTAB1
fun getProdImgTAB1(): Int {
    return prodImgTAB1
    }

fun setprodImgTAB1(prodImgTAB1: Int) {
    this.prodImgTAB1 = prodImgTAB1
    }
// End - prodImgTAB1


} // End Class

TAB1Adapter.kt

class TAB1Adapter(private val context: Context) : RecyclerView.Adapter<TAB1Adapter.TAB1ViewHolder>() {

    private val tab1Model: MutableList<TAB1Model> = mutableListOf() // Initialize tab1Model
    private lateinit var onSelectedListenerTAB1: OnItemClickListener // Initialize tab1Listener

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TAB1ViewHolder {
        return TAB1ViewHolder(LayoutInflater.from(context).inflate(R.layout.item_tab1_layout, parent, false))
    } //End - onCreateViewHolder

    override fun getItemCount(): Int {
        return tab1Model.size
    } // End - getItem

    override fun onBindViewHolder(holder: TAB1ViewHolder, position: Int) {
        holder.tab1BindView(tab1Model[position])
    } //End - onBindViewHolder


    //Start - setTAB1Model
    fun setTAB1(data: List<TAB1Model>) {
        tab1Model.clear()
        tab1Model.addAll(data)
        notifyDataSetChanged()
    } 
    //End - setTAB1Model


    // Start - getTAB1Model
    fun getTAB1(): MutableList<TAB1Model> {
        return tab1Model
    } 
    // End - getTAB1Model

    
    // Start - TAB1ViewHolder
    inner class TAB1ViewHolder(tab1view: View) : RecyclerView.ViewHolder(tab1view) {
        val imgProdTAB1 = tab1view.findViewById<ImageView>(R.id.iv_prodTAB1)
        val cvTAB1: MaterialCardView = tab1view.findViewById(R.id.cv_tab1)

        fun tab1BindView(tab1Model: TAB1Model) {
            imgProdTAB1.setImageResource(tab1Model.getProdImgTAB1())
    }

          init {
              cvTAB1.setOnClickListener { onSelectedListenerTAB1.onItemClick(it, layoutPosition) }
         }

    } 
    // End - TAB1ViewHolder

    // Start - setOnClickItemListenerTAB1
    fun setOnClickItemListenerTAB1(onItemClickListener: OnItemClickListener) {
        this.onSelectedListenerTAB1 = onItemClickListener
    } 
    // End - setOnClickItemListenerTAB1

OtherActiviy1.kt

class OtherAtivity1 : AppCompatActivity() {

    var prodBundle : Bundle? = null // Initialize Bundle
   
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_other1)


        initView() // Assign Extras Reciver

    } // End - OnCreate

    
    // Start - Extras Reciver
    fun initView() {
        prodBundle = intent.extras

        phtv_ProdName.text = prodBundle?.getString( "prodNameTAB1" )
        phtv_ProdPrice.text = prodBundle?.getString( "prodPriceTAB1" )
        prodBundle?.getInt("prodImgTAB1")?.let { ph_ivProd.setImageResource(it) }
    } 
    // End - Extras Reciver


} // End - Class

OtherActiviy2.kt

class OtherAtivity2 : AppCompatActivity() {

   
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_other2)


    } // End - OnCreate



} // End - Class

OnItemClickListener.kt

interface OnItemClickListener {
    fun onItemClick(item: View, position:Int)
}

I hope someone help me solve this problem. Thank you so much for taking your time to help me. :)



Laravel 9 jetstream , I need to sanitize this Controllers is there away to do that? [closed]

I just started my first Laravel project and create an 'authorized waiting view' for role users, using laravel-9 jetstream and custom-made middleware. Is there a way to reduce the number of codes that have been repeated again and again?

  • are there artisan commands to do that?
  • what is the best way to reduce code duplication.

 $name = $authorizeRequestUser->name;
 $contact_number = $authorizeRequestUser->contact_number;
 $email = $authorizeRequestUser->email;
 $massage = 'Please Contact bellow persion to Authorize your login';

check the repeating code above.

please let me know if there is a specific way to do that.

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class AuthorizeWaitingController extends Controller
{
    public function index() {
        $name = 'John Doe';
        $contact_number = '07xxxxxxx';
        $email = 'jonhdoe@gmail.com ';
        $massage = 'Please Contact bellow persion to Authorize your login';
        
        if (auth()->user()->role_id === 2){
            $authorizeRequestUser = User::where('role_id',1)->first();

           if ($authorizeRequestUser !== null) {
                $name = $authorizeRequestUser->name;
                $contact_number = $authorizeRequestUser->contact_number;
                $email = $authorizeRequestUser->email;
                $massage = 'Please Contact bellow persion to Authorize your login';
           } 

        }else if(auth()->user()->role_id === 3){
            $authorizeRequestUser = User::where('role_id',2)->where('center_id', auth()->user()->center_id)->first(); //OrFail
          
            if($authorizeRequestUser === null){
                $authorizeRequestUser = User::where('role_id',1)->first();
                if ($authorizeRequestUser !== null) {
                    $name = $authorizeRequestUser->name;
                    $contact_number = $authorizeRequestUser->contact_number;
                    $email = $authorizeRequestUser->email;
                    $massage = 'Please Contact bellow persion to Authorize your login';
                }
            }else{
                $name = $authorizeRequestUser->name;
                $contact_number = $authorizeRequestUser->email;
                $massage = $authorizeRequestUser->contact_number;
                $email  = 'Please Contact bellow persion to Authorize your login';
            }
           
        }
        
        return view('components.authorize-waiting', compact('name', 'contact_number', 'email', 'massage'));

    }
}

```````````````````````````````````````````````````


2022-07-28

Getting name of current express middleware function

Long time reader first time question asker. My question is about dynamically accessing function names in express ^4.17.1. I have poured over both the internet and the express documentation with no luck.

I currently have input validation set up on all of my express middleware functions that ensures I'm getting the right information in the right format. When bad or incomplete information is given to a particular middleware I throw a nicely formatted error to the global error handler and I include the route that errored, the file in which the error occured, and the exact middleware in which it occured.

I've been able to dynamically retrieve both the route and the file name, but I'm having issues finding a way around hard coding in the name of the middleware. I can access the route stack and get the names of ALL middleware in the route, but there doesn't seem to be a way to determine which one you're in aside from keeping that list on res.locals and changing the array as you go (which isn't ideal). Here is a simple example of what I'm talking about.

const path = require("path");
const currFile = path.basename(__filename);

module.exports = {
  getStudentAssets(req, res, next) {
    const { studentName } = req.body;
    if (typeof studentName !== "string") {
      const iWouldLoveToGetThisDynamically = "getStudentAssets";
      const error = {
        status: 400,
        log: `ERROR on route ${req.originalUrl} in ${currFile} ${iWouldLoveToGetThisDynamically} middleware`,
      };
      return next(error);
    }
    // do random stuff
  },
};

I have a feeling there is a way to track which layer you're currently on as accessing req.route.stack looks something like this

[
  Layer {
    handle: [Function: getStudentAssets],
    name: 'getStudentAssets',
    params: undefined,
    path: undefined,
    keys: [],
    regexp: /^\/?$/i { fast_star: false, fast_slash: false },
    method: 'get'
  },
  Layer {
  // other middleware
  }
]

There has to be a way to identify which layer you're currently on, other than keeping a counter stored separately on res.locals that you update every middleware. If you've read this far thank you!



Swift - Return Generic Type/Data

I have URLSession shared instance that fetches data. It returns a generic type. Everything works fine when I'm fetching data from a server and displaying it. But when I fetch an image I need to return the Generic Type as the data. How can I return the generic type/data so that it can be used to create the image in the imageView?

UIImageView:

extension UIImageView {
    
    func loadImage(with url: URL) {
        
        if let cachedImage = imageCache.object(forKey: url.absoluteString as AnyObject) as? UIImage {
            self.image = cachedImage
            return
        }
        
        URLSessionManager.fetchData(with: url, isImageFetch: true) { (result: Result<Data, SessionDataTaskError>) in

            switch result {

            case .failure(let error):

                print(error)

            case .success(let data):

                guard let downloadedImage = UIImage(data: data) else {
                    print("image data is nil")
                    return
                }

                DispatchQueue.main.async{ [weak self] in

                    imageCache.setObject(downloadedImage, forKey: url.absoluteString as AnyObject)
                    self?.image = downloadedImage
                }
            }
        }
    }
}

URLSessionManager:

class URLSessionManager {
    
    static let shared = URLSessionManager()
    
    static func fetchData<T: Decodable>(with url: URL, isImageFetch: Bool = false, completion: @escaping (Result<T, SessionDataTaskError>)->Void) { // SessionDataTaskError is just an Enum
        
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            
            if let error = error {
                completion(.failure(SessionDataTaskError.failedIssue(error)))
                return
            }
            
            guard let data = data else {
                completion(.failure(SessionDataTaskError.dataIsNil))
                return
            }
            
            if isImageFetch {

                // *** How can I return the generic type/data so that it can be used to create the image in the imageView? ***
                return
            }

            do {
                
                let genericType = try JSONDecoder().decode(T.self, from: data)
                
                completion(.success(genericType))
                
            } catch {
                
                completion(.failure(SessionDataTaskError.catchIssue(error)))
                
                guard let err = error as? DecodingError else {
                    debugPrint("decodingError-:", error)
                    return
                }
                
                switch err {
                case .typeMismatch(let key, let value):
                    print("decodingError-Mismatch: \(key), value \(value) and ERROR: \(error.localizedDescription)")
                case .valueNotFound(let key, let value):
                    print("decodingError-ValueNotFound: \(key), value \(value) and ERROR: \(error.localizedDescription)")
                case .keyNotFound(let key, let value):
                    print("decodingError-KeyNotFound(: \(key), value \(value) and ERROR: \(error.localizedDescription)")
                case .dataCorrupted(let key):
                    print("decodingError-DataCorrupted: \(key), and ERROR: \(error.localizedDescription)")
                default:
                    print("decodingError-UnknownError: \(error.localizedDescription)")
                }
            }
            
        }.resume()
    }
}


Fragment doesnt show data from database (I recently started learning programming)

Database is working since i can see the data in app inspection i dont know what i am doing wrong and cant display the data in the FragmentShow fragment i want the data to be displayed in the above fragment in a recyclerview Any help will be appreciated ( i am a beginner )

Fragment with recyclerview

  class FragmentShow: Fragment(R.layout.fragment_show) {
private var _binding: FragmentShowBinding? = null
private val binding get() = _binding!!
private lateinit var sqLiteHelper: SQLiteHelper
private var adapter: EntryAdapter? = null

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    sqLiteHelper = SQLiteHelper(requireActivity() as MainActivity)
    _binding = FragmentShowBinding.inflate(inflater,container,false)
    initRecyclerView()
    getEntries()

    return view
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    adapter?.notifyDataSetChanged()
    sqLiteHelper = SQLiteHelper(requireActivity() as MainActivity)

}



private fun initRecyclerView() {
    binding.recyclerviewID.layoutManager = LinearLayoutManager(requireActivity() as MainActivity)
    adapter = EntryAdapter()
    binding.recyclerviewID.adapter = adapter



}

private fun getEntries() {
    val entrylist = sqLiteHelper.getEntry()
    adapter?.addItems(entrylist)

}


override fun onDestroyView() {
    super.onDestroyView()
    return
}

}

Adapter

 class EntryAdapter : RecyclerView.Adapter<EntryAdapter.ViewHolder>() {
private var entryList: ArrayList<Entry> = ArrayList()
private var onClickItem: ((Entry) -> Unit)? = null
private var onClickDeleteItem: ((Entry) -> Unit)? = null

fun addItems(items: ArrayList<Entry>) {
    this.entryList = items
    notifyDataSetChanged()
}
fun setOnClickItem(callback: (Entry) -> Unit) {
    this.onClickItem = callback
}

fun onClickDeleteItem(callback: (Entry) -> Unit) {
    this.onClickDeleteItem = callback
}


override fun onCreateViewHolder(parent: ViewGroup, viewType: Int)= ViewHolder (
   LayoutInflater.from(parent.context).inflate(R.layout.recycler_view_row,parent,false)
)

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val ent = entryList[position]
    holder.bindView(ent)
    holder.itemView.setOnClickListener { onClickItem?.invoke(ent) }
    holder.btnDelete.setOnClickListener { onClickDeleteItem?.invoke(ent) }
}

override fun getItemCount(): Int {
    return entryList.size
}

class ViewHolder(view: View): RecyclerView.ViewHolder(view) {
    private var id = view.findViewById<Button>(R.id.IdTv)
    private var name = view.findViewById<TextView>(R.id.NameTV)
    private var work = view.findViewById<TextView>(R.id.WorkTv)
    private var problems = view.findViewById<TextView>(R.id.ProblemTv)
    var btnDelete = view.findViewById<Button>(R.id.btnDelete)

    fun bindView(entry: Entry){
        id.text = entry.id.toString()
        name.text = entry.name
        work.text = entry.work
        problems.text = entry.problems

    }

}

}

MainActivity

    class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
private lateinit var adapter: EntryAdapter
private lateinit var sqLiteHelper: SQLiteHelper
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    sqLiteHelper = SQLiteHelper(this)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)

    binding.btnFirstFragment.setOnClickListener {
        fragmentNav(FragmentEntry())
    }


    binding.btnSecondFragment.setOnClickListener {
        fragmentNav(FragmentShow())

    }

}

private fun fragmentNav(fragment: Fragment) {
    val fragmentManager = supportFragmentManager
    val fragmentTransaction = fragmentManager.beginTransaction()
    fragmentTransaction.replace(R.id.fragmentContainerView2,fragment)
    fragmentTransaction.commit()
}

}



"Lateinit property `app` has not been initialized" Error after Hilt Migration

I'm migrating our codebase from Dagger 2 to Hilt. I'm kind of a noob. I've gotten everything to build and compile. There is a crasher on app launch with this error:

Logcat

2022-07-27 11:31:26.297 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.appname.company, PID: 17599
    java.lang.RuntimeException: Unable to create application com.appname.BaseApplication: kotlin.UninitializedPropertyAccessException: lateinit property app has not been initialized
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6767)
        at android.app.ActivityThread.access$1500(ActivityThread.java:256)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2091)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7870)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
     Caused by: kotlin.UninitializedPropertyAccessException: lateinit property app has not been initialized
        at com.appname.BaseApplication$Companion.getApp(BaseApplication.kt:746)
        at com.appname.BaseApplication$Companion$sharedPrefs$2.invoke(BaseApplication.kt:839)
        at com.appname.BaseApplication$Companion$sharedPrefs$2.invoke(BaseApplication.kt:838)
        at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74)
        at com.appname.BaseApplication$Companion.getSharedPrefs(BaseApplication.kt:838)
        at com.appname.BaseApplication$Companion.getOverrideUrl(BaseApplication.kt:894)
        at com.appname.BaseApplication$Companion.getBaseUrl(BaseApplication.kt:908)
        at com.appname.db.network.NetworkService.<init>(NetworkService.kt:47)
        at com.appname.DaggerBaseApplication_HiltComponents_SingletonC$Builder.build(DaggerBaseApplication_HiltComponents_SingletonC.java:308)
        at com.appname.Hilt_BaseApplication$1.get(Hilt_BaseApplication.java:22)
        at dagger.hilt.android.internal.managers.ApplicationComponentManager.generatedComponent(ApplicationComponentManager.java:40)
        at com.appname.Hilt_BaseApplication.generatedComponent(Hilt_BaseApplication.java:33)
        at com.appname.Hilt_BaseApplication.onCreate(Hilt_BaseApplication.java:41)
        at com.appname.BaseApplication.onCreate(BaseApplication.kt:182)
        at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1223)

The property app in BaseApplication is referenced all over the codebase.

BaseApplication.kt

@HiltAndroidApp
open class BaseApplication : Application() {
    ....

    // (Injections in case they are relevant) //

    @Inject
    lateinit var hsAnalytics: HsAnalytics

    ....

    @Inject @field:Named(NetworkService.Keys.GRAPH_QL_OKHTTP_CLIENT)
    lateinit var okHttpClient: OkHttpClient

    @Inject
    lateinit var apolloClient: ApolloClient
    ....
    
    // onCreate()
    override fun onCreate() {
        super.onCreate()

        // Assign static "app" variable before ANYTHING else. <- This note was in the code base from an old dev that is no longer around
        app = this
    
        ....
    }

        ....
    companion object {
        ....
        // TODO: Should consider whether or not these should be static <- Notes from old dev who isn't around anymore
        //<editor-fold desc="Utility methods to help non-context classes retrieve context-related objects">
        @JvmStatic
        lateinit var app: BaseApplication
            private set
        ....
    }
}

AppModule.kt

@Module
@InstallIn(SingletonComponent::class)
object AppModule {

    @Singleton
    @Provides
    fun provideApplication(@ApplicationContext application: BaseApplication): BaseApplication {
        return application as BaseApplication
    }

    @Provides
    @Singleton
    internal fun provideContext(application: BaseApplication): Context = application
}

Any idea why app suddenly isn't being instantiated?

Update - NetworkService.kt

@InstallIn(SingletonComponent::class)
@Module
class NetworkService @Inject constructor() {

    object Keys {
        const val GRAPH_QL_OKHTTP_CLIENT = "graph_ql"
        const val ACTIVITY_FEED_RETROFIT = "activity_feed_retrofit"
        const val ACTIVITY_FEED_OKHTTP = "activity_feed_client"
    }

    private val baseUrl: String = BaseApplication.baseUrl
    private val feedBaseUrl: String = BaseApplication.feedBaseUrl

    lateinit var api: NetworkServiceAPI
    lateinit var feedApi: FeedNetworkServiceAPI
    lateinit var harInterceptor: HarInterceptor

    @Provides
    @Singleton
    internal fun provideAPI(retrofit: Retrofit): NetworkServiceAPI {
        return retrofit.create(NetworkServiceAPI::class.java)
    }

    @Provides
    @Singleton
    internal fun provideFeedAPI(@Named(Keys.ACTIVITY_FEED_RETROFIT) retrofit: Retrofit): FeedNetworkServiceAPI {
        return retrofit.create(FeedNetworkServiceAPI::class.java)
    }

    @Provides
    @Singleton
    internal fun provideRetrofit(gson: Gson, okHttpClient: OkHttpClient): Retrofit {
        val contentType = "application/json".toMediaType()
        return Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(defaultJson.asConverterFactory(contentType))
//                .addConverterFactory(GsonConverterFactory.create(gson))
                .client(okHttpClient)
                .build()
    }

    @Provides
    @Singleton
    @Named(Keys.ACTIVITY_FEED_RETROFIT)
    internal fun provideFeedRetrofit(@Named(Keys.ACTIVITY_FEED_OKHTTP) okHttpClient: OkHttpClient): Retrofit {
        val contentType = "application/json".toMediaType()
        val converter = defaultJson.asConverterFactory(contentType)
        return Retrofit.Builder()
                .baseUrl(feedBaseUrl)
                .addConverterFactory(converter)
                .client(okHttpClient)
                .build()
    }

    @Provides
    @Singleton
    @Inject
    internal fun provideClient(chuckerInterceptor: ChuckerInterceptor,
    harInterceptor: HarInterceptor): OkHttpClient {
        val builder = OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .addCertificateTransparencyInterceptor()

        builder.addInterceptor(object : Interceptor {
            @Throws(IOException::class)
            override fun intercept(chain: Interceptor.Chain): Response {
                val url = chain.request().url.toString()
                Timber.d("Calling URL: $url")
                val requestBuilder = chain.request().newBuilder()

                // Add every default header to all connections that are made
                val headers = Brand.getInstance().getHttpHeaders(url)
                for ((key, value) in headers) {
                    requestBuilder.addHeaderRemovingSymbols(key, value)
                }

                return chain.proceed(requestBuilder.build())
            }
        })
                .addNetworkLoggingInterceptor(chuckerInterceptor)
                .addInterceptor(harInterceptor)

        if (DEBUGGABLE) {
            // In Debug, log network requests
            val logging = HttpLoggingInterceptor()
            logging.level = HttpLoggingInterceptor.Level.BASIC
            builder.addInterceptor(logging)
                    .addInterceptor(CurlInterceptor { message -> Timber.d(message) })
        }

        return builder.build()
    }

    @Provides
    @Singleton
    @Inject
    @Named(Keys.ACTIVITY_FEED_OKHTTP)
    internal fun provideActivityFeedClient(
            chuckerInterceptor: ChuckerInterceptor,
            harInterceptor: HarInterceptor): OkHttpClient {
        val builder = OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .addCertificateTransparencyInterceptor()

        builder.addInterceptor(object : Interceptor {
            @Throws(IOException::class)
            override fun intercept(chain: Interceptor.Chain): Response {
                val url = chain.request().url.toString()
                Timber.d("Calling URL: $url")
                val requestBuilder = chain.request().newBuilder()

                // Add every default header to all connections that are made
                val headers = Brand.getInstance().getHttpHeaders(url)
                val apiToken = BaseApplication.sharedPrefs.getString(AppConstants.API_TOKEN, null)
                apiToken?.let { headers["Api-key"] = it }
                headers.forEach { (key, value) ->
                    requestBuilder.addHeaderRemovingSymbols(key, value)
                }

                return chain.proceed(requestBuilder.build())
            }
        })
                .addNetworkLoggingInterceptor(chuckerInterceptor)
                .addNetworkInterceptor(harInterceptor)

        if (DEBUGGABLE) {
            // In Debug, log network requests
            val logging = HttpLoggingInterceptor()
            logging.level = HttpLoggingInterceptor.Level.BASIC
            builder.addInterceptor(logging)
                    .addInterceptor(CurlInterceptor { message -> Timber.d(message) })
        }

        return builder.build()
    }

    @Provides
    @Singleton
    @Inject
    @Named(Keys.GRAPH_QL_OKHTTP_CLIENT)
    internal fun provideGraphQlClient(
            chuckerInterceptor: ChuckerInterceptor,
            harInterceptor: HarInterceptor): OkHttpClient {
        val builder = OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .addCertificateTransparencyInterceptor()

        builder.addInterceptor(object : Interceptor {
            @Throws(IOException::class)
            override fun intercept(chain: Interceptor.Chain): Response {
                val url = chain.request().url.toString()
                Timber.d("Calling URL: $url")
                val requestBuilder = chain.request().newBuilder()

                // Add every default header to all connections that are made
                val headers = Brand.getInstance().getHttpHeaders(url)
                val useSuperToken = false
                val superUserToken = BaseApplication.appResources.getString(R.string.activity_feed_super_user_token)
                val apiToken = if (useSuperToken && DEBUGGABLE && superUserToken.isNotEmpty()) {
                    superUserToken
                } else {
                    BaseApplication.sharedPrefs.getString(AppConstants.API_TOKEN, null)
                }
                if (apiToken != null) headers["Authorization"] = "Bearer $apiToken"
                headers.forEach { (key, value) ->
                    requestBuilder.addHeaderRemovingSymbols(key, value)
                }

                return chain.proceed(requestBuilder.build())
            }
        })

                .addNetworkLoggingInterceptor(chuckerInterceptor)
                .addNetworkInterceptor(harInterceptor)

        if (DEBUGGABLE) {
            // In Debug, log network requests
            val logging = HttpLoggingInterceptor()
            logging.level = HttpLoggingInterceptor.Level.BASIC
            builder.addInterceptor(logging)
                    .addInterceptor(CurlInterceptor { message -> Timber.d(message) })
        }

        return builder.build()
    }

    private fun OkHttpClient.Builder.addCertificateTransparencyInterceptor(): OkHttpClient.Builder = apply {
        addNetworkInterceptor(certificateTransparencyInterceptor())
    }

    private fun OkHttpClient.Builder.addNetworkLoggingInterceptor(interceptor: ChuckerInterceptor): OkHttpClient.Builder = apply {
        if (BaseApplication.sharedPrefs.getBoolean(AppConstants.DEBUG_ENABLE_NETWORK_LOGGING, false)) {
            addNetworkInterceptor(interceptor)
        }
    }

    @Provides
    @Singleton
    @Inject
    fun providesNetworkLoggingInterceptor(@ApplicationContext context: Context): ChuckerInterceptor {
        return ChuckerInterceptor(context)
    }

    @Provides
    @Singleton
    @Inject
    fun providesHarInterceptor(@ApplicationContext context: Context): HarInterceptor {
        return HarInterceptor(context)
    }

    @Provides
    @Singleton
    @Inject
    fun providesApolloClient(@Named(Keys.GRAPH_QL_OKHTTP_CLIENT) okHttpClient: OkHttpClient): ApolloClient {
        val apiUrl: String = BaseApplication.apiBaseUrl
        return ApolloClient.builder().serverUrl("$apiUrl/graphql")
                .okHttpClient(okHttpClient).build()
    }

    @Provides
    @Singleton
    internal fun provideGson(): Gson {
        return GsonBuilder()
                .setLenient()
                .serializeNulls()
                .create()
    }

    @Provides
    @Singleton
    @Inject
    fun providesNetworkService(api: NetworkServiceAPI,
                               feedApi: FeedNetworkServiceAPI,
                                harInterceptor: HarInterceptor): NetworkService {
        this.api = api
        this.feedApi = feedApi
        this.harInterceptor = harInterceptor
        return this
    }

    companion object {
        val defaultJson = Json {
            encodeDefaults = true
            ignoreUnknownKeys = true
            isLenient = true
            allowSpecialFloatingPointValues = false
        }
    }

}

fun Request.Builder.addHeaderRemovingSymbols(key: String, value: String?): Request.Builder {
    Timber.d("Header: $key : $value")
    value?.let { return addHeader(key, it.replace(Regex("[^\\u0020-\\u007e‘’]"), "")) }
    return this
}


CP only folders data that match in two different directories into one directory using linux or bash

What would be a efficient way to look into two different directories and if subdirectories match, copy these subfolders in a new output folder linux or bash scripting? I know I need cp command and do match based on SC#### values.

Example folder one:

[NAME]$ Project
Sample_SC1234-AAA-AAA
Sample_SC2345-AAA-BBB
Sample_SC3456-CCC-CCC
Sample_SC4567-DDD-AAA

Example folder Two:

[NAME]$ Lz
Sample_SC1234-AAA-BBB
Sample_SC4567-BBB-AAA
Sample_SC5678-DDD-BBB
Sample_SC6789-BBB-DDD

Wanted output:

[NAME]$ New
Sample_SC1234-AAA-BBB
Sample_SC4567-BBB-AAA
Sample_SC1234-AAA-AAA
Sample_SC4567-DDD-AAA


VBA macro how to click on button on website on chrome, using Selenium

I am trying to program to click on one button on website on chrome. The name of the button is "Add to Cart".

Please see HTML of the website: enter image description here

And this is the VBA code:

CD.FindElementByCss("div.addToCartButtons clearAfter > button blue right s-addToCart > span.Add to Cart").Click

How can I do this?



Duplicate entry for key 'PRIMARY' codeigniter

i got error Duplicate entry '19-0' for key 'PRIMARY' after insert all multiple to database

$resp = curl_exec($curl);
$gorong = json_decode($resp);
foreach ($gorong->data as $g){
                        $this->db->insert('mod_auto_harga', array(
                        'sv_id' => '19',
                        'kode' => $g->buyer_sku_code,
                        'keterangan' => $g->product_name,
                        'harga' => $g->price,
                        'status' => $g->seller_product_status,
                        'type' => $g->type,
                        ));
     
        $id = $this->db->insert_id();
 

enter image description here



2022-07-27

Enabling Wordpress debug mode in docker-compose environment

I'm having problems understanding how to enable wordpress debug mode through docker-compose. image of wp-config.php debug section

define( 'WP_DEBUG', !!getenv_docker('WORDPRESS_DEBUG', '') );

This is the part of the wp-config.php file where I should be able to enable it. The file is read only and it seems to be designed to enable this feature through docker-compose.yaml file but I cant figure out how. I have tried adding WORDPRESS_DEBUG: 'true' to the environment section of wordpress service but it throws error with true/fals data type and 'true' as a string does not seem to work. The only solution I can come up with is to edit the file as superuser.



searching in strings from tk-inter text fails

Why does the search fail when taking a string from a tk-inter text box? The search works fine if I define the keyword as a string.

Minimal example:

import tkinter as tk
root = tk.Tk()
string="banana\napplepie\napple\n"

def searchcall():
 
    textboxcontent=textExample.get("1.0","end")
    keyword=filterbox.get("1.0","end")
    keyword="apple" # search works as expected

    print("keyword",keyword)
    print("is keyword in textbox",keyword in textboxcontent)
    for elem in textboxcontent.split():
        print("seaching for",keyword,"in",elem,keyword in elem)
 
        

textExample=tk.Text(root, height=10)
textExample.insert(1.0,string)
textExample.pack()
filterbox=tk.Text(root, height=1)
filterbox.insert(1.0,"apple")
filterbox.pack()
btnRead=tk.Button(root, height=1, width=11, text="search", 
                    command=searchcall)

btnRead.pack()
root.mainloop()


Writing to a CSV file in an S3 bucket using boto 3

I'm working on a project that needs to update a CSV file with user info periodically. The CSV is stored in an S3 bucket so I'm assuming I would use boto3 to do this. However, I'm not exactly sure how to go about this- would I need to download the CSV from S3 and then append to it, or is there a way to do it directly? Any code samples would be appreciated.



How does pybind11 methods end up calling functions from the shared library?

I can make as much out as its build system generates a shared object, and also a Python module as a proxy to that shared object. But how does the Python runtime end up doing a dlopen of the generated shared object and bind Python method calls on to corresponding functions in the shared library?

I also found a reference in Python's import system about shared libraries, but nothing beyond that. Does CPython treat .so files in the module path as Python modules?



XCode can't build my project because it says my Apple ID session is expired but I can't login?

So it says my session has expired, I try to login, but nothing happens... It's not like it's wrong or something if I type just one character it says "Wrong password" but if I type the correct password literally nothing happens and I can't continue building my project because of this, does anyone know what I can do? I tried to find other people with this problem but nobody seemed to have a problem where they couldn't login to their Apple ID recently.

Picture



how to edit adb connect limit

I found that the maximum number of devices connected to ADB through IP:PORT on my Linux server is 30 devices. I want to make this limit more, such as 1000 devices, by modifying the ADB source code. But I am from https://android .googlesource.com/platform/packages/modules/adb No 30 related codes were found in the downloaded source code. I tried to download more source code for ADB dependencies, but still can't find the relevant code. I don't know much about C language. Can someone give me some hints? Where should I find the code to limit the connection limit?

I'm downloading all the code for AOSP now, but it always fails because of network and hard disk space issues. I'm trying to figure out a way to fix it. If I download all the code for AOSP. Will it help me to solve this problem?