Monday, July 19, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


what is the difference between inherit and direct value in css

Posted: 19 Jul 2021 08:10 AM PDT

What is the differences or benefits using inherit instead of direct value for given example.

example with inherit

html {    box-sizing: border-box;  }    *,  *::before,  *::after {    box-sizing: inherit;  }  

example with direct value

*,  *::before,  *::after {    box-sizing: border-box;  }  

Flutter define Theme of `SliverAppBar`

Posted: 19 Jul 2021 08:10 AM PDT

I'm using a SliverAppBar instead of a normal AppBar but I couldn't find a way to define an App wide theme for a SliverAppBar.
Below is an excerpt of my ThemeData with the style of the AppBar:

theme.dart

appBarTheme: const AppBarTheme(    elevation: 0.0,    backgroundColor: Color(0xFFf7fbff),    iconTheme: IconThemeData(      color: Color(0xFF0B0C10),    ),  ),  

I would be interested to know if it's possible to also theme the SliverAppBar the same as a normal AppBar?

Perl DBI / MS ODBC Driver (LinuxL:RHEL) / SQL-Server: How to insert/update BLOB varbinary(max) data?

Posted: 19 Jul 2021 08:10 AM PDT

New to SQL-Server. I'm attempting to load a pdf to a SQL-Server table (data type varbinary(max)) via PERL/MS ODBC driver/DBD::ODBC using the following (simplified) code:

use DBI qw(:sql_types);    open my $pdfFH, "test.pdf";  my @pdf = <$pdfFH>; close $pdfFH;  my $pdfStr = join('', @pdf);    my $dbh = <...valid db-handle ...>;  my $sth = $dbh->prepare(qq(  insert into       TestTable(Report)  values      (?)));  $sth->bind_param(1,$pdfStr,DBI::SQL_VARBINARY);  $sth->execute;  

Error:

DBD::ODBC::st bind_param failed: [Microsoft][ODBC Driver 17 for SQL Server]Invalid precision value (SQL-HY104) at ./t_sqlserver.pl line 37.  DBD::ODBC::st execute failed: [Microsoft][ODBC Driver 17 for SQL Server]COUNT field incorrect or syntax error (SQL-07002) at ./t_sqlserver.pl line 38.  

I am able to successfully load other data types. An alternative is to load the pdf locally from the file system using OPENROWSET(BULK...) but I would prefer to load directly to avoid moving the file from Linux to Windows.

Nested handlebars issue

Posted: 19 Jul 2021 08:09 AM PDT

So i have created a custom handle bar that check equality like this

HandlerBars.registerHelper('ifEquals', (arg1, arg2, options) => {        if (arg1 == arg2) {          return options?.fn(this);        }        return options?.inverse(this);      });  

and i am basically using it in the html like this {{#ifEquals property "string"}}

Now in this block i have a text to render and another #if handle bar.

The problem is that it renders the text before the if handle bar but it doesnt call the if handle bar even if it should return a property

How do I allow http cookies with Cypress and Firefox?

Posted: 19 Jul 2021 08:09 AM PDT

I have a simple Cypress test that tests login. The page it is logging into is running on port 80 as http for testing. Because of this the cookies are not set to secure. When I try running the test I get....

Cookie "token" has been rejected because a non-HTTPS cookie can't be set as "secure".

If I run in a regular private Firefox window this does not happen. Is there a Cypress config setting I need or something?

How could we get the id of new team which is created by cloning another team?

Posted: 19 Jul 2021 08:09 AM PDT

I'm currently working on an application in which we could create teams from customize template and delete them simply. I picked Azure function to create my teams as it is more flexible. So I do a POST with Graph SDK of C# for creating my new team by cloning the templates in our database. But, if we want to delete a team, we need to have the id of the team. So I want to get the response of the response of the my POST which let me create my new team.

So how can I get it? Here you are my POST for cloning my new team.

await graphClient.Teams[teamIDToCopy]                          .Clone(visibility,partsToClone,displayName,description,mailNickname,null)                          .Request()                          .PostAsync();  

Any help appreciated, thanks in advance.

Providing an email link to verify an email address in a React app

Posted: 19 Jul 2021 08:09 AM PDT

I have created and deployed an app that uses React (including React Router) on the front end and Express for Node JS on the back-end. I have created a process whereby users register for the app and are then sent an email with a link to click on to verify their account.

When they click the link, the server side process works fine (i.e. it updates the sql database to confirm that the email has been verified and the user is redirected to 'https://www.deployed-app.com/verificationsuccess'). Before deployment, this worked just fine but now it no longer works and the user gets 'Cannot GET /verificationsuccess'.

I think the question boils down to this: how do I get the server to send a redirect to a specific React Component?

After searching for hours on line I'm at a loss as to how to tackle this and would gratefully appreciate any help or pointers in the right direction.

My React App looks like this:

function App() {    return (      <Router>      <div className="AppPage">        <Nav/>        <Switch>          <Route path="/" exact component={LandingPage}/>          <Route path="/about" exact component={About}/>          <Route path="/login" exact component={Login}/>          <Route path="/passwordreset" component={PasswordReset}/>          <Route path="/account" component={Account}/>          <Route path="/verificationsuccess" exact component={VerificationSuccess}/>          <Route path="/verificationfail" exact component={VerificationFail}/>          <Route path="/404" exact component={FourOhFour}/>          <Route path="/notverified" component={NotVerified}/>          <Route path="/registersuccess" exact component={RegisterSuccess}/>          <Route path="/selectedBook" exact component={Book}/>          <Route path="/plan/" component={ReadingPlanView}/>          <Route path="/" component={FourOhFour}/>        </Switch>      </div>      </Router>    );  }  

"GraphQL API not deployed" error when adding Sanity.io to Gatsby Site

Posted: 19 Jul 2021 08:09 AM PDT

I'm trying to add Sanity to a Gatsby site.

I installed Sanity and deployed a GraphQL API according to these instructions: https://www.sanity.io/docs/graphql

When I run gatsby develop, I get the "GraphQL API not deployed" error.

The repo is here: https://github.com/ChrisWillburn/chris-willburn1

Anyone know how to get Sanity working with this project?

Assigning cell value based to vlookup result - VBA

Posted: 19 Jul 2021 08:09 AM PDT

After failing to figure out how to do that for a while, I'll try my luck here:

I'm essentially trying to compare two situations using VBA. A similar (and a lot simpler) example:

enter image description here

F2, for example, calculate 152+D2, while F3 calculates 185+D3.

I wish to run a macro that would check the effect of one person getting a different amount of points. For example, if A2 = Max the macro should assign the value of A3 (18) to D3. If A2 = Lewis, 18 would become the new value of D2.

Tried using vlookup and match+index in order to find the cell that I want to change. When using vlookup, the code looked similar to this:

First I copied F2:F4 to I2:I4, so the results would be comparable. Then tried to replace the value of D2:D4 according to A2&A3:

name = Range("A2").value  newvalue = Range("A3").value    Find = Application.VLookup(name, Range("C2:D4"), 2, False)  Find.value = newvalue  

Perhaps I should be looking for the cell itself, and not the value, and then it would work (maybe using offset, or offset+match? couldn't make it work)?

Would appreciate any help!

Creating a new column using scores from past years (which is in the same dataframe)

Posted: 19 Jul 2021 08:09 AM PDT

I'm sorry if this question has already been answered, but I don't really know how to phrase my question.

I have a dataframe structured in this way:

country| year | score  France | 2020 | 10  France | 2019 | 9  Germany| 2020 | 15  Germany| 2019 | 14  

I would like to have a new column called "previous_year_score" that would look into the dataframe looking for the "score" of a "country" for the "year - 1". In this case France 2020 would have a "previous_year_score" of 9, while France 2019 would have a NA

Custom js element positioning problem on resize

Posted: 19 Jul 2021 08:10 AM PDT

This js script creates a floating label for the input when typing something into the input. My problem is that the labels position is not accurate when resizing the page. Why is that? Maybe i should use other units rather than % ? Maybe i should use other units rather than % ?

var sw = $(window).width();  var sh = $(window).height();    $(document).on('keydown keyup paste', '.field', function(){      var name = $(this).attr('name');      var ph = $(this).attr('placeholder');      var px = $(this).position().left / sw * 100;      var py = $(this).position().top / sh * 100;      var pl = parseInt($(this).css('padding-left')) / sw * 100;      var pt = parseInt($(this).css('padding-top')) / sh * 100;;      var fs = parseInt($(this).css('font-size')) * (100 / sw);      var ff = $(this).css('font-family');      var fw = $(this).css('font-weight');      var fc = $(this).css('color');        if($('#label_'+name).length ) {          if($(this).val().length < 1) {              $(this).prev().animate({top: py+pt+"%"}, 50, function() {                  $('#label_'+name).remove();              });               }      } else {          var label = $('<label></label>');          label.text(ph);          label.attr("id","label_"+name)          label.css('background','white');          label.css('color',fc);          label.css('font-size',fs+"vw");          label.css('font-weight',fw);          label.css('font-family',ff);          label.css('padding','0vw 0.1vw 0vw 0.1vw');          label.css('z-index','2');          label.css('position','absolute');          label.css('left',px+pl+"%");          label.css('top',py+pt+"%");          $(this).before(label);          $(label).animate({top: py-(pt/2)+"%"}, 50);      }  });
.field{      display: block;      padding:0.8vw;      font-size:1vw;      border:0.1vw solid #bebebe;      background-color: #F8FAEC;      border-radius:0.3vw;      background: white;  }  .field:focus{      outline: none;      border:0.1vw solid red;      color:red;  }  .field:focus::-webkit-input-placeholder {      font-size:1vw;      color:red;  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>      <input class="field" type="name" name="name" placeholder="Név *">   

How to use if else on a non-existant value

Posted: 19 Jul 2021 08:10 AM PDT

The contents of the ScheduledStartDate list is either None or a string. How can I change my codes below to detect and skip the ScheduledStartDate[j] that contains None?

j = 0  while j< len1:      if (ScheduledStartDate[j] == None):        else:          ScheduledStartDate[j] = datetime.datetime.strptime(ScheduledStartDate[j], format)                j=j+1  

Efficiently create pairs of people from a list with the condition that they've never been paired before

Posted: 19 Jul 2021 08:09 AM PDT

I have a list with n names: sample = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

I also have a list of pairs that these are NOT allowed to pair, let's say sample2 = [['a', 'e'], ['e', 'g'], ['b', 'a']]

I would like an efficient way of randomly creating pair list from sample to get a list, given that they don't exist in sample2, such as: newlist = [['a', 'h'], ['b', 'g'], ['f', 'c'], ['e', 'd']].

Each element are only allowed to appear once in the paired list.

I have seen answers from this post Efficiently pair random elements of list, which is done in Python and doesn't have the addition requirements that the pairs in sample2 must not appear.

searching for matching items powershell "-icontain" & "ilike"

Posted: 19 Jul 2021 08:10 AM PDT

i try to filter objects in a directory if they contain in my filter. i got the problem, that the files that i dont want to filter, also contain my files in its names.

The files i want to filter look like : 0000.pdf, 0001.tsv, 0065.png the Syntax is the same, every item i want to filter, starts with "00", contains a dot, and after the dot there are tree characters , like "png", "tif" or "doc"

the files i dont want to filter look like: batman_N_#_0000.xls, spiderman_N_#_0022.xls,bane_N_#_0020.png

my code looks like:

if($foldercontentz -ilike "00*.*"){    Add-Content -path $destinationFolderSave\0___missingFiles.txt -value $folderDirection     }  

is there a better way to filter it, or can i filter those files, with another method, is it even possible? or have i to change the files. i tought it would filter the files because my objects starts with "00" everytime, and the files i dont want to filter not.

Edit:

$pdfFiles= "Desktop\Import\superheros\"    $sidepaths= Get-ChildItem -path $pdfFiles -Directory    $filesfolder = New-Object System.Collections.Generic.List[System.Object]      for($i=0;$i -le $sidepaths.count;$i++){  $filesfolder.add($sidepaths[$i])    }      for($i=0;$i -le $filesfolder.count;$i++){  $folder= $pdfFiles+$filesfolder[$i]  #write-host $folder        $folder| foreach{    $contentfolder = Get-ChildItem $_  $location=$directories[$i]      if($contentfolder -contains "00*.*" ){  #Write-Output $contentfolder "haaadadasd" $filesfolder[$i]  Add-Content -path $destinationFolderSave\0___missingFiles.txt -value $contentfolder       }  

$_GET gives always 1 [duplicate]

Posted: 19 Jul 2021 08:10 AM PDT

I am new at get/post methods. I create my own license manager plugin. I have completed 90% of things.

I have plugin.php?license=60f416581f911 link. my plugin checks this URL and gets JSON from there. I want to set license code system into this method.

to make this, in that PHP file, I wrote below code.

<?php  if ($_GET["license"] = "60f416581f911" ) {  //these code always work.In other words, if gives always 1 when I change license code  

I want to work the code if the license code is true but they works always.to test it, I change the license code.

probably, it is related syntax?

How to convert a .TIF into a GeoTiFF

Posted: 19 Jul 2021 08:09 AM PDT

I am using a function to download Google map images given a pair of latitude and longitude of the area. I can manage to change the format of the downloading images into jpeg or png or tiff but I would like to save the images as Geotiff in order to keep the spatial information. Is there a way to do that? Like input the existing image and then input the format I want it to be converted. Here is the code

def __init__(self, lat, lng, zoom=12, layer='s'):        self._lat = lat      self._lng = lng      self._zoom = zoom      self._layer = layer    def getXY(self):          tile_size = 256        numTiles = 2 << self._zoom        # Find the x_point given the longitude      point_x = (tile_size / 2 + self._lng * tile_size / 360.0) * numTiles // tile_size        # Convert the latitude to radians and take the sine      sin_y = math.sin(self._lat * (math.pi / 180.0))        # Calulate the y coorindate      point_y = ((tile_size / 2) + 0.5 * math.log((1 + sin_y) / (1 - sin_y)) * -(      tile_size / (2 * math.pi))) * numTiles // tile_size        return int(point_x), int(point_y)    def generateTiles(self, **kwargs):          start_x = kwargs.get('start_x', None)      start_y = kwargs.get('start_y', None)      tile_width = kwargs.get('tile_width', 5)      tile_height = kwargs.get('tile_height', 5)        # Check that we have x and y tile coordinates      if start_x == None or start_y == None:          start_x, start_y = self.getXY()        # Determine the size of the image      width, height = 256 * tile_width, 256 * tile_height        # Create a new image of the size require      map_img = Image.new('RGB', (width, height))        for x in range(0, tile_width):          for y in range(0, tile_height):              url = f'https://mt0.google.com/vt?lyrs={self._layer}&x=' + str(start_x + x) + '&y=' + str(start_y + y) + '&z=' + str(self._zoom)              current_tile = str(x) + '-' + str(y)              urllib.request.urlretrieve(url, current_tile)                im = Image.open(current_tile)              map_img.paste(im, (x * 256, y * 256))                os.remove(current_tile)                               current_tile = str(x) + '-' + str(y)              urllib.request.urlretrieve(url, current_tile)                im = Image.open(current_tile)              map_img.paste(im, (x * 256, y * 256))                os.remove(current_tile)            return map_img    def main():      gmd = ImagesDownloader(lat, lon, 15, layer ='s')    print("The tile coorindates are {}".format(gmd.getXY()))    try:      # Get the high resolution image      img = gmd.generateTiles()  except IOError:      print("Could not generate the image - try adjusting the zoom level and checking your coordinates")  else:      # Save the image to disk      img.save("high_resolution_image.tif")      print("The map has successfully been created")      if __name__ == '__main__':  main()  

MySQL View with Conditional Sum

Posted: 19 Jul 2021 08:10 AM PDT

I'm trying to create a view that SUMS a table column based on two other columns (id and class), but I'm struggling with the inner query, or at least I think thats the problem.

The VIEW is not recognizing the 'id' column and thus is summing the entire column for each id.

I've left my attempts out of the fiddle for simplicity and easier understanding.

Here is my fiddle: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=e6aa3d66e791936779ea3a4c5b0d8580

CREATE TABLE Table1 (id INT,class varchar(10),amount varchar(50));    CREATE OR REPLACE VIEW View1 AS    select id,      concat_ws(' / ',          concat_ws('','A:',(select  coalesce(SUM(amount),0)                              from Table1                              where class = 'A')),          concat_ws('','B:',(select  coalesce(SUM(amount),0)                              from Table1                          where class = 'B')),          concat_ws('','C:',(select  coalesce(SUM(amount),0)                              from Table1                              where class = 'C'))        ) as totals  from Table1  group by id  

The expected outcome for each id should be:

A: 0.25  B: 0.50  C: 0.75  

Web scraping in Python using Selenium

Posted: 19 Jul 2021 08:10 AM PDT

I am new to web scraping and i am facing a problem. In the appending part, it seems to append only the first row of the table I want to scrape! I am sure I am missing something. Any ideas? Thanks in advance! The code snippet is the following:

driver = visit_main_page()    contents = driver.find_elements_by_xpath('//*[@id="mw-content-text"]/div[1]')    tables = contents[0].find_elements_by_xpath('//*[@id="mw-content-text"]/div[1]/table')    data = {"Date": [], "Time": [], "Place": [], "Latitude": [], "Longitude": [], "Fatalities": [], "Magnitude": []}    for i in tables:        try:          dates = driver.find_elements_by_xpath('//*[@id="mw-content-text"]/div[1]/table[2]/tbody/tr[1]/td[1]')          times = driver.find_elements_by_xpath('//*[@id="mw-content-text"]/div[1]/table[2]/tbody/tr[1]/td[2]')          places = driver.find_elements_by_xpath('//*[@id="mw-content-text"]/div[1]/table[2]/tbody/tr[1]/td[3]')          lat = driver.find_elements_by_xpath('//*[@id="mw-content-text"]/div[1]/table[2]/tbody/tr[1]/td[4]')          long = driver.find_elements_by_xpath('//*[@id="mw-content-text"]/div[1]/table[2]/tbody/tr[1]/td[5]')          fat = driver.find_elements_by_xpath('//*[@id="mw-content-text"]/div[1]/table[2]/tbody/tr[1]/td[6]')          magn = driver.find_elements_by_xpath('//*[@id="mw-content-text"]/div[1]/table[2]/tbody/tr[1]/td[7]')      except NoSuchElementException:          print('No such content!')          pass      time.sleep(1)        for d in dates:          data['Date'].append(d.text)        for t in times:          data['Time'].append(t.text)        for p in places:          data['Place'].append(p.text)        for la in lat:          data['Latitude'].append(la.text)        for lo in long:          data['Longitude'].append(lo.text)        for f in fat:          data['Fatalities'].append(f.text)        for m in magn:          data['Magnitude'].append(m.text)  

How to write in streaming to bigquery from Apache Beam?

Posted: 19 Jul 2021 08:09 AM PDT

I'm trying to use the Apache Beam Go SDK for Dataflow to read from PubSub and write to BigQuery (in streaming so).

The following code without the window is running but nothing is written into BigQuery.

The following code with the window is not running : I got Error processing pipeline. in Dataflow.

package main    import (      "context"      "encoding/json"      "flag"      "time"        "github.com/apache/beam/sdks/go/pkg/beam"      "github.com/apache/beam/sdks/go/pkg/beam/io/bigqueryio"      "github.com/apache/beam/sdks/go/pkg/beam/io/pubsubio"      "github.com/apache/beam/sdks/go/pkg/beam/log"      "github.com/apache/beam/sdks/go/pkg/beam/x/beamx"      "github.com/apache/beam/sdks/go/pkg/beam/x/debug"  )    type (      ProcessedTask struct {          TaskId     string    `json:"task_id" bigquery:"task_id"`          Connector  string    `json:"connector" bigquery:"connector"`          Success    bool      `json:"success" bigquery:"success"`          Retry      bool      `json:"retry" bigquery:"retry"`          Message    string    `json:"message" bigquery:"message"`          FinishedAt time.Time `json:"finished_at" bigquery:"finished_at"`      }  )    func buildPipeline(s beam.Scope) {      rawProcessedTasks := pubsubio.Read(s, "project", "topic", &pubsubio.ReadOptions{Subscription: "subscription"})        processedTasks := beam.ParDo(s, func(ctx context.Context, data []byte) (ProcessedTask, error) {          var task ProcessedTask          if err := json.Unmarshal(data, &task); err != nil {              log.Error(ctx, err)              return task, err          }          return task, nil      }, rawProcessedTasks)        debug.Printf(s, "Task : %#v", processedTasks)        /* The window I added */      windowedProcessedTasks := beam.WindowInto(s, window.NewFixedWindows(time.Minute), processedTasks)      /* end of the added window */        bigqueryio.Write(s, "project", "table", processedTasks)  }    func main() {      flag.Parse()      beam.Init()        p, s := beam.NewPipelineWithRoot()      buildPipeline(s)        ctx := context.Background()      if err := beamx.Run(ctx, p); err != nil {          log.Exitf(ctx, "Failed to execute pipeline: %v", err)      }  }  

I tried to add a window since in the code, the data is buffered until it achieve 10000 rows or 10485760 bytes of data.

I would like to write in streaming or write each x minutes. I don't have a lot of events, I'm not sure to achieve that limit in a week and I need it to be near-realtime.

Does anyone have suggestions?

Check for correct input via scanf

Posted: 19 Jul 2021 08:09 AM PDT

I have an integer 'n' that is responsible for amount of numbers to enter later on. I need to check for any incorrect inputs here. The first scanf for 'n' works fine, but the second has some flaws. The case is following:

n = 3 (e.g.) - doesn't matter

Then I want to scanf: 1 2 3 4

It will be scanned first 3 values but I need to throw out an error.

Same goes with: 1 2 3.5 - (last number is float but it still reads 3)

and with a char: 1 2 3g

if (scanf("%d", n) == 1 && getchar() == '\n') {          if (n > NMAX || n < 0) {              error = 1;              return;          }          for (int i = 0; i < n; i++) {              if (scanf("%d", p) == 1) {  

The ONLY correct input is the exact same amount of integer numbers (equals to 'n') to scan in a for loop.

UPD: I can use only <stdio.h> library as well as only scanf.

yarn + how to configure the resource-manager. web Appaddress

Posted: 19 Jul 2021 08:09 AM PDT

in yarn configuration , we have the following parameters ( according to https://hadoop.apache.org/docs/r2.7.6/hadoop-yarn/hadoop-yarn-common/yarn-default.xml )

yarn.resourcemanager.webapp.address             ${yarn.resourcemanager.hostname}:8088   The http address of the RM web application.  yarn.resourcemanager.webapp.https.address       ${yarn.resourcemanager.hostname}:8090   The https adddress of the RM web application.  yarn.resourcemanager.resource-tracker.address   ${yarn.resourcemanager.hostname}:8031     

we are not sure about how to set the hostname

for example

we can set the parameter:

yarn.resourcemanager.webapp.address as

master01.formula45.com:8088        ( when master01.formula45.com is the hostname of the machine that resource manager is installed)  

or maybe better as

0.0.0.0:8088  

references:

https://superuser.com/questions/949428/whats-the-difference-between-127-0-0-1-and-0-0-0-0 https://serverfault.com/questions/78048/whats-the-difference-between-ip-address-0-0-0-0-and-127-0-0-1

Unable to create .exe for windows from my laptop other options?

Posted: 19 Jul 2021 08:09 AM PDT

I've been using pyinstaller and it always gives me Unix Executable File. I am on a mac and trying to get a python file turned into .exe to run on windows. What should I do?

Has anyone with a mac found a fix?

Find users who have visited URL A and B with SQL?

Posted: 19 Jul 2021 08:10 AM PDT

Let's say you have a table with user, url, datetime, in which each row is a website visit.

How to find users who have visited both an URL contaning string pattern A and visited an URL containing string pattern B?

The fact it's "containing a string pattern ...", and not a simple equality makes it impossible to use a query with something like

url in ('action1.php', 'action2.php')  

like in SQL querying a customer ID who ordered both product A and B.

How to extract each value from delimited string in batch script and how to place labels for proper flow

Posted: 19 Jul 2021 08:10 AM PDT

I want to extract folder name from a path stored in a variable. I want each folder name to be extracted and stored in separate variable. I tried the below code and got the output but the output is not as desired. I only want one cycle of output. Also I want to understand how to place labels in batch files. I'm finding difficulties in this.

Query1

set MYDIR=C:\FOLDER1\FOLDER2\FOLDER2    call :parse "%MYDIR%"  :parse  setlocal  set MYDIRS=%1  set MYDIRS=%MYDIRS:"=%  FOR /f "tokens=1* delims=\" %%a IN ("%MYDIRS%") DO (    if not "%%a" == "" call :sub %%a    if not "%%b" == "" call :parse "%%b"  )    :sub    @echo Subfolder extracted=^%1  

Output

Subfolder extracted= C:  Subfolder extracted= FOLDER1  Subfolder extracted= FOLDER2  Subfolder extracted= FOLDER3  Subfolder extracted= C:  Subfolder extracted= FOLDER1  Subfolder extracted= FOLDER2  Subfolder extracted= FOLDER3  

Query2

Also when i use a label to check if my string is empty and if uts empty it should go to the :eof however it goes to eof even when the MYDIR is not empty

set MYDIR=C:\FOLDER1\FOLDER2\FOLDER2    if "%MYDIR%" == "" goto :err_emptyFile    :err_emptyFile  @echo File path is empty  goto :eof    call :parse "%MYDIR%"  :parse  setlocal  set MYDIRS=%1  set MYDIRS=%MYDIRS:"=%  FOR /f "tokens=1* delims=\" %%a IN ("%MYDIRS%") DO (    if not "%%a" == "" call :sub %%a    if not "%%b" == "" call :parse "%%b"  )    :sub    @echo Subfolder extracted=^%1    :eof  @echo :eof  @echo file path is empty  

output

File path is empty  :eof  File path is empty  Subfolder extracted= C:  Subfolder extracted= FOLDER1  Subfolder extracted= FOLDER2  Subfolder extracted= FOLDER3  Subfolder extracted= C:  Subfolder extracted= FOLDER1  Subfolder extracted= FOLDER2  Subfolder extracted= FOLDER3  

dash-leaflet (geojson): change color of last clicked feature

Posted: 19 Jul 2021 08:09 AM PDT

I'm trying to change color of polyline (feature) on click, but I don't know how. I know there is component click_feature and I should use it somehow (so I can target specific feature, but I don't know how to update color).

Something like that:

app.clientside_callback(      """function(feature){          // set and return color          ;}""",      Output("geojson", ???), # To what children?      Input("geojson", "click_feature")      )  

So any ideas, how to change color of specific feature on click event?

Thanks!

How to inject UserManager mock while using WebApplicationFactory for integration tests?

Posted: 19 Jul 2021 08:10 AM PDT

I am using WebApplicationFactory to create some integration tests agains some Web APIs written in .NET 5

In The samples I have seen (like this:https://codeburst.io/integration-tests-for-asp-net-core-web-apis-using-mstest-f4e222a3bc8a) there is a way to configure the web applicaton instance like this:

_factory = new WebApplicationFactory<ProductionOrdersController>();  _factory = _factory.WithWebHostBuilder(builder =>  {      builder.UseSetting("https_port", "5001").UseEnvironment("Testing");      builder.ConfigureServices(services =>      {          services.AddScoped<IStudentsService, MockStudentService>();      });  });  

The problem is that "AddScoped" method is not available. On the lastest package (Microsoft.AspNetCore.Mvc.Testing) there is a Add method only

Any ideas how to inject my service mocks into "ProductionOrdersController", for example UserManager, ApplicationDbContext, etc?

Thanks!

Word- VBA- How To Automatically Run Code Before Printing?

Posted: 19 Jul 2021 08:09 AM PDT

Document has shading wdColorGray25 by default. I want to be able to remove all shading before printing (or saving as a PDF) but this doesn't seem to work as simple as it would in Excel (the code works fine by itself in a standard module).

Private Sub appWord_DocumentBeforePrint(ByVal Doc As Document, Cancel As Boolean)      With ActiveDocument.Styles("example").Font          With .Shading              .BackgroundPatternColor = wdColorAutomatic          End With      End With  End Sub  

Then of course I want the document to return to the default shading when I am not trying to print

Hotwire breaks link_to rails

Posted: 19 Jul 2021 08:09 AM PDT

I recently added Hotwire to my rails app to update modals but this broke a link_to I had that redirected users to stripe. I looked online for ways to work around it but since Hotwire is relatively new, I couldn't find it. Does anyone have any recommendations on getting link_to to work with turbo stream?

How to authenticate an user in firebase-admin in nodejs?

Posted: 19 Jul 2021 08:10 AM PDT

At the moment I am creating a Firebase API on nodejs. I would like to handle all Firebase stuff (like authentication) with firebase-admin on nodejs. But what is the correct way to authenticate a user over nodejs in firebase-admin without the Javascript Firebase SDK on the client side? On the official documentation for admin I didn't find a function called signInWithEmailAndPassword (like as on the client side SDK) for nodejs. There is only a function called: "getUserByEmail", but this function doesn't check if the user has entered the correct password.

This is my form:

<form class="sign-box" action="/login" method="post">          <div class="form-group">            <input id="username" name="username" type="text" class="form-control" placeholder="E-Mail"/>        </div>        <div class="form-group">            <input id="password" name="password" type="password" class="form-control" placeholder="Password"/>        </div>        <button type="submit" class="btn btn-rounded">Sign in</button>    </form>  

Once the form is submitted I pass the values to my API in nodejs:

app.post('/login', urlencodedParser, function (req, res) {        // getting the values        response = {          username: req.body.username,          password: req.body.password        };            // authenticate the user here, but how ?    });  

My first idea was to use the Firebase SDK on the client side to sign in with signInWithEmailAndPassword and to get the uid. Once I had the UID I wanted to sent the UID to nodejs and call the function createCustomToken and to return the generated token (with some additional claims) back to the client. Once I get the token back I would use the function signWithCustomToken (on the client side) to authenticate the user. Is this way correct or is there a better way ?

#1071 - Specified key was too long; max key length is 767 bytes

Posted: 19 Jul 2021 08:09 AM PDT

When I executed the following command:

ALTER TABLE `mytable` ADD UNIQUE (  `column1` ,  `column2`  );  

I got this error message:

#1071 - Specified key was too long; max key length is 767 bytes  

Information about column1 and column2:

column1 varchar(20) utf8_general_ci  column2  varchar(500) utf8_general_ci  

I think varchar(20) only requires 21 bytes while varchar(500) only requires 501 bytes. So the total bytes are 522, less than 767. So why did I get the error message?

#1071 - Specified key was too long; max key length is 767 bytes  

No comments:

Post a Comment