text:
Q: After reboot host goes into maintenance mode as I've the remote filesystems on LVM stack created over iSCSI LUNs - RHEL 7.x On RHEL 7.x I observe that the remote filesystems (SAN) does not allow host to come up after reboot. It enters maintenance mode and I've to comment out the entries in /etc/fstab to bring the host up and running.
I've few mount points /etc/fstab created over LVM stack which in turn is laid on iSCSI LUNs.
I guess this is due to systemd introduced from RHEL 7.x onwards. However I'm unable to get remote filesystems mounted after local filesystems. Let me know how/where to specify this ordering?

A: Got this working by having _netdev as one of the mount options.
Also setting use_lvmetad in /etc/lvm/lvm.conf to 1 will bring the VGs/LVs online and mounts work without any issues. I do not observe the host going into
maintenance mode after reboot.


text:
Q: in Angular6 service is not loading
i just started learning angular everything was going good as soon before i added service(dish.service.ts) to my project.
this is the error
 ./src/app/services/dish.service.ts
Module parse failed: Unexpected token (15:13)
You may need an appropriate loader to handle this file type.
dish.service.ts
import { Injectable } from '@angular/core';
import { Dish } from '../shared/dish';
import { Dishes } from '../shared/dishes';

@Injectable({
  providedIn: 'root'
})
export class DishService {

  constructor() {
    getDishes():Dish[]{
        return DISHES;
    }
  }
}

app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platformbrowser/animations';
import { MatToolbarModule } from '@angular/material/toolbar';
import { FlexLayoutModule } from '@angular/flex-layout';
import { MatListModule } from '@angular/material/list';

import { MatGridListModule } from '@angular/material/grid-list';
import { MatCardModule } from '@angular/material/card';
import { MatButtonModule } from '@angular/material/button';

import { AppComponent } from './app.component';
import 'hammerjs';
import { MenuComponent } from './menu/menu.component';
import { DishDetailsComponent } from './dish-details/dish-details.component';
import { DishService } from './services/dish.service';

@NgModule({
  declarations: [
    AppComponent,
    MenuComponent,
    DishDetailsComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    MatToolbarModule,
    MatListModule,
    MatGridListModule,
    MatCardModule,
   MatButtonModule,
    FlexLayoutModule
  ],
  providers: [ DishService ],
  bootstrap: [AppComponent]
})
export class AppModule { }

A: First of all no need to register services in app.module.ts -> providers:[] because you are using angular 6 and it's have features now like providedIn: 'root'.
Second you added your function in getDishes() in constructor, so remove from there and add it after constructor like,
@Injectable({
   providedIn: 'root'
})
export class DishService {

   constructor() {}

   getDishes(): Dish[]{
     return DISHES;
   }
}

A: There are multiple ways in which you can use your service though, depends on your requirement
how you want to handle

*

*Put service in app.module.ts
By adding the service in the providers array it means in your application you want to maintain a single instance of the service and you want to inject one service into another
eg:
//import the service
providers: [yourseriviceName]
//this would create a single instance also don't added
@Injectable({providedIn: 'root'})
// as it is not need .

*If you want to import in only in your component and want multiple instances of the service

service.ts:
export class dummyService {
    constructor(parameters) {

    }

    yourMethod(){
        return //Something
    }
}

component.ts
import your service as well
@Component({
    selector: 'dummy',
    styleUrls: ['dummy.component.sass'],
    templateUrl: 'dummy.component.html',
    providers:[dummyService]
})

export class yourComponentName {
    constructor(private dummyservice:dummyService) {
    }

    //Acces your service via
    this.dummyservice.yourMethod()
}

*When you want to inject one service in another service:

//import injectable from angular core
//import your service which you want to inject

//Note ensure you import injectable first and then your service
@injectable()
export class dummyService {
    constructor(parameters) {

    }

    yourMethod(){
        return //Something
    }
}

Coming to your problem it is problem with your method it is in the constructor, to give you a better overview when you create a class in typescript the constructor is executed first, and then other angular lifecycle hooks
so please refer to my second point and keep your method outside of the constructor and access it as I have shown in component.ts.

redpajama_set_name: RedPajamaStackExchange


text:
Q: what is the easy/minimal way to remotely(over the Internet) connect a Ubuntu 20.04 system from another Ubuntu 20.04 system? what is the easy/minimal way to remotely(over the Internet) connect a Ubuntu 20.04 system from another Ubuntu 20.04 system? I have tried team-viewer any-desk in the past.
But is there a native way to remotely(over the Internet) connect a Ubuntu 20.04 to another Ubuntu 20.04 within the Ubuntu's applications/sources/out-of-the-box?
Looking for a step by step practical approach..

A: ssh
I think it is easy to use ssh. Install openssh-server in [at least] one of the computers, and log in with ssh from the other computer or transfer files with sftp or simply via the file browser.
Several users have found the following link useful in order to run graphical programs via ssh -X,
What is the simplest way to have remote GUI access to Ubuntu 16.04 "server" from Ubuntu 16.04 "desktop"?

A: On the system you want to connect to:

*

*install "vino" package. The entry for "Desktop sharing" should appear somewhere in the menu.

*You have to set some configuration parameters for vino-server, but probably the only way to do it is via dconf-editor (the GUI to set these parameters has been removed long ago), so you have to install it too if it isn't already installed. In dconf, goto /org/gnome/desktop/remote-access and:
a) set authentication-methods to ['vnc']
b) set prompt-enabled to false
c) set require-encryption to false
d) set vnc-password to base64 encoded value of the password you want to use to connect

*Start vino-server by clicking the desktop sharing entry from the menu.

On the other system, use any VNC client (eg. Remmina, which is installed by default) to connect.


text:
Q: Problem with adding SQL paramerters from data access Layer in c# First I am giving examples of two methods
public static List<FormGridEntity> GetAllCandidatesByProgram(string programShortName)
    {
        List<FormGridEntity> formGridEntities = null;
        try
        {
            string cmd = SELECT + " WHERE " + CANDIDATE_PROGRAM_PA + " = " +       CANDIDATE_PROGRAM;`enter code here`
            //string cmd = SELECT

            DAOParameters dps = new DAOParameters();
            dps.AddParameter(CANDIDATE_PROGRAM_PA, programShortName);
            List<SqlParameter> ps = Common.Methods.GetSQLParameters(dps);
            SqlDataReader dataReader = QueryHandler.ExecuteSelectQuery(cmd, ps);
            formGridEntities = Maps(dataReader);
            dataReader.Close();
        }

        catch (Exception exception)
        {
            throw exception;
        }
        return formGridEntities;
    }

and another method is
public static List<FormGridEntity> GetAllCandidatesByDates(DateTime initialDate,DateTime finalDate)
    {
        List<FormGridEntity> formGridEntities = null;
        try
        {
            string cmd = SELECT + " WHERE " + FORM_SUBMISSION_DATE_PA + " BETWEEN " + initialDate + " AND " + finalDate;
            //string cmd = SELECT

            DAOParameters dps = new DAOParameters();
            //What will I do here? since
            **//dps.AddParameter(FORM_SUBMISSION_DATE_PA, initialDate);
            //dps.AddParameter(FORM_SUBMISSION_DATE_PA, finalDate);**
            List<SqlParameter> ps = Common.Methods.GetSQLParameters(dps);
            SqlDataReader dataReader = QueryHandler.ExecuteSelectQuery(cmd, ps);
            formGridEntities = Maps(dataReader);
            dataReader.Close();
        }

        catch (Exception exception)
        {
            throw exception;
        }
        return formGridEntities;
    }

I have commentd out
Here the caps terms are all constants that above in the class like
private const string FORM_PURCHASING_DATE = "DateOfPurchase";
private const string FORM_PURCHASING_DATE_PA = "@DateOfPurchase"
private const string FORM_SUBMISSION_DATE = "DateOfSubmission";
private const string FORM_SUBMISSION_DATE_PA = "@DateOfSubmission";

the SELECT is also defined correctly. I am using this Layer perfectly. But now a scenario ocurred where I am getting confused what to do. So far I have been adding values with parameter that has one to one relationship. But, in my second method, I am using the between operator where two values is referring to one parameter, what will I write here to make the things working properly. I have commented out the particular region that I want to modify. please help me if possible. Here is the method  GetSQLParameters
    public static List GetSQLParameters(DAOParameters dps)
        {
            List parameters = new List();
        foreach (DictionaryEntry de in dps.hs)
        {
            SqlParameter p = new SqlParameter();
            p.ParameterName = de.Key.ToString();
            if (de.Value.ToString() == Convert.ToString(0))
            {
                p.Value = DBNull.Value;
            }
            else
            {
                p.Value = de.Value;
            }

            parameters.Add(p);
        }

        return parameters;

A: In GetAllCandidatesByDates(), perhaps you should have:
FORM_SUBMISSION_DATE + "BETWEEN @initialDate AND @finalDate"

And then bind initialDate to "@initialDate" parameter and finalDate to "@finalDate" parameter? The way you have it now, you are not using parameters for these dates, but instead converting concrete DateTime values to strings and concatenating these strings directly into your final SQL.


text:
Q: How to freeze layer parameters in Flux.jl I am currently working on a transfer learning problem so I would like to freeze most of my layers such that the model is not re-trained, and only the final layer's weights are modified. How can I choose which layers to freeze with Flux.jl?

A: Flux provides a simple interface to do this which is to only pass in the layers you want to be modified to the Flux.params() function as shown below:
m = Chain(
      Dense(784, 64, relu),
      Dense(64, 64, relu),
      Dense(32, 10)
    )

ps = Flux.params(m[3:end])

In the above example, we chose to only update the final Dense layer (which is commonly what you do in a transfer learning example).
You can see a full example with more build up in the Flux.jl tutorial on transfer learning: https://fluxml.ai/tutorials/2020/10/18/transfer-learning.html


text:
Q: static-link-runtime-shared-libraries in mxmlc I use -static-link-runtime-shared-libraries=false for compiling my app and when I upload the new swf I periodically receive an Error #2046. If -static-link-runtime-shared-libraries=true used it works OK. How do I handle with that?
I placed all the swz files into the same place as my app:
$ ls -l gae/static/swf/
total 4452
-rwxr-xr-x 1 soid soid  490561 2011-05-07 01:57 datavisualization_4.1.0.16076.swf
-rwxr-xr-x 1 soid soid  291306 2011-05-07 01:57 datavisualization_4.1.0.16076.swz
-rwxr-xr-x 1 soid soid 1045994 2011-05-07 01:57 framework_4.1.0.16076.swf
-rwxr-xr-x 1 soid soid  627104 2011-05-07 01:57 framework_4.1.0.16076.swz
-rw-r--r-- 1 soid soid  116596 2010-12-17 01:42 mapeditor.swf
-rwxr-xr-x 1 soid soid  150731 2011-05-07 01:57 osmf_flex.4.0.0.13495.swf
-rwxr-xr-x 1 soid soid   98079 2011-05-07 01:57 osmf_flex.4.0.0.13495.swz
-rwxr-xr-x 1 soid soid  207521 2011-05-07 01:57 rpc_4.1.0.16076.swf
-rwxr-xr-x 1 soid soid  131927 2011-05-07 01:57 rpc_4.1.0.16076.swz
-rwxr-xr-x 1 soid soid  503167 2011-05-07 01:57 spark_4.1.0.16076.swf
-rwxr-xr-x 1 soid soid  319302 2011-05-07 01:57 spark_4.1.0.16076.swz
-rwxr-xr-x 1 soid soid   69851 2011-05-07 01:57 sparkskins_4.1.0.16076.swf
-rwxr-xr-x 1 soid soid   54538 2011-05-07 01:57 sparkskins_4.1.0.16076.swz
-rwxr-xr-x 1 soid soid  263124 2011-05-07 01:57 textLayout_1.1.0.604.swf
-rwxr-xr-x 1 soid soid  156998 2011-05-07 01:57 textLayout_1.1.0.604.swz

I'm watching my server logs but I don't see any requests to these files. What's wrong with that?

A: I did a quick search and found this article in the adobe forums: http://forums.adobe.com/message/3501406
The author seems to have had similar inconsistent results as you and it had to do with loading RSL's - flex framework ones that you have listed in the question.
In his problem, IIS was blocking .swz files altogether.  After changing the IIS configuration, the problems went away.


text:
Q: flattening nested Json in pyspark, where each array type would be a separate data frame Taking this schema(json dataframe) as an example:
 root
     |-- abstract: string (nullable = true)
     |-- adx_keywords: string (nullable = true)
     |-- asset_id: long (nullable = true)
     |-- byline: string (nullable = true)
     |-- column: string (nullable = true)
     |-- des_facet: array (nullable = true)
     |    |-- element: string (containsNull = true)
     |-- eta_id: long (nullable = true)
     |-- geo_facet: array (nullable = true)
     |    |-- element: string (containsNull = true)
     |-- id: long (nullable = true)
     |-- media: array (nullable = true)
     |    |-- element: struct (containsNull = true)
     |    |    |-- approved_for_syndication: long (nullable = true)
     |    |    |-- caption: string (nullable = true)
     |    |    |-- copyright: string (nullable = true)
     |    |    |-- **media-metadata**: array (nullable = true)
     |    |    |    |-- element: struct (containsNull = true)
     |    |    |    |    |-- format: string (nullable = true)
     |    |    |    |    |-- height: long (nullable = true)
     |    |    |    |    |-- url: string (nullable = true)
     |    |    |    |    |-- width: long (nullable = true)
     |    |    |-- subtype: string (nullable = true)
     |    |    |-- type: string (nullable = true)
     |-- nytdsection: string (nullable = true)
     |-- org_facet: array (nullable = true)
     |    |-- element: string (containsNull = true)
     |-- per_facet: array (nullable = true)
     |    |-- element: string (containsNull = true)
     |-- published_date: string (nullable = true)
     |-- section: string (nullable = true)

here I would like to get each array type as separate data frame. I am able to segregate the first levels such as des_facet,geo_facet and media and put it into  individual data-frames but unable to do the same for second level for eg:  media-metadata in media(array type). A solution to extract nested arrays as an individual dataframe would be helfull
Thanks in advance


text:
Q: How to merge multiple datagridview column into one in windows forms app which contains some dynamic controls? I have a problem of merging multiple columns of data gridview into one. My data gridview contains some dynamic controls also added based on some conditions (e.g. Drop down and Textbox).
I am using windows forms and I want to a achieve a layout that looks like this:

Note that there is a vertical stack of controls in one cell of the grid.
How can I achieve that?
"Really_Long_file_name_of_the_Attachment.doc" is a non-editable text box.
FORM_TYPE_DROPDOWN is a dropdown with about 100 different selections.  Each selection can be quite wide (maybe 60 characters)
"Claims description if claims is selected" is a text box that can accept up to 60 characters of input.  It is an optional field.
"Message about the attachment" is a placeholder for an error or warning message if there is something wrong with the file.
The problem Dipak is trying to solve is getting those 4 controls in one cell of a grid.


text:
Q: Displaying SQL results in vb.net I am using SQL in vb.net. I believe I have successfully connected to the database and at the moment I am able to display the information I have received in a message box with:
    sql = "SELECT ID FROM LoginInformation WHERE Username = '" & txt_Username.Text & "' AND Password = '" & txt_Password.Text & "'"
    DataSets = database.sqlSelect(sql)
    MsgBox(DataSets.Tables("LoginInformation").Rows(0).Item(0))

However, I do not want it to show the same cell of the database every time I use this code and I am unsure as to how to display what I am actually looking for with the SQL statement. From the above code, I have tried to find the 'ID' but it will always display the cell located at (0,0)
Any help will be appreciated!
Thanks.

A: You should loop throw this DataSets.Tables("LoginInformation") to get all the rows and columns.
See this example quoted from here:
Private Sub PrintRows(ByVal dataSet As DataSet)
   Dim table As DataTable
   Dim row As DataRow
   Dim column As DataColumn
   For Each table in dataSet.Tables
      For Each row In table.Rows
         For Each column in table.Columns
            Console.WriteLine(row(column))
         Next column
      Next row
   Next table
End Sub


text:
Q: Pattern Matching with SQL Like for a range of characters Is there a way to use Pattern Matching with SQL LIKE, to match a variable number of characters with an upper limit?
For example, I have one column which can have "correct values" of 2-10 numbers, anything more than 10 and less than 2 is incorrect.

A: If you really want to use like you can do:
where col like '__' or col_like '___' or . . .

or:
where col like '__%'  and        -- at least two characters
      col not like '_________%'  -- not 9 characters

The more typical method would be:
where len(col) between 2 and 10

If you want to ensure they are numbers:
where len(col) between 2 and 10 and
      col not like '%[^0-9]%'

A: You can use Regex.
SELECT * FROM mytable WHERE mycol LIKE '%[0-9]{2,10}%';

should do it (that's off the top of my head, so double-check!

A: You could make a function to do this the long way of inspecting each character like below:
DECLARE @TempField varchar(max)= '1v3Abc567'

DECLARE @FieldLength int = LEN(@TempField)
DECLARE @CountNumeric int = 0

WHILE @FieldLength > 0
BEGIN
SELECT @CountNumeric = @CountNumeric +  ISNUMERIC( SUBSTRING (@TempField,@FieldLength,1))
SET @FieldLength = @FieldLength - 1
END

SELECT @CountNumeric NumericCount


text:
Q: Как сделать чтобы результат выводился в многострочном текстовом поле? #1.6 Разложить целое число на простые множители.
#Вывести на экран все простые множители (в порядке возрастания) и их порядки.
from tkinter import *

def func(event):

    N = int(ent.get())
    F = N
    for i in range(2, F):
        if F%i==0:
            d=0
            for B in range(2, i):
                if i % B ==0:
                    d+= 1
            if d == 0:
                por = 0
                while N % i ==0:
                    por += 1
                    N=N//i

                #print("делитель",i,"порядок",por)
                s=f"делитель {i}, порядок {por}"

                tex = Text(root,width=40,
                           font="Verdana 12",
                           wrap=WORD)

                #tex.insert(1.0, s)

root = Tk()   #главный экран

root.title('1.6 Разложение числа на простые множители')#название главного окна
root.geometry('400x175')

lab1 =  Label(root, text = 'Разложить целое число на простые множители. \n Вывести на экран все простые множители \n (в порядке возрастания) и их порядки.', font = 'Arial 12')

lab2 = Label(root, text = 'Введите n:', font = 'Arial 12')
ent = Entry(root)

but = Button(root)
but["text"]="Разложить"
but.bind('<Button-1>', func)

tex = Text(width = 15, height = 5, font = 'Arial 12')

lab1.pack()
lab2.pack()
ent.pack()
but.pack()
tex.pack()
root.mainloop()


text:
Q: Как задать ширину через высоту? Условно у меня есть объект, в котором ширина стоит match parent, и я хочу чтобы высота была width/2, или  что-то подобное, как такое можно сделать?

A: строка app:layout_constraintDimensionRatio="2:1" задает ширину в две высоты

<View
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:layout_constraintDimensionRatio="2:1" />


text:
Q: How to create bounding box using css? I'm new in vue.js and I want to ask can I create bounding box to any element? This bounding box seems like view box in svg
Example that I made this checkbox like this
checkbox
And here are the code to make the box of the checkbox
/* checkbox aspect */
    [type="checkbox"]:not(:checked) + label:before,
    [type="checkbox"]:checked + label:before {
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        width: 1.4em;
        height: 1.4em;
        border: 1px solid #aaa;
        background: #FFF;
        border-radius: .2em;
        box-shadow: inset 0 1px 3px rgba(0,0,0, .1), 0 0 0 rgba(203, 34, 237, .2);
        -webkit-transition: all .275s;
                transition: all .275s;
    }

    /* checked mark aspect */
    [type="checkbox"]:not(:checked) + label:after,
    [type="checkbox"]:checked + label:after {
        content: '✕';
        position: absolute;
        top: .525em;
        left: .18em;
        font-size: 1.375em;
        color: #CB22ED;
        line-height: 0;
        -webkit-transition: all .2s;
                transition: all .2s;
    }

And what I want to do is create bounding box 32px for this checkbox, this bounding box should be similar with viewbox in svg
You can see the icon grid and rules here. Let's assume the centerpoint is where the checkbox should be, and then they have bounding box (blue rectangle).

A: Ok here is hopefully something that will at least set you on your way:
If you have a wrapper object, you can put the element of your choice inside and together an "overlay" element:

I am a content

Now with CSS only you can position the contents inside like a stack where the overlay is the top-most element. To do so you can use the position property.
I've used flex for the example just to position stuff better. I also gave the wrapper a fixed size to better illustrate the idea but in theory it could be left out (in which case it would grow as long as the page due to the child's 100% width... if the parent's width is set it would grow to 100% of it)
div.wrapper{
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  width: 300px;
  height: 300px;
}

div.overlay{
  position:absolute;
  width: 100%;
  height: 100%;

}

div.overlay:hover{
  background-color: #0000FFAA; /*Transparency is controlled by the last two hex-numbers (AA in this case)*/
}

div.content{
  background-color: red;
}

When you hover with the mouse it will show the overlay (due to the hover rule) but if you need you can control this with a Vue property or something and just hide/show the overlay depending on how the property is set.
You can see the result in this on this jsfiddle: https://jsfiddle.net/r4tfumqe/3/


text:
Q: Stop Test suite Execution python selenium Given this test suite :
import unittest

class unittestDex(unittest.TestCase):

    def test_page1(self):
       pass

    def test_page2(self):
       pass

    def test_page3_isCritical(self):
       #I am passing isCritical variable as boolean, this will be received after the test is executed, true/false
       if isCritical == True:
          #stop the whole execution, test_page4 shoudn't run anymore

    def test_page4(self):
       pass

    @staticmethod
    def main():
        suite = unittest.TestSuite()
        suite.addTest(unittestDex(metname='test_page1')
        suite.addTest(unittestDex(metname='test_page2')
        suite.addTest(unittestDex(metname='test_page3')
        suite.addTest(unittestDex(metname='test_page4')
        unittest.TextTestRunner(verbosity=2).run(suite)

if __name__ == "__main__":
main()

Is there a way to stop the suite run somehow if  the isCritical condition is met?
Basically i'm asking if anybody found a way to stop a test suite run.
This solution dosen't really work for me because it somehow merges all tests together and runs as a unit and i dont want that :
Tried pytest.exit('Test suit exited manually') and raise Exception  but the tests dosen't stop from executing, the next test method starts immediately after

A: You can use pytest -x to stop test suite after first  failure.
value can be configured using --maxfail=num where num is the number of failure


text:
Q: Manipulate dynamic array of pointers to 2 array I'm trying to init the value of the array inside the function but i'm really struggling with it.
The following code gives me a EXC_BAD_ACCESS (code=1, address=0x0) error.
At the end I want an array like [piecesNumber][10][10] where pieces number is 12.
MAX_SIZE is just a define = 10.
int main() {

    int (*pieces) [MAX_SIZE][MAX_SIZE] = NULL;

    createPieces(&pieces);

    for (int i = 0; i < 12; ++i) {
        for (int x = 0; x < MAX_SIZE; ++x) {
            for (int y = 0; y < MAX_SIZE; ++y) {
                printf("%d",pieces[i][x][y]);
            }
            printf("\n");
        }
    }

    return 0;
}

void createPieces(int (**pieces)[MAX_SIZE][MAX_SIZE]){

    *pieces = malloc(sizeof(int[MAX_SIZE][MAX_SIZE])*piecesNumber()); //piecesNumber = 12

    for (int i = 0; i < 12; i++) {
        for (int x = 0; x < MAX_SIZE; x++) {
            for (int y = 0; y < MAX_SIZE; y++) {
                *pieces[i][x][y] = 1;
            }
        }
    }

}

Thank you very much for you're help I'm trying to solve this since yesterday morning :(

A: The problem is caused by unintended grouping.  The following:
*pieces[i][x][y] = 1;

should be:
(*pieces)[i][x][y] = 1;

Without the parentheses, the * operator is only applied after the indexing, which clearly won't work.


text:
Q: Convert docx to pdf using PHP I am currently generating multiple .docx files using PHPWord. I need to find a way to combine these docx files and save them as 1 pdf file. Is there a way that this can be done?

A: Open the generated docx with PHPDOCX http://www.phpdocx.com/
    require_once 'phpdocx_pro/classes/TransformDoc.inc';
    $docx = new TransformDoc();
    $docx->setStrFile('document.docx');
    $docx->generateXHTML();
    $html = $docx->getStrXHTML();

Also, you can export the docx to PDF with
    $docx->generatePDF();

Note this is not a free library

A:   /**
   * return the pdf stream as a string returned from the function
   */
  function  output($debug = false) {
  ...
  }

so just write the result of 'generatePDF()' to a file.
for example:
$content = $docx->generatePDF();
$myfile = fopen("newfile.pdf", "w");
fwrite($myfile, $content);
fclose($myfile);


text:
Q: ADO Release IIS Web App Manage Task Physical Path as an expression How do I specify the physical path as an expression with a variable like release-n when managing a virtual application in an ADO IIS Web App Manage task?
We're just getting started with ADO Releases to IIS servers. We have IIS Web App Manage and Deployment tasks working, but only to a static physical path on the server.
I would like to store the new releases in versioned directories, and have the virtual application updated to point to the version being deployed.
For example
  Default Web Site
       /card-poc     <-- web application stored outside of wwwroot
           /release-1
           /release-2
           ...
           /release-n   <-- IIS virtual application physical path is pointed to here

So in an ADO Release IIS Web App Manage task, how do I specify the physical path as an expression with a variable like release-n?
I've tried d:\IIS_VDs\CARD-poc\Release-$(rev:r)\ to get the release name, but I get the error
The given path's format is not supported.
The expected outcome is that the directory would be created, the virtual application would be altered to point to the new directory, and then the subsequent IIS Web App Deploy task would copy the files to the new dir. The goal is to allow a server operator to roll back an application to a prior version without knowledge of or access to to ADO, Version Control, or really anything except the IIS server.

A: I tested $(rev:r) and got the same error as you. I think the problem is getting the value of the $(rev:r) variable. I try to Write-Host "$(rev:r)" in the powershell task, but the task cannot get the value of $(rev:r).  According to this ticket , it seems $(rev:r) is a special variable format that only works in the Number field in the editor.

As workaround, you can try to use Release.ReleaseName predefined variable.
Release.ReleaseName : The name of the current release. Example: Release-47


text:
Q: Generating a sequence in R I am working with a list in R that looks like this
[1] 0 0 4 4 0 4 0

now suppose that I want to generate a list of numbers corresponding to this list like this
[[1]]
[1] 1 1

[[2]]
[1] 2 2

[[3]]
[1] 3 6

[[4]]
[1] 7 10

[[5]]
[1] 11 11

[[6]]
[1] 12 15

[[7]]
[1] 16 16

So in other words, the first list gives the groups of a list of a sequence of numbers from 1 to 16 and the second list gives the start and end of each group.
This is probably easier to see if you consider the sequence
1 2 3-6 7-10 11 12-15 16
Is there an easy way to do this?  I think I could do it using some sort of global index and lapply but I wanted to see if there were an easier way.

A: Here's one way
# alternate input suggested by @MichaelChirico
d = c(0,0,3,3,0,3,0)

# my preferred approach
library(data.table) # version 1.9.5+
Map(c,
  seq_along(d)+shift(cumsum(d), type="lag", fill=0),
  seq_along(d)+cumsum(d)
)

A similar variation by @akrun:
# alternate input, starting from OP's
d2 = c(0, 0, 4, 4, 0, 4, 0)
d2 = replace( d2, !d2, 1)

# @akrun's answer
Map(c, cumsum(d2)-d2+1, cumsum(d2))

And some more:
# my original answer
start = c(1,head(cumsum(d+1)+1,-1))
Map(c, start, start + d)

# another way
s = sequence(d+1)
Map(c, seq_along(s)[s==1], seq_along(s)[c(diff(s) < 1, TRUE)] )

A: Here's a slightly different approach:
x <-  c(0,0,3,3,0,3,0)

f <- function(x) {
    ee <- split(seq_len(sum(x+1)), rep.int(seq_along(x), x+1))
    lapply(ee, range)
}
f(x)

A: Here's a function that'll do it, no way near as elegant as @Frank's answer:
mygenerator <- function(vec){
  counter <- 1
  outlist <- list()
  for(i in 1:length(vec)){
    if(vec[i] == 0){
      outlist[[i]] <- c(counter, counter)
      counter <- counter + 1
    } else {
      outlist[[i]] <- c(counter, counter + vec[i] - 1)
      counter <- counter + vec[i]
    }
  }
  outlist
}

mygenerator(c(0, 0, 4, 4, 0, 4, 0))

[[1]]
[1] 1 1

[[2]]
[1] 2 2

[[3]]
[1] 3 6

[[4]]
[1]  7 10

[[5]]
[1] 11 11

[[6]]
[1] 12 15

[[7]]
[1] 16 16


text:
Q: Doorkeeper Authentication from Rails GraphQL I'm trying to provide a "sign in" for GraphQL queries in a Rails (4.2.10) app. The "user" and "password" fields are being passed in. In my mutations.rb, I have:
field :signin, !types.Boolean do
  argument :user, !types.String
  argument :password, !types.String
  resolve -> (_, args, _) {
     #what here?
  }
end

Some documentation (out of date?) suggests:
Doorkeeper.authenticate args

This gets me a "undefined method `authorization'" in my tests, which I assume means I'm missing a callback somewhere. I've dug down but not been able to figure out what I need.
I've also tried
Doorkeeper::Application.by_uid_and_secret args.user, args.password

and this seems to return nil.

A: It seems like you're trying to build a signin mutation to take the OAuth credentials. This seems like a bad idea. OAuth is a well-established set of processes that API clients know how to follow. The OAuth Client Credentials flow process already includes a way to pass credentials to the OAuth server and get back an access token.
That access token should be used (as part of the value in an Authorization header for example) to authenticate subsequent GraphQL API calls.
So instead of implementing a mutation that replaces the OAuth flow, add an OAuth implementation to your API consumer, and enable the Client Credentials flow in Doorkeeper.


text:
Q: Protecting servo drive outputs from inductive loads. Can anyone please help with the following. I am in the process of connecting a Schneider Electric Servo Drive for a Cnc project.
I want to wire a fault output from one of the 5 drive outputs. (Do1-Do5).
The manual says" Use an appropriate external protective circuit or device to reduce the risk of inductive direct current load damage. "
The output will simply be disconnecting the enable to the drive if a fault is detected within the drive. I am not switching any other load.
The question is do I need to protect this circuit as described in the manual or can I wire directly?
I have attached a screenshot of the circuit from the manual.
Thanks

A: If I understand correctly, you will be using one of the 5 driver output to drive a relay which will connect/disconnect the enable of the driver.
The function of the relay is irrelevant, a relay is an inductive load, hence you will need to "Use an appropriate external protective circuit or device to reduce the risk of inductive direct current load damage ".
Even if you just drive the relay to make it click, without serving any other purpose, you will need to protect the servo driver output.
An inductor (the relay coil) can't change it's current instantly, the purpose of the protection circuit is to provide a path for the current when the coil is switched off. Otherwise, a voltage spike will occur possibly damaging the output of the servo driver.


text:
Q: can i update in codeigniter all fields in cart quantity and other fields like size, brand and other value library can i update in code igniter all Fields in cart quantity and other fields like size, brand and other value library
THIS Is my Controller
function update_cart(){

    foreach($_POST['cart'] as $id => $cart)
    {
        $price = $cart['price'];
        $amount = $price * $cart['qty'];
        $sold_weight = $cart['sold_weight'];

        $data = $this->cart_model->update_cart($cart['rowid'], $cart['qty'], $sold_weight, $price,  $amount);
         print_r($data); die();

    }
    $this->session->set_flashdata('success','Cart is update.');
    redirect('carts/view_cart');
}

This is my modal
function update_cart ($rowid, $qty, $sold_weight, $price, $amount)
{
    $data = array(
        'rowid'   => $rowid,
        'qty'     => $qty,
        'sold_weight' => $sold_weight,
        'price'   => $price,
        'amount'   => $amount
    );

    $this->cart->update($data);
}

and i update sold_weight in cart

A:
class MY_Cart extends CI_Cart
{
    // echo "hi"; die();
function __construct()
{
    // parent::CI_Cart();
     parent::__construct();
}

function update_all($items = array())
{
    // Was any cart data passed?
    if ( ! is_array($items) OR count($items) == 0)
    {
        return false;
    }

    // You can either update a single product using a one-dimensional array,
    // or multiple products using a multi-dimensional one.  The way we
    // determine the array type is by looking for a required array key named "rowid".
    // If it's not found we assume it's a multi-dimensional array
    if (isset($items['rowid']))
    {
        $this->_update_item($items);
    }
    else
    {
        foreach($items as $item)
        {
            $this->_update_item($item);
        }
    }

    $this->_save_cart();
}

/*
 * Function: _update_item
 * Param: Array with a rowid and information about the item to be updated
 *             such as qty, name, price, custom fields.
 */
function _update_item($item)
{
    foreach($item as $key => $value)
    {
        //don't allow them to change the rowid
        if($key == 'rowid')
        {
            continue;
        }

        //do some processing if qty is
        //updated since it has strict requirements
        if($key == "qty")
        {
            // Prep the quantity
            $item['qty'] = preg_replace('/([^0-9])/i', '', $item['qty']);

            // Is the quantity a number?
            if ( ! is_numeric($item['qty']))
            {
                continue;
            }

            // Is the new quantity different than what is already saved in the cart?
            // If it's the same there's nothing to do
            if ($this->_cart_contents[$item['rowid']]['qty'] == $item['qty'])
            {
                continue;
            }

            // Is the quantity zero?  If so we will remove the item from the cart.
            // If the quantity is greater than zero we are updating
            if ($item['qty'] == 0)
            {
                unset($this->_cart_contents[$item['rowid']]);
                continue;
            }
        }

        $this->_cart_contents[$item['rowid']][$key] = $value;
    }
}

}


text:
Q: Gradle build failing - "A problem was found with the configuration of task ':app:generateSafeArgsDebug' (type 'ArgumentsGenerationTask')." I'm trying to open and run the android architecture components sample project here: https://github.com/android/architecture-components-samples/tree/main/GithubBrowserSample in Android Studio. One one machine I'm able to get the project built and run just fine, but on my primary machine I'm seeing a build task error:
A problem was found with the configuration of task ':app:generateSafeArgsDebug' (type 'ArgumentsGenerationTask').
> No value has been specified for property 'enableGradleWorkers'.

I've tried the version of gradle and the gradle plugin that the project seems to have been built with, as well as the latest of each. I do have "android.enableGradleWorkers=true" specified in gradle.properties.
I haven't found this message when searching around, but I often see similar-looking errors when opening projects from different sources. I'd love to be able to fix this one, and ideally understand more about what to check when encountering build errors with projects from different sources in the future.


text:
Q: Why does !{}.length evaluate to true in JavaScript? Why does !{}.length evaluate to true in JavaScript if {}.length throws the error Uncaught SyntaxError: Unexpected token '.'. In fact, !{}.definitelyNotAMethod also evaluates to true.
Objects don't possess length methods, but if you were expecting the object to be an array and didn't perform the proper validations, this could cause a hard-to-spot bug in your code base.
Thanks for taking a look!


text:
Q: Templatting HAProxy log name with rsyslog? I'm trying to set up HAProxy logging with rsyslog, and I currently have HAProxy logs going to a single log file, i.e.:
$AddUnixListenSocket /dev/log

:programname, startswith, "haproxy" {
  /var/haproxy/logs/HAProxy.log
  stop
}

Is there a way to use the current date stamp in the log name? i.e.
$AddUnixListenSocket /dev/log

:programname, startswith, "haproxy" {
  /var/haproxy/logs/HAProxy.%$year%-%$month%-%$day%.log
  stop
}


text:
Q: Consolidating Data from Other Workbooks into One Workbook Current Situation: I am consolidating a data package that receives multiple inputs from programs that roll into mine. Essentially, each program provides me their set of data and I am responsible for accurately consolidating data into one Excel workbook in a certain format. I have pushed out a template so that all the data comes back in the same format, but now I am having trouble quickly consolidating besides using "copy and paste".
Solutions I've looked into: I've looked into using connections to see if can pull in the data I need through a connected file however it imports the table in a different format and does not transfer correctly into the consolidation template that I have set up. I tried doing external source referencing to pull in data that way, but again the formatting is off. I know there are ways to just pull in the workbook, but I need data from specific points in these program workbooks that I can slot into my consolidated workbook. In most cases, copy and pasting would work, but I have over hundreds of programs that flow into this data sheet so any help would be appreciated!

A: How about setting the destination range to the values of the source range?
e.g.:
rngTarget.Resize(rngSource.Rows.Count, rngSource.Columns.Count).Value = rngSource.Value


text:
Q: Ruby - Return byte array containing two's complement representation of Bignum/Fixnum I'm trying to return a byte array containing the two's-complement representation of a Bignum or Fixnum (in Ruby).  There's a method in Java that does exactly that - Docs: Java toByteArray() method, Code for it: https://gist.github.com/867409
My requirements are the same as the Java method (taken from the Java page): The byte array will be in big-endian byte-order: the most significant byte is in the zeroth element. The array will contain the minimum number of bytes required to represent this BigInteger, including at least one sign bit, which is (ceil((this.bitLength() + 1)/8)).
Ruby doesn't have the >>> operator which (I think) is why I'm having so many issues getting this concept converted to Ruby.
Adding some not-working code:
def to_byte_array(num)
  result = []
  until num == 0
    result = [num & 0xff] + result
    num = num >> 8
  end
  result
end

A: The end condition is a bit tricky. Here it goes:
def to_byte_array(num)
  result = []
  begin
    result << (num & 0xff)
    num >>= 8
  end until (num == 0 || num == -1) && (result.last[7] == num[7])
  result.reverse
end

p [0, 1, 255, 256, -1, -128, -256].map{|i| to_byte_array(i)}
# => [[0], [1], [0, 255], [1, 0], [255], [128], [255, 0]]


text:
Q: Updating deprecated code, from each() to foreach() I'm working to fix some old code that triggers a warning on PHP 7.2.0, beacause each() is deprecated.
I tried to replace each() with foreach() like the following, but it doesn't work.
I found some answers on StackOverflow, but none with a straight pure return as in the old code I'm trying to fix.
Old code that needs to be updated (works well, but triggers a warning):
if ($n > 0){
    if ($n !== count($array)){
        return (bool) each($array);
    }
}

What I tried (and doesn't work):
if ($n > 0){
    if ($n !== count($array)){
        foreach($array as $key => $value) {
            return (bool) $value;
        }
        unset($value);
    }
}

Any help is appreciated, thank you :)

A: It seems like the php team encourages you to manage array pointers yourself. you can replace the original array with an ArrayIterator wrapper.
$arrayItor = new ArrayIterator($array);

Then your code can be updated by using this iterator.
if ($n > 0){
    if ($n !== $arrayItor->count()){
        $ret = $arrayItor->current();
        $arrayItor->next();
        return (bool)$ret;
    }
}

Another approach is current and next are not deprecated yet, so you can use them to replace the each function
if ($n > 0){
    if ($n !== count($array)){
        $ret = current($array);
        next($array);
        return (bool)$ret;
    }
}


text:
Q: RDLC line chart report to compare each item from different departments and 3 different time period I want to create RDLC line chart report to compare
- 1 item for many departments in 3 different periods.
What data field should I retrieve from database? I used below Query but that's not enough for chart.
SELECT  d.DepartmentName,
        SUM(CASE  WHEN r.Date BETWEEN '2016-10-01' AND '2016-10-31' THEN ri.RequiredQty ELSE 0 END) FirstMonth,
        SUM(CASE  WHEN r.Date BETWEEN '2016-11-01' AND '2016-11-30' THEN ri.RequiredQty ELSE 0 END) SecondMonth,
        SUM(CASE  WHEN r.Date BETWEEN '2016-12-01' AND '2016-12-31' THEN ri.RequiredQty ELSE 0 END) ThirdMonth
FROM    RequisitionItem ri, Requisition r, [User] u, Department d
WHERE   ri.RequisitionID = r.RequisitionID
AND     r.UserID = u.UserID
AND     u.DepartmentID = d.DepartmentID
AND     ri.ItemID = 'C001'
AND     d.DepartmentID IN ( 'BIOL' , 'COMM', 'BIZL', 'CPSC')
GROUP BY d.DepartmentName

A: This is not the correct way to get data to generate your chart.
Each row of your select should contain 3 informations

*

*Series information in your case the department

*X Axis data that, I imagine, should be the time period

*Y Axis data that is the required quantity

So your query should loook like something like this
        SELECT  d.DepartmentName, --series field
            LEFT(CONVERT(varchar, r.Date,112),6) Period, --X Axis Values
            SUM(ri.RequiredQty) Quantity, --Y axis values
        FROM    RequisitionItem ri, Requisition r, [User] u, Department d
        WHERE   ri.RequisitionID = r.RequisitionID
        AND     r.UserID = u.UserID
        AND     u.DepartmentID = d.DepartmentID
        AND     ri.ItemID = 'C001'
        AND     d.DepartmentID IN ( 'BIOL' , 'COMM', 'BIZL', 'CPSC')
        GROUP BY d.DepartmentName, LEFT(CONVERT(varchar, r.Date,112),6)

Info: this instruction LEFT(CONVERT(varchar, r.Date,112),6) is used to transform your date field in a YYYYMM field so that the group by groups department and month together.


text:
Q: How can I generate a flat excel file from a .rdl report? I have a .rdl report that formats data as a report.  I want to export that data to excel as a flat table with the raw data that was returned based on the params in the report.  The default excel export looks just like the report which isn't what I want (I just want rows and columns).  Is there an easy way to do this?

A: You can save it as csv file. After that you must import that file in excel not open that with excel.

A: If you want to do it as a non-CSV format then make sure that you have zero formatting on any of the report and also try and make sure that any fields are converted into their type - sometimes excel misunderestimates dates etc, Use .net convert functions to do this - alternatively you may have to hack the dataset datatype for a field.
Remove any headers, footers, charts - you're basically after as vanilla as possible
If you do include any of these, make sure they start and finish points line up, if not then you'll get split cells.


text:
Q: How do I stop Odoo from calling a function too many times? I've been trying to solve a problem we have in my company. We use a prestashop web page that's connected to odoo. Sometimes, each platform get a different price in the orders (just cents but you can't pass the order if the difference is bigger than 0.03, we can change that number but dont want).
I did a python program that gave me the new values to adjust the prices in odoo, and now I'm trying to implement it in odoo, it turns out that it's easier said than done.
In order to call the function, I need to search an order in the odoo interface, click edit and change a value (if the difference between both prices are bigger than 0.03 the function that gets called), then I can see in the terminal that prices are recalculated perfectly (even though the function is called too many times, twice per order.order_line, don't know why). At that moment, I can see the ddbb directly and check that the value has been actually changed.
Problem: when clicking the save button, the function is called yet again, why?, when odoo rereads each line in the order, it takes the previous value (just the first line) and keeps modifying that value only.
So, does someone know why that happens?, and more importantly how could I make it so that odoo reads the last value?
we are using odoo 9.
There are no errors, just wrong results.
I attach only the pieces of code that might be causing the problem. The initial function is amount_all, this one calls self._price_readjuster_when_different_odooPR(), within that function updatingLinePrices is called.
Hope everything is clear to understand
class SaleOrder(models.Model):
    _inherit = 'sale.order'
def updatingLinePrices(self, order, price_adjusted):
    ## Updates the new price for each product
    for line, newPrice in zip(order.order_line, price_adjusted):
        #import pdb; pdb.set_trace()
        try:
            if order.order_line.search([['id', '=', line.id], ['name', '=', '[DISCOUNT] Cupon de Descuento']]).id == False:
                #56 => 10%
                tax = 1.1 if str(line.tax_id.id) == 56 else 1.21 #
                if not self.env.context.get('line'):
                    line.with_context(line=True).write({
                    "price_subtotal": newPrice * line.product_uom_qty,
                    "price_unit": newPrice,
                    "price_tax": (newPrice*tax)-newPrice,
                    "price_total": newPrice*tax,
                    "price_reduce": newPrice,
                    })

        except Exception as e:
            print("Error updating to new prices: {}".format(e))
    return line

@api.depends('order_line.price_total')
def _amount_all(self):
    """
    Overrides method to calculate amount_tax over price_tax ignoring tax calculation method.
    """
    #print("_amount_all function has been called")
    for order in self:
        amount_total = amount_untaxed = amount_tax = 0.0
        for line in order.order_line:
            amount_untaxed += line.price_subtotal
            amount_tax += line.price_tax

        amount_total = amount_untaxed + amount_tax
        if self.prestashop_bind_ids.total_amount_tax and self.prestashop_bind_ids.total_amount:
            variation_in_tax = abs(self.prestashop_bind_ids.total_amount_tax - amount_tax)
            variation_in_total = abs(self.prestashop_bind_ids.total_amount - amount_total)
            variation = variation_in_tax + variation_in_total
            print('\n\nvariation_tax: {}\nvariation_total: {}\nVariation: {}\n\n'.format( variation_in_tax, variation_in_total, variation))
            if variation >= 0.03 and variation_in_tax >= 0.03 or variation_in_total > 0.03:

                self._price_readjuster_when_different_odooPR()

            order.update({
                'amount_untaxed': order.pricelist_id.currency_id.round(amount_untaxed),
                'amount_tax': order.pricelist_id.currency_id.round(amount_tax),
                'amount_total': amount_total,
            })

A: I kind of solved it. The problem is that odoo is calling the method far more times than I can control, probably I should've placed the code in a different spot but since I don't know how that method it's called, I just added a button and it works just fine.
The idea was for odoo to readjust the price itself but the problem isn't that frequent anyway.


text:
Q: How to open a new port in apache I want to open a new port in apache so that i can accept http requests on the port with http://ip:port

A: Check Binding to Addresses and Ports:

For example, to make the server accept connections on both port 80 and
  port 8000, on all interfaces, use:
Listen 80
Listen 8000

To make the server accept connections on port 80 for one interface,
  and port 8000 on another, use
Listen 192.0.2.1:80
Listen 192.0.2.5:8000

IPv6 addresses must be enclosed in square brackets, as in the
  following example:
Listen [2001:db8::a00:20ff:fea7:ccea]:80


text:
Q: NHibernate New item added to bag collection does not get saved when updating parent entity I'm using NHibernate version 3.1.0.4000 with hbm mapping files.
When I have an entity which contains a bag collection and i save the entity with all the items added to the bag then it saves all the collection items fine. However, when i then subsequently (after the initial save) add another item to the collection and save the entity then it does not save the new item in the collection. I had a look at the SQL being generated by NHibernate and it creates the initial Insert SQL statement, but it does not create the Update SQL statement to update the foreign key value. This issue occurs for all bags in the solution.
Here is a mapping extract:
    <?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   default-lazy="false"
                   namespace="some_namespace"
                   assembly="some_assembly">

  <class name="Landing"
            table="[Landing]"
            select-before-update="true"
            optimistic-lock="version">
    <id name="Id"
        column="[Id]"
        unsaved-value="null">
      <generator class="assigned" />
    </id>

    <version name="Version"
            column="[Version]"
            unsaved-value="null" />

    <bag name="LandingPermits"
         cascade="all-delete-orphan"
         access="field.camelcase">
      <key column="[LandingId]" />
      <one-to-many class="LandingPermit" />
    </bag>

  </class>
</hibernate-mapping>

Here's the Save method on my NHibernate Repository:
    public NHibernateRepository(ISessionFactory factory, string queriesAssemblyName = null, string clientName = null)
{
    this.sessionFactory = factory;
    this.queriesAssemblyName = queriesAssemblyName;
    this.clientName = clientName;

    if (!string.IsNullOrEmpty(this.queriesAssemblyName))
        LoadQueries();
}

public virtual void Save(IAggregateRoot entity)
{
    Save(new IAggregateRoot[] { entity });
}

public virtual void Save(IAggregateRoot[] entities)
{
    try
    {
        using (var session = OpenSession())
        {
            using (var transaction = session.BeginTransaction())
            {
                try
                {
                    foreach (var entity in entities)
                    {
                        if (entity.IsNew)
                            entity.AddedDateTime = DateTime.Now;
                        else
                            entity.UpdatedDateTime = DateTime.Now;

                        session.SaveOrUpdate(entity.GetType().Name, entity);
                    }
                    transaction.Commit();
                }
                catch (Exception e)
                {
                    transaction.Rollback();
                    throw e;
                }
                finally
                {
                    if (session.Connection.State == ConnectionState.Open)
                        session.Connection.Close();

                    session.Connection.Dispose();
                    session.Close();
                }
            }
        }
    }
    catch (GenericADOException e)
    {
        var sqlException = e.InnerException as SqlException;

        if ((sqlException != null) && (sqlException.Number == ForeignKeyExceptionNumber))
            throw new EntityInUseException("Save", sqlException);
        else
            throw new RepositoryException("Save", e.InnerException);
    }
    catch (StaleObjectStateException e)
    {
        throw new ConcurrencyException("Save", e, new Identity((Guid?)e.Identifier));
    }
    catch (Exception e)
    {
        throw new RepositoryException("Save", e);
    }
}

I have tried a few things, including setting the inverse property to true, but no success.
Hope this is enough information for anyone to asssist.
Thanks

A: If your collection is inverse=false (the default), that means that the owner of the collection (the parent) is responsible for the relationship.
It's not clear in your code above if both parent and child are IAggregateRoot, but if they both are it means that, when you save the child in a session not aware of the parent, that the child will be saved fine but will not be added to the collection.
If you would use inverse=true, the child would be responsible for the relationship. In this case the model should be bidirectional and you should map both ends.
You have a few options here...

*

*Is the child really an aggregate root? Maybe it should be persisted together with its parent?

*Use a bidirectional relationship and use inverse=true


text:
Q: Sourcing a shell script from JS Imagine we have a env.sh with following content.
export SOME_VAL="abcd"

We want to source this shell script from a JS (node.js) script bootstrap.js.
const childProcess = require('child_process');
const cmd = '. ' + pathToEnvScript;
childProcess.exec(cmd, (err, stdout, stderr) => {
    if (err) console.error(err);
    console.log(stdout);
})

Here is how we call the bootstrap.js.
echo $SOME_VAL # empty
node bootstrap.js
echo $SOME_VAL # empty

Why the sourcing doesn't take any effect? The sourcing works if we call source env.sh from terminal, but doesn't work for node bootstrap.js.

A: Given that

a child process cannot modify its parent env (unless you hack your shell)

the best you can do is

make nodejs tell your shell what to do to update its environment as it would have if it had sourced the script itself.

I assume you are only interested in variables and not functions.
Here is your solution.
bootstrap.js:
const childProcess = require('child_process');
const script = process.argv[2];
childProcess.exec("env > ./1.txt; . ./"+script+" >/dev/null 2>&1; env > ./2.txt; diff 1.txt 2.txt | grep '^>'", (err, stdout, stderr) => {
    stdout.split('\n').forEach((line) => console.log(line.substr(2)));
})

and how you should call it:
echo $SOME_VAL # empty
eval `node bootstrap.js ./file.sh`
echo $SOME_VAL # abcd

A: childProcess.exec(command) spawns a shell then executes the command within that shell. Using export makes variables available to child processes of the shell, but not to its parent. Node and the shell from which you invoke Node never see the variable.

A: this is not working for at least two reasons.  source is a Bash internal command, and node spawns /bin/sh by default.  And even if you told child_process.exec to spawn a Bash shell:

child_process.exec("ls", { shell: "/bin/bash" }, (err, stdout) => ())

then the source'd variables would be added to the environment of the shell process, not the environment of node.js .
I don't know what the exact specific requirements are for your project but your best bet might be to open the file in node and parse its contents to find key/value pairs and set node's environment that way.


text:
Q: How to set "run only if logged in" and "run as" with TaskScheduler in C#? I've got code that uses the C# TaskManager object to create a task.  On Windows 7 it works fine but on Windows XP (and presumably other Windows) it doesn't work at all because the default user for the task is system and thus there's no session for the GUI to be displayed.  If I modify the created task manually in the control panel widget to set the job to run only when user is logged in and only for the particular user, then everything works perfectly. But despite hours of searching I see no options for setting these options in the C# objects.  Anyone know a solution with the existing objects?  I'd hate to rewrite everything to manually run the scheduler EXE and pass in stuff by command-line.
Q

A: Okay, I figured out the answer!
I didn't realize it but I had been using a third-party Task Scheduler Managed Wrapper (it'd been a while since I wrote that part of my code) and that explains why help was hard to find!  I stumbled across that page a moment ago and right there in their examples was just what I needed!  The detailed solution in context can be found here, but the key part is:
// Create a new task definition and assign properties
TaskDefinition td = ts.NewTask();
td.Principal.UserId = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
td.Principal.LogonType = TaskLogonType.InteractiveToken;

Thanks for trying to help!


text:
Q: Can AC in-rush cause problems for other devices on same circuit? I'm working with a system that is encountering hardware faults in the field (micro-controller circuits appear to be damaged in some non-visible way); the symptoms are such that it's likely some condition at the site is causing damage to the hardware, since replacing electronics fixes the issue, it doesn't fail when operated away from the site, then fails again within a week or two of returning to the site.
Is it possible that AC power conditioning issues could damage electrical components in the system?  One device of note at the site is a centrifuge that can pull a 100A in-rush current (at 220V) for up to 1 second, followed by continuous operation at up to 30A.  I've heard of power surges causing issues with electronics, so is it possible that a 100A in-rush on the AC power supply circuit could cause damaging surges to other components on the same supply circuit?  I would think that the AC-to-DC power supply for the electronics would protect against this?

A: It is possible that transient voltages associated with starting and stopping the motor could cause problems. The power supply filtering for the electronic system should protect it from most transients on the power lines.
The first thing that I would look at is the routing of any input and output wiring for the electronic system. If any of that wiring is in the same conduit with motor power and control wiring that could easily cause problems. If the electronic I/O wiring is not in metal conduit and close to other wiring that is not in conduit, that could also cause problems.
Also any wiring or electromechanical control components in the same enclosure with electronic control equipment can cause problems.
All enclosures and metal conduits should have protective earth ground connections that are not shared with motor and motor control grounding connections.
There are a lot of possibilities.
Grounding and separation of electronic equipment wiring from power equipment wiring should be covered in the installation instructions for the electronic equipment. You should carefully read the installation instructions and inspect the installation to see if they have been followed.


text:
Q: Beamer TOC: Right-align section numbers I am trying to use capital roman numerals (I, II, ...) to present each section in my beamer TOC with its section number. The following MWE works overall, but it can be seen that the roman numbers, and thus also the section titles, are not aligned. Instead, the roman numbers are left-aligned, and the distance between section number and title is fixed, thus shifting sections to the right depending on the width of the roman numeral.
[During the creation of this MWE, I wanted to have the second section the number 25, to visualize the problem better, as XXV is much wider than I (compared to II). However, despite setting the section counter to 24 and thesection being correctly set at 25 in the frame title, the inserttocsectionnumber command in the TOC only produces a 2 instead of 25. It would be good if there was a solution for that problem as well, i.e. to force TOC to take actual section numbers instead of what seems to be its own count.]
\documentclass[t, sansserif, onlymath, 10pt]{beamer}%\mode<handout>

\makeatletter
\defbeamertemplate{section in toc}{sections numbered roman}{%
  \@Roman\inserttocsectionnumber.\ %
  \inserttocsection\par}
  \renewcommand*{\numberline}[1]{%
  \hb@xt@\@tempdima{\hfil#1 }%
}
\makeatother

\begin{document}

\setbeamertemplate{section in toc}[sections numbered roman]
\setbeamerfont{section in toc}{size=\normalsize, family = \sffamily}
\setbeamerfont{section in toc}{shape = \normalfont}

\begin{frame}
  \frametitle{Overview}
  \tableofcontents[currentsection]
\end{frame}
\section{section one}
\begin{frame}
  \frametitle{xxx1 \thesection}
\end{frame}

\setcounter{section}{24}

\section{section two/twenty-five}
\begin{frame}
  \frametitle{xxx2 \thesection}
\end{frame}

\setbeamercovered{transparent}
\begin{frame}
\frametitle{{Agenda}}
\begin{enumerate}[I.]
\item <1|handout: 1> { Overview} \\
\vspace{0.9cm}
\item <0|handout: 1> {sec1}\\
\vspace{0.9cm}
\item <0|handout: 1> {sec 2: }\\
\end{enumerate}
\end{frame}

\end{document}

Including the last slide gives pretty much how I want the result to look (in fact, it is where I am coming from, but I need automation). You can see that, using the "enumerate" package, the "enumerations" are right-aligned, and so are the section titles.
In the document preamble, the code
  \defbeamertemplate{section in toc}{sections numbered roman}{%
  \@Roman\inserttocsectionnumber.\ %
  \inserttocsection\par}

serves to use roman numerals and insert section numbers before section titles, and
  \renewcommand*{\numberline}[1]{%
  \hb@xt@\@tempdima{\hfil#1 }%
  }

tries to right-align the number using a command taken from Right-align numbers in ToC
, but that is rather on alignment between sections and subsections relative to each other, and the above code snipped does not do the trick.

A: Quick workaround:
place the Roman number in a boxed of fixed width
\documentclass[t, sansserif, onlymath, 10pt]{beamer}%\mode<handout>

\makeatletter
\defbeamertemplate{section in toc}{sections numbered roman}{%
  \makebox[0.8cm]{\hfill\@Roman\inserttocsectionnumber.}\space%
  \inserttocsection\par
}
\makeatother

\begin{document}

\setbeamertemplate{section in toc}[sections numbered roman]

\begin{frame}
  \frametitle{Overview}
  \tableofcontents
\end{frame}

\section{section one}
\begin{frame}
  \frametitle{xxx1 \thesection}
\end{frame}

\makeatletter
\beamer@tocsectionnumber=24
\makeatother

\section{section two/twenty-five}
\begin{frame}
  \frametitle{xxx2 \thesection}
\end{frame}

\end{document}


text:
Q: Text manipulation with vim (or maybe shell) I have one file full with records like this:
"Full name","URL-style name","key_1a","key_2a"
"Full name","URL-style name","key_1b","key_2b"
"Full name","URL-style name","key_1c","key_2c"
...

I have another file full with records like this:
"URL-style name","key_1a","key_2a"
"URL-style name","key_1b","key_2b"
"URL-style name","key_1c","key_2c"
...

Knowing that ("key_1","key_2") is a primary key (unique), I'd like to add in the second file the "Full name" column.
How would you do this? I'm looking for a solution with vim or in bash shell script.

A: Let's take a modified version of your sample data:
file1
"Full nameA","URL-style name","key_1a","key_2a"
"Full nameB","URL-style name","key_1b","key_2b"
"Full nameC","URL-style name","key_1c","key_2c"

file2
"URL-style name1","key_1a","key_2a"
"URL-style name2","key_1b","key_2b"
"URL-style name3","key_1c","key_2c"

Processing
As noted in a comment, one limitation of the join command is that it can only join on a single column, but the question has a compound key with two columns. There are ways around that, of course: basically, you reformat the inputs to join so that the composite column is identifiable as a single column under the delimiter used, and you have to ensure that the data in each file is sorted correctly in order of that composite column. Nevertheless, join is probably the way to do it; there's just some prep-work and post-processing required. Also, Bash v4 has 'process substitution' which is very useful for this command.

*

*Generate a joinable file from file1 with the data we need.
There are several ways to do this; both sed (somewhat inscrutably) or awk could be used:
$ sed 's/\([^,]*\),[^,]*,\([^,]*\),\([^,]*\)/\2:\3,\1/' file1
"key_1a":"key_2a","Full nameA"
"key_1b":"key_2b","Full nameB"
"key_1c":"key_2c","Full nameC"
$ awk -F, '{ printf "%s:%s,%s\n", $3, $4, $1 }' file1
"key_1a":"key_2a","Full nameA"
"key_1b":"key_2b","Full nameB"
"key_1c":"key_2c","Full nameC"
$

*Generate a joinable file from file2 with the data we need:
$ sed 's/\([^,]*\),\([^,]*\),\([^,]*\)/\2:\3,\1/' file2
"key_1a":"key_2a","URL-style name1"
"key_1b":"key_2b","URL-style name2"
"key_1c":"key_2c","URL-style name3"
$ awk -F, '{ printf "%s:%s,%s\n", $2, $3, $1 }' file2
"key_1a":"key_2a","URL-style name1"
"key_1b":"key_2b","URL-style name2"
"key_1c":"key_2c","URL-style name3"
$

*Given this preprocessing, a straight sort suffices to get the data ready for join.
$ join -t, -o 2.2,0,1.2 \
>      <(awk -F, '{ printf "%s:%s,%s\n", $3, $4, $1 }' file1 | sort) \
>      <(awk -F, '{ printf "%s:%s,%s\n", $2, $3, $1 }' file2 | sort)
"URL-style name1","key_1a":"key_2a","Full nameA"
"URL-style name2","key_1b":"key_2b","Full nameB"
"URL-style name3","key_1c":"key_2c","Full nameC"
$

*And now we need to post-process the colon into a comma:
$ join -t, -o 2.2,0,1.2 \
>      <(awk -F, '{ printf "%s:%s,%s\n", $3, $4, $1 }' file1 | sort) \
>      <(awk -F, '{ printf "%s:%s,%s\n", $2, $3, $1 }' file2 | sort) |
> sed 's/":"/","/'
"URL-style name1","key_1a","key_2a","Full nameA"
"URL-style name2","key_1b","key_2b","Full nameB"
"URL-style name3","key_1c","key_2c","Full nameC"
$

Clearly, you can choose any appropriate character instead of a colon; Control-A (0x01) is unlikely to appear in your HTML.
This assumes that, as shown, your CSV data has no commas in the strings.  If you have commas inside the strings, then life is much harder; you need a proper CSV interpreter to handle the data.  Perl has Text::CSV and there's also csvfix.

A: In awk:
$ awk -F, 'NR==FNR{a[$3$4]=$1;next}($2$3 in a){print a[$2$3]","$0}' file1 file2
"Full name","URL-style name","key_1a","key_2a"
"Full name","URL-style name","key_1b","key_2b"
"Full name","URL-style name","key_1c","key_2c"

A: The command you are searching for is join.
Please see man join for detailed information.
If you get an error like pfull.txt:6: is not sorted you may either sort the input files before with the sort command, or give the --nocheck-order option a try.

A: If you dont have to match entries with each other, since data is in the same order in both files:
Use Vim VISUAL BLOCK mode.
Open both files in Vim in two windows (:sp <filename> or :vsp <filename> will help with that), start block selection of your desired text with CTRLv, copy with y.
Move between windows with CTRLwh  j  k  l, depending if you have vertical or horizontal splitting.
Position you cursor where you want to paste your clipboard data, press p.


text:
Q: error running a dockerfile that use go and makke file : error 1 hi am trying to clone this repository and run the docker file to create a load-watcher images but i am getting this error and it's not working i try to search by my self but i am stuck because am a beginner in go and make files
so this is the repository:
https://github.com/paypal/load-watcher.git
this is the first command am trying to run (it's right in the top of the read-me file of the repository):
sudo docker build -t load-watcher .
and this is the error:
Step 1/7 : FROM golang:1.16
 ---> 972d8c0bc0fc
Step 2/7 : WORKDIR /go/src/github.com/paypal/load-watcher
 ---> Using cache
 ---> 34ef186a096c
Step 3/7 : COPY . .
 ---> 5361f9fef122
Step 4/7 : RUN make build
 ---> Running in 51d0b4396ecc
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 /usr/local/go/bin/go  build -o bin/load-watcher main.go
go: github.com/francoispqt/gojay@v1.2.13: Get "https://proxy.golang.org/github.com/francoispqt/gojay/@v/v1.2.13.mod": dial tcp: lookup proxy.golang.org on 194.167.49.3:53: read udp 172.17.0.2:58077->194.167.49.3:53: i/o timeout
make: *** [Makefile:24: build] Error 1
The command '/bin/sh -c make build' returned a non-zero code: 2

please if any one work with this or know how to help i will be grateful, i have been trying to solve it for a week now !!!!


text:
Q: Is LINQ to SQL the best way to build a Model or create my own classes I am develop a medium system in ASP.net with MS SQL Server Database and I wonder what is the best way to create a model layer with LINQ or create own classes that dealing with database?

A: The best way is subjective, but I think the easiest is to use LINQ to SQL.

A: Using the LINQ designer is a great way to build your model in a UI avoiding the need to write any code.  You can setup object hierarchy using the inheritance option and also have associated classes which you can access via the datacontext in code.  All of the SQL is then handled for you and means you don't have to write anything, simply call SubmitChanges() on the datacontext.  All of the generated code can be viewed, but there is a lot to take in.
I would suggest to try writing your own classes manually with the LINQ attributes etc so you get an idea of what it is doing behind the scenes.  Then you will realise how the inheritance and association is implemented and actually makes the designer easier to understand too.


text:
Q: How to access the underlying default concurrent queue of a blocking collection? I have multiple producers and a single consumer. However if there is something in the queue that is not yet consumed a producer should not queue it again. (unique no duplicates blocking collection that uses the default concurrent queue)
if (!myBlockingColl.Contains(item))
    myBlockingColl.Add(item)

However the blocking collection does not have a contains method nor does it provide any kind of TryPeek() like method. How can I access the underlying concurrent queue so I can do something like
if (!myBlockingColl.myConcurQ.trypeek(item)
  myBlockingColl.Add(item)

In a tail spin?

A: This is an interesting question. This is the first time I have seen someone ask for a blocking queue that ignores duplicates. Oddly enough I could find nothing like what you want that already exists in the BCL. I say this is odd because BlockingCollection can accept a IProducerConsumerCollection as the underlying collection which has the TryAdd method that is advertised as being able to fail when duplicates are detected. The problem is that I see no concrete implementation of IProducerConsumerCollection that prevents duplicates. At least we can write our own.
public class NoDuplicatesConcurrentQueue<T> : IProducerConsumerCollection<T>
{
  // TODO: You will need to fully implement IProducerConsumerCollection.

  private Queue<T> queue = new Queue<T>();

  public bool TryAdd(T item)
  {
    lock (queue)
    {
      if (!queue.Contains(item))
      {
        queue.Enqueue(item);
        return true;
      }
      return false;
    }
  }

  public bool TryTake(out T item)
  {
    lock (queue)
    {
      item = null;
      if (queue.Count > 0)
      {
        item = queue.Dequeue();
      }
      return item != null;
    }
  }
}

Now that we have our IProducerConsumerCollection that does not accept duplicates we can use it like this:
public class Example
{
  private BlockingCollection<object> queue = new BlockingCollection<object>(new NoDuplicatesConcurrentQueue<object>());

  public Example()
  {
    new Thread(Consume).Start();
  }

  public void Produce(object item)
  {
    bool unique = queue.TryAdd(item);
  }

  private void Consume()
  {
    while (true)
    {
      object item = queue.Take();
    }
  }
}

You may not like my implementation of NoDuplicatesConcurrentQueue. You are certainly free to implement your own using ConcurrentQueue or whatever if you think you need the low-lock performance that the TPL collections provide.
Update:
I was able to test the code this morning. There is some good news and bad news. The good news is that this will technically work. The bad news is that you probably will not want to do this because BlockingCollection.TryAdd intercepts the return value from the underlying IProducerConsumerCollection.TryAdd method and throws an exception when false is detected. Yep, that is right. It does not return false like you would expect and instead generates an exception. I have to be honest, this is both surprising and ridiculous. The whole point of the TryXXX methods is that they should not throw exceptions. I am deeply disappointed.

A: In addition to the caveat Brian Gideon mentioned after Update, his solution suffers from these performance issues:

*

*O(n) operations on the queue (queue.Contains(item)) have a severe impact on performance as the queue grows

*locks limit concurrency (which he does mention)

The following code improves on Brian's solution by

*

*using a hash set to do O(1) lookups

*combining 2 data structures from the System.Collections.Concurrent namespace

N.B. As there is no ConcurrentHashSet, I'm using a ConcurrentDictionary, ignoring the values.
In this rare case it is luckily possible to simply compose a more complex concurrent data structure out of multiple simpler ones, without adding locks. The order of operations on the 2 concurrent data structures is important here.
public class NoDuplicatesConcurrentQueue<T> : IProducerConsumerCollection<T>
{
    private readonly ConcurrentDictionary<T, bool> existingElements = new ConcurrentDictionary<T, bool>();
    private readonly ConcurrentQueue<T> queue = new ConcurrentQueue<T>();

    public bool TryAdd(T item)
    {
        if (existingElements.TryAdd(item, false))
        {
            queue.Enqueue(item);
            return true;
        }
        return false;
    }

    public bool TryTake(out T item)
    {
        if (queue.TryDequeue(out item))
        {
            bool _;
            existingElements.TryRemove(item, out _);
            return true;
        }
        return false;
    }
    ...
}

N.B. Another way at looking at this problem: You want a set that preserves the insertion order.

A: I would suggest implementing your operations with lock so that you don't read and write the item in a way that corrupts it, making them atomic.  For example, with any IEnumerable:
object bcLocker = new object();

// ...

lock (bcLocker)
{
    bool foundTheItem = false;
    foreach (someClass nextItem in myBlockingColl)
    {
        if (nextItem.Equals(item))
        {
            foundTheItem = true;
            break;
        }
    }
    if (foundTheItem == false)
    {
        // Add here
    }
}

A:
How to access the underlying default concurrent queue of a blocking collection?

The BlockingCollection<T> is backed by a ConcurrentQueue<T> by default. In other words if you don't specify explicitly its backing storage, it will create a ConcurrentQueue<T> behind the scenes. Since you want to have direct access to the underlying storage, you can create manually a ConcurrentQueue<T> and pass it to the constructor of the BlockingCollection<T>:
ConcurrentQueue<Item> queue = new();
BlockingCollection<Item> collection = new(queue);

Unfortunately the ConcurrentQueue<T> collection doesn't have a TryPeek method with an input parameter, so what you intend to do is not possible:
if (!queue.TryPeek(item)) // Compile error, missing out keyword
    collection.Add(item);

Also be aware that the queue is now owned by the collection. If you attempt to mutate it directly (by issuing Enqueue or TryDequeue commands), the collection will throw exceptions.


text:
Q: Could not find gradle.jar (com.android.tools.build:gradle:3.5.1) I was downloading Android Studio 3.5 .. and I got this error saying ::
ERROR: Could not find gradle.jar (com.android.tools.build:gradle:3.5.1). Searched in the following locations:
    https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.5.1/gradle-3.5.1.jar
I checked some solutions about adding google() repo to the build.gradle and it was already there
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
     repositories {
        google()
        jcenter()
                  }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.1'
                 }
            }

allprojects {
    repositories {
        google()
        jcenter()
                 }
            }

task clean(type: Delete) {
    delete rootProject.buildDir
        }

no ""offline work"" checked in global gradle setting

A: I had this problem and this method has solved my problem
Please follow the below steps:

*

*Download gradle.jar from https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.5.1/gradle-3.5.1.jar

*Close your android studio project

*Close android studio

*Remove > C:\Users\your user\ .gradle directory

*Open your project

*Make sure you are connect with internet

*Sync your project


text:
Q: Backgroundworker not busy I'm sorry for a somewhat blunt question, that could probably have dozens of answers, but I don't even know what to look for...
I am using a background worker, and for some reason, it doesn't seem to get busy.
Before trying to launch the worker, I am checking if it's busy.
The code I have inside it is the follwoing:
    void ClientMsg_BgWrkrTimer_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker ClientMsg_BgWrkrTimer = sender as BackgroundWorker;
        string current = msgqueue.Last().Key;
        if (msgqueue.Last().Value.t_Type == 0 || msgqueue.Last().Value.t_Type == 1)
        {
            TimedMsgIcon.Enabled = true;
            foreach (KeyValuePair<string, UUID> g in Msgqueue.Last().Value.t_ngroups)
            {
                GroupNotice ntc = new GroupNotice();
                ntc.Subject = Msgqueue.Last().Value.t_nmsg;
                ntc.Message = Msgqueue.Last().Value.t_nmsg;
                ntc.OwnerID = Client.Self.AgentID;
                UUID key = UUID.Zero;
                if (UUID.TryParse(Msgqueue.Last().Value.t_attach.ToString(), out key))
                {
                    ntc.AttachmentID = key;
                }
                Client.Self.InstantMessage(Client.Self.Name, g.Value, ntc.Subject + "|"
                    + ntc.Message, UUID.Zero, InstantMessageDialog.GroupNotice,
                    InstantMessageOnline.Online, Vector3.Zero, UUID.Zero,
                    ntc.SerializeAttachment());
                Thread.Sleep(2000);
            }
        }
    }

I have narrowed down the culprit to be this one:
    Client.Self.InstantMessage(Client.Self.Name, g.Value, ntc.Subject + "|"
        + ntc.Message, UUID.Zero, InstantMessageDialog.GroupNotice,
        InstantMessageOnline.Online, Vector3.Zero, UUID.Zero,
        ntc.SerializeAttachment());

And most probably it's being the Serialization, which is this (comming from the library I am using):
    public struct GroupNotice
    {
        ///
        public string Subject;
        ///
        public string Message;
        ///
        public UUID AttachmentID;
        ///
        public UUID OwnerID;

        ///
        ///
        ///
        /// <returns></returns>
        public byte[] SerializeAttachment()
        {
            if (OwnerID == UUID.Zero || AttachmentID == UUID.Zero)
                return Utils.EmptyBytes;

            OpenMetaverse.StructuredData.OSDMap att = new OpenMetaverse.StructuredData.OSDMap();
            att.Add("item_id", OpenMetaverse.StructuredData.OSD.FromUUID(AttachmentID));
            att.Add("owner_id", OpenMetaverse.StructuredData.OSD.FromUUID(OwnerID));

            return OpenMetaverse.StructuredData.OSDParser.SerializeLLSDXmlBytes(att);
        }
    }

The question is, why is this preventing my worker from being busy?
As soon as I take it out, it works like a charm.
I need it though, so I hope anyone could help me suggest what's causing the problem, and how to use it properly in the worker.
Edit:
I'm sorry for missing out the vital point of "Not working"..
So
By "not working", I mean the Client.Self.InstantMessage() doesn't fire off, and the backgroundworker doesn't get bussy.
As mentioned, I test first to see if the worker is busy or not before entering the worker:
    void MsgTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        if (!ClientSpam_BgWrkrTimer.IsBusy)
        {
            Messagebox.Show("Going into BgWrkr!");
            ClientSpam_BgWrkrTimer.RunWorkerAsync();
        }
    }

When using the Client.Self.InstantMessage(), the messagebox keep popping up at every timer tick and the worker never comes to an end.
However, if I remove it, the worker get's completed.

A: I notice that you have a Thread.Sleep(2000) statement in your worker.  That will cause the worker's .IsBusy property to be true for about 2 seconds, plus whatever time was spent in the method before the Sleep.
You also mentioned that when the call to Client.Self.InstantMessage(...) is present, then the worker never appears busy.  To me, this seems like the Thread.Sleep call is never being executed, which means that it is likely that the Client.Self.InstantMessage method is throwing an exception.
Try wrapping the call to Client.Self.InstantMessage in a try/catch block to see if an exception is being thrown.  You'll be able to observe the message in the Visual Studio Output Window when running in the debugger.
        ...

        try
        {
            Client.Self.InstantMessage(Client.Self.Name, g.Value, ntc.Subject + "|"
                + ntc.Message, UUID.Zero, InstantMessageDialog.GroupNotice,
                InstantMessageOnline.Online, Vector3.Zero, UUID.Zero,
                ntc.SerializeAttachment());
        }
        catch(Exception e)
        {
            Debug.WriteLine("Exception while calling InstantMessage: {0}", e.ToString());
        }

        Thread.Sleep(2000);

        ...

You can also examine the RunWorkerCompletedEventArgs.Error property (from the BackgroundWorker.RunWorkerCompleted event) to see if the worker threw an exception.
Once you know what the exception is, you'll be able to better diagnose the cause of the problem.


text:
Q: Find opposite numbers and replace them with NA Assume that I have this dataset
x   y
na  100
na   na
na   na
na   200
-100   na
200   100
500   1000
600   20000
na    200
100    -1000
1000    na
na      1000
-200    -100
0        na
300     0
na     -200
-300    na
na      0

well i want to replace with NA the opposite values without loosing the rows, the desired output would be
x   y
na  100
na   na
na   na
na   NA
NA   na
NA   NA
500   NA
600   20000
na    200
NA    NA
1000    na
na      1000
NA    NA
0        na
NA     0
na     NA
NA    na
na      0

For example if in my dataset but on the same column exist two opposite numbers i want to replace both of them with NA. If i have -100 and +100 replace them with NA.

A: Let's take this as data example:
df <- data.frame(x = c("na",-100,100,200,500,-200,"na"),
                 y = c("na","na",300,-300,500,-400,"na"))
     x    y
1   na   na
2 -100   na
3  100  300
4  200 -300
5  500  500
6 -200 -400
7   na   na

Then we can do:
library(dplyr)
output <- df %>%
  mutate(across(everything(), ~ifelse(. == "na", NA, .))) %>%
  mutate(across(everything(), ~as.numeric(.))) %>%
  mutate(across(everything(), ~ifelse(. %in% -., NA, .)))

Which results in:
    x    y
1  NA   NA
2  NA   NA
3  NA   NA
4  NA   NA
5 500  500
6  NA -400
7  NA   NA

Edit: To keep the rep. That's kind of tricky, there should be better solution, but it works:
df %>%
  mutate(across(everything(), ~ifelse(. == "na", NA, .))) %>%
  mutate(across(everything(), ~as.numeric(.))) %>%
  group_by(x) %>%
  mutate(count_x = 1:n()) %>%
  ungroup() %>%
  group_by(y) %>%
  mutate(count_y = 1:n()) %>%
  ungroup() %>%
  mutate(across(x, ~ifelse(. %in% -. & count_x == 1, NA, .))) %>%
  mutate(across(y, ~ifelse(. %in% -. & count_y == 1, NA, .))) %>%
  select(-count_x, -count_y)

Input:
df <- data.frame(x = c("na",-100,100,200,500,-200,100,"na"),
                 y = c("na","na",300,-300,300,-400,300,"na"))
     x    y
1   na   na
2 -100   na
3  100  300
4  200 -300
5  500  300
6 -200 -400
7  100  300
8   na   na

Output:
      x     y
  <dbl> <dbl>
1    NA    NA
2    NA    NA
3    NA    NA
4    NA    NA
5   500   300
6    NA  -400
7   100   300
8    NA    NA

A: You can write a function making iteratively the changes:
f <- function(y) {
  for(i in 1:(length(y)-1)) {
    for(j in (i+1):length(y)) {
      if(!is.na(y[i]) & !is.na(y[j]) & y[i] != 0 & y[i] == -y[j]) {
        y[c(i,j)] <- NA
      }
    }
  }
  y
}

x[] <- lapply(x, f)

x
#      x     y
#1    NA    NA
#2    NA    NA
#3    NA    NA
#4    NA    NA
#5    NA    NA
#6    NA   100
#7   500    NA
#8   600 20000
#9    NA   200
#10   NA    NA
#11 1000    NA
#12   NA  1000
#13   NA    NA
#14    0    NA
#15   NA     0
#16   NA    NA
#17   NA    NA
#18   NA     0

Data:
x <- data.frame(x = c(NA, NA, NA, NA, -100, 200, 500, 600, NA,
100, 1000, NA, -200, 0, 300, NA, -300, NA), y = c(100, NA, NA,
200, NA, 100, 1000, 20000, 200, -1000, NA, 1000, -100, NA, 0,
-200, NA, 0))


text:
Q: Need to play a mp3 audio over the internet without latency in iOS (Swift) We are trying to achieve low latency audio streaming(only encoded audio data present, no video data) using AVPlayer.  We have tested audio streaming protocols like HTTP & HLS and have observed a minimum of 3 seconds latency to play.
Does AVPlayer require an input buffer of a minimum of 3 seconds on the device before starting the playback?
Does latency reduction have any correlation with the quality of audio playback?
Can we reduce this latency? If yes, are there any suggestions or recommended practices?

A: Latency can be minimized by using Audio Units, as Audio Units can request to be configured with very short audio buffers, typically 20 mS down to 5 mS, or even less on some Apple devices.  UDP with MTU size packets can be used to stream data over the network, where your network buffering and traffic interference may be the dominating factor in added latency.  You will likely have to add some amount of latency (circular ring buffer fill level) to account for worse case network timing jitter.  Then, for mp3 compressed audio, add on the minimum mp3 block size and how long your chosen mp3 decoder takes.
Other APIs and protocols can potentially add large amounts of overhead and buffering latency.

A: You can just observe playerItem.loadedTimeRanges an play pause AVPlayer manually if buffer (aka loadedTimeRanges) enough for you latency conditions


text:
Q: Page gets reloaded after clicking the submit button

$(document).ready(function() {
  $("submit").click(function(event) {
    event.preventDefault();
  });
});

function norefresh() {
  return false;
}
<form method="post" action="<?php echo htmlspecialchars($_SERVER[" PHP_SELF "]);?>">

        NAME OF THE LANDLORD
        <input type="text" class="form-control" id="lname" name="lname">

        PAN OF LANDLORD
        <input type="text" class="form-control" id="lpan" name="lpan">

        ADDRESS OF LANDLORD
        <input type="text" class="form-control" id="ladd" name="ladd">

        ACCOMODATION ADDRESS
        <input type="text" class="form-control" id="lacc" name="lacc">

  <input type="submit" class="btn btn-primary pull-right" name="submit" value="Add New" onClick="getintotab();resetform();return false;" />

</form>

<?php
 if(isset($_POST['submit'])){
  $sql1 = $db->query("INSERT INTO Landlord(name, landlord_pan, landlord_address, acc_address) VALUES ('".$_POST["lname"]."','".$_POST["lpan"]."','".$_POST["ladd"]."','".$_POST["lacc"]."')");

  if($sql1 == TRUE){
   echo "";
  }
  else{
   echo "Error: " . $sql1 . "
" . mysqli_error($db);
  }
 }
?>

The php script on clicking the submit button sends the form data to a mysql database and the getintotab() function stores the form value on the same page in a table resetform() resets the form
but on clicking the submit button the page gets reloaded.
I have already tried the following:

*

*norefresh()

*preventdefault()

*making the input type as button instead of submit

Still no luck

A: You need to use event.preventDefault() but your selector "submit" won't match anything.
Either add an identifier to your submit button:
<input type="submit" id="submit" ... >

Then use that as your selector:
  $("#submit").click(function(event) {
    event.preventDefault();
    # You should add the other function calls here
    # instead of having function calls in two separate places.
  });

Or add an identifier to your form:
<form id="form" ... >

Then add a listener for the submit action (the way I'd recommend):
  $("#form").submit(function(event) {
    event.preventDefault();
    # You should add the other function calls here
    # instead of having function calls in two separate places.
  });

A: You are hitting server with a http request (form submit). This will result in page reload.
You should hit server by an XmlHttpRequest i.e AJAX call to get/post data from/to server respectively. This refreshes only part of page and does not reload complete page. Hope this helps.

A: I think you can remove onClick="getintotab();resetform();return false;" and use all js stuff in jquery selector and it will work for you.

A: you should use this trick:
<input type="submit" class="btn btn-primary pull-right" name="submit" value="Add New" />

to
<input type="button" class="btn btn-primary pull-right" name="submit" value="Add New" />

Hope this helps.


text:
Q: Fractional factorial design with mixed categorical and numerical variables analysis for more than two levels I have an experiment setup that consists of multiple continuous and multiple categorical variables. Right now, I am just using two levels for the categorical variables, allowing me to encode them as -1 and 1, and thereby, in terms, allowing me to do a simple linear-regression analysis for the entire/fractional model (currently up to three-factor interactions, and using a resolution V design).
I am planning a similar experiment, where I have both numerical and categorical variables too, yet this time the categorical variables have more than two levels. The options I have seen to encode these categorical variables are:

*

*Encoding every level as an on/off variable.

*Introduce a number of variables that are treated like binary bits, thereby allowing me to represent four levels with two variables, eight with three, and so on.

In either case, however, I do not understand how to then proceed with the analysis. How do I fit a linear model to an experiment containing variables encoded in that way?
There is, of course, software, that could do that part for me, but I am looking for a conceptual understanding.


text:
Q: Merge two arrays containing objects and remove duplicate values I need to merge two arrays of objects into 1 array and remove duplicate email values.
How can I do that?
These are my sample arrays:
$array1 = [
    (object) ["email" => "gffggfg"],
    (object) ["email" => "wefwef@test.it"],
    (object) ["email" => "wefewf"],
];
$array2 = [
    (object) ["email" => "gffggfg@test.it"],
    (object) ["email" => "wefwef"],
    (object) ["email" => "wefewf"],
];

My expected result is:
[
   (object) ['email' => 'gffggfg'],
   (object) ['email' => 'wefwef@test.it'],
   (object) ['email' => 'wefewf'],
   (object) ['email' => 'gffggfg@test.it'],
   (object) ['email' => 'wefwef'],
]

A: I've been running some benchmarks of all the ways I can imagine of doing this. I ran tests on stacking lots of arrays of 10-20 string elements, resulting in one array with all unique strings in there. This sould be about the same for stacking just 2 arrays.
The fastest I've found was the simplest thing I tried.
$uniques = [];
foreach($manyArrays as $arr ) {
  $uniques = array_unique(array_merge($uniques, $arr));
}

I had branded this 'too naive to work', since it has to sort the uniques array every iteration. However this faster than any other method. Testing with 500.000 elements in manyArrays, each containing 10-20 strings om PHP 7.3.
A close second is this method, which is about 10% slower.
$uniques = [];
foreach($manyArrays as $arr ) {
  foreach($arr as $v) {
    if( !in_array($v, $uniques, false) ) {
      $uniques[] = $v;
    }
  }
}

The second method could be better in some cases, as this supports the 'strict' parameter of in_array() for strict type checking. Tho if set to true, the second option does become significantly slower than the first (around 40%). The first option does not support strict type checking.

A: You can combine the array_merge() function with the array_unique() function (both titles are pretty self-explanatory)
$array = array_unique (array_merge ($array1, $array2));

A: If I understand the question correctly:
 $a1 = Array(1,2,3,4);
 $a2 = Array(4,5,6,7);
 $array =  array_diff(array_merge($a1,$a2),array_intersect($a1,$a2));
 print_r($array);

return
Array
(
[0] => 1
[1] => 2
[2] => 3
[5] => 5
[6] => 6
[7] => 7
)

A: Faster solution:
function concatArrays($arrays){
    $buf = [];
    foreach($arrays as $arr){
        foreach($arr as $v){
            $buf[$v] = true;
        }
    }
    return array_keys($buf);
}

$array = concatArrays([$array1, $array2]);

A: Because the email properties in the array of objects contain non-numeric values, you can temporarily assign first level keys (with array_column()) then merge the two arrays with the union operator (a function-less action).
If the temporary keys are disruptive to your next process, you can re-index the array with array_values().
Code: (Demo)
var_export(
    array_values(
        array_column($array1, null, 'email')
        + array_column($array2, null, 'email')
    )
);

Output:
array (
  0 =>
  (object) array(
     'email' => 'gffggfg',
  ),
  1 =>
  (object) array(
     'email' => 'wefwef@test.it',
  ),
  2 =>
  (object) array(
     'email' => 'wefewf',
  ),
  3 =>
  (object) array(
     'email' => 'gffggfg@test.it',
  ),
  4 =>
  (object) array(
     'email' => 'wefwef',
  ),
)

"Merge and keep unique objects" will also work with a special flag.
Code: (Demo)
var_export(
    array_unique(
        array_merge($array1, $array2),
        SORT_REGULAR
    )
);
// same result as other snippet

A: Very old thread, but...
OP's arrays contains objects.
If I were op, I would declare a class that receives the sub arrays in the constructor  with a __toString() function that returns the email.
If op then makes his objects into instances of that class, array_unique should call __toString() when comparing

A: A little bit late answer, but I just found that the array union operator + does the job quite greatly (found here at the 3rd section).
$array1 + $array2 = $array //if duplicate found, the value in $array1 will be considered ($array2 value for array_merge, if keys clearly specified)