2021-02-28

How do I make make multiple RecyclerViews for with the same data?

I created a calendar app that stores tasks as well as their description and time. It makes use of a RecyclerView to arrange the given data. But I want to create a new RecyclerView that can retrieve this same data and display it on the activity_main layout as a listview.

Like the arrow shows on the picture, that's where I want to display the listview

Would I need to create another RecyclerView or make use of the one I have? How can I achieve it?

Please respond as soon as possible. Thank you very much.



from Recent Questions - Stack Overflow https://ift.tt/37P5x6n
https://ift.tt/eA8V8J

Return every row that contains the most occurring value

This question may seem similar to a common question that asks to return the most occurring value. However, I need to list every row containing the value that occurs most often.

In my example there is a zipCode that appears 3 times (the most out of any zip code). I would like to list every occurrence of that zip code without having to know which zip code has the most occurrences at the time of the query.

My Query:

SELECT *, COUNT(zipCode) AS NumOccurrences
FROM customers
GROUP BY zipCode
ORDER BY NumOccurrences DESC
LIMIT 1

Returns:

enter image description here

What I want to return:

enter image description here

Without using this query obviously:

SELECT *
FROM customers
WHERE zipCode = 10001

I want to return each of the 3 occurrences of that zip code and not just the first instance of it. Without having to use the query above because I may not now which zip code occurs the most at the time of the query.



from Recent Questions - Stack Overflow https://ift.tt/3dRslpV
https://ift.tt/37VfIWT

DevExpress components require ASPxHttpHandlerModule registered in the web.config file

My friend has created a project in asp.net and I am trying to run one of its '.aspx' pages on my side in Visual Studio 2019 but it is giving me this error when I run the project:

DevExpress components require ASPxHttpHandlerModule registered in the web.config file.

Full exception: Exception

He is using DevExpress controls; I have downloaded DevExpress 20.2 and my web.config is also all set, but when I try to run it's giving me the same error.

Here is my web.config file:

<?xml version="1.0" encoding="utf-8"?>
<!--
          For more information on how to configure your ASP.NET application, please visit https://go.microsoft.com/fwlink/?LinkId=169433
          -->
<configuration>
    <configSections>
        <sectionGroup name="devExpress">
            <section name="themes" type="DevExpress.Web.ThemesConfigurationSection, DevExpress.Web.v20.2, Version=20.2.5.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" requirePermission="false" />
            <section name="compression" type="DevExpress.Web.CompressionConfigurationSection, DevExpress.Web.v20.2, Version=20.2.5.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" requirePermission="false" />
            <section name="settings" type="DevExpress.Web.SettingsConfigurationSection, DevExpress.Web.v20.2, Version=20.2.5.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" requirePermission="false" />
            <section name="errors" type="DevExpress.Web.ErrorsConfigurationSection, DevExpress.Web.v20.2, Version=20.2.5.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" requirePermission="false" />
            <section name="resources" type="DevExpress.Web.ResourcesConfigurationSection, DevExpress.Web.v20.2, Version=20.2.5.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" requirePermission="false" />
        </sectionGroup>
    </configSections>
    <connectionStrings>
        <add name="Foodcourt" connectionString="Data Source=168.1.35.207,25000;Initial Catalog=db5628_LMHV3;User Id=db5628_frysys;Password=Varykino1a" providerName="System.Data.SqlClient" />
    </connectionStrings>
    <system.web>
        <compilation debug="true" targetFramework="4.7.2">
            <assemblies>
                <add assembly="System.Web.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
                <add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
                <add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
                <add assembly="System.Drawing.Common, Version=4.0.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" />
                <add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
                <add assembly="Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845DCD8080CC91" />
                <add assembly="Microsoft.ReportViewer.Common, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845DCD8080CC91" />
                <add assembly="Microsoft.Build.Framework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
                <add assembly="DevExpress.Web.ASPxRichEdit.v20.2, Version=20.2.5.0, Culture=neutral, PublicKeyToken=B88D1754D700E49A" />
                <add assembly="DevExpress.Web.v20.2, Version=20.2.5.0, Culture=neutral, PublicKeyToken=B88D1754D700E49A" />
                <add assembly="DevExpress.RichEdit.v20.2.Core, Version=20.2.5.0, Culture=neutral, PublicKeyToken=B88D1754D700E49A" />
                <add assembly="DevExpress.Data.v20.2, Version=20.2.5.0, Culture=neutral, PublicKeyToken=B88D1754D700E49A" />
                <add assembly="DevExpress.Printing.v20.2.Core, Version=20.2.5.0, Culture=neutral, PublicKeyToken=B88D1754D700E49A" />
                <add assembly="DevExpress.Office.v20.2.Core, Version=20.2.5.0, Culture=neutral, PublicKeyToken=B88D1754D700E49A" />
                <add assembly="DevExpress.Web.ASPxSpellChecker.v20.2, Version=20.2.5.0, Culture=neutral, PublicKeyToken=B88D1754D700E49A" />
                <add assembly="DevExpress.SpellChecker.v20.2.Core, Version=20.2.5.0, Culture=neutral, PublicKeyToken=B88D1754D700E49A" />
                <add assembly="DevExpress.Web.ASPxThemes.v20.2, Version=20.2.5.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" />
                <add assembly="netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" />
            </assemblies>
            <buildProviders>
                <add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
            </buildProviders>
        </compilation>
        <httpRuntime targetFramework="4.7.2" />
        <pages>
            <namespaces>
                <add namespace="System.Web.Optimization" />
            </namespaces>
            <controls>
                <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
                <add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" />
            </controls>
        </pages>
        <httpModules>
            <add type="DevExpress.Web.ASPxHttpHandlerModule, DevExpress.Web.v20.2, Version=20.2.5.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" name="ASPxHttpHandlerModule" />
        </httpModules>
        <httpHandlers>
            <add path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" validate="false" />
            <add type="DevExpress.Web.ASPxHttpHandlerModule, DevExpress.Web.v20.2, Version=20.2.5.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" verb="GET,POST" path="DX.ashx" validate="false" />
            <add type="DevExpress.Web.ASPxUploadProgressHttpHandler, DevExpress.Web.v20.2, Version=20.2.5.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" verb="GET,POST" path="ASPxUploadProgressHandlerPage.ashx" validate="false" />
        </httpHandlers>
    </system.web>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" />
                <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" />
                <bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Drawing.Common" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-4.0.0.1" newVersion="4.0.0.1" />
            </dependentAssembly>
        </assemblyBinding>
    </runtime>
    <system.webServer>
        <modules>
            <add type="DevExpress.Web.ASPxHttpHandlerModule, DevExpress.Web.v20.2, Version=20.2.5.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" name="ASPxHttpHandlerModule" />
        </modules>
        <validation validateIntegratedModeConfiguration="false" />
        <handlers>
            <add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
            <add type="DevExpress.Web.ASPxHttpHandlerModule, DevExpress.Web.v20.2, Version=20.2.5.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" verb="GET,POST" path="DX.ashx" name="ASPxHttpHandlerModule" preCondition="integratedMode" />
            <add type="DevExpress.Web.ASPxUploadProgressHttpHandler, DevExpress.Web.v20.2, Version=20.2.5.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" verb="GET,POST" path="ASPxUploadProgressHandlerPage.ashx" name="ASPxUploadProgressHandler" preCondition="integratedMode" />
        </handlers>
    </system.webServer>
    <devExpress>
        <themes enableThemesAssembly="true" styleSheetTheme="" theme="" customThemeAssemblies="" baseColor="" font="" />
        <compression enableHtmlCompression="false" enableCallbackCompression="true" enableResourceCompression="true" enableResourceMerging="true" />
        <settings accessibilityCompliant="false" bootstrapMode="" doctypeMode="Html5" rightToLeft="false" checkReferencesToExternalScripts="true" protectControlState="true" ieCompatibilityVersion="edge" />
        <errors callbackErrorRedirectUrl="" />
    </devExpress>

</configuration>

Have tried several solutions but none worked. Can anyone tell me what's wrong and what to do?

Thanks!



from Recent Questions - Stack Overflow https://ift.tt/3bJl8FK
https://ift.tt/3bRamNQ

Add Network Image to Flutter BottomNavigationBar (google_nav_bar)

i am using google_nav_bar.dart package for BottomNavigationBar. And, I want to use Network Image as icon in it. I tried a lot of resources but nothing is working. Please help me out.

Package: https://pub.dev/packages/google_nav_bar

My Code Snippet where I want to use NetworkImage.

GButton(
          icon: LineIcons.user,
          text: 'Profile',
       ),


from Recent Questions - Stack Overflow https://ift.tt/3uE063X
https://ift.tt/eA8V8J

Insert to Multiple tables using Select statment?

I am trying to do mysql copy & paste statement.

I have MySQL table like this:

Table 1: Employee
empid  F_Name      L_Name    Email 
1      Nitin       Varpe     fedexnit@gmail.com
2      Prashant    Bankar    pbankar@yahoo.com
Table 1: salary
salaryid  empid    Month       Salary 
1         1        Feb 2021    fedexnit@gmail.com
2         2        Feb 2021    pbankar@yahoo.com

Suppose if I click copy and paste button I should get following output:

Table 1: Employee
empid  F_Name      L_Name    Email 
1      Nitin       Varpe     fedexnit@gmail.com
2      Prashant    Bankar    pbankar@yahoo.com
3      Nitin       Varpe     fedexnit@gmail.com
4      Prashant    Bankar    pbankar@yahoo.com
Table 1: salary
salaryid  empid    Month       Salary 
1         1        Feb 2021    1000
2         2        Feb 2021    2000
3         3        Feb 2021    1000
4         4        Feb 2021    2000

It should insert to the same table with different id. I used INSERT INTO Employee SELECT statement but it is not working. Kindly give us perfect mysql statement.



from Recent Questions - Stack Overflow https://ift.tt/2ZYjNVW
https://ift.tt/eA8V8J

Mocha sidebar vscode extension is not auto refreshing the tests

I have just installed the mocha-sidebar extension in vs code. I am using the following config in my settings.json file:

{
"mocha.files.glob": "test/**/*.spec.js",
"mocha.requires": [],
"mocha.env": {
    "NODE_ENV": "test"
},
"mocha.sideBarOptions": {
    "lens": true, 
    "decoration": true,
    "autoUpdateTime": 1000,
    "showDebugTestStatus": true 
}

}

If I click the green play button in the extension window it runs the tests correctly and shows the results in the sidebar. If I now update the test to make it fail the previously green circle next to the test changes to yellow, but nothing else happens.

I would expect the test to be shown with a red circle (failing), I would also expect the test in the test file to have a red dot next to the failing test, but this remains green.

I have to run the tests by pressing the green play button again from the sidebar.

The other thing I have noticed is that when a test fails, it reports the failure in the test file e.g. //expected a to equal a. But when the test is updated to pass the comment does not get removed and I have to switch files and then return to the test file which then seems to remove the comment.

Thanks in advance!



from Recent Questions - Stack Overflow https://ift.tt/3aYdok0
https://ift.tt/eA8V8J

How do I suppress expected Axios error messages when testing error states with react-testing-library?

I'm working on adapting some React code of mine to use @testing-library/react, react-query, and msw to mock network calls that I make using axios.

So far (after some brainbending) I've got it working with this code! (yay!)

The test in question (simplified):

import React from 'react';
import { rest } from 'msw';
import { setupServer } from 'msw/node';
import { screen, waitFor, waitForElementToBeRemoved } from '@testing-library/react';
import { queryCache } from 'react-query';
import userEvent from '@testing-library/user-event';
import Login from '../Login';
import { render, queryClient } from '~/testhelpers/helpers.integration';
// #endregion imports

const server = setupServer(
    // ...default setup for successful request; not relevant here
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

describe('rendering', () => {
    describe('error', () => {
        it.only('should render error message when request fails', async () => {
            server.use(
                rest.post(`${API_BASE_URL}api/auth/token`, (req, res, ctx) => {
                    return res(ctx.status(400), ctx.json('Invalid username or password.'));
                })
            );
            render(<Login />);
            const usernameInput = screen.getByLabelText('Username');
            const passwordInput = screen.getByLabelText('Password');
            const submitInput = screen.getByRole('button', { name: 'Login' });
            userEvent.type(usernameInput, 'testUsername');
            userEvent.type(passwordInput, 'testPassword');
            userEvent.click(submitInput);
            await waitFor(() => {
                expect(screen.getByText('Invalid username or password.')).toBeInTheDocument();
            });
        });
    });
});

Again, this test works! Hooray! But the issue is that I am making axios think (via msw) that it is receiving a 400 response for this query, and I get this big chunk of error message in my console when I run this test with Jest:

 PASS  src/display/views/login/__tests__/Login.spec.js
  rendering
    error
      √ should hide loading indicator and render error message when request fails (522 ms)

  console.error
    Error: Request failed with status code 400
        at createError (C:\Users\me\Documents\_Programming\GitHub\my-project\node_modules\axios\lib\core\createError.js:16:15)
        at settle (C:\Users\me\Documents\_Programming\GitHub\my-project\node_modules\axios\lib\core\settle.js:18:12)
        at XMLHttpRequestOverride.handleLoad [as onreadystatechange] (C:\Users\me\Documents\_Programming\GitHub\my-project\node_modules\axios\lib\adapters\xhr.js:59:7)
        at XMLHttpRequestOverride.triggerReadyStateChange (C:\Users\me\Documents\_Programming\GitHub\my-project\node_modules\node-request-interceptor\src\interceptors\XMLHttpRequest\XMLHttpRequestOverride.ts:133:33)     
        at XMLHttpRequestOverride.trigger (C:\Users\me\Documents\_Programming\GitHub\my-project\node_modules\node-request-interceptor\src\interceptors\XMLHttpRequest\XMLHttpRequestOverride.ts:145:12)
        at C:\Users\me\Documents\_Programming\GitHub\my-project\node_modules\node-request-interceptor\src\interceptors\XMLHttpRequest\XMLHttpRequestOverride.ts:306:18
        at runNextTicks (internal/process/task_queues.js:62:5)
        at processTimers (internal/timers.js:489:9) {
      config: {
        adapter: [Function: xhrAdapter],
        transformRequest: { '0': [Function: transformRequest] },
        transformResponse: { '0': [Function: transformResponse] },
        timeout: 0,
        xsrfCookieName: 'XSRF-TOKEN',
        xsrfHeaderName: 'X-XSRF-TOKEN',
        maxContentLength: -1,
        validateStatus: [Function: validateStatus],
        headers: {
          Accept: 'application/json, text/plain, */*',
          'Content-Type': 'application/json;charset=utf-8'
        },
        method: 'post',
        url: 'http://baseurl/api/auth/token',
        data: '{"username":"testUsername","password":"testPassword"}'
      },
      request: XMLHttpRequestOverride {
        requestHeaders: {
          Accept: 'application/json, text/plain, */*',
          'Content-Type': 'application/json;charset=utf-8'
        },
        responseHeaders: { 'x-powered-by': 'msw', 'content-type': 'application/json' },
        _events: [],
        UNSENT: 0,
        OPENED: 1,
        HEADERS_RECEIVED: 2,
        LOADING: 3,
        DONE: 4,
        onreadystatechange: [Function: handleLoad],
        onabort: null,
        onerror: [Function: handleError],
        onload: null,
        onloadend: null,
        onloadstart: null,
        onprogress: null,
        ontimeout: [Function: handleTimeout],
        url: 'http://baseurl/api/auth/token',
        method: 'POST',
        readyState: 4,
        withCredentials: false,
        status: 400,
        statusText: 'Bad Request',
        data: '{"username":"testUsername","password":"testPassword"}',
        response: '"Invalid username or password."',
        responseType: 'text',
        responseText: '"Invalid username or password."',
        responseXML: null,
        responseURL: '',
        upload: null,
        timeout: 0,
        async: true,
        user: undefined,
        password: undefined
      },
      response: {
        data: 'Invalid username or password.',
        status: 400,
        statusText: 'Bad Request',
        headers: { 'x-powered-by': 'msw', 'content-type': 'application/json' },
        config: {
          adapter: [Function: xhrAdapter],
          transformRequest: [Object],
          transformResponse: [Object],
          timeout: 0,
          xsrfCookieName: 'XSRF-TOKEN',
          xsrfHeaderName: 'X-XSRF-TOKEN',
          maxContentLength: -1,
          validateStatus: [Function: validateStatus],
          headers: [Object],
          method: 'post',
          url: 'http://baseurl/api/auth/token',
          data: '{"username":"testUsername","password":"testPassword"}'
        },
        request: XMLHttpRequestOverride {
          requestHeaders: [Object],
          responseHeaders: [Object],
          _events: [],
          UNSENT: 0,
          OPENED: 1,
          HEADERS_RECEIVED: 2,
          LOADING: 3,
          DONE: 4,
          onreadystatechange: [Function: handleLoad],
          onabort: null,
          onerror: [Function: handleError],
          onload: null,
          onloadend: null,
          onloadstart: null,
          onprogress: null,
          ontimeout: [Function: handleTimeout],
          url: 'http://baseurl/api/auth/token',
          method: 'POST',
          readyState: 4,
          withCredentials: false,
          status: 400,
          statusText: 'Bad Request',
          data: '{"username":"testUsername","password":"testPassword"}',
          response: '"Invalid username or password."',
          responseType: 'text',
          responseText: '"Invalid username or password."',
          responseXML: null,
          responseURL: '',
          upload: null,
          timeout: 0,
          async: true,
          user: undefined,
          password: undefined
        }
      }
    }

      at CustomConsole.console.error (node_modules/@testing-library/react/dist/act-compat.js:52:34)
      at node_modules/react-query/lib/core/mutation.js:115:32

I think, to a certain extent, this is expected, but it's REALLY unnecessary spam in my tests given that I am expecting and in fact wanting that request to fail. Is there a best practice way to remove this unnecessary log via config for Jest, RTL, msw, or Axios?



from Recent Questions - Stack Overflow https://ift.tt/2NKFXIQ
https://ift.tt/eA8V8J

React Native Firebase Cloud Messaging throwing errors on build for RN 0.63.4

I followed the instructions from here but the compilation is showing these errors. I'm guessing it's some sort of version incompatibility, but I believe I'm on the latest version of react-native-firebase. When I build the app, these errors show up:

❌  /Users/matt/Desktop/myapp/node_modules/react-native-firebase/ios/RNFirebase/messaging/RNFirebaseMessaging.m:91:51: expected a type

- (void)applicationReceivedRemoteMessage:(nonnull FIRMessagingRemoteMessage *)remoteMessage {
                              ^



❌  /Users/matt/Desktop/myapp/node_modules/react-native-firebase/ios/RNFirebase/messaging/RNFirebaseMessaging.m:99:28: expected a type

didReceiveMessage:(nonnull FIRMessagingRemoteMessage *)remoteMessage {
                                                  ^



❌  /Users/matt/Desktop/myapp/node_modules/react-native-firebase/ios/RNFirebase/messaging/RNFirebaseMessaging.m:278:50: expected a type

- (NSDictionary*)parseFIRMessagingRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
                           ^



❌  /Users/matt/Desktop/myapp/node_modules/react-native-firebase/ios/RNFirebase/messaging/RNFirebaseMessaging.m:44:30: property 'shouldEstablishDirectChannel' not found on object of type 'FIRMessaging *'

    [FIRMessaging messaging].shouldEstablishDirectChannel = YES;
                                                 ^



❌  /Users/matt/Desktop/myapp/node_modules/react-native-firebase/ios/RNFirebase/messaging/RNFirebaseMessaging.m:223:31: no visible @interface for 'FIRMessaging' declares the selector 'sendMessage:to:withMessageID:timeToLive:'

    [[FIRMessaging messaging] sendMessage:data to:to withMessageID:messageId timeToLive:[ttl intValue]];
                             ^



❌  /Users/matt/Desktop/myapp/node_modules/react-native-firebase/ios/RNFirebase/messaging/RNFirebaseMessaging.m:279:43: property 'appData' not found on object of type '__strong id'

    NSDictionary *appData = remoteMessage.appData;
     ~~~~~~~~~~~~~~~~~~~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
...
** BUILD FAILED **


The following build commands failed:
    CompileC /Users/matt/Library/Developer/Xcode/DerivedData/myapp-gpcpfeonrmwlebbsoklspvmumvzd/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RNFirebase.build/Objects-normal/x86_64/RNFirebaseFirestore.o /Users/matt/Desktop/myapp/node_modules/react-native-firebase/ios/RNFirebase/firestore/RNFirebaseFirestore.m normal x86_64 objective-c com.apple.compilers.llvm.clang.1_0.compiler
    CompileC /Users/matthewrosendin/Library/Developer/Xcode/DerivedData/myapp-gpcpfeonrmwlebbsoklspvmumvzd/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RNFirebase.build/Objects-normal/x86_64/RNFirebaseMessaging.o /Users/matt/Desktop/myapp/node_modules/react-native-firebase/ios/RNFirebase/messaging/RNFirebaseMessaging.m normal x86_64 objective-c com.apple.compilers.llvm.clang.1_0.compiler
(2 failures)

Nothing was working, so I updated my Podfile as shown here

Here's my Podfile:

...
platform :ios, '11.0'

target 'myapp' do
  pod 'Firebase/Analytics'
  pod 'Firebase/Messaging'
  ...

I tried removing these pods, as React Native >= 0.60 seems to do auto-linking.

In my package.json:

...
    "react-native-firebase": "^5.6.0",
    "@react-native-firebase/app": "^10.8.1",
    "@react-native-firebase/firestore": "^10.8.1",
    "@react-native-firebase/messaging": "^10.8.1",
...


from Recent Questions - Stack Overflow https://ift.tt/3ktqmcs
https://ift.tt/eA8V8J

error: no match for call to '(const std::ranges::__sort_fn)

I was practicing vectors and ranges in c++ 20 was stuck at following state.

#include <iostream>
#include <vector>
#include <random>
#include <ranges>
#include <algorithm>

namespace ranges = std::ranges;

struct Model
{
    double next_event_time;
};

std::vector<Model> generate_examples(int number)
{
    // A uniform random number generator object
    // Used as the source of randomness
    std::default_random_engine generator;

    // Calls () operator on generator to get uniformly-distributed integers
    // then transforms the obtained values to output the disired distribution

    // Will uniformly generate values between 0 ~ 1
    std::uniform_real_distribution<double> distribution(0.0, 1.0);

    std::vector<Model> models;

    for (auto i = 0; i < number; i++)
    {
        models.push_back(Model{.next_event_time = distribution(generator)});
    }

    return models;
}

Model get_next_model(const std::vector<Model> &models)
{
    ranges::sort(models | std::views::transform([](const Model &x) { return x.next_event_time; }));

    return models[0];
}

int main()
{
    std::vector<Model> models = generate_examples(10);

    for (const auto &model : models)
        std::cout << model.next_event_time << std::endl;
}

I compiled the code with g++ 10.2 and got error

 error: no match for call to '(const std::ranges::__sort_fn) ~~~
ranges::sort(models | std::views::transform([](const Model &x) { return x.next_event_time; }));

Instead of std::views::transform, I also tried

  1. lambda expression
  2. ranges::sort(models, {}, &Model::next_event_time)

But they all produced similar no match for call to error. Why is this happening?



from Recent Questions - Stack Overflow https://ift.tt/3sCF2c3
https://ift.tt/eA8V8J

How to change generated thumbnail color profile

In my iOS app, I'm recording a video. Later I'm generating a thumbnail from that video and saving it on device. My code looks like this:

let asset = AVAsset(url: videoUrl)
let imageGenerator = AVAssetImageGenerator(asset: asset)
imageGenerator.appliesPreferredTrackTransform = true
imageGenerator.maximumSize = CGSize(width: 1280, height: 720)
let image = try imageGenerator.copyCGImage(at: thumbnailTime, actualTime: nil)
let thumbnail = UIImage(cgImage: image)
let jpgData = thumbnail.jpegData(compressionQuality: 0.8)
try jpgData!.write(to: thumbnailUrl!)

The saved image looks good, but it has a color profile set to QuickTime 'nclc' Video (1,1,6)

enter image description here

I'm doing exactly the same thing in the Android app, and there color profile is set to sRGB

enter image description here

How can I generate a thumbnail on iOS that will have a color profile set to sRGB instead of `QuickTime 'nclc' Video (1,1,6)'?



from Recent Questions - Stack Overflow https://ift.tt/37WjsaR
https://ift.tt/37Qp6Ll

NameError: name 'mNewCal' is not defined issue

Im having some issue with my code. Im not really sure what's wrong with it. Thank you

if mNewCal or fNewCal < 1200:

NameError: name 'mNewCal' is not defined

sorry if the format is a little weird, stack overflow made it weird.

gender = int(input("enter your gender as a number from the following \n Male: 1 \n Female: 2 \n " ))
height = int(input("Please enter your height in inches: "))
age = int(input("Please enter your age: "))
weight = int(input("Enter your weight in lbs: "))
exercise = int(input("How much exercise do you do during the week (enter number) \n little to no: 1 \n light: 2 \n moderate: 3 \n heavy: 4 \n  "))
if gender == 1:
   mBMR = 66 + (6.3 * weight) + (12.9 * height) - (6.8 * age)
elif gender == 2:
    fBMR = 655 + (4.3 * weight) + (4.7 * height) - (4.7 * age)

if gender == 1:
    if exercise == 1:
        cal = mBMR * 1.2

    elif exercise == 2:
        cal = mBMR * 1.375

    elif exercise == 3:
        cal = mBMR * 1.55

    elif exercise == 4:
        cal = mBMR * 1.8

else:
    if exercise == 1:
        cal = fBMR * 1.2

    elif exercise == 2:
        cal = fBMR * 1.375

    elif exercise == 3:
        cal = fBMR * 1.55

    elif exercise == 4:
        cal = fBMR * 1.8



if gender == 1:
    mTotalCal = mBMR * 1.2
    #print(mTotalCal)

else:
    fTotalCal = fBMR * 1.2
   # print(fTotalCal)


looseWeight = str(input("do you want to loose weight? if yes, enter Y: \n if no enter N: \n "))

if looseWeight == "Y":
    yesWeight = int(input("How much weight do you want to loose (lbs) ? "))

else:
    print("thank you for using Nakul Industries health program!")


weeks = yesWeight
days = weeks * 7
months = days / 30


if gender == 1:
    mNewCal = mTotalCal - 500
else:
    fNewCal = fTotalCal - 500



if mNewCal or fNewCal < 1200:
    print("WARNING! your total intake will be less then 1200 calories, please consult a doctor before following this.")
    print("In order to lose " + yesWeight + " ,it will take " + weeks + " weeks " + "\n" + "or " + days + " days" + "\n or " + "approximately " + months + " months.")
else:
    print(
        "In order to lose " + yesWeight + " ,it will take " + weeks + " weeks " + "\n" + "or " + days + " days" + "\n or " + "approximately " + months + " months.")


from Recent Questions - Stack Overflow https://ift.tt/3uBCeOl
https://ift.tt/eA8V8J

How can I build a docker image with it parent folder as workdir?

This probably is a dumb question, but I'm newbie in Docker and I'm struggle with this. I have a project with many subfolders, like the example below:

project-folder:
       folder_1:
           code1.py
           Dockerfile
           requirements.txt
       folder_2:
           code2.py
           Dockerfile
           requirements.txt
       folder_data:
           file1
           file2
           file3

Then, I would like to do this:

  1. Maintain my workdir in project-folder for all containers;
  2. Inside each container, I should be able to access the folder_data - I know that I have to specify a volume, I just don't know how to do this without keep my project-folder as workdir;
  3. I need to pass my workdir (project-folder) to my code1.py

Note: my image was created successfully only when I create it within each subfolder, like this Dockerfile:

FROM python:3.6-slim
COPY . /folder_1
WORKDIR /folder_1
RUN pip install -r requirements.txt
CMD ["python3", "code1.py", "$(pwd)"]

Image creation comand:

docker build -t image_folder1 .

I am currently creating the image in the context of folder_1, because I was unable to create the image correctly in the context of the project-folder



from Recent Questions - Stack Overflow https://ift.tt/3pWECfb
https://ift.tt/eA8V8J

a program to change letters in DNA nucleotide

I'm making a program to change the sequence of DNA. When finding the letter "a", replace it with a "t", and opposite. But I've encountered a problem cause when the program runs, it replaces "a" with "t", then replaces "t" with "a" again.

How can I fix that?

The code:

def opposite_nucleotide(dna):
     dna = dna.replace("a", "t")
     dna = dna.replace("t", "a")
     dna = dna.replace("g", "c")
     dna = dna.replace("c", "g")
     return dna

dna3 = input("Enter the DNA to represent it's oppsite one: ")
dna4 = opposite_nucleotide(dna3)
print(dna4)


from Recent Questions - Stack Overflow https://ift.tt/2ObEJGf
https://ift.tt/eA8V8J

Send data from a check label

Good day, I've the following problem, I'm making a form that I sent the data to a Gmail email, the problem is that when choosing a plan, the page throws an error. The mail arrives without any inconvenience and the selected plan but, the page remains with the error. Here I take the data and organize it to be prepared to be sent to Gmail. I'm using the PHPMailer library

$mail->Body = "<h3>Nombre : $nombre <br>Empresa : $empresa <br>Direccion : $direccion 
    <br>Contacto: $contacto <br>Email: $email <br>Ciudad : $ciudad 
    <br>PlanA : $planA <br>PlanB : $planB <br>PlanC : $planC <br>PlanD : $planD </h3>";

This is the error that marks the page

And This is what I have in the HTML part

When sending them, the error on the page jumps. Is there any way to fix it?



from Recent Questions - Stack Overflow https://ift.tt/3uOzWM2
https://ift.tt/eA8V8J

Using System.Random over multiple data types - the Haskell way?

I'm trying to learn Haskell in the most "Haskell way" possible, so I'm trying to avoid things like dos and lets that sort of obscure what's actually going on.

So I have a data type called Org that in is defined as so:

data Org = Org 
    { pos :: Pos2D
    , color :: Color           
    } deriving (Show)

where Color and Pos2D are defined as so:

-- Not actually defined like this, it's Graphics.Gloss.Data.Color
data Color = Color Float Float Float Float
data Pos2D = Pos2D Float Float

Now I've implemented UniformRange for Pos2D and Uniform for Color as so:

instance UniformRange Pos2D
  where
    uniformRM (Pos2D x1 y1, Pos2D x2 y2) g = Pos2D
        <$> uniformRM (x1, x2) g
        <*> uniformRM (y1, y2) g

instance Uniform Color
  where
    uniformM g = G.makeColor
        <$> uniformRM (0.0, 1.0) g
        <*> uniformRM (0.0, 1.0) g
        <*> uniformRM (0.0, 1.0) g
        <*> return 1.0

Given a tuple of Pos2D (representing the corners of the bounds), it will return a random Pos2D distributed uniformly between those. And for Color, it will return a random color with uniform R, G, and B values, but with a fixed alpha = 255 (1.0).

The question is now, how do I make an org?

randomOrg :: RandomGen g => g -> Org
randomOrg = -- ...
  where
    gen = mkStdGen 1337

The issue I'm having is that uniformR and uniformM take a g and return a tuple of (a, g). So I'm not sure what the cleanest, most "Haskelly" way would be to actually chain these calls together to create the Org.

Any thoughts? Thanks,

Edit:

I know that I can do this:

randomOrg :: RandomGen g => g -> Org
randomOrg g = Org pos color
  where
    (pos, g1) = uniformR (Pos2D 0 0, Pos2D 720 480) g
    (color, g2) = uniform g1

But I'm not a fan of that for obvious reasons.



from Recent Questions - Stack Overflow https://ift.tt/2ZYiVAE
https://ift.tt/eA8V8J

Placing items below category in template

So I wrote a small shopping list application using Django. Users may enter their desired items which are stored in a database alongside a category they reside in to make the list presented to the user more clean and giving them (the users) a good overview of what they are going to buy. The goal is to show the user a list which is categorized, something like this:

VEGETABLES

  • Paprika
  • Tomatoes

VARIOUS

  • Toothpaste
  • Toilet Paper

And so on. I have like five categories saved in my database and users may choose one corresponding category once they add an item to the list below which the item will be displayed in the list.

These are my database models:

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=20)
    tag = models.CharField(max_length=2)

    def __str__(self):
        return self.name

class Item(models.Model):
    text = models.CharField(max_length=40)
    count = models.CharField(max_length=100)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    complete = models.BooleanField(default=False)
    

    def __str__(self):
        return self.text

this is my views.py

def items(request):
    item_list = Item.objects.order_by('id')
    categories = Category.objects.all()
    form = ItemForm()
    context = {'item_list' : item_list, 'form' : form, 'categories' : categories}
    return render(request, 'buyit/index.html', context)

and this is my index.html (very basic, stripped off all the css and html stuff):

        

I got this functions from the Jinja2 template from a code snippet and it might be, that I didn't understand it correctly. However, the debugger tells me:

TemplateSyntaxError at /
Could not parse the remainder: '()' from 'category.item_set.all()'

Any hints on what I am doing wrong? Simply displaying the categories worked fine but after adding

    

things crashed. Any help is highly appreciated!

Thanks in advance!



from Recent Questions - Stack Overflow https://ift.tt/3bIyO3P
https://ift.tt/eA8V8J

MSVC cannot return an object that can be copied but cannot be moved

While fiddling around with copy elision I came across this strange behavior:

class Obj {
 public:
  Obj() = default;

  Obj(Obj&&) = delete;
  Obj(const Obj&) { std::cout << "Copy" << std::endl; }
};

Obj f1() {
  Obj o;
  return o; // error C2280: move constructor is deleted
}

Obj f2() {
  Obj o;
  return Obj(o); // this however works fine
}

int main() {
  Obj p = f1();
  Obj q = f2();

  return 0;
}

GCC and Clang accept this code and are able to use copy elision in both cases.

In f1() MSVC complains that it cannot return o because the move constructor of Obj is deleted. However, I would expect it to be able to fall back on the copy constructor. Is this a bug in MSVC or is this desired behavior (that I don't understand) and GCC / Clang are too permissive?

If I provide a move constructor, MSVC is able to elide the move when compiling as Release.

Interestingly MSVC is able to compile f2(). As far as I understand this is due to the mandatory copy elision when the result of a constructor call is returned. However it feels counter-intuitive that I am only able to return o by-value if I manually copy it.

I know that this situation might not be relevant for practical use since copyable objects usually are also moveable, but I am interested in the underlying mechanics.

Here is the online example for testing: https://godbolt.org/z/sznds7



from Recent Questions - Stack Overflow https://ift.tt/2NKG4Eg
https://ift.tt/eA8V8J

Parsing a function call (e.g. `exp '(' exp ')'`) in Bison: results in shift/reduce errors (precedence issue)

I'm trying to parse a function call (currently just one argument, but I'll allow for several when I get it working).

Suppose exp is defined as

%left '+'
%precedence CALL
exp:
    exp '+' exp { ... }
|   exp '(' exp ')' %prec CALL { ... }
|   LITERAL { ... }
;

This creates an ambiguity. If I use -Wcounterexamples then it says that exp '+' exp · '(' exp ')' could be parsed in 2 ways, either shifting or reducing at the '('.

calc.y: warning: shift/reduce conflict on token '(' [-Wcounterexamples]
  Example: exp '+' exp • '(' exp ')'
  Shift derivation
    exp
    ↳ exp '+' exp
              ↳ exp • '(' exp ')'
  Example: exp '+' exp • '(' exp ')'
  Reduce derivation
    exp
    ↳ exp             '(' exp ')'
      ↳ exp '+' exp •

It appears that it doesn't know that a call should have a precedence that is higher or lower than +. What can I do to make sure that it knows that x+y(z) should be equivalent to x+(y(z)) and not (x+y)(z)?

Bison: strange shift-reduce conflict seems related.



from Recent Questions - Stack Overflow https://ift.tt/2PanSEk
https://ift.tt/eA8V8J

Discord bot crashes when message contain mention

undefined:1
(@!310599774002872330)
 ^

SyntaxError: Invalid or unexpected token

Commands work fine but whenever it involves a mention/ping it crashes the bot and spits out the above error.



from Recent Questions - Stack Overflow https://ift.tt/3b1xk5G
https://ift.tt/eA8V8J

Problem applying Decorator Design Pattern to JavaScript code

I have a class named Calculation which I added two functions are addOperationToName() and sayOperation() as examples of the Decorator design pattern. However, when I test it using Jest, I got an error that 'fn is not a function'. Can someone help me?

Calculation.js

class Calculation {
constructor(a, b, op) {
    this.a = a;
    this.b = b;
    this.op = op;
}

static Create(a, b, op){
    return new Calculation(a, b, op);
}

 GetResults() {
    return this.op(this.a,this.b)
}

addOperationToName(fn){
    return function(name){
        const operation = name + ' is a operation';
        fn(operation);
    }
}

sayOperation(name){
    console.log(name);
}
}
module.exports = Calculation;

Calculation.test.js

const Calculation = require('../src/models/Calculation');

test('Test say name for Product operation', () => {
let op = Product;
let calculation = new Calculation(1,2,op);
let sayTest = calculation.addOperationToName(calculation.sayOperation());
expect(sayTest('Multiply')).toBe('Multiply is an operation');
});


from Recent Questions - Stack Overflow https://ift.tt/2O8DBDi
https://ift.tt/eA8V8J

Discord.py copy and paste channels command

    @commands.command()
    @commands.has_guild_permissions(administrator=True)
    async def copy(self, ctx):
        if str(ctx.author.id) not in Server.server_data:
            Server.server_data[str(ctx.author.id)] = Server.create_new_data()
        if str(ctx.author.id) in Server.server_data:
            Server.server_data[str(ctx.author.id)] = Server.create_new_data()
        
        channels = ctx.guild.text_channels
        Server.server_data[str(ctx.author.id)]["Channels"].append(str(channels))
        embed=discord.Embed(color=discord.Color.blue(), description = f"{ctx.guild.name}'s channels has been saved.")
        await ctx.send(embed=embed)

    @commands.command()
    @commands.has_guild_permissions(administrator=True)
    async def paste(self, ctx):
        embed=discord.Embed(color=discord.Color.blue(), description = "All channels have been pasted")
        channel = Server.server_data[str(ctx.author.id)]["Channels"]
        await ctx.guild.create_text_channel(channel)
        await ctx.send(embed=embed)

So I am trying to make a command for pasting the channels into a empty backup server but when do s!paste it sends an error message, which I tried to fix for a while but nothing is working.

Error <class 'discord.errors.HTTPException'>: 400 Bad Request (error code: 50035): Invalid Form Body
In name: Could not interpret "["[<TextChannel id=814160761068191817 name='general' position=0 nsfw=False news=False category_id=814160761068191815>, <TextChannel id=815038327610146866 name='false' position=1 nsfw=False news=False category_id=None>]"]" as string.
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/runner/Security-Bot/cogs/copy.py", line 28, in paste
    await ctx.guild.create_text_channel(channel)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/guild.py", line 929, in create_text_channel
    data = await self._create_channel(name, overwrites, ChannelType.text, category, reason=reason, **options)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 247, in request
    raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In name: Could not interpret "["[<TextChannel id=814160761068191817 name='general' position=0 nsfw=False news=False category_id=814160761068191815>, <TextChannel id=815038327610146866 name='false' position=1 nsfw=False news=False category_id=None>]"]" as string.


from Recent Questions - Stack Overflow https://ift.tt/3r2lOwi
https://ift.tt/eA8V8J

How can i disable a TaskQueues or TaskRouter from the web

I am using Twilio TaskRouter. And sometimes, i needed a way to stop a queue from functioning. Is there a way to disable a TaskQueues or TaskRouter from the web?



from Recent Questions - Stack Overflow https://ift.tt/2ZYOKcy
https://ift.tt/eA8V8J

npm run dev error (django/react/webpack/babel)

I'm following a code along of a django with react project and have run in to an error(s) that I can't get past. When I run npm run dev I get the error:

ERROR in ./portfolio/frontend/src/index.js 1:0-35
Module not found: Error: Can't resolve './components/App' in '/home/anthony/Desktop/playground/portfolio/portfolio/frontend/src'
resolve './components/App' in '/home/anthony/Desktop/playground/portfolio/portfolio/frontend/src'
  using description file: /home/anthony/Desktop/playground/portfolio/package.json (relative path: ./portfolio/frontend/src)
    using description file: /home/anthony/Desktop/playground/portfolio/package.json (relative path: ./portfolio/frontend/src/components/App)
      no extension
        /home/anthony/Desktop/playground/portfolio/portfolio/frontend/src/components/App doesn't exist
      .js
        /home/anthony/Desktop/playground/portfolio/portfolio/frontend/src/components/App.js doesn't exist
      .json
        /home/anthony/Desktop/playground/portfolio/portfolio/frontend/src/components/App.json doesn't exist
      .wasm
        /home/anthony/Desktop/playground/portfolio/portfolio/frontend/src/components/App.wasm doesn't exist
      as directory
        /home/anthony/Desktop/playground/portfolio/portfolio/frontend/src/components/App doesn't exist

As I understand it, this is because in my index.js I have:

import App from './components/App';

but webpack isn't looking for /App.jsx (note the jsX). After much googling I found that I need to add "resolve" + "extensions" which I now have.

webpack.config.js

module.exports = {
    module: {
        rules: [
            { 
                test: /.(js|jsx)$/, 
                exclude: /node_modules/, 
                resolve: { extensions: [".js", ".jsx"] }, 
                use: { loader: "babel-loader" } 
            }, 
        ] 
    }
}

The same error still comes up. If I change App.jsx to App.js then I get the following error:

ERROR in ./portfolio/frontend/src/components/App.js 7:8
Module parse failed: Unexpected token (7:8)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|     render() {
|         return (
>         <div>hello</div>
|         )
|     }

After much more googling I think this is because HTML is not JS, hence why App.jsx is needed? But then the viscous circle starts all over again... For reference here is my App.jsx:

import React, { Component } from 'react' 
import ReactDOM from 'react-dom'

class App extends Component { 
    render() { 
        return (
            <div>hello</div>    
        )    
    }    
}

ReactDOM.render(<App />, document.getElementById('app'));

.babelrc

{
    "presets": ["@babel/preset-env", "@babel/preset-react"],
    "plugins": ["transform-class-properties"] 
}

package.json

{
  "name": "portfolio",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "webpack --mode development --entry ./portfolio/frontend/src/index.js --output-path ./portfolio/frontend/static/frontend/",
    "build": "webpack --mode production ./portfolio/frontend/src/index.js --output-path ./portfolio/frontend/static/frontend/"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.13.1",
    "@babel/plugin-syntax-import-meta": "^7.10.4",
    "@babel/preset-env": "^7.13.5",
    "@babel/preset-react": "^7.12.13",
    "babel-loader": "^8.2.2",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "webpack": "^5.24.2",
    "webpack-cli": "^4.5.0"
  },
  "dependencies": {
    "babel-preset-es2015": "^6.24.1",
    "prop-types": "^15.7.2",
    "react": "^17.0.1",
    "react-dom": "^17.0.1"
    
  }
}


from Recent Questions - Stack Overflow https://ift.tt/3aXWt10
https://ift.tt/eA8V8J

2021-02-27

Reduce bundle size of lodash

Is this correct to create a file in which I'll put all imports?

// lodash-helper.js
export const isEqual = import('lodash/isEqual');
export const includes = import ('lodash/includes');
export const filter = import ('lodash/filter');

// some-file.component.ts
import { isEqual } from 'src/core/helpers/lodash-helper'; // In this file I need only one import


from Recent Questions - Stack Overflow https://ift.tt/2O93nY0
https://ift.tt/eA8V8J

What's the ideal way to handle SSL Subject Alternative Names in a CAA record?

Suppose I want to request an SSL certificate from "Example CA" with the following domain names on it:

  • Subject Name: foocorp.com
  • Subject Alt Name: www.foocorp.com
  • Subject Alt Name: images.foocorp.com
  • Subject Alt Name: foocorp.net
  • Subject Alt Name: *.foocorp.net
  • Subject Alt Name: foocorp.biz
  • Subject Alt Name: *.foocorp.biz

If I wanted to implement CAA for this certificate, I could see a few ways to construct the DNS records to permit issuance. But it's not immediately clear if each method will work correctly for each domain. Here are the variants I've considered, and my thinking for each.

#1: Only implement the record for the domain listed as the Subject Name. If that's all the CA checks, that's all we need:

foocorp.com.    IN    CAA    0 issue "ca.example.com"

I have a sneaking suspicion that this won't work, and we have to add CAA records to everything listed in the SAN list for the certificate to be issued. If that's indeed the case, I suppose this won't work.

#2: List each domain as wild, and don't worry about any of the subdomains:

foocorp.com.    IN    CAA    0 issuewild "ca.example.com"
foocorp.net.    IN    CAA    0 issuewild "ca.example.com"
foocorp.biz.    IN    CAA    0 issuewild "ca.example.com"

This feels like the simplest approach that could work, although I'm not sure if I would have to re-specify any records using issue to allow issuance to the apex domains.

#3: Meticulously match the CAA records with the structure of the certificate:

foocorp.com.           IN    CAA    0 issue "ca.example.com"
www.foocorp.com.       IN    CAA    0 issue "ca.example.com"
images.foocorp.com.    IN    CAA    0 issue "ca.example.com"
foocorp.net.           IN    CAA    0 issue "ca.example.com"
foocorp.net.           IN    CAA    0 issuewild "ca.example.com"
foocorp.biz.           IN    CAA    0 issue "ca.example.com"
foocorp.biz.           IN    CAA    0 issuewild "ca.example.com"

This seems like a real pain in the butt to manage. As with option #2, it's not clear to me if issue+issuewild is over-specified and we could make do with keeping only one of them.


What's the best way to construct the CAA records for this situation?



from Recent Questions - Stack Overflow https://ift.tt/3dPmG3s
https://ift.tt/eA8V8J

WebdriverIO version 7, using @cucumber/cucumber v7, using junit v7, the count of tests is not updating

Upgraded to Version 7 for WebdriverIO. In the process upgraded the cucumber framework as well to ver 7 "@wdio/cucumber-framework":"^7.0.7",

After upgrading noticed that the test counts are not updating. Unable to use junit reports with Jenkins.

I could only get it to work if I downgraded cucumber from version 7 to 6. Using 6.11.1 and it works fine now.

Anyone facing same issue?

Bit surprising on the official page also - the test counts are showing 0 for examples. tests="0" failures="0" errors="0" skipped="0"

Am I missing something here?

https://webdriver.io/docs/junit-reporter/



from Recent Questions - Stack Overflow https://ift.tt/3kq6kzM
https://ift.tt/eA8V8J

Obtaining eBay OAuth access code after user clicks

So, I am trying to obtain the eBay OAuth access_token into my React app and have gotten stuck because I don't know how to get that back to my app once the access_token comes through.

I have created a page in React with a button meant to display an eBay OAuth link after user clicks.

However, I am doing all this testing from my local machine, namely localhost:3000 (frontend) and localhost:8000 (express backend).

And to bypass the https requirement by ebay (I am using http://localhost:8000 which is a no-no for the eBay redirect url), I am using ngrok to produce links that look like https://8e37hhnc176c.ngrok.io/ which go in the ebay RuName settings.

All is well and good until I have to obtain the access_token because by clicking the link created by clicking that initial button, it opens a new page that I cannot access the localstorage or cookie for. I am at a loss as to how to get this back to my redux React frontend app. I thought about having it write this token to a temp file on the server but I don't like that potential security risk.

How can I return the access_code returned from eBay to my app?

Attempts:

  • Tried res.cookie by returning a view page which ultimately showed me that wouldn't work because it's a new tab that opens and even tho you could put a cookie in, it just cannot be seen by my app :(
  • Tried res.send() with res.cookie but that STILL produces another unrelated tab


from Recent Questions - Stack Overflow https://ift.tt/3aXReOC
https://ift.tt/eA8V8J

How to add cargo (or any executable) to path in Dockerfile for subsequent build steps?

I have the following snippet in my Dockerfile:

RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
RUN USER=root cargo new --bin foobar

The problem is, the 2nd RUN fails because cargo is not in the path.

Is there a way to fix this?

I've tried setting the path like this (inspired by this answer):

ENV PATH $HOME/.cargo/.bin:$PATH

but this doesn't seem to do the trick



from Recent Questions - Stack Overflow https://ift.tt/3sJEH7R
https://ift.tt/eA8V8J

Can not convert from String to LocalDate in java

Hello I here for a DateTimeFormatter problem with the language, let me introduce you:

  • I'm reading a CSV file with this String Format: "dd-MMM-yyyy" <--> "28-dic-2017"
  • Then i have to parse each string from a list to LocalDate to handle each with timeAPI methods.
  • When Executed it returns:

Exception in thread "main" java.time.format.DateTimeParseException: Text '28-dic-2017' could not be parsed at index 3 at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2051) at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1953) at java.base/java.time.LocalDate.parse(LocalDate.java:429) at com.examen.Presentation.Principal.parseDate(Principal.java:28) at com.examen.Presentation.Principal.main(Principal.java:19)

public static LocalDate parseDate(String fecha) {

    Locale loc = new Locale("es", "ES");
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy", loc);
    LocalDate date = LocalDate.parse(fecha, formatter);

    return date;
}

I've got the same error trying different things and methods from locale and DateTimeFormatter don't even know what i was doing, but I think that this should work OBVIOUSLY NOT so please HELP!! Thank You!!



from Recent Questions - Stack Overflow https://ift.tt/3dPGvI0
https://ift.tt/eA8V8J

clang-tidy does not recognize standard libraries

I have a simple program that compiles and runs successfully, but I can't get clang-tidy to work.

My program:

#include <iostream>

int main() {
    return 0;
}

CMakeLists.txt:

cmake_minimum_required(VERSION 3.1)
project(myProg CXX)
set(CMAKE_CXX_COMPILER "/usr/bin/clang++")
set(CMAKE_CXX_STANDARD 14)
add_executable(myProg test.cpp)

I produce a compile_commands.json using -DCMAKE_EXPORT_COMPILE_COMMANDS=ON to be used with clang-tidy:

[
{
  "directory": "/Users/me/myProj/build",
  "command": "/usr/bin/clang++ -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX11.1.sdk -mmacosx-version-min=10.15 -o CMakeFiles/myProg.dir/test.cpp.o -c /Users/me/myProj/test.cpp",
  "file": "/Users/me/myProj/test.cpp"
}
]

This compiles and runs successfully.

Now, when I run clang-tidy -p=/Users/me/myProj/build /Users/me/myProj/test.cpp, I get this:

test.cpp:1:10: error: 'iostream' file not found [clang-diagnostic-error]

When writing this question, I realized that when I add the following line to the compile_commands.json, clang-tidy can successfully find iostream:

-I/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1

Also, when I don't specify the compiler in my cmake file and I use the default compiler in /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++, clang-tidy runs with no error.



from Recent Questions - Stack Overflow https://ift.tt/3svRgmT
https://ift.tt/eA8V8J

Assignment of an array in node.js to process.env variable results in String

When I assign an array variable to say process.env.deviceData, it changes to String.

Example:

$ node
Welcome to Node.js v14.15.5.
Type ".help" for more information.
> result=['1','2','3']
[ '1', '2', '3' ]
> process.env.deviceData=result
[ '1', '2', '3' ]
> console.log(process.env.deviceData)
1,2,3
undefined
> console.log(result)
[ '1', '2', '3' ]
undefined
> typeof process.env.deviceData
'string'
> typeof result
'object'

Is above expected? If yes, how can I assign array variable to process.env.deviceData?



from Recent Questions - Stack Overflow https://ift.tt/3sA914m
https://ift.tt/eA8V8J

MIPS Swapping Operation

Say I have an array with 10 elements and assume the $s1 register is already loaded with the base address. How would I write a simple operation that will swap A[4] and A[9]? So far i've come up with something which consists of using a temp register, but i'm not sure if its correct:

lw $t0, 4($s1) 
sw 4($s1), 9($s1)
sw 9($s1), $t0


from Recent Questions - Stack Overflow https://ift.tt/3ktjdcr
https://ift.tt/eA8V8J

How to take fs.createWriteStream and upload it to Gapi google drive api create function?

I have a chrome extension that takes file information from a backend node.js server in order to serve google drive files up within the extension. What I am having trouble with in this specific instance is uploading a file saved on the backend to a gapi client on the front end that allows a user to upload it to their google drive. The authentication and everything is fine, the main problem is the upload.

Here is my code.

background.js(client side):

  var parentFolder;
  var fileArray;
  let classroomUrl = 'https://connect.smartpathed.com/getclassroomparent';
  await fetch(classroomUrl)
  .then(response => response.text())
  .then(data => parentFolder = data)
  .then(data => console.log(parentFolder));
  let fileArrayUrl = "https://connect.smartpathed.com/getclassroomarrayselect";
  await fetch(fileArrayUrl)
  .then(response => response.json())
  .then(data => fileArray = data)
  .then(data => console.log(fileArray));
  function sleep(milliseconds) {
    const date = Date.now();
    let currentDate = null;
    do {
      currentDate = Date.now();
    } while (currentDate - date < milliseconds);
  }
  gapi.client.init({
    apiKey: API_KEY,
    discoveryDocs: DISCOVERY_DOCS,
  }).then(function() {
    chrome.identity.getAuthToken({interactive: true}, async function(token) {
      gapi.auth.setToken({
        'access_token': token,
      });
      for(var i = 0; i < fileArray.length; i++) {
      if (fileArray[i].type != "folder") {
      const fileNameFile = fileArray[i].name;
      const typeFile = fileArray[i].type;
      const descriptionFile = fileArray[i].description;
      let newType = ''
      if(typeFile === 'docx') {
        newType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
      }
      if(typeFile === 'pptx') {
        newType = 'application/vnd.google-apps.presentation'
      }
      if(typeFile === 'xlsx') {
        newType = 'application/vnd.google-apps.spreadsheet'
      }
      if(typeFile === 'pdf') {
        newType = 'application/pdf'
      }
      var destFile = './src/Pages/downloads/' + fileNameFile + '.' + typeFile;
      var newId = ''
      var fileMetadata = {
        'name': fileNameFile,
        'description': descriptionFile,
        'parents': [parentFolder]
      };
      console.log(fileMetadata)
      var media;
      await fetch('https://connect.smartpathed.com/makefile', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({
          newType: newType,
          fileDest: destFile,
        })
      })
      .then(() => {
        alert('next step activated')
        fetch('https://connect.smartpathed.com/getfile')
        .then(res => res.json)
        .then(data => media = data)
        .then(data => console.log("this is the body of topfile: " + data))
        }) 
      gapi.client.drive.files.create({
        resource: fileMetadata,
        media: media,
        fields: 'id'
      })
      .then(function (err, file) {
        if (err) {
          console.log("Error for file creation: " + JSON.stringify(err));
          console.log(media);
        } else {
          console.log("file download complete." + file);
          newId = file.id;
        } 
      })
    }

Post requests(Node.js back end):

  app.post('/makefile', (req, res) => {
  const newType = req.body.newType;
  console.log("this is the file type in post request: " + newType);
  const dest = req.body.fileDest;
  console.log("this is the file destination: " + dest);

  var media = {
    mimeType: newType,
    body: fs.createReadStream(dest),
  };

  app.set("media", media);

})

app.get("/getfile", (req, res) => {
  const file = req.app.get('media');
  console.log(file);
  res.send(file);
})

All of this code works fine until it comes to the media request, and the subsequent file creation through drive.files.create. I know that the fs.createReadStream works on the back end, and that the information transfers over, because I am able to see it in the log. I don't, however, know if it is even possible to transfer an fs.createReadStream body to the client side, and be able to use it in the media request in the google.drive.create function. It could just not be possible due to pathing issues.

With that said, is there any way to achieve what I am trying to achieve here, that being the transfer of the media var to the client side to allow the body of the file saved on the backend to be uploaded through gapi?

Glad to clarify if this needs more context.



from Recent Questions - Stack Overflow https://ift.tt/3q3oeJz
https://ift.tt/eA8V8J

Float Property does not work after applied to the html file?

I am trying to make the navigation menu a left vertical menu. But instead of becoming a vertical menu, it look like this: https://i.stack.imgur.com/7J4tS.png[1]. The selector is linked to the right id and tag in the HTML file.

Below I have attached the css file. What may the potential issue that cause the float property no working properly on my page.

CSS File:

* {

    margin:0;
}

body {

    text-align: center;
    background-color: #f4e1d2;  /*change the the background color of the entire page*/
    font-family: papyrus, copperplate, serif;
}
#nav {   /*navigation menu*/

    background-color: #f18973;
    height: 80px;
    /*display:flex;
    align-items: center;*/

}
header {
    padding: 2.5%; 
    text-align: center;
    background-color:#bc5a45;
}

h1 {

    margin-bottom: 3%;
    margin-top: 5%;
    color: #bc5a45;
    font-size: calc(2px + 2vw);
}

h2 {

    margin-top: 3%;
    margin-bottom: 1%;
    color: #bc5a45;
    font-size: calc(5px + 1vw);
    
}

h3 {

    color: #bc5a45; 
    font-size: calc(1px + 1vw);
}

#nav li {
   
    padding-left: 25px;
    
    color: white;
   
}


ul { 
    
    font-size: calc(1px + 1vw);
    
   
}
ol {

    width: 15%;
    margin: auto;
    color: #f18973
}

p {

   color: #f18973; 
   width: 60%;
   margin: auto;
   font-size: calc(1px + 1vw);

}

video { 
   
    margin: 1%;
}

img {
    margin: 1%;
}



footer {

    background-color: #b2b2b2;
    clear: both;
}

header h1 {
    color: white;
    letter-spacing:5px;
    font-size:calc(10px + 2vw);
    margin-bottom: 10px;
}

header p {

    margin-top: 10px;
    color:white;
    
    
}

a:link {

    color: white;
}

#page-wrapper {  /*wrap the entire body tag*/

    float:left;
    width:100%;
    box-sizing:border-box;
}


#main-content { /*wrap the main content*/

    width:75%;
    float:left;
    box-sizing:border-box;
}



#nav {

  float:left;
  width: 25%;
  box-sizing: border-box;  
}


from Recent Questions - Stack Overflow https://ift.tt/2MsS907
https://ift.tt/eA8V8J

How to search value in Dataset

My Dataset< Row > (java spark) input is :

Heros Powers Rank
Superman Invisible 1
Batman Strength 2
SpiderMan Strong 3

By knowing the name of my heros, i would like to retrieve the rank. For exemple for Superman, i would like to have the return 1, not all the line but just the value. I don't know how to do by using a spark dataset. Thank for your help !



from Recent Questions - Stack Overflow https://ift.tt/3dRPSqv
https://ift.tt/eA8V8J

Slicing and performance

It might be that I don't understand slicing that well. I want to add one list from a particular index to another list. I was wondering, because I read that if you slice a list that you make a (deep)copy of it, which method is faster:

method 1

new_lst += old_lst[i:]

method 2

while i < len(old_lst):
    new_list.append(old_lst[i])
    i += 1


from Recent Questions - Stack Overflow https://ift.tt/3bNm0cx
https://ift.tt/eA8V8J

Getting class atributte in method in python

I have this class and method:

class Person(object):            
    def __init__(self, name):
          self.name = personname
          self.surname = personsurname
    def changenameorsurname(self, x, y):
         self.x = y
         return
AdamSmith = Person ("Adam", "Smith")

I want to use method changenameorsurname to change AdamSmith's name or surname but if I use this code I'm getting name error.

AdamSmith.changenameorsurname(personname, Dave)

Name Error: name personname is not defined.

Is there elegant way to reference personname in code like this? Or do I have to make two separate methods like this:

def changename(self,  y):
             self.name = y
             return
AdamSmith.changename(Dave)


from Recent Questions - Stack Overflow https://ift.tt/3aYfkZV
https://ift.tt/eA8V8J

How to change an object attribute inside of a setTimeOut call [duplicate]

I'm creating a "simulation" as a practicing using HTML, CSS and Javascript objects. It's a simulation of testing a smartphone

class smartphone {
  constructor(name, color, weight, screenResolution, camResolution, ram) {
    this.name = name;
    this.color = color;
    this.weight = weight;
    this.screenResolution = screenResolution;
    this.camResolution = camResolution;
    this.ram = ram;
    this.on = false;
  }

And I'm creating a method which "simulates" the startup of a smartphone:

turnOn(){
    if (this.on == false){
      document.getElementById("status").innerHTML = "Turning on...";
      document.getElementById("status").classList.remove("off")
      document.getElementById("status").classList.add("on")
      setTimeout(function(){
        this.on = true; //Line 26
        alert(`${this.name} is on.`) //Line 27
        document.getElementById("img").src = "xperia.png";
        document.getElementById("status").innerHTML = "ON";
    }
      , 3000); // Here I indicate the time (ms) which gonna pass before the code above starts. this is to simulate the time a smartphone takes to turn on 
    }else {
      alert(`${this.name} it's already on.`);
    }
  }

But I got an error when executing line 26 and line 27... First, a console error appears when executing this.on = true; "this.on" it's not defined. And when executing line 27 I got an alert which says undefined is on. I suppose that I get those errors because the function can't access to the object attributes. Is this right? If it is right, what can I do so the function can access to object attributes and redefine them?



from Recent Questions - Stack Overflow https://ift.tt/3bGPYyE
https://ift.tt/eA8V8J

why command are not recognized by the command prompt?

I have tried several times to type the command 'ls' at the command prompt of Windows 10 but it shows me that the command is not recognized as an internal or external command, an executable program or a batch file.



from Recent Questions - Stack Overflow https://ift.tt/3su1unO
https://ift.tt/eA8V8J

How to upload large file (~100mb) to Azure blob storage using Python SDK?

I am using the latest Azure Storage SDK (azure-storage-blob-12.7.1). It works fine for smaller files but throwing exceptions for larger files > 30MB.

azure.core.exceptions.ServiceResponseError: ('Connection aborted.', timeout('The write operation timed out'))

from azure.storage.blob import BlobServiceClient, PublicAccess, BlobProperties,ContainerClient

    def upload(file):
        settings = read_settings()
        connection_string = settings['connection_string']
        container_client = ContainerClient.from_connection_string(connection_string,'backup')
        blob_client = container_client.get_blob_client(file)
        with open(file,"rb") as data:
            blob_client.upload_blob(data)
            print(f'{file} uploaded to blob storage')
    
    upload('crashes.csv')


from Recent Questions - Stack Overflow https://ift.tt/37PUuK2
https://ift.tt/eA8V8J

lm formula: the difference between `as.factor()` and `as.as.character()`

I was wondering why factor(gpid) doesn't work like as.character(gpid) in my manova() call below?

data <- read.csv("https://raw.githubusercontent.com/rnorouzian/v/main/df.csv")

#   gpid anx socskls assert
#1     1   5       3      3
#2     1   5       4      3
#3     1   4       5      4

summary(manova(cbind(anx,socskls,assert) ~ factor(gpid), data = data))

#          Df   Pillai approx F num Df den Df Pr(>F)
#gpid       1 0.073734   0.7695      3     29 0.5205

But when I change gpid to character the output is what it should be:

summary(manova(cbind(anx,socskls,assert) ~ as.character(gpid), data = data))

#                    Df  Pillai approx F num Df den Df   Pr(>F)   
# as.character(gpid)  2 0.62209   4.3642      6     58 0.001058 **


from Recent Questions - Stack Overflow https://ift.tt/3b2X8hP
https://ift.tt/eA8V8J

Applying .get() function On a Pandas series

I am working on sample dataset to retrieve location information from address(some details are changed for identification purpose);

temp2=pd.DataFrame({'USER_ID':[1268,12345,4204,4208], 'IP_ADDR':['142.176.00.83','24.000.63.230','187.178.252.99','187.178.250.99']})

My goal is to get Lattitude and longitude information using the ip2geotools python package. The syntax is follows;

!pip install ip2geotools
response = DbIpCity.get(a, api_key='free')
json_file = response.to_json()

where a='142.176.00.83'. Then we get a JSON file like this;

'{"ip_address": "142.176.00.83", "city": "Charlotte", "region": "Prince Edward", "country": "CA", "latitude": 46.2, "longitude": -63.131}'

I am trying to apply the function on an entire pandas series (vectored form) and retrieve latitude and longitude as two different columns. Here is my attempt:

temp2['y'] = temp2['IP_ADDR'].apply(lambda x: DbIpCity.get(x, api_key='free'))

But it seems it doesn't like this syntax, InvalidRequestError: . Can I kindly get some help on how to vectorize this operation and retrieve fields from JSON file. thanks



from Recent Questions - Stack Overflow https://ift.tt/2MuYicn
https://ift.tt/eA8V8J

StatusCode 400 Bad Request in Entity Framework

I have this function for returning a list of decks in my DeckController that sends a request to my GetDecks function in my DeckDataController that works as expected. However when I try adding other methods I get a status code 400 bad request.

    //DeckController.cs
    // GET: Deck/List
    /// <summary>
    /// Get a list of all Decks
    /// </summary>
    /// <returns>returns a list of Decks</returns>
    public ActionResult List()
    {
        // api string
        string url = "DeckData/GetDecks";
        
        //http request to the url
        HttpResponseMessage response = client.GetAsync(url).Result;
        Debug.WriteLine(response);

        if (response.IsSuccessStatusCode)
        {                    
            IEnumerable<DeckDto> Decks = response.Content.ReadAsAsync<IEnumerable<DeckDto>>().Result;    
            return View(Decks);
        }
        else
        {
            return RedirectToAction("Error");
        }
    }


    //DeckDataController.cs
    /// Get a list of decks in the database alongside ok code (200)
    /// </summary>
    /// <returns>A list of decks</returns>
    /// GET: api/DeckData/GetDecks
    [HttpGet]
    [ResponseType(typeof(IEnumerable<DeckDto>))]
    public IHttpActionResult GetDecks()
    {
        // get the list of decks from the database
        List<Deck> Decks = db.Decks.ToList();

        // create an empty Deck data transfer object
        List<DeckDto> DeckDtos = new List<DeckDto> { };
        Debug.WriteLine("In GetDecks");


        // for each deck create a new DeckDto and push it to the list of DeckDtos.
        foreach (var deck in Decks)
        {
            DeckDto newDeck = new DeckDto
            {
                DeckID = deck.DeckID,
                DeckTitle = deck.DeckTitle
            };

            DeckDtos.Add(newDeck);

        }

        return Ok(DeckDtos);
    }

For example, adding the following function to my DeckDataController breaks my server.

    // DeckDataController.cs
    /// <summary>
    /// Finds a deck based on the deckID
    /// </summary>
    /// <param name="id">DeckID</param>
    /// <returns>returns a DeckDto object if found, otherwise NotFound object</returns>
    [HttpGet]
    [ResponseType(typeof(DeckDto))]
    public IHttpActionResult FindDeck(int id)
    {

        // find the deck in the database
        Deck deck = db.Decks.Find(id);

        // if deck isnt found
        if (deck == null)
        {
            return NotFound();
        }

        // create a data transfer object to send back
        DeckDto DeckDto = new DeckDto
        {
            DeckID = deck.DeckID,
            DeckTitle = deck.DeckTitle
        };
        return Ok(DeckDto);
    }

but if I comment out the above function everything seems to be work fine.



from Recent Questions - Stack Overflow https://ift.tt/3sxqYAU
https://ift.tt/eA8V8J

Removing elements from an array of records containing string fields?

Check the example below... I have an array TSrvClientList.Items with record elements. These elements have string fields. When I remove an element, I need to move the following ones in that empty space left. I don't like to copy field by field... And I thought I'd use the Move function to do it faster, but I'm not sure if this is a proper way to do it. If the record contained only unmanaged types, I'm sure it's OK, I uesed many times. But with those strings, I don't know... Should I call a Finalize first ? Or do it differently ? My test code seems it works as it is, directly moving those strings, but I'd like to make sure it's not just a coincidence.

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
  Vcl.Graphics,  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, SynCommons, System.SyncObjs,
  Vcl.StdCtrls;

type
  TSrvClientInfo = record
   ClientIP: String;
   ClientGUID: Cardinal;
   AESKey: THash256;
   TransCons: Integer;
  end;

  TSrvClientList = record
   private
    Valid: DWord;
   public
    Items: array of TSrvClientInfo;
    procedure Init;
    procedure Free;
    procedure AddClient(const IP: String; GUID: Cardinal; AESKey: THash256);
    procedure RemoveClient(const IP: String; GUID: Cardinal);
  end;

  TForm1 = class(TForm)
    BAddItem: TButton;
    BRemoveItem: TButton;
    procedure FormCreate(Sender: TObject);
    procedure BAddItemClick(Sender: TObject);
    procedure BRemoveItemClick(Sender: TObject);
  public
    Code: Byte;
    Clients: TSrvClientList;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

//===== TSrvClientList =======================================================

procedure TSrvClientList.Init;
begin
 if Valid <> $12344321 then begin
  Valid:= $12344321;
  SetLength(Items, 0);
 end;
end;

procedure TSrvClientList.Free;
begin
 if Valid = $12344321 then begin
  SetLength(Items, 0);
  Valid:= 0;
 end;
end;

procedure TSrvClientList.AddClient(const IP: String; GUID: Cardinal; AESKey: THash256);
var I: Integer;
begin
 if Valid <> $12344321 then Exit;
 I:= Length(Items); SetLength(Items, I+1);
 Items[I].ClientIP:= IP;
 Items[I].ClientGUID:= GUID;
 Items[I].AESKey:= AESKey;
 Items[I].TransCons:= 0;
end;

procedure TSrvClientList.RemoveClient(const IP: String; GUID: Cardinal);
var I, R: Integer;
begin
 if Valid <> $12344321 then Exit;
 I:= 0; while (I < Length(Items)) and ((Items[I].ClientIP <> IP) or (Items[I].ClientGUID <> GUID)) do Inc(I);
 if (I > High(Items)) then Exit;
 R:= High(Items) - I;
 if R > 0 then Move(Items[I+1], Items[I], SizeOf(TSrvClientInfo) * R);
 SetLength(Items, Length(Items)-1);
end;

// ----------------------------------------------------

procedure TForm1.FormCreate(Sender: TObject);
begin
 Clients.Init;
 Code:= 1;
end;

procedure TForm1.BAddItemClick(Sender: TObject);
var IP: String;
    GUID: Cardinal;
    AESKey: THash256;
begin
 IP:= '192.168.0.3';
 GUID:= $12345678;
 FillChar(AESKey[0], 32, 0); AESKey[0]:= Code; Inc(Code);
 Clients.AddClient(IP, GUID, AESKey);
 Caption:= IntToStr(Length(Clients.Items));
end;

procedure TForm1.BRemoveItemClick(Sender: TObject);
var IP: String;
    GUID: Cardinal;
begin
 IP:= '192.168.0.3';
 GUID:= $12345678;
 Clients.RemoveClient(IP, GUID);
 Caption:= IntToStr(Length(Clients.Items));
end;

end.


from Recent Questions - Stack Overflow https://ift.tt/2ZWS1ZS
https://ift.tt/eA8V8J

Flutter Geolocator 5.0.1 not working properly

I'm having a problem with the flutter geolocator: ^5.0.1 dependencies. Bt it doesn't show the location also not showing any error. I have given permission in the manifest file also.

I'm using flutter stable version 1.22.6 and for this project compile SDK version is 29.

Manifest file:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />`

Flutter Code for getting location:

                  String specificAddress;
                  try {
                    Position position = await Geolocator()
                        .getCurrentPosition(
                            desiredAccuracy: LocationAccuracy.best);
                    List<Placemark> placeMarks = await Geolocator()
                        .placemarkFromCoordinates(
                            position.latitude, position.longitude);
                    Placemark mPlaceMark = placeMarks[0];

                    // String completeAddressInfo =
                    //     "${mPlaceMark.subThoroughfare} ${mPlaceMark.thoroughfare}, " +
                    //         "${mPlaceMark.subLocality} ${mPlaceMark.locality}, " +
                    //         "${mPlaceMark.subAdministrativeArea} ${mPlaceMark.administrativeArea}, " +
                    //         "${mPlaceMark.postalCode} ${mPlaceMark.country}, ";

                    specificAddress =
                        "${mPlaceMark.subLocality}, ${mPlaceMark.locality}, ${mPlaceMark.country}";

                    locationTextEditingController.text = specificAddress;
                    setState(() {
                      _location = specificAddress;
                    });
                  } catch (e) {
                    _showSnackbar(e.toString());
                  }`

Error > when I press the "get my location button" it shows nothing....

enter image description here

What can I try to resolve this?



from Recent Questions - Stack Overflow https://ift.tt/3bEh1KY
https://ift.tt/3qRn5Gp

trying to create a Discord webhook, with the avatar and username assigned inside the code

I am trying to create a Discord webhook, with the avatar and username assigned inside the code.

This is the code I have so far. I have no idea what comes before or after this.

{
  "username": "Webhook",
  "avatar_url": "https://i.imgur.com/4M34hi2.png",
  "content": "Text message. Up to 2000 characters.",
}


from Recent Questions - Stack Overflow https://ift.tt/3sxBY1a
https://ift.tt/eA8V8J

2021-02-26

How to center quantity and make buttons even - collection feature - shopify

Can anybody help me with the CSS that I need to center the quantity in my collection feature in Shopify? Also the shop buttons are kinda uneven. Does anybody know how to bring them in the same line? Here's an image:

enter image description here



from Recent Questions - Stack Overflow https://ift.tt/3bGHtn7
https://ift.tt/eA8V8J

Calculate average across all the branches for that day

I am currently struggling on how to calculate average across all the branches.

Like below you can see, call queue name is the unique name that has a call count for each day, multiple times a day.

I want to calculate the average call count across all the call queue names for each day to compare individual call name across the average of all the call queue names.

I am struggling for quite sometime and I was able to use averagex,

Per_day_count = AVERAGEX(VALUES(fAgentTimelineAnalytics[Call Queue Name]), 
CALCULATE(COUNT(fAgentTimelineAnalytics[Call Count])))  

Can someone please point me in the right direction.

enter image description here



from Recent Questions - Stack Overflow https://ift.tt/2MuPT8O
https://ift.tt/3dNQqxG

How can I modify my db for a Logistic regression in R?

I have the following fields in my database:

  • record: row number
  • Father: (1 to 7 values)
  • Mother: (1 to 7 values)
  • Age: 13, 14, 15 and 16 yo.
  • Gender: Male/Female
  • Suicide: (1/0 values)

I'd like to create a ggplot from this logistic regression model where my response variable is Suicide vs Parent's education (Father & Mother) The plot has a straight line and not a curve as I expect, I'm using this code:

ggplot( baseRL, aes(x=Father, y=Suicide)) +
  geom_point() +
  geom_smooth(data = baseRL, aes(x = Father, y = Suicide),
              method = "glm", method.args = list(family = "binomial"), 
              se = FALSE)

Is there another way to plot my objective? Thanks!



from Recent Questions - Stack Overflow https://ift.tt/3qQDcE9
https://ift.tt/eA8V8J

Passing data to the keras model.fit() function more effficiently

I am training an LSTM wich on a time series. The input sequence has length 480, and I create my trainingsdata from a bigger timeseries array, where all the values are in the right order. I take blocks of length 480, starting at every possible position in the array and fill the container that will be passed to the model.fit() function with these blocks. But this is of course very inefficient as I need huge amounts of memory to train my model as the first sample contains values [0, 1, 2, ... , 479] and the second one values [1, 2, 3, ... , 480] and so on... When training im not able to fit all this (redundant) data into my RAM at once. Is there any way to solve this by using e.g. some kind of array that references the corresponding parts in the bigger timeseries array? Thanks for any help!



from Recent Questions - Stack Overflow https://ift.tt/3r03u78
https://ift.tt/eA8V8J

Health probe says the endpoints (Azure Container Instances) are degraded

I have set up a health probe to ping Azure Containers from my load balancer so that requests are forwarded to only healthy nodes. However, I am getting "Degraded" status despite the containers being up and running. I am aware this has got to do with the reponse the health probe gets from the IP Address but I cannot figure out what changes do I need to make to my container settings to ensure that it works as expected



from Recent Questions - Stack Overflow https://ift.tt/3kr48YU
https://ift.tt/eA8V8J

Decimal tryparse doesn't parse decimal value

decimal.TryParse(".0005e+92", System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out decimal x)

This returns false. What should I change?



from Recent Questions - Stack Overflow https://ift.tt/37MxtHU
https://ift.tt/eA8V8J

Create proportion of responses across columns

Hello lovely folks of stack overflow:

i am a beginner in R and at the moment i'm trying to create a proportion for each participant in my study of how many close friends they have who are different from them over their total number of friends.

My data from qualtrics is arranged so that participants were able to categorize up to 20 friends as "same" or "different", these responses are arranged in columns from Q34_1_44 to Q34_20_63. Of course not every participant had/rated the whole available 20 close friends, so many columns are almost all empty. Regardless i am trying to create another column that contains a numerical value that is equal to number of different friends/total (so blanks don't matter). i have tried the following (but got stuck as i realized this wasn't an appropriate function (or at least as far as i know):

    dataset.clean2 <- mutate(dataset.clean1, diff.friend=ifelse(Q34_1_44=="Different race",))

if anyone knows an easy to understand (no matter how tedious) way to find each participant's percentage of different friends your answers would be highly appreciated!

Thanks you so much in advance <3



from Recent Questions - Stack Overflow https://ift.tt/2Mq18zc
https://ift.tt/eA8V8J

New column in pandas df based on array

Say I have a df like the one below.

    num value
0   1   229
1   2   203
2   3   244
3   4   243
4   5   230

And an array: array([ 2, 4]).

I would like to create a new column for binary variable, such that it is 1 when num is equal to the value in the array and 0 otherwise.

    num value binary
0   1   229   0
1   2   203   1
2   3   244   0
3   4   243   1
4   5   230   0

Wanted to use: df["binary"] = np.where(df["num"] == dtemp.num.unique(), 1, 0), where dtemp.num.unique() is the aforementioned array. But since the lengths of df and array are different - I get the "Lengths must match to compare" error.



from Recent Questions - Stack Overflow https://ift.tt/3syheX3
https://ift.tt/eA8V8J

Ion.RangeSlider. Problem with parsing a value

I have JS-Range Slider. I need to get min and max values from input, but I get an error in console when I I move the slider: The specified value "1000;2327" cannot be parsed, or is out of range." and etc

<input type="number" class="js-range-slider" name="my_range" value="" data-min="100" data-max="4000" data-from="1000" data-to="2000" data-grid="true" />

Why is it happening?

$(".js-range-slider").ionRangeSlider({
    type: "double",
    prefix: '$',
    min: 100,
    max: 4000,
    from: 1000,
    to: 2000,
    values: [75, 300000]
});



$(".filter-btn_send").click(function () {
    var min = $(".js-range-slider").slider("option", "min");
    var max = $(".js-range-slider").slider("option", "max");

    console.log("min: " + min + " max: " + max);
});

enter image description here

enter image description here



from Recent Questions - Stack Overflow https://ift.tt/3aSAfxc
https://ift.tt/3syhdlX

How to suppress KeyError in Python when dataframe is empty when mapping multiple Foursquare results and an API result is blank

I'm retrieving Foursquare venue data and plotting it on a Folium map. I'm plotting several API call results on the same map.

When the API returns an empty JSON result because there are no queried venues within the search, it throws a KeyError because the code is referencing columns in the dataframe that doesn't exist, because the API result is blank.

I want to continue to display the map with other results, and have the code ignore or suppress instances where the API result is blank.

I've tried try/except/if to test if the dataframe is blank, though cannot figure out how to "ignore the blanks and skip to the next API result".

Any advice would be appreciated.

## Foursquare Query 11 - name origin location
address = 'Convent Station, NJ' ## Try "Madison, NJ" for working location example
geolocator = Nominatim(user_agent="foursquare_agent")
location = geolocator.geocode(address)
latitude = location.latitude
longitude = location.longitude

## name search parameters
search_query = 'Pharmacy'
radius = 1200

## define corresponding URL
url = 'https://api.foursquare.com/v2/venues/search?client_id={}&client_secret={}&ll={},{}&oauth_token={}&v={}&query={}&radius={}&limit={}'.format(CLIENT_ID, CLIENT_SECRET, latitude, longitude,ACCESS_TOKEN, VERSION, search_query, radius, LIMIT)
results = requests.get(url).json()

## Convert to pandas dataframe
# assign relevant part of JSON to venues
venues = results['response']['venues']
venues
# tranform venues into a dataframe
dataframe = json_normalize(venues)

## Filter results to only areas of interest
# keep only columns that include venue name, and anything that is associated with location
filtered_columns = ['name', 'categories'] + [col for col in dataframe.columns if col.startswith('location.')] + ['id']
dataframe_filtered = dataframe.loc[:, filtered_columns]

# function that extracts the category of the venue
def get_category_type(row):
  try:
        categories_list = row['categories']
  except:
        categories_list = row['venue.categories']
        
  if len(categories_list) == 0:
        return None
  else:
        return categories_list[0]['name']

# filter the category for each row
dataframe_filtered['categories'] = dataframe_filtered.apply(get_category_type, axis=1)

# clean column names by keeping only last term
dataframe_filtered.columns = [column.split('.')[-1] for column in dataframe_filtered.columns]

## Visualize the data
dataframe_filtered.name

    # add the query 11 pharmacies as blue circle markers
for name, lat, lng, label in zip(dataframe_filtered.name, dataframe_filtered.lat, dataframe_filtered.lng, dataframe_filtered.name+" - "+dataframe_filtered.city+", "+dataframe_filtered.state):
  folium.CircleMarker(
        [lat, lng],
        radius=5,
        color='blue',
        popup= label,
        fill = True,
        fill_color='blue',
        fill_opacity=0.6
    ).add_to(venues_map)

    ###
    ###
    ###

 
# display map
print('Location loaded, search parameters defined, url generated, results saved & converted to dataframe, map generated!')
venues_map

Error when API result is blank (there are no Foursquare results in the search radius)

/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:21: FutureWarning:

pandas.io.json.json_normalize is deprecated, use pandas.json_normalize instead

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-57-2deac5f680d4> in <module>()
     24 # keep only columns that include venue name, and anything that is associated with location
     25 filtered_columns = ['name', 'categories'] + [col for col in dataframe.columns if col.startswith('location.')] + ['id']
---> 26 dataframe_filtered = dataframe.loc[:, filtered_columns]
     27 
     28 # function that extracts the category of the venue

6 frames
/usr/local/lib/python3.7/dist-packages/pandas/core/indexing.py in _validate_read_indexer(self, key, indexer, axis, raise_missing)
   1296             if missing == len(indexer):
   1297                 axis_name = self.obj._get_axis_name(axis)
-> 1298                 raise KeyError(f"None of [{key}] are in the [{axis_name}]")
   1299 
   1300             # We (temporarily) allow for some missing keys with .loc, except in

KeyError: "None of [Index(['name', 'categories', 'id'], dtype='object')] are in the [columns]"


from Recent Questions - Stack Overflow https://ift.tt/3qZYH5m
https://ift.tt/eA8V8J