text:
Q: What is the recommend way to arrive at AngularJS 1.5.+, with LiveReload when upgrading from 1.3.7? I have a Wakanda 10, community version, solution that uses AngularJS 1.3.7, and it does not yet use LiveReload.
I want to upgrade to Wakanda 11, community version,AngularJS 1.5+, with LiveReload.
What is the simplest way to do this?
I understand that I may have to do coding changes.
Should I download the Wakanda 11, community version, and start a new project with it that has LiveReload built-in, and then copy my Project into it and debug?

A: In order to upgrade your application you have two face two different problematics:
A) Upgrade AngularJS from 1.3.7 to 1.5.x.
This step is pretty straight-forward. It's necessary to replace your AngularJS library inside your application with the version you desire.
If a bower.json is included in your application (and it should be since we are speaking of a Wakanda scaffolded application) then you can modify the following lines:
"dependencies": {
  "angular": "~1.4.4",
  "angular-wakanda": "~1.0.4"
}

and run in terminal from the folder of the application the command bower update to do it automatically.
Update angular-wakanda to the latest compatible version.
Please note that you are upgrading minor versions of AngularJS and probably also angular-wakanda. Minor changes in API and methods can be present and break your application.
B) Add live-reload to your application
Many efforts have been done in the latest Wakanda Studio versions to achieve agnostic compatibility with different scaffoldings. Adding live-reload to your Wakanda application means adding a standard live-reload kit as you normally do with web applications.
It can be made with Gulp, Webpack, Grunt, Browserify. Wakanda Studio would try to run any environment.
Since the angular-wakanda + Gulp live-reload environment is the one included in the actual scaffolding, I suggest you to start with it as follows:

*

*In the package.json file add the following devDependencies:
"devDependencies": {
  "gulp": "^3.9.0",
  "gulp-connect": "^2.2.0",
  "http-proxy-middleware": "^0.9.0",
  "minimist": "^1.2.0"
}

*In order to trigger gulp, add to the same files the following scripts to your package.json file:
"scripts": {
  "serve": "gulp serve",
  "start": "npm run serve"
}

*Create or copy from an existing Wakanda solution the gulpfile.js file. You can copy this gulpfile.js if you prefer a more generic approach than the actual included in the base solution. It's important to adapt the configuration parameters to your actual application scaffolding if necessary:
var defaultOptions = {
  default: {
    serverUrl: 'http://127.0.0.1:8081',
    port: 8000,
    livereloadPort: 35729,
    app: 'app/',
    output: 'app/',
  }
};

*Finally re-open the solution and click Run Page. This should trigger an npm install and an npm start, which will trigger gulp serve which will enable live-reload.
Please note that the implementation can have minor configuration differences depending on the Wakanda Studio version you are using. I suggest you to always update to the latest available.
For a deeper understanding on Wakanda Studio build process I also suggest you to check out this tutorial which also explain how to add SASS precompilation to the application.


text:
Q: jQuery: Append child element before child element I have an HTML code like this:

I want to append child elements inside div#content before the div.foobar element. How can do that?

A: You can use before()/insertBefore() like
$('#content .foobar').before(newcontent)
$(newcontent).insertBefore('#content .foobar')

or if you want to insert new content as the first child of #content then use prepend()
$('#content').prepend(newcontent)

A: Before I answer your question let me make something more clearer and easier to u so that you understand what your trying to
Append  means you can insert elements as child elements at the end of the selector
example append() and appendTo()
Prepend  means you can insert elements as child elements at the beginning of the selector
example prepend() and prependTo()
Notice that selector will be considered as a parent
Before means you can add elements just before the selector
example before() and insertBefore()
After means you can add elements just after the selector
example after() and insertAfter()
before and after does not treat selector as a parent element
Now to answer your question
You can do it using prepend or before

$("your element").insertBefore("#content div.foobar") // or
$("#content div.foobar").before("element") // or
$("#content").prepend("element") // or
$("element").prependTo("#content")

Notice the selector positions in prepend() and prependTo()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Vuejs, Dynamic b-table with editable fields and two-way databinding I'm trying to generate a dynamic b-table with editable fields and with two-way databinding.
I would like to not have any hardcoded values. Now, I have:
<b-table striped hover :items="filtered">
    <template v-slot:cell(issueDescription)="row">
      <b-form-input v-model="row.item.issueDescription" />
    </template>
    <template v-slot:cell(endTime)="row">
      <b-form-input v-model="row.item.endTime" />
    </template>
    <template v-slot:cell(startTime)="row">
      <b-form-input v-model="row.item.startTime" />
    </template>
</b-table>

Where:
filtered = [ { "issueDescription": "this is a description", "endTime": "2020-02-11T14:00:00.000Z",
"startTime": "2020-02-11T01:24:00.000Z" }]

If I generate template with a v-for, then I got editable fields in every column, but no binding at each field.
<b-table striped hover :items="filtered">
    <template v-for="x in filtered" v-slot:cell()="row">
      <b-form-input v-model="row.item.BIND_TO_SPECIFIC_TABLE_ROW_COL" />
    </template>
</b-table>

How do I bind to the specific row,col??
I've made a fiddle: https://jsfiddle.net/gfhu1owt/

A: If you want to have ALL fields editable, you can use this syntax.
<template v-slot:cell()="{ item, field: { key } }">
  <b-form-input v-model="item[key]" />
</template>

It's pretty similar to what you had. You just needed to use the key from the slot context object. (I've shorthanded it a bit, but it's the same as going row.field.key).
Also note that i don't use a v-for in the template, this is because v-slot:cell() is a fallback slot which is valid for all slots unless a specific one is defined. For example v-slot:cell(issueDescription) would overwrite v-slot:cell() for the issueDescription field.
While the above works, the problem might come one day when you have a field you DONT want to be editable, like maybe an id field in your object.
To solve this issue, I've defined my fields and passed them to the table. I've also added a editable property to the fields i want to be editable. (note this is not a standard thing in the field object, but something specific for you use-case).
I then created a computed property editableFields which returns all fields that have editable: true, and then use editableFields in my v-for inside b-table.
This way you can pick and choose which properties you want to be editable in your objects.

new Vue({
  el: "#app",
  computed: {
    editableFields() {
      return this.fields.filter(field => field.editable)
    }
  },
  data: {
    filtered: [
      {
        "id": "1",
        "issueDescription": "this is a description",
        "endTime": "2020-02-11T14:00:00.000Z",
        "startTime": "2020-02-11T01:24:00.000Z"
      },
      {
        "id": "2",
        "issueDescription": "this is a description",
        "endTime": "2020-02-11T14:00:00.000Z",
        "startTime": "2020-02-11T01:24:00.000Z"
      }
    ],
    fields: [
      { key: 'id', label: 'ID' },
      { key: 'issueDescription', label: 'Issue Description', editable: true },
      { key: 'startTime', label: 'Start Time', editable: true },
      { key: 'endTime', label: 'End Time', editable: true }
    ]
  }
})
<link href="https://unpkg.com/bootstrap@4.4.1/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://unpkg.com/bootstrap-vue@2.4.1/dist/bootstrap-vue.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
<script src="https://unpkg.com/bootstrap-vue@2.4.1/dist/bootstrap-vue.min.js"></script>

<div id='app'>
  <b-table :items="filtered" :fields="fields">
    <template v-for="field in editableFields" v-slot:[`cell(${field.key})`]="{ item }">
      <b-input v-model="item[field.key]"/>
    </template>
  </b-table>
</div>


text:
Q: Change decimal number(dynamically changed) style to roman or katakana in some html tag (or div, class, id etc.) using html+css? Searched everywhere but found only list styling guides and counter styling guides in css that didn't worked out.
So I have for e.g. <html-tag class="class" id="id">23</html-tag> number inside html-tag is changed dynamically(counter) using vue watch. I want to display number in upper roman or katakana (basically any known formats that supported by modern browsers)
The preferred answer is simple html+css or short js implementation

A: You need Intl.NumberFormat
For example
// the nu extension key requests a numbering system, e.g. Chinese decimal
console.log(new Intl.NumberFormat('zh-Hans-CN-u-nu-hanidec').format(number));
// → 一二三,四五六.七八九

A: For Roman Numerals 1-99 you could use a function like this:

function convertToRoman(num) {
  const units = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'];
  const tens = ['X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'];
  let numArr = [];

  for (let i = 0; i < 99; i++) {
    numArr.push(i);
  }

  const roman = numArr.map(i => {
    if ((i + 1) % 10 == 0) return tens[(i + 1) / 10 - 1];
    else if (i < 10) return units[i];
    else return `${tens[Math.floor(i / 10) - 1]}${units[i.toString().split("")[1]]}`;
  });

  return roman[num - 1];
}

console.log(convertToRoman(23))


text:
Q: Determine whether the given formula represents an inner product or not . Problem
In the linear space of all real polynomials , determine whether or not $(f,g)$ is an inner product if$(f,g)$ is defined by the formula given .
$a) (f,g) = f(1)g(1)$
$b)(f,g) = |\int_{0}^{1} f(t)g(t) dt|$
$c) (f,g)= \int_{0}^{1} f'(t)g'(t) dt$
$d) (f,g) = (\int_{0}^{1} f(t) dt)(\int_{0}^{1} g(t) dt)$
Attempt
$a,c,d$ represents inner product as all are commutative,distributive, homogeneous and positive
$b$ is not homogeneous .So it does not represents inner product.
In solving $c)$ i have assumed functions to be continuous ( don't know whether this assumption is valid or not.)
Is my attempt correct?
Any help or suggestion will be appreciated

A: Recall that in order to be an inner product, $(.|.)$ has to be :
$\cdot$ Commutative : $\forall f,g\in\mathbb{R}[X],(f|g)=(g|f)$
$\cdot$ Linear with respect to the first (or the second) argument : $\forall f,g,h\in\mathbb{R}[X], \forall \lambda \in \mathbb{R}, (f+\lambda h|g)=(f|g)+\lambda(h|g)$ (This is what you call "distributive")
$\cdot$ Positive and homogenous : $\forall f\in\mathbb{R}, (f|f)\geq0 \text{ and} (f|f)=0 \Leftrightarrow f=0$
Now :
a) is not an inner product because it is not homogenous :
$$(f|f)=0 \Leftrightarrow f(1)^2=0 \Leftrightarrow f(1)=0$$
Which is not equivalent to $f=0_{\mathbb{R}[X]}$ (take X-1 as a counter-example)
b) nether : it is not symetrical with respect to the first argument (nor the second), due to the fact that $|a+b|=|a|+|b| is false in general.
c) nether ; it is not homogenous :
$$(f|f)=0 \Leftrightarrow \forall x\in(0,1),f'(x)=0 \Leftrightarrow f \text{ is constant on (0,1)}$$
Which is not equivalent to $f=0_{\mathbb{R}[X]}$ (take f(X)=1 as a counter-example)
d) nether, because it is not homogenous :
$$(f|f)=0 \Leftrightarrow \left(\int_0^1f(x)\text{d}x\right)^2=0 \Leftrightarrow \int_0^1f(x)\text{d}x=0$$
Which is not equivalent to $f=0_{\mathbb{R}[X]}$ (take f(x)=1-2x as a counter-example).


text:
Q: String.format() "%11.2lf" of C++ is equivalent to ?
You guys have any resource that shows the equivalent formats for both Java and C++?

A: Short answer: The Java equivalent is "%11.2f".
In C's printf() (but not scanf()), %f and %lf are equivalent; Both take a double argument.
In Java's Formatter.format(), %f is legal but %lf is not.  %f works for Float, Double and BigDecimal values.

A: C++ cpplusplus.com or MSDN
Java Sun javadocs

A: Boost Format. http://www.boost.org/doc/libs/1_37_0/libs/format/doc/format.html#syntax
It has the basically the same formatters as printf().
But they are type safe and can be used on streams.


text:
Q: How to obtain Facebook user access token using new Facebook SDK We intend to switch to Facebook PHP SDK 4.0.0 using Graph API v.2.2. I am very new to this new Facebook SDK and I am playing around it a bit. In this moment I am trying to get the privileges, like this:
/* PHP SDK v4.0.0 */
/* make the API call */
Facebook\FacebookSession::setDefaultApplication($appID, $appSecret);
$session = new Facebook\FacebookSession($accessToken);
/* PHP SDK v4.0.0 */
/* make the API call */
$request = new Facebook\FacebookRequest(
  $session,
  'GET',
  '/me/permissions'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();

This is working wonderfully, if I have the correct $appID, $appSecret and $accessToken values. For $appID and $appSecret I see no problem, because they are application-level settings, obtained from the developers page. However, I am struggling about how to get the $accessToken. I have been testing with a user who has a valid facebook access token and I have read the value from the database, but I wonder how could I obtain the following logic:

*

*read access token from database if existent

*check the validity of the access token

*if it is invalid, obtain a new access token

*request for long-lived access token

*set the value of $accessToken to the valid access token obtained from either the database or, if invalid/inexistent, obtained via Facebook SDK.

Note, that I have no problems using the database, so we can skip the steps of loading/storing the access token from/into the database. Does anybody know how can I implement this?

A: The FacebookSession class has a method getToken – so once you've gone through the login flow successfully, it will give you the user's access token. As for checking if a token is still valid, it has a validate method as well.
And checking the token for validity is possible without logging in, you just have to create a session using that token.
And btw., if the user already logged in to your app once, then on subsequent calls to the login dialog they will be redirected straight back from Facebook to your app, without any additional user interaction required (as long as they are logged in to Facebook itself.)


text:
Q: GCS Generate_Signed_Url expires upon loading I am implementing some code to generate a signed url for some images that are specified in a json file, this is the method used to generate them
def geturl(image_name):
    storage_client = storage.Client()
    bucket = 'Bucket Name'
    source_bucket = storage_client.get_bucket(bucket)
    blobs = source_bucket.list_blobs()
    for blob in blobs:
        if image_name == blob.name:
            url_lifetime = 3600
            serving_url = blob.generate_signed_url(url_lifetime)
            return serving_url
    return

after this they are used in an img scr <>, however when loading the page the images do not load and following the url i receive the error
The provided token has expired
Request signature expired at: 1970-01-01T10:00:00+00:00
even when changing the lifetime the error message persists

A: Your parameter url_lifetime is not initialized correctly. The correct meaning is expiration date which is a value in seconds from January 1, 1970 GMT. Your expiration was one hour into 1970.
The correct method is current time + 3600 seconds.
There are many ways to get the current time. Example: int(time.time()) which returns the current time in your timezone in seconds. Typically you will want to convert the current time to GMT and then grab the seconds.
Note: In this answer, I am using GMT in the same usage as UTC.
from datetime import timezone, datetime
int(datetime.now(tz=timezone.utc).timestamp()

A: Let me add two examples:
1
def _sign_gcp_blob_url(verb, obj_path, content_type, expiration):
from oauth2client.service_account import ServiceAccountCredentials

import base64

from six.moves.urllib.parse import urlencode, quote

GCS_API_ENDPOINT = 'https://storage.googleapis.com'

expiration_in_epoch = int(expiration.timestamp())

signature_string = ('{verb}\n'

                '{content_md5}\n'

                '{content_type}\n'

                '{expiration}\n'

                '{resource}')

signature = signature_string.format(verb=verb,

    content_md5='',

    content_type='',

    expiration=expiration_in_epoch,

    resource=obj_path)

creds =

ServiceAccountCredentials.from_json_keyfile_name(settings.GOOGLE_APPLICATION_CRE
DENTIALS)
signature = creds.sign_blob(signature)[1]

encoded_signature = base64.b64encode(signature)

base_url= GCS_API_ENDPOINT + obj_path

storage_account_id = creds.service_account_email

return '{base_url}?GoogleAccessId={account_id}&Expires={expiration}&Signature={signature}'.format(base_url=base_url,
    account_id=storage_account_id,
    expiration = expiration_in_epoch,
    signature=quote(encoded_signature))

Example 2
https://github.com/GoogleCloudPlatform/storage-signedurls-python/commit/828486a99e34d38fc3ccbb434899284c8b069044


text:
Q: How to sum elements from a List and create sublist with them when they sum to a value of n in Python I am kinda stuck.
So here is my scenario.
I have a list of small file(parquet files). My goal is track them and merge them in a more optimal parquet files size.
While i could just read all and run repartition, this wont apply to my use case, since they share location with other already partitioned files(would be to much to handle in terms of data volume).
So i have list
That looks like this:
[
[('filepath.parquet',1000),
('filepath.parquet',1000)],

[('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000)],

 [('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000)]
]

My Goal is to have max group size parameter that will create sub lists of this lists based on the sum of bytes.
Using my list example with a max_group of 5000 where i have one main list with 3 sub lists i would get:
1 - main list - no change here
1 - sub list 1 would keel all its elements since the sum of the bytes is only 2000
2 - sub list 2 would be split in 2 sub sub lists since the total sum is 8000 and max_group is 5000.
eg:
[('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000)],

[('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000)]

*

*so one sub sub list will be 5000 and the other will be 3000

3 - sub list 3 - will be split in 3 sub sub lists as bellow, again following the same max_group
[('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000)],

[('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000)],

[('filepath.parquet',1000)]

So my final list would be:
[ -- main list
    [ -- sub list
            [ -- sub sub list
            ('filepath.parquet',1000),
            ('filepath.parquet',1000)
            ],

            [
            ('filepath.parquet',1000),
            ('filepath.parquet',1000),
            ('filepath.parquet',1000),
            ('filepath.parquet',1000),
            ('filepath.parquet',1000)
            ],

            [
            ('filepath.parquet',1000),
            ('filepath.parquet',1000),
            ('filepath.parquet',1000)
        ]
    ],

    [
            [
            ('filepath.parquet',1000),
            ('filepath.parquet',1000),
            ('filepath.parquet',1000),
            ('filepath.parquet',1000),
            ('filepath.parquet',1000)
            ],

            [
            ('filepath.parquet',1000),
            ('filepath.parquet',1000),
            ('filepath.parquet',1000),
            ('filepath.parquet',1000),
            ('filepath.parquet',1000)
            ],
    ],
    [
            [
            ('filepath.parquet',1000)
            ]
    ]
]

So i am trying to do this in python:
my code :
lst = [
[('filepath.parquet',1000),
('filepath.parquet',1000)],

[('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000)],

 [('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000),
('filepath.parquet',1000)]
]

max_group  = 5000
i = 0
for k,sublst in enumerate(lst):
    print('entering sublst: ' + str(k))
    for file in sublst:
        f, v = file
        tot = i + v
        print(f)
        while tot <= max_group:
            tot = tot + v

A: Here you are trying to iterate v which is an integer and get a sum. The following is the sum method.
def sum(*args, **kwargs): # real signature unknown
    """
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers

    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may
    reject non-numeric types.
    """
    pass

You need to pass an array to the sum method.
The following code will give you the intended solution.
max_group = 5000
i = 0
final_list = []
for k, sublst in enumerate(lst):
    print('entering sublst: ' + str(k))
    size = 0
    temp_list = []
    for file in sublst:
        f, v = file
        size += v

        if size > max_group:
            final_list.append(temp_list)
            temp_list = [file]
            size = v
        else:
            temp_list.append(file)

    if len(temp_list) > 0:
        final_list.append(temp_list)

First, it will append the v to the size, but it will not append f to the list. If the size is greater than the max_group, the temp_list will be appended to the final_list and initialize the temp_list with the file. Then it will reinitialize size as well. If the size is less than max_group it will keep appending to the temp_list. At the end of the for loop, it will check the temp_list length and if there are leftover elements in the temp_list, the temp list will be appended to the final_list as well.


text:
Q: Azure Remote Desktop - Access Denied I'm currently facing an Access Denied error while connecting to an Azure VM. This VM is registered in an Active Directry. When I log with the AD credentials, I get an "Access Denied" error message with a "Ok" button without any other text on the screen. I never faced this issue before. The maching was working perfectly last week...
Do you have any idea about this issue ?
Thanks for your help
Access Denied Error Screenshot

A: Can you still access the VM and its using your Azure Portal login? If so, try adding the AD user via RDP.

*

*Go to Computer Mgmt on the VM via Remote Desktop

*Expand the list of Remote Desktop Users.

*Select the user(s) to add.

See details in the MSDN thread:
https://social.msdn.microsoft.com/Forums/en-US/9ebce1bb-2aa0-4bb0-adc7-d1e229c5ee9e/add-user-to-remote-desktop-group-in-azure-vm?forum=WAVirtualMachinesforWindows
If you're having RDP issues with the primary user account, check the Settings blade of your VM in the Azure Portal, and look at the Users list under Resource Management.
Hope that helps!

A: I had the same issue, in my case it was related to Terminal Service Licensing.
First save a local copy of the RDP file from the portal and run this command at a PowerShell command prompt to connect. This will disable licensing for just that connection:
mstsc <File name>.RDP /admin

after you are able to connect then open the Event Viewer an look for an Event with ID 4105 in WIndows Logs > System. this event should appear every time a logging was attempted.
If that is the case, follow this steps to solve the issue
Event ID 4105 — Terminal Services Per User Client Access License Tracking and Reporting
Hope this helps.


text:
Q: How to convert dataset of images to tensor? I've got a dataset of images that looks like this:
array([[[[0.35980392, 0.26078431, 0.14313725],
     [0.38137255, 0.26470588, 0.15196078],
     [0.51960784, 0.3745098 , 0.26176471],
     ...,
     [0.34313725, 0.22352941, 0.15      ],
     [0.30784314, 0.2254902 , 0.15686275],
     [0.28823529, 0.22843137, 0.16862745]],

    [[0.38627451, 0.28235294, 0.16764706],
     [0.45098039, 0.32843137, 0.21666667],
     [0.62254902, 0.47254902, 0.36470588],
     ...,
     [0.34607843, 0.22745098, 0.15490196],
     [0.30686275, 0.2245098 , 0.15588235],
     [0.27843137, 0.21960784, 0.16176471]],

    [[0.41568627, 0.30098039, 0.18431373],
     [0.51862745, 0.38529412, 0.27352941],
     [0.67745098, 0.52058824, 0.40980392],
     ...,
     [0.34901961, 0.22941176, 0.15588235],
     [0.29901961, 0.21666667, 0.14901961],
     [0.26078431, 0.20098039, 0.14313725]],

    ...,

What I need is convert it to tensor so that I could pass it to CNN.
I'm trying to do it like that:
from torchvision import transforms as transforms
transform = transforms.Compose([
            transforms.ToTensor(),
            transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
        ])

How can I apply this transform to my dataset? Thanks for any help.

A: you probably want to create a dataloader. You will need a class which iterates over your dataset, you can do that like this:
import torch
import torchvision.transforms

class YourDataset(torch.utils.data.Dataset):
    def __init__(self):

       # load your dataset (how every you want, this example has the dataset stored in a json file
        with open(<dataset-path>, "r") as f:
            self.dataset = json.load(f)

    def __getitem__(self, idx):
        sample = self.dataset[idx]
        data, label = sample[0], sample[1]

        transform = transforms.Compose([
            transforms.ToTensor(),
            transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
        ])
        return transform(data), torch.tensor(label)

    def __len__(self):
        return len(self.dataset)

Now you can create a dataloader:

train_set = YourDataset()

train_dataloader = torch.utils.data.DataLoader(
            train_set,
            batch_size=64,
            num_workers=1,
            shuffle=True,
        )

And now you can iterator over the dataloader in your train-loop:
for samples, labels in self.train_set:
    . . .
    # samples will hold N samples of your dataset where N is the batchsize

If you need more explanation, take a look a pytorchs documentation on this topic.

A: After being initialized a torchvision transform can be called on a PIL image or torch.Tensor depending on the transform (in the documentation you can find precisely what is expected by a given transform). So assuming your transform pipeline is valid (output type for each transform is compatible with input type of following transform) then you can simply call it: transform(data).
This should work with your data since transforms.ToTensor can accept a numpy.ndarray as input

Alternatively, if your dataset is a little more complex than a simple NumPy array. You could implement your own Dataset class which would handle: image fetching in file system, performing relevant transformations, etc... Here's a rough guideline:
class MyDataset(Dataset):
    def __init__(self):
        super(MyDataset, self).__init__()

        # define your data for example a list of images
        self.data = ...

        # define your transform pipline
        transform = transforms.Compose([
            transforms.ToTensor(),
            transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
        ])

    def __getitem__(self, index):
        path = self.data[index]
        img = Image.open(path)
        return self.transform(x)

Where Image is imported from PIL.

For you case, though, you would have something a little simpler:
class MyDataset(Dataset):
    def __init__(self, data):
        super(MyDataset, self).__init__()

        self.data = data

        # define your transform pipline
        transform = transforms.Compose([
            transforms.ToTensor(),
            transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
        ])

    def __getitem__(self, index):
        x = self.data[index]
        return self.transform(x)

And you would pass your numpy.ndarray to the MyDataset's initializer.


text:
Q: Entity Framework 5 library consumers need entity framework dlls? I have a Project "Project.EntityFramework" which contains a context to my db.  When attempting to consume the context from a separate project within the same solution "Project.Business" like:
using (var db = new EntityFramework.Entities())
{
    // Code
}

I get the compiler error on "using":
Error   12  'EntityFramework.Entities': type used in a using statement must be implicitly convertible to 'System.IDisposable'   ....

Now I can F12 and drill down to the Entities, and see it is implementing IDisposable - I can make this error go away if I put reference dlls to entity framework in "Project.Business" but this is defeating the purpose of what I wanted to accomplish - not having any dependency on EF within my Business layer.
Am I doing something wrong?  Or is this just how it has to be?

A: You're not doing anything wrong. If you want the business layer to not depend on EF, you'll need to wrap access to your DbContext class with something else. The Repository pattern is a popular one.

A: To expand on @Spivonious' answer, here is what I did to accomplish the repository pattern on my DbContext - hopefully it's mostly implemented properly :/
public interface IFooEntity : IDisposable
{
    IEnumerable<Foo> Get();
}

public class FooRepository : IFooEntity
{
    private readonly Entities _context;

    public FooService()
    {
        this._context = new Entities();
    }

    public IEnumerable<Foo> Get()
    {
        return _context.Foo;
    }

    public void Dispose()
    {
        _context.Dispose();
    }
}

original code from question:
using (var db = new EntityFramework.Entities())
{
    // Code
}

changed to:
using (var db = new EntityFramework.Repository.FooRepository())
{
    // Code
}

this allowed my code in the separate project to use my repository rather than the context itself, allowing the business project to not have to rely on entity framework references.

A: I had this same issue after adding some code and referencing a DLL with the model in it. After some head scratching I realised I hadn't referenced EntityFramework. The problem went away after adding that.


text:
Q: Understanding DAO-pattern and interfaces I'm reading J. Bloch's effective Java and he said the following:

Once an interface is released and widely implemented, it is almost
  impossible to change.

So, now consider the simple interface for DAO-pattern:
public interface UserDao{

    public User getById(int id);

    public Collection<User> getAll();

    public boolean delete(int userId);

    public boolean update(User u);

}

This is how my Dao interface looked when it was released firstly. By the time, I had to add some functionality to users in order to aggregate all users by its registration_date or something similar. So, I needed to add  corresponding method declarations to the DAO-interface and implement it.
Moreover for now I can't imagine how DAO-interfaces may be more or less stable at all, because adding some new DAO-operations happens very often.
Maybe it's my DAO design disaster, or interfaces are hardly suitable for DAOs?

A: I think that sentence of J. Bloch is meant to public interfaces, and not for your DAO case.
Think of you creating a public API to let any programmer use your platform. If you are changing that interface, your are requiring programmers to adapt his code, so this will be frustrating.
But if you are creating an interface for the purpose of your internal app, you are not assuming that risk, and it is worth to evolve your interface as you need.
Obviously you have to consider how many classes implements your interface and assume the cost of the modification.


text:
Q: Windows API DiInstallDevices causes Exception I am trying to access Win32 APIs to install a driver on a device. I am using a bunch of functions from the setupapi.h, all of which work well. In this piece of code, I am using those to get the parameters (i.e. names of/pointers to device and driver) that are needed to call this install function (which is not part of the setupapi.h but of the newdev.h).
Following is my P/Invoke and the actual method call. I have used the debugger to investigate and I am pretty sure that the information I get from the SetupAPI is correct. (I.e., the parameters are fine, by which I mean that they do contain the desired information.)
IntPtr deviceInfoSet;
Win32SetupApi.SP_DEVINFO_DATA devInfoData;
GetDeviceHandleFromMatch(deviceInfo, out deviceInfoSet, out devInfoData);
Win32SetupApi.SP_DRVINFO_DATA drvInfoData;
GetDriverHandleFromMatch(driverInstance, deviceInfoSet, devInfoData, out drvInfoData);

try
{
   bool needReboot = false;
   Win32SetupApi.DiInstallDevice(
      IntPtr.Zero,
      deviceInfoSet,
      devInfoData,
      drvInfoData,
      0,
      ref needReboot);
}
catch (Exception ex)
{
   throw;
}

[DllImport("newdev.dll", SetLastError = true)]
  public static extern bool DiInstallDevice(
     IntPtr hParent,
     IntPtr lpInfoSet,
     SP_DEVINFO_DATA DeviceInfoData,
     SP_DRVINFO_DATA DriverInfoData,
     UInt32 Flags,
     [MarshalAs(UnmanagedType.Bool)] ref bool NeedReboot);

The exception I get is "Attempt to read/write protected memory", there is no information available via LastWin32Error.
Any thought on what might blow up here ist greatly appreciated!

A: Got it!
[DllImport("newdev.dll", SetLastError = true)]
public static extern bool DiInstallDevice(
    IntPtr hParent,
    IntPtr lpInfoSet,
    ref SP_DEVINFO_DATA DeviceInfoData,
    ref SP_DRVINFO_DATA DriverInfoData,
    UInt32 Flags,
    ref bool NeedReboot);

The structs have to be passed by reference as descrided here. Not sure whether the Bool marshalling was wrong, but I removed that, too.

Can't believe this took hours to figure out again, gotta love P/Invoke. Hope this will help somebody else, too.


text:
Q: Add servlet in a clojure ring project I am integrating Togglz library into a Clojure Ring project to support feature toggles and would like to activate the Togglz admin console. According to the Togglz documentation it is necessary to add a servlet in the /WEB-INF/web.xml file for projects that don't support Servlet 3.0. I used the :uberjar-merge-with leiningen plugin to merge the file with the Togglz servlet configuration with the web.xml file autogenerated by leiningen. However, this was not sufficient to activate the admin console.
I could not find much information on how to integrate a servlet from an external library into a Ring application. What would be the best way to do it?

A: I have not tried it myself, but the lein-servlet library seems to promise to do exactly that


text:
Q: Single parsley.js error message for multiple fields I'm looking for a way to use a single parsley validation error message for a set of input fields. The primary example of this would be for an address input field, but I'm sure others can come up with similar examples where this might be useful.

<input name='address1' data-parsley-maxlength="255" data-parsley-errors-container="#error-container">
<input name='address2' data-parsley-maxlength="255" data-parsley-errors-container="#error-container">
<input name='address3' data-parsley-maxlength="255" data-parsley-errors-container="#error-container">

Using the above code right now would result in 3 different error messages, but I want to set up a scenario where only one message would be displayed if any of the inputs are invalid.
Thanks in advance
Update
After a bit of JS console fun, I think I've found something that works. The idea below is to prevent any UI changes being done by parsley on the group, and to trigger a check on the whole group each time one of the elements are validated. This may not be the best way to do things, but it appears to be working with my single test-case. I'm thinking that this could be re-worked into a validator so that I can re-use it for other sets of inputs in the future.

<input name='address1' data-parsley-ui-enabled='false' data-parsley-trigger='change' data-parsley-group='address-grp' data-parsley-maxlength="255" data-parsley-errors-container="#error-container">
<input name='address2' data-parsley-ui-enabled='false' data-parsley-trigger='change' data-parsley-group='address-grp' data-parsley-maxlength="255" data-parsley-errors-container="#error-container">
<input name='address3' data-parsley-ui-enabled='false' data-parsley-trigger='change' data-parsley-group='address-grp' data-parsley-maxlength="255" data-parsley-errors-container="#error-container">

var $addressFields = $("[data-parsley-group='address-grp']");
addressFields.each(function(index, element) {
  $(element).parsley().on('field:validated', function(parsleyField) {
    var fieldOptions = parsleyField.actualizeOptions().options;
    var classHandler = fieldOptions.classHandler(parsleyField);
    var container = $(fieldOptions.errorsContainer);
    classHandler.removeClass(fieldOptions.successClass);
    classHandler.removeClass(fieldOptions.errorClass);
    var valid = parsleyField.parent.isValid(fieldOptions.group);
    if(valid) {
      console.log("Valid");
      classHandler.addClass(fieldOptions.successClass);
      container.html("");
    } else {
      console.log("Invalid");
      classHandler.addClass(fieldOptions.errorClass);
      container.html("Error");
    }
  });
});

A: You can do this fairly cleverly with a bit of CSS if you add a particular class to your error container.
HTML:

CSS:
.parsely-single-error .filled ~ .filled {
    display: none;
}

Explanation
The CSS reads, "hides any child elements of the error-container that have the class 'filled' and come after another element that has the class 'filled'".  This has the effect of hiding all but the first 'filled' error in the error container.
For reference, the parsely error container looks like this when filled:

This value is required.

This value is required.

This value is required.

A: I'm not sure there a great way to do this.
You could try configuring it so that errors are put in the same container, and then use CSS to only show the :first of them?


text: Q: Firebase database structuring We are working on a mobile app and there are primarily 5 objects added. how should we reference to Other objects data? should we use some id or should full path. What if we dont make duplicate data and use only one reference to update/delete. will it kill the performance? what is the best way to create DB structure for millions of records?


text:
Q: Why is it not required to have '()' at the end of the success function? I got the following code:
navigator.geolocation.getCurrentPosition(
  successFunction
);

I was wondering why it is not required to use the '()' at the end of the succesFunction? Isn't it required to call a function with the '()' --> somefunction()
What's the logic behind it?

A: Because you're passing in the function reference, not the returned value of the function.

A: A function is a thing that can be invoked—where it runs code and returns a result. You invoke a function by using the parentheses. But, if you want to talk about the thing, if you want to pass the function around so that someone else can invoke it, you leave off the parentheses.
In this case, the getCurrentPosition() function is asking you to give it a function so that it can call it later on. So instead of invoking successFunction, you pass along a reference to it.
If you instead wrote:
navigator.geolocation.getCurrentPosition(
  successFunction()
);

…then what would happen is successFunction() would be invoked—the code of the function would be run, and possibly return a value—and THEN you would invoke getCurrentPosition(), passing along as an argument whatever value successFunction returned.

A: In JavaScript you can pass functions as objects:
Try executing this example:
function myFunction() {
    console.log('hello');
}

function anotherFunction(functionParameter) {
    console.log('executing function passed as argument:');
    functionParameter();
}

anotherFunction(myFunction);

This code will print:
"executing function passed as argument:"
"hello"


text:
Q: The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't I have the following code:
var _editedService = Service(
  id: '',
  name: '',
  description: '',
  aboutUs: '',
  streetNumber: null,
  streetName: '',
  suburb: '',
  city: '',
  province: '',
  zipCode: null,
  contactNum: null,
  email: '',
  logoUrl: '',
  imageUrl: '',
);

When I run this I receive the following error:

Error: The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't.

I've went through the other Stack response but there were no success.
Any advice?
This is the Service Class:
class Service with ChangeNotifier {
  final String id;
  final String name;
  final String description;
  final String aboutUs;
  final double? streetNumber;
  final String streetName;
  final String suburb;
  final String city;
  final String province;
  final double? zipCode;
  final double? contactNum;
  final String email;
  final String logoUrl;
  final String imageUrl;
  late final bool? isFavorite;

  Service({
    required this.id,
    required this.name,
    required this.description,
    required this.aboutUs,
    required this.streetNumber,
    required this.streetName,
    required this.suburb,
    required this.city,
    required this.province,
    required this.zipCode,
    required this.contactNum,
    required this.email,
    required this.logoUrl,
    required this.imageUrl,
    this.isFavorite = false,
  });

  void toggleFavoriteStatus() {
    isFavorite = !isFavorite!;
    notifyListeners();
  }
}

A: I tested the code in dartpad and it's totally fine, there is nothing wrong with it.
So some other part of the code is throwing the error, update your answer with a detailed error message like error line number etc.
The problem is related to dart null safety.
Here is an example:
main() {
  print(add('hello', 'world'));
}

String add(String a, String? b) {
  return a + b;
}

The above block of code will raise an error: The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't
And to solve it, you have to use the null-aware operator:
main() {
  print(add('hello', 'world'));
}

String add(String a, String? b) {
  return a + b!;
}

Note: the !(exclemation mark) after b in return statement. It will solve the problem.

A: use "!" at the end of what you are returning
String? xya = "safdd";
String yz = xya!;

A: This may help you
With null safety on, variables cannot be null if they haven't got a ? at the end. For example:
String myString = "Hello World"; //This CANNOT be null
String? myString = null; //This CAN be null

The solution may be putting a null check ! as or replace with an empty string if null.
String myString = myOtherString!
String myString = myOtherString ?? "Something else";


text:
Q: When to use the lock thread in C#? I have a server which handles multiple incoming socket connections and creates 2 different threads which store the data in XML format.
I was using the lock statement for thread safety almost in every event handler called asyncronously and in the 2 threads in different parts of code.  Sadly using this approach my application significantly slows down.
I tried to not use lock at all and the server is very fast in execution, even the file storage seems to boost; but the program crashes for reasons I don't understand after 30sec - 1min. of work.
So. I thought that the best way is to use less locks or to use it only there where's strictly necessary.  As such, I have 2 questions:

*

*Is the lock needed when I write to the public accessed variables (C# lists) only or even when I read from them ?

*Is the lock needed only in the asyncronous threads created by the socket handler or in other places too ?
Someone could give me some practical guidelines, about how to operate. I'll not post the whole code this time. It hasn't sense to post about 2500 lines of code.

A: You ever sit in your car or on the bus at a red light when there's no cross traffic? Big waste of time, right?  A lock is like a perfect traffic light. It is always green except when there is traffic in the intersection.
Your question is "I spend too much time in traffic waiting at red lights. Should I just run the red light? Or even better, should I remove the lights entirely and just let everyone drive through the intersection at highway speeds without any intersection controls?"
If you're having a performance problem with locks then removing locks is the last thing you should do. You are waiting at that red light precisely because there is cross traffic in the intersection. Locks are extraordinarily fast if they are not contended.
You can't eliminate the light without eliminating the cross traffic first.  The best solution is therefore to eliminate the cross traffic. If the lock is never contended then you'll never wait at it. Figure out why the cross traffic is spending so much time in the intersection; don't remove the light and hope there are no collisions. There will be.
If you can't do that, then adding more finely-grained locks sometimes helps. That is, maybe you have every road in town converging on the same intersection. Maybe you can split that up into two intersections, so that code can be moving through two different intersections at the same time.
Note that making the cars faster (getting a faster processor) or making the roads shorter (eliminating code path length) often makes the problem worse in multithreaded scenarios. Just as it does in real life; if the problem is gridlock then buying faster cars and driving them on shorter roads gets them to the traffic jam faster, but not out of it faster.

A:
Is the lock needed when I write to the public accessed variables (C# lists) only or even when I read from them ?

Yes (even when you read).

Is the lock needed only in the asyncronous threads created by the socket handler or in other places too ?

Yes.  Wherever code accesses a section of code which is shared, always lock.

This sounds like you may not be locking individual objects, but locking one thing for all lock situations.
If so put in smart discrete locks by creating individual unique objects which relate and lock only certain sections at a time, which don't interfere with other threads in other sections.
Here is an example:
// This class simulates the use of two different thread safe resources and how to lock them
// for thread safety but not block other threads getting different resources.
public class SmartLocking
{
    private string StrResource1 { get; set; }
    private string StrResource2 { get; set; }

    private object _Lock1 = new object();
    private object _Lock2 = new object();

    public void DoWorkOn1( string change )
    {
        lock (_Lock1)
        {
            _Resource1 = change;
        }
    }

    public void DoWorkOn2( string change2 )
    {
        lock (_Lock2)
        {
            _Resource2 = change2;
        }
    }
}

A: Always use a lock when you access members (either read or write). If you are iterating over a collection, and from another thread you're removing items, things can go wrong quickly.
A suggestion is when you want to iterate a collection, copy all the items to a new collection and then iterate the copy. I.e.
var newcollection; // Initialize etc.
lock(mycollection)
{
  // Copy from mycollection to newcollection
}

foreach(var item in newcollection)
{
  // Do stuff
}

Likewise, only use the lock the moment you are actually writing to the list.

A: The reason that you need to lock while reading is:
let's say you are making change to one property and it has being read twice while the thread is inbetween a lock. Once right before we made any change and another after, then we will have inconsistent results.
I hope that helps,

A: Basically this can be answered pretty simple:
You need to lock all the things that are accessed by different threads. It actually doesnt really matter if its about reading or writing. If you are reading and another thread is overwriting the data at the same time the data read may get invalid and you possibly are performing invalid operations.


text:
Q: Calculate the approximate entropy of a matrix of time series Approximate entropy was introduced to quantify the the amount of regularity and the unpredictability of fluctuations in a time series.
The function
approx_entropy(ts, edim = 2, r = 0.2*sd(ts), elag = 1)

from package pracma, calculates the approximate entropy of time series ts.
I have a matrix of time series (one series per row) mat and I would estimate the approximate entropy for each of them, storing the results in a vector. For example:
library(pracma)

N<-nrow(mat)
r<-matrix(0, nrow = N, ncol = 1)
for (i in 1:N){
     r[i]<-approx_entropy(mat[i,], edim = 2, r = 0.2*sd(mat[i,]), elag = 1)
}

However, if N is large this code could be too slow. Suggestions to speed it? Thanks!

A: I would also say parallelization, as apply-functions apparently didn't bring any optimization.
I tried the approx_entropy() function with:

*

*apply

*lapply

*ParApply

*foreach (from @Mankind_008)

*a combination of data.table and ParApply

The ParApply seems to be slightly more efficient than the other 2 parallel functions.
As I didn't get the same timings as @Mankind_008 I checked them with microbenchmark.
Those were the results for 10 runs:

Unit: seconds
expr      min       lq     mean   median       uq      max neval cld
forloop     4.067308 4.073604 4.117732 4.097188 4.141059 4.244261    10   b
apply       4.054737 4.092990 4.147449 4.139112 4.188664 4.246629    10   b
lapply      4.060242 4.068953 4.229806 4.105213 4.198261 4.873245    10   b
par         2.384788 2.397440 2.646881 2.456174 2.558573 4.134668    10   a
parApply    2.289028 2.300088 2.371244 2.347408 2.369721 2.675570    10   a
DT_parApply 2.294298 2.322774 2.387722 2.354507 2.466575 2.515141    10   a

Full Code:
library(pracma)
library(foreach)
library(parallel)
library(doParallel)

# dummy random time series data
ts <- rnorm(56)
mat <- matrix(rep(ts,100), nrow = 100, ncol = 100)
r <- matrix(0, nrow = nrow(mat), ncol = 1)

## For Loop
for (i in 1:nrow(mat)){
  r[i]<-approx_entropy(mat[i,], edim = 2, r = 0.2*sd(mat[i,]), elag = 1)
}

## Apply
r1 = apply(mat, 1, FUN = function(x) approx_entropy(x, edim = 2, r = 0.2*sd(x), elag = 1))

## Lapply
r2 = lapply(1:nrow(mat), FUN = function(x) approx_entropy(mat[x,], edim = 2, r = 0.2*sd(mat[x,]), elag = 1))

## ParApply
cl <- makeCluster(getOption("cl.cores", 3))
r3 = parApply(cl = cl, mat, 1, FUN = function(x) {
  library(pracma);
  approx_entropy(x, edim = 2, r = 0.2*sd(x), elag = 1)
})
stopCluster(cl)

## Foreach
registerDoParallel(cl = 3, cores = 2)
r4 <- foreach(i = 1:nrow(mat), .combine = rbind)  %dopar%
  pracma::approx_entropy(mat[i,], edim = 2, r = 0.2*sd(mat[i,]), elag = 1)
stopImplicitCluster()

## Data.table
library(data.table)
mDT = as.data.table(mat)
cl <- makeCluster(getOption("cl.cores", 3))
r5 = parApply(cl = cl, mDT, 1, FUN = function(x) {
  library(pracma);
  approx_entropy(x, edim = 2, r = 0.2*sd(x), elag = 1)
})
stopCluster(cl)

## All equal Tests
all.equal(as.numeric(r), r1)
all.equal(r1, as.numeric(do.call(rbind, r2)))
all.equal(r1, r3)
all.equal(r1, as.numeric(r4))
all.equal(r1, r5)

## Benchmark
library(microbenchmark)
mc <- microbenchmark(times=10,
  forloop = {
    for (i in 1:nrow(mat)){
      r[i]<-approx_entropy(mat[i,], edim = 2, r = 0.2*sd(mat[i,]), elag = 1)
    }
  },
  apply = {
    r1 = apply(mat, 1, FUN = function(x) approx_entropy(x, edim = 2, r = 0.2*sd(x), elag = 1))
  },
  lapply = {
    r1 = lapply(1:nrow(mat), FUN = function(x) approx_entropy(mat[x,], edim = 2, r = 0.2*sd(mat[x,]), elag = 1))
  },
  par = {
    registerDoParallel(cl = 3, cores = 2)
    r_par <- foreach(i = 1:nrow(mat), .combine = rbind)  %dopar%
      pracma::approx_entropy(mat[i,], edim = 2, r = 0.2*sd(mat[i,]), elag = 1)
    stopImplicitCluster()
  },
  parApply = {
    cl <- makeCluster(getOption("cl.cores", 3))
    r3 = parApply(cl = cl, mat, 1, FUN = function(x) {
      library(pracma);
      approx_entropy(x, edim = 2, r = 0.2*sd(x), elag = 1)
    })
    stopCluster(cl)
  },
  DT_parApply = {
    mDT = as.data.table(mat)
    cl <- makeCluster(getOption("cl.cores", 3))
    r5 = parApply(cl = cl, mDT, 1, FUN = function(x) {
      library(pracma);
      approx_entropy(x, edim = 2, r = 0.2*sd(x), elag = 1)
    })
    stopCluster(cl)
  }
)

## Results
mc
Unit: seconds
expr      min       lq     mean   median       uq      max neval cld
forloop 4.067308 4.073604 4.117732 4.097188 4.141059 4.244261    10   b
apply 4.054737 4.092990 4.147449 4.139112 4.188664 4.246629    10   b
lapply 4.060242 4.068953 4.229806 4.105213 4.198261 4.873245    10   b
par 2.384788 2.397440 2.646881 2.456174 2.558573 4.134668    10  a
parApply 2.289028 2.300088 2.371244 2.347408 2.369721 2.675570    10  a
DT_parApply 2.294298 2.322774 2.387722 2.354507 2.466575 2.515141    10  a

## Time-Boxplot
plot(mc)

The amount of cores will also affect speed, and more is not always faster, as at some point, the overhead that is sent to all workers eats away some of the gained performance. I benchmarked the ParApply function with 2 to 7 cores, and on my machine, running the function with 3 / 4 cores seems to be the best choice, althouth the deviation is not that big.

mc
Unit: seconds
expr      min       lq     mean   median       uq      max neval  cld
parApply_2 2.670257 2.688115 2.699522 2.694527 2.714293 2.740149    10   c
parApply_3 2.312629 2.366021 2.411022 2.399599 2.464568 2.535220    10 a
parApply_4 2.358165 2.405190 2.444848 2.433657 2.485083 2.568679    10 a
parApply_5 2.504144 2.523215 2.546810 2.536405 2.558630 2.646244    10  b
parApply_6 2.687758 2.725502 2.761400 2.747263 2.766318 2.969402    10   c
parApply_7 2.906236 2.912945 2.948692 2.919704 2.988599 3.053362    10    d

Full Code:
## Benchmark N-Cores
library(microbenchmark)
mc <- microbenchmark(times=10,
                     parApply_2 = {
                       cl <- makeCluster(getOption("cl.cores", 2))
                       r3 = parApply(cl = cl, mat, 1, FUN = function(x) {
                         library(pracma);
                         approx_entropy(x, edim = 2, r = 0.2*sd(x), elag = 1)
                       })
                       stopCluster(cl)
                     },
                     parApply_3 = {
                       cl <- makeCluster(getOption("cl.cores", 3))
                       r3 = parApply(cl = cl, mat, 1, FUN = function(x) {
                         library(pracma);
                         approx_entropy(x, edim = 2, r = 0.2*sd(x), elag = 1)
                       })
                       stopCluster(cl)
                     },
                     parApply_4 = {
                       cl <- makeCluster(getOption("cl.cores", 4))
                       r3 = parApply(cl = cl, mat, 1, FUN = function(x) {
                         library(pracma);
                         approx_entropy(x, edim = 2, r = 0.2*sd(x), elag = 1)
                       })
                       stopCluster(cl)
                     },
                     parApply_5 = {
                       cl <- makeCluster(getOption("cl.cores", 5))
                       r3 = parApply(cl = cl, mat, 1, FUN = function(x) {
                         library(pracma);
                         approx_entropy(x, edim = 2, r = 0.2*sd(x), elag = 1)
                       })
                       stopCluster(cl)
                     },
                     parApply_6 = {
                       cl <- makeCluster(getOption("cl.cores", 6))
                       r3 = parApply(cl = cl, mat, 1, FUN = function(x) {
                         library(pracma);
                         approx_entropy(x, edim = 2, r = 0.2*sd(x), elag = 1)
                       })
                       stopCluster(cl)
                     },
                     parApply_7 = {
                       cl <- makeCluster(getOption("cl.cores", 7))
                       r3 = parApply(cl = cl, mat, 1, FUN = function(x) {
                         library(pracma);
                         approx_entropy(x, edim = 2, r = 0.2*sd(x), elag = 1)
                       })
                       stopCluster(cl)
                     }
)

## Results
mc
Unit: seconds
expr      min       lq     mean   median       uq      max neval  cld
parApply_2 2.670257 2.688115 2.699522 2.694527 2.714293 2.740149    10   c
parApply_3 2.312629 2.366021 2.411022 2.399599 2.464568 2.535220    10 a
parApply_4 2.358165 2.405190 2.444848 2.433657 2.485083 2.568679    10 a
parApply_5 2.504144 2.523215 2.546810 2.536405 2.558630 2.646244    10  b
parApply_6 2.687758 2.725502 2.761400 2.747263 2.766318 2.969402    10   c
parApply_7 2.906236 2.912945 2.948692 2.919704 2.988599 3.053362    10    d

## Plot Results
plot(mc)

As the matrices get bigger, using ParApply with data.table seems to be faster than using matrices. The following example used a matrix with 500*500 elements resulting in those timings (only for 2 runs):

Unit: seconds
expr      min       lq     mean   median       uq      max neval cld
ParApply 191.5861 191.5861 192.6157 192.6157 193.6453 193.6453     2   a
DT_ParAp 135.0570 135.0570 163.4055 163.4055 191.7541 191.7541     2   a

The minimum is considerably lower, although the maximum is almost the same which is also nicely illustrated in that boxplot:

Full Code:
# dummy random time series data
ts <- rnorm(500)
# mat <- matrix(rep(ts,100), nrow = 100, ncol = 100)
mat = matrix(rep(ts,500), nrow = 500, ncol = 500, byrow = T)
r <- matrix(0, nrow = nrow(mat), ncol = 1)

## Benchmark
library(microbenchmark)
mc <- microbenchmark(times=2,
                     ParApply = {
                       cl <- makeCluster(getOption("cl.cores", 3))
                       r3 = parApply(cl = cl, mat, 1, FUN = function(x) {
                         library(pracma);
                         approx_entropy(x, edim = 2, r = 0.2*sd(x), elag = 1)
                       })
                       stopCluster(cl)
                     },
                     DT_ParAp = {
                       mDT = as.data.table(mat)
                       cl <- makeCluster(getOption("cl.cores", 3))
                       r5 = parApply(cl = cl, mDT, 1, FUN = function(x) {
                         library(pracma);
                         approx_entropy(x, edim = 2, r = 0.2*sd(x), elag = 1)
                       })
                       stopCluster(cl)
                     }
)

## Results
mc
Unit: seconds
expr      min       lq     mean   median       uq      max neval cld
ParApply 191.5861 191.5861 192.6157 192.6157 193.6453 193.6453     2   a
DT_ParAp 135.0570 135.0570 163.4055 163.4055 191.7541 191.7541     2   a

## Plot
plot(mc)

A: Parallelization would speed things up.
Current System Time: without parallelization
library(pracma)

ts <- rnorm(10000)                                       # dummy random time series data

mat <- matrix(ts, nrow = 100, ncol = 100)
r <- matrix(0, nrow = nrow(mat), ncol = 1)               # to collect response

system.time ( for (i in 1:nrow(mat)){                    # system time:  for loop
      r[i]<-approx_entropy(mat[i,], edim = 2, r = 0.2*sd(mat[i,]), elag = 1)
                        } )

 user  system elapsed
31.17    6.28   65.09

New System Time: with parallelization
Using foreach and its back-end parallelization package doParallel to control resources.
library(foreach)
library(doParallel)

registerDoParallel(cl = 3, cores = 2)                      # initiate resources

system.time (
       r_par <- foreach(i = 1:nrow(mat), .combine = rbind)  %dopar%
                pracma::approx_entropy(mat[i,], edim = 2, r = 0.2*sd(mat[i,]), elag = 1)
            )

stopImplicitCluster()                                      # terminate resources

user  system elapsed
0.13    0.03   29.88

P.S. I would recommend setting up the cluster, core allocations as per your configuration and speed requirements.
Also the reason I didn't include the comparison with apply family is because of their sequential nature in implementation, that would produce only a marginal improvement. For a considerable improvement in speed, shifting from a sequential to parallelized implementation is recommended.


text:
Q: Como criar uma regex equivalente a uma BNF? Preciso criar uma expressão regular que seja equivalente à seguinte BNF:
<SEQ> ::= <DIG><SEQ> | <DIG>
<DIG> ::= 0|1

Tentei criar um código em Python com a biblioteca regex:
import re

reg = r'[0-2]'

print(reg)

Era um teste, mas não consegui criar de fato uma regex que seja equivalente à BNF.

A: Se a ideia é gerar uma regex equivalente a esta BNF, então seria algo assim:
import re

r = re.compile('^[01]+$')

print(r.match('010100111')) # retorna um objeto Match
print(r.match('010120111')) # None

A regex usa os marcadores ^ e $ que indicam respectivamente o início e fim da string.
Depois temos a classe de caracteres [01] que significa "um dígito 0 ou 1" e o quantificador + que indica uma ou mais ocorrências. Assim, a regex reconhece uma sequência de zeros e uns, de tamanho mínimo 1 e sem limite máximo (exatamente o mesmo que a BNF representa).
No exemplo acima, podemos ver que se a string só tem zeros e uns, é encontrado um match, e se tiver qualquer caractere diferente, não encontra nada.
Obs: eu até poderia usar [0-1] em vez de [01], mas neste caso dá na mesma ("um digito de 0 a 1" e "o dígito 0 ou 1" é basicamente a mesma coisa).

Antes da edição e dos comentários, não estava claro que o objetivo era gerar a regex acima. De qualquer forma, vou manter a versão que tentava responder à pergunta original.

Se dada uma BNF, você quer criar uma sequência que corresponda à definição, então regex não é a ferramenta certa para a tarefa.
No caso, você teria que implementar na mão, ou usar alguma lib pronta. Uma alternativa é usar o NLTK. Como eu não uso muito esse tipo de coisa, acabei pegando um exemplo daqui e adaptando para o seu caso:
from nltk import CFG
from nltk.parse.generate import generate

# cria a gramática a partir da BNF
grammar = CFG.fromstring(""" SEQ -> DIG SEQ | DIG
    DIG -> "0" | "1" """)

# gera várias "palavras" válidas da gramática
for production in generate(grammar, depth=5):
    print(' '.join(production))

No caso acima, a saída foi:
0 0 0
0 0 1
0 1 0
0 1 1
0 0
0 1
1 0 0
1 0 1
1 1 0
1 1 1
1 0
1 1
0
1

A partir daí você pode ler a documentação (aqui e aqui) para gerar exatamente o que você precisa.
Pois a gramática em questão gera uma sequência potencialmente infinita de zeros e uns (e não "uma sequência de 0 a 2", como originalmente dito), então não está claro se você precisa gerar alguma sequência qualquer que seja válida, ou alguma específica, ou todas de determinado tamanho, etc.
Mas a ideia geral provavelmente é essa...


text:
Q: Python import pandas infinite loop on task scheduler I have this script that works fine when executed manually. Problem is that when I Windows Task Scheduler It seems to hang somewhere.
The task is executed by a service account with privileges to run as a batch job, and has full control over the Anaconda3 folder.
import pandas as pd
print("Hello")

I tried to execute this to show some log on what's happening at it seems like the problem is when importing pandas.
python -m trace --trace script.py > logfile.log

Greatly appreciate any resolution on this.


text:
Q: UICollectionView doesn't scroll inside UITableViewCell I'm having an issue with UICollectionView scrolling inside UITableViewCell.
Unfortunately, the CollectionView doesn't scroll at all. When I'm trying to disable other UITableViewCells it works without any problem and vice versa.
CollectionViewCell:
import UIKit

class CategoriesCollectionViewCell: UICollectionViewCell {
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
        layoutUI()
    }

    required init(coder adecoder: NSCoder) {
        fatalError("init(codeer:) has not been implemented")
    }

    lazy var categoriesImage: UIImageView = {
        let categoriesImage = UIImageView()
        categoriesImage.contentMode = .scaleToFill
        categoriesImage.layer.cornerRadius = 8.0
        categoriesImage.image = UIImage(named: "pizza")
        categoriesImage.layer.cornerRadius = 8.0
        categoriesImage.layer.masksToBounds = true
        categoriesImage.translatesAutoresizingMaskIntoConstraints = false
        return categoriesImage
    }()

    lazy var containerView: UIView = {
        let containerView = UIView()
        containerView.backgroundColor = .black
        containerView.alpha = 0.7
        containerView.translatesAutoresizingMaskIntoConstraints = false
        return containerView
    }()

    lazy var categoryName: UILabel = {
        let categoryName = UILabel()
        categoryName.textColor = .white
        categoryName.font = UIFont(name: "AvenirNext-DemiBold", size: 16)
        categoryName.text = "Soup"
        categoryName.textAlignment = .left
        categoryName.translatesAutoresizingMaskIntoConstraints = false
        return categoryName
    }()

    lazy var recipesNumber: UILabel = {
        let recipesNumber = UILabel()
        recipesNumber.textColor = .white
        recipesNumber.font = UIFont(name: "AvenirNext-Regular", size: 16)
        recipesNumber.text = "33"
        recipesNumber.textAlignment = .left
        recipesNumber.translatesAutoresizingMaskIntoConstraints = false
        return recipesNumber
    }()

    func setupcategoriesImageConstraints() {
        NSLayoutConstraint.activate([
            categoriesImage.topAnchor.constraint(equalTo: topAnchor),
            categoriesImage.bottomAnchor.constraint(equalTo: bottomAnchor),
            categoriesImage.leadingAnchor.constraint(equalTo: leadingAnchor),
            categoriesImage.trailingAnchor.constraint(equalTo: trailingAnchor),
        ])
    }

    func setupContainerViewConstraints() {
        NSLayoutConstraint.activate([
            containerView.topAnchor.constraint(equalTo: categoriesImage.topAnchor),
            containerView.bottomAnchor.constraint(equalTo: categoriesImage.bottomAnchor),
            containerView.leadingAnchor.constraint(equalTo: categoriesImage.leadingAnchor),
            containerView.trailingAnchor.constraint(equalTo: categoriesImage.trailingAnchor)
        ])
    }

    func setupCategoryNameConstraints() {
        NSLayoutConstraint.activate([
            categoryName.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 16),
            categoryName.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 16),
            categoryName.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: 16)
        ])
    }

    func setuprecipesNumberConstraints() {
        NSLayoutConstraint.activate([
            recipesNumber.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -16),
            recipesNumber.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 16),
            recipesNumber.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: 16)
        ])
    }

    func addSubviews() {
        addSubview(categoriesImage)
        categoriesImage.addSubview(containerView)
        containerView.addSubview(categoryName)
        containerView.addSubview(recipesNumber)
    }

    func layoutUI() {
        addSubviews()
        setupcategoriesImageConstraints()
        setupContainerViewConstraints()
        setupCategoryNameConstraints()
        setuprecipesNumberConstraints()
    }
}

CollectionViewInTableViewCell:
import UIKit

class CategoriesTableViewCellCollectionViewCell: UITableViewCell, UICollectionViewDelegateFlowLayout {

    let categories = ["italian food", "chinese food", "korean food", "italian food", "chinese food", "korean food", "italian food", "chinese food", "korean food", "italian food", "chinese food", "korean food"]

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        layoutUI()
        selectionStyle = .none
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    lazy var containerView: UIView = {
        let containerView = UIView()
        containerView.backgroundColor = .clear
        containerView.translatesAutoresizingMaskIntoConstraints = false
        return containerView
    }()

    lazy var categoriesNameLabel: UILabel = {
        let categoriesNameLabel = UILabel()
        categoriesNameLabel.text = "Categories"
        categoriesNameLabel.textColor = .customDarkGray()
        categoriesNameLabel.textAlignment = .left
        categoriesNameLabel.font = UIFont(name: "AvenirNext-Regular", size: 14)
        categoriesNameLabel.translatesAutoresizingMaskIntoConstraints = false
        return categoriesNameLabel
    }()

    lazy var seeAllCategoriesButton: UIButton = {
        let seeAllCategoriesButton = UIButton()
        seeAllCategoriesButton.setTitle("See all", for: .normal)
        seeAllCategoriesButton.setTitleColor(.CustomGreen(), for: .normal)
        seeAllCategoriesButton.titleLabel?.font = UIFont(name: "AvenirNext-Regular", size: 14)
        seeAllCategoriesButton.translatesAutoresizingMaskIntoConstraints = false
        seeAllCategoriesButton.addTarget(self, action: #selector(test), for: .touchUpInside)
        return seeAllCategoriesButton
    }()

    @objc func test() {
        print("Test worked")
    }

    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        collectionView.backgroundColor = .clear
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(CategoriesCollectionViewCell.self, forCellWithReuseIdentifier: "CategoriesCollectionViewCell")
        return collectionView
    }()

    func setupContainerViewConstraints() {
        NSLayoutConstraint.activate([
            containerView.topAnchor.constraint(equalTo: topAnchor, constant: 16),
            containerView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16),
            containerView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16),
            containerView.heightAnchor.constraint(equalTo: categoriesNameLabel.heightAnchor)
        ])
    }

    func setupCategoriesNameLabelConstraints() {
        NSLayoutConstraint.activate([
            categoriesNameLabel.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
            categoriesNameLabel.centerYAnchor.constraint(equalTo: containerView.centerYAnchor)
        ])
    }

    func setupSeeAllCategoriesButtonConstraints() {
        NSLayoutConstraint.activate([
            seeAllCategoriesButton.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
            seeAllCategoriesButton.centerYAnchor.constraint(equalTo: containerView.centerYAnchor)
        ])
    }

    func setupCollectionViewConstraints() {
        NSLayoutConstraint.activate([
            collectionView.topAnchor.constraint(equalTo: categoriesNameLabel.topAnchor, constant: 16),
            collectionView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 16),
            collectionView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16),
            collectionView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16),
        ])
    }

    func addSubviews() {
        addSubview(categoriesNameLabel)
        addSubview(containerView)
        containerView.addSubview(seeAllCategoriesButton)
        containerView.addSubview(collectionView)
    }

    func layoutUI() {
        addSubviews()
        setupCollectionViewConstraints()
        setupContainerViewConstraints()
        setupCategoriesNameLabelConstraints()
        setupSeeAllCategoriesButtonConstraints()
    }

}

extension CategoriesTableViewCellCollectionViewCell: UICollectionViewDelegate, UICollectionViewDataSource {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return categories.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CategoriesCollectionViewCell", for: indexPath) as! CategoriesCollectionViewCell

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: self.frame.width / 2, height: self.frame.width / 4)
    }

}

TableViewCell:
import UIKit

class HomeTableViewCell: UITableViewCell {

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        layoutUI()
        selectionStyle = .none
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    lazy var containerView: UIView = {
        let containerView = UIView()
        containerView.backgroundColor = .white
        containerView.translatesAutoresizingMaskIntoConstraints = false
        containerView.layer.shadowColor = UIColor.black.cgColor
        containerView.layer.shadowOpacity = 1
        containerView.layer.shadowOffset = .init(width: 2, height: 2)
        containerView.layer.shadowRadius = 7.0
        containerView.layer.cornerRadius = 8.0
//        containerView.clipsToBounds = true
        return containerView
    }()

    lazy var foodImage: UIImageView = {
        let foodImage = UIImageView()
        foodImage.translatesAutoresizingMaskIntoConstraints = false
        foodImage.contentMode = .scaleAspectFill
        foodImage.clipsToBounds = true
        foodImage.layer.cornerRadius = 8.0
        return foodImage
    }()

    lazy var foodTitle: UILabel = {
        let foodTitle = UILabel()
        foodTitle.textColor = .CustomGreen()
        foodTitle.numberOfLines = 0
        foodTitle.translatesAutoresizingMaskIntoConstraints = false
        return foodTitle
    }()

    func setupContainerView() {
        NSLayoutConstraint.activate([
            containerView.topAnchor.constraint(equalTo: topAnchor, constant: 16),
            containerView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -16),
            containerView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16),
            containerView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16),
        ])
    }

    func setupFoodImage() {
        NSLayoutConstraint.activate([
            foodImage.topAnchor.constraint(equalTo: containerView.topAnchor),
            foodImage.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
            foodImage.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
            foodImage.heightAnchor.constraint(equalToConstant: 250)
        ])
    }

    func setupFoodTitle() {
        NSLayoutConstraint.activate([
            foodTitle.topAnchor.constraint(equalTo: foodImage.bottomAnchor, constant: 16),
            foodTitle.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -16),
            foodTitle.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 16),
            foodTitle.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -16)
        ])
    }

    func addSubview() {
        addSubview(containerView)
        containerView.addSubview(foodImage)
        containerView.addSubview(foodTitle)
    }

    func layoutUI() {
        addSubview()
        setupContainerView()
        setupFoodImage()
        setupFoodTitle()
    }

}

HomeView:
class HomeView: UIView {

    var recipes: Recipes?
    var recipesDetails = [Recipe]()
    let indicator = ActivityIndicator()

    override init( frame: CGRect) {
        super.init(frame: frame)
        layoutUI()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    lazy var foodTableView: UITableView = {
        let foodTableView = UITableView()
        foodTableView.translatesAutoresizingMaskIntoConstraints = false
        foodTableView.backgroundColor = .white
        foodTableView.delegate = self
        foodTableView.dataSource = self
        foodTableView.register(CategoriesTableViewCellCollectionViewCell.self, forCellReuseIdentifier: "CategoriesTableViewCellCollectionViewCell")
        foodTableView.register(HomeTableViewCell.self, forCellReuseIdentifier: "HomeTableViewCell")
        foodTableView.rowHeight = UITableView.automaticDimension
//        foodTableView.estimatedRowHeight = 100
        foodTableView.showsVerticalScrollIndicator = false
        foodTableView.separatorStyle = .none
        return foodTableView
    }()

    func setupFoodTableView() {
        NSLayoutConstraint.activate([
            foodTableView.topAnchor.constraint(equalTo: topAnchor),
            foodTableView.bottomAnchor.constraint(equalTo: bottomAnchor),
            foodTableView.leadingAnchor.constraint(equalTo: leadingAnchor),
            foodTableView.trailingAnchor.constraint(equalTo: trailingAnchor)
        ])
    }

    func addSubview() {
        addSubview(foodTableView)
    }

    func layoutUI() {
        indicator.setupIndicatorView(self, containerColor: .customDarkGray(), indicatorColor: .white)
        addSubview()
        setupFoodTableView()
        fetchData()

    }

    func fetchData() {
        AF.request("https://api.url").responseJSON { (response) in
            if let error = response.error {
                print(error)
            }
            do {
                self.recipes = try JSONDecoder().decode(Recipes.self, from: response.data!)
                self.recipesDetails = self.recipes?.recipes ?? []
                DispatchQueue.main.async {
                    self.foodTableView.reloadData()
                }
            } catch {
                print(error)
            }
            self.indicator.hideIndicatorView()
        }
    }

}

extension HomeView: UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return recipesDetails.count

    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "CategoriesTableViewCellCollectionViewCell", for: indexPath) as! CategoriesTableViewCellCollectionViewCell
            cell.layoutIfNeeded()
            cell.collectionView.reloadData()
            return cell
        }

        let cell = tableView.dequeueReusableCell(withIdentifier: "HomeTableViewCell", for: indexPath) as! HomeTableViewCell
        let url = URL(string: recipesDetails[indexPath.row].image ?? "Error")
        cell.foodImage.kf.setImage(with: url)
        cell.foodTitle.text = recipesDetails[indexPath.row].title
        cell.layoutIfNeeded()
        return cell

    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return 160

        } else {
            return 250
        }

    }

}

Can anyone tell me what is the problem or what I did wrong?
Thanks.

A: You cannot scroll your collection view because it is outside the bounds of its superview. In your code, you have this line:
containerView.heightAnchor.constraint(equalTo: categoriesNameLabel.heightAnchor)

That makes your containerView height only around 20-pts, but you also have your collection view as a subview of containerView.
Here is how your code looks for me (pretty much as-is):

And, I cannot scroll the collection view.
You can confirm it is outside the containerView bounds by giving containerView a background color (I used cyan):

You can also confirm it by setting containerView.clipsToBounds = true:

Now, we don't even see the collection view.
You have a couple other constraint issues, but they don't really relate to being unable to scroll the collection view.
Your layout is also a little confusing, in that you have your Categories label outside your containerView... it seems it would make much more sense to have that label + the "See All" button + the collection view all inside the containerView.
I made a few edits to your CategoriesTableViewCellCollectionViewCell which resolves that issue -- and I think is close to your ultimate goal. You may need to do a little tweaking, but hopefully it will give you a good direction.
class CategoriesTableViewCellCollectionViewCell: UITableViewCell, UICollectionViewDelegateFlowLayout {

    let categories = ["italian food", "chinese food", "korean food", "italian food", "chinese food", "korean food", "italian food", "chinese food", "korean food", "italian food", "chinese food", "korean food"]

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        layoutUI()
        selectionStyle = .none
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    lazy var containerView: UIView = {
        let containerView = UIView()
        containerView.backgroundColor = .clear
        containerView.translatesAutoresizingMaskIntoConstraints = false
        return containerView
    }()

    lazy var categoriesNameLabel: UILabel = {
        let categoriesNameLabel = UILabel()
        categoriesNameLabel.text = "Categories"
        categoriesNameLabel.textColor = .gray // .customDarkGray()
        categoriesNameLabel.textAlignment = .left
        categoriesNameLabel.font = UIFont(name: "AvenirNext-Regular", size: 14)
        categoriesNameLabel.translatesAutoresizingMaskIntoConstraints = false
        return categoriesNameLabel
    }()

    lazy var seeAllCategoriesButton: UIButton = {
        let seeAllCategoriesButton = UIButton()
        seeAllCategoriesButton.setTitle("See all", for: .normal)
//      seeAllCategoriesButton.setTitleColor(.CustomGreen(), for: .normal)
        seeAllCategoriesButton.setTitleColor(UIColor(red: 0.0, green: 0.5, blue: 0.0, alpha: 1.0), for: .normal)
        seeAllCategoriesButton.titleLabel?.font = UIFont(name: "AvenirNext-Regular", size: 14)
        seeAllCategoriesButton.translatesAutoresizingMaskIntoConstraints = false
        seeAllCategoriesButton.addTarget(self, action: #selector(test), for: .touchUpInside)
        return seeAllCategoriesButton
    }()

    @objc func test() {
        print("Test worked")
    }

    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        collectionView.backgroundColor = .clear
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(CategoriesCollectionViewCell.self, forCellWithReuseIdentifier: "CategoriesCollectionViewCell")
        return collectionView
    }()

    func setupContainerViewConstraints() {
        NSLayoutConstraint.activate([
            containerView.topAnchor.constraint(equalTo: topAnchor, constant: 16),
            containerView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16),
            containerView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16),
            // should not be constrained to categoriesNameLabel height
            //containerView.heightAnchor.constraint(equalTo: categoriesNameLabel.heightAnchor)
            // constrain 16-pts from bottom of cell
            containerView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -16)
        ])
    }

    func setupCategoriesNameLabelConstraints() {
        NSLayoutConstraint.activate([
            categoriesNameLabel.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
            // centerY to seeAllCategoriesButton
            categoriesNameLabel.centerYAnchor.constraint(equalTo: seeAllCategoriesButton.centerYAnchor)
        ])
    }

    func setupSeeAllCategoriesButtonConstraints() {
        NSLayoutConstraint.activate([
            seeAllCategoriesButton.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
            // constrain top to containerView top
            seeAllCategoriesButton.topAnchor.constraint(equalTo: containerView.topAnchor)
        ])
    }

    func setupCollectionViewConstraints() {
        NSLayoutConstraint.activate([
            collectionView.topAnchor.constraint(equalTo: seeAllCategoriesButton.bottomAnchor, constant: 0),
            collectionView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -16),
            collectionView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16),
            collectionView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16),
        ])
    }

    func addSubviews() {
        // but categoriesNameLabel inside containerView
        //addSubview(categoriesNameLabel)
        addSubview(containerView)
        containerView.addSubview(categoriesNameLabel)
        containerView.addSubview(seeAllCategoriesButton)
        containerView.addSubview(collectionView)
    }

    func layoutUI() {
        addSubviews()
        setupCollectionViewConstraints()
        setupContainerViewConstraints()
        setupCategoriesNameLabelConstraints()
        setupSeeAllCategoriesButtonConstraints()
    }

}

The result looks like this - and you can see that I have scrolled the collection view a bit:

A: I have the same issue, and I found that just because the structure of tableViewCell.
cell - cell's contentView
Wrong way
addSubview(aView)
cell - aView - cell's contentView
you can't interact with aView
Correct
self.contentView.addSubview(aView)
cell - cell's contentView - aView
Now you can interact with aView.
Just change the line
addSubview(containerView)
to
self.contentView.addSubview(containerView)
will fixed your problem.


text:
Q: Do we need to compile scss to css - React I have a question regarding if we need to compile our scss files to css and then import the css files in our react components or can we just import scss directly in the components?
I managed to import scss directly since we use react-scripts higher than version 2(which is the starting point having the sass-loader support) but are there some drawback to importing scss directly?
Currently our configuration is that we watch for scss changes and with node-sass-chokidar
we compile it to css and import the css files, but I would like to change that so we don't have a bunch of css and scss files in the same folder level.
Thank you

A: The answer was given by Martin in the post's comment


text:
Q: Laravel MySQL Query not working error (Allowed memory size of 536870912 bytes exhausted (tried to allocate 264245248 bytes) Any idea why this query will not work in Laravel 7? It runs fine in MySQL workbench. Error reported is Memory error
$rows = Sections::select("t1.name AS lev1, t1.id as lev1_id, t2.name as lev2, t2.id as lev2_id, t3.name as lev3, t3.id as lev3_id, t4.name as lev4, t4.id as lev4_id, t5.name as lev5, t5.id as lev5_id
        sections AS t1
        LEFT JOIN sections AS t2 ON t2.parent = t1.id
        LEFT JOIN sections AS t3 ON t3.parent = t2.id
        LEFT JOIN sections AS t4 ON t4.parent = t3.id
        LEFT JOIN sections AS t5 ON t5.parent = t4.id
        WHERE t1.name = 'Windows'");

A: Your server as exceed the maximum memory limit of 536MB and trying to allocate more 264MB. You need to increase your memory limit on your php.ini file or reduce your dataset.

A: copy your script first line and try it
ini_set('memory_limit', '1024M');

A: I have changed the query to
$rows = Sections::selectRaw('t1.name AS lev1, t1.id as lev1_id, t2.name as lev2, t2.id as lev2_id, t3.name as lev3, t3.id as lev3_id, t4.name as lev4, t4.id as lev4_id, t5.name as lev5, t5.id as lev5_id
        sections AS t1
        JOIN sections AS t2 ON t2.parent = t1.id
        JOIN sections AS t3 ON t3.parent = t2.id
        JOIN sections AS t4 ON t4.parent = t3.id
        JOIN sections AS t5 ON t5.parent = t4.id
        WHERE t1.name = ?', ['Windows'])
                ->get()
now the error is
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'sections AS t1 JOIN sections AS t2 ON t2.parent = t1.id JOIN sec' at line 2 (SQL: select t1.name AS lev1, t1.id as lev1_id, t2.name as lev2, t2.id as lev2_id, t3.name as lev3, t3.id as lev3_id, t4.name as lev4, t4.id as lev4_id, t5.name as lev5, t5.id as lev5_id sections AS t1 JOIN sections AS t2 ON t2.parent = t1.id JOIN sections AS t3 ON t3.parent = t2.id JOIN sections AS t4 ON t4.parent = t3.id JOIN sections AS t5 ON t5.parent = t4.id WHERE t1.name = Windows from sections)


text:
Q: Embed facebook event edit form As far as I know you cannot edit FB events through the Graph API.
What I want is to include in my page an Edit button for an event with exactly the same functionality behind as the one from Facebook. Same goes for a "Create" button.
How can I do this?

A: There is no social plugin for this, and it´s not possible with the Graph API as you found out already. There is no other way. You can only go to Facebook to create/edit Events. Btw, the possibility to create events was removed with v2.0 and the upgrade process may still happen, so if some App can still create events it´s most likely because it´s still at v1.0. Sooner or later it will get upgraded though. More about the changes: https://developers.facebook.com/docs/apps/changelog#v2_0
Just to be clear about workaround solutions: Loading parts of Facebook into an iframe is not allowed and not possible. More information: Load Facebook into an iframe
Meaning, if you try to load any part of facebook.com in an iframe, you will get the following error in your console:

Load denied by X-Frame-Options:
  https://www.facebook.com/events/upcoming does not permit framing.

...which basically means that you are not allowed to load any part of facebook.com in an iframe.

A: Short answer: Facebook doesn't allow that anymore (as of Graph API 2.0).
Facebook has removed that functionality in Graph API 2.0 (probably to avoid spams). That's unfortunate as it was a cool integration for useful apps.
Here you can see the changelog stating that this functionality is not available anymore: https://developers.facebook.com/docs/apps/changelog
Create event Removed - Apps can no longer create events with the API.
Now, I'm thinking that they could allow such an integration for special partners. E.g. Zapier seems to have an integration that creates Facebook events for your Google events, thus I'm guessing it's possible if you can strike a deal with Facebook:
https://zapier.com/zapbook/google-calendar/facebook-pages/6308/create-facebook-page-event-from-google-calendar-event/
But at the same time, another big event provider, Eventbrite, seems not to have managed to secure such a deal (not yet at least):
http://help.eventbrite.com/customer/portal/articles/428611-how-to-publish-your-eventbrite-event-to-facebook
Thus, short answer is that Facebook doesn't want you to create events on their platform, whatever their reason is.
Technically it is possible, but it's nasty
Now, if you really want to do it, there is a way, though I wouldn't recommend it as it relies on the structure of the DOM of the Facebook page. Here how (most of the below is done in JavaScript):

*

*you use an internal frame to load the facebook events page home.

*you 'click' the create event button behind the scenes, using javascript

*you create a similar interface to capture all those fields in your application.

*once the user clicks 'submit' on your page, after filling in all those details, you copy those to the Facebook DOM to the corresponding fields and submit that page (using JS again).

*You search the newly created event (you can do this using Graph API) and show it to the user.

*Voila, you now have created a Facebook event and the user won't even know it.

NOTE: This is heavily relying on the structure of the Facebook DOM, thus a small change in the DOM of the Facebook Events page might break your functionality ... not the best user experience.


text:
Q: How to use ELSE statement in .bat file that has multiple IF statements? I'm writing a Windows batch file to enable, disable or make manual a Windows Service.
How would you use an ELSE statement if you have multiple IF options?
For example:
if /I "%c%" EQU "A"  goto :automatic
if /I "%c%" EQU "M"  goto :manual
if /I "%c%" EQU "D"  goto :disabled

I need an ELSE statement to send the script to an ECHO line that returns an error message if the user enters anything other than A, M or D.
Thanks for your help.

A: Ken White already showed you the perfect solution in his answer.
I want to show you how complicated it were in case you really wanted to use else clauses.
Let us stick to the following code:
if /I "%c%" EQU "A"  goto :automatic
if /I "%c%" EQU "M"  goto :manual
if /I "%c%" EQU "D"  goto :disabled
echo Wrong user input!

*

*Separate if/else statements:
The parentheses are mandatory; the :message block can be elsewhere in the script:
if /I "%c%" EQU "A"  goto :automatic
if /I "%c%" EQU "M"  goto :manual
if /I "%c%" EQU "D" (goto :disabled) else goto :message

:message
echo Wrong user input!

*Nested if/else statements:
if /I "%c%" EQU "A" (goto :automatic) else (
    if /I "%c%" EQU "M" (goto :manual) else (
        if /I "%c%" EQU "D" (goto :disabled) else (
            echo Wrong user input!
        )
    )
)

Or written in a different way:
if /I "%c%" EQU "A" (
    goto :automatic
) else if /I "%c%" EQU "M" (
    goto :manual
) else if /I "%c%" EQU "D" (
    goto :disabled
) else (
    echo Wrong user input!
)

Or more compact:
if /I "%c%" EQU "A" (goto :automatic
) else if /I "%c%" EQU "M" (goto :manual
) else if /I "%c%" EQU "D" (goto :disabled
) else echo Wrong user input!

As you can see, Ken White's solution is still the simplest and most legible one.

By the way, Squashman suggested a very good alternative, namely the choice command:
choice /C AMD /N /M "Select mode - [A]utomatic, [M]anual or [D]isabled: "
if ErrorLevel 3 goto :disabled
if ErrorLevel 2 goto :manual
if ErrorLevel 1 goto :automatic
goto :eof

A: Just adding another goto without a condition will work:
if /I "%c%" EQU "A"  goto :automatic
if /I "%c%" EQU "M"  goto :manual
if /I "%c%" EQU "D"  goto :disabled
goto :ErrorInfo

If none of the first three are acceptable, the code falls through to the last one, which would take them to whatever code you want to execute if an unacceptable value was entered (or none at all).

A: Evaluating single letter user input can be eased if you append the letter(s) to a label prefix and check aginst a given set:
@Echo off
:Cont
Set MSG="Press [A]utomatic, [M]anual or [D]isabled :"
Set Choices=AMD
Set /P c=%MSG%
Echo:%Choices%|Find /i "%c:~0,1%" >NUL 2>&1 && Goto :Choice%c% || Goto :BadChoice

:Badchoice
Echo %c% is a bad choice
Goto :Cont

:ChoiceA
Echo ChoiceA
Goto :Cont

:ChoiceM
Echo ChoiceM
Goto :Cont

:ChoiceD
Echo ChoiceD
Goto :Cont

Or very similar incorporating Squashman's suggestion with choice.exe (here also with a 10 second timeout on the first letter):
@Echo off&Setlocal EnableDelayedExpansion
:Cont
Set MSG="Press [A]utomatic, [M]anual or [D]isabled :"
Set Choices=AMD
CHOICE /C %Choices% /T 10 /D %Choices:~0,1% /M %MSG%
Set /A _=%Errorlevel% - 1
If %_% lss 255 Goto :Choice!Choices:~%_%,1!

:Badchoice
Echo %c% is a bad choice
Goto :Cont

:ChoiceA
Echo ChoiceA
Goto :Cont

:ChoiceM
Echo ChoiceM
Goto :Cont

:ChoiceD
Echo ChoiceD
Goto :Cont

A: I think this is the simplest way:
setlocal EnableDelayedExpansion
set "options=AMD"

if "!options:%c%=!" neq "%options%" (
   goto :option-%c%
) else (
   goto badOption
)

:option-A automatic
echo Automatic
goto continue

:option-M manual
echo Manual
goto continue

:option-D disabled
echo Disabled
goto continue

First, a string with valid options is defined. Then, the if command check if %c% is one of such options; if the answer is Yes, the goto :option-%c% command directly jumps to the desired label without the use of any additional if. This method is very efficient, specially if there are a lot of different options. If you want to add more options just add letters to the string, not additional if commands.