text:
Q: Specifying logging in a JBoss and Hibernate environment We have a Java-based webapp running on JBoss EAP 6.4.  We were getting way too many log messages from certain portions of our code, for example, thousands of
15:06:31,400 INFO  [stdout] (pool-6-thread-1) Hibernate: select nextval ('hibernate_sequence')

In our presistence.xml, we had:
<properties>
    <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
    <property name="hibernate.connection.datasource" value="java:jboss/datasources/ourDS"/>
    <!-- Scan for annotated classes and Hibernate mapping XML files  -->
    <property name="hibernate.archive.autodetection" value="class, hbm"/>
    <property name="hibernate.hbm2ddl.auto" value="update" />
    <property name="hibernate.show_sql" value="true" />
    <property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform"/>
</properties>

Following the advice of this blog, we commented out the show_sql line, because we want to have finer control of our logging.  After doing so, the hibernate logging disappeared, as expected.  Next, we tried to turn logging back on, using JBoss's standalone.xml file and setting the level for org.hibernate.SQL to be INFO.
<profile>
    <subsystem xmlns="urn:jboss:domain:logging:1.5">
        <console-handler name="CONSOLE">
            <level name="INFO"/>
            <formatter>
                <named-formatter name="COLOR-PATTERN"/>
            </formatter>
        </console-handler>
        <periodic-rotating-file-handler name="FILE" autoflush="true">
            <formatter>
                <named-formatter name="PATTERN"/>
            </formatter>
            <file relative-to="jboss.server.log.dir" path="server.log"/>
            <suffix value=".yyyy-MM-dd"/>
            <append value="true"/>
        </periodic-rotating-file-handler>
        <logger category="org.hibernate.SQL">
            <level name="INFO"/>
        </logger>
        <logger category="org.jboss.as.config">
    <!-- other config omitted -->
</profile>

This doesn't seem to work.  None of the original Hibernate log messages appear.  Why?
As I've mentioned, ultimately we want to have finer-grained output of our messages, i.e., suppress  logging for certain Hibernate persistence operations while enabling it for others.  But first I need to figure out the basic problem.
BTW, I've set a breakpoint in the Java debugger to inspect the debug setting.
Logger sqlLogger = Logger.getLogger("org.hibernate.SQL");
Level sqlOrigLogLevel = sqlLogger.getLevel();

It shows INFO.

A: Hibernate logs in the org.hibernate.SQL category at the DEBUG level, your configuration limits it to INFO so they are silenced. You need to lower that level to DEBUG if you want to see the logs.
This not the same thing as hibernate.show_sql, when that option is enabled it uses the console, not the logger. So it should probably be disabled


text:
Q: BizTalk - SFTP - Overwrite Existing file I am trying to copy a file using SFTP .
Suppose in the destination SFTP location same file name exists, can we overwrite that with a new file?
Or can we delete the existing file in the destination and copy the new one?
We know the file name which needs to be moved to destination SFTP location.

A: In the SFTP adapter, the default behavior is to overwrite if it already exists. It's probably best to try it out yourself, because you will have questions about how components behave more often in BizTalk.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Проседает по времени при апдейте документа Есть коллекция в Монго, сейчас в ней 227750 документов. Сигнатура документа такая:
{
    "_id" : ObjectId("5c5d4c3a086dad5e5ab8d397"),
    "Uid" : "SomeiDString",
    "SomeTextField" : "SomeText"
}

индексы - два поля:
{
    "v" : 2,
    "key" : {
        "_id" : 1
    },
    "name" : "_id_",
    "ns" : "db.mycollection"
},
{
    "v" : 2,
    "unique" : true,
    "key" : {
        "Uid" : 1.0
    },
    "name" : "Uid_1",
    "ns" : "db.mycollection",
    "background" : true
}

В шарпе выполняю асинхронный UpdateOneAsync, по фильтру Uid, апдейчу "SomeTextField".
private async Task < bool > PutSomeTextMongoDb(string Uid, string SomeText) {
  var collection = database.GetCollection < User > (MONGO_DB_COLLEСTION);
  var filter = Builders < User > .Filter.Eq("Uid", Uid);
  var update = Builders < User > .Update.Set("SomeText", SomeText);
  var option = new UpdateOptions {
    IsUpsert = true
  };
  var result = await collection.UpdateOneAsync(filter, update, option);
  return result.ModifiedCount != 0;
}

Проблема заключается в том, что на 5000 запрсов среднее время выполнения всякой логической обработки и записи в монго хорошо 2-3 мс, но у некоторых обращений в монгу время заметно вырастает - запрос на добавление в монгу и получение от неё ответа доходит до 1000 мс. С чем может быть это связано? Может ли быть какой-то lock при апдейте, или может когда монга делает flush на диск, там копится некая очередь?
mongostat и mongotop ответов не дали...


text:
Q: How to show entered order no and selected product name and id i am new in mvc. so could not figure out what to add in code to show entered order no and selected product name and id.
here is full code and dotnetfiddle url https://dotnetfiddle.net/6vn2GO
Model code
using System;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Collections.Generic;

namespace HelloWorldMvcApp
{
    public class OrderViewModel
    {
        [Display(Name = "Order number")]
        public int? OrderNumber { set; get; }
        [Display(Name = "Product")]
        [Required(ErrorMessage = "Please select a product")]
        public int SelectedProductId { set; get;}
        public SelectList ProductList { get; set; }
    }

    public class Product
    {
        public int ID { set; get; }
        public string Name { set; get; }
    }

    public static class Repository
    {
        public static IEnumerable<Product> FetchProducts()
        {
            return new List<Product>()
            {
                new Product(){ ID = 1, Name = "Ketchup" },
                new Product(){ ID = 2, Name = "Mustard" },
                new Product(){ ID = 3, Name = "Relish" }
            };
        }
    }

}

Controller code
using System;
using System.Web.Mvc;
using System.Collections.Generic;

namespace HelloWorldMvcApp
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            OrderViewModel model = new OrderViewModel();
            model.OrderNumber=null;
            ConfigureViewModel(model);
            return View(model);
        }
        [HttpPost]
        public ActionResult Index(OrderViewModel model)
        {
            if (!ModelState.IsValid)
            {
                ConfigureViewModel(model);
                return View(model);
            }
            // save and redirect
            // but for testing purposes
            ConfigureViewModel(model);
            return View(model);
        }

        private void ConfigureViewModel(OrderViewModel model)
        {
            IEnumerable<Product> products = Repository.FetchProducts();
            model.ProductList = new SelectList(products, "ID", "Name");
        }
    }
}

View.cshtml code
@model HelloWorldMvcApp.OrderViewModel
@{
    Layout = null;
}

<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Bootstrap 101 Template</title>

        <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">

Hello Stranger

                @using (Html.BeginForm())
                {

                        @Html.LabelFor(m => m.OrderNumber)
                        @Html.TextBoxFor(m => m.OrderNumber, new {@class="form-control"})
                        @Html.ValidationMessageFor(m => m.OrderNumber)

                        @Html.LabelFor(m => m.SelectedProductId)
                        @Html.DropDownListFor(m => m.SelectedProductId, Model.ProductList, "-Please select-", new {@class="form-control"})
                        @Html.ValidationMessageFor(m => m.SelectedProductId)

                    <button type="submit" class="btn btn-success submit">Save</button>
                }

please tell me what code i need to add in view html to show entered order no and selected product name and id. thanks

A: You could set the value of your order number on the [HttpPost] Action method and check if it's null on the view side and show/hide stuff accordingly.
Another (probably better) alternative would be to just create a new view and return that when the model state is valid.  To get the order number, you'll need to fetch the inserted ID from the database and pass that to the view.
Edit to show some code:
Controller Code:
using System;
using System.Web.Mvc;
using System.Collections.Generic;

namespace HelloWorldMvcApp
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            OrderViewModel model = new OrderViewModel();
            model.OrderNumber=null;
            ConfigureViewModel(model);
            return View(model);
        }
        [HttpPost]
        public ActionResult Index(OrderViewModel model)
        {
            if (!ModelState.IsValid)
            {
                ConfigureViewModel(model);
                return View(model);
            }
            // save and redirect
            // but for testing purposes
            ConfigureViewModel(model);
            // you'll need to figure out how you're generating your
            // order numbers
            //
            model.OrderNumber = 1; // just set this statically for now for POC
            return View(model);
        }

        private void ConfigureViewModel(OrderViewModel model)
        {
            IEnumerable<Product> products = Repository.FetchProducts();
            model.ProductList = new SelectList(products, "ID", "Name");
        }
    }
}

View Code:
@model HelloWorldMvcApp.OrderViewModel
@{
    Layout = null;
}

<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Bootstrap 101 Template</title>

        <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">

         @{
          if(Model.OrderNumber == null)
          {

Hello Stranger

                @using (Html.BeginForm())
                {

                        @Html.LabelFor(m => m.OrderNumber)
                        @Html.TextBoxFor(m => m.OrderNumber, new {@class="form-control"})
                        @Html.ValidationMessageFor(m => m.OrderNumber)

                        @Html.LabelFor(m => m.SelectedProductId)
                        @Html.DropDownListFor(m => m.SelectedProductId, Model.ProductList, "-Please select-", new {@class="form-control"})
                        @Html.ValidationMessageFor(m => m.SelectedProductId)

                    <button type="submit" class="btn btn-success submit">Save</button>
                }

            } else {

show your confirmation stuff here

            }
         }

that will reuse the same view, though as I said, I'd recommend using a different view.


text:
Q: xmessage to the active X window from cron I have made cron commands like "go to sleep", "open window", "close window" etc. to pop out with xmessage using it's argument -display. Usually -display :0.0 produces the desired result but there are times when I use multiple X screens (:0.1, :0.2..) and therefore I miss these messages.
Is there a way to find out which X session is active in like that user is viewing that session at that very moment?

A: Try with the commands who -t, or even just w
These commands will give you information about the console and the X server


text:
Q: Access training operation in a tf.keras.Model How would one access a training operation from a tf.keras.models.Model?
Consider the following:
import tensorflow as tf
from tensorflow.keras.layers import Dense, Input, Flatten
from tensorflow.keras.models import Model
import numpy as np
from sys import exit as xit
# Make some dummy data
dummy_data_shape=(5,5)
def batch_generator(size):
    """ Makes some random data """
    def _gen():
        y_batch=np.random.randint(0,2, size=size)
        y_batch=np.expand_dims(y_batch,-1)
        y_expanded=np.expand_dims(y_batch,-1)
        x_batch=np.ones((size,*dummy_data_shape))*y_expanded
        yield x_batch,y_batch
    return _gen()

# Make some simple model
Y=tf.placeholder(tf.float32,[None,1])
X = Input(shape=dummy_data_shape)
layer_mod = Flatten()(X)
layer_mod = Dense(1)(layer_mod)

# Tie it all together and compile
out_model = Model(inputs=[X], outputs=[layer_mod])
out_model.compile(
    optimizer=tf.keras.optimizers.Adam(),
    loss=tf.keras.metrics.binary_crossentropy
)

### How can I access a train_op from the out_model?
with tf.Session() as sess:
    data_iter=batch_generator(10)
    sess.run(tf.global_variables_initializer())
    x,y=next(data_iter)
    ## Here: How to access the operation that trains the model?
    train_op=out_model.train_op #<-- ?
    sess.run(train_op, feed_dict={X:x,Y:y})

What should the second to last line in the code above be for the model to train?


text:
Q: Can I record a zoom meeting without attending? I mostly just want to use this for talks I cannot attend, but is there a way to record a zoom meeting without having to be present at the particular time.

A: From a recent Zoom blog post:

We do not have a backdoor that allows someone to enter a meeting without being visible.

So it is not possible to even view a Zoom meeting without being a participant, let alone record that meeting.

A: No only the current host of a zoom meeting can record it.
And honestly I wouldn't like anybody not participating in my meeting to record it. The correct way is to notify the organizer you can't attend and ask for the recording.


text:
Q: Mutex lock does not work as expected in C I try to implement a Hospital Simulation Project with threads but the mutex lock does not work as expected registration size should not be lower than zero if registration size is equal to zero then threads must wait for increment but if I increment the number of patients (they are also threads) registration size can be lower than 0. Why is that happening?
int REGISTRATION_SIZE = 10;
pthread_cond_t condRegister;
pthread_mutex_t mutex;

Patient:
struct Patient {
    struct Disease disease;
    pthread_t thread_id;
    int thread_num;
    int Hunger_Meter; // Initialized between 1 and 100 at creation.
    int Restroom_Meter; // Initialized between 1 and 100 at creation.
};

Thread function:
void *thread_func(void *p){
    struct Patient *patient = (struct Patient*)p;
    registration();
    return NULL;
}

Sleep method:
void sleepForMs(int ms){
    usleep( 1000 *  ms);
}

Thread Usage:
void registration(struct Patient *p){
    int rnd_wait_time;
    pthread_mutex_lock(&registration_mutex);
    while(REGISTRATION_SIZE == 0){
        rnd_wait_time = generate_rnd_numb(WAIT_TIME) + 1;
        //printf("Patient[%d] waiting for an availabe desk.\n",p->thread_num);
        sleepForMs(rnd_wait_time);
        increase_meters(p);
        checkForRestOrCafe(p);
        pthread_cond_wait(&register_cond,&registration_mutex);
    }
    REGISTRATION_SIZE--;
    printf(" Registration size: %d \n", REGISTRATION_SIZE);
    pthread_mutex_unlock(&registration_mutex);

    int register_time = generate_rnd_numb(REGISTRATION_TIME) + 1;
    sleepForMs(register_time);

    pthread_mutex_lock(&registration_mutex);
    REGISTRATION_SIZE++;
    pthread_mutex_unlock(&registration_mutex);
    pthread_cond_signal(&register_cond);
}

Main:
int main()
{
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&condRegister, NULL);

    srand(time(NULL));
    int NUMB_OF_PATIENT = 3000;

    struct Disease *diseases = malloc(sizeof(struct Disease));
    diseases = create_diseases();

    struct Patient patient[NUMB_OF_PATIENT];

    create_patients(patient,NUMB_OF_PATIENT,diseases);

    for (int i = 0; i < NUMB_OF_PATIENT; i++)
    {
        pthread_create(&(patient[i].thread_id), NULL, thread_func, (void *)(patient + i));
    }

    //wait for all threads
    for (int i = 0; i < NUMB_OF_PATIENT; i++)
    {
        pthread_join(patient[i].thread_id, NULL);
    }

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&condRegister);
    return (0);
}

Divide Registration into functions:
void wait_for_available_resource(struct Patient *p, pthread_mutex_t mutex, pthread_cond_t cond, int resource){
    int rnd_wait_time;
    pthread_mutex_lock(&mutex);
    while(resource == 0){
        rnd_wait_time = generate_rnd_numb(WAIT_TIME) + 1;
        sleepForMs(rnd_wait_time);
        increase_meters(p);
        checkForRestOrCafe(p);
        pthread_cond_wait(&cond,&mutex);
    }
    resource--;
    printf(" Resource Number: %d \n", resource);
    pthread_mutex_unlock(&mutex);
}

void spend_process_time(int needed_time){
    int elapsed_time = generate_rnd_numb(needed_time) + 1;
    sleepForMs(elapsed_time);
}

void release_resource(pthread_mutex_t mutex, int resource_number, pthread_cond_t cond){
    pthread_mutex_lock(&mutex);
    printf("-----------\n");
    printf("resource number:%d\n",resource_number);
    resource_number++;
    printf("resource number:%d\n",resource_number);
    HOSPITAL_WALLET += REGISTRATION_COST;
    printf("-----------\n");
    pthread_mutex_unlock(&mutex);
    pthread_cond_signal(&cond);
}

void registration(struct Patient *p){
    wait_for_available_resource(p,registration_mutex,register_cond,REGISTRATION_SIZE);
    spend_process_time(REGISTRATION_TIME);
    release_resource(registration_mutex,REGISTRATION_SIZE,register_cond);

}


text:
Q: Apex addError() works only for text/number SObject fields, when use inlineEditSupport in pageBlockTable I have few custom validations, which i use in my controller. And i found that not for all fields it works correctly. I figured out that it shows only message, but doesnt show error near the inputField area, if the field type is not a text or a number. And everything is ok, if i remove inlineEditSupport
My part of vf page:
<apex:pageMessages id="messages" />
<apex:pageBlockTable  value="{!questions}" var="question" >
                  <apex:column headerValue="field 1" >
                       <apex:outputField value="{!question.field1__c}" >
                           <apex:inlineEditSupport event="ondblClick" />
                       </apex:outputField>
                    </apex:column>
                    <apex:column headerValue="field 2" >
                       <apex:outputField value="{!question.field2__c}" >
                           <apex:inlineEditSupport event="ondblClick" />
                       </apex:outputField>
                    </apex:column>
                    <apex:column headerValue="field 3" >
                       <apex:outputField value="{!question.field3__c}" >
                           <apex:inlineEditSupport event="ondblClick" />
                       </apex:outputField>
                    </apex:column>

In controller:
for (Question__c question : questions) {
   question.field1__c.addError('field1 is required');
   question.field2__c.addError('field2 is required');
   question.field3__c.addError('field3 is required');
}

Any ideas, why that happens and how to fix it?

A: This has to do with how inlineEdit mechanism is Salesforce is realised: outputField has a paired inputField element, and only one is rendered at a time, depending in what mode you are. addError in its order can only render error message for input field, but it's not rendered at the time when validation occur.
Here is what I'm using to validate required fields on VF page with inlineEditSupport:
Disclaimer: code below could include other people's code, more likely a combination of them, but I don't remember from where it was taken, and it also has a good portion of my trial and error's
VF page
<apex:pageBlockSection >
<apex:inlineEditSupport rendered="{!shouldDisable == 0}" />

    <apex:repeat value="{!$ObjectType.Action__c.FieldSets.EditAction}" var="fieldValue">

        <apex:outputField id="reqField" value="{!aLine[fieldValue]}"
            rendered="{!fieldValue.Required || fieldValue.DBRequired}"/>
        <apex:outputField value="{!aLine[fieldValue]}"
            rendered="{! !(fieldValue.Required || fieldValue.DBRequired)}"/>
    </apex:repeat>
</apex:pageBlockSection>

var j$ = jQuery.noConflict();
var reqMarked = false;

j$(document).ready(function() {
    j$('.inlineEditWrite,.inlineEditWriteOn')
        .dblclick(function() {
            if (!reqMarked) {
                markRequired();
            }
    });
});

function markRequired() {
    j$('[id*=reqField].inlineEditDiv, .inlineEditGroup')
        .addClass('inlineEditRequiredDiv')
        .removeClass('inlineEditDiv');

    j$('[id*=reqField_ileinneredit].inlineEditCompoundDiv')
        .addClass('inlineEditRequiredDiv');
}

In controller:
public pageReference onSave()
{
    pageReference pr = null; // refresh the page by default
    fieldsValidation();
    // commit changes if there is no validation (or any other) page error messages
    if (ApexPages.getMessages().size() == 0)
    {
        try
        {
            update aLine;
            pr = new pageReference('/' + aLine.Id);
        }
        catch(DmlException ex)
        {
            ApexPages.addMessages(ex);
            for (Integer i = 0; i < ex.getNumDml(); i++)
            {
                // Process exception here
                System.debug(ex.getDmlMessage(i));
             }
            System.debug('DmlException caught: ' + ex.getMessage());
        }
    }
return pr;
}

public void fieldsValidation()
{
// validation on required fields from 2 fieldsets
    List<Schema.FieldSetMember> editAction = SObjectType.Action__c.FieldSets.EditAction.getFields();
    editAction.addAll(SObjectType.Action__c.FieldSets.EditAction_Wide.getFields());

    String listRequired = ''; // Will hold all blank required filed labels

    for(integer a=0;a<editAction.size();a++)
    {
        if((editAction[a].DBRequired || editAction[a].Required) &&
         (aLine.get(editAction[a].getFieldPath()) == null || aLine.get(editAction[a].getFieldPath()) == ''))
        {
            listRequired += ', ' + editAction[a].Label;
        }
    }
    if (!String.isBlank(listRequired))
    {
        aLine.addError('The following field' + (listRequired.indexOf(',', 1) == -1 ? ' is ' : 's are ') +
            'required: ' + listRequired.removeStart(', ') + '');
    }
}


text:
Q: Windows 10 machine without a monitor. Display options? Is it possible to connect a laptop to a Windows desktop, with no connected monitor, and use the screen of the laptop as the desktop's monitor?

A: The answer may vary, depending on the use you mean to have:

*

*You need to connect the desktop and laptop only once, and leave the system as that, or

*You also use the laptop on its own sometimes. This is a more complex scenario. Case 1, with repeated reboots, may become similar to this case 2.

You have a few options:

*

*Connect a software for sharing screen/control (e.g., TeamViewer, VNC), with the desktop as a server and the laptop as a client. Then whatever you do on the desktop will be seen in TeamViewer on the laptop.
The connection goes through the network, so it might be not completely smooth.
You would need (some of this applies to other options as well):
1.1. A monitor available for the initial setup of the desktop.
1.2. To confirm you can allow TeamViewer on the desktop to automatically allow connections from the client (so you don't need to take any action on the desktop each time you connect).
1.3. To have both devices connected to the network.

*Use SpaceDesk.

*Use your laptop as a wireless display, with Project to this PC. Only with Win 10 (given the tag, I assume this is your case).

*Mess with the hardware (for the more venturous). See also this.
Related:

*

*https://www.quora.com/Can-I-use-a-laptop-as-a-primary-monitor-for-my-CPU/answer/Kelly-Curry-31

*https://www.techradar.com/how-to/how-to-use-your-laptop-as-a-monitor

*https://techguided.com/how-to-use-a-laptop-as-a-monitor/

*https://store.hp.com/us/en/tech-takes/how-do-I-use-laptop-as-monitor

*https://freedom251.com/use-laptop-as-a-monitor/

*https://hardforum.com/threads/can-i-use-a-laptop-as-the-primary-display-for-a-desktop-system.1618229/

*https://basiccomputertips.com/can-you-use-a-laptop-as-a-monitor/


text:
Q: Inconsistent image move behavior in quilljs with react i have encountered an issue, when making a text editor with support of image based tags. There is a need to move those tags around freely in the text, which is being made impractical by this issue.
Basically when I start dragging an image, and then drop it on desired location, one of two results can happen: A) it works as intended and B) the image is dropped to the end/beginning of the sentence. You can see the behaviour in attached gif. Resulting behavior
I'm using react and typescript combination for creating the page with quill being inserted in a component.

// TextEditor/index.tsx
import * as React from 'react';
import * as Quill from 'quill';

import { TextEditorState, TextEditorProps } from '../@types';
import { generateDelta } from '../@utils/generateDelta';

const formats = [
  'image'
];

class TextEditor extends React.Component<TextEditorProps, TextEditorState> {
  constructor(props: TextEditorProps) {
    super(props);
    this.state = {
      Editor: undefined
    }
  }

  componentDidMount() {
    const self = this;
    this.setState({Editor: new Quill('#editor-container', {formats: formats, debug: 'warn'})});

  }

  changeText(text: string) {
    if(typeof(this.state.Editor) !== 'undefined') {
      this.state.Editor.setContents(generateDelta(text), 'api');
    }
  }

  render() {
    return (

    );
  }
}

export default TextEditor;

And the usage of this component in another component is just

// editor.tsx
import TextEditor from '../QuillEditor/TextEditor';

...

onUpdate(text: string) {
  this.refs.targetEditor.changeText(text);
}

...
render() {
  return (
    ...
    <TextEditor
      ref={'targetEditor'}
    />
    ...
  )
}

I have tried to change the text editor to just contentEditable div and that worked flawlessly, so it shouldn't be because of some css glitch.
Has anyone some idea of what could be causing this?
EDIT Feb 6:
I have found out, that this issue is manifesting only in Chrome, as IE and MS Edge did not encountered this issue. I have tried to switch off all extensions, yet the issue is still there. Private mode also didn't help.

A: After few days of research I have figured out what is causing the issue.
The combination of Quill and React won't work, because of the way React 'steals' input events, while creating the shadow DOM. Basically, because it tries to process my input in contenteditable div created by Quill, it causes some actions to not fire, resulting in the weird behaviour. And because Quill tries to do it by itself, outside of React DOM.
This I have proved in my simple testing project, where adding a simple input tag anywhere on the page broke down the Quill editor.
Possible solution would be to use react-quill or some other component container, however I haven't managed to make it successfully work, or write some yourself, which would incorporate Quill to React in its DOM compatible way.


text:
Q: How can i fill the recylerview with firebase realtime database data? I tried so many solutions about this, but none of this resolve my problem. I can not reach the database using recyclerview. I have firebase realtime database data like this;
Tag
  --- Main Category
               ----- keyID
                         ------ main-Category, sub-category
Tags class
public class Tags {
    private String id;
    private String mainTags;
    private String subTags;

    public Tags() {}

    public Tags(String id, String mainTags, String subTags) {
        this.id = id;
        this.mainTags = mainTags;
        this.subTags = subTags;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getMainTags() {
        return mainTags;
    }

    public void setMainTags(String mainTags) {
        this.mainTags = mainTags;
    }

    public String getSubTags() {
        return subTags;
    }

    public void setSubTags(String subTags) {
        this.subTags = subTags;
    }
}

and this is TagAdapter
public class TagAdapter extends RecyclerView.Adapter<TagAdapter.ItemViewHolder> {

    private List<Tags> mTagList;
    private Context mContext;

    public TagAdapter(List<Tags> mTagList, Context mContext) {
        this.mTagList = mTagList;
        this.mContext = mContext;
    }

    @NonNull
    @Override
    public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.each_item_tags, parent,false);
        return new ItemViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ItemViewHolder holder, int position) {

        Tags tags = mTagList.get(position);
        holder.tvTags.setText(tags.getSubTags());
        holder.tvMainTags.setText(tags.getMainTags());

    }

    @Override
    public int getItemCount() {
        return mTagList.size();
    }

    public class ItemViewHolder extends RecyclerView.ViewHolder{

        private TextView tvMainTags, tvTags;

        public ItemViewHolder(@NonNull View itemView) {
            super(itemView);

            tvMainTags = itemView.findViewById(R.id.tvMainTag);
            tvTags = itemView.findViewById(R.id.tvTags);
        }
    }
}

TagsFragment
  @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_tags, container, false);
        rvTags = view.findViewById(R.id.rvTags);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvTags.setLayoutManager(linearLayoutManager);
        rvTags.hasFixedSize();

        tagAdapter = new TagAdapter(tagsList, getContext());
        rvTags.setAdapter(tagAdapter);

        return view;
    }

private void getTagView(){
        FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
        DatabaseReference dbRefTags = firebaseDatabase.getReference().child("Tag");

        dbRefTags.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                for (DataSnapshot ds : dataSnapshot.getChildren()){
                    if (ds.exists()) {
                        try {
                            Tags tags = ds.getValue(Tags.class);
                            tagsList.add(tags);
                        }catch (Exception e){
                            Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show();
                        }

                    }else {
                        Toast.makeText(getContext(), "Bir hata oluştu", Toast.LENGTH_SHORT).show();
                    }
                }

                tagAdapter.notifyDataSetChanged();
            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

}

There is no error show up when running but i couldn't be able to retrieve data. And i tried firebaseRecyclerView.Adapter also and in the last dependency, i couldn't make it work. I don't know what is wrong in here. how can i solve this?

A: Get The data with child name ds.child("SubTag").getValue()
  dbRefTags.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    for (DataSnapshot parentDS : dataSnapshot.getChildren()) {
                        Log.d("Tag:", String.valueOf(parentDS.getKey()));
                        for (DataSnapshot ds : parentDS.getChildren()) {
                            Tags tags = new Tags();
                            tags.setMainTag(parentDS.getKey());
                            tags.setSubTag(ds.child("SubTag").getValue().toString());
                            Log.d("Tag: -> SubTag)", tags.getSubTag());
                            tagsList.add(tags);
                        }
                    }
                    tagAdapter.notifyDataSetChanged();
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {
                    Toast.makeText(getContext(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });


text:
Q: Customize dynamic dialog PRIMNG How i can customize dynamic dialog template from PrimNG?
I follow this guide https://www.primefaces.org/primeng/#/dynamicdialog .
I want to customize footer part with my own template, but i don`t no how it do.
Help please)
Thanks!!!

A: You can customize on the main css file like this:
body .ui-dialog .ui-dialog-footer {
  padding: 10px 15px;
  background-color: #20252e;
}


text:
Q: Flutter How to Save a Google Places Object Into Shared Preferences How can I achieve the following functionality:
I'm attempting to save a PlacesDetailsResponse:
prefs.setString("last_known_google_places_location", json.encode(_placeDetail));

Then call it back like:
PlacesDetailsResponse last_location_obj = json.decode(prefs.getString("last_known_google_places_location")!);

Error:
E/flutter ( 5976): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'PlacesDetailsResponse?'
E/flutter ( 5976): #0      MyWidget.example(package:flutter_listings/main.dart:381:17)
E/flutter ( 5976): <asynchronous suspension>

I'm using the package:
import 'package:flutter_google_places/flutter_google_places.dart';

The code seems to suggest I can save it via json encode... here is the official class from the package:
@JsonSerializable()
class PlacesDetailsResponse extends GoogleResponseStatus {
  final PlaceDetails result;

  /// JSON html_attributions
  @JsonKey(defaultValue: <String>[])
  final List<String> htmlAttributions;

  PlacesDetailsResponse({
    required String status,
    String? errorMessage,
    required this.result,
    required this.htmlAttributions,
  }) : super(
          status: status,
          errorMessage: errorMessage,
        );

  factory PlacesDetailsResponse.fromJson(Map<String, dynamic> json) =>
      _$PlacesDetailsResponseFromJson(json);
  Map<String, dynamic> toJson() => _$PlacesDetailsResponseToJson(this);
}

A: It appears I was missing a step and not decoding the json into a PlacesDetailsResponse object, you can accomplish this via the class fromJson method:
 PlacesDetailsResponse the_last_place = PlacesDetailsResponse.fromJson(json.decode(prefs.getString("last_known_google_places_location")!));


text:
Q: jsf conditionally set id i have a custom tag and want to allow to set the id of an inner element
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:rich="http://richfaces.org/rich"
    xmlns:a4j="http://richfaces.org/a4j">

<f:subview rendered="#{not empty id}">
    <h:message styleClass="message" id="#{id}" errorClass="message error"
        warnClass="message warn" for="#{element}" />
</f:subview>
<f:subview rendered="#{not id}">
    <h:message styleClass="message" errorClass="message error"
        warnClass="message warn" for="#{element}" />
</f:subview>
</html>

but i always get
Empty id attribute is not allowed

how can i archieve that when the user sets an id it is used, and when not jsf should generate it by its own

A: Use <c:if> to conditionally add a <f:attribute> with the id.
<h:message styleClass="message" errorClass="message error" warnClass="message warn" for="#{element}">
    <c:if test="#{not empty id}">
        <f:attribute name="id" value="#{id}" />
    </c:if>
</h:message>

By the way, using <html> instead of <ui:composition> in a custom tag or even without it is quite strange. Are you sure that you end up with syntactically valid HTML? Further, your second <f:subview rendered> expression is incorrect, but that has nothing to do with the particular error message you got.

A: Using BalusC's answer left me with IllegalArgumentException in UIComponent class where it's specifically thrown for id:
else if ("id".equals(name) || "parent".equals(name)) {
    throw new IllegalArgumentException();
}

I ended up using Omnifaces' o:tagAttribute.


text:
Q: pandas pivot_table column names For a dataframe like this:
d = {'id': [1,1,1,2,2], 'Month':[1,2,3,1,3],'Value':[12,23,15,45,34], 'Cost':[124,214,1234,1324,234]}
df = pd.DataFrame(d)

     Cost  Month  Value  id
0    124       1     12   1
1    214       2     23   1
2    1234      3     15   1
3    1324      1     45   2
4    234       3     34   2

to which I apply pivot_table
df2 =    pd.pivot_table(df,
                        values=['Value','Cost'],
                        index=['id'],
                        columns=['Month'],
                        aggfunc=np.sum,
                        fill_value=0)

to get df2:
       Cost            Value
Month     1    2     3     1   2   3
id
1       124  214  1234    12  23  15
2      1324    0   234    45   0  34

is there an easy way to format resulting dataframe column names like
id     Cost1    Cost2     Cost3 Value1   Value2   Value3
1       124      214      1234    12        23       15
2      1324       0       234     45         0       34

If I do:
df2.columns =[s1 + str(s2) for (s1,s2) in df2.columns.tolist()]

I get:
    Cost1  Cost2  Cost3  Value1  Value2  Value3
id
1     124    214   1234      12      23      15
2    1324      0    234      45       0      34

How to get rid of the extra level?
thanks!

A: Using clues from @chrisb's answer, this gave me exactly what I was after:
df2.reset_index(inplace=True)

which gives:
id     Cost1    Cost2     Cost3 Value1   Value2   Value3
1       124      214      1234    12        23       15
2      1324       0       234     45         0       34

and in case of multiple index columns, this post  explains it well. just to be complete, here is how:
df2.columns = [' '.join(col).strip() for col in df2.columns.values]

A: 'id' is the index name, which you can set to None to remove.
In [35]: df2.index.name = None

In [36]: df2
Out[36]:
   Cost1  Cost2  Cost3  Value1  Value2  Value3
1    124    214   1234      12      23      15
2   1324      0    234      45       0      34


text:
Q: Nginx, too many redirects, err_too_many_redirects I have been learning and testing various installations of NGINX for proxy_pass (both custom compilation and standard install) using 2 servers. The problem(s) that I am having relate to "err_too_many_redirects"; Specifically, there are many references to clearing cache (I use Chrome) but that does not resolve the problem. I have also looked at the regular expressions hoping to find any misconfiguraitons, but so far nothing (from RTFM) has shown me anything that suggests a misconfiguration.
Primary server has a single domain, standard install, only 1 additional "server directive" noted below. The secondary server also has a standard install with a completely different domain name which resolves fine locally, just not from external requests (i.e. "hosts" file is configured).
server {

    server_name my2ndweb.com *.my2ndweb.com;

    location ~* {
        proxy_pass http://xxx.xxx.xxx.xxx;
    }

    ...

}

I have also modified the location directive with "/" instead of "~*", as well as the FQDN at the "proxy_pass" statement (I read somewhere the hosts file would resolve it rather than re-directing to a local address...did nothing for it though);
Anyway, this all works if I use a single server and just place the different domains within different folder structures, but that defeats the purpose of having a failover option if one server breaks...-no I did not configure failover, just thinking about it.
NOTE: There is no other error in the logs whatsoever regarding redirects!
k/r
axetone

A: ANSWER:
I made the mistake of not removing the wildcard "*" from the nginx.conf file path statement that points to the directory (or in this case with the wildcard DIRECTORIES) used for the site configurations...~thus the error(s) I was given at reload time pointing to a line item error was actually in one of the other conf files and NOT my "default" conf file.
Silly silly mistake!
Solution: Replace the wildcard "*" from the end of the "include.." path statement in nginx.conf and instead use the actual folder/file name ONLY.
Ex:
include /etc/nginx/sites-enabled/*.conf;
REPLACE WITH:
include /etc/nginx/sites-enabled/default;   # or whatever your filename is.


text:
Q: How to make a class override an element CSS style? Below is my CSS and HTML code respectively. I want all paragraphs to be black font except for one group of three. I know that I could give each of these three paragraphs their own class but I would prefer if there was a way to change all of them at once. I thought that wrapping them in a div tag and giving that div tag the ".special-paragraphs" class would work but it doesn't. Is there any way to do this or am I forced to edit each paragraph individually?
p {
  color: black;
}

.special-paragraphs {
  color: chartreuse;
  background-color: pink;
  font-family: Arial, Helvetica, sans-serif;
}

Lorem ipsum dolor sit amet consectetur adipisicing elit.

      Quo, quaerat repudiandae ad culpa minus repellat dolore, possimus

      nemo qui sunt voluptas architecto iure accusantium nihil pariatur

      dolores debitis error asperiores.

Amet perspiciatis, cupiditate illo pariatur rem quasi ab

      reprehenderit? Ex nisi consectetur possimus, corrupti voluptates

      ullam, quod accusamus id iure quas consequuntur? Obcaecati aspernatur

      minima, temporibus ea sed totam adipisci!

Ipsa odit aut dicta perspiciatis vero commodi sequi reiciendis.

      Eum fugit sapiente blanditiis non quisquam veniam harum iusto! Ex,

      at. Laboriosam iusto provident consequuntur ab necessitatibus deserunt

      ducimus, fugit fuga!

A: you can use

...it's not the better, but works

A: try add !important :
    .special-paragraphs {
      color: chartreuse !important;
      background-color: pink;
      font-family: Arial, Helvetica, sans-serif;
    }

A: You don't need to give the style for default P element. Because it will overwrite all the P elements. So you have to add the style for special-paragraphs only. It will work.
.special-paragraphs
{
  color: chartreuse;
  background-color: pink;
  font-family: Arial, Helvetica, sans-serif;
}

I am normal

I am red

I am blue

I am green


text:
Q: Internal LTO tape drive becomes hot We use an internal LTO3 tape drive (HP Ultrium 920) in a PC (no particular server hardware) running Linux. The tape drive becomes quite hot - I don't have the exact temperature, but you may touch it for a second or two, then it hurts ;-) This happens when the tape has nothing to do (during reading/writing, it might become even hotter, I haven't checked that).
Besides that, the system is working fine. Now I'm wondering

*

*Why does the tape becomes so hot?

*Is this something I need to care about?

*Is there something like a 'standby' mode for the tape? (I think it should not consume that much energy when it is not used)

A: Tape drives are designed to be in server hardware with correct cooling and air flow setups. I would suggest you check the internal cooling arrangements especially in area of the tape drive and address this.
But I have just checked our tape drives and they are warm but these are in s a tape ibrary.

A: This is way too hot, there are always parts in any computer that would get too hot (CPU/GPU normally) but there's obviously an airflow problem with your server/'PC'. I'd get it unplugged as soon as you can and look to place it in something with appropriately cooled.
Edit - looking at their spec that particular drive isn't supposed to go over 40C/104F - so that's really not right at all.


text:
Q: Handle action onClick in DatePicker Antd I have an antd DatePicker at the header of an collapse as below
<DatePicker
  showNow
  allowClear={false}
  className={styles.edit_start_time}
  value={moment(experiment.start_time)}
  format="MMMM DD, YYYY h:mm A"
  addonBefore="Start At:"
  onChange={handleExperimentStartTimeChange}
  showTime={{ use12Hours: true, format: "h:mm A" }}
  onClick={e => e.stopPropagation()} />

The issue I am facing is every time I click on the date or time fields the collapsible is expanding and closing which not not have happened considering  onClick={e => e.stopPropagation()} which I have added.
Can anyone help me with this one.
Thanks.

A: Adding header as the collapsible property of Panel will work for you.
So, only clicking the header will trigger collapse/expand.
So, Panel element will be like:
<Panel
    header="This is panel header 1"
    key="1"
    collapsible="header"
    extra={genExtra()}
>

and your DatePicker component:
const genExtra = () => (
  <DatePicker
    showNow
    allowClear={false}
    value={moment(experiment.start_time)}
    format="MMMM DD, YYYY h:mm A"
    addonBefore="Start At:"
    onChange={handleExperimentStartTimeChange}
    showTime={{ use12Hours: true, format: "h:mm A" }}
  />
);

You don't even have to stopPropagation.
Working demo at CodeSandbox.


text:
Q: Is there a way to apply wilcoxon test grouped by site? I want to use Wilcoxon 2-sided test for two treatments across multiple groups, i.e. there is a before and after treatment (Conc) for each of several sample sites. I want to split the dataset into a list by Site then apply the test so i can have an output for each Site individually, however, i am having trouble setting this up as a function that can repeat.
I have a number of sites (Site) and two levels of treatment (Scenario), with resulting scores (Conc):
'data.frame':   7344 obs. of  6 variables:
 $ Site        : chr  "A" "B" "C" "D" ...
 $ Scenario    : chr  "1" "1" "1" "1" "2" "2" "2" "2" ...
 $ Conc        : num  4.7727 0.055 0.0552 0.055 0.055 ...

there are multiple Conc data points (~60) within each Site/Scenario combination. The reason i chose a Wilcoxon test is primarily because i have slightly uneven sample numbers between treatments (Scenario) for each Site.
When i use this code for the entire dataset i get a sensible result:
t1 <- wilcox.test(Conc ~ Scenario, data = data.frame)
t1

However, this code doesn't apply the test for each site individually.
I have looked looked at all similar examples i could find (on SO and elsewhere) and this is the best code i could come up with:
t2 = data.frame %>% group_by(Site) %>% do(tidy(wilcox.test(Conc~Scenario, data=data.frame), na.rm=TRUE, equal.var=FALSE))
t2

this code is giving me an output for each site but all test outputs are the same, even the p value:
# A tibble: 107 x 5
# Groups:   Site [107]
   Site     statistic p.value method                                      alternative
   <chr>       <dbl>   <dbl> <chr>                                             <chr>
 1 A         6145702   0.690 Wilcoxon rank sum test with continuity correction two.sided
 2 B         6145702   0.690 Wilcoxon rank sum test with continuity correction two.sided
 3 C         6145702   0.690 Wilcoxon rank sum test with continuity correction two.sided
 4 D         6145702   0.690 Wilcoxon rank sum test with continuity correction two.sided
 5 E         6145702   0.690 Wilcoxon rank sum test with continuity correction two.sided
 6 F         6145702   0.690 Wilcoxon rank sum test with continuity correction two.sided

Can anyone see what I'm doing wrong?
thanks for your help

A: EDITED 21/08/2020 to more closely mirror your data
Here's a solution with dplyr and purrr EDITED to include broom::tidy results...
# 'data.frame': 5626 obs. of 3 variables:
# $ Site.Year: Factor w/ 3 levels "Baffle Creek at Newton Road_2018_2019",..: 1 1 1 1 1 1 1 1 1 1 ...
# $ Scenario : chr "FF_Total" "FF_Total" "FF_Total" "FF_Total" ...
# $ PAF : num 4.77 4.77 4.77 4.77 4.77

set.seed(2020)

Site.Year <- rep(c("Baffle Creek at Newton Road_2018_2019",
                   "Baffle Creek at Newton Road_2017_2018",
                   "Baffle Creek at Newton Road_2019_2020"), 50)
Scenario <- rep_len(c(rep("FF_Total", 4), rep("Not_FF_Total", 4)), 150)
PAF <- rnorm(150, mean = 2.5, sd = 1)

DailyPAF_long <- data.frame(Site.Year, Scenario, PAF)

DailyPAF_long$Site.Year <- factor(DailyPAF_long$Site.Year)
# str(DailyPAF_long)
# wilcox.test(PAF ~ Scenario, data = DailyPAF_long)

library(dplyr)
library(purrr)

DailyPAF_long %>%
  base::split(Site.Year) %>%
  purrr::map(~ wilcox.test(PAF ~ Scenario, data = .)) %>%
  purrr::map_dfr(~ broom::tidy(.))

#> # A tibble: 3 x 4
#>   statistic p.value method                       alternative
#>       <dbl>   <dbl> <chr>                        <chr>
#> 1       361  0.355  Wilcoxon rank sum exact test two.sided
#> 2       219  0.0723 Wilcoxon rank sum exact test two.sided
#> 3       380  0.195  Wilcoxon rank sum exact test two.sided


text:
Q: Unix - which application is in the foreground? I need to be able to determine if a certain application/binary in Unix is running in the foreground.
I do not want to look at CPU utilization or memory utilization because technically the application could be in the background and performing a long running task.
I'm not necessarily interested in code samples.  Is this something that can be achieved using Python or some other scripting library?

A: I highly recommend the python package psutil which is ideal for system getting information about spawned and all other processes. The method is_running() of a process object appears to be the one you want.


text:
Q: What else might be stopping manifest.json from being served? The problem I am having seems fairly common though does not seem to be resolved by existing answers.
I am running an MVC app through an azure web app. When I publish the site and run it I get the following error regarding the manifest.json file:

The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

Most existing answers point to the mime mapping, however to the web.config I have added the following lines inside the existing system.webServer block:
<staticContent>
  <remove fileExtension=".json" />
  <mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>

This has not worked.
Things I have checked:

*

*manifest.json exists in /js/ as does test.json I can open test.json

*the file exists under the same domain as the file requesting it

This is the manifest.json file:
{
  "name": "MidexPRO",
  "short_name": "MidexPRO",
  "icons": [
    {
      "src": "/favicons/android-chrome-36x36.png",
      "sizes": "36x36",
      "type": "image/png"
    },
    {
      "src": "/favicons/android-chrome-48x48.png",
      "sizes": "48x48",
      "type": "image/png"
    },
    {
      "src": "/favicons/android-chrome-72x72.png",
      "sizes": "72x72",
      "type": "image/png"
    },
    {
      "src": "/favicons/android-chrome-96x96.png",
      "sizes": "96x96",
      "type": "image/png"
    },
    {
      "src": "/favicons/android-chrome-144x144.png",
      "sizes": "144x144",
      "type": "image/png"
    },
    {
      "src": "/favicons/android-chrome-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "/favicons/android-chrome-256x256.png",
      "sizes": "256x256",
      "type": "image/png"
    },
    {
      "src": "/favicons/android-chrome-384x384.png",
      "sizes": "384x384",
      "type": "image/png"
    },
    {
      "src": "/favicons/android-chrome-512x512.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ],
  "theme_color": "#57baa3",
  "background_color": "#57baa3",
  "start_url": "/app.htm",
  "display": "standalone",
  "scope": "/",
  "orientation": "portrait"
}

This is the test.json file:
{
  "a": 1
}

UPDATE...
I'm still finding myself stuck on this and no further luck on google. Just a hope that a fresh look at the question may prompt some responses!


text:
Q: Ethers: invalid object key I'm tryin send transaction via ethers, seems looks good, but has error...
Connections with wallet ok.
Code bellow:
const { ethers } = require("ethers");
(async () => {

    prov2="provider url Alchemy"

    const provider = new ethers.providers.JsonRpcProvider(prov2);
    let wallet = ethers.Wallet.fromMnemonic("my mnemonic")
    const signer = wallet.connect(provider)
    const gasPrice = provider.getGasPrice();

   let nonce = await provider.getTransactionCount(
        wallet.address,
        "latest"
  );
   const recepient = "0x00000000006c3856cbEf3e08E8dF289169EdE581";
   let txn = {
        type: 2,
        chainId: 5,
        from: wallet.address,
        to: recepient,
        value: ethers.utils.parseUnits("0.000001", "ether"),
        maxPriorityFeePerGas: ethers.utils.parseUnits("150","gwei"),
        maxFeePerGas: ethers.utils.parseUnits("170","gwei"),
        nonce: nonce
   };

    try {
        let signedTx = await signer.sendTransaction(txn)
    const receipt = await txn.wait();
    console.log(receipt);
    } catch (e) {
        console.log(e.name)
        console.log(e.message)
    }

})();

And got: invalid object key error ....
I tried googling the error, but got nothing

What can it be?

A: The error message says "object key error". I suspect that your transaction object.
let txn = {type: 2,...}

is not correct. I checked the https://docs.ethers.io/v5/api/utils/transactions/ and there is no type key property in the transaction object


text:
Q: ExtJS grid cell editing I am using extjs 4 cell editing plugin with extjs grid. It's working fine with one grid but when I create a new grid on the same page which also require cell editing, exiting grid data vanishes.  I have spent full day in diagnose the problem but in vain.
Following is the code for model, store and grids:
Ext.define('site', {
    extend: 'Ext.data.Model',
    fields: [{
        name: 'siteid'
    }, {
        name: 'description'
    }, {
        name: 'picevd'
    }, {
        name: 'Dateofaudit',
        type: 'date',
        dateFormat: 'Y-m-d'
    }, {
        name: 'dateofrecord',
        type: 'date'
    }, {
        name: 'id'
    }]
});

Ext.define('d696', {
    extend: 'Ext.data.Model',
    fields: [{
        name: 'siteid'
    }, {
        name: 'description'
    }, {
        name: 'picevd'
    }, {
        name: 'Dateofaudit',
        type: 'date',
        dateFormat: 'Y-m-d'
    }, {
        name: 'dateofrecord',
        type: 'date'
    }, {
        name: 'id'
    }]
});

var Dstore = Ext.create('Ext.data.Store', {
    //autoDestroy: true,
    storeId: 'Dstore',
    autoLoad: true,
    model: 'site',
    proxy: {
        url: '../server/sitetheftgrid.php?TYPE=SITE',
        type: 'ajax',
        reader: {
            type: 'json',
            root: 'results'
        }
    },
    sorters: [{
        property: 'Dateofaudit',
        direction: 'ASC'
    }]
}); // END Dstore

Ext.create('Ext.data.Store', {
    //autoDestroy: true,
    storeId: 'a',
    model: 'd696',
    proxy: {
        url: '../server/sitetheftgrid.php',
        type: 'ajax',
        reader: {
            type: 'json',
            root: 'results'
        }
    }
    //sorters: [{property: 'Dateofaudit',direction:'ASC'}]
}); // END Dstore

var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
    clicksToEdit: 2
});

var grid = Ext.create('Ext.grid.Panel', {
    store: Dstore,
    columns: [{
        id: 'siteid',
        header: 'Site Id',
        dataIndex: 'siteid',
        width: 100,
        field: {
            allowBlank: false
        }
    }, {
        header: 'Detail',
        dataIndex: 'description',
        flex: 1,
        field: {
            allowBlank: false
        }
    }, {
        header: 'Date Of Audit',
        dataIndex: 'Dateofaudit',
        width: 150,
        field: {
            xtype: 'datefield',
            format: 'm/d/y'
        }
    }, {
        header: 'Date Of Record',
        dataIndex: 'dateofrecord',
        width: 150
    }],
    width: '100%',
    height: 300,

    id: 'sitegrid',
    frame: true,
    plugins: [cellEditing]
});

var stor = Ext.data.StoreManager.lookup('a');

Ext.create('Ext.grid.Panel', {
    store: stor,
    columns: [{
        header: 'Site Id',
        dataIndex: 'siteid1',
        width: 100,
        field: {
            allowBlank: false
        }
    }, {
        header: 'Detail',
        dataIndex: 'description2',
        flex: 1,
        field: {
            allowBlank: false
        }
    }, {
        header: 'Date Of Audit',
        dataIndex: 'Dateofaudit4',
        width: 150,
        field: {
            xtype: 'datefield',
            format: 'm/d/y'
        }
    }, {
        header: 'Date Of Record',
        dataIndex: 'dateofrecord2',
        width: 150
    }],
    width: '100%',
    height: 300,
    id: 'sitegrid2',
    frame: true,
    autoScroll: true, //when i uncomment this data in first grid vanishes
    /*  plugins:[ Ext.create('Ext.grid.plugin.CellEditing', {
         clicksToEdit: 1
        })]*/
});

A: Just use different cell editing per grid  for example:
var cellEditing1 = Ext.create('Ext.grid.plugin.CellEditing', {clicksToEdit: 2});
var cellEditing2 = Ext.create('Ext.grid.plugin.CellEditing', {clicksToEdit: 2});

A: Try to add plugin on component init. This was helpful for me
Ext.create('Ext.grid.Panel', {
    store: stor,
    columns: [{
        header: 'Site Id',
        dataIndex: 'siteid1',
        width: 100,
        field: {
            allowBlank: false
        }
    }, {
        header: 'Detail',
        dataIndex: 'description2',
        flex: 1,
        field: {
            allowBlank: false
        }
    }, {
        header: 'Date Of Audit',
        dataIndex: 'Dateofaudit4',
        width: 150,
        field: {
            xtype: 'datefield',
            format: 'm/d/y'
        }
    }, {
        header: 'Date Of Record',
        dataIndex: 'dateofrecord2',
        width: 150
    }],
    width: '100%',
    height: 300,
    id: 'sitegrid2',
    frame: true,
    autoScroll: true,
    initComponent: function () {
        this.plugins = [Ext.create('Ext.grid.plugin.CellEditing', {
            clicksToEdit: 1
        })];

        this.callParent(arguments);
    }
});


text:
Q: Vyatta VPN IPsec tunnel random dropouts I keep getting random dropouts for my VPN tunnel, it only happens rarely (~twice a week) if I do a "service ipsec restart" then it immediately starts working again. Really annoying as I'm try to replicate a large VM to our DR site and everytime the tunnel drops I have to start again!
Config as below. Any ideas guys?
esp-group DR {
         compression disable
         lifetime 3600
         mode tunnel
         pfs enable
         proposal 1 {
             encryption aes128
             hash sha1
         }
     }

 ike-group DR {
         dead-peer-detection {
             action restart
             interval 15
             timeout 30
         }
         lifetime 28800
         proposal 1 {
             dh-group 2
             encryption aes128
             hash sha1
         }
     }

peer *.*.*.* {
             authentication {
                 mode pre-shared-secret
                 pre-shared-secret ***
             }
             connection-type initiate
             description "DR Site"
             ike-group DR
             local-address *.*.*.*
             tunnel 2 {
                 allow-nat-networks disable
                 allow-public-networks disable
                 esp-group DR
                 local {
                     prefix 192.168.*.0/24
                 }
                 remote {
                     prefix 10.*.0.0/24
                 }
             }
         }

After checking the logs, they seemed to be full with this message:
Apr  3 13:23:37 *.*.*.* pluto[20789]: packet from *.*.*.*:500: received Vendor ID payload [Dead Peer Detection]
Apr  3 13:23:37 *.*.*.* pluto[20789]: packet from *.*.*.*:500: ignoring Vendor ID payload [RFC 3947]
Apr  3 13:23:37 *.*.*.* pluto[20789]: packet from *.*.*.*:500: ignoring Vendor ID payload [draft-ietf-ipsec-nat-t-ike-03]
Apr  3 13:23:37 *.*.*.* pluto[20789]: packet from *.*.*.*:500: ignoring Vendor ID payload [draft-ietf-ipsec-nat-t-ike-02_n]
Apr  3 13:23:37 *.*.*.* pluto[20789]: packet from *.*.*.*:500: ignoring Vendor ID payload [draft-ietf-ipsec-nat-t-ike-02]
Apr  3 13:23:37 *.*.*.* pluto[20789]: packet from *.*.*.*:500: ignoring Vendor ID payload [draft-ietf-ipsec-nat-t-ike-00]
Apr  3 13:23:37 *.*.*.* pluto[20789]: packet from *.*.*.*:500: initial Main Mode message received on *.*.*.*:500 but no connection has been authorized with policy=PSK
Apr  3 13:23:39 *.*.*.* heartbeat: [3397]: ERROR: process_status_message: bad node [****] in message
Apr  3 13:23:39 *.*.*.* heartbeat: [3397]: ERROR: MSG: Dumping message with 12 fields
Apr  3 13:23:39 *.*.*.* heartbeat: [3397]: ERROR: MSG[0] : [t=status]
Apr  3 13:23:39 *.*.*.* heartbeat: [3397]: ERROR: MSG[1] : [st=active]
Apr  3 13:23:39 *.*.*.* heartbeat: [3397]: ERROR: MSG[2] : [dt=2710]
Apr  3 13:23:39 *.*.*.* heartbeat: [3397]: ERROR: MSG[3] : [protocol=1]
Apr  3 13:23:39 *.*.*.* heartbeat: [3397]: ERROR: MSG[4] : [src=****]
Apr  3 13:23:39 *.*.*.* heartbeat: [3397]: ERROR: MSG[5] : [(1)srcuuid=0x201c570(36 27)]
Apr  3 13:23:39 *.*.*.* heartbeat: [3397]: ERROR: MSG[6] : [seq=28077b]
Apr  3 13:23:39 *.*.*.* heartbeat: [3397]: ERROR: MSG[7] : [hg=50b63627]
Apr  3 13:23:39 *.*.*.* heartbeat: [3397]: ERROR: MSG[8] : [ts=533d60db]
Apr  3 13:23:39 *.*.*.* heartbeat: [3397]: ERROR: MSG[9] : [ld=0.00 0.01 0.05 1/87 31182]
Apr  3 13:23:39 *.*.*.* heartbeat: [3397]: ERROR: MSG[10] : [ttl=3]
Apr  3 13:23:39 *.*.*.* heartbeat: [3397]: ERROR: MSG[11] : [auth=1 96fa591a077c1bd3941d450c9c8973d8f0a9440f]

A: The setting I found which helped tunnel stability a lot was
set vpn ipsec auto-update '60'
My dead peer detection intervals & timeouts were longer than yours (30 & 120 seconds, respectively), and I used VTIs, but your configurations are otherwise almost identical to mine.  I was able to sustain 400 Mbps through the tunnel inside a VyOS VM no problems.

A: Sorry, cannot comment, not really an answer:

*

*Did you try to increase the ike-group DR dead-peer-detetion timeout value?

*Is it possible than, randomly, twice a week, there is a peak of network usage which saturate all the available bandwidth?


text:
Q: Logic. Express the proposition in symbols Assume we are dealing only with integers.
Using only numerals, variables, logical symbols and the mathematical symbols, I need express the following proposition:

$$100 \text{ is a multiple of } 5 $$

I've tried it, and, in my own words I came up with:

If n is a multiple of 100 then 100 is multiple of 5.

Trying to see if this is right.

A: We have,
n = 100k
= 5(20k)
So 100 is a multiple of 5.

A: I assume you need it in logic:
$\exists x : 100 = 5 * x$

A: "$100$ is a multiple of $5$"  by definition:
$$\exists\, x\in \mathbb Z \;( \,5x = 100\,)$$
And we can verify that statement is true by showing the existence of such an integer x:
$$5x= 100 \iff x = \frac{100}{5} = 20, $$ noting that the one and only integer satisfying $5x = 100$ is $x=20$.

Note that there is another way with which to express "$100$ is a multiple of $5$" $\iff$  "$5$ is a divisor of $100$."  The notation used to express "$5$ divides $100$" is given by $$5\mid 100$$  And the logical definition given above expresses as much.


text:
Q: $ Composer can't find mongodb extension, required Mongodb extension I'm using with latest php version 7.2 on macOS Mojave / macOS Big Sur / macOS Monterey / macOS Ventura and receiving error like
 $composer require mongodb/mongodb
Using version ^1.4 for mongodb/mongodb
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)

For more information about question : see the screenshoot

Your requirements could not be resolved to an installable set of
packages.

Problem 1
- mongodb/mongodb v1.4.x-dev requires ext-mongodb ^1.5.0 -> the requested PHP extension mongodb is missing from your system.
- mongodb/mongodb 1.5.x-dev requires ext-mongodb ^1.6 -> the requested PHP extension mongodb is missing from your system.
- mongodb/mongodb 1.4.2 requires ext-mongodb ^1.5.0 -> the requested PHP extension mongodb is missing from your system.
- mongodb/mongodb 1.4.1 requires ext-mongodb ^1.5.0 -> the requested PHP extension mongodb is missing from your system.
- mongodb/mongodb 1.4.0 requires ext-mongodb ^1.5.0 -> the requested PHP extension mongodb is missing from your system.
**- Installation request for mongodb/mongodb ^1.4 -> satisfiable by mongodb/mongodb[1.4.0, 1.4.1, 1.4.2, 1.5.x-dev, v1.4.x-dev].

Installation failed, reverting ./composer.json to its original content.
I have already installed mongoDB extension still receiving problem
Not sure what I've missed steps to installation. If anyone can help me with this composer problem, I'd greatly appreciate it. in advance Thanks.

A: Install PHP extension by running this command on your terminal.
sudo pecl install mongodb

At the end, you will see following information.
Build process completed successfully
Installing '/usr/local/Cellar/php/7.3.3/pecl/20180731/mongodb.so'
install ok: channel://pecl.php.net/mongodb-1.5.3
Extension mongodb enabled in php.ini

and then restart your PHP service.

A:
composer require mongodb/mongodb --ignore-platform-reqs

composer require mongodb/mongodb --ignore-platform-reqs
composer require jenssegers/mongodb --ignore-platform-reqs

Using version ^3.4 for jenssegers/mongodb
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 2 installs, 0 updates, 0 removals
  - Installing mongodb/mongodb (1.4.2): Downloading (100%)
  - Installing jenssegers/mongodb (v3.4.5): Downloading (100%)
jenssegers/mongodb suggests installing jenssegers/mongodb-session (Add MongoDB session support to Laravel-MongoDB)
jenssegers/mongodb suggests installing jenssegers/mongodb-sentry (Add Sentry support to Laravel-MongoDB)
Writing lock file
Generating optimized autoload files

composer require jenssegers/mongodb --ignore-platform-reqs
It solved my problem.

A: This error will happen when using WAMP as there is an unique php.ini for WAMP and CMD.
So you might have added the mongo-ext to your WAMP php.ini and so it looks as though it is running and included in the enabled extension's list. However, this is not available to the command line php.ini and also you need to confirm the CMD version of PHP you are running

*

*You can confirm your CMD PHP version in the windows ENV variable "path"

*If the CMD php version is not the same as the version you have included your
mongo-ext, you will have to either install the mongo-ext into that version of PHP or change your path variable to point to the version of PHP you are  currently using

*Then ensure that the extension=php_mongodb is setup in both your WAMP and CMD version of php.ini

In order to confirm you have been successful your mongo-ext will show in your phpinfo() and if you run php -m on the CMD it will show in the rendered list
composer require jenssegers/mongodb --ignore-platform-reqs

The above is not the correct way to do it, as it will create problems into the future with other packages, updates and/or installs.

A: Please check if mongodb modules is installed

php -m

Go to the installation directory and run the below command ( it will take some time)

composer require mongodb/mongodb --ignore-platform-reqs

This will ignore the MongoDB required packages & rest will be installed.
If you want the MongoDB Module to be installed then execute the below command

sudo apt-get install php-mongodb


text:
Q: How to get rid of a flicker by hovering over a button? I have a flicker at the end of the hovering over a button

.button {
    color: #add8e6;
    border: 2px solid rgb(237, 125, 194);
    border-radius: 5px;
    padding: 18px 36px;
    display: inline-block;
    font-family: "Lucida Console", Monaco, monospace;
    font-size: 14px;
    letter-spacing: 1px;
    cursor: pointer;
    box-shadow: inset 0 0 0 0 rgb(237, 125, 194);
    -webkit-transition: ease-out 0.4s;
    -moz-transition: ease-out 0.4s;
    transition: ease-out 0.4s;
  }

  .slide_right:hover {
    box-shadow: inset 400px 0 0 0 rgb(237, 125, 194);
  }
<!DOCTYPE html>

        <title>Fashion Closet</title>
        <link href="/styles/styles.css" rel="stylesheet">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

Fashion Closet

Unique look for daily routine</h22>

                    <input id="search-text" type="text" class="input" placeholder="Filter looks">
                    <select id="filter-by" class="dropdown">
                        <option value="byEdited">Sort by last edited</option>
                        <option value="byCreated">Sort by recently created</option>
                        <option value="alphabetical">Sort alphabetically</option>
                    </select>

            <button id="create-look" class="button slide_right">Create a new look</button>

If adding -webkit-backface-visibility: hidden; to a .button, this gets underlined, and it doesn't help. What else can I try?
Maybe a problem is that I have an image as a background?

A: So this is a weird bug but it seems to fix if you set your box-shadow: inset 0 0 0 0.01px. Check more here.
I hope this is what you are looking for!

.button {
    color: #add8e6;
    border: 2px solid rgb(237, 125, 194);
    border-radius: 5px;
    padding: 18px 36px;
    display: inline-block;
    font-family: "Lucida Console", Monaco, monospace;
    font-size: 14px;
    letter-spacing: 1px;
    cursor: pointer;
    -webkit-transition: ease-out 0.4s;
    -moz-transition: ease-out 0.4s;
    transition: ease-out 0.4s;
    box-shadow: inset 0 0 0 0.01px rgb(237, 125, 194);
  }

  .slide_right:hover {
    box-shadow: inset 400px 0 0 0.01px rgb(237, 125, 194);
  }
<!DOCTYPE html>

        <title>Fashion Closet</title>
        <link href="/styles/styles.css" rel="stylesheet">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

Fashion Closet

Unique look for daily routine</h22>

                    <input id="search-text" type="text" class="input" placeholder="Filter looks">
                    <select id="filter-by" class="dropdown">
                        <option value="byEdited">Sort by last edited</option>
                        <option value="byCreated">Sort by recently created</option>
                        <option value="alphabetical">Sort alphabetically</option>
                    </select>

            <button id="create-look" class="button slide_right">Create a new look</button>


text:
Q: List of count for each date I have specific scenario to show list of count for each date. Below are query and what I tried.
I need datewise count for each day using below condition. (Count less then date)
 SELECT COUNT(*)
   FROM Queues (nolock)
  WHERE InsDateTime < '2014-05-27'

Now, I need to use UNION if I need it for multiple days like below.
 SELECT COUNT(*)
   FROM Queues (nolock)
  WHERE InsDateTime < '2014-05-27'

  UNION

 SELECT COUNT(*)
   FROM Queues (nolock)
  WHERE InsDateTime < '2014-05-26'

And So on..
I need count for each day dynamically with above condition.. I am confused from where to start. As of now I am using union for multiple days to get output.

A: So, assuming that for instance you want those calculation for every day starting on May first:
SELECT  A.InsDateTime,
        B.N
FROM (  SELECT DISTINCT CONVERT(DATE,InsDateTime) InsDateTime
        FROM dbo.Queues) A
OUTER APPLY (SELECT COUNT(*) N
             FROM dbo.Queues
             WHERE InsDateTime < A.InsDateTime) B
WHERE A.InsDateTime >= '20140501'

A: select d1.dt, count()
  from queries d1
  join queries d2
    on d2.dt < d1.dt
   and d1.dt in ('2014-05-27', '2014-05-26')
 group by d1.dt
 order by d1.dt


text:
Q: Дана действительная матрица размера 6×9 . Найти среднее арифметическое наибольшего и наименьшего значений ее элементов У меня вопрос следующий: Как мне перестроить этот код так, чтобы в нем использовались map, filter и пр. функции
import random
m=int(input())
n=int(input())
matrix=[[random.randint(1,101) for j in range(n)] for i in range(m)]
print('Matrytsa')

amin = amax = matrix[0][0]

for i in range(m):
    amin = min(map (matrix[i], amin))
    amax = max(map (matrix[i], amax))

    print(matrix[i])

print((amax+amin)/2)


text:
Q: Creating MSIX using msbuild produces "doesn't have a target" error but works in Visual Studio I have three WPF applications that I am including in a MSIX package. I have a solution that contains the three applications along with shared projects and a "Windows Application Packaging Project". I can build the MSIX by Choosing Publish -> Create App Packages on the Packaging project in Visual Studio. I am choosing Sideloading with a self-signed certificate and a Release (Any CPU) option.

This produces the MSIX output as expected.
I'm now trying to do the same thing through MSBuild so that I can integrate this into our automated build system. I'm using the command:
MSBuild.exe /restore /p:AppxBundle=Never /p:UapAppxPackageBuildMode=Sideloading  /p:Configuration=Release;Platform="Any CPU" /p:AppxPackageDir=C:\temp\Output\ /p:AppxPackageSigningEnabled=false

This produces errors for the WPF applications as per below.
:\Repos\app\app.sln" (default target) (1:2) ->
"C:\Repos\app\appPackage\appPackage.wapproj" (default target) (19:6) ->
"C:\Repos\app\app\app.csproj" (publish target) (2:18) ->
  C:\Program Files\dotnet\sdk\6.0.107\Sdks\Microsoft.NET.Sdk\targets\Microsoft.PackageDependencyResolution.targets(267,5): error NETSDK1047: Assets file 'C:\Repos\app\app\obj\project.assets.json' doesn't have a target for 'net6.0-windows10.0.19041/win-x86'. Ensure that restore has run and that you have included 'net6.0-windows10.0.19041' in the TargetFrameworks for your project. You may also need to include 'win-x86' in your project's RuntimeIdentifiers. [C:\Repos\app\app\app.csproj]

Why does this work in Visual Studio, but no in MSBuild? And how can I get this to work in MSBuild?


text:
Q: Does orbital refer to a locus where the probability of finding an electron is maximum? If I want to draw a certain circle or parabola, I will need an equation from which I can plot points on a polar or cartesian co-ordinate.
If orbitals refer to locus of equipotential points where the probability of finding an electron is maximum, there must be an equation for locus from which I will be able to plot points on cartesian or polar co-ordinate.
When I draw a circle after plotting all the points, I can say that its shape is 'round.' Likewise, If I have necessary equation for plotting points for the orbitals, then I can say that s orbital is 'spherical' and p orbital is 'dumbell shape.'
So, where's the equation of drawing the locus of s orbital or p orbital?

A: Typically textbooks depict the "shape" of the orbital by taking the region within which the electron has a 90 percent chance* of being found. The probability density function can be found by solving the Schrodinger equation for the hydrogen atom, then taking the resulting wavefunction and computing its squared magnitude.
*It could be any arbitrary probability, but the textbooks I own all say 90 percent.


text:
Q: Improper Neutralization of Script-Related HTML Tags in a Web Page (Basic XSS) CWE ID 80 I run my application with VERACODE tool but I got struggling with some issues.
One of the issue which I face is Improper Neutralization of the Script-Related HTML Tags in a Web Page (Basic XSS) (CWE ID 80).
This happens in many screens in my application.
In the following particular line:
NewDivButton.Style["display"] = SearchParameters.NewDivButtonVisibility;

Does anyone have any suggestion on  how to fix this issue?

A: Welcome Manikandan. The best answer to this question would involve knowledge of the language/framework you're using if you could share that?
One thing to note, is that there are many things you could do that would make the warning "go away", but wouldn't make your app any more secure. For that reason, it's best to understand the core of the problem, and then apply the standard fix for the language/framework you're working in. If in doubt, check with a security professional.
In general, XSS is a set of issues where you (potentially) render user input as part of your output.
In this example if I send you a link that says yoursite.com?NewDivButtonVisibility=">SendYourPrivateInfoSomewhereBad();
If you click a link like this, and the site blindly inserts the script into the page, it could steal data.
The best protection is often to validate input, only allowing known-valid input through.
Another common approach is to HTML-encode the unknown value being displayed. However, more care is needed depending on where the output is rendered (e.g. if already within a script tag)
There's much more general information on this type of issue here: https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html#cross-site-scripting-prevention-cheat-sheet


text:
Q: Как из функции создать глобальную переменную или объект? Я хочу при вызове функции создать Player: TPlayer;  record или class,
но что б он оставался после завершения функции, до тех пор пока я его не уничтожу
Как мне это реализовать?

A: Создайте класс типа ТМенеджерИгроков
В классе - поле со списком клиентов-игроков
Также методы для работы (добавление клиента, удаление, и т.п.)
При старте приложения создайте объект ТМенеджерИгроков
Далее пользуйтесь его методами
При добавлении клиента - создавайте TPlayer и добавляйте пару клиент-TPlayer в список
При удалении клиента - убирайте


text:
Q: Connecting to Microsoft SQL server using Python I am trying to connect to SQL through python to run some queries on some SQL databases on Microsoft SQL server. From my research online and on this forum the most promising library seems to be pyodbc. So I have made the following code
import pyodbc
conn = pyodbc.connect(init_string="driver={SQLOLEDB}; server=+ServerName+;
database=+MSQLDatabase+; trusted_connection=true")
cursor = conn.cursor()

and get the following error
Traceback (most recent call last):
  File "C:\Users...\scrap.py", line 3, in <module>
    conn = pyodbc.connect(init_string="driver={SQLOLEDB}; server=+ServerName+; database=+MSQLDatabase+; trusted_connection=true")
pyodbc.Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')

I have looked at the folowing posts and tried changing my driver to {sql server} and have connected using ODBC links before in SAS, which is partially what my above code is based on, so don't think I need to install anything else.
pyodbc.Error: ('IM002', '[IM002] [unixODBC][Driver Manager]Data source name not found, and no default driver specified (0) (SQLDriverConnect)')
Pyodbc - "Data source name not found, and no default driver specified"
Thanks

A: Minor addition to what has been said before. You likely want to return a dataframe. This would be done as
import pypyodbc
import pandas as pd

cnxn = pypyodbc.connect("Driver={SQL Server Native Client 11.0};"
                        "Server=server_name;"
                        "Database=db_name;"
                        "uid=User;pwd=password")
df = pd.read_sql_query('select * from table', cnxn)

A: Following Python code worked for me. To check the ODBC connection, I first created a 4 line C# console application as listed below.
Python Code
import pandas as pd
import pyodbc
cnxn = pyodbc.connect("Driver={SQL Server};Server=serverName;UID=UserName;PWD=Password;Database=My_DW;")
df = pd.read_sql_query('select TOP 10 * from dbo.Table WHERE Patient_Key > 1000', cnxn)
df.head()

Calling a Stored Procedure
 dfProcResult = pd.read_sql_query('exec dbo.usp_GetPatientProfile ?', cnxn, params=['MyParam'] )

C# Program to Check ODBC Connection
    static void Main(string[] args)
    {
        string connectionString = "Driver={SQL Server};Server=serverName;UID=UserName;PWD=Password;Database=My_DW;";
        OdbcConnection cn = new OdbcConnection(connectionString);
        cn.Open();
        cn.Close();
    }

A: Try using pytds, it works throughout more complexity environment than pyodbc and more easier to setup.
I made it work on Ubuntu 18.04

Ref: https://github.com/denisenkom/pytds

Example code in documentation:
import pytds
with pytds.connect('server', 'database', 'user', 'password') as conn:
    with conn.cursor() as cur:
        cur.execute("select 1")
        cur.fetchall()

A: In data source connections between a client and server there are two general types: ODBC which uses a DRIVER and OLEDB which uses a PROVIDER. And in the programming world, it is a regular debate as to which route to go in connecting to data sources.
You are using a provider, SQLOLEDB, but specifying it as a driver. As far as I know, neither the pyodbc nor pypyodbc modules support Window OLEDB connections. However, the adodbapi does which uses the Microsoft ADO as an underlying component.
Below are both approaches for your connection parameters. Also, I string format your variables as your concatenation did not properly break quotes within string. You'll notice I double the curly braces since it is needed in connection string and string.format() also uses it.
# PROVIDER
import adodbapi
conn = adodbapi.connect("PROVIDER=SQLOLEDB;Data Source={0};Database={1}; \
       trusted_connection=yes;UID={2};PWD={3};".format(ServerName,MSQLDatabase,username,password))
cursor = conn.cursor()

# DRIVER
import pyodbc
conn = pyodbc.connect("DRIVER={{SQL Server}};SERVER={0}; database={1}; \
       trusted_connection=yes;UID={2};PWD={3}".format(ServerName,MSQLDatabase,username,password))
cursor = conn.cursor()

A: here's the one that works for me:
from sqlalchemy import create_engine
import urllib
import pandas

conn_str = (
r'Driver=ODBC Driver 13 for SQL Server;'
r'Server=DefinitelyNotProd;'
r'Database=PlayPen;'
r'Trusted_Connection=Yes;')

quoted_conn_str = urllib.parse.quote_plus(conn_str)
engine = create_engine('mssql+pyodbc:///?odbc_connect={}'.format(quoted_conn_str))
sqlcmd = """select * from information_schema.tables"""
df = pd.read_sql(sqlcmd, engine)

A: Try with pymssql: pip install pymssql
import pymssql

try:
    conn = pymssql.connect(server="host_or_ip", user="your_username", password="your_password", database="your_db")
    cursor = conn.cursor()
    cursor.execute ("SELECT @@VERSION")
    row = cursor.fetchone()
    print(f"\n\nSERVER VERSION:\n\n{row[0]}")
    cursor.close()
    conn.close()
except Exception:
    print("\nERROR: Unable to connect to the server.")
    exit(-1)

Output:
SERVER VERSION:

Microsoft SQL Server 2016 (SP2-CU14) (KB4564903) - 13.0.5830.85 (X64)
        Jul 31 2020 18:47:07
        Copyright (c) Microsoft Corporation
        Standard Edition (64-bit) on Windows Server 2012 R2 Standard 6.3 <X64> (Build 9600: ) (Hypervisor)

The connection can also be checked from the terminal, with a single line of code with sqlcmd. See syntax.
╔═════════╦═════════════════════════════════════════╗
║ Command ║               Description               ║
╠═════════╬═════════════════════════════════════════╣
║   -S    ║ [protocol:]server[instance_name][,port] ║
║   -U    ║ login_id                                ║
║   -p    ║ password                                ║
║   -Q    ║ "cmdline query" (and exit)              ║
╚═════════╩═════════════════════════════════════════╝

sqlcmd -S "host_or_ip"  -U "your_username" -p -Q "SELECT @@VERSION"

output:
Password:    your_password

--------------------------------------------------------------------------------------------------------------------------------------------------------
Microsoft SQL Server 2016 (SP2-CU14) (KB4564903) - 13.0.5830.85 (X64)
        Jul 31 2020 18:47:07
        Copyright (c) Microsoft Corporation
        Standard Edition (64-bit) on Windows Server 2012 R2 Standard 6.3 <X64> (Build 9600: ) (Hypervisor)

(1 rows affected)

Network packet size (bytes): 4096
1 xact[s]:
Clock Time (ms.): total         1  avg   1.00 (1000.00 xacts per sec.)

A: I Prefer this way ... it was much easier
http://www.pymssql.org/en/stable/pymssql_examples.html
conn = pymssql.connect("192.168.10.198", "odoo", "secret", "EFACTURA")
cursor = conn.cursor()
cursor.execute('SELECT * FROM usuario')

A: I tried to connect sql server in following ways and those worked for me.
To connect using windows authentication
import pyodbc

conn = pyodbc.connect('Driver={SQL Server};Server='+servername+';Trusted_Connection=yes;Database='+databasename+';')
cursor = conn.cursor()
cursor.execute("Select 1 as Data")

To use sql server authentication I used following code.
import pyodbc

conn = pyodbc.connect('Driver={SQL Server};Server='+servername+  ';UID='+userid+';PWD='+password+';Database='+databasename)
cursor1 = conn.cursor()
cursor1.execute("SELECT 1 AS DATA")

A: This is how I do it...
import pyodbc
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=server_name;"
                      "Database=db_name;"
                      "Trusted_Connection=yes;")

cursor = cnxn.cursor()
cursor.execute('SELECT * FROM Table')

for row in cursor:
    print('row = %r' % (row,))

Relevant resources:

*

*https://github.com/mkleehammer/pyodbc/wiki/Connecting-to-SQL-Server-from-Windows

*http://blogs.msdn.com/b/cdndevs/archive/2015/03/11/python-and-data-sql-server-as-a-data-source-for-python-applications.aspx

A: My version. Hope it helps.

import pandas.io.sql
import pyodbc
import sys

server = 'example'
db = 'NORTHWND'
db2 = 'example'

#Crear la conexión
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=' + server +
                      ';DATABASE=' + db +
                      ';DATABASE=' + db2 +
                      ';Trusted_Connection=yes')
#Query db
sql = """SELECT [EmployeeID]
      ,[LastName]
      ,[FirstName]
      ,[Title]
      ,[TitleOfCourtesy]
      ,[BirthDate]
      ,[HireDate]
      ,[Address]
      ,[City]
      ,[Region]
      ,[PostalCode]
      ,[Country]
      ,[HomePhone]
      ,[Extension]
      ,[Photo]
      ,[Notes]
      ,[ReportsTo]
      ,[PhotoPath]
  FROM [NORTHWND].[dbo].[Employees] """
data_frame = pd.read_sql(sql, conn)
data_frame

A: This is how I had done it.
import pyodbc

connection = pyodbc.connect("DRIVER={SQL Server Native Client 10.0};"

                            "SERVER=server_name;"

                            "DATABASE=database_name;"

                            "UID=user_id_of_database;"

                            "PWD=password_of_database;")

cursor = connection.cursor()

cursor.execute('SELECT * FROM Table')

Always make sure you had specified the correct Driver. You can check your Driver by following the steps given below.

*

*Open the Windows Control Panel.

*Open the Administrative Tools folder.

*Double-click Data Sources (ODBC) to open the ODBC Data Source Administrator window.

*Click the Drivers tab

A: An alternative approach would be installing Microsoft ODBC Driver 13, then replace SQLOLEDB with ODBC Driver 13 for SQL Server
Regards.

A: I found up-to-date resources here:
Microsoft | SQL Docs | Python SQL Driver
There are these two options explained including all the prerequisites needed and code examples:
Python SQL driver - pyodbc (tested & working)
Python SQL driver - pymssql


text:
Q: Pass GET variable into On Click function I'm trying to pass my Amount variable from the link to the Pay function inside the On Click, but I can't. How can I do?
Link: example.tld/index.php?amount=20
Code:
<?php $amount = $_GET['amount']; ?>
<button onclick="pay(<?php echo $amount; ?>)">Pay</button>


text:
Q: Pulseaudio Sample Rates too Different (A2DP) Issue:
I am running Raspbian (from February 2017). I have setup the Raspberry Pi to run its bluetooth as A2DP and am streaming audio to it via Amazon Echo Dot (Pandora). It runs great for a good 30 minutes then the audio playback just stops. When I go to check the /var/log/syslogs I find the following:
Errors:
Mar 24 22:12:34 raspberrypi pulseaudio[615]: [pulseaudio] module-loopback.c: Sample rates too different, not adjusting (44100 vs. 85062).
...
...
...
Mar 24 22:19:34 raspberrypi pulseaudio[615]: [pulseaudio] module-loopback.c: Sample rates too different, not adjusting (44100 vs. 462646).

Things I have tried:
I have changed the resample-method from default to trivial and the problem still persists.
I have tried searching online and can't seem to find any similar issues, at least none with any information in what is causing it and none with anything close to resembling a solution.
My Conclusion:
To me it looks as though the sample rate from the Echo Dot seems to continue to grow, and pulseaudio can handle it up until the new rate hits the (base rate * x), in which it becomes "too different" and won't adjust to the new rate.
Questions:
What can be done? Is there something I can disable that will allow for playback? Is there anyway to reset the incoming rate to a more manageable number once it gets too high?
Band-aid Fixes:
I can manually disconnect the Amazon Echo Dot, and reconnect the dot and audio playback will begin again and play normally for another 20-30 minutes until the issue begins again.
Update:
I have tried setting the resampling rate again to trivial this time I receive the following error:
Mar 25 02:11:45 raspberrypi pulseaudio[595]: [bluetooth] module-bluez5-device.c: SBC decoding error (-2)

I am suspecting this is "progress", but what can be about this specific error?


text:
Q: How to find text in data file and calculate average using perl I would like to replace a grep | awk | perl command with a pure perl solution to make it quicker and simpler to run.
I want to match each line in input.txt with a data.txt file and calculate the average of the values with the matched ID names and numbers.
The input.txt contains 1 column of ID numbers:
FBgn0260798
FBgn0040007
FBgn0046692

I would like to match each ID number with it's corresponding ID names and associated value. Here's an example of data.txt where column 1 is the ID number, columns 2 and 3 are ID name1 and ID name2 and column 3 contains the values I want to calculate the average.
FBgn0260798 CG17665 CG17665 21.4497
FBgn0040007 Gprk1   CG40129 22.4236
FBgn0046692 RpL38   CG18001 1182.88

So far I used grep and awk to produce an output file containing the corresponding values for matched ID numbers and values and then used that output file to calculate the counts and averages using the following commands:
# First part using grep | awk
exec < input.txt
while read line
    do
            grep -w $line data.txt | cut -f1,2,3,4 | awk '{print $1,$2,$3,$4} ' >> output.txt
    done
 # Second part with perl

open my $input, '<', "output_1.txt" or die; ## the output file is from the first part and has the same layout as the data.txt file

my $total = 0;
my $count = 0;

while (<$input>) {

    my ($name, $id1, $id2, $value) = split;
    $total += $value;
    $count += 1;

}

print "The total is $total\n";
print "The count is $count\n";
print "The average is ", $total / $count, "\n";

Both parts work OK but I would like to make it simplify it by running just one script. I've been trying to find a quicker way of running the whole lot together in perl but after several hours of reading, I am totally stuck on how to do it. I've been playing around with hashes, arrays, if and elsif statements without zero success. If anyone has suggestions etc, that would be great.
Thanks,
Harriet

A: If I understand you, you have a data file that contains the name of each line and the value for that line. The other two IDs are not important.
You will use a new file called an input file that will contain matching names as found in the data file. These are the values you want to average.
The fastest way is to create a hash that is keyed by the names and the values will be the value for that name in the data file. Because this is a hash, you can quickly locate the corresponding value. This is much faster than grep`ing the same array over and over again.
This first part will read in the data.txt file and store the name and value in a hash keyed by the name.
use strict;
use warnings;
use autodie;   # This way, you don't have to check if you can't open the file
use feature qw(say);

use constant {
    INPUT_NAME  => "input.txt",
    DATA_FILE   => "data.txt",
};

#
# Read in data.txt and get the values and keys
#
open my $data_fh, "<", DATA_FILE;
my %ids;
while ( my $line = <$data_fh> ) {
    chomp $line;
    my ($name, $id1, $id2, $value) = split /\s+/, $line;
    $ids{$name} = $value;
}
close $data_fh;

Now, that you have this hash, it's easy to read through the input.txt file and locate the matching name in the data.txt file:
open $input_fh, "<", INPUT_FILE;
my $count = 0;
my $total = 0;
while ( my $name = <$input_fh> ) {
    chomp $name;
    if ( not defined $ids{$name} ) {
         die qq(Cannot find matching id "$name" in data file\n);
    }
    $total += $ids{$name};
    $count += 1;
}
close $input_fh;
say "Average = " $total / $count;

You read through each file once. I am assuming that you only have a single instance of each name in each file.


text:
Q: HTTPS Prerequiste for Button Click I am using angular to make a user profile page that I only want to be accessible if connected using HTTPS.

Please access this page through SSL (https) to change your password.

        <button type="button" class="btn btn-lg btn-danger" ng-click="openPasswordModal()">Change Password</button>

What can I do to enforce that the button cannot be accessed except when the page is loaded in HTTPS?
Thanks.

A: From my understanding, that's not how https works.. Pretty sure your web server needs to be configured to use SSL, it's not something the user has control over when visiting your site. If you're using IIS, see: http://support.microsoft.com/kb/324069. Otherwise try searching for "configuring https" for whatever web server you're using (IIS, Apache, etc.)
To answer your question about how to disable a button, you can use the ng-disabled directive. See https://docs.angularjs.org/api/ng/directive/ngDisabled for more info.

A: You can enforce this in the client looking for https:// in the url field and redirect the user if he/she is using http://.
However the above is not recommended. You can always tamper with client-side scripts and disable such features.
Enforce this using apache/nginx or whatever webserver that you use.


text:
Q: SmartyException 0():Missing '$template' parameter with Prestashop I am using PrestaShop for my online store
https://www.fyndpris.co.uk/
The desktop version is working perfectly but i have a problem with AMP NOT in the homepage but when i am trying to access some products like this link :
https://www.fyndpris.co.uk/mobile/product/8282714-fyndpris-children-s-loft-bed-frame-with-slide-ladder-pinewood-97x208-cm
 (1/1) SmartyException
0():Missing '$template' parameter

in smarty_internal_templatebase.php line 177
at Smarty_Internal_TemplateBase->_execute(null, null, 'layouts/layout-full-width.tpl', null, 0)
in smarty_internal_templatebase.php line 116
at Smarty_Internal_TemplateBase->fetch(null, null, 'layouts/layout-full-width.tpl', null, false, true, false)
in SmartyDev.php line 40
at SmartyDev->fetch(null, null, 'layouts/layout-full-width.tpl')
in FrontController.php line 683
at FrontControllerCore->smartyOutputContent(null)
in FrontController.php line 667
at FrontControllerCore->display()
in Controller.php line 312
at ControllerCore->run()
in Dispatcher.php line 515
at DispatcherCore->dispatch()
in index.php line 28

Note that i have reviewed these two question about the same Error :
1- question1
but i can'y find out a solution for my problem
[4]: 'SmartyException' with message 'Missing template name' in Smarty .
I will disable the Amp for now to avoid make the user face the Error before i find the solution
Knowing that i have posted many question at PrestaShop community but unfortunately there was no answer
I hope i described my problem correctly

A: I have the same error, using a frontcontroller for a cron rutine... so I wrote again the Controller keeping the structure as the documentation
"Minimum controller example" and "Using a front controller as a cron task" in
https://devdocs.prestashop.com/1.7/modules/concepts/controllers/front-controllers/
so, check structure maybe this could solve the problem

A: Refresh the smarty cache in Presta performance settings