Tuesday, July 6, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


ajax post list of objects contains file to asp.net controller not working

Posted: 06 Jul 2021 08:08 AM PDT

iam working on asp.net core , i want send list objects that contains file from ajax request to controller

here is more details: in this image the object i want to send it include file enter image description here

ViewModel

 public class FormDataVM      {          public Guid FormTemplateId { get; set; }          public int FieldTemplateId { get; set; }          public string Value { get; set; }      }  

The Controller

[HttpPost]          public async Task<JsonResult> SubmitForm(List<FormDataVM> formData , IFormFile file)          {              if (ModelState.IsValid)              {                  var uploads = Path.Combine(_hostingEnvironment.WebRootPath, "images");                    if (file != null && file.Length > 0)                  {                      var fileName = Guid.NewGuid().ToString().Replace("-", "") +                                      Path.GetExtension(file.FileName);                      using (var s = new FileStream(Path.Combine(uploads, fileName),                                                                  FileMode.Create))                      {                          await file.CopyToAsync(s);                        }  // to be continued                  }                  return Json(new { status = "success", message = "success" });              }              return Json(new { status = "failed", message = "failed" });          }  

The ajax request : which the data is the object that printed in console

function SubmitForm(data) {              $.ajax({                  type: "POST",                  url: "@Url.Action("SubmitForm", "Form")",                  data: data,                  contentType: false,                  processData: false,                  success: function (message) {                      alert(message);                  },                  error: function () {                      alert("there was error uploading files!");                  }              });          }  

when i send the request the list in action always count is 0 and file is null , so how to fix this issue.

react className conditional setting according to all of state

Posted: 06 Jul 2021 08:08 AM PDT

I currently making a vocabulary website and got state from mysql, and the state is like this.

1: memorize : 0  2: memorize : 0  3: memorize : 0  4: memorize : 0  5: memorize : 1  6: memorize : 0  

So if I check the checkbox on the list of website, each state turns to 1. and 0 means not checked. every time check the box, it changes the value of state(from0 to 1)

and what I want to make is the button(finish) that active&disable. If all of the state turn in to 1, I want to make this finish button active. So I decided to make 2 className, active, notActive, however it is really hard to make the condition.

How to use "If" structure to examine all state? I have tried using State.map, but this only works when examine each state, not whole.

in conclusion, I want to make

  useEffect(() =>{if( all of the state === 1){ buttonClassName = active}}  

could you tell me how to embody"all of the state" ?

UICollectionView nested in a UIScrollView loads all cells at once

Posted: 06 Jul 2021 08:08 AM PDT

I have a few very long collectionViews, all nested inside a scrollView. since the prefetching range is related to the scrollView, all the cells are "visible" on the scrollView, even though most of them are not visible on the screen at all. Hence, when calling reloadData(), it reloads all the cells, instead of reloading only the visible cells. it ends up in a very long UI freeze.

Is there a way to load only the cells that are truly visible on the screen?

Deploy resources using ARM template

Posted: 06 Jul 2021 08:08 AM PDT

I'm having a scenario, where I need to use the same app service plan to deploy the resources (app service) in another resource group.

App service plan resides in another resource group.

I tried this, which is giving "app service plan not found error". Here is the Deployment.json file.

Reference: https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-deploy-az-cli?view=azure-bot-service-4.0&tabs=csharp#option-1-existing-app-service-plan

This deployment json works fine when we tried to deploy the app in the same resource group without creating a new plan.

{  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",  "contentVersion": "1.0.0.0",  "parameters": {      "appId": {          "type": "string",          "metadata": {              "description": "Active Directory App ID, set as MicrosoftAppId in the Web App's Application Settings."          }      },      "appSecret": {          "type": "string",          "metadata": {              "description": "Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings. Defaults to \"\"."          }      },      "botId": {          "type": "string",          "metadata": {              "description": "The globally unique and immutable bot ID. Also used to configure the displayName of the bot, which is mutable."          }      },      "botSku": {          "defaultValue": "F0",          "type": "string",          "metadata": {              "description": "The pricing tier of the Bot Service Registration. Acceptable values are F0 and S1."          }      },      "newAppServicePlanName": {          "type": "string",          "defaultValue": "",          "metadata": {              "description": "The name of the new App Service Plan."          }      },      "newAppServicePlanSku": {          "type": "object",          "defaultValue": {              "name": "S1",              "tier": "Standard",              "size": "S1",              "family": "S",              "capacity": 1          },          "metadata": {              "description": "The SKU of the App Service Plan. Defaults to Standard values."          }      },      "appServicePlanLocation": {          "type": "string",          "metadata": {              "description": "The location of the App Service Plan."          }      },      "existingAppServicePlan": {          "type": "string",          "defaultValue": "",          "metadata": {              "description": "Name of the existing App Service Plan used to create the Web App for the bot."          }      },      "newWebAppName": {          "type": "string",          "defaultValue": "",          "metadata": {              "description": "The globally unique name of the Web App. Defaults to the value passed in for \"botId\"."          }      }  },  "variables": {      "defaultAppServicePlanName": "[if(empty(parameters('existingAppServicePlan')), 'createNewAppServicePlan', parameters('existingAppServicePlan'))]",      "useExistingAppServicePlan": "[not(equals(variables('defaultAppServicePlanName'), 'createNewAppServicePlan'))]",      "servicePlanName": "[if(variables('useExistingAppServicePlan'), parameters('existingAppServicePlan'), parameters('newAppServicePlanName'))]",      "resourcesLocation": "[parameters('appServicePlanLocation')]",      "webAppName": "[if(empty(parameters('newWebAppName')), parameters('botId'), parameters('newWebAppName'))]",      "siteHost": "[concat(variables('webAppName'), '.azurewebsites.net')]",      "botEndpoint": "[concat('https://', variables('siteHost'), '/api/messages')]"  },  "resources": [      {          "comments": "Create a new App Service Plan if no existing App Service Plan name was passed in.",          "type": "Microsoft.Web/serverfarms",          "condition": "[not(variables('useExistingAppServicePlan'))]",          "name": "[variables('servicePlanName')]",          "apiVersion": "2018-02-01",          "location": "[variables('resourcesLocation')]",          "sku": "[parameters('newAppServicePlanSku')]",          "properties": {              "name": "[variables('servicePlanName')]"          }      },      {          "comments": "Create a Web App using an App Service Plan",          "type": "Microsoft.Web/sites",          "apiVersion": "2015-08-01",          "location": "[variables('resourcesLocation')]",          "kind": "app",          "dependsOn": [              "[resourceId('Microsoft.Web/serverfarms', variables('servicePlanName'))]"          ],          "name": "[variables('webAppName')]",          "properties": {              "name": "[variables('webAppName')]",              "serverFarmId": "[resourceId('Microsoft.Web/serverfarms', variables('servicePlanName'))]",              "siteConfig": {                  "appSettings": [                      {                          "name": "WEBSITE_NODE_DEFAULT_VERSION",                          "value": "10.14.1"                      },                      {                          "name": "MicrosoftAppId",                          "value": "[parameters('appId')]"                      },                      {                          "name": "MicrosoftAppPassword",                          "value": "[parameters('appSecret')]"                      }                  ],                  "cors": {                      "allowedOrigins": [                          "https://botservice.hosting.portal.azure.net",                          "https://hosting.onecloud.azure-test.net/"                      ]                  }              }          }      },      {          "apiVersion": "2017-12-01",          "type": "Microsoft.BotService/botServices",          "name": "[parameters('botId')]",          "location": "global",          "kind": "bot",          "sku": {              "name": "[parameters('botSku')]"          },          "properties": {              "name": "[parameters('botId')]",              "displayName": "[parameters('botId')]",              "endpoint": "[variables('botEndpoint')]",              "msaAppId": "[parameters('appId')]",              "developerAppInsightsApplicationId": null,              "developerAppInsightKey": null,              "publishingCredentials": null,              "storageResourceId": null          },          "dependsOn": [              "[resourceId('Microsoft.Web/sites/', variables('webAppName'))]"          ]      }  ]  

}

how to Installing core20 armhf on Proxmox hypervisor

Posted: 06 Jul 2021 08:08 AM PDT

I been trying to install core20 armhf on Proxmox. The problem is it couldn't find the disk where it can boot from. if anyone can help please.

DataprocCreateClusterOperator fails due to TypeError

Posted: 06 Jul 2021 08:08 AM PDT

I am trying to deploy a Dataproc cluster with airflow.providers.google.cloud.operators.dataproc.DataprocCreateClusterOperator, but I get a cryptic TypeError.

Here is the task definition:

CLUSTER_CONFIG = {      "config_bucket": <my_bucket>,      "temp_bucket": <my_bucket>,      "master_config": {          "num_instances": 1,          "machine_type_uri": "c2-standard-8",          "disk_config": {"boot_disk_type": "pd-standard", "boot_disk_size_gb": 1024},      },      "initialization_actions": [<address>],  }    create_cluster = DataprocCreateClusterOperator(      task_id="create_cluster",      project_id=PROJECT_ID,      cluster_config=CLUSTER_CONFIG,      region=REGION,      cluster_name=CLUSTER_NAME,      metadata=[("ENV", ENV)],      dag=dag)  

Traceback:

Traceback (most recent call last)    File "/usr/local/lib/airflow/airflow/models/taskinstance.py", line 985, in _run_raw_tas      result = task_copy.execute(context=context    File "/usr/local/lib/airflow/airflow/providers/google/cloud/operators/dataproc.py", line 603, in execut      cluster = self._create_cluster(hook    File "/usr/local/lib/airflow/airflow/providers/google/cloud/operators/dataproc.py", line 540, in _create_cluste      metadata=self.metadata    File "/usr/local/lib/airflow/airflow/providers/google/common/hooks/base_google.py", line 425, in inner_wrappe      return func(self, *args, **kwargs    File "/usr/local/lib/airflow/airflow/providers/google/cloud/hooks/dataproc.py", line 304, in create_cluste      metadata=metadata    File "/opt/python3.6/lib/python3.6/site-packages/google/cloud/dataproc_v1beta2/services/cluster_controller/client.py", line 412, in create_cluste      request = clusters.CreateClusterRequest(request    File "/opt/python3.6/lib/python3.6/site-packages/proto/message.py", line 506, in __init_      pb_value = marshal.to_proto(pb_type, value    File "/opt/python3.6/lib/python3.6/site-packages/proto/marshal/marshal.py", line 208, in to_prot      pb_value = rule.to_proto(value    File "/opt/python3.6/lib/python3.6/site-packages/proto/marshal/rules/message.py", line 32, in to_prot      return self._descriptor(**value  TypeError: Parameter to MergeFrom() must be instance of same class: expected google.cloud.dataproc.v1beta2.NodeInitializationAction got str  

React: Mapping a value through an object to return an SVG

Posted: 06 Jul 2021 08:08 AM PDT

I'm trying to pass a value from a parent component (that renders a label) and hopefully soon an icon down into my CountryFlag component.

So far it's being passed like so:

<CountryFlag     countryCode={option.code}   />  

option.code returns a countryCode such as "AFN".

I then want to take that countryCode into my CountryFlag component and map through my CountryMap array so that if for example, "AFN" is passed through from the parent component, I will be able to return the "Afghan" SVG as part of the rendered FlagComponent.

I know I'm still a bit off the final implementation but any suggestions on where I may go next would be really appreciated.

import Afghanistan from "./CountryFlags/Afghanistan.svg";  import Albania from "./CountryFlags/Albania.svg"    import styled from "styled-components";    const countryMap = {    AFN: {      countryCode: "AFN",      name: "afghanistan",      icon: Afghanistan,    },    ALL: {      countryCode: "ALL",       name: "albania",      icon: Albania,    },  };    const StyledImage = styled.div`    height: 32px;    width: 32px;  `;    const CountryFlag = ({className, code="" }: Props) => {    const FlagComponent = countryMap[code];      if (!FlagComponent) {      console.warn(`icon for ${code} is not valid`);      return null;    }    return (      <StyledImage>        <FlagComponent>          src={}        </FlagComponent>      </StyledImage>    );  }    export default CountryFlag;    

Azure function timer scheduler

Posted: 06 Jul 2021 08:07 AM PDT

I been looking around but I could not really find an answer. I have a function which has scheduler schedule = "0 3/12 * * * * I am trying to figure out what does this schedule mean? Thanks.

How can I write a code for this question?

Posted: 06 Jul 2021 08:07 AM PDT

Create a PythagoreanTriple application that displays all pythagorean triples with values of A and B less than 100. A pythagorean triple is a set of three integers that make the equation a^2 + b^2 = c^2 true. The application should include a PerfectSquare() method with three parameters and prints the resulted Pythagorean triple in the form a^2 + b^2 = c^2 .

[AWS]Making code changes via ftp client are not getting reflected on website

Posted: 06 Jul 2021 08:07 AM PDT

I have an angular js application running on ec2 instance. When I make changes to the code via ftp client/ssh the files are modified, but the changes are not rendered on the website. I tried restarting pm2, cleared browser cache, restarted instance, checked file permissions, tried all possible things but nothing seem to work. I am not able to figure out where is the issue It is strange, where is AWS accessing my code from if the changes are not rendered?

Can someone please help me with it. Thank you in anticipation. (P.S I am new to AWS)

Why wouldn't request method execute in my code?

Posted: 06 Jul 2021 08:07 AM PDT

I just started learning nodejs and when I was following Js bootcamp course, this code's "req.on" part wouldn't work for me while it did execute for the instructor

const express = require('express')  const app = express()`enter code here`    app.get('/', (req, res) => {      res.send(`        <div>          <form method="POST">            <input placeholder="email" />            <input placeholder="password" />            <input placeholder="password confirmation" />            <button>Sign Up</button>          </form>        </div>      `);  });  app.post('/', (req, res) => {           req.on('data', data => {          console.log('1')          const parsed = data.toString('utf8').split('&')          const formData = {}            for (let _ of parsed) {              const [key, value] = _.split('=')              formData[key] = value          }          console.log(formData)      })        res.send('Account created!!!');  });    app.listen(3000, () => {      console.log('listening')  })  

what is the difference between function(int &a){ a = a + 2 } and function(int *a){ *a = *a + 2 }

Posted: 06 Jul 2021 08:07 AM PDT

what is the difference between:

function(int &a)  {      a = a + 2;  }  

and:

function(int *a)  {      *a = *a + 2;   }  

For what I understand they are the same no?

If there are differences can you explain them with examples?

VBA split string sentences with multiple values

Posted: 06 Jul 2021 08:08 AM PDT

My Excel raw data looks something like this:

;123456p,Roses and butterflies;;124456h,Violets are blue;

;123456d,Hello world;

Trying to split the text sentences out only, for rows with multiple sentences I would need them in separate columns, is this at all possible? Below is what I tried.

Private Sub CommandButton1_click()      Dim splitstring As String      Dim myarray() As String      splitstring = Worksheets("raw").Cells(1, 1).Value      myarray = Split(splitstring, ";")      For i = 0 To URound(myarray)        Next    End Sub    Sub raw()    End Sub  

extract data without html tags

Posted: 06 Jul 2021 08:07 AM PDT

I am trying to scrape a university world ranking website; however I have trouble extracting one of the keys without its html tags.

I get <div class="td-wrap"> <a href="/universities/massachusetts-institute-technology-mit" class="uni-link">Massachusetts Institute of Technology (MIT) </a></div>

I'd like to get: Massachusetts Institute of Technology (MIT)

Here is how I parse the data:

def parser_page(json):      if json:          items = json.get('data')          for i in range(len(items)):              item = items[i]              qsrank = {}              if "=" in item['rank_display']:                  rk_str = str(item['rank_display']).split('=')[-1]                  qsrank['rank_display'] = rk_str              else:                  qsrank['rank_display'] = item['rank_display']              qsrank['title'] = item['title']              qsrank['region'] = item['region']              qsrank['score'] = item['score']                yield qsrank   

More information, here is how the keys are presented:

{        "core_id": "624",        "country": "Italy",        "city": "Trieste",        "guide": "",        "nid": "297237",        "title": "<div class=\"td-wrap\"><a href=\"\/universities\/university-trieste\" class=\"uni-link\">University of Trieste<\/a><\/div>",        "logo": "\/sites\/default\/files\/university-of-trieste_624_small.jpg",        "score": "",        "rank_display": "651-700",        "region": "Europe",        "stars": "",        "recm": "0--"      }  

Everything is fine beside the title as you can see above, I am trying to extract the data without the tags around it.

JMeter recording display different content on the requested page

Posted: 06 Jul 2021 08:08 AM PDT

Hello everyone please help. I used JMeter to record my performance test scripts on ASP.net. Used browser IE and MS Edge. Jmeter Certificate is installed. the proxy is set. 90% of the script recorded perfectly fine. However, there some certain link or requests, I either got an error or it displayed different content or unexpected content displayed. When I turn off the Proxy, and access the browser, I go through the exactly test steps. There is no error and the content display correctly on the landing page.

I used Jmeter 5.3.

Thanks for your help.

Close ngbDropdown from child component

Posted: 06 Jul 2021 08:08 AM PDT

I have see answer to close dropdown from parent component, does any body knows how can I close it from child component

I have something like this

   <div ngbDropdown class="d-inline-block" [placement]="'bottom-left'" [autoClose]="false">        <button class="btn btn-transparent color-primary-hover" ngbDropdownToggle>Filters</button>        <div ngbDropdownMenu>          <app-search-filter></gxp-search-filter>        </div>      </div>  

Can anybody help me that i close dropdown from app-search-filter? Thanks in advance

Print the docString of the currently running python script from an imported module

Posted: 06 Jul 2021 08:07 AM PDT

I desire the following behaviour

# module.py  """ module's docString """    def foo():     print(??something??)     do other stuff`  
# script.py  """ Scripts docString """    from module import foo    foo()    do otherstuff  

Now when I run python script.py I would like the call to foo() to print the docString of script.py

I have tried

# module.py  """ module's docString """    def foo():     print(__doc__)     do other stuff`  

But this prints the docString of module.py

How do I compare each row with all the others and if it's the same I concatenate to a new dataframe? Python

Posted: 06 Jul 2021 08:07 AM PDT

I have a DataFrame with 2 columns:

import pandas as pd    data = {'Country': ['A',  'A', 'A' ,'B', 'B'],'Capital': ['CC',  'CD','CE','CF','CG'],'Population': [5, 35, 20,34,65]}    df = pd.DataFrame(data,columns=['Country',  'Capital',  'Population'])    

I want to compare each row with all others, and if it has the same Country, I would like to concatenate the pair into a new data frame (and transfor it into a new csv).

new_data =  {'Country': ['A',  'A','B'],'Capital': ['CC',  'CD','CF'],'Population': [5, 35,34],'Country_2': ['A', 'A' ,'B'],'Capital_2': ['CD','CE','CG'],'Population_2': [35, 20,65]}    df_new = pd.DataFrame(new_data,columns=['Country',  'Capital',  'Population','Country_2','Capital_2','Population_2'])  

NOTE: This is a simplification of my data, I have more than 5000 rows and I would like to do it automatically I tried comparing dictionaries, and also comparing one row at a time, but I couldn't do it. Thank you for the attention

Get id, name from master table - Ruby

Posted: 06 Jul 2021 08:08 AM PDT

The association is has follows

Company has_many company_commodities  CompanyCommodity belongs to Company  CompanyCommodity belongs to Commodity  

Consider that company1 has an entry in the company_commodities table.

Now in the decorator file, i need to get the commodity name and id of that record.

I have implemented as follows.

company1 = Company.find(1)  arr = co.company_commodities.map(&:commodity).pluck(:name, :id)  arr.map { |a| { name: a[0], id: a[1] } }  

This produces the output as

[{:name=>"Pharmaceuticals", :id=>25},   {:name=>"Medical Devices", :id=>26}]  

Is there a cleaner way to do this? 

Sorting Level Data by Two properties when One or More Values are the Same

Posted: 06 Jul 2021 08:08 AM PDT

I am having some trouble sorting data by two parameters for a leaderboard command on a Discord.js bot. I currently have it where the users are sorted by level. The only issue with this is that when there are two users with the same level, it needs to be sorted by whoever has the most XP:

Example:
User1: Lvl 20; 50/200XP
User2: Lvl 20; 80/200XP
User2 should show up before User 1

I've been trying various solutions I found, but none have solved the problem, any help on this is much appreciated, thank you!

Level data & XP Data Stored here:

  let level = db.all().filter(data => data.ID.startsWith(`guild_646074330249429012_level`)).sort((a, b) => b.data - a.data)        let userXP = db.all().filter(data => data.ID.startsWith(`guild_646074330249429012_xp`)).sort((a, b) => b.data - a.data)    

Why am I getting ValueError in Python and how can I fix it?

Posted: 06 Jul 2021 08:08 AM PDT

a=[]  b=[]  t=int(input())  for j in range(0,t):      n=int(input())      k=int(input())      for i in range(0, n):          element=int(input())          a.append(element)      for i in range(n-k, n):          b.append(a[i])      for i in range(0, n-k):          b.append(a[i])      print(b)  

enter image description here

angular Apollo Bad Request

Posted: 06 Jul 2021 08:08 AM PDT

hello dear developers actually i have a problem i'm using Appollo in my Ionic/Angular project and i have this simple mutation in my code

CreateUser(email,phone_num,password){          return this.apollo      .mutate<any>({        mutation: gql`        mutation create_user($email:String!,$phone_num:String!,$password:String!) {          create_user(input:{email:$email,phone_num:$phone_num,password:$password}){            user {              id              first_name              last_name              phone_num              email              biography              gender              profile_picture              created_at              is_active            }      message      ok      }  }         `,        variables:{          email:email,          phone_num:phone_num,          password:password        },      })    }  

when i execute this query in the backend(django) graphical page its working but in the angular project returns bad request 400 what should i do ?

Overriding GetHashCode() - how important is random distribution of hashes?

Posted: 06 Jul 2021 08:07 AM PDT

In anticipation of first comments, I do understand some hash table theory so please read on...

I have a mutable reference type (contents can change) that is used as key in a Dictionary.

Yes this is intentional (in fact unavoidable). The Dictionary grows to millions of entries and I wish to optimise access by key.

My objects do have a guaranteed-unique, private, integer field which seems a potentially ideal hash code in that underlying hashtable collisions would be impossible, however these are (nearly) sequential 1,2,4,5,6,9,10,11,...

In Principle : Should I do this

public override int GetHashCode()  {    return myUniqueId;  }  

or this

public override int GetHashCode()  {    return GenerateRandomInt(seed:myUniqueId);    // where a 1:1 relationship exists between input seeds and output pseudo random numbers    // (still avoiding hash collisions but at the cost of the PRNG call)  }  

from a hashtable-theory / best-practice point-of-view, or is the answer likely to be implementation-specific (I'd have to measure - probably per deployment environment)?

Eric Lippert mentions random distribution as a "guideline" in this blog article: Lippert Fabulous adventures in coding

Mongoose: unable to update data

Posted: 06 Jul 2021 08:07 AM PDT

I want to update user data without entering all the fields like for example if I only enter name then only name gets updated other values remain same. But, when I tried doing that my password validation is showing error, and also saying isAdmin is required.

here is my thunder Client Screen: enter image description here

To check whether I am getting all user data I consollLoged and I am getting every field: enter image description here

Here is my code: userModel.js

const mongoose = require("mongoose");  const bcrypt = require("bcryptjs");    const userSchema = mongoose.Schema(    {      name: {        type: String,        required: true,      },      email: {        type: String,        required: true,        unique: true,        match: [          /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,          "Please enter a valid email address",        ],      },      password: {        type: String,        required: true,        match: [          /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/,          "Password must contain minimum eight characters, atleast one letter, one number & one speccial character ",        ],      },      isAdmin: {        type: Boolean,        required: true,        default: false,      },    },    {      timestamps: true,    }  );    userSchema.methods.matchPassword = async function (enteredPassword) {    return await bcrypt.compare(enteredPassword, this.password);  };    // We are encrypting data before saving it  userSchema.pre("save", async function (next) {    if (!this.isModified("password")) {      next();    }      const salt = await bcrypt.genSalt(10);    this.password = await bcrypt.hash(this.password, salt);  });    const User = mongoose.model("User", userSchema);  module.exports = User;  

userController.js

//  @description: Update user  //  @route:       PUT /api/users/:id  //  @access:      Private/Admin  exports.updateUser = async (req, res, next) => {    try {      const user = await User.findById(req.params.id);        if (user) {        console.log(`USER: ${user}`);        user.name = req.body.name || user.name;        user.email = req.body.email || user.email;        user.isAdmin = req.body.isAdmin;          const updatedUser = await user.save();          res.json({          _id: updatedUser._id,          name: updatedUser.name,          email: updatedUser.email,          isAdmin: updatedUser.isAdmin,        });      } else {        const error = new Error("Sorry, user Not Found");        error.status = 404;        next(error);      }    } catch (error) {      next(error);    }  };  

How to get desired response in res.send()?

Posted: 06 Jul 2021 08:08 AM PDT

What I am trying to do is fetch details from Db and while I get the response,the attributes name shouldn't be same as the Db so for that I am using for loop. WHile i try to console it I am getting desired response but I am getting empty array/the last data of the db. Can anyone help me out?

// ------display all customer group---->  const displayCustomerGroup = async (req,res,next) =>{      var results = await Group.findAll();      var newData ={};      var data = {};       for(var i = 0; i < results.length ; i++){        for(const [key,value] of Object.entries(results[i].dataValues)){          newData[key.replace("cg_","")] = value;              }            console.log(newData)    }    res.json({      status:"success",      message:"Successfully",      data:newData       })          }  

Replacing everything between nth occurrences in file

Posted: 06 Jul 2021 08:07 AM PDT

I have a file with the fields as seen below :

2|508|PNP|20-dec-2015 12:32:20|3451101|0|3xPirate Ship Cruise | CPT||0598  2|504|PNP|20-dec-2015 12:32:20|3451101|0|3xPirate Ship Cruise | CPT||0598  2|505|PNP|20-dec-2015 12:32:20|3451101|0|3xPirate Ship Cruise || CPT||0598  2|506|PNP|20-dec-2015 12:32:20|3451101|0|3xPirate Ship Cruise | |CPT||0598  

I want get the final file down to this:

2|508|PNP|20-dec-2015 12:32:20|3451101|0|3xPirate Ship Cruise  CPT||0598  2|504|PNP|20-dec-2015 12:32:20|3451101|0|3xPirate Ship Cruise  CPT||0598  2|505|PNP|20-dec-2015 12:32:20|3451101|0|3xPirate Ship Cruise  CPT||0598  2|506|PNP|20-dec-2015 12:32:20|3451101|0|3xPirate Ship Cruise  CPT||0598  

I have tried the following:

sed 's/|//7'  

This is great because it removes the unwanted | delimiter, in the 7th field, however, the data sometimes has more than 1 pipe in the 7th field, which my code does not pick up on in its first run through.

Is there a way with either sed, awk, or python to remove one or more | in the 7th field so that the total | pipes are only 8 total |?

My algorithm doesn't encrypt/decrypt correctly. How to deal with special characters in cryptography?

Posted: 06 Jul 2021 08:08 AM PDT

I created this cryptographic algorithm just for a project, i don't intend to use it. Still i don't understand how c++ works with special characters and why sometimes it encrypt and decrypt correctly and sometimes it just encrypt and decrypt just some block of data. My algorithm encrypts blocks of 36 bytes and the last block is padded with the original block. The encryption function is simple but when it encrypt sometimes it encrypt less characters and other times it just take a part from the Text-criptat.txt to decrypt. The number of characters in Text-criptat.txt and Text-decriptat.txt it just isn't equal with the one in the original file. Please help! Thanks!

#include <iostream>  #include <fstream>  #include <string>  #include <stdio.h>  using namespace std;  string key;    void reverseStr(string& str)  {      int n = str.length();      for (int i = 0; i < n / 2; i++)          swap(str[i], str[n - i - 1]);  }    string paddingdata(string str) {      int x = 36;      for (int i = 0; ; i++)      {          if (x == i)              i = 0;          if (str.size() == x)              break;          str.push_back(str[i]);      }      return str;  }    string swifting(string& str, string key, int k)  {      if (k == 0) {          for (int i = 0; i < str.length(); i++)          {              if (i % 2 == 0) {                  str[i] = str[i] + key[i];              }              else {                  str[i] = str[i] - key[i];              }          }      }      else {          for (int i = 0; i < str.length(); i++)          {              if (i % 2 == 0) {                  str[i] = str[i] - key[i];              }              else {                  str[i] = str[i] + key[i];              }          }      }      return str;  }    string XOROP(string data, string key)  {      string dataaux = data;      for (int i = 0; i < dataaux.size(); i++)      {          dataaux[i] = data[i] ^ key[i];      }      return dataaux;  }      string expandKey(string keyword)  {      int x = 36;      for (int i = 0; ; i++)      {          if (x == i)              i = 0;          if (keyword.size() == x)              break;          keyword.push_back(keyword[i]);      }      return keyword;  }    // Se modifica cheia.  string modifyKey(string key)  {      string dataaux = key;      for (int i = 0; i < key.size(); i++)      {          char p = key[i];          for (int j = i + 1; j < key.size(); j++) {              p += key[j];          }          dataaux[i] = key[i] ^ p;      }      reverseStr(dataaux);      return dataaux;  }    string encryption(string keyx, string data)  {      for (int i = 0; i < data.length(); i++) {          reverseStr(data);          data = swifting(data, keyx, 0);          data = XOROP(data, keyx);      }      return data;  }    string decryption(string keyx, string data)  {      for (int i = 0; i < data.length(); i++) {          data = XOROP(data, keyx);          data = swifting(data, keyx, 1);          reverseStr(data);      }      return data;  }    void afisarefisiercriptat(string s) {      fstream fpt;      fpt.open("Text-criptat.txt", fstream::out);      if (!fpt)      {          cout << "\nEroare";          return;      }      fpt << s;      fpt.close();  }    void afisarefisierdecriptat(string s) {      fstream fpt;      fpt.open("Text-decriptat.txt", fstream::out);      if (!fpt)      {          cout << "\nEroare!";          return;      }      fpt << s;      fpt.close();  }      int main()  {      bool encrypt = true;      string encryptinput, input, encryptmessage = "", message = "", decryptmessage = "";      cout << "C for encrypt/ D for decrypt: ";      getline(cin, encryptinput);      if (encryptinput == "d" || encryptinput == "D") {          encrypt = false;      }      cout << "Insert the KEY: ";      getline(cin, key);      string auxkey = expandKey(key);      cout << "Extended key is: " << auxkey << endl;      char ch;      string fileName;      fstream fps, fpt;      cout << "Name of the file: ";      cin >> fileName;      fps.open(fileName, fstream::in);      if (!fps)      {          cout << "\nEroare!";          return 0;      }      while (fps >> noskipws >> ch)      {          input = input + ch;      }      cout << "The text is : " << input << endl;      fps.close();      if (encrypt) {          if (input.size() <= 36) {              message = paddingdata(input);              auxkey = modifyKey(auxkey);              message = encryption(auxkey, message);              afisarefisiercriptat(message);          }          else {              int x = 0;              int t = 0;              int r = input.size() % 36; //               int e = input.size() / 36; //               while (x == 0) {                  cout << "Starting encrypting the block " << t << endl;                  for (int i = 36 * t; i < 36 * (t + 1); i++) {                      message += input[i];                  }                  auxkey = modifyKey(auxkey);                  encryptmessage += encryption(auxkey, message);                  cout << "The encrypted message after encrypting the block  " << t << " is: " << encryptmessage << endl;                  if (e == t + 1) x = 1;                  message = "";                  t++;              }              if (r > 0) {                  string lastblock = "";                  cout << "Starting encrypting the last block " << endl;                  for (int i = 0; i < r; i++) {                      lastblock += input[e * 36 + i];                  }                  lastblock = paddingdata(lastblock);                  auxkey = modifyKey(auxkey);                  encryptmessage += encryption(auxkey, lastblock);                  cout << encryptmessage << endl;              }              afisarefisiercriptat(encryptmessage);          }      }      else {          int x = 0;          int e = input.size() / 36;          int t = 0;          for (int t = 0; t <= e - 1; t++) {              cout << "Starting decrypting block " << t << endl;              for (int i = 36 * t; i < 36 * (t + 1); i++) {                  message += input[i];              }              auxkey = modifyKey(auxkey);              decryptmessage += decryption(auxkey, message);              cout << "The decrypted message after the block " << t << "is: " << decryptmessage << endl;              message = "";          }          afisarefisierdecriptat(decryptmessage);      }      return 0;  }  

So i tried for days to understand why it doesn't work sometimes so.. i entered an input in a file:

Unlike the radar, which knows which direction it is sending its signal, the receiver simply gets a pulse of energy and has to interpret it. Since the radio spectrum is filled with noise, the receiver's signal is integrated over a short period of time, making periodic sources like a radar add up and stand out over the random background. The rough direction can be calculated using a rotating antenna, or similar passive array using phase or amplitude comparison.

And in the encrypted file(Text-criptat.txt) it shows me something like this:

쉕⇄䖗䣜洠⸌�൙렊ퟬ璣⯜꼂�圌↌瑣㙩ﬕℬ鈷椼⃔댡歼٭祬꼲鸞μ뭄꼡愾吨찐┸芰掕꧕ꇆ兟䆤辐겍碣뀝⍤탕⚯귘⇮䜂棹뙑�䅘桳垄к狵퀽礠癜Ϙ渭핣연ꪰ갡뽡ᾐ즌搳핲}殍吙ꗤ僼ꃴ誐এ䗃耬怄賥녒褣ᘱ剥㭋섚遴㮍夀呮ꆆ熰堤諳晝綐⌀㜈ⱚ炸ሕ입桰ڏ듘◝�浘ꏱ�w⧰連悿持猀䗯䍲쭥菙ꀡ惩᧲醜�ꓡ磤硵촠곎獸䄌샆ᏼ갹㼀斖傚栤⃽삾浯በ⌡䮻鎲噠氐鷨鈀쇷碯惘軵ꝉ𠉯껁䫴�팼⒕鳩갥嗘ꆻ枎⇨ൈ輊ᅔ꾶ꔀⓢ⺥්副篠ﴭ䳙滋梘팡臻◠犚릹餀엯Ꜯ䓘턌꾰�괙䱐ၹ퀭壡偍爡㬑ḯﳖР鍁

In the encrypted file there are 236 characters, 7 more bytes than in the original file, maybe because the last block of 36 characters it's padded, it adds more characters until there is a fix number of blocks of 36 chars. So now i understand it isn't about characters it's all about bytes but i don't know why it doesn't decrypt properly, because the result in the decrypted file using the same key is:

Unlike the radar, which knows which direction it is sending its signal, the receiver simply gets a pulse of energy and has to interpret it. Since the radio spectrum is filled with

Here there are only 180 characters. My algorithm encrypts and decrypts only 36 bytes at a time so it decrypted only 5 blocks of data and i don't know why. It only happens when it shows me that chinese/koreean encryption in the encrypted file. Otherwise it works. I think there must be a character that c++ can't take it from the encrypted file and it just stops. Please help. THx!

Python: iterate through the rows of a csv and calculate date difference if there is a change in a column

Posted: 06 Jul 2021 08:08 AM PDT

Only basic knowledge of Python, so I'm not even sure if this is possible?

I have a csv that looks like this: [1]: https://i.stack.imgur.com/8clYM.png (This is dummy data, the real one is about 30K rows.) I need to find the most recent job title for each employee (unique id) and then calculate how long (= how many days) the employee has been on the same job title.

What I have done so far:

import csv  import datetime  from datetime import *    data = open("C:\\Users\\User\\PycharmProjects\\pythonProject\\jts.csv",encoding="utf-8")  csv_data  = csv.reader(data)  data_lines = list(csv_data)  print(data_lines)    for i in data_lines:      for j in i[0]:   

But then I haven't got anywhere because I can't even conceptualise how to structure this. :-( I also know that at one point I will need:

datetime.strptime(data_lines[1][2] , '%Y/%M/%d').date()  

Could somebody help, please? I just need a new list saying something like: id jt days 500 plumber 370

Edit to clarify: The dates are data points taken. I need to calculate back from the most recent of those back until the job title was something else. So in my example for employee 5000 from 04/07/2021 to 01/03/2020.

How to integrate exporting to csv with backend list in octobercms

Posted: 06 Jul 2021 08:07 AM PDT

I am a beginner of OctoberCMS and I am going to use export feature in backend list. I have read document about importing and exporting in backend of octobercms.

But I am not sure how to use this feature and I want to know followings.

  1. How to add export button on backend list.
  2. How to integrate exporting with backend list.

I hope your kind assistance. Thank you.

Escape double quotes in a string

Posted: 06 Jul 2021 08:09 AM PDT

Double quotes can be escaped like this:

string test = @"He said to me, ""Hello World"". How are you?";  

But this involves adding character " to the string. Is there a C# function or other method to escape double quotes so that no changing in string is required?

No comments:

Post a Comment