text:
Q: How to fetch FLAGS of an email using IMAP libcurl? I want to get FLAGS of an email that I fecthed with libcurl.
How can I design the url?
I just can get header and mime body, not including FLAGS of individual mail with current code.
Even though I searched through RFC documents,
I couldn't find any examples on url scheme which can also fetch FLAGS.
If you can provide me with some tips on the url, I would appreciate it.

A: FLAGS can't be fetched via libcurl, in part because they can't be addressed using a URL. The RFC says what can be addressed:

The IMAP URL scheme is used to designate IMAP servers, mailboxes,
  messages, MIME bodies, and search programs


text:
Q: CSS file wont load This is my jsp page
<%--
  Created by IntelliJ IDEA.
  User: stefa
  Date: 8/26/2021
  Time: 3:24 PM
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">

    <title>Title</title>
    <link rel="stylesheet" type="text/css" href="resources/css/login.css/">

        <form>
            <input type="text" id="login" class="fadeIn second" name="login" placeholder="login">
            <input type="text" id="password" class="fadeIn third" name="login" placeholder="password">
            <input type="submit" class="fadeIn fourth" value="Log In">
        </form>

            Forgot Password?

You can see how I tried to implement css file

How to fix this? What can I try more? Why my program wont load css file? I also tried to put css in auto created resources folder but still doesnt work

redpajama_set_name: RedPajamaStackExchange


text:
Q: custom ViewGroup example? I searched here on SO, on Google, on the android docs...
But I cannot find a single snippet of code with a example of custom viewgroup, I find at most some vague explanations...
Can someone provide one? How you make a viewgroup where you can put its children where you want?

A: I think the simplest example to look at is the source for AbsoluteLayout.java
https://github.com/android/platform_frameworks_base/blob/master/core/java/android/widget/AbsoluteLayout.java
You need to override onMeasure to measure the children and onLayout to position them.
I have strikingly more complicated ViewGroup code I can share as well if you want.

A: It't quite simple, all you need to do is to call super.onMeasure after calculate the exact dimentions of yout view.
class ProportionalConstraintLayout @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {

        val exactWidth = 100 //do something to calculate the view widht
        val exactHeight = 100 //do something to calculate the view height

        setMeasuredDimension(exactWidth, exactHeight)
        super.onMeasure(
            MeasureSpec.makeMeasureSpec(exactWidth, MeasureSpec.EXACTLY),
            MeasureSpec.makeMeasureSpec(exactHeight, MeasureSpec.EXACTLY)
        )

    }

}


text:
Q: ASP.Net make it work with a different format of jsonstring I have created this vb.net file and it is working when i send a string like this:
?data={"id":"12345","timestamp":"2012-03-03 12:00:00","latitude":"23.41223","longitude"="54.12345"}

but i also want it to work with a format like this:
?id=12345&timestamp=2012-03-03 12:00:00&latitude=23.41223&longitude=54.12345

How do i make this work in my vb.net file
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not String.IsNullOrEmpty(Request.QueryString("data")) Then
            Dim data As String = Request.QueryString("data")

            Dim myObj As New MyObject
            Dim properties() As PropertyInfo = myObj.GetType().GetProperties()
            Dim values() As String = Server.UrlDecode(data).Replace("[", "").Replace("]", "").Replace("{", "").Replace("}", "").Replace(""":""", """=""").Split(New Char() {","}, StringSplitOptions.RemoveEmptyEntries)
            For Each value As String In values
                Dim keyValue() As String = value.Split(New Char() {"="}, StringSplitOptions.RemoveEmptyEntries)
                For Each prop As PropertyInfo In properties
                    If prop.Name.ToLower = keyValue(0).ToLower.Replace("""", "") Then
                        prop.SetValue(myObj, keyValue(1).Replace("""", ""), Nothing)
                    End If
                Next
            Next

        lblText1.Text = String.Format("ID: {0}", myObj.ID)
        lblText2.Text = String.Format("Longitude: {0}", myObj.Longitude)
        lblText3.Text = String.Format("Latitude: {0}", myObj.Latitude)
        lblText4.Text = String.Format("Timestamp: {0}", myObj.Timestamp)

    Cmd.Parameters.Clear()
    Cmd.Parameters.AddWithValue("@ID", myObj.ID)
    Cmd.Parameters.AddWithValue("@Longitude", myObj.Longitude)
    Cmd.Parameters.AddWithValue("@Latitude", myObj.Latitude)
    Cmd.Parameters.AddWithValue("@Timestamp", myObj.Timestamp)

    Con.ConnectionString = "Data Source=servert\sql;Initial Catalog=table;Integrated Security=True"
        Cmd.Connection = Con
        Con.Open()
    Cmd.CommandText = "IF EXISTS (SELECT 1 FROM Locatie WHERE id = @ID) " & Environment.NewLine & _
                  "  BEGIN UPDATE Locatie SET Longitude = @Longitude, Latitude = @Latitude, Timestamp = @Timestamp WHERE id=@ID END " & Environment.NewLine & _
                  "ELSE " & Environment.NewLine & _
                  "   BEGIN INSERT INTO Locatie VALUES (@ID, @Longitude, @Latitude, @Timestamp) END "

     Reader = Cmd.ExecuteReader

        Reader.Close()
       Con.Close()
       Con.Dispose()

        End If

    End Sub

    Public Class MyObject
        Private _ID As String
        Private _Longitude As String
        Private _Latitude As String
        Private _Timestamp As String

        Public Property ID As String
            Get
                Return _ID
            End Get
            Set(value As String)
                _ID = value
            End Set
        End Property

        Public Property Longitude As String
            Get
                Return _Longitude
            End Get
            Set(value As String)
                _Longitude = value
            End Set
        End Property

        Public Property Latitude As String
            Get
                Return _Latitude
            End Get
            Set(value As String)
                _Latitude = value
            End Set
        End Property

        Public Property Timestamp As String
            Get
                Return _Timestamp
            End Get
            Set(value As String)
                _Timestamp = value
            End Set
        End Property

    End Class

</script>

Where probably the key must be around here, so that there is also a second option where the second string is split set the values as id, longitude, latitude and timestamp:
 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not String.IsNullOrEmpty(Request.QueryString("data")) Then
            Dim data As String = Request.QueryString("data")

            Dim myObj As New MyObject
            Dim properties() As PropertyInfo = myObj.GetType().GetProperties()
            Dim values() As String = Server.UrlDecode(data).Replace("[", "").Replace("]", "").Replace("{", "").Replace("}", "").Replace(""":""", """=""").Split(New Char() {","}, StringSplitOptions.RemoveEmptyEntries)
            For Each value As String In values
                Dim keyValue() As String = value.Split(New Char() {"="}, StringSplitOptions.RemoveEmptyEntries)
                For Each prop As PropertyInfo In properties
                    If prop.Name.ToLower = keyValue(0).ToLower.Replace("""", "") Then
                        prop.SetValue(myObj, keyValue(1).Replace("""", ""), Nothing)
                    End If
                Next
            Next

A: Do a check on the query string. If the string starts with data, then allocate values to the variables using the first method, else allocate values to variables by getting the value of the query string.
Example:
If Not String.IsNullOrEmpty(Request.QueryString("data")) Then
    'Use reflection logic
Else
    MyObj.Longitude = Request.QueryString("longitude")
End If

Edit
Example of the implementation within the provided Page_Load subroutine.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim myObj As New MyObject

    If Not String.IsNullOrEmpty(Request.QueryString("data")) Then
        Dim data As String = Request.QueryString("data")

        Dim properties() As PropertyInfo = myObj.GetType().GetProperties()
        Dim values() As String = Server.UrlDecode(data).Replace("[", "").Replace("]", "").Replace("{", "").Replace("}", "").Replace(""":""", """=""").Split(New Char() {","}, StringSplitOptions.RemoveEmptyEntries)
        For Each value As String In values
            Dim keyValue() As String = value.Split(New Char() {"="}, StringSplitOptions.RemoveEmptyEntries)
            For Each prop As PropertyInfo In properties
                If prop.Name.ToLower = keyValue(0).ToLower.Replace("""", "") Then
                    prop.SetValue(myObj, keyValue(1).Replace("""", ""), Nothing)
                End If
            Next
        Next
    Else
        If Not (String.IsNullOrEmpty(Request.QueryString("id")) Then
            myObj.ID = Request.QueryString("id")
        Else
            myObj.ID = "Not set"
        End If

        If Not (String.IsNullOrEmpty(Request.QueryString("longitude")) Then
            myObj.Longitude = Request.QueryString("longitude")
        Else
            myObj.Longitude = "Not set"
        End If

        If Not (String.IsNullOrEmpty(Request.QueryString("latitude")) Then
            myObj.Latitude = Request.QueryString("latitude")
        Else
            myObj.Latitude = "Not set"
        End If

        If Not (String.IsNullOrEmpty(Request.QueryString("timestamp")) Then
            myObj.Timestamp = Request.QueryString("timestamp")
        Else
            myObj.Timestamp = "Not set"
        End If
    End If

    lblText1.Text = String.Format("ID: {0}", myObj.ID)
    lblText2.Text = String.Format("Longitude: {0}", myObj.Longitude)
    lblText3.Text = String.Format("Latitude: {0}", myObj.Latitude)
    lblText4.Text = String.Format("Timestamp: {0}", myObj.Timestamp)

    'Rest of sub here
End Sub


text:
Q: Ускорить процесс выборки из БД Есть два класса: сервер и матч.
public class Server
{
    public int Id {get; set;}
    ...
    public virtual ICollection<Match> Matches {get; set;}
}

public class Match
{
    public int Id {get; set;}
    public sting Timestamp {get; set;}
    ...
    public virtual Server Server {get; set;}
}

Между ними связь One-to-many. Нужно посчитать среднее количество матчей в день на каждом сервере.
Сейчас это делаю примерно так (пробовал по-разному):
в классе сервер определил метод
public double GetAverageMatchesByDay()
{
    if (Matches.Count == 0) return 0;

    retrun Matches
           .ToList()
           .GroupBy(m => DateTimeOffset.Parse(m.Timestamp).UtcDateTime.Date)
           .Select(g => g.Count())
           .Average();
}

Ну и дальше, где нужно:
foreach(var server in context.Servers)
{
    var averageMatchesPerDay = server.GetAverageMatchesPerDay();
}

Проблема в том, что при 10 000 серверов и всего лишь по 10 матчей на каждом, это работает уже очень долго, матчей предполагается гораздо больше.
Как правильно реорганизовать связь, либо способ хранения, либо способ выборки всего этого, чтобы скорость ответа не превышала пару секунд?
Заранее спасибо.


text:
Q: Update 2 lines with When I have the table below which has similar names in the column 'Nam':

I need to update the column status with the condition below:
If val2 > Val1 (either in first line or in the second line)-->both status should change to "OK"
IF  val2 in both lines are smaller than Val1 (in both lines) -->  Status=False'
I don't know how to update this condition like (if else)
Thanks for your help.

A: You can do it with EXISTS:
UPDATE t1
SET t1.Status = CASE
  WHEN EXISTS (SELECT 1 FROM tablename t2 WHERE t2.Nam = t1.Nam AND t2.Val2 > t2.Val1) THEN 'OK'
  ELSE 'False'
END
FROM tablename t1

See the demo.

A: You can use window functions and an updatable CTE:
with toupdate as (
      select t.*,
             sum(case when val2 >= val1 then 1 else 0 end) over (partition by nam) as num_increasing,
             sum(case when val2 <= val1 then 1 else 0 end) over (partition by nam) as num_decreasing
      from t
     )
update toupdate
    set status = (case when num_increasing = 0 then 'false' else 'ok' end)
    where num_increasing = 0 or num_decreasing = 0

Note that this is doing the "inverse" of your logic -- counting the exceptions.


text:
Q: Deleted files upon project name change I had a working application.  I changed the project name through the targets section.  A pop up window came through concerning changing references.  I didn't read it thoroughly and accepted the changes.  Now 2 files are missing from my project and I don't see them in my project folder or in the trash.
How might I find them?  Undoing is not an option.  Time machine is not an option.  I do however have a 'good' build on my actual iPhone.  Can I recover that project?

A: I'm afraid it's probably not looking good. First of all, you won't be able to recover the files from your iPhone, unless they're assets (ie, graphics, media, etc). If it's actual code, that's a no go.
Secondly, when you rename a project XCode will ask you if you want to take a snapshot of the project - did you enable this? If you did you'll be able to roll back to the project status before you made the change.
Of course, perhaps the project files still exist and they're just hiding in your project: in this case if you can remember something inside the files you can grep your project directory for them (grep is a command line utility that lets you search inside of files: if you're unfamiliar with it you can check this guide out).
If none of that works, consider this a lesson in version control. XCode has built in support for Git now - if you've never used Git or version control this could be a great time to learn. Version control lets you keep a history of all the changes you've made and roll back as appropriate (if, for example, you accidentally delete a file or make a change that turns bad). I'm simplifying a lot, but there's a lot of great resources online about using Git, and now that it's totally unified with XCode there's no real excuse not to use it.


text:
Q: Не работает update msql Есть код :
                     <?php

$query = "SELECT DISTINCT title FROM jos_categories";
$result = mysql_query($query);

$query2 = "SELECT DISTINCT metadesc FROM jos_categories";
$result2 = mysql_query($query2);

 while ($row=mysql_fetch_assoc($result))
                            {
                            $title = $row['title'];
                            };
$meta_create = "UPDATE jos_categories SET metadesc = $title";
$result3 = mysql_query($meta_create);

?>

Нужно в поле metadesc вставить значение из поля title, но не вставляется...


text:
Q: How to add index from JSX map to CSS file? I have n dropdown input element which I am re-using in differernt parts of different applications. The dropdown input element has options with dropdowns inside of itself. The dropdowns can vary in length, and have 50 options or just 5. Something like this:

I need to add some styling based on a class react-select-2-option-[indexOfTheOptionWithDropdown]. For example the dynamic css class for Sydney 333 is react-select-2-option-2 because it's the second dropdown element in the whole input.
Sydney 333222 has a dynamic class of react-select-2-option-1.
However, I have no idea how to do it in a way that the application would be able to recognize how many options with dropdowns there are and assign an index to each classes ending based on the length and position in the array of options. I need it because the 'react-select' library is assigning default styles which are seemingly impossible to overwrite any other way. I could just hardcode it, although that seems pretty static and anti-codish?
I'm mapping the options in a JSX component with index numbers. And ideally, I'd need to send that index to the CSS file somehow. Is it even possible? Should I use something like styled css components and pass index to overwrite the CSS, or is there some other way to achieve this?
EDIT:
hard coded react-select-2-option-4:hover with white background

default style ( options have a grey background, and do not show that and item is hovered over )

A: You can use an index to define a CSS class name like the one below.
var options = <list of DOM options like Sydney 333222 and Sydney 333>;
for (var i in options) {
  options[i].className = `react-select-2-option-${i}`;
}

But this is a strange approach. It's better for you to use a variable with common CSS and apply this to the specific style:
var commonCss = { color: 'red', fontWeight: 'bold' };
var especificCss = [{ border: 'solid 1px blue'}];
var options = <list of DOM options like Sydney 333222 and Sydney 333>;
for (var i in options) {
  Object.keys({ ...commonCss, ...especificCss[i]}).forEach(function(key) {
    options[i][key].className = options[key];
  });
}

Also you can to define a class css with the common style and them apply only the specific.
var especificCss = [{ border: 'solid 1px blue'}];
var options = <list of DOM options like Sydney 333222 and Sydney 333>;
for (var i in options) {
  Object.keys(especificCss[i]).forEach(function(key) {
    options[i][key].className = options[key];
  });
}


text:
Q: django-haystack SearchView has no as_view() I have a view
class CustomSearchView(SearchView):
    template_name = "bunkering/search.html"
    queryset = SearchQuerySet().all()
    form_class = SearchForm

subclassing SearchView imported with
from haystack.forms import ModelSearchForm, SearchForm
from haystack.views import SearchView, FacetedSearchView

In my urls.py I use
url(r'^search/$', CustomSearchView.as_view(), name='search'),

But when I visit my site, I get AttributeError
'super' object has no attribute 'as_view'

What am I doing wrong?

A: You should import base SearchView from haystack.generic_views not from haystack.views.
Classes from generic_views are standard Django class-based views and support as_view method.


text:
Q: Thread-safety and concurrent modification of a table in SQLite3 Does thread-safety of SQLite3 mean different threads can modify the same table of a database concurrently?

A: No - SQLite does not support concurrent write access to the same database file. SQLite will simply block one of the transactions until the other one has finished.

A: note that if you're using python, to access a sqlite3 connection from different threads you need to disable the check_same_thread argument, e.g:
sqlite.connect(":memory:", check_same_thread = False)
as of the 24th of may 2010, the docs omit this option. the omission is listed as a bug here

A: Not necessarily. If sqlite3 is compiled with the thread safe macro (check via the int sqlite3_threadsafe(void) function), then you can try to access the same DB from multiple threads without the risk of corruption. Depending on the lock(s) required, however, you may or may not be able to actually modify data (I don't believe sqlite3 supports row locking, which means that to write, you'll need to get a table lock). However, you can try; if one threads blocks, then it will automatically write as soon as the other thread finishes with the DB.

A: You can use SQLite in 3 different modes:
http://www.sqlite.org/threadsafe.html
If you decide to multi-thread mode or serialized mode, you can easy use SQLite in multi-thread application.
In those situations you can read from all your threads simultaneously anyway. If you need to write simultaneously, the opened table will be lock automatycally for current writing thread and unlock after that (next thread will be waiting (mutex) for his turn until the table will be unlocked). In all those cases, you need to  create separate connection string for every thread (.NET Data.Sqlite.dll). If you're using other implementation (e.g. any Android wrapper) sometimes the things are different.


text:
Q: common strings in two lists of strings in Python I have two lists of strings:
a = ['ab','ac','ad',..., 'aba','abc',...] # n = 10000 of unique strings
b = ['ab', 'ac', ..., 'ab']               # m = 100 have duplicates
c = []

How to find common string between these two strings? My solution runs in m*n complexity (right?):
    for i in a:
        if i in b:
            c.append(i)

is there a way to solve it in O(m) time complexity?

A: since the value in a are unique, so you can create a dict, in O(n), to access and check that element in O(1).
Iterate through b and check each element of b with dict in O(1), it will save time then using set operation and also include if there are same multiple same element present in b and in a also
a = ['ab','ac','ad', 'aba','abc'] # n = 10000 of unique strings
b = ['ab', 'ac', 'ab', 'kk']               # m = 100 have duplicates
c = []

a_dic = {i:1 for i in a}
sol = []

for i in b:
    if a_dic.get(i, None):
        sol.append(i)

A: You can convert your lists to set and do a intersection on them using &:
>>> a = ['ab','ac','ad','aba','abc']
>>> b = ['ab', 'ac', 'ab']

>>> set(a) & set(b)
{'ab', 'ac'}

Set Intersection returns elements which are common in both the sets. But note: Since set are unordered, you won't be able to maintain the order from list a or b if that's needed.
Here's a functional approach to achieve the same using set.intersection() method:
>>> set(a).intersection(b)
{'ac', 'ab'}


text:
Q: Text Generation in Deep Learning Tensorflow I am currently doing text generation in tensorflow. After training the model, when predicting the text and decoding the numbers to text why we used tf.random.categorical(predictions, num_samples=1)[-1,0].numpy??

A: 1.: tf.random.categorical just returns one of the argument numbers (not the argument itself) that have the greatest probability, based on the probability distribution that it takes as an argument - predictions in this case. It only returns one since we set num_samples=1.
(For a better answer on what exactly tf.random.categorical does, look here.)
2.: [-1,0] is simple index slicing, we just take the first element of the last element.
We take it from the last element since the output is always just the input offset by one position, hence the last element is the new word - and that's what we're searching for in this case.
3.: And numpy() is being used because we don't (usually) want to deal with tensors at this point. The return of tf.random.categorical is a tensor. So we convert it using numpy().


text:
Q: Failed to Find Keys at Zone Apex I'm trying to create a signed zone file, but previous examples are not working for me. See below
[root@dnsserv1 named]# dnssec-keygen -r /dev/random -a RSASHA1 -b 1024 -n ZONE example.edu
Generating key pair.........................+++++ ..............................................+++++
example.edu.+005+56778

# Create KSK
[root@dnsserv1 named]# dnssec-keygen -r /dev/random -a RSASHA1 -b 1024 -n ZONE -f KSK example.edu
Generating key pair........................................................................+++++ ..........+++++
example.edu.+005+27182

[root@dnsserv1 named]#  dnssec-signzone -o example.edu -k  'example.edu.+005+56778' example.edu.zone  'example.edu.+005+27182.key'
dnssec-signzone: warning: example.edu.zone:1: no TTL specified; using SOA MINTTL instead
dnssec-signzone: fatal: failed to find keys at the zone apex: not found

This "failed to find keys at the zone apex: not found" error doesn't seem like it's common. If I search for it on Google, almost nothing comes up. Did I forget to do something? I've tried many different variants on what's shown above.


text:
Q: Bypassing session login redirect for index robots only using express middleware I've written a webapp on NodeJS Express/SailsJS, all my internal content pages are protected by an authentication session middleware using passportJS. So far so good.
Thing is, I want to be able to render the pages freely without redirecting to login only for certain user agents so pages are indexable but not renderable for a user browser.
How do I achieve that? I've explored building a custom middleware that transcends the authentication mechanism but haven't had any accomplishments yet.


text:
Q: How do you style a office fabric react component? I can't figure out how to style the fabric ui component.  I just want to change the background of the nav bar to be black with white phone instead of white background and black font.  However, this seems to be really difficult with the current component.
There is virtually no documenation on how to style either.
https://dev.office.com/fabric#/components/nav
Thanks,
Derek

A: css inline not working?
Example:
style={{backgroundColor:'black', color:'white'}}

Regards.


text:
Q: postgresql rename multiple substrings in a json string with one query I want to save update requests. So instead of doing this:
update table set column = REPLACE(column,'abc','xyz');
update table set column = REPLACE(column,'def','uvw');
...

I would like to do something like this:
UPDATE table
SET column =
CASE
    WHEN column like '%"abc":%' THEN REPLACE(column,'"abc":','"xyz":')
    WHEN column like '%"def":%' THEN REPLACE(column,'"def":','"uvw":')
    ...
END
WHERE COLUMN2 = 'something';

But this is not doing the kind of loop I need. It replaces only the first match it finds.
I know I can also do something like this:
update table
set column = REPLACE(REPLACE(column,'abc','xyz'),'def','uvw')
where COLUMN = 'something';

But I don't know about the performance of each of them.

A: You can try different formatting for nested replaces:
update table
set column =    REPLACE(
                REPLACE(
                REPLACE(
                REPLACE(column, 'abc','xyz'),
                                'def','uvw'),
                                'zxc','acv'),
                                'xcv','bvn')
where COLUMN = 'something';


text:
Q: Having aliases active in a terminal session without using bashrc or bash_profile or bash_aliases? This question is an offshoot of my question on whether there's anything wrong with having aliases on a production server.
So I tried creating a shell script with some aliases
#!/bin/sh
echo "creating aliases..."
alias f='clear;cd ..;ls;pwd'
alias ff='clear;cd ../..;ls;pwd'

Did a chmod +x al.sh, and ran the script ./al.sh, but although the "creating aliases..." statement got printed, none of the aliases worked, because they were obviously active only until the script ran.
So is there a way I can run a script containing the aliases I want, which will remain active as long as the terminal session is active? The basic idea being, not to cause problems for colleagues who use the same server.

A: For cases when you want to store functions and aliases just for your session, I find it quite useful to have a file with them and sourcing it when I login the server.
So just place it somewhere like:
~/nav_alias_file.sh

And then just after sshing the server type:
source ~/nav_alias_file.sh

Note by the way that, as Sundeep expressed in comments, you do not need the shebang in that file.


text:
Q: JSON Object validation with JSONSchema Validator const Validator = require('jsonschema').Validator;

const validator = new Validator();

const obj =
  [
    {
    "id":"1",
    "firstname":"Jack"
    }
  ];

const instance= {
      properties: {
        id: {
          type: 'number'
          },
          firstname: {
            type: 'string'
        }
      },
      required: ['id', 'firstname'],
      additionalProperties: false
};
const  result = validator.validate(obj, instance);
console.log(result.errors);

I want to validate a JSON Object using jsonschema Validator. when json object is not as per schema, then also validate function is not returning any error. irrespective of obj being as per schema/instance or not, its error section always returning null.

A: You've defined obj as an array as opposed to an object. As a result, validation is passing because you've used JSON Schema keywords which only apply to objects. (Many JSON Schema keywords are only applicable to specific types.)
In your schema, add "type": "object", and you should see an error when the instance is not an object.
On a side note, an "instance" is the data you want to validate, and a "schema" is the JSON Schema you want to use for validation.


text:
Q: How Can I Open the Modal Dialog Box in Checkout Authentication? I want to make it so that when any User buys a product, when checkout is clicked on then the first modal dialog box opens to either login or use a guest account to purchase the product.

A: Edit: Checkout the Code below or in the attached link
Link:
magento/magento2/blob/487f5f45/app/code/Magento/Checkout/view/frontend/web/js/sidebar.js#L52-L66
Code:
events['click ' + this.options.button.checkout] = $.proxy(function () {
    var cart = customerData.get('cart'),
        customer = customerData.get('customer');
if (!customer().firstname && cart().isGuestCheckoutAllowed) {
    if (this.options.url.isRedirectRequired) {
        location.href = this.options.url.loginUrl;
    } else {
        authenticationPopup.showModal();
    }

    return false;
}
location.href = this.options.url.checkout;
}, this);


text:
Q: Each then() should return a value or throw Firebase cloud functions I am writing a cloud function for firebase using javascript but I am stuck, I don't know the exact meaning of error and unable to solve it..
The error states: 27:65  error    Each then() should return a value or throw  promise/always-return
'use strict'

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.sendNotification = functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite((change, context) => {

    const user_id = context.params.user_id;
    const notification_id = context.params.notification_id;
    console.log('We have a notification from : ', user_id);

    if (!change.after.val()) {
        return console.log('A Notification has been deleted from the database : ', notification_id);
    }
    const deviceToken = admin.database().ref(`/ServiceProvider/${user_id}/device_token`).once('value');
    return deviceToken.then(result => {
        const token_id = result.val();
        const payload = {
            notification: {
              title : "New Friend Request",
              body: "You Have Received A new Friend Request",
              icon: "default"
            }
        };

        return admin.messaging().sendToDevice(token_id, payload).then(response => {

            console.log('This was the notification Feature');

        });

    });

});

A: Change this:
    return admin.messaging().sendToDevice(token_id, payload).then(response => {

    console.log('This was the notification Feature');

  });

into this:
    return admin.messaging().sendToDevice(token_id, payload).then(response=>{
      console.log('This was the notification Feature');
      return true;
    },err=>
    {
      throw err;
    });

As the error says when using then you need to return a value.

A: Change this:
    return admin.messaging().sendToDevice(token_id, payload).then(response => {

        console.log('This was the notification Feature');

    });

To this:
    return admin.messaging().sendToDevice(token_id, payload).then(response => {

        console.log('This was the notification Feature');
        return null;   // add this line

    });

The then callback just needs to return a value.
However, eslint may then complain about nested then() in your code, which is also an anti-pattern.  Your code should really be structured more like this:
const deviceToken = admin.database().ref(`/ServiceProvider/${user_id}/device_token`).once('value');
return deviceToken.then(result => {
    // redacted stuff...
    return admin.messaging().sendToDevice(token_id, payload);
}).then(() => {
    console.log('This was the notification Feature');
});

Note that each then chains off of each other, rather than being nested inside each other.

A: That's jslinting telling you that each .then must include a return value. In other words, avoid promise anti pattern.
You might find async functions easier to wrap your head around. Note that you'll need to run the Node 8 runtime for async support though...


text:
Q: How can I query Amazon dynamoDB to get recent 20 data in android? Hi what I'm trying to do is getting recent data from my AWS dynamoDB.
In my database, the sort key is lastUpdatedDate and the partition key is userId.
I've found that I should set 'limit' as condition to get only 20 data.
But I don't know how to sort my data with my sort key.
Maybe I should get my largest lastUpdatedDate and sort with it, but I cannot do that.
Please help me!

A: Please note that LIMIT has slightly different meaning compared to LIMIT available in some SQL databases.
Limit:-

The maximum number of items to evaluate (not necessarily the number of
  matching items). If DynamoDB processes the number of items up to the
  limit while processing the results, it stops the operation and returns
  the matching values up to that point, and a key in LastEvaluatedKey to
  apply in a subsequent operation, so that you can pick up where you
  left off. Also, if the processed data set size exceeds 1 MB before
  DynamoDB reaches this limit, it stops the operation and returns the
  matching values up to the limit, and a key in LastEvaluatedKey to
  apply in a subsequent operation to continue the operation. For more
  information, see Query and Scan in the Amazon DynamoDB Developer
  Guide.

ScanIndexForward:-

You can use the ScanIndexForward parameter to get results in forward
  or reverse order, by sort key.


text:
Q: Crash when trying to sort an array I am trying to make a highscore page in a space shooter game I made. So, what I do is save the score using this code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSNumber *highscore = [[NSNumber alloc] initWithInt:_totalSeconds];
NSString *choice = [NSString stringWithFormat:@"%@/userschoice", documentsDirectory];
NSMutableArray *array = [NSArray arrayWithContentsOfFile:choice];
[array addObject: highscore];
[array writeToFile:choice atomically:YES];

Where the integer _totalSeconds is the user's score. Then, in my viewDidLoad function, I put this code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *choice = [NSString stringWithFormat:@"%@/userschoice", documentsDirectory];
NSMutableArray *array = [NSArray arrayWithContentsOfFile:choice];
int _highscoresAmount = [array count];
NSNumber *highscore2 = [[NSNumber alloc] init];
NSNumber *highscore2Two = [[NSNumber alloc] init];

int _count = 0;

while (_count<_highscoresAmount){

    for (int i=0; i<_highscoresAmount; i++){

        int j = i+1;
        highscore2 = [array objectAtIndex:i];
        highscore2Two = [array objectAtIndex:j];
        if (highscore2Two > highscore2){

            [array replaceObjectAtIndex:i withObject:highscore2Two];
            [array replaceObjectAtIndex:j withObject:highscore2];

        }

}

    _count = _count + 1;

}

for (int i=0; i< _highscoresAmount;i++){

    highscore2 = [array objectAtIndex:i];
    NSString *highscore3 = [NSString stringWithFormat:@"%@", highscore2];
    NSLog(highscore3);

}

The goal of this code is to retrieve the array that I wrote in the file with the path specified in my code. Then, I want to sort the array from highest to lowest.
This builds fine, but when I load the view, the app crashes. What is the problem?
Note: I also tried doing a for loop inside of a for loop using similar code and the same problem occured.
Also, here is the crash log:
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
unable to read unknown load command 0x22
kill
quit

A: I see two major things wrong here. The first is that you're declaring the array as NSMutableArray, but actually making an NSArray. You need to use [NSMutableArray arrayWithContentsOfFile:] to make a mutable array.
The second is that you shouldn't be implementing your own sorting algorithm. Just use the built in sorting methods (-sortUsingComparator: for example)
(edit)
Oh, also, you should use -stringByAppendingPathComponent rather than +stringWithFormat, for constructing paths


text:
Q: Google Form Script Population I am trying to populate a google form with questions scraped from a google sheet. Currently when I run my code I am getting the questions created, but only 25% or so actually have the string, the rest are simply blank. The questions that appear correctly change every time I run the script. It is seemingly random.
function formPopulation() {
  var ss = SpreadsheetApp.openById("--");
  var sheet = ss.getSheetByName('Tracker');
  var auditTool = ss.getSheetByName('Audit Tool');
  var validatorInfo = ss.getSheetByName('Validator Info');
  //Sheet Info

  var rows = auditTool.getLastRow(); //Number of Rows
  var columns = auditTool.getLastColumn(); //Number of Columns

  var startRow = 1;
  var startColumn = 1;

  var dataRange = auditTool.getRange(startRow, startColumn, rows, columns);
  //getRange(first row of data, first column of data, last row of data, last column of data)

  var data = dataRange.getValues();
  //Sets working range of script

  var form = FormApp.openById("--");
  var item = form.addListItem();

  var entityName = "";
  var arrayOfEntities = [];
  var newEntity = '';

  for (var i = 4; i < columns; i++) {
     //4 because that is where entity names begin
     entityName = data[i][2];
     Logger.log('entityName: ' + entityName);
     newItem = item.createChoice(entityName);
     arrayOfEntities.push(newItem);
  };

  item.setTitle("Select Entity").setChoices(arrayOfEntities);

  var requirement = "";
  var arrayOfRequirements = [];
  var newRequirement = '';

  for (var j = 5; j < rows; j++) {
     //5 because that is where Requirements begin
     if (data[0][j] != null)  {
     requirement = data[0][j];
           if (requirement != "" || requirment != null){
             requirement = "question #" + j;
             Logger.log('requirement: ' + requirement);
             form.addMultipleChoiceItem().setTitle(requirement).setChoiceValues(['Complete', 'Incomplete']);
      };
     };
   };
};

The first question is supposed to be a multiple choice item where each 'entity' is an option. The remainder of the questions are supposed to be whether each 'requirement' is marked complete or incomplete.
Here is the spreadsheet I am working from

A: you have a typo:
           if (requirement != "" || requirment != null){
should be 'requirement'

A: *

*Here in last forloop

requirement = "question #" + j;

*Please verify, is it ok ? or you should use

requirement = "question #" + j + ' ' +data[0][j];


text:
Q: Difference between "Start application pool immediately" and Start Mode AlwaysRunning In IIS Manager, an application pool has checkbox for "Start application pool immediately" in the basic setting dialog, and an advanced setting called "Start Mode" which can be set to "OnDemand" or "AlwaysRunning".
What is the difference between these settings?

A: It looks like "Start application pool immediately" controls whether the application pool is "Started" when the World Wide Web Publishing service is started.  But a "started" application pool is not necessarily running (meaning there may not be a w3wp process).
If an app pool is not "started" then you will get a 503 when you hit a site that uses that app pool.
If an app pool is "started" then a w3wp process will service your request.  "Always Running" means that when the application pool is started a w3wp process starts.  OnDemand means the w3wp process spins up when you first hit a website that is associated with the application (there is a delay while the w3wp starts).

A: Bit late to respond but I will add my findings as I looked around to find asnwer to this same question.
"OnDemand": IIS will launch worker process when first request for Web application is received.
"AlwaysRunning": IIS Launches the worker process for the application pool as soon as IIS is started OR when application pool is created.

A: Had the same question as the original poster but could not find a concise answer, below is the analysis from my research.

Application Pool != Worker Process (w3wp.exe)

*

*Typically we see a single w3wp.exe instance running for each application pool but technically we can configure a web garden with multiple w3wp.exe instances running.

Web gardens... are they good or bad or what?

*A worker process executes in the context of a single application pool.

Start application pool immediately = Automatic or manual start

Basic Settings...

*

*Enabled
IIS will automatically start the application pool.

*Disabled
Someone needs to manually start the application pool.

Start Mode = Worker process start mode: immediately or on demand

Advance Settings...

*

*AlwaysRunning
If the application pool is running immediately start up the w3wp.exe process.

*OnDemand
If the application pool is running start the w3wp.exe process when there is an inbound application request.

Additional Notes

*

*IISRESET /stop
Stop IIS, application pool(s) and worker process(es) (w3wp.exe instances).

*IISRESET /start
Start IIS and the above configuration settings will determine when the application pool(s) and worker process(es) (w3wp.exe) start up.

*IIS Manager Stop Web Server GUI action
Stop the web server from handling inbound requests but will not stop the application pool(s) or w3wp.exe process(es).

*IIS Manager Start Web Server GUI action
Start the web server to handle inbound requests but will not start the application pool(s) or w3wp.exe process(es).

Menu action to start/stop a Web Server

*IIS Manager Stop Application Pool GUI action
Stop the w3wp.exe process.

*IIS Manager Start Application Pool GUI action
AlwaysRunning vs. OnDemand will determined when the w3wp.exe process starts up.

Menu action to start/stop an Application Pool

A: Per IIS 8 What's new – Application pool settings:

Start Mode
A few web applications take a significant amount of time to start up.
  IIS by default only launches a worker process when the first request
  for the web application is received. So for the web applications that
  require a longer time to initialize, users might see slow responses.
For such applications it is a good idea to launch the worker process
  as soon as IIS is started. The application pools have a startMode
  setting which when set to AlwaysRunning launches the worker process
  for the application pool as soon as IIS is started.
IIS 8 provides you this setting in the Application Pool Settings UI.


text:
Q: Leaflet tooltip issue on multiple markers at same location i have two different markers at same location.For the marker at the bottom it has a tooltip while the marker at the top has not. when i hover my mouse on markers the tooltip doesn't show up.
what can i do about this problem?

A: You can set the zIndexOffset to show the marker with the tooltip on top.
L.marker([0,0], {zIndexOffset: 1}).addTo(map).bindTooltip('TEST')

https://jsfiddle.net/falkedesign/gaoydfcb/

A: i just bind bottom marker's tooltip to top marker's tooltip and it solved my problem:
marker_at_bottom.bindTooltip(...); // that tooltip was not visible
marker_at_top.bindTooltip(marker_at_bottom.getTooltip()); // so i just assigned bottom's tooltip to top one


text:
Q: How to make file visible in Java I hava this code to make external file invisible:
    void hide(File src) throws InterruptedException, IOException {

        // win32 command line variant
        Process p = Runtime.getRuntime().exec("attrib +h " + src.getPath());
        p.waitFor();

And now i dont know how to make the file visible back (The user give the path of the file)..

A: Should be nearly 100% identical to the code you have. Instead of +h it should be -h. Here you can find more information on the attribcommand. Syntax is
ATTRIB [+R | -R] [+A | -A] [+S | -S] [+H | -H] [[drive:][path]filename] [/S]
+ Sets an attribute.
- Clears an attribute.
R Read-only file attribute.
A Archive file attribute.
S System file attribute.
H Hidden file attribute.
/S Processes files in all directories in the specified path.

A: Replace exec("attrib +h " + src.getPath() to exec("attrib -h " + src.getPath()).
 This will make attribute from hidden to visible.
+r : Used to set the file attribute as read-only.

-r : Used to clear the read-only file attribute.

+a : Used to set the file attribute as archive.

-a : Used to clear the archive file attribute.

+s : Used to set the file attribute as a system file.

-s : Used to clear the system file attribute.

+h : Used to make the file attribute as hidden not visible to the user.

-h : Used to clear the hidden file attribute.

A: This is an old method. You should be using java.nio.file.Files.setFileAttribute() unless you're working with a version of Java older than 7.
The Javadoc gives the example of setting dos:hidden to true. Of course the reverse is setting it to false (More properly, Boolean.FALSE).
This way you won't create another process, which is a relatively costly operation.
Mind the various checked exceptions, of course.


text:
Q: How many messages can an activemq topic hold with multiple durable subscribers? I have multiple durable subscribers subscribed to a topic? How many messages can the topic hold? What is the maximum number of messages it can hold?
I am using KahaDB as persistence adapter. I am assuming it depends on the amount of memory that KahaDB has .Is that right?

A: Yes. It depends on the amount of memory available to KahaDB as well as the size of each message.
ActiveMQ has a strategy to page down exceeding memory to disk, so that available Java heap won't be a limit. However, paging message has performance implications so every scenario has to be tested.
Read up on message cursors for details


text:
Q: Calling REST service method from AJAX I am calling a REST service method from AJAX.
$(document).ready(function () {
        var xmml = getXmlLoginRequest();
        var wsdlURL = getWSDL('search');
        $.ajax({
            type: "POST",
            url: wsdlURL,
            data: xmml,
            contentType: "text/xml;charset=utf-8",
            dataType: 'text',
            success: function (result) {
                debugger;
                alert(" success" + result);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                debugger;
                alert(" error" + "jq :" + jqXHR + "textStatus :" + textStatus + "error : " + errorThrown);
            }
        });

        function getXmlLoginRequest() {
            debugger;
            var xml = '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> \
             <soap:Body> \
                <search> \
                <qry>svein </qry> \
                </search> \
             </soap:Body> \
           </soap:Envelope>';

            return xml;
        }
        function getWSDL(methodName) {
            debugger;
            var url = 'http:/MyURL/search.php?username=abc&password=def';
            return url;
        }

    });

I am getting result as empty in success block. If I change dataType to text, I get an exception in Failure block which says cannot parse NULL.
Am I writing incorrect syntax? When I run the url on browser with method and its parameters, it gives proper result.

A: What I see here is SOAP and not REST. You should try jQuery SOAP Plugin and not jQuery AJAX method directly.
Moreover WSDL Url is not the service URL, but URL of service description. The service URL is located in WSDL.
Service should be located on the same domain as your html page, because of same-origin-policy.

A: The dataTytpe can be xml, json, script, or html only. Leave it blank for default: Intelligent Guess.
Also make sure that the URL wsdlURL will not violate the  same-origin policy.


text:
Q: Pandas 'count(distinct)' equivalent I am using Pandas as a database substitute as I have multiple databases (Oracle, SQL Server, etc.), and I am unable to make a sequence of commands to a SQL equivalent.
I have a table loaded in a DataFrame with some columns:
YEARMONTH, CLIENTCODE, SIZE, etc., etc.

In SQL, to count the amount of different clients per year would be:
SELECT count(distinct CLIENTCODE) FROM table GROUP BY YEARMONTH;

And the result would be
201301    5000
201302    13245

How can I do that in Pandas?

A: I believe this is what you want:
table.groupby('YEARMONTH').CLIENTCODE.nunique()

Example:
In [2]: table
Out[2]:
   CLIENTCODE  YEARMONTH
0           1     201301
1           1     201301
2           2     201301
3           1     201302
4           2     201302
5           2     201302
6           3     201302

In [3]: table.groupby('YEARMONTH').CLIENTCODE.nunique()
Out[3]:
YEARMONTH
201301       2
201302       3

A: Interestingly enough, very often len(unique()) is a few times (3x-15x) faster than nunique().

A: Using crosstab, this will return more information than groupby nunique:
pd.crosstab(df.YEARMONTH,df.CLIENTCODE)
Out[196]:
CLIENTCODE  1  2  3
YEARMONTH
201301      2  1  0
201302      1  2  1

After a little bit of modification, it yields the result:
pd.crosstab(df.YEARMONTH,df.CLIENTCODE).ne(0).sum(1)
Out[197]:
YEARMONTH
201301    2
201302    3
dtype: int64

A: Here is an approach to have count distinct over multiple columns. Let's have some data:
data = {'CLIENT_CODE':[1,1,2,1,2,2,3],
        'YEAR_MONTH':[201301,201301,201301,201302,201302,201302,201302],
        'PRODUCT_CODE': [100,150,220,400,50,80,100]
       }
table = pd.DataFrame(data)
table

CLIENT_CODE YEAR_MONTH  PRODUCT_CODE
0   1       201301      100
1   1       201301      150
2   2       201301      220
3   1       201302      400
4   2       201302      50
5   2       201302      80
6   3       201302      100

Now, list the columns of interest and use groupby in a slightly modified syntax:
columns = ['YEAR_MONTH', 'PRODUCT_CODE']
table[columns].groupby(table['CLIENT_CODE']).nunique()

We obtain:
YEAR_MONTH  PRODUCT_CODE CLIENT_CODE
1           2            3
2           2            3
3           1            1

A: I am also using nunique but it will be very helpful if you have to use an aggregate function like 'min', 'max', 'count' or 'mean' etc.
df.groupby('YEARMONTH')['CLIENTCODE'].transform('nunique') #count(distinct)
df.groupby('YEARMONTH')['CLIENTCODE'].transform('min')     #min
df.groupby('YEARMONTH')['CLIENTCODE'].transform('max')     #max
df.groupby('YEARMONTH')['CLIENTCODE'].transform('mean')    #average
df.groupby('YEARMONTH')['CLIENTCODE'].transform('count')   #count

A: Distinct of column along with aggregations on other columns
To get the distinct number of values for any column (CLIENTCODE in your case), we can use nunique. We can pass the input as a dictionary in agg function, along with aggregations on other columns:
grp_df = df.groupby('YEARMONTH').agg({'CLIENTCODE': ['nunique'],
                                      'other_col_1': ['sum', 'count']})

# to flatten the multi-level columns
grp_df.columns = ["_".join(col).strip() for col in grp_df.columns.values]

# if you wish to reset the index
grp_df.reset_index(inplace=True)

A: Here is another method and it is much simpler. Let's say your dataframe name is daat and the column name is YEARMONTH:
daat.YEARMONTH.value_counts()

A: With the new Pandas version, it is easy to get as a data frame:
unique_count = pd.groupby(['YEARMONTH'], as_index=False).agg(uniq_CLIENTCODE=('CLIENTCODE', pd.Series.count))

A: Now you are also able to use dplyr syntax in Python to do it:
>>> from datar.all import f, tibble, group_by, summarise, n_distinct
>>>
>>> data = tibble(
...     CLIENT_CODE=[1,1,2,1,2,2,3],
...     YEAR_MONTH=[201301,201301,201301,201302,201302,201302,201302]
... )
>>>
>>> data >> group_by(f.YEAR_MONTH) >> summarise(n=n_distinct(f.CLIENT_CODE))
   YEAR_MONTH       n
      <int64> <int64>
0      201301       2
1      201302       3

A: Create a pivot table and use the nunique series function:
ID = [ 123, 123, 123, 456, 456, 456, 456, 789, 789]
domain = ['vk.com', 'vk.com', 'twitter.com', 'vk.com', 'facebook.com',
          'vk.com', 'google.com', 'twitter.com', 'vk.com']
df = pd.DataFrame({'id':ID, 'domain':domain})
fp = pd.pivot_table(data=df, index='domain', aggfunc=pd.Series.nunique)
print(fp)

Output:
               id
domain
facebook.com   1
google.com     1
twitter.com    2
vk.com         3

A: *

*To obtain the number of different clients and sizes per year (i.e. number of unique values of multiple columns), use a list of columns:
df.groupby('YEARMONTH')[['CLIENTCODE', 'SIZE']].nunique()

*Actually, the result from the above code can be obtained using SQL syntax on df using pandasql (a module built on pandas that lets you query pandas DataFrames using SQL syntax).
#! pip install pandasql
from pandasql import sqldf
sqldf("""
SELECT COUNT(DISTINCT CLIENTCODE),
       COUNT(DISTINCT SIZE)
  FROM df
  GROUP BY YEARMONTH
""")

*If you want to keep YEARMONTH as a column, i.e. the analog of the following SQL query
SELECT YEARMONTH,
       COUNT(DISTINCT CLIENTCODE),
       COUNT(DISTINCT SIZE)
  FROM df
  GROUP BY YEARMONTH

in pandas is the following (set as_index to False):
df.groupby('YEARMONTH', as_index=False)[['CLIENTCODE', 'SIZE']].nunique()

*If you need to set custom names to the aggregated columns, i.e. the analog of the following SQL query:
SELECT YEARMONTH,
       COUNT(DISTINCT CLIENTCODE) AS `No. clients`,
       COUNT(DISTINCT SIZE) AS `No. size`
  FROM df
  GROUP BY YEARMONTH

use named aggregation in pandas:
(
    df.groupby('YEARMONTH', as_index=False)
      .agg(**{'No. clients':('CLIENTCODE', 'nunique'),
              'No. size':('SIZE', 'nunique')})
)


text:
Q: Comparing keys of one dictionary to another dictionary with a list of values I have a dictionary with a list of values of varying numbers of items.
I want to compare the values of this dictionary (dict1) to the keys of another (dict2), and if they match print the key and value of the matching component of dict1, along with the value of dict2.
Both of the dictionaries are quite large, and currently this is taking way too long as you could have guessed from this basic script.
dict1 = {boys:[tom,jon],girls:[suzy]}

dict2 = {suzy:paper-stapler-extraordinaire,jon:paper-shredderoligist,tom:garbage-specialist}

output:
    boys \t tom \t garbage-specialist

    boys \t jon \t paper-shredderoligist  etc.....

for k,v in dict2.items():

    for key,value in dict1.items():
         if k in value[0]:
             print str(key)+"\t"+str(value[0])+"\t"+v
         if len(value)>1:
             if k in value[1]:
                 print str(key)+"\t"+str(value[0])+"\t"+v

Could someone suggest a more memory efficient method?  Perhaps a list comprehension?
This has not been working...
a = [k for k in dict2 if k in dict]

A: for dict1_key, dict1_values in dict1.iteritems():
    for dict1_value in dict1_values:
        try:
            dict2_value = dict2[dict1_value]
            print str(dict1_key) + '\t' + str(dict1_value) + '\t' + str(dict2_value)
        except KeyError:
            pass

That combines a few techniques to speed it up and use less memory. iteritems uses less memory (as others have mentioned). By using try and then using dict2[dict1_value], you can ensure that dict2 is only searched once, and then with the hash algorithm, which should be much faster than iterating through all the elements. For all the cases where dict2 does not have dict1_value in it, the first statement under try fails, causing the catch block to harmlessly pass.

A: Are you looking for something along the lines of:
[(k,i,dict2[i]) for k,v in dict1.items() for i in v if i in set(dict2.keys())]

which returns the key,value of dict1 and value of dic2 for every value in dict1 that is a key in dict2. This can be edited to return a string etc...
This outputs:
[('boys', 'tom', 'garbage-specialist'),
 ('boys', 'jon', 'paper-shredderoligist'),
 ('girls', 'suzy', 'paper-stapler-extraordinaire')]

The set() on dict2.keys() is used to make the key look-up faster.


text:
Q: How to remove top padding in a Table Cell Here is the styling and the table inside the render function.
const style = theme => ({

table: {
    maxHeight: '90vh',
},

tableCell: {
    textAlign: 'center',
    border: "solid",
    borderColor: '#000',
    borderWidth: 1,
    padding: 0,
}

})

<TableContainer component={Paper}>
            <Table className={classes.table} aria-label="simple table">
                <TableBody>
                    <TableRow>
                        <TableCell colSpan={2} className={classes.tableCell}>
                            {
                                this.getOilIndicator(data)
                            }
                        </TableCell>

And this is the function:
getOilIndicator(data) {
    return (
    <>
    <Typography variant="subtitle1" align="center" >{"OIL LEVEL"}</Typography>
    <div>
        <Grid xs
            item>
                {
                    this.getDevice(_.find(this.state.devices, { "id": 5 }), data)
                }
        </Grid>
    </div>
    </>

The problem here is that there's an unnecessary padding at the top even after setting the padding to 0. How to remove this padding. I want to place the text 'Oil Level' at the topmost part of the table cell but because of the padding, I'm unable to do so.


text:
Q: Membership validation fails on login. How to determine cause? I have an Azure web site that uses forms authentication with an Azure membership via the standard Microsoft tools and database.  When I website administration tool, it sees the database and creates the users correctly.  When I try to login however, I receive an authentication error.
The really strange part is that I have another Azure website that also uses a membership database.  I copied the membership info directly from that sites web.config file into my broken site.  When I go to administer the website, again, it sees the users correctly but when I attempt to login, I get receive an authentication error.  To be clear, I can login properly from the working site but when I move the config info over to my new site, the same credentials fail.
How can I determine what is causing the problem?  Below is code from web.config:
<add name="StrataluxAuthorize" connectionString="Data Source=xxxxxxx.database.windows.net;Initial Catalog=StrataluxAuthorize;Persist Security Info=True;User ID=xxxxxx;Password=xxxxxxxxxx" providerName="System.Data.SqlClient" />

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" defaultUrl="~/" timeout="600" />
</authentication>
<profile defaultProvider="DefaultProfileProvider">
  <providers>
    <add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
  </providers>
</profile>
<membership defaultProvider="DefaultMembershipProvider">
  <providers>
    <add connectionStringName="StrataluxAuthorize" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="true" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  </providers>
</membership>
<roleManager enabled="true" defaultProvider="DefaultRoleProvider">
  <providers>
    <add connectionStringName="StrataluxAuthorize" applicationName="/" name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  </providers>
</roleManager>

A: Just a guess based on the info given. Be sure that the "ApplicationName" property of the membership profider matches for both sites that will use the same Membership database. It doesn't appear that you have explicitly defined one so I believe by default it will use the Web Project Name. So if there is a mismatch (presumably there would be) between the 2 website names then the membership db will try to create a new application id in the database.
Sample Config:
<membership defaultProvider="DefaultMembershipProvider">
  <providers>
    <add connectionStringName="StrataluxAuthorize" enablePasswordRetrieval="false"  enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="true" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="" name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  </providers>
</membership>

Just a bit more clarification:
If you want the users which originaly appeared in web app "A" to be available in web app "B" then the application name in the configuration of web app "B" should be "A". Otherwise the membership provider will view it as a new application and it will get its own id and unique set of users.


text:
Q: find actual frequency in case of normalized frequency .suppose that we have  some sample
y =

   31.2241
   -5.9830
   22.6058
   -2.2309
  -42.8272
   29.2850
   -6.2652
   20.8502
   -2.4639
  -44.7525
   30.1104
   -6.0180
   21.4476
   -1.5089
  -45.1826
   29.2744

and somehow i know that it  it got by  sinusoidal method which contains two sin function at different frequency and amplitude,so i apply  music method
pmusic(y,4)

and picture

i know location  of peaks at normalized peaks, but i dont know actual frequency, how to find it?as i know formula is normalized  frequency*fs/2, but what about fs? can i find it?

A: If you don't have the sampling rate given explicitly, you can just get it by dividing the length (in time) of your dataset by the number of samples.
Without fs, duration or some other information relating your samples to points in time, you're out of luck.
If you do have the necessary info, pmusic will accept it and return values in proper, non-normalized, frequency.
Below, we've got two cos waves added together, total dataset is 5s in duration with 512 samples. The two terms to add are the number of samples for it to use (I put 256, but [] would have done the same because 256 is the default value.) and the sampling rate in Hz.
This will give you a non-normalized plot of your results.
x = linspace(0,5,512);
y = 1*cos(2*pi*2*x)+1*cos(2*pi*10*x);

pmusic(y,4,256,512/5)


text:
Q: C# XNA как узнать разрешение экрана/окна Нужно узнать текущие разрешение экрана(для полно экранного режима) и отдельно нужно узнать разрешение окна(оконный режим)
Есть какие либо стандартный функции в C# или в XNA для получения этой информации?
p.s. для оконного режима можно сделать возможность выбора разрешения окна, а эти значения можно вручную прописать как варианты, но для полноэкранного режима нужно знать возможные корректные разрешения:
у моего экрана разрешение 1366х768
а у кого то 1920x1080

A: Можно так:
SystemInformation.PrimaryMonitorSize

Или так:
SystemInformation.VirtualScreen

Ну, или так:
System.Windows.Forms.Screen.PrimaryScreen.Bounds

A: var graphics = new GraphicsDeviceManager(this);

Поля PrefferedBackBufferHeight и PrefferedBackBufferWidth.

A: GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;
GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;


text:
Q: Analytic iff Holomorphic on open domains of $\mathbb{C}$ I am reading through the proof of Griffiths and Harris on pages $2/3$. I am struggling with the proof of
$f$ is holomorphic iff $f$ is analytic.
They have a proof of holomorphicity and analaticity of function defined over open subsets of the complex plane. First I suppose that
$$\frac{\partial f}{\partial \overline{z}}=0.$$
I'd like to know where he uses this in proving there exists a converging power series, so first assuming $\frac{\partial f}{\partial \overline{z}}=0,$ does he use Cauchy Integral Formula? and this fact?
I also want to know what the most formal definition of $\textit{holomorphic}$ is vs. $\textit{analytic}$. From my understanding $f$ is holomorphic on some open $U \subset \mathbb{C}$ if for each $z \in U$, one has
$$\frac{\partial f}{\partial \overline{z}}=0.$$
And $f$ is analytic on all of $U$ is for each $z_0 \in U$ one can write $f$ as a power series centered at some $z_0 \in U$,
$$f(z)=\sum_{n=0}^\infty a_n(z-z_0)^n$$
such that the series converges on $U$.
First off, are these the more standard definitions of holo and analytic? Secondly, in proving holomorphic $\Rightarrow$ analytic, where do they use that the partial of the conjugate is zero? If anyone has a copy of Griffiths $\&$ Harris. Sorry if my question is too elementary, I am applying for PhDs for Fall 2022 and just wanna head start on some of the concepts I may encounter once there.

A: The definition that an infinitely differentiable function $f$ is holomorphic on an open subset $U\subset\mathbb{C}$ if $$\frac{\partial f}{\partial \bar z}= 0 $$
a perfectly good definition and is essentially just a restatement of the Cauchy Riemann equations. It seems in Griffiths and Harris they prove a generalized version of the Cauchy integral formula which holds for any $C^{\infty}$ function (which reduces to the standard version when $\frac{\partial f}{\partial \bar z}=0$) and use this to prove that such functions are analytic.
If you want to learn about the equivalent definitions of holomorphic/complex analytic functions and theorems about their equivalence I'd suggest a book specifically on complex analysis.

A: I do not have a copy of that text book at hande, but the standard definition of holomorphic function is that it is a differentiable function, that is, that, for each $z_0$ in its domain, the limit
$$\lim_{z \rightarrow z_0}\frac{f(z)-f(z_0)}{z-z_0}$$
exists.Quite often, but not always, it is added to the definition the condition that the domain of $f$ is an open subset of $\Bbb C$.


text:
Q: Proving the sums of three cubes conjecture by the Hasse principle In his Cours d'arithmétique Serre applies the Hasse-Minkowski theorem to quadratic forms of the form:
$$
x^2 + y^2 + z^2 = n
$$
for $n \in \mathbb{N}$ to prove that a natural number $n$ is a square if and only if $-n$ is not a square in $\mathbb{Q}_2$, and hence that a natural number can be expressed as the sum of three squares provided that it is not of the form $4^a(8b-1)$ for some $a\in \mathbb{N}_0$, $b \in \mathbb{N}$.
My question is about if one might prove the sums of three cubes conjecture by analogous means.
Now we know that the Hasse principle does not hold for a general cubic forms, if we knew that it holds for cubic forms of the form:
$$
x^3 + y^3 + z^3 = n
$$
for some $n \in \mathbb{N}$, could we reduce the proof of the sum of three cubes conjecture to a local statement, analogous to the above.
Has any work been done to prove the sum of the cubes conjecture by these means?
Is the Hasse principle known to hold for cubic forms of the above form?
I suppose this would naturally entail the introduction of something like an analogy of the Hilbert symbol in the cubic case.
Many thanks.
Edit: This would naturally not work if the Hasse principle were known to fail for a cubic form:
$$
x^3 + y^3 + z^3 = n
$$
for some $n \in \mathbb{N}$, so a natural way of dismissing the above proof strategy would be to provide such a counter-example. - Is any such counter-example known to exist?

A: I don't think that the Hasse principle is useful here. First, Hasse-Minkowski fails in general for cubic polynomials, e.g., for $3x^3+4y^3+5z^3$. For $x^3+y^3+z^3=n$ I don't see how to use it.
Secondly, Ramanujan has used generating functions to obtain parametrised solutions for $x^3+y^3+z^3=1$ and $x^3+y^3+z^3=2$, and this direction appears to be more interesting, see for example the article by Harper.
In $1992$, Roger Heath-Brown conjectured that every
$n$ unequal to $4$ or $5$ modulo $9$ has infinitely many representations as sums of three cubes.Conversely it easy to see that the other $n$ cannot be a sum of three cubes. There are many computational aspects, too, which made the problem popular for $n=33$ and $n=42$.


text:
Q: AS3-What's the difference between "rotation" and "rotationZ"? Both of them, do the same. so, are they completely same as each other or there is difference?

A: Conceptually they are the same, but there is some difference to be aware of.
Display objects can either be 2d (transform.matrix) or 3d (transform.matrix3D), but not both. The rotation property reflects rotation of the matrix or matrix3D, while rotationZ explicitly represents rotation around the Z axis of the matrix3D property. The difference here is that if you set rotationZ it will, like all 3d properties (z, rotationX, etc), convert the display object to 3d (transform.matrix3D) even if no other 3d properties are set. For example:
var sprite:Sprite = new Sprite();

sprite.rotation = 50;
trace(sprite.transform.matrix); // [object Matrix]
trace(sprite.transform.matrix3D) // null

sprite.rotationZ = 50;
trace(sprite.transform.matrix); // null
trace(sprite.transform.matrix3D) // [object Matrix3D]

This is notable because the 3d rendering (transform.matrix3D) does introduce some blurring due to the way 3d is projected onto 2d, while 2d rendering (transform.matrix) does not.
So, if you aren't going to use any other 3d properties, stick to rotation. If you are going to use other 3d properties, using rotationZ makes more sense.
Other than that, they are the same. ;)
Hope that helps.


text:
Q: Clickhouse DB slows down on a daily basis at 10am for seemingly no reason I have been using Clickhouse at work for analytics purposes for a while now.
I am currently running Clickhouse v22.6.3 revision 54455 on-premise on a VM with:

*

*fast storage

*200Gb of RAM

*no swap

*a 40-cores CPU.

I have a few Tb of data, but no table bigger than 300 Gb. I do not use distributed tables or replication yet, and I write frequently into Clickhouse (but I don't use deletes or updates and prefer using things like the ReplacingMergeTree engine). I also leverage the MaterializedView feature for a few tables. Let me know if you need any more context or parameter, I use a pretty standard configuration.
Now, for a few months I have been experiencing performances issues where the server significantly slows down every day at 10am, and I cannot figure out why.
Based on Clickhouse built-in Graphite monitoring, the "symptoms" of the issue seem to be as follow:
At 10am:
On the server side:

*

*Both load and RAM usage remain reasonable. Load goes up a little.

*Disk write await time goes up (which I suspect is what leads to higher load)

*Disk utilization % skyrockets to something between 90 and 100%

On Clickhouse side:

*

*DiskSpaceReservedForMerge stays roughly the same (ie between 0 and 70Gb)

*both OpenFileForRead and OpenFileForWrite go up by a factor of ~2

*BackgroundCommonPoolTask goes slightly up, so does BackgroundSchedulePoolTask (which I found weird, because I thought this pool was dedicated to distributed operations - which I don't use) - both numbers remain seemingly reasonable

*The number of active Merge tasks per minutes drop significantly but I'm unsure whether it's a consequence of slow writing or if it's causing it

*both insert and general querying time are multiplied by ~10 which renders the database effectively unusable even for small tasks

Restarting Clickhouse usually fixes the problem but I obviously do not want to restart my main database every day at 10am. Most of the heavy load I put on the DB (such as data extraction and transformation, etc) happens earlier in the morning (and end around 7-8am) and runs fine. I do not have any heavy tasks running at 10am. The Clickhouse VM takes most of its host resources and I have confirmed with the devOps team that there doesn't seem to be a problem on the host or anything else scheduled on it at that time.

Is there any kind of background tasks or process that is run by Clickhouse on a daily basis and that could have a high impact on our disk capacity? What else can I monitor to figure out what is causing this problem?
Again, let me know if I can be more thorough on our settings and the state of the DB when the "bug" occurs.

A: Do you use https://github.com/innogames/graphite-ch-optimizer ?
Do you use TTL ?
select * from system.merges;

select * from system.part_log where event_time between ~10am~


text:
Q: tensorflow retrain with inception model doesn't generate retrained_labels.txt
I am following this tutorial. I am using following command to retrain my model with flowers data set:
python -m scripts.retrain --bottleneck_dir=tf_files/bottlenecks
--model_dir=tf_files/models/inceptionv3
--summaries_dir=tf_files/training_summaries/inceptionv3
--output_graph=tf_files/retrained_graph.pb
--output_lables=tf_files/retrained_labels.txt
--image_dir=tf_files/flower_photos

it runs successfully with final test accuracy = 91.9% (N=664). But it doesn't generate retrained_labels.txt. am I missing something here?

A: --output_lables=tf_files/retrained_labels.txt
Argument output_lables is  incorrect, replace it with output_labels.


text:
Q: Solving ODEs inside a Subsystem in Simulink I'm trying to figure out how to solve a system of ODEs inside a subsystem in a Simulink model. Basically, each call to this subsystem, which happens at each tick of the simulation clock (fixed-step), entails solving the ODEs. So there's like a different "clock" for the subsystem.
I have an M-file that implements the function for the system of ODEs. Currently, I have a MATLAB Function block for that. It needs a lot of parameters that I can get from the base workspace (via evalin and using coder.extrinsic('evalin') at the beginning). But I'm not allowed to define function_handle objects or inner functions to parameterize the function that is used by ode*. I think that if I'm able to solve the ODEs in this block, I'll have solved my problem. But those restrictions are "ruining" it.
I'd appreciate if you have any ideas of how to accomplish this. I welcome different approaches.
Thank you.
EDIT
A simple example is given below. It attempts to solve the van der Pol equation by changing the mu parameter randomly. This is the main idea I have at the moment, which doesn't work because of the problems mentioned above.
This is the main model with the subsystem:

This is the subsystem:

This is the MATLAB Function block implementation (note that there's an error in the @ symbol, since defining function_handle objects isn't allowed):

A: Just use the MATLAB Function block as a wrapper.  Put the bulk of your code into a "standard" MATLAB function (i.e. one callable from MATLAB, not the MATLAB Function block) and call that function (after defining it as coder.extrinsic) from the MATLAB Function block.

A: This will be a bit more complex than Phil Goddard's solution. The advantage is that it will allow you to generate standalone code, if necessary, whereas extrinsic functions are not compatible with standalone code generation.
The functions ode23 and ode45 are supported for code generation as of MATLAB R2014b so this applies if your MATLAB release is at least that new. Supposing so, the main limitation you are seeing is that anonymous functions are not supported for code generation.
Simulate Anonymous Function Parameters with Persistent Variables
However, these parameterized anonymous functions can be simulated using a normal function with a persistent. To simulate your function with the parameter mu, make a MATLAB file odefcn.m:
function x = odefcn(t,y)
%#codegen
persistent mu;
if isempty(mu)
  % Adjust based on actual size, type and complexity
  mu = 0;
end
if ischar(t) && strcmp(t,'set')
  % Syntax to set parameter
  mu = y;
else
  x = [y(2); mu*(1-y(1)^2)*y(2)-y(1)];
end

Then in the MATLAB Function Block, use:
function y = fcn(mu)
%#codegen
% Set parameter
odefcn('set',mu);

% Solve ODE
[~,Y] = ode45(@odefcn,[0, 20], [2; 0]);
y = Y(end,1);

That should work both for simulation and for code generation. You can just add more arguments to odefcn if you need more parameters.


text:
Q: cv::Mat will be changed after inserting it into a std::map? What is the underlying reason? I meet this problem when I deal with image streams from multi-cameras. I create a map and put all images into it based on the camera id, so I have:
std::mat<uint32_t, cv::Mat> images;

I will add image into that map by calling addImages as soon as receiving data from a specific camera:
void addImages(uint32_t camera_id, CameraData imgData)
{
  cv::Mat img = cv::Mat(imgData.height(), imgData.width(), CV_8UC3, (void *)imgData.ptr);
  images.insert(make_pair(camera_id, img));
  cv::imshow("origin image", img);
}

When I show images from that map somewhere else, strange thing happens. The image changes and I can tell that its color differs from the original one.
void showImage(uint32_t camera_id)
{
  cv::imshow("get image", images[camera_id]);
  cv::waitKey(1);
}

But when I change addImages codes a little bit, images are same as original ones which is expected.
void addImages(uint32_t camera_id, CameraData imgData)
{
  cv::Mat img = cv::Mat(imgData.height(), imgData.width(), CV_8UC3, (void *)imgData.ptr);

  // NOTE THIS LINE!!!
  images.insert(make_pair(camera_id, img.clone()));

  cv::imshow("origin image", img);
}

So, my question is, what is the difference? Is there any other way to solve this problem?

A: This line seems incorrect.
cv::Mat img = cv::Mat(imgData.height(), imgData.width(), CV_8UC3, (void *)imgData.ptr);

Here's a quote from the documentation on the fourth parameter to this constructor

Pointer to the user data. Matrix constructors that take data and step
parameters do not allocate matrix data. Instead, they just initialize
the matrix header that points to the specified data, which means that
no data is copied.

In other words the Mat object just stores this pointer, it doesn't copy the data from it.
Now when your addImages function exits it destroys the imgData object which (presumably) invalidates the pointer you have just stored in the img object. That results in the problem you see.
The second version creates a clone of the img object which does copy the image data and so breaks the connection between the img object and the imgData object.
You might be able to fix this problem by passing the imgData parameter by reference. This means the imgData object would not be destroyed at the end of the function. But you would still have a situation where the Mat object and the CameraData object are sharing image data. So that might not be a good solution, but only you could say that for sure.


text:
Q: Delay loading of script I am trying to delay the loading of this chat script on my website but cannot get it to work for some reason.
console.log(script) returns the correctly dynamically generated script but for some reason the script (live chat) is not running on the page.
I have removed some content for privacy but here is my code:
HTML
<!DOCTYPE html>
<%@ LANGUAGE="VBSCRIPT" %>

    <meta charset="utf-8">
    <meta name="robots" content="noindex, nofollow">
    <meta content="width=device-width, initial-scale=1, shrink-to-fit=no" name="viewport">
    <meta name="description" content="Website Description">

    <title>Website</title>

    <link rel="alternate" href="https://www.website.com/website" hreflang="x-default"/>
    <link rel="canonical" href="https://www.website.com/website">

    <%
        FormHeader = "Request Demo Now"
        FormBtn = "Get Demo Now"

        sub Process
            Interest = "Demo Request: Website - mrkt"

            WebComment = Comments
            CSR = UserLog(Interest, "DQT")
            Message = Comments & vbCrLf
            Message = Message & " Name: " & Name & vbCrLf
            Message = Message & " Email: " & email & vbCrLf
            Message = Message & " Phone: " & Phone & vbCrLf
            Message = Message & " Company: " & Company & vbCrLf
            Message = Message & " Product: " & Interest & " " & vbCrLf
            Message = Message & " GDPR Agreement: " & Agreement & Checked & gdpragree & vbCrLf
            Message = Message & " Referrer: " & REFERER & vbCrLf & vbCrLf
            message = message + Ip2Message & vbCrLf & vbCrLf
            result = Mail("email@email.com", emailfrom, Interest  & " " & Reg & " " & IpCountry & " " & Csr, Message )
        end sub
    %>

<% sub Form%>
<%end sub%>

JS
    setTimeout(function() {
        var script = document.createElement('script');
        script.type = "text/javascript";
        script.setAttribute("id", "6461f488b9172537ed0bfce1966c165e");
        script.src = "//support.website.com/script.php?id=6461f488b9172537ed0bfce1966c165e";
        console.log(script);
        document.querySelector('head').appendChild(script);
    }, 5000);

A: Add  tag in your html and it will work (run and look in chrome console  ) and remember that your script should be defined below that tag.

setTimeout(function() {
    var script = document.createElement('script');
    script.src = "//support.website.com/script.php?id=6461f488b9172537ed0bfce1966c165e";
    script.type = "text/javascript";
    script.setAttribute("id", "6461f488b9172537ed0bfce1966c165e");
    document.getElementsByTagName('head')[0].appendChild(script);
}, 50);
xxx

After question upate
I put your full code (after question update) into snippet and it works without error you mention in previous versions of your question

Uncaught TypeError: Cannot read property 'appendChild' of null.

Here is snippet

<!DOCTYPE html>
<%@ LANGUAGE="VBSCRIPT" %>

    <meta charset="utf-8">
    <meta name="robots" content="noindex, nofollow">
    <meta content="width=device-width, initial-scale=1, shrink-to-fit=no" name="viewport">
    <meta name="description" content="Website Description">

    <title>Website</title>

    <link rel="alternate" href="https://www.website.com/website" hreflang="x-default"/>
    <link rel="canonical" href="https://www.website.com/website">

    <%
        FormHeader = "Request Demo Now"
        FormBtn = "Get Demo Now"

        sub Process
            Interest = "Demo Request: Website - mrkt"

            WebComment = Comments
            CSR = UserLog(Interest, "DQT")
            Message = Comments & vbCrLf
            Message = Message & " Name: " & Name & vbCrLf
            Message = Message & " Email: " & email & vbCrLf
            Message = Message & " Phone: " & Phone & vbCrLf
            Message = Message & " Company: " & Company & vbCrLf
            Message = Message & " Product: " & Interest & " " & vbCrLf
            Message = Message & " GDPR Agreement: " & Agreement & Checked & gdpragree & vbCrLf
            Message = Message & " Referrer: " & REFERER & vbCrLf & vbCrLf
            message = message + Ip2Message & vbCrLf & vbCrLf
            result = Mail("email@email.com", emailfrom, Interest  & " " & Reg & " " & IpCountry & " " & Csr, Message )
        end sub
    %>

<% sub Form%>
<%end sub%>

When you run it and go to chrome element inspector you will notice that your script appear in snippet  tag  (I also add console.log('xx') to yur js to be sure that your script was executed):

If you error stop appear (because in this version of your question you remove it) and live chat still not works, then this is separate problem and find/ask another question in StackOverflow (put there also your script //support.website.com/script.php?id=6... content )

A: Use document.querySelector() if you are trying to access one element. This way you don't have to access the head by index. Also, unless you have to have the script imported by this time, it's usually best to add scripts near the bottom of the document.
This should work:

setTimeout(function() {
  var script = document.createElement('script');
  script.src = "//support.website.com/script.php?id=6461f488b9172537ed0bfce1966c165e";
  script.type = "text/javascript";
  script.setAttribute("id", "6461f488b9172537ed0bfce1966c165e");
  document.querySelector('head').appendChild(script);
}, 5000);

Also, ensure a  tag exists.
My VBScript skills are not great, but try adding something like this to your script like so:

Hope this helps,

A: Load or run your script at the end of your body, just before your body end tag.


text:
Q: Reading input from a 2nd USB HID without interfering with main form having found lots of answers to questions here, I decided to ask since I found something really really close to what I want to achieve in my app.
How to read input from a USB HID device
But this solution differs just a bit from what I need.
So I have one simple form in charge of counting how many "d"'s are pressed on a USB HID;
which is actually an electronic sensor connected to an iPAC which emulates the keyboard input to the PC, I use this to count how many cycles a fan is making, every time the fan passes it actives the sensor, the sensor activates the input in the iPAC, and the iPAC sends a various "d"'s to the main form, I use a simple Boolean variable along with the key up and down events to evaluate if it's a new cycle, additionally I have a couple of buttons and select boxes on the form to report and register problems, this form is connected to an Access DB, but, since the fan cycles about 3 times per seconds, it sends too much input that makes the form totally unusable and it doesn't even let me use the mouse, I it ever let's me and try to select an option from a box, it instantly populates it with hundreds of d's.
Do you have any recommendations for and API that will let me just listen to the input?
I just need to know how many cycles the fan is making.


text:
Q: Unity play mode keeps opening Mixed Reality Portal Using Unity 2019.4.16f1 on Windows 10, configured for legacy built-in XR, when I press the Play button in the editor, for some reason it opens the Windows Mixed Reality Portal and runs it in a simulator, rather than right there in the Unity IDE, but I want it to play in the IDE.
The thing is, it just randomly seemed to start doing this. I've been working for a while now with it playing in the editor, and as far as I know I didn't change any sort of configuration options. It just... always runs in the MR Portal now.
How do I configure whether it opens in the Portal vs the Unity IDE?

A: If you have XR enabled for a UWP app it will open either the WMR portal simulator or run on device if available.
You might have enabled 'developer mode'?
In order to disable this behavior you're going to have to disable the WMR portal simulator or disable XR support in unity. There's no other way to prevent it from opening WMR portal otherwise as far as I'm aware.


text:
Q: How to pass a string as a generic in TypeScript I want to create a generic type that I can use to transform normal type into a type that complies with my API response structure. So the issue is that I have bunch of types and I want to infer off of them another bunch of types that will be look something like this:
// this is a type that i have
interface IModel {
  key1: string
  key2: string
}

//this is a type I want to infer
interface IModelResponse {
  model: {
    key1: string
    key2: string
  }
}

// the way i want to do this is through generics in TypeScript
// so let's say something like this:
type IModelResponse = IBaseResponse<IModel, 'model'>

I tried something like this:
export interface IBaseResponse<T, modelName extends string> {
  [key: modelName]: T
}

but it gives me an error "An index signature parameter type must be either 'string' or 'number'."
is there something i don't get, or is this impossible to implement in the way that I intend? Would appreciate some help!

A: It can be implemented using the in keyword
interface IModel {
  key1: string
  key2: string
}

type BaseResponse<T, ModelName extends string> = {
  [key in ModelName]: T
}

type IModelResponse = BaseResponse<IModel, 'model'>


text:
Q: Use Javascript variable in Symfony path (Ajax request) I've created a Ajax request who posts data to a Symfony path. Inside my Symfony path I want to use a Javascript variable to generate my route.
$(document).ready(function () {
            function cbOnClick(cb) {
                cbValue = cb.checked;
                todoId = cb.getAttribute('data-id');

                $.ajax({
                    url: '{{ (path('change_todo_status', {'todo_id': todoId})) }}',
                    type: "POST",
                    dataType: "json",
                    data: {
                        "status": "cbValue"
                    },
                    async: true,
                    success: function (data) {
                        console.log(data)
                    }
                });
                return false;
            }
        });

Inside my url I want to set the todoId, but I'm getting te error the variable "todoId" does not exists.

A: In '{{ (path('change_todo_status', {'todo_id': todoId})) }}', twig expects a twig variable. I already had that issue and I used a placeholder to be replaced in javascript.
In example :
let todoId = cb.getAttribute('data-id');
/*
 * this will generate a path with ReplaceMeWithCorrectValue instead of the correct value.
 * You have to use a placeholder that correspond to the restrictions defined in your route.
 */
let url = "{{ (path('change_todo_status', {'todo_id': 'ReplaceMeWithCorrectValue'})) }}";

url = url.replace("ReplaceMeWithCorrectValue", todoId);

And then, in your ajax :
$.ajax({
        url: url,
   // the remain of your code


text:
Q: Como faço para usar a função IN do SQL no PHP Fiz esse código que confronta duas bases, uma para saber se o funcionário logou no servidor de login/logoff e se o funcionário é do pré (temos pré e pós) mas não consigo usar a função IN para comparar as bases
<?php
include 'conexao.php';
include 'conexaoSmart241.php';
$iniMes1 = date('2021/m/d 08:00:00');
$gestao4 = 'MARINA GONCALVES DA SILVA SENA';
$qLogados = pg_query($conexao241, "SELECT distinct nome FROM public.smart_login_agentes WHERE datahora_ini >= '$iniMes1' AND nome_gestor LIKE '$gestao4'");
while ($row = pg_fetch_assoc($qLogados)) {
  $logados4 = $row['nome'];
    $logados44 = $logados4 ."," .$logados44  ;
}
$string = "$logados44";
$qLogados = mysqli_query($conexao, "SELECT distinct vendedor FROM tbl_equipes2 WHERE gestor LIKE '$gestao4' AND vendedor IN($string)");
$lista1 = mysqli_fetch_assoc($qLogados);
$logados45 = $lista1['vendedor'];
?>

Estou usando de forma errada?
Preciso transformar em string, array ou algo do tipo?


text:
Q: Cache images during component did mount I am trying to cache images whose url i got from my api so that i dont see my imageview background when the api loads and the images dont
I am calling this function inside my async componentDidMount
 async getData(){

    this.setState({isLoading: true})
    fetch('https://news119.herokuapp.com/getData')
      .then((response) => response.json())
      .then((responseJson) => {
        this.preload(responseJson.data)
        Toast.show('Refreshed');

        this.setState({
          currentIndex:0,
          dataSource: responseJson.data.sort((a,b)=>a.date<b.date),
        }, async function(){

          this.setState({

            isLoading: false,
            loaded:true,

          })
          AsyncStorage.setItem('ApiData',JSON.stringify(this.state.dataSource))
          AsyncStorage.setItem('POINTER', '0');

        });

      })
      .catch((error) =>{
        console.error(error);
      });
  }
//the preload function
    async  preload(data){
    console.log(data)
    await FastImage.preload([data.map((item)=>{uri:item.img.data})])

Library used is react-native-fast-images.
I can see the api data in the console but the app crashes without any error screen
If you have a better way to do this(but i need to use the fast images library) please suggest me that too!

A: 'this' inside your promise doesn't mean your components 'this', it means the promise functions 'this'. You need to create a variable before your promise referring to your components 'this' and use that inside the promise to setState.
const component = this
fetch('..').then((result) => {component.setState({...})})


text:
Q: Parsing command line arguments for osascript -l JavaScript I'm looking for a way to get command line arguments for a javascript file that is using osascript.
I've tried referencing argv which works with apple script files.
I've tried referencing system, and I've tried referencing this.
Documentation appears to be light on the ground ... I've tried multiple searches but I'm either getting node matches or apple script matches.
This is the script I want to pass parameters to.
#!/usr/bin/osascript

console.log(this)

for ( key in this ) {
    console.log(key)
}

var app = Application.currentApplication()
app.includeStandardAdditions = true
var Calendar = Application("Calendar")

var eventStart = app.currentDate()
eventStart = eventStart
eventStart.setDate(eventStart.getDate() + 1)
eventStart.setHours(15)
eventStart.setMinutes(0)
eventStart.setSeconds(0)
var eventEnd = new Date(eventStart.getTime())
eventEnd.setHours(16)

var projectCalendars = Calendar.calendars.whose({name: "csmu"})
var projectCalendar = projectCalendars[0]

var event = Calendar.Event({summary: "Important Meeting!", startDate: eventStart, endDate: eventEnd})
projectCalendar.events.push(event)
event

This is an example run.
./create-event.js '{"calendar":"BD2T-AT"}'
[object GlobalObject]
eventEnd
eventStart
Calendar
event
app
projectCalendar
projectCalendars
Application("Calendar").calendars.whose({_match: [ObjectSpecifier().name, "csmu"]}).calendars.at(0).events.byId("3F6F91B0-06CD-4688-ADED-238BA40915DC")

How do you parse command line arguments for osascript -l JavaScript

A: I tried creating a run function. That worked!
Example script.
#!/usr/bin/osascript

function run(command_line_parameters){

    command_line_parameters = JSON.parse(command_line_parameters)

    calendar_name = command_line_parameters['calendar']

    summary = command_line_parameters['summary']

    starts = command_line_parameters['starts']
    start_date_time = starts.split(' ')
    start_date = start_date_time[0]
    start_time = start_date_time[1].split(':')

    ends = command_line_parameters['ends']
    end_date_time = ends.split(' ')
    end_date = end_date_time[0]
    end_time = end_date_time[1].split(':')

    var app = Application.currentApplication()
    app.includeStandardAdditions = true
    var Calendar = Application("Calendar")

    var eventStart = new Date(start_date)

    eventStart.setHours(start_time[0])
    eventStart.setMinutes(start_time[1])
    eventStart.setSeconds(0)

    var eventEnd = new Date(end_date)
    eventEnd.setHours(end_time[0])
    eventEnd.setMinutes(end_time[1])
    eventEnd.setSeconds(0)

    console.log(calendar_name,summary,starts,ends)

    var projectCalendars = Calendar.calendars.whose({name: calendar_name})
    var projectCalendar = projectCalendars[0]

    var event = Calendar.Event({summary: summary, startDate: eventStart, endDate: eventEnd})
    projectCalendar.events.push(event)
    event

}

Example run.
./create-event.js '{"calendar":"BD2L-AT", "starts":"2018-12-16 09:00", "ends":"2018-12-16 13:43", "summary":"Created from command line"}'

Which created an event in the BD2L-AT calendar from 09:00 to 13:43 on the 16 of December 2018.