Friday, August 27, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Run python function from command-line - invalid syntax due to full file path

Posted: 27 Aug 2021 08:01 AM PDT

I try to run a python function from command-line:

H:\myfolder\python.exe -c "from P:\myproject\myscript import myfct; myfct(1,2)"  

An error occurs with this message:

P:\myproject\myscript ...   ^  SyntaxError: invalid syntax  

It works fine without the folder path:

H:\myfolder\python.exe -c "from myscript import myfct; myfct(1,2)"  

The script should preferably run from other directories as well. Double backslash does not solve the problem as also stated here. As far as I can judge, it's not a problem of directory change. How do I have to write the command string which contains the full file path?

The directory P: is a mapped network directoy. Is this a problem?

I'm using Python 3.9.5 on Windows 10 Pro.

How to avoid using a package in Angular Universal

Posted: 27 Aug 2021 08:01 AM PDT

I have been using Angular Universal SSR (Angular 12) with Express and @agm/core (Google Maps). I get this error:

ERROR ReferenceError: window is not defined at WindowRef.getNativeWindow  

this happens because @agm/core is trying to use window and this is not defined in server side.

So my question is, how can i disable this package in server side for not get this type of errors?.

For the integration you have to import @agm/core at app.module like this:

AgmCoreModule.forRoot({        apiKey: ['YOUR_API_KEY_HERE'],  })  

And then you will be able to use the agm-map component.

ansible create specific dictionnary

Posted: 27 Aug 2021 08:01 AM PDT

I have a problematic, I have playbook ansible, which store files from sub directories in list and each item on list I associate a number starting from 100.

The problem is he create it dynamically the dictionnary and he mix up the number and file. For instance

dict_config = ["config1": 100, "config2":101]

when I add a new file on subdirectory

I want to be dict_config = ["config1": 100, "config2":101, "config3":102] but it is dict_config = ["config1": 100, "config3":101, "config2":102]

so for new file, I want on dict_config, he add an new item at last position and no mix up the dictionnary.

- name: Get config file    find:      paths: "/etc/config"      file_type: file    register: found_files    - name: Get only file names    set_fact:      file_names: "{{ found_files['files'] | map(attribute='path') | map('basename') | list }}"    - name: Apply filter while looping    set_fact:      config_file: "{{ file_names | map('splitext')| map('first') | list }}"    - name: Set up dict to map customer and port    set_fact:      dict_config: "{{ dict(config_file|zip(_serial)) }}"    vars:      start: 100      _len: "{{ config_file|length }}"      _serial: "{{ range(start, start + _len|int) | list }}"  

TypeError: __init__() takes from 2 to 11 positional arguments but 12 were given

Posted: 27 Aug 2021 08:01 AM PDT

I'm trying to process a wiki XML corpus in Jupyter notebook by using a python file because the code inside the file helps in keeping the punctuations while prospecting the corpus.

Here's the content of the python file:

  from nltk.tokenize import  WhitespaceTokenizer  import nltk.data  import re    from gensim.corpora.wikicorpus import *       sent_detector = nltk.data.load('tokenizers/punkt/english.pickle')      reA = re.compile("\'{2,}", re.UNICODE) # Multiple quotes  reB = re.compile("={2,}", re.UNICODE)  # Multiple equals  reB2 = re.compile("={2,}$", re.UNICODE)  # Multiple equals, at the end of a token    reC = re.compile("^(\w{0,}[.!?;:\"\(\)])'{2,}$") # Sentence ender followed by double quotes - want to retain only the former    reD = re.compile("\*+\s*(\'{0,5}[A-Z])", re.UNICODE) # Asterisk(s) followed by capital (with optional space) - assume bullet point, sub * for .    def sent_end_rep(matchobj):      return matchobj.group(1)    def bullet_rep(matchobj):      return '. '+matchobj.group(1)      def tokenize(content, token_min_len = 1, token_max_len = 15, lower=True):      #used to override original method in wikicorpus.py      outlist = []      # Sentences      for sent in sent_detector.tokenize(re.sub(reD,bullet_rep,content)): # Asterisk followed by capital - assume bullet marker, swap * for .          for t in WhitespaceTokenizer().tokenize(sent):              if len(t) >= token_min_len and len(t) <= token_max_len and not t.startswith('_'):                  if re.fullmatch(reA,t):  # Omit markup tokens of multiple quotes                      continue                  elif re.fullmatch(reB,t): # Multiple equals (heading markup) -> newline                      t = '\n'                  elif re.fullmatch(reC,t):                      t = re.sub(reC,sent_end_rep,t) # Retain sentence enders followed by double quotes                                        t = re.sub(reA,'',t) # Remove blocks of multiple quotes (from markup)                  t = re.sub(reB2,'\n',t) # Multiple equals at end of a token should be a newline (to keep headings as sentences)                  t = re.sub(reB,'',t) # Remove blocks of multiple equals (from markup)                                        if lower:                      outlist.append(utils.to_unicode(t.lower()))                  else:                      outlist.append(utils.to_unicode(t))                                outlist.append('\n')      return outlist        def process_article(args, token_min_len=TOKEN_MIN_LEN, token_max_len=TOKEN_MAX_LEN, lower=True):     # override original method in wikicorpus.py      text, lemmatize, title, pageid = args      text = filter_wiki(text)      if lemmatize:          result = utils.lemmatize(text)      else:          result = tokenize(text, token_min_len, token_max_len, lower)      return result, title, pageid      def _process_article(args):      """Same as :func:`~gensim.corpora.wikicorpus.process_article`, but with args in list format.      Parameters      ----------      args : [(str, bool, str, int), (function, int, int, bool)]          First element - same as `args` from :func:`~gensim.corpora.wikicorpus.process_article`,          second element is tokenizer function, token minimal length, token maximal length, lowercase flag.      Returns      -------      (list of str, str, int)          List of tokens from article, title and page id.      Warnings      --------      Should not be called explicitly. Use :func:`~gensim.corpora.wikicorpus.process_article` instead.      """      tokenizer_func, token_min_len, token_max_len, lower = args[-1]      args = args[:-1]        return process_article(          args, token_min_len=token_min_len,          token_max_len=token_max_len, lower=lower      )      class MyWikiCorpus(WikiCorpus):      def __init__(self, fname, processes=None, lemmatize=utils.has_pattern(), lower=True, token_min_len=1, token_max_len=15, dictionary=None, filter_namespaces=('0',), tokenizer_func=tokenize, article_min_tokens=50, filter_articles=None):          WikiCorpus.__init__(self, fname, processes, lemmatize, dictionary, filter_namespaces, tokenizer_func, article_min_tokens, token_min_len, token_max_len, lower, filter_articles)        def get_texts(self):          articles, articles_all = 0, 0          positions, positions_all = 0, 0            tokenization_params = (self.tokenizer_func, self.token_min_len, self.token_max_len, self.lower)          texts = \              ((text, self.lemmatize, title, pageid, tokenization_params)               for title, text, pageid               in extract_pages(bz2.BZ2File(self.fname), self.filter_namespaces, self.filter_articles))          pool = multiprocessing.Pool(self.processes, init_to_ignore_interrupt)                    # process the corpus in smaller chunks of docs, because multiprocessing.Pool          # is dumb and would load the entire input into RAM at once...          for group in utils.chunkize(texts, chunksize=10 * self.processes, maxsize=1):              for tokens, title, pageid in pool.imap(_process_article, group):  # chunksize=10):                  articles_all += 1                  positions_all += len(tokens)                  # article redirects and short stubs are pruned here                  if len(tokens) < ARTICLE_MIN_WORDS or any(title.startswith(ignore + ':') for ignore in IGNORED_NAMESPACES):                      continue                  articles += 1                  positions += len(tokens)                  if self.metadata:                      yield (tokens, (pageid, title))                  else:                      yield tokens          pool.terminate()            logger.info(              "finished iterating over Wikipedia corpus of %i documents with %i positions"              " (total %i articles, %i positions before pruning articles shorter than %i words)",              articles, positions, articles_all, positions_all, ARTICLE_MIN_WORDS)          self.length = articles  # cache corpus length  

so inside the Jupyter notebook I'm importing the file as

from mywikicorpus import MyWikiCorpus    

and reading the corpus using this class

wiki = MyWikiCorpus('enwiki-latest-pages-articles-multistream22.xml-p41496246p42996245.bz2')  

But I get error and I'm not sure what's wrong with it,I searched but didn't find any answers I tried to remove "self" from line 2 and 3 inside the class from the python file but it didn't work. The error: TypeError: init() takes from 2 to 11 positional arguments but 12 were given

Get input from user - Dart

Posted: 27 Aug 2021 08:01 AM PDT

As a Java dev, it seems hella weird to use String's methods when using either an int or a double.

Let me provide a really simple program:

import "dart:io";

void main () {

print ("Type a number:"); int num1 = int.parse(stdin.readLineSync());

print ("Type another one:"); int num2 = int.parse(stdin.readLineSync());

print (num1 + num2);

}

I wonder if would it be possible not to do that.

Thanks in advance!

My react app loads on my pc and on my ipad, but on my phone it displays "site is unreachable"

Posted: 27 Aug 2021 08:00 AM PDT

Here is the screenshot. The app loads on my pc, on my ipad and on my iphone as well. But on my nord CE, chrome shows site unreachable.

image from my one plus nord

Sticky Items have weird positions when rotating

Posted: 27 Aug 2021 08:00 AM PDT

I made three parent Elements with a sticky Element in it. The problem is since I added rotate the text is placed wrong vertically and horizontally. For example, the elements are displayed outside the parent element and the shorter the text is the further to the left it is. Here is the code and some pictures (Press full page in snippet):

* {    margin: 0;    padding: 0;  }    .parent {    height: 1000px;  }    .parent:nth-child(odd) {    background: red;  }    .parent:nth-child(even) {    background: blue;  }    .sticky {    position: sticky;    top: 0;    transform: rotate(-90deg);    display: inline-block;    background: #fff;    padding: 10px;    box-shadow: 0 0 8px -1px silver;    border-radius: 2px;      }
<!-- First Parent -->    <div class="parent">    <div class="sticky">    I'm Sticky Number One and i'm long  </div>    </div>    <!-- Second Parent -->    <div class="parent">    <div class="sticky">    I'm Sticky Number Two  </div>    </div>    <!-- Third Parent -->    <div class="parent">    <div class="sticky">    I'm Sticky 3  </div>    </div>


Here are some images:

Without rotating:

Without rotating

With rotating:

With rotating

Different alignment when text is longer/shorter

alignment

How can i fix this problem?

Thanks in advance <3

vscode auto imports not working as expected

Posted: 27 Aug 2021 08:00 AM PDT

My vscode only auto imports modules if the files they are contained in are opened in the editor. For example if I want to import <Component/> from Component.js, I have to open the Component.js file first in the IDE and only then auto suggestion 'finds' it and suggests it. Is this normal behavior?

Am I using the useEffect hook correctly to try and fetch data?

Posted: 27 Aug 2021 08:01 AM PDT

I am having some issues with my React code when trying to use the useEffect hook to fetch data from an API.

This is my boiled down code:

const App = () => {        const [ data, setData ] = useState([]);      const [ loading, setLoading ] = useState(false);        useEffect(() => {                    const loadData = async () => {                try {                  setLoading(true);                  const response = await fetch(`htts://localhost/api/`);                  const json = await response.json();                  console.log(json);                  setData(json);                  setLoading(false);              } catch (error) {                  console.log("error: " + error);              }          }            loadData();        }, []);  }  

I am running into issues that when I render the html it's giving me errors that I am unable to map to some of the data that I am setting from my API.

I was thinking that setting the data variable would give me the ability to spit out data in the template and the various object key names like:

{       data.keyname.map((item, index) => {              return (                      <option key={ index }                              value={ item.displayName }                      >                      { item.displayName }                      </option>              );      })  }  

Am I overlooking something here? It appears that my data isn't loading so the render code can't loop through any of the data it needs to in order to render the app.

Post request works after 2 clicks, how to reduce it to 1?

Posted: 27 Aug 2021 08:00 AM PDT

Here is my code,

<form action="/" method="post">     <input class="filmcek" type="submit" value="RASTGELE CEK">  </form>  
var random_mov;  app.post("/" , (req,res) =>{    Movie.aggregate().sample(1)         .read('primaryPreferred').exec((err,docs) =>{              random_mov = docs[0]    });    res.redirect("/")  })  

It is working fine after 2 clicks. But for the first time, I have to click it twice.

When I click the button in my HTML, it works after 2 clicks.

I wanted to my button work immediately.

Javascript 'Unicode property escapes', why is backslash needed [duplicate]

Posted: 27 Aug 2021 08:01 AM PDT

Given that javascript statement

let x = '(?<![\p{L}])(officesuite)'    console.log(x);  

prints that string, notice the backslash in not there as expected

(?<![p{L}])(officesuite)   

If i modify the statement above and remove the backslash like that, the print output is the same (no backslash). I wonder why is backslash needed in first place?

let x = '(?<![p{L}])(officesuite)'    console.log(x);  

this prints the same out output

(?<![p{L}])(officesuite)   

I wonder why is backslash needed in javascript \p{...} when the string in memory appear to be the same without it? It appears that it doesn't escape anything?

strange corruption in rawpy.imread

Posted: 27 Aug 2021 08:01 AM PDT

I intended to read a DNG formatted image with the code rawpy.imread(path), however it returned me with a error message, saying unknown file: data corrupted at xxxxxxx (7-digit number).

Following this error, I found the program is still able to continue to run anyway, and the DNG image is not a flat one, since when visiting its property of raw_image_visible, it returned me with a ndarray of four channels. I have the lastest version of rawpy package (0.16.0) under Windows 10 environment.

I shared the photo via Google Drive. I have no idea how I can address this issue. Any kind of help is appreciated.

React Native Expo-Location returns Location service unavailable during initial useEffect

Posted: 27 Aug 2021 08:01 AM PDT

Main Problem: I am using expo-location in my Android app in order to find the gps coordinates of the user. I have read and used the sample code provided in the expo documentation. My main problem is that, Location.getCurrentPositionAsync({}) returns Location provider is unavailable. Make sure that location services are enabled. This is my code below:

useEffect(() => {      (async () => {        let { status } = await Location.requestForegroundPermissionsAsync();        if (status !== 'granted') {          setErrorMsg('Permission to access location was denied');          return;        }        let location = await Location.getCurrentPositionAsync({});        console.log(location);      })();    }, []);  

Status returns granted but getCurrentPositionAsync({}) returns an error. I implemented a janky solution by using try-catch blocks and running getCurrentPositionAsync({}) again in the catch block, which seems to work. This is my code below:

useEffect(() => {      (async () => {        let { status } = await Location.requestForegroundPermissionsAsync();        if (status !== 'granted') {          setErrorMsg('Permission to access location was denied');          return;        }        try {          var location = await Location.getCurrentPositionAsync({});        } catch {          location = await Location.getCurrentPositionAsync({});        }        console.log(location);      })();    }, []);  

Does anyone know why this is happening?

Missing Value Error although "na.action" was set to "na.roughfix"

Posted: 27 Aug 2021 08:01 AM PDT

I would like to create a Random Forest model with caret. Since there are missing values in the training set, I was looking for possible solutions and came across the option "na.roughfix" from the package "randomForest". If the library randomForest is loaded, this option can be used as argument for the parameter "na.action" within the train function of caret. Inside the train function I use a 5-fold CV and tune for the best ROC value. I do this to ensure comparability between other models. The method I've chosen for the Random Forest is "ranger".

But now something strange happens: When I trigger the train function, the calculation is started, but for example the following error message appears:

model fit failed for Fold5: mtry= 7, splitrule=gini, min.node.size= 5 Error : Missing data in columns: ...

The "..." stands for the columns in which the missing values occur. Moreover, this error message always occurs, no matter for which fold or value for mtry.

I am well aware that there are missing values in these columns ... that's why I use na.roughfix. I also remove the NZVs, but that doesn't help either.

I would be very happy about an explanation or even a solution!

Many greetings

Edit.: I've seen now that, if I want to choose the "na.action" arugment in the train function, it does not appear automatically, which it usually does. It seems that it's somehow lost ... maybe this is the reason, why caret does not use the na.roughfix ...

Edit. 2: I guess that this is one part of the problem. train behaves always differently, depending on the previous arguments. In my train function I use a recipe from the recipe package to remove the NZVs. As soon as I remove the recipe, the na.action argument becomes available again. However, now the preProcess argument vanished, meaning I cannot remove the NZVs anymore. This is really a mess ...

Save the array numeric values in reverse in another array, then store the result in a variable as a numeric value

Posted: 27 Aug 2021 08:01 AM PDT

In general, in the following code, my goal was to store the values of the array from end to begining in a new array, then display it as a number, Of course, in the meantime, I doubled the value of each array cell.

I want to know is there an easier way?

let firstArray = [1, 2, 3];  const secondArray = [];  firstArrayLength = firstArray.length;    let i = 0;  let y = 0;    while (i < firstArrayLength) {    secondArray.push(firstArray.pop());    i++;  };    secondArrayLength = firstArrayLength;    while (y < secondArrayLength) {    if (y == 0) {      secondArray[y] = secondArray[y] * 100;      secondArray[y] = secondArray[y] * 2;    }    if (y == 1) {      secondArray[y] = secondArray[y] * 10;      secondArray[y] = secondArray[y] * 2;    }    if (y == 2) {      secondArray[y] = secondArray[y] * 1;      secondArray[y] = secondArray[y] * 2;    }    y++;  }    let sum = 0;    for (let i = 0; i < secondArray.length; i++) {    sum = sum + secondArray[i];  }    console.log(sum);

Can I use memory after pointer deinitialization?

Posted: 27 Aug 2021 08:01 AM PDT

Can I use memory after pointer deinitialization?

e.g.

let q = UnsafeMutablePointer<Float>.allocate(capacity: 1)  q.pointee = 123.125  let bq = UnsafeRawBufferPointer(start: q.deinitialize(count: 1), count: 4) // (*)  for i in bq.reversed() {      print(String(i, radix: 16), terminator: " ")  }    q.deallocate()  print()  

It's my core solution of this task: https://pl.spoj.com/problems/PP0504D/

Problem in the task is simple: Write a function which show binary representation of Float value.

float2binary(123.125) prints 42 f6 40 0 But that is not the crux of the problem.

I'm not deeply in pointers. My doubt is: May I use memory after deinitialization which is points by another pointer (this memory is NOT deallocated)? What does deinitialization really mean?

let p = UnsafeMutablePointer<Int>.allocate(capacity: 1)  p.initialize(to: 7)  print(p.pointee)  p.initialize(to: 9)  p.deinitialize(count: 1)  // something may crash the memory in this place?  print(p.pointee)  p.deallocate()  

Anyone can show me the code that causes the crash after deinicialize(count:) ?

Django / DRF - Got AttributeError when attempting to get a value for field `users_answers_set` on serializer `TestTakerSerializer`

Posted: 27 Aug 2021 08:01 AM PDT

everyone. Working with DRF gave me this error:

models.py:

class TestTaker(models.Model):      user = models.ForeignKey(User, on_delete=models.CASCADE)      test = models.ForeignKey(Test, on_delete=models.CASCADE)        class UsersAnswers(models.Model):      test_taker = models.ForeignKey(TestTaker, on_delete=models.CASCADE)      question = models.ForeignKey(Question, on_delete=models.CASCADE)      answer = models.ForeignKey(Answer, on_delete=models.CASCADE)       

serializers.py

class UsersAnswersSerializer(serializers.ModelSerializer):      class Meta:          model = UsersAnswers          fields = "__all__"      class TestTakerSerializer(serializers.ModelSerializer):      users_answers_set = UsersAnswersSerializer(many=True)        class Meta:          model = TestTaker          fields = "__all__"  

And I get:

Got AttributeError when attempting to get a value for field `users_answers_set` on serializer `TestTakerSerializer`.  The serializer field might be named incorrectly and not match any attribute or key on the `TestTaker` instance.  Original exception text was: 'TestTaker' object has no attribute 'users_answers_set'.  

I tried to add "source" parameter to users_answers_set, but nothing changed. Thank you.

How can I retain the information entered into a simple form even upon refresh button or revisiting using "localstorage"?

Posted: 27 Aug 2021 08:01 AM PDT

How can I retain the information entered into a simple form even upon refresh button or revisiting using localstorage? If there is an option for user to choose not retain the data please specify that too??

[my form][1]

the info once entered must be there upon refresh [1]: https://i.stack.imgur.com/KUC1e.png

Google App Script does not enter the function

Posted: 27 Aug 2021 08:01 AM PDT

Google App Script doesnt seem to enter into a function. The logs show that the variables before the function were all initialized, which means the custom function is working. I also tested it an hour ago, and my custom function worked.

enter image description here

I also have other script files with functions but the only global varialbe is from a Spreadsheet.getActiveSpreadsheet();

enter image description here

Logs:

7:40:47 PM  Notice  Execution started  7:40:48 PM  Info    Mapped named ranges.  7:40:51 PM  Info    Initialized SyncData variables...  7:46:47 PM  Error   Exceeded maximum execution time  

My code is pretty simple as I was just testing a custom function. My goal is to TEST a function that does a batch retrieve of all named ranges instead of doing it one by one.

/****   retrieve settings   ******/  //const DataSourceRange       = ranges.get("DataSourceRange").getValue();  let ranges = mapNamedRanges(thisSpreadSheet.getNamedRanges());  const TrackerHeaderRow      = ranges.get('TrackerHeaderRow').getRange().getValue();  const firstRowTrackerData   = TrackerHeaderRow + 1;    const FirstColHeaderName    = ranges.get("FirstColHeaderName").getRange().getValue();    /****   setting up sheets    ******/  const TrackerSheetName      = ranges.get("TrackerSheetName").getRange().getValue();  const QuerySheetName        = ranges.get("QuerySheetNameSetting").getRange().getValue();    const trackerSheet          = thisSpreadSheet.getSheetByName(TrackerSheetName);  const querySheet            = thisSpreadSheet.getSheetByName(QuerySheetName);    Logger.log('Initialized SyncData variables...')    function testRange(){    Logger.log('Testing ranges mapping');    let ranges1 = mapNamedRanges(thisSpreadSheet.getNamedRanges());    Logger.log('ranges len = ' + ranges.size);    //Logger.log(ranges1);      const trackerSheetNameRange = ranges1.get('TrackerSheetName').getRange();      Logger.log(trackerSheetNameRange.getValue());      //testing for sheets        Logger.log('Testing sheets mapping');    const sheets = thisSpreadSheet.getSheets();    const sheet = mapSheetNames(sheets);    Logger.log('sheet sample: ' + sheet.get("SLI Tracker"));      for( var i in sheets ) {     Logger.log('sheet: '+ sheets[i]);    }     }  

Custom functions:

/**   * @param {Array} namedRangesArray - requires a multidimensional array consisting the properties and content of the namedRange   * @return {Map} returns a keyed/mapped array   */  function mapNamedRanges(namedRangesArray) {    let map = new Map();      //Logger.log('namedRanges length: ' + namedRangesArray.length);      for (i=0; i < namedRangesArray.length; i++){      map.set(namedRangesArray[i].getName(),namedRangesArray[i]); //key, value    }        Logger.log('Mapped named ranges.');      return map;  }    /**   * @param {Array} sheetsArray - an array of sheets   * @return {Map} returns a keyed/mapped array   */  function mapSheetNames(sheetsArray) {    let map = new Map();      for (i=0; i < sheetsArray.length; i++){      map.set(sheetsArray[i].getName(),sheetsArray[i]); //key, value    }      return map;  }  

To add:

onOpen() function seems to be running forever too...

enter image description here

Code below for onOpen trigger function:

function onAppOpen() {     const ui = SpreadsheetApp.getUi();    ui.createMenu('⚙️ SLI Tools')      .addSubMenu (ui.createMenu('Tracker')        .addItem('↺ Refresh data', 'refreshDataToTrackerAlert')        .addItem('⇧ Upload changes', 'uploadChangesAlert')        .addItem('⇧ Upload ALL rows', 'uploadAllChangesAlert')               .addSeparator()               .addItem('✕ Clear data', 'clearDataAlert')                )      .addSubMenu(ui.createMenu('Billing')        .addItem('⇩ Export to PDF', 'printToPdf')               .addSeparator()               .addItem('🖌 Format tables', 'formatDataTable')       )      .addSubMenu(ui.createMenu('Uploader')        .addItem('⇧ Upload new JO', 'uploadDataToSourceAlert')               .addSeparator()               .addItem('✕ Clear data', 'clearUploaderDataAlert')      )             .addSeparator()       .addSubMenu(ui.createMenu('Data')        .addItem('↺ Refresh background query', 'refreshQueryAlert')      )        .addToUi();    }  

The sheet itself also seems to reload forever.

enter image description here

This shows that the file is connected to the internet and not disconnected.

enter image description here

Update:

It seems to be working again. Could it be the GAS servers malfunctioning?

Update 2:

I haven't changed the code for the function in this test. The last 2 runs had an average of 19 seconds runtime.

After some minutes, the script gets stuck again.

enter image description here

Chrome also isnt at full CPU although it is expected to hog the memory with 4 tabs running.

enter image description here

How does scanf know if it should scan a new value?

Posted: 27 Aug 2021 08:00 AM PDT

I'm studying about how scanf works.

After scanned other type variable, char variable stores a white-space('\n') by getchar() or scanf("%c"). To prevent this, they should clear buffer. And I did it with rewind(stdin)

though stdin is rewinded previous input value is keeping in buffer. and I can do something with the previous value normally.(nothing runtime errors) but if I try scanf again, scanf will scan a new value even there is a normal value in buffer. how does scanf determine if it should scan a new value?

I found this mechanism with below code.

#include <stdio.h>  #define p stdin    int main() {      int x;      char ch;        void* A, * B, * C, * D, * E;        A = p->_Placeholder;      printf("A : %p\n", A);//first time, it shows 0000      scanf_s("%d", &x);        B = p->_Placeholder;      printf("B : %p\n", B);//after scanned something, I think it's begin point of buffer which is assigned for this process      rewind(stdin);//rewind _Placeholder         C = p->_Placeholder;      printf("C : %p\n", C);//it outputs the same value as B - length of x        D = p->_Placeholder;      printf("D : %c\n", ((char*)D)[0]);//the previous input value is printed successfully without runtime error. it means buffer is not be cleared by scanf      scanf_s("%c", &ch, 1);//BUT scanf knows the _Placeholder is not pointing new input value, so it will scan a new value from console. How??        E = p->_Placeholder;      printf("E : %p\n", E);      printf("ch : %c\n", ch);  }  

Woocommerce new order additional email recipient added in order meta

Posted: 27 Aug 2021 08:01 AM PDT

I'm trying to add an additional recipient to the customer order confirmation email.

I have added a meta value for the additional recipients email address into the order successfully and have hooked into some of the emails, however, I am finding it tricky to find the hook for the conformation email.

My code:

add_filter('woocommerce_email_recipient_customer_processing_order', 'ddl_additional_email_checkout', 10, 2);  add_filter('woocommerce_email_recipient_customer_completed_order', 'ddl_additional_email_checkout', 10, 2);  add_filter('woocommerce_email_recipient_customer_invoice', 'ddl_additional_email_checkout', 10, 2);  add_filter('woocommerce_email_recipient_customer_invoice_paid', 'ddl_additional_email_checkout', 10, 2);  add_filter('woocommerce_email_recipient_customer_note', 'ddl_additional_email_checkout', 10, 2);  function ddl_additional_email_checkout($emails, $object){            $additional_email = get_post_meta($object->id, 'additional_recipient', true);            if( $additional_email ){          $emails .= ',' . $additional_email;      }        return $emails;    }  

Ideally I'd hook into something like woocommerce_email_recipient_customer_new_order but that does not appear to be an option.

Many thanks.

Extracting data based off of values in a column - Excel

Posted: 27 Aug 2021 08:01 AM PDT

How would I set up a sheet that extracts data from a table with selected rows based off of the values from a column. In this example, I have 5 types of Chips with respective information for each. I attempted to use Filter( ) but it did not appear as an option in my version of Excel.

I have a column simply listing Food Items, "Chip 1","Chip3","Chip4". I would like to have the second table show information for only Chips 1,3,4 on another sheet. This criteria column will likely change as well so the final table must reflect that each time it changes.

Thanks!

Edit Criteria Table

Food Item
Chip 1
Chip 3
Chip 4

Original table

Food Item Caloric Count Percentage of Protein Percentage of Fat
Chip 1 111 1% 2%
Chip 2 500 3% 2.5%
Chip 3 40 .4% .5%
Chip 4 50 .5% .5%
Chip 5 372 3% 5%

Table 2

Food Item Caloric Count Percentage of Protein Percentage of Fat
Chip 1 111 1% 2%
Chip 3 40 .4% .5%
Chip 4 50 .5% .5%

EDIT I went searching for a solution. Lookup value is in table 'Criteria' row J15 and would match one of the values in 'Data' Column A, the table where rows to be extracted from. I still get an error where Excel thinks I am mistakenly trying to type a formula. I've been trying to work on this for hours, thanks for all the help thus far.

Link for reference: https://www.reddit.com/r/excel/comments/8etavq/return_all_rows_that_match_a_certain_criteria_on/dxxyyta/

=INDEX('Data'!A1:A124,SMALL(IF('Data'!$A$5:$A$124='Criteria'!$J$15,ROW('Data'$A$5:$A$124)-ROW(INDEX('Data'$A$5:$A$124,1,1))+1),row()-2))

Livewire: Trying to get property 'id' of non-object generating code from foreach

Posted: 27 Aug 2021 08:01 AM PDT

I'm new to Livewire and I encounter an error which origin I don't know.

I made a page with a list of simple objects (id, name, and description). The page has a list of all the items available and I want to click on that list to view the item properties or a button to delete the item.

That list is made with this foreach:

@foreach($listaTareas as $t)    <div class="data col-12" wire:click="show({{ $t->id }})">      <label>{{ $t->nombre }}</label>      <label class="hint">ID: {{ $t->id }}</label>      <button type="button" class="btn btn-danger" wire:click="delete({{ $t->id }})"><i class="fas fa-trash"></i></button>    </div>  @endforeach  

Which renders perfectly

List rendered

However, clicking on any div or in the trash can button results in error Trying to get property 'id' of non-object pointing at <div class="data col-12" wire:click="show({{ $t->id }})">.

If I delete the show and delete attributes (and modify the livewire component consequentely) leaving something like this:

@foreach($listaTareas as $t)    <div class="data col-12" wire:click="show">      <label>{{ $t->nombre }}</label>      <label class="hint">ID: {{ $t->id }}</label>      <button type="button" class="btn btn-danger" wire:click="delete"><i class="fas fa-trash"></i></button>    </div>  @endforeach  

I still get the same error, this time pointing at <label>{{ $t->nombre }}</label>, so crearly there is something obvious I'm doing incredibly wrong. I have heard about the wire:key attribute but I don't know how to use it for my purposes.

All the code:

Livewire view

<div class="row align-items-start">      <!-- Sección de la lista de tareas -->      <div class="col-5">          <div id="listado" class="contenedor-data">                <div id="add">                  <label for="btnadd" class="info">Puedes añadir una tarea con este botón...</label>                  <button id="btnadd" type="button" class="btn btn-primary" wire:click="create">Añadir</button>              </div>                @foreach($listaTareas as $t)                  <div class="data col-12" wire:click="show({{ $t->id }})">                      <label>{{ $t->nombre }}</label>                      <label class="hint">ID: {{ $t->id }}</label>                      <button type="button" class="btn btn-danger" wire:click="delete({{ $t->id }})"><i class="fas fa-trash"></i></button>                  </div>              @endforeach                        <div id="coletilla">                  <a class="btn btn-primary" href="#add" role="button">&nbsp;<i class="fas fa-angle-up"></i>&nbsp;</a>              </div>            </div>      </div>      <!-- Sección del desglose de tareas -->      <div class="col-7">          <div id="desglose" class="contenedor-data">                <div class="form-group">                  <label for="nombre">Tarea:</label>                  <label id="id_tarea" class="hint">{{ $tid }}</label>                  <input type="text" class="form-control" id="nombre" placeholder="Nombre de la tarea" wire:model="nombre">              </div>                            <div class="form-group">                  <label for="descripcion">Descripción</label>                  <textarea class="form-control" id="descripcion" aria-describedby="hint" wire:model="descripcion"></textarea>                  <small id="hint" class="form-text text-muted">Aquí va la descripción de la tarea.</small>              </div>                            <div>                  <button id="btnadd" type="button" class="btn btn-success" wire:click="create">Añadir</button>                  <button id="btnmod" type="button" class="btn btn-primary">Modificar</button>                  <button id="btndel" type="button" class="btn btn-danger">Eliminar</button>              </div>            </div>      </div>  </div>  

Livewire Component

<?php    namespace App\Http\Livewire;    use Livewire\Component;  use App\Models\Tarea;    class Index extends Component  {        // Atributos de tareas      public $tid;      public $nombre;      public $descripcion;        // Listado tareas      public $listaTareas = array();        public function create() {          $tarea = new Tarea;            $tarea->nombre = $this->nombre;          $tarea->descripcion = $this->descripcion;            if ($tarea->save()) {              $this->tid = 'ID: '.$tarea->id;          }        }        public function show($id) {          /* Just to try if it works */          $this->descripcion = "Show $id";      }        public function delete() {          /* Just to try if it works */          $this->descripcion = "Delete $id";      }        private function rellenarTareas() {          $tareas = Tarea::get();            foreach($tareas as $tarea) {              $this->listaTareas[] = $tarea;          }      }        public function mount()      {          // Rellenamos la lista con las tareas que ya existen          $this->rellenarTareas();      }        public function render()      {          return view('livewire.index');      }  }  

Mac with two Python version (2.7 and 3.9) but pointing to 2.7 [closed]

Posted: 27 Aug 2021 08:00 AM PDT

I'm trying to install AWS cli (https://docs.aws.amazon.com/cli/latest/userguide/install-macos.html) in my mac (Big Sur 11.5.2).

When I try I got an error saying python 2.7 is old and I need at least python 3.6. I found that I have two python versions installed:

which python  => /usr/bin/python    python -V  => Python 2.7.16    which python3  => /usr/local/bin/python3     python3 --version  => Python 3.9.6    

I have two options: 1- Uninstall python 2.7. But it seems that it is a bad idea (How to uninstall Python 2.7 on a Mac OS X 10.6.4?) 2- Keep both python versions, but how do I make AWS use python 3.9.6 instead of python 2.7?

I want to understand how to put 2 (and more) images on top of each other

Posted: 27 Aug 2021 08:01 AM PDT

So I made a page that just has 2 images with 2 texts next to them. I don't understand how to make them on top of each other instead of next to each other

Example of how I want it

And this is the code.

  <head>          <meta name="viewport" content="width=device-width, initial-scale=1.0" />      <title>Dog and Cat</title>        <style>        body {          margin: 0;        }        .box {          position: relative;          display: inline-block;        }        .box .text {          position: absolute;          z-index: 999;          margin: 0 auto;          left: 100%;          right: 0;          top: 30%;          text-align: center;          width: 60%;        }        img {          margin: 0;          height: 200px;          padding: 5%;          border-radius: 10%;        }      </style>    </head>    <body>      <div class="box">        <img          src="https://images.unsplash.com/photo-1543466835-00a7907e9de1?ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8ZG9nfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"          alt="dog"        />        <div class="text">          <h2></h2>        </div>      </div>      <div class="box">        <img          src="https://images.unsplash.com/photo-1519052537078-e6302a4968d4?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTR8fGNhdHxlbnwwfDB8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"          alt="cat"        />        <div class="text">          <h2>cat</h2>        </div>      </div>    </body>  </html>  

Treatment asa binary variable

Posted: 27 Aug 2021 08:00 AM PDT

Could anyone may help me to fix this error?

Error: The treatment must be a binary variable.  

Trying keeping on running such following code lines and cannot figure out where the problem is and why this is occurring, although after running the mutate function, which is required mutually by the matchit function.

    library(Matching)      library(MatchIt)      library(cobalt)      library(WeightIt)      library(twang)      library(tidyverse)      library(Hmisc)      library(emmeans)      library(rms)      library(rpart)       library(randomForest)      library(survey)      library(glue)      library(nnet)                set.seed(1)          matching_lg_1 <- map(            .x = ratios, ~ matchit(              procedure ~ age + sub_id + intermacs_iv + gender + bsa + redo +                ef + days_cvvh_preop, data = cardio_db_matched %>%               mutate(procedure = if_else(procedure =='proc_1', 1, 0), .data = cardio_db_matched),               distance = "logit", method = "nearest", ratio = .x, caliper = 0.2,              m.order = "random", replace = FALSE            )          ) %>%            set_names(x = ., nm = c("ratio_1:1", "ratio_1:2"))  

The variable in the original dataset may assume the following values: proc_1 proc_2

Thanks for paying attention.

Dynamically add json object into array with jq

Posted: 27 Aug 2021 08:01 AM PDT

Below is the template of my employee.json file

{      "orgConfig": {          "departments": []      }  }  

where departments will have array of departments like below

{      "name" : "physics",      "id" : "1234",      "head" : "abcd"  }  

similarly

{      "name" : "chemistry",      "id" : "3421",      "head" : "xyz"  }  

so the final array structure i want to construct is as below

{      "orgConfig": {          "departments": [              {                  "name" : "physics",                  "id" : "1234",                  "head" : "abcd"              },              {                  "name" : "chemistry",                  "id" : "3421",                  "head" : "xyz"              },              {                  "name" : "Maths",                  "id" : "4634",                  "head" : "jklm"              }          ]      }  }  

Below is the code where i am adding the json elements to an departments array dynamically

#!/bin/bash    source department.properties   # will have departments=physiscs,chemistry,Maths,computers .. etc  IFS=',' read -ra NAMES <<< "$departmentsToImport"    position=0  for i in "${NAMES[@]}"; do      #./jsonfiles will chemistry.json, physics.json, Maths.json etc      value=`cat ./jsonfiles/$i.json`            if [ $position -eq 0 ]      then         cat employee.json | jq --arg value "$value" '.orgConfig.departments[0] |= .+ $value' > tmp.json && mv tmp.json employee.json      else         cat employee.json | jq --arg position "$position" value "$value" '.orgConfig.departments[$position] |= .+ $value' > tmp.json && mv tmp.json employee.json      fi      ((position++))      rm -rf tmp.json  done    exit $?  

but program throws below error

jq: error (at <stdin>:51): Cannot index array with string "1"  

But if use direct index instead of variable position then it works fine.

cat employee.json | jq --argjson value "$value" '.orgConfig.departments[1] |= .+ $value' > tmp.json && mv tmp.json employee.json   

I do not know how many key value maps of departments i have. I cannot hard code the index. Any help to above problem and Dynamically add json object into array?

Thanks

Quartz.NET - Call a function after the Job has completed Full Execution

Posted: 27 Aug 2021 08:01 AM PDT

We are using Quartz.Net to trigger jobs on a schedule in a Windows Service . I have a situation where I have to Trigger a job every 5 minutes from Start DateTime till End DateTime.

After the job is completed we need to calculate the Next Start DateTime and Next End DateTime and save to the DB -

For this I tried to override the JobListener which has a method: JobWasExecuted

public class xPTJobListener : JobListenerSupport  {      public override string Name { get { return "xPTJobListener"; } }        public override void JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException)      {            var dataMap = context.MergedJobDataMap;          var schedule = (MyDTO)dataMap["Schedule"];            using (var logger = new xPTLogger())          {              logger.LogMessage(MessageType.Information, string.Format("Inside JobWasExecuted() - [{0}] - ", schedule.Id));          }            base.JobWasExecuted(context, jobException);      }  }  

and also the TriggerComplete in the TriggerListener

public class xPTTriggerListener : TriggerListenerSupport  {      public override string Name { get { return "xPTTriggerListener"; } }        public override void TriggerComplete(ITrigger trigger, IJobExecutionContext context, SchedulerInstruction triggerInstructionCode)      {            var dataMap = context.MergedJobDataMap;          var schedule = (MyDTO)dataMap["Schedule"];            using (var logger = new xPTLogger())          {              logger.LogMessage(MessageType.Information, string.Format("Inside Trigger Complete - [{0}] - ", schedule.Id));          }              base.TriggerComplete(trigger, context, triggerInstructionCode);        }  }  

But the problem with above methods is that they are both executed each time the job is called.

So if I have a Job which runs from 12:01 AM and ends 12:02 AM every 5 seconds - Both these methods get called 12 times

What I need is to call a method only once after the One Job iteration has Ended - (After the Job is executed 12 Times)?

How do I do this in Quartz?

EDIT

Creating the Triggers

public static ITrigger GenerateTrigger(RouteMonitorScheduleDTO routeSchedule, double fGmtOffset, xPTLogger logger)  {      ITrigger trigger = null;        switch (routeSchedule.ScheduleInfo.PeriodType)      {          case PeriodTypeEnum.Once:              trigger = TriggerBuilder.Create()                          .WithIdentity(string.Format("trigger_{0}", routeSchedule.RouteScheduleId), DefaultGroup)                          .StartAt(routeSchedule.DepartureDateTime)                          .WithSimpleSchedule(s => s.WithIntervalInMinutes(5))                          .EndAt(routeSchedule.ArrivalDateTime.AddMinutes(5))                          .Build();              break;          case PeriodTypeEnum.Daily:          case PeriodTypeEnum.WeekDays:          case PeriodTypeEnum.Weekly:          case PeriodTypeEnum.Monthly:              var schedule = routeSchedule.ScheduleInfo;                      var cronExpresion = xPTCronBuilder.GenerateCronExpression(                                      schedule.PeriodType,                                                               schedule.ScheduleStringValue,                                       fGmtOffset,                                                   routeSchedule.DepartureDateTime,                                      routeSchedule.ArrivalDateTime.AddMinutes(5), 5);              trigger = TriggerBuilder.Create()                          .WithIdentity(string.Format("trigger_{0}", routeSchedule.RouteScheduleId), DefaultGroup)                          .WithCronSchedule(cronExpresion)                          .Build();              break;      }        return trigger;  }  

EDIT Trigger with Cron:

trigger = TriggerBuilder.Create()  .WithIdentity(string.Format("trigger_{0}", 1), "Group1")  .WithCronSchedule("0 0-45/5 7-7 ? * TUE,WED *").Build();  

As you can see from above cron expression it will run from 7 AM to 7:45 AM every 5 minutes every Tuesday and Wednesday.

So 1 iteration is 7AM to 7:45 AM on Tuesday, the Next is 7 AM to 7:45 on Wednesday. I need to call a function after each Iteration has completed.

So let's say that when the Last Trigger is fired for 7:45 AM on Tuesday - I need to call the function.

Hierarchical package structure in Eclipse

Posted: 27 Aug 2021 08:02 AM PDT

I am working with eclipse on an android project. I want to have packages inside of packages inside of packages and so on...

The problem is I can only have 1 type of subpackage. (I want more depth) At the moment my project looks like this:

- com.company.main    - subpackone      + class1      + class2      + class3    - subpacktwo      + class4    - subpackthree      + class5  

But what I want is something like this:

- com.company.main    - subpackone      + class1      + class2      + class3      - subpacktwo        + class4        - subpackthree          + class5  

When I try to create more packages inside of subpackages it just changes the name of the already existing subpackage. I already set the Package Presentation to Hierarchical in eclipse.

Fit cell width to content

Posted: 27 Aug 2021 08:00 AM PDT

Given the following markup, how could I use CSS to force one cell (all cells in column) to fit to the width of the content within it rather than stretch (which is the default behaviour)?

<style type="text/css">  td.block  {  border: 1px solid black;  }  </style>  <table style="width: 100%;">  <tr>      <td class="block">this should stretch</td>      <td class="block">this should stretch</td>      <td class="block">this should be the content width</td>  </tr>  </table>  

EDIT: I realize I could hard code the width, but I'd rather not do that, as the content which will go in that column is dynamic.

Looking at the image below, the first image is what the markup produces. The second image is what I want.

enter image description here

No comments:

Post a Comment