text:
Q: PHP Explode Numbers In Square Brackets I have the following list which I get from Android into PHP in this format:
//How I get phonenumberlist
$phonenumberlist = isset($_POST['PhoneNumberList']) ? $_POST['PhoneNumberList'] : '';
//The output of phonenumberlist when I print to text
$phonenumberlist = [0761234567, 072999999, 0731111111];

I would like to explode these numbers individually, I tried:
 $phonenumberlist_exploded = explode(',', $phonenumberlist);
 foreach ($phonenumberlist_exploded as $number)
 {
     echo $number;
 }

I get the following warning:
Warning: explode() expects parameter 2 to be string, array given in

A: $phonenumberlist is already an array. There's no need to explode it. Just iterate through it to echo out the values.
You will have an issue with the leading zeros, however:

Parse error: Invalid numeric literal

So you will need to wrap those values in quotes to make PHP handle them as strings:
$phonenumberlist = ['0761234567', '072999999', '0731111111'];
foreach($phonenumberlist as $number) {
    echo $number;
}

Demo

A: You may convert the list like this:-
$phonenumberlist = '[0761234567, 072999999, 0731111111]';
$phonenumberlist = str_replace([' ', '[', ']', ','], ['', '["', '"]', '","'], $phonenumberlist);
$phonenumberlist = json_decode($phonenumberlist, true);

It will:-

*

*Remove all spaces

*Wrap all numbers with double quote (convert them to string type)

*Convert the string to array using json_decode.

[Edit 1]
Another option:-
$phonenumberlist = '[0761234567, 072999999, 0731111111]';
$phonenumberlist = trim(trim($phonenumberlist, '['), ']');
$phonenumberlist = explode(', ', $phonenumberlist);

*

*Trim the brackets

*Explode the string to an array

Hope this helps.


text:
Q: Disappeared photos I have Copied my photos from Lumix camera to laptop with Windows 7 and now I can only see half of the amount of photos on my camera.
The amount of MB tells me that the ones I cannot see are also there on the camera.
Can anybody tell me what has happened and how I can make these photos to be seen again on camera, please?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Global filter in primeng p-table doesn't work for complex row data Primefaces primeng filter p-table example - global filtering doesn't work for complex data.
Example uses model:
export interface Car {
vin?;
year?;
brand?;
color?;
price?;
saleDate?;
}

If we add field engine to car interface:
export interface Engine {
type?;
power?;
atRpm?;
}

And add column Engine to the template to display rowData.engine.type data, global filter is not working for this column.  How to solve this?
I'd prefer to avoid data flattening if possible. Because it should be done on large amount of data and the original model is productively used in application.

A: I think this should works:
[globalFilterFields]="['engine.type']"

Add other fields if you want :
'engine.type', 'engine.power'


text:
Q: NullReferenceException using two constructor class I'm new here. I can't find solution to my problem anywhere. I'm writing a project to school. I have two forms. In first form, I have a DataGridView object, when I'm storing data in a SQL Server database. I'm passing usernames from DataGridView to second form using code:
List<string> usersList = new List<string>();

for (int i = 0; i < dataGridViewUsers.RowCount; i++)
{
    usersList.Add(dataGridViewUsers.Rows[i].Cells[1].Value.ToString());
}

AddFileForm addFile = new AddFileForm(usersList);
addFile.Show();

In second form in have following code:
    private List<string> userNames;
    private Files file;

    public AddFileForm()
    {
        file = new Files();
        userNames = new List<string>();
        InitializeComponent();
    }

    public AddFileForm(List<string> _userNames)
    {
        this.userNames = _userNames;
        InitializeComponent();
        listBoxUserList.DataSource = _userNames;
    }

    private AddFileForm(Files _file)
    {
        this.file = _file;
        InitializeComponent();
        listBoxUserList.SelectedValue = _file.userName;
        listBoxItems.SelectedValue = _file.directory;
    }

Passing data from first form works fine, but the problem starts when I try to pass data from listBoxUserList and listBoxItems to database using stored-procedures. I'm adding data to listBoxItems manually. NullReferenceException occur on a button click, here:
private void buttonAdd_Click(object sender, EventArgs e)
{
    if (listBoxUserList.SelectedItems.Count != 0 && listBoxItems.SelectedItems.Count != 0)
    {
            file.userName = listBoxUserList.SelectedValue.ToString();
            file.directory = listBoxItems.SelectedValue.ToString();
                try
                {
                    DBConnection connection = new DBConnection();
                    connection.AddFile(file);

                    MessageBox.Show("File added to database.");
                }
                catch (Exception)
                {
                    MessageBox.Show("Failed database connection!");
                }
            }
            else
            {
                MessageBox.Show("First, select items to add to database");
            }
        }

Value from both listBoxes is not null, I have checked this. The main problem probably is in class constructor. My stored procedure works fine, when I was comment constructor who passing data from first form, it perfectly passing data to database. So, what's wrong? What i should do with constructors of class, it will work property in both cases?
I'm pasting error details
System.NullReferenceException was unhandled
  HResult=-2147467261
  Message=Odwołanie do obiektu nie zostało ustawione na wystąpienie obiektu.
  Source=FilesEncoding
  StackTrace:
       w FilesEncoding.AddFileForm.buttonAdd_Click(Object sender, EventArgs e) w C:\Users\Grabarz\Documents\Visual Studio 2010\Projects\FilesEncoding\FilesEncoding\AddFileForm.cs:wiersz 110
       w System.Windows.Forms.Control.OnClick(EventArgs e)
       w System.Windows.Forms.Button.OnClick(EventArgs e)
       w System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       w System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       w System.Windows.Forms.Control.WndProc(Message& m)
       w System.Windows.Forms.ButtonBase.WndProc(Message& m)
       w System.Windows.Forms.Button.WndProc(Message& m)
       w System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       w System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       w System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       w System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       w System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       w System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       w System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       w System.Windows.Forms.Application.Run(Form mainForm)
       w FilesEncoding.Program.Main() w c:\users\grabarz\documents\visual studio 2010\Projects\FilesEncoding\FilesEncoding\Program.cs:wiersz 18
       w System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       w System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       w Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       w System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       w System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       w System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       w System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       w System.Threading.ThreadHelper.ThreadStart()
  InnerException:

A: I'm not sure, is this code correct, but finally it start to work! I've got similar solution, here but I don't know what's are diffrents between constructor in my topic question, and this. In my opinion my first record should work perfectly too. Here's my code:
private string userName;
private string fileDirectory;

public AddFileForm(Files _file) : this(_file.userName, _file.directory) {  }
public AddFileForm(string user, string directory)
{
    userName = user;
    fileDirectory = directory;
    InitializeComponent();
}

private void buttonAdd_Click(object sender, EventArgs e)
{
    userName = listBoxUserList.SelectedItem.ToString();
    fileDirectory = listBoxItems.SelectedItem.ToString();
        try
        {
            Files file = new Files();
            file.userName = userName;
            file.directory = fileDirectory;
            DBConnection connection = new DBConnection();
            connection.AddFile(file);
        }
        catch (Exception)
        {
            MessageBox.Show("Failed database connection!");
        }
    }


text:
Q: Move Windows 10 folders to another disk to free up space I have a 60GB SSD that is near full and Windows is having trouble installing updates.
I feel like I picked all the low hanging fruit ages ago; documents, programs and pretty much anything that is not Windows related is already installed on another drive. I have cleaned up old Windows installations
The biggest culprits are Windows and the AppData folder. Windows and User folders take up about 50GB.

I've thought about moving the User folder to another disk but multiple sources tell me this is a bad idea.
What is a safe way to free up disk space without too much headache?
Also, I don't see Windows/Installer in my File Explorer even with hidden folders visible. I can still navigate to it via the address bar. I vaguely remember having moved this in the past with mklink to another drive but maybe that never happened or got undone somehow? Could something like mklink be a viable solution to this problem (and how)?


text:
Q: Why do we use Jacobi method? If Gauss-Seidel is more efficient than Jacobi method, then why do we need to learn it? Does it have any advantages over Gauss-Seidel?

A: One of the disadvantages of Gauss-Seidel method is that successive updating of all the entries makes parallelizing this algorithm much harder/inefficient.


text:
Q: Splitting digits from a packed-decimal field I have a 7-digit packed-decimal field on my file. How can I define data items that would extract/separate these 7 digits?
For example I want to have the first two digits in one data item and the other digits in another, so I can manipulate them later.

A: In some other languages one of the things which may be common would be to "divide by a multiple of 10", an appropriate multiple, of course.
However, don't ever consider that with COBOL. A "divide" is "expensive".
       05  input-packed-decimal
                            PACKED-DECIMAL PIC 9(7).

Then:
       05  FILLER
           REDEFINES input-packed-decimal.
           10  ipd-split-two-and-five
                            PACKED-DECIMAL PIC 99V9(5).

   01  two-digits                          PIC 99.
   01  five-digits                         PIC 9(5).
   01  FILLER
       REDEFINES five-digits.
       05  five-digits-as-decimals         PIC V9(5).

       MOVE ipd-split-two-and-five  TO two-digits
                                       five-digits-as-decimals

Then you are able to use two-digits and five-digits for whatever you want.
Another way:
   01  ws-input-seven                      PIC 9(7).
   01  FILLER
       REDEFINES ws-input-seven.
       05  two-digits                      PIC 99.
       05  five-digits                     PIC 9(5).

       MOVE input-packed-decimal    TO ws-input-seven

The first way will also work for signed source fields (just put an S in the appropriate place in each PICture clause).
The second will not work with signed fields, because the source sign will no propagate to the two-digits field because the MOVE is not even aware that there is such a field.
Take care when REDEFINESing PACKED-DECIMAL or BINARY fields (on an IBM Mainframe, these can also have USAGE COMP-3 and COMP/COMP-4/COMP-5). Always, when defining with the same, or similar, USAGE, define the same number of digits. For a REDEFINES field the compiler will always assume that you know what you are doing, so it will not do any "truncation of source" for you. So you have to ensure that you are not, explicitly or implicitly, expecting truncation of source when you use fields subordinate to a REDEFINES.
To get the second digit, don't ever do this:
       05  FILLER
           REDEFINES input-packed-decimal.
           10  ignore-one-use-2nd-next-five
                            PACKED-DECIMAL PIC 9V9(5).

To get the second digit, use PACKED-DECIMAL PIC 99V9(5) as before, but define the receiving field with only one digit position. The compiler will happily then generate code to do the truncation you expect.
If you are "unable to use REDEFINES" you'll have to create a new field in the WORKING-STORAGE with the same characteristics as your input field, and use that.
The data-names I've used here are solely for this general explanation. Use good, descriptive, names to your task. If the first two digits are part-type, and the last five are part-number, make sure that is clear fro your naming.
Don't name them "Var(n)" or similar and don't give them names which are misleading.

A: 01  the-array.
03  filler pic x(02) value '00'.

03  filler pic x(02) value '01'.

03  filler pic x(02) value '02'.

and so on, until
03  filler pic x(02) value 'FF'.

01  two-array redefines the-array.
03  harry occurs 256 pic x(02).

91  sub1.
03  filler pic x(01) value low-values.

93  sub1-byte2 pic x(01).

01  sub2 redefines sub1 comp.
01  pd pic x(04).
01  pub pic 9(04).
01  eggs.
03  eggs1 pic x(01).

03  eggs2 pic x(01).

perform varying pub
from 1 by 1
until pub > 4
move pd(pub:1) to sub1-byte2

move harry(sub2 + 1) to eggs

display eggs1 egg2

end-perform.
So an array of 256 2 byte fields with values of '00' thru 'FF'.
step thru the 4 byte field that holds your packed decimal field.
use each byte as a subscript into the array (add 1 to ensure '00' points to first field in array).
2 byte field pointed to has the values of the 2 nibbles that represent that byte from the packed decimal field.
the right hand nibble of the fourth byte in the packed decimal field is for the sign.


text:
Q: SQL WINDOW FUNC when no unique partition I have this table:

Date
ID
Product_A_Count
Product_B_Count

1
A
1
2

2
A
1
2

3
A
2
1

4
A
1
2

I want to convert it to:

Start_Date
End_Date
ID
Product_A_Count
Product_B_Count

1
2
A
1
2

3
3
A
2
1

4
4
A
1
2

Is there a way to do it by using just SQL? I've been trying out row_number and lag but none looks right (because the partition by combination of ID, Product_A_Count and Product_B_Count is not unique).
Many thanks for all suggestions!!

A: This is a type of gap-and-islands problem.  In this case, the difference of row numbers is probably the simplest solution:
select id, product_a_count, product_b_count, min(date), max(date)
from (select t.*,
             row_number() over (partition by id order by date) as seqnum,
             row_number() over (partition by id, product_a_count, product_b_count order by date) as seqnum_2
      from t
     ) t
group by id, product_a_count, product_b_count, (seqnum - seqnum_2);

There might be simpler solution if, for instance, the dates are all regularly spaced.


text:
Q: Why won't \marginpar wrap it's text? I'm using miktex 2.8 on Windows. For some reason, the \marginpar command has stopped working. It used to work as expected, but not the lines will not wrap. I have set marginparwidth to 1in and still the lines will not wrap, they just go right off the page (or right into the text for margin pars on the odd pages). If I change marginparwidth to something smaller, I see the text move, so I think the value is being recognized, but I can't figure out what changed so that the text is not wrapping.

A: So the problem was \usepackage{pdfsync}. Evidently this is the old way to do PDF synchronization. The new way is to add "-synctex=-1" to the command for pdfTex. Using the synctex switch for pdflatex does not screw with the marginpar command, but using the pdfsync package does. Weird.


text:
Q: How do I collect many pieces stored in html files into one template in Django? Supposing I have a page to display that consists of several pieces like this:

    1st piece

    2nd piece

    3rd piece

I want to keep each piece in a separate html-file:

1st piece

2nd piece

3rd piece

And add them into a base template using Django templates:

    {% block piece1 %}... import piece1.html ...{% endblock %}

    {% block piece2 %}... import piece2.html ...{% endblock %}

    {% block piece3 %}... import piece3.html ...{% endblock %}

How do I manage base.html to make it import all pieces by their names in Django? Or maybe there's a different approach to do it easily?
In my project I'm going to use a complicated structure of pieces and big size for each one. This is why I want to keep each piece in a separate html-file.

A: Use the include tag.
{% include 'piece1.html' %}
{% include 'piece2.html' %}


text:
Q: Find the order of $\sqrt[3]{2}(1+\zeta_3)$ and $\sqrt[3]{2}(1-\zeta_3)$ over $\mathbb{Q}$ Find the order of $\sqrt[3]{2}(1+\zeta_3)$ and $\sqrt[3]{2}(1-\zeta_3)$ over $\mathbb{Q}$
I am not sure how to tackle this problem.
MY notes:
$\mathbb{Q}(\sqrt[3]{2},\zeta_3)$ has degree 6. The degree of both elements is $2$ over $\mathbb{Q}(\sqrt[3]{2})$. I have never done a problem like this so I am not sure how to proceed. The first one I can do as it is a root of $x^3+2$. How do i deal with the second one

A: While not as quick as the suggestions in the comment, here is another way to deduce that $\mathbb{Q}(\sqrt[3]{2}(1 + \zeta_3)) = \mathbb{Q}(\sqrt[3]{2},\zeta_3)$: Note that
$$[\sqrt[3]{2}(1 + \zeta_3)]^3 =2(1 + \zeta_3)^3 = 2 + 6\zeta_3 + 6 \zeta_3^2 + 2\zeta_3^3 $$
Since $\zeta_3^3 = 1$, we have that $[\sqrt[3]{2}(1 + \zeta_3)]^3 = 4 + 6\zeta_3 + 6\zeta_3^2$. After subtracting $4$ and dividing by $6$, we see that $\zeta_3 + \zeta_3^2 \in \mathbb{Q}(\sqrt[3]{2}(1 + \zeta_3))$. Note that,
$$(\zeta_3 + \zeta_3^2)^2 = \zeta_3^2 + 2\zeta_3^3 + \zeta_3^4 = 2\zeta_3^2 + 2 $$
After dividing by $2$ and subtracting $1$, we see that $\zeta_3^2 \in \mathbb{Q}(\sqrt[3]{2}(1 + \zeta_3))$. After squaring we see that $\zeta_3 \in \mathbb{Q}(\sqrt[3]{2}(1 + \zeta_3))$. You can now deduce that $\sqrt[3]{2} \in \mathbb{Q}(\sqrt[3]{2}(1 + \zeta_3))$. Hence,
$$\mathbb{Q}(\sqrt[3]{2}(1 + \zeta_3)) = \mathbb{Q}(\sqrt[3]{2},\zeta_3)$$
A similar technique works with $\sqrt[3]{2}(1 - \zeta_3)$


text:
Q: python Generate an alphanumeric Sequence I need a custom alphanumeric sequence for a custom_id on django model for each Product.
def save(self, *args, **kwargs):
    if self.custom_id is None:
        self.custom_id = f"{custom_seq(self.id)}"
    return super(Product, self).save(*args, **kwargs)

I want custom Alphanumeric sequence to be generated as:
eg. letters=4, digits=3 then,
'AAAA001', 'AAAA002', 'AAAA003'... 'ZZZZ999'
if letters =3 and digits =4
'AAA0001', 'AAA0002'... 'ZZZ9999'

Here is my try:
def custom_seq(pk, letter=4, digits=3):
  init = ''
  alpha = string.ascii_uppercase
  for i in alpha:
    for j in alpha:
      for k in alpha:
         for l in alpha:
            yield(i+j+k+l)

This will genrate only 'AAAA'  to 'ZZZZ', but not sure how to add digits in front of it and make this dynamic.

A: You can use itertools.product in order to get the combinations of alphabets and digits easily.
import string
import itertools

def custom_seq(pk, letter=4, digits=3):
    alpha = string.ascii_uppercase
    digit = string.digits
    alpha_list = [alpha]*letter
    digit_list = [digit]*digits
    for i in itertools.product(*alpha_list):
        for j in itertools.product(*digit_list):
            yield "".join(i + j)
            # print("".join(i + j))


text:
Q: javascript nested typed object to json and back For serialisation purposes, I was wondering if there is a library for converting typed objects into plain json and back.
the naive solution would be something like:
function Person( name, sex, age ) {
    this.name = name;
    this.sex = sex;
    this.age = age;
}

Person.prototype.serialize = function () {
    var obj = this;
    return '{ ' + Object.getOwnPropertyNames( this ).map( function ( key ) {
        var value = obj[key];
        if ( typeof value === 'string' ) { value = '"' + value + '"'; }
        return '"' + key + '": ' + value;
    }).join( ', ' ) + ' }';
};

Person.deserialize = function ( input ) {
    var obj = JSON.parse( input );
    return new Person( obj.name, obj.sex, obj.age );
};

(from: Javascript Serialization of Typed Objects)
Is there a simple solution for nested types?
Edit:
Suppose I have a set of Models (like backbone models):
User, Task, etc.
Each model supports toJson, and fromJson functions.
toJson returns a plain object with the model's attributes.
fromJson takes a plain object and creates a new model object.
I'm looking for a solution which can restore the types. For example by saving a '_prototype' property with the name of the original type.
Edit:
I just found this: https://stackoverflow.com/a/14028886/1163440
This is what I had in mind.. but I am looking for nested types

A: You can use the JSON.stringify with a replacer and JSON.parse with a reviver like this:
function Person (name) {
    this.name = name;
}

var p = new Person('haaa');

p.children = [new Person('haaa jr')]

var str = JSON.stringify(p, function replacer (key, value) {
    //warning this change the object. maybe use $.extend or xtend, or a deep clone library
    value.__type = value.constructor.name
    return value;
});

var parsed = JSON.parse(str, function reviver (key, value) {
    if (value.__type === 'Person') {
      var p = new Person(value.name);
      Object.getOwnPropertyNames(value).forEach(function (k) {
        p[k] = value[k];
      });
      return p;
    }
    return value;
});

console.log('is children a Person?', parsed.children[0] instanceof Person);

The serialized object will look like this:
{
  "name": "haaa",
  "children": [
    {
      "name": "haaa jr",
      "__type": "Person"
    }
  ],
  "__type": "Person"
}

Replacer and reviver are very powerful extensibility points.


text:
Q: What is the spinning circle on IPhone data Does the spinning circle when accessing data from the internet on an IPhone mean you are using data?  It seems it's always spinning non stop on Facebook.  I am concerned this indicates data usage.

A: Yes it does.  To see how much, or to prevent data access to certain apps when on mobile/cellular visit Settings > Mobile (or Cellular) and scroll to the list of apps at the bottom, here you can see what is enabled for mobile access, and how much data has been used since the last reset point.
You can reset the stats back to zero from the same page any time you like.  This is useful if you know for example that your Data billing cycle starts on the 17th, and you can set yourself a reminder to reset it on that date.
Note that the above is only really useful on iOS7, you don't say what version you use, if you use an older version the same rough idea applies only it's not split by individual applications, and you can't get granular detail or control.


text:
Q: Scilab Invalid Index I already new learn Scilab. I want to ask about, why when I used matrix in my script it showed "invalid index" on my compiler. In this case, I want to rewrite my python code into the scilab code.
Here is my scilab code and picture I want to get. Thank you
// Semiconductor Parameter Definition
k               = 8.617333262145e-5;                                            // Boltzmann Constant                        (eV/K)
q               = 1.602e-19;                                                    // Elementary charges
h               = 6.62606957e-34;                                               // Planck constant                           (eV/K)
m0              = 9.10938291e-31;                                               // Mass of electron                          (kg)
mn              = 1.08*m0;                                                      // Si electron effective mass                (kg)
mp              = 0.56*m0;                                                      // Si hole effective mass                    (kg)
Temp            = 1000 + 273;                                                   // Temperature                               (Kelvin)
Alpha           = 4.73E-4;                                                      // Fitting alpha param                       (eV/K)
Beta            = 636;                                                          // Fitting beta param                        (K)
Eg_o            = 1.166;                                                        // Si - Band gap reference room temp         (eV)
Eg              = Eg_o - ((Alpha*Temp^2)/(Temp+Beta));                          // Si - Band gap for temp dependence         (eV)

// Difussion Parameter for Boron Doped
Dixo            = 0.037e-4;                                                     // m2/sec
Dixe            = 3.46;                                                         // eV
Dipo            = 0.72e-4;                                                      // m2/sec
Dipe            = 3.46;                                                         // eV
Dix             = Dixo*exp(-Dixe/(k*Temp));
Dip             = Dipo*exp(-Dipe/(k*Temp));

// Intrinsic Semiconductor for Temperature Dependence
Nc              = 2*(2*%pi*mn*k*Temp/h^2)^1.5;                                  // Density of States in the Conduction Band
Nv              = 2*(2*%pi*mp*k*Temp/h^2)^1.5;                                  // Density of States in the Valance Band
ni              = sqrt(Nc*Nv*exp(-Eg/(k*Temp)));                                // Intrinsic Carrier Concentration
// Initialization Parameter
iter_max        = 10;                                                           // Iteration Maximal
crit            = 1e-12;
mesh_time       = 500;                                                          // Number of Mesh for time
mesh_length     = 100;                                                          // Mesh length for x
time_max        = 500;                                                          // total time                                    (second)
length_max      = 2e-6;                                                         // length x                                      (meter)
dtime           = time_max/mesh_time;                                           // step-size for time                            (second)
dlength         = length_max/mesh_length;                                       // step-size for x                               (meter)

// Doping Concentration for Semiconductor
N_d              = 1e18;                                                        // Carrier concentration for substrate          (cm-3)
N_a              = 1e15;                                                        // Carrier concentration for borond doped       (cm-3)

// Variables for Making Matrix
x               = zeros(mesh_length);                                           // Interval of mesh length
times           = zeros(mesh_time);                                             // Interval of mesh times
Nd              = zeros(mesh_length);                                           // Substrate Donor
Na              = zeros(mesh_length);                                           // Acceptor Dopant
N_carr          = zeros([mesh_length, mesh_time]);                                // Quasi-equilibrium for carrier
Diff            = zeros([mesh_length, mesh_time]);                                // Non-dimeNdion parameter for Diffusion
C               = zeros([mesh_length, mesh_time]);                                // Carrier concentration

/////////////////////////////////////////////////////////////// Forward Difference Method \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Initial Concentration at t = 0
for i = 1:mesh_length
    x(i) = -length_max/2 + i*dlength                                           // Interval for length semiconductor
    if i > 1:(mesh_length/2) then                                                   // Right-side of the half x-grid
        Nd(i)  = 0                                                            // Donor Substrate                              (cm-3 to m-3)
        Na(i)  = N_a*1e6                                                       // Acceptor dopant                              (cm-3 to m-3)
        C(i,0) = abs(Nd(i) - Na(i))                                            // Initial Concentration
    else                                                                        // Left-side of the half x-grid
        Nd(i)  = N_d*1e6;                                                       // Donor Subtrate                               (cm-3 to m-3)
        Na(i) = N_a*1e6;                                                       // Acceptor dopant                              (cm-3 to m-3)
        C(i,0) = abs(Nd(0) - Na(0));
    end,
end

A: In Scilab the index for matrices starts from 1 not from 0


text:
Q: How to enable extensions through terminal? Is there a way to enable and disable extensions in version 1.x via the command line?
How can I enable an extension through terminal?
What is the command?

A: There is no CLI command for Magento 1 extensions as this was added in Magento 2.  If you check the file from the installed extension found in app/etc/modules/Vendor_Module.xml, there will be a node <active>true</active> that should be true when enabled and false when disabled.  Additionally, there is a data-value in core_config_data for each module that should be 0 if the extension is enabled and 1 when it is disabled.  You can select that with the following query:
SELECT *
FROM core_config_data
WHERE path = 'advanced/modules_disable_output/Vendor_Module';

From there, just make sure your cache is cleared, log out & back in.

A: You can use this tool: https://github.com/netz98/n98-magerun
$ n98-magerun.phar dev:module:disable MyVendor_MyModule
$ n98-magerun.phar dev:module:disable --codepool="community"


text:
Q: Is there any method to call class member functions? Is there any method that I can call display function of Purchase class.
#include <iostream>
#include<stdio.h>
#include<string>
using namespace std;
class Purchase
{
private:
string userName;
int countOfItems;
float amount;
float static totalAmt;
int static totalCountOfItems;

public:

void display(Purchase obj[],int n)
{
    for(int i=0;i<n;i++)
    {
        setTotalAmt(obj[i].getTotalAmt()+obj[i].getAmount());
        setCountOfItems(obj[i].getCountOfItems()+obj[i].getCountOfItems());
    }
    cout<<"Total Amount Received :"<<getTotalAmount();
    cout<<"Total Number of Items sold :"<<getTotalCountOfItems();
}
};

getters and setter are already member functions.
How can i call display function in main function
My main function looks like this:
#include <iostream>
#include<string>
#include<stdio.h>
#include "Purchase.cpp"
using namespace std;
int main()
{
    int n;
    string userName;
    int countOfItems;
    float amount;
    cout<<"Enter the Number of customers :";
    cin>>n;
    Purchase P[n];
    for(int i=0;i<n;i++)
    {
        cin.ignore();
        cout<<"Enter the Name of the customer :";
        getline(cin,userName);
        P[i].setUserName(userName);
        cout<<"Enter the No of Items purchased :";
        cin>>countOfItems;
        P[i].setCountOfItems(countOfItems);
        cout<<"Enter the purchase amount :";
        cin>>amount;
        P[i].setAmount(amount);
    }
    cout<<"Purchase Details :";
    for(int i=0;i<n;i++)
    {
        cout<<"Customer "<<i+1<<" :"<<P[i].getUserName()<<endl;
        cout<<"No of Items purchased :"<<P[i].getCountOfItems()<<endl;
        cout<<"Purchase amount :"<<P[i].getAmount()<<endl;
    }
    cout<<"\n";
    return 0;
}

At last i have to add calling of display function so that i can add amount and countofitems of every object.

A:
Is there any method to call class member functions?

You could take the address of a member function and pass that later.
But with C++11 or better (read n3337, the C++11 standard), please read more about C++ then consider using lambda-expressions. Of course use <algorithm> and <functional>  standard headers.
Take also time to read more about standard containers and strings.

void display(Purchase obj[],int n)

Why can't you use a void display_vect(std::vector<Purchase>&vec); ? If you cannot change the API of display, consider calling your display_vect from your display member function.
Read about the rule of five.

A: I'm not completely sure what the issue is, or what you've been asked to do. But it's clear that display should not be a member function of Product. Member function of Product should be concerned with one particular product but display is printing all products, so it should be a stand-alone functon not a member function. Your code should look like this
class Product
{
    ...
};

void display(Purchase obj[],int n)
{
    ...
}

Then calling it from main is trivial.
int main()
{
    ...
    display(P, n);
}


text:
Q: Import XML data using powershell I have got an excel file which happens to be an XML table, I have saved it as an xml file instead and whilst trying to use powershell to import it to a SQL database. It is coming up with blank values.
<?xml version="1.0"?>
 <RecordsExport xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <RecordsExport>
     <ResultSet>
       <SRN>1</SRN>
       <Name>Tom</Name>
       <Gender>Male</Gender>
       <ChangeDate xsi:nil="true" />
    </ResultSet>
    <ResultSet>
      <SRN>2</SRN>
      <Name>Jack</Name>
      <Gender>Male</Gender>
      <ChangeDate xsi:nil="true" />
    </ResultSet>
  </RecordsExport>
</RecordsExport>

Powershell code
$xmldata = Get-Content -Path 'C:\temp\test.xml'
 $import_data = foreach ($data in $xmldata.RecordsExport.ResultSet){

 [PSCustomObject]@{
     SRN = $data.SRN
     Name= $data.Name
     Gender = $data.Gender
     ChangeDate = $data.ChangeDate
 }

 }

A: Simply,
$xml_file = get-content "C:\TEMP\test.xml"
$xml_file = [xml]$xml_file

Then, example in your case :
$xml_file.RecordsExport.ResultSet

To print Result Set.


text:
Q: Laravel - Installing packages that were installed with composer on live server I have a laravel project on namecheap shared server, I have set up everything and it is working there. But after that, I have added locally on my machine to the project imagecache intervention package with composer. I don't know how to install it on the server though, I have tried with running composer commands through ssh:
php composer require intervention/imagecache

But I got an error:

Could not open input file: composer

Since, their support told me that they actually have composer uploaded in the folder public_html and not where my project is and that is public_html/myProject if that is the problem. Since I have no idea, how the composer is installed and setup there, I wonder how can I install this package. I have also tried by just uploading the whole directory of the package from my local vendor folder in the project to the production server, but that didn't work either, images were still not visible when I was using imagecache route. How can I fix that?

A: Run this: php -c php.ini composer.phar install
First You have to create php.ini file with this info.
max_execution_time = 300
max_input_time = 300
memory_limit = 512M
suhosin.executor.include.whitelist = phar
detect_unicode = Off

A: If you have ssh then you can create a folder where ever you wan't.
It is better if you put it in the same level that your public folder and then install composer inside this folder:
with curl
curl -sS https://getcomposer.org/installer | php

if you don't have curl or the server has restrictions you can use:
php -r "readfile('https://getcomposer.org/installer');" | php

or you can "Manual Download" the composer.phar and upload it trough ftp
https://getcomposer.org/download/
Then you need to give execution rights to the composer.phar file and you
chmod a+x composer.phar

can also create an alias to run composer from your public folder
alias composer="path/to/composer/composer.phar"

This alias will work until you close your console.  In some shared servers you will see a file call: .bashrc where you can put the alias


text:
Q: Perform Aggregate by grouping in Object list using LINQ I need to calculate the Aggregate of a certain property from an object list by grouping the objects based on another property.. For example, I have a list of 5 objects as below:
list<cls> Objlist = new list<cls>();

 Obj1.Name="earth";
 Obj1.Value = 10;
 objlist.add(Obj1);

 Obj2.Name="sun";
 Obj2.value = 15;
 objlist.add(Obj2);

 Obj3.Name = "earth";
 Obj3.Value = 25;
 objlist.add(Obj3);

 Obj4.Name = "earth";
 Obj4.Value = 35;
 objlist.add(Obj4);

 Obj5.Name="sun";
 Obj5.value = 50;
 objlist.add(Obj5);

What I need is another list to have the avg value of earth and sun objects.. How this can be accomplished using LINQ?

A: Average is what you need from LINQ, use GroupBy to group by Name first:
var result = Objlist.GroupBy(x => x.Name)
            .Select(g => new {
                                 Name = g.Key,
                                 Value = g.Average(o => o.Value)
                             });


text:
Q: What does this mean: Object of class WP_Error could not be converted to string When I click on preview a post, I get the following error:
Catchable fatal error: Object of class WP_Error could not be converted to string in functions.php on line 288
The line 288 is as follows
echo get_category_parents($cat, TRUE, '' . $delimiter . '');

Any ideas on this please?

A: The only way that function returns an instance of WP_Error is if $cat (in your example) has an empty value. You need to check the return before doing anything with it. Replacing that line with this should fix the problem:
echo is_wp_error( $cat_parents = get_category_parents($cat, TRUE, '' . $delimiter . '') ) ? '' : $cat_parents;


text:
Q: Silverlight 4 MediaElement play sound I converted a local sound file to a resource, which built this in my XAML:
<UserControl.Resources>
    <my:Uri x:Key="SoundFiles">file:///c:/Audio/HebrewDemo/Shalom.wav</my:Uri>
</UserControl.Resources>

I did this by pasting a local disk mp3 filename into source, then clicked on the "dot" by source and chose "Extract Value to Resource".
When I run, it tells me that "Uri" is not valid, and sure enough, in the Intellisense, I see other elements that start with "uri" but not just URI by itself.
In the real world I want to specify a dynamic mp3 file name.  For example, I might have a database of foreign language words used for flashcards, I want to play a sound file on a URL.  But I thought I would try to walk before running...
Now I'm trying this:
    mediaElement1.Source = new Uri(
                     "http://HebrewResources.com/SoundFiles/Shalom.mp3",
                      UriKind.Absolute);
    mediaElement1.Play();

The status bar in the FireFox browser indicates some data being transferred from the website.  However, I never hear any sound. Could it just be an encoding issue?  If it is not encoded properly, would I get an error?
Also, can I put the Uri statement in the load or make it run in the background, so the user can read the screen, at the same time the sound file is downloading?  In other words, when he clicks the button to hear the soundfile, ideally it would already be preloaded for him.  In this language-learning app, the user will see a word in a foreign language, and try to pronounce it himself, then he will click the "Play" button to hear the sound to check his results.

A: The first code which points to the local file won't work in a normal Silverlight application because of Silverlights "sanboxed" security model. Running a normal Silverlight application in your browser, you can't access local resources like you can if you were running an installed winforms/WPF application. Have a look at this video tutorial http://www.silverlight.net/learn/videos/all/local-file-access/, if you want to learn more about accessing local files using Silverlight.
In regards to your second piece of code, it should work, so quite possibly it's an encoding issue, and no unfortunately you often don't get any errors for things like that.
I created a sample app and pointed it at your mp3 file and it' wouldn't work, however a quick search for sample mp3s, lead me to another freely available (first hit). Using the code/url below, it works ok.
myMediaelement.Source = new Uri("http://www.robtowns.com/music/blind_willie.mp3", UriKind.Absolute);

In regards to the loading, it will start downloading the file when it hits the code that sets the source of the mediaelement. So if you set the source for the media element in your constructor or in your loaded event, it will automatically start downloading in the background. Then you just call myMediaelement.Play(); on the button click event.
If you find using Firefox a bit limited, when it comes to determine what and when something like external files or webservices are being loaded. There's a great free tool called Fiddler (http://www.fiddlertool.com/fiddler/version.asp) which will let you monitor those things very easily.
Good luck :)


text:
Q: Rspec, how to expect to receive with only a subset of key value pair? I have a spec that expects a class to receive a method with some arguments. I only want to check for a subset of key/value pair from the arguement hash :
  it 'calls Stripe::Checkout::Session#create with the correct line items' do
      expect(Stripe::Checkout::Session).to receive(:create).with({
          line_items: [{
            price: "bla",
            quantity: 1
          }],
        }
      )
      subject
    end

here I only want to check that line_items is present in the argument hash with the correct value.
However the actual hash received has more values and I get the following error :
#<Stripe::Checkout::Session (class)> received :create with unexpected arguments
     expected: ({:line_items=>[{:price=>"bla", :quantity=>1}]}, *(any args))
          got: ({:allow_promotion_codes=>true, :automatic_tax=>{:enabled=>true}, :billing_address_collection=>"requir...vh.me/fr/thank-you?checkout_session_id={CHECKOUT_SESSION_ID}", :tax_id_collection=>{:enabled=>true}}, {:stripe_account=>"bla"})

How can I tell rspec to only check for the presence of a subset of key/value pair ?

A: You want hash_including, which matches subsets of hashes:
  ...to receive(:create).with(hash_including(
    line_items: [{
      price: "bla",
      quantity: 1
    }],
  )

See the docs: https://relishapp.com/rspec/rspec-mocks/v/3-2/docs/setting-constraints/matching-arguments


text:
Q: overflow:hidden but let the content auto-scroll I have a div where content is appended periodically to it via query's append(). As the content gets longer, it will eventually overflow the div. I want no scrollbars to appear when overflowed, but still have the content scroll up to show the new content below.
Is this possible? When I use overflow-x: hidden no scrollbar appears but the content is hidden.

A: If the size of the container is fixed, you could place the content inside an absolutely positioned wrap like so:

bah

and css:
.container {
    y-overflow: hidden;
    position: relative;
    height: 200px;
    width: 200px;
}

.wrap {position:absolute; bottom: 0; left:0;right:0;
}

http://jsfiddle.net/sXGd9/

A: append() will add to content at the end. You may want to prepend() new content, so the data get added before the old content.
As for overflow, you can set it to scroll so that scrollbars appear if necessary, or hidden so no scrollbars will appear but the content won't be visible. Otherwise  you can set it to visible so it will be visible but the scrollbars won't appear.
Do you want the overflowed content to be visible? If so set the overflow: visible otherwise set overflow: hidden (because you don't want scrollbars).
Anyway with this you wan't be able to scroll the content. If you need to scroll you have to build your own scroll system, adding event handler to your container.

A: If you have each appended content in your "#container" div wrapped in a seperate ".append" div you can do something like:
var pos = $('#container div:last').position();
$('#container').scrollTop(pos.top);

Is this helpfull?
Other solutions can be found in earlier post:
How do I scroll a row of a table into view (element.scrollintoView) using jQuery?


text:
Q: How to generate jhipster application into a different directory? When I run the following in jhipster-generator's /cli directory:
cd cli
node jhipster.js

I'm generating the application in the same directory (cli). How would I change this directory to somewhere else? For example, export all the generated files into a specific directory.
I believe the directory has something to do with this line of code in jhipster.js:
const localCLI = require.resolve(path.join(process.cwd(), 'node_modules', 'generator-jhipster', 'cli', 'cli.js'));

Note: I'm not running the application with "jhipster" command.


text:
Q: Preserve parent-child relationships when copying hierarchical data We have a table representing a tree of values associated with an entity (call it a project), where the ParentID column refers to the id column of a row's parent. The id column is an auto-incremented IDENTITY column and primary key. Root nodes have a ParentID of 0.
We want to be able to clone the data for a given project and have the resulting ParentIDs refer to the appropriate new ids for the copied values, in a way that meets the restrictions described below the example.
For example, copying the data for ProjectID 611 in the below table:
    id      ProjectID    Value         ParentID
--------------------------------------------------
     1      611           Animal        0
     2      611           Frog          1
    13      611           Cow           1
    14      611           Jersey Cow    13
    25      611           Plant         0
    29      611           Tree          25
    31      611           Oak           29

Should result in:
    id      ProjectID    Value         ParentID
--------------------------------------------------
     1      611           Animal        0
     2      611           Frog          1
    13      611           Cow           1
    14      611           Jersey Cow    13
    25      611           Plant         0
    29      611           Tree          25
    31      611           Oak           29
    32      612           Animal        0
    33      612           Frog          32
    34      612           Cow           32
    35      612           Jersey Cow    34
    36      612           Plant         0
    37      612           Tree          36
    38      612           Oak           37

Restrictions:

*

*Solution must work for SQL Server 2005. That is, we can't use MERGE (alas).

*We're not comfortable making assumptions about ids or how they compare to ParentIDs; the solution should apply, in principle, to ids/ParentIDs that are uniqueid, for example.

*We'd rather not add an additional column to the table. (My current solution adds an "OldId" column, which the copy procedure sets when copying rows. So I'm currently using a combination of INSERT-SELECT and UPDATE-FROM, joining the OldId column on the ParentID column to get the new id.)  We'd rather not pepper all of our hierarchical tables with OldId columns just to support this copy operation.

*Solution must be reasonably performant; my initial solution was going to be a complicated set of rescursive function calls and loops processing one item at a time. I quickly abandoned that route!

A: A CTE works nicely with MERGE, but is problematic in SQL Server 2005. Sorry for the misleading comment earlier.
The following shows how to clone a project (with multiple trees) and fix up up the parentage to separate the new forest from the old. Note that it does not depend on any particular arrangement of Id's, e.g. they need not be dense, monotonically increasing, ... .
-- Sample data.
declare @Projects as Table
  ( Id Int Identity, ProjectId Int, Value VarChar(16), ParentId Int Null );
insert into @Projects ( ProjectId, Value, ParentId ) values
  ( 611, 'Animal', 0 ),
  ( 611, 'Frog', 1 ),
  ( 611, 'Cow', 1 ),
  ( 611, 'Jersey Cow', 3 ),
  ( 611, 'Plant', 0 ),
  ( 611, 'Tree', 5 ),
  ( 611, 'Oak', 6 );
-- Display the raw data.
select * from @Projects;

-- Display the forest.
with IndentedProjects ( Id, ProjectId, Value, ParentId, Level, Path ) as
  ( -- Start with the top level rows.
  select Id, ProjectId, Value, ParentId, 0, Convert( VarChar(1024), Right( '000' + Convert( VarChar(4), Id ), 4 ) )
    from @Projects
    where ParentId = 0
  union all
  -- Add the children one level at a time.
  select P.Id, P.ProjectId, P.Value, P.ParentId, IP.Level + 1, Convert( VarChar(1024), IP.Path + '<' + Right( '000' + Convert( VarChar(4), P.Id ), 4 ) )
    from IndentedProjects as IP inner join
      @Projects as P on P.ParentId = IP.Id
  )
  select Space( Level * 2 ) + Value as [IndentedValue], Id, ProjectId, Value, ParentId, Level, Path
    from IndentedProjects
    order by Path;

-- Clone the project.
declare @OldProjectId as Int = 611;
declare @NewProjectId as Int = 42;
declare @Fixups as Table ( OldId Int, [NewId] Int );
begin transaction -- With suitable isolation since the hierarchy will be invalid until we apply the fixups!
insert into @Projects
  output Inserted.ParentId, Inserted.Id
    into @Fixups
  select @NewProjectId, Value, Id -- Note that we save the old Id in the new ParentId.
    from @Projects as P
    where ProjectId = @OldProjectId;
-- Apply the fixups.
update PNew
  set ParentId = IsNull( FNew.[NewId], 0 )
  -- Output the fixups just to show what is going on.
  output Deleted.Id, Deleted.ParentId as [ParentIdBeforeFixup], Inserted.ParentId as [ParentIdAfterFixup]
  from @Fixups as F inner join
    @Projects as PNew on PNew.Id = F.[NewId] inner join -- Rows we need to fix.
    @Fixups as FOld on FOld.OldId = PNew.ParentId inner join
    @Projects as POld on POld.Id = FOld.OldId left outer join
    @Fixups as FNew on FNew.OldId = POld.ParentId;
commit transaction;

-- Display the forest.
with IndentedProjects ( Id, ProjectId, Value, ParentId, Level, Path ) as
  ( -- Start with the top level rows.
  select Id, ProjectId, Value, ParentId, 0, Convert( VarChar(1024), Right( '000' + Convert( VarChar(4), Id ), 4 ) )
    from @Projects
    where ParentId =0
  union all
  -- Add the children one level at a time.
  select P.Id, P.ProjectId, P.Value, P.ParentId, IP.Level + 1, Convert( VarChar(1024), IP.Path + '<' + Right( '000' + Convert( VarChar(4), P.Id ), 4 ) )
    from IndentedProjects as IP inner join
      @Projects as P on P.ParentId = IP.Id
  )
  select Space( Level * 2 ) + Value as [IndentedValue], Id, ProjectId, Value, ParentId, Level, Path
    from IndentedProjects
    order by Path;

A: You can get the ParentID by adding the MAX(ID) to the old ParentID.
DECLARE @projectID INT
SET @projectID = 611

SET IDENTITY_INSERT YourTable ON
BEGIN TRANSACTION

DECLARE @maxID INT
SELECT @maxID= MAX(ID) FROM YourTable WITH (UPDLOCK,HOLDLOCK)

INSERT INTO YourTable(ID, ProjectID, Value, ParentID)
SELECT
    ID + @maxID,
    ProjectId + 1,
    Value,
    CASE
        WHEN ParentID > 0 THEN ParentID + @maxID
        ELSE 0
    END
FROM YourTable WITH (UPDLOCK,HOLDLOCK)
WHERE
    ProjectID = @projectID

COMMIT TRANSACTION
SET IDENTITY_INSERT YourTable OFF

You should use a transaction to lock the table. You could also add locking hints.


text:
Q: How to check if a syn::Field is a struct in rust proc_macro I have a proc_macro that produces a telemetry function to parse a structs member variables and it works great for non nested structs.  I have found that I need to recursively call my handle_named_field function on any syn::Field that is a struct.  The problem is that I cannot see a way to determine if a field is a struct or not, if I had a syn::Data variable it is trivial, like in my handle_data.
How can I check inside of handle_named_fields(fields: &syn::FieldsNamed) if a field is a struct or not?
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, parse_quote, DeriveInput};

#[proc_macro_derive(Telemetry)]
pub fn derive(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let output = parse_derive_input(&input);
    match output {
        syn::Result::Ok(tt) => tt,
        syn::Result::Err(err) => err.to_compile_error(),
    }
    .into()
}

fn parse_derive_input(input: &syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> {

    let struct_ident = &input.ident;
    let struct_data = parse_data(&input.data)?;
    let struct_fields = &struct_data.fields;

    let _struct_ident_str = format!("{}", struct_ident);
    let tele_body = match struct_fields {
            syn::Fields::Named(fields_named) => handle_named_fields(fields_named)?,
            syn::Fields::Unnamed(fields_unnamed) => {
                let field_indexes = (0..fields_unnamed.unnamed.len()).map(syn::Index::from);
                let field_indexes_str = (0..fields_unnamed.unnamed.len()).map(|idx| format!("{}", idx));
                quote!(#( .field(#field_indexes_str, &self.#field_indexes) )*)
            }
            syn::Fields::Unit => quote!(),
        };

    let telemetry_declaration = quote!(
        trait Telemetry {
            fn telemetry(self, header_stream: Arc<Mutex::<Box <std::io::Write + std::marker::Send + Sync>>>, data_stream: Arc<Mutex::<Box <std::io::Write + std::marker::Send + Sync>>>);
        }
    );

    syn::Result::Ok(
        quote!(
            use std::thread;
            use std::collections::VecDeque;

            #[derive(Serialize, Deserialize, Default, Debug)]
            pub struct VariableDescription {
                pub var_name_length: usize,
                pub var_name: String,
                pub var_type_length: usize,
                pub var_type: String,
                pub var_size: usize,
        }

        #[derive(Serialize, Deserialize, Default, Debug)]
        pub struct TelemetryHeader {
            pub variable_descriptions: VecDeque::<VariableDescription>,
        }

        #telemetry_declaration
        impl Telemetry for #struct_ident {
            fn telemetry(self, header_stream: Arc<Mutex::<Box <std::io::Write + std::marker::Send + Sync>>>, data_stream: Arc<Mutex::<Box <std::io::Write + std::marker::Send + Sync>>>) {
                        thread::spawn(move || {
                             #tele_body;
                        });
            }
        }
    )
    )
}

fn handle_named_fields(fields: &syn::FieldsNamed) -> syn::Result<proc_macro2::TokenStream> {
    let idents = fields.named.iter().map(|f| &f.ident);
    let types = fields.named.iter().map(|f| &f.ty);
    let num_entities = fields.named.len();
    let test = quote! (
                let mut tele_header = TelemetryHeader {variable_descriptions: VecDeque::with_capacity(#num_entities)};
                #(
                    if()
                        tele_header.variable_descriptions.push_back( VariableDescription {
                        var_name_length: stringify!(#idents).len(),
                        var_name: stringify!(#idents).to_string(),
                        var_type_length: stringify!(#types).len(),
                        var_type: stringify!(#types).to_string(),
                        var_size: std::mem::size_of_val(&self.#idents),
                    });

                )*
                header_stream.lock().unwrap().write(&bincode::serialize(&tele_header).unwrap()).unwrap();
                data_stream.lock().unwrap().write(&bincode::serialize(&self).unwrap()).unwrap();
        );
        syn::Result::Ok(test)
}

fn parse_named_field(field: &syn::Field) -> proc_macro2::TokenStream {
    let ident = field.ident.as_ref().unwrap();
    let ident_str = format!("{}", ident);
    let ident_type = &field.ty;
    if field.attrs.is_empty() {

                quote!(
                    if true {
                        println!("TRUE");
                    }
                println!("Var Name Length: {}", stringify!(#ident_str).len());
                println!("Var Name: {}", #ident_str);
                println!("Var Type Length: {}", stringify!(#ident_type).len());
                println!("Var Type: {}", stringify!(#ident_type));
                println!("Var Val: {}", &self.#ident);
            )
    }
    else {
        quote!()
    }
}

fn parse_data(data: &syn::Data) -> syn::Result<&syn::DataStruct> {
    match data {
        syn::Data::Struct(data_struct) => syn::Result::Ok(data_struct),
        syn::Data::Enum(syn::DataEnum { enum_token, .. }) => syn::Result::Err(
            syn::Error::new_spanned(enum_token, "CustomDebug is not implemented for enums"),
        ),
        syn::Data::Union(syn::DataUnion { union_token, .. }) => syn::Result::Err(
            syn::Error::new_spanned(union_token, "CustomDebug is not implemented for unions"),
        ),
    }
}


text:
Q: Whether there is a UDT backend for boost::asio? Please, tell to me are whether exist UDT protocol backend for boost::asio?
UDT is a reliable UDP based application level data transport protocol for distributed data intensive applications over wide area high-speed networks. ( http://udt.sourceforge.net/index.html )

A: TCP, UDP, and ICMP are supported by Boost.Asio. Other protocols can be implemented by extending the Protocol type requirements. There are several threads on the asio-users mailing list discussing adding support for SCTP, you may be able to use that as an example.

A: This may sound like a shameless plug... But we are currently developing a UDT library based on boost.asio, so that you can have an stream_socket API based on UDP.
Boost Asio Based UDT
At this point, the library is functional (you can async_connect/ async_accept / async_write / async_read stream of bytes between client and server), but we do not support messaging yet. You can use every major Boost.Asio toolkit features with it (e.g. futures, coroutines, and even using TLS above UDT)
The library is still pretty young and we encounter performance issues due to timer precision as discussed here.


text:
Q: HTML table  linked to Javascript how? I have an order form within an HTML table associated to some JavaScript verification logic. The current code works but I would like some enhancements to be implemented.
Currently, pressing the "verify" order button gives me the following output:

Line 0 = 1 Qty Line 1 = 4 Qty Line 2 = 2 Qty

Instead of showing table lines numbers followed by quantity value, I need the text to contain the actual products names. E.g. "Line 0 = 1" → "Apple = 1" …
I cannot really seem to figure it out can someone tell me how to do this?

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>Untitled Document</title>

  <FORM NAME="f">

            Order Form

            Item

            Qty

            Each

            Total

          Apple

            <INPUT NAME="line" TYPE="text" SIZE="5" VALUE="" ONKEYUP="count(this.form,0,5.95)">

          $ 5.95

            <INPUT NAME="line_sum" TYPE="text" SIZE="10" READONLY>

          Banana

            <INPUT NAME="line" TYPE="text" SIZE="5" VALUE="" ONKEYUP="count(this.form,1,10.95)">

          $ 10.95

            <INPUT NAME="line_sum" TYPE="text" SIZE="10" READONLY>

          Orange

            <INPUT NAME="line" TYPE="text" SIZE="5" VALUE="" ONKEYUP="count(this.form,2,20.95)">

          $ 20.95

            <INPUT NAME="line_sum" TYPE="text" SIZE="10" READONLY>

            <INPUT TYPE="button" VALUE="Reset" ONCLICK="init()">

            Grand Total :

            <INPUT NAME="grand_total" TYPE="text" SIZE="10" READONLY>

            <INPUT TYPE="button" VALUE="Press to Verify Order" ONCLICK="get_data(this.form)">

  </FORM>
  <FORM NAME="g" METHOD="post" ENCTYPE="text/plain" ACTION="mailto:user@isp">

            <TEXTAREA NAME="order" ROWS="5" COLS="35">


text:
Q: List items changing classes on hover So i have the following codes
HTML

Twitter

Twitter

Twitter

Twitter

CSS:
.social ul a {
  display: block;
  padding: 1em 1em;
  background-color: #fca311;
  color: white;
}

ul a .span-social {
  display: none;
  opacity: 0;
  margin-left: 5px;
  -webkit-transition: display .5s linear, opacity .33s linear;
  transition: display .5s linear, opacity .33s linear;
}

ul a .show {
  display: inline-block;
  opacity: 1;
}

JS:
            var x = document.getElementsByClassName('list-item');
            for (var i = 0; i < x.length; i++) {
                x[i].addEventListener('mouseover', () => {
                    var li = document.getElementsByClassName('span-social');
                    for (var i = 0; i < li.length; i++) {
                        var showli = li[i];

                        if (showli.style.display === "none") {
                            showli.className = "span-social show";
                        } else {
                            showli.className = "span-social";
                        }
                    }
                })
            }

But i can't make it work , i check it in the console , no errors caught. Tried to loop through the list and handle every item in particular ( to add the event mouseover ) but still , no effect.


text:
Q: How to display local-memory cache in Django Templates? I set the local-memory cache "message" as shown below:
from django.core.cache import cache

cache.set("message", "success", 300)

Then, I tried to display it in the Django Template "index.html" as shown below:
# "index.html"

{{ cache.get.message }}

But, "success" is not displayed.
So, are there any ways to display the local-memory cache in Django Templates?

A: Django's template system is not simply Python embedded into HTML. It has a few wrappers built-in for looping, conditionally rendering, etc.
From Django Docs:

If you have a background in programming, or if you're used to languages which mix programming code directly into HTML, you'll want to bear in mind that the Django template system is not simply Python embedded into HTML. This is by design: the template system is meant to express presentation, not program logic.

In order to get a value from the cache you need to run cache.get('key_name') which is not allowed from within a template.
You can retrieve the value you want to display in the view and pass it to its template directly.


text:
Q: Is it possible to sandbox and run C++ or C# code that's entered in a textfield in a browser? I'm diving into web development after ten years of desktop development and I'm experimenting with some testing concepts.  I was wondering if it's possible to sandbox and run C++ code that's entered in a textfield in a browser?  By that, I mean run the C++ or C# code on the backend webserver and return an analysis of the code.  Just to be clear, I don't mean run C++ or C# code that's intended to generate any kind of markup, but simply to blackbox test the C++ or C# block of code that's entered.

*

*How would you invoke the compiler, depending on the web server you're using?

*How could you sandbox the code to prevent malicious behavior?  If we're considering only one of the C variants, what about blacklisting/whitelisting specific functions and libraries to prevent malicious behavior?  Or would that blacklist be too long and too limiting to allow any fair amount of code to run?

These are some fairly high-level questions that I'm asking just because I'm having a hard time finding some direction, but I'm going to continue researching them right now.  Thanks so much in advance for your help!

A: You might find the codepad about page interesting.

A: # 1 is easy with C#. The Reflection capabilities of .NET allow you to compile and run code "on the fly." And here's a link to another good looking tutorial.
# 2 is a little more difficult but I suppose a basic sand boxing technique might involve executing a dynamic process under a limited, and therefore sand boxed account. Programmatically you could analyze the dynamicly built assembly's dependencies and not allow it to run if it used APIs in certain namespaces such as System.IO. This is non-trivial to say the least though.
C++ doesn't have reflection capabilities and so 3rd party libraries would be your best bet.

A: The Dinkumware site has something like this.
A simple Perl (or Python, ...) cgi could be used to invoke the compiler, parse it results, run the resulting executable if any and display it's results.
I would take a look at SELinux (maybe AppArmor?) for access controls. Maybe not allowing it write and read to/from the disk and limit it's running time. I don't know if the later can be done with SELinux, too.

A: If the server runs Linux, you may consider using chroot

A: We actually did just that with our product called iKnode. We are using this idea to create a Backend in the cloud.
We did this by creating a SandBox that takes an specific piece of code and executes it, captures the result and returns it to the user. This is all done in the cloud.

How would you invoke the compiler, depending on the web server you're
  using?

We did this by using the CodeDom utilities from the .Net framework. And we are exploring the coming 'compiler as a service' project coming from Microsoft code-named Roslyn.
This is a good starting point on using CodeDom to programatically compile.

How could you sandbox the code to prevent malicious behavior? If we're
  considering only one of the C variants, what about
  blacklisting/whitelisting specific functions and libraries to prevent
  malicious behavior? Or would that blacklist be too long and too
  limiting to allow any fair amount of code to run?

We did this by wrapping the code execution in a separate and limited AppDomain. You can see some examples here.
Additionally, you might want to look into the MonoSandBox, which was created for Moonlight, but it is a more robust SandBox. We are experimenting with it right now, to move away from AppDomains. We believe the MonoSandBox is way better than simple AppDomains.


text:
Q: Unwinding nested data responses into structs when a slice is part of the response I'd like to get some input into how you would all go about unwinding nested response data into custom structs. Below is an example of the data i'm being returned. I'm trying to get to the user data.
{
  "_links": {
    "self": {
      "href": "/api/v2/user-search/default/test?after=1585612800000&limit=20&offset=0&q=johnsmith%40test.com",
      "type": "application/json"
    }
  },
  "totalCount": 1,
  "items": [
    {
      "lastPing": "2020-04-30T02:56:10.430867577Z",
      "environmentId": "xxxx",
      "ownerId": "xxxx",
      "user": {
        "key": "johnsmith@test.com",
        "email": "johnsmith@test.com",
        "firstName": "john",
        "lastName": "smith"
      },
      "_links": {
        "parent": {
          "href": "/api/v2/users/default/test",
          "type": "application/json"
        },
        "self": {
          "href": "/api/v2/users/default/test/johnsmith@test.com",
          "type": "application/json"
        },
        "settings": {
          "href": "/api/v2/users/default/test/johnsmith@test.com/flags",
          "type": "text/html"
        },
        "site": {
          "href": "/default/test/users/johnsmith@test.com",
          "type": "text/html"
        }
      }
    }
  ]
}

Currently I'm doing the below
respData := map[string][]map[string]map[string]interface{}{}
json.Unmarshal(respBody, &respData)

userData := respData["items"][0]["user"]

I'd love to be able to unmarshal it into a custom struct but I can't seem to get it to work. The  nested slice that the user object sits within is what keeps throwing me off.

A: type User struct {
    Key       string `json:"key"`
    Email     string `json:"email"`
    FirstName string `json:"firstName"`
    LastName  string `json:"lastName"`
}

type LinkInfo struct {
    Href string `json:"href"`
    Type string `json:"type"`
}

type Item struct {
    LastPing      time.Time `json:"lastPing"`
    EnvironmentID string    `json:"environmentId"`
    OwnerID       string    `json:"ownerId"`
    User          User      `json:"user"`
    Links         LinkInfo  `json:"_links"`
    Self          LinkInfo  `json:"self"`
    Settings      LinkInfo  `json:"settings"`
    Parent        LinkInfo  `json:"parent"`
    Site          LinkInfo  `json:"site"`
}

type ItemDetails struct {
    Links      LinkInfo `json:"_links"`
    TotalCount int      `json:"total_count"`
    Items      []Item
}

Can you try this?
https://play.golang.org/p/S_CUN0XEh-d

A: From what you mentioned it sounds like you were on the right track. Your JSON is pretty large, so let me give you a smaller example similar to the part you mentioned you're having trouble with (the user object inside the items list).
type response struct {
  TotalCount int `json:"totalCount"`
  Items []*itemStruct `json:"items"`
}

type itemStruct struct {
  LastPing string `json:"lastPing"`
  User *userStruct `json:"user"`
}

type userStruct struct {
  Key string `json:"key"`
}

Basically to map to a JSON list of objects, just put a field like this in your struct: Objects []*structWhichMapsToMyObject
Edit: Here's the code running in Go Playground: https://play.golang.org/p/EvSvv-2s8y8

A: If you want this:
"user": {
    "key": "johnsmith@test.com",
    "email": "johnsmith@test.com",
    "firstName": "john",
    "lastName": "smith"
}

Declare a matching Go struct:
type User struct {
    Key       string `json:"key"`
    Email     string `json:"email"`
    FirstName string `json:"firstName"`
    LastName  string `json:"lastName"`
}

Then, since the user's parent object looks like this:
"items": [
    {
        "lastPing": "2020-04-30T02:56:10.430867577Z",
        "environmentId": "xxxx",
        "ownerId": "xxxx",
        "user": { ... },
        "_links": { ... }
    }
]

you also need to declare a matching Go struct for that (you can omit fields you don't need):
type Item struct {
    User User `json:"user"`
}

and then the parent of the parent:
{
    "_links": {
        "self": {
            "href": "/api/v2/user-search/default/test?after=1585612800000&limit=20&offset=0&q=johnsmith%40test.com",
            "type": "application/json"
        }
    },
    "totalCount": 1,
    "items": [ ... ]
}

and the matching Go struct for the grandparent, again, include only the fields you need:
type ResponseData struct {
    Items []Item `json:"items"`
}

Once you have this you can decode the json into an instance of ResponseData:
var rd ResponseData
if err := json.Unmarshal(data, &rd); err != nil {
    panic(err)
}
for _, item := range rd.Items {
    fmt.Println(item.User)
}

https://play.golang.com/p/7yavVSBcHQP


text:
Q: Kernel K nearest neighbours with sparse data I have a big sparse matrix (around 5 million of lines, 20 000 predictors), and I would like to run a kernelized k-NN on it. However, I don't know how to scale the data properly.
So far, I have scaled my data to the unit sphere (all my entries are nonnegative), and my k-NN was working perfectly.
(Note that centering and reducing the data with sparse matrix is problematic : Feature scaling for non-negative sparse data - and I cannot drop sparsity at all)
Now I would like to use a polynomial kernel :
$K(\mathbf{x},\mathbf{y}) = (1 + \langle \mathbf{x},\mathbf{y} \rangle)^d$
I end up working with the following distance : $d^2(f(x), f(y)) = K(\mathbf{x},\mathbf{x}) - 2K(\mathbf{x}, \mathbf{y}) + K(\mathbf{y} ,\mathbf{y})$
Now, say $d=2$ and I constrain my data to the unit sphere in the first place. Then $K(\mathbf{y},\mathbf{y})=K(\mathbf{x},\mathbf{x})=4$ and $K(\mathbf{x},\mathbf{y})$ becomes a monotonic function of $ \langle \mathbf{x},\mathbf{y} \rangle$, producing the same classification, regardless of $d$.
Now, if I don't scale the data at all, it will not be scaled in the represented space and I expect poor performance (since my classification will be driven by features with high order of magnitudes only).
The question is, how should I pre-process my data ? Is there a transformation of the kernel that would mimic the pre-processing for me ?


text:
Q: Is there a way to delete parts that meet the conditions in notepad++? I want to erase all parts of notepad++ between certain symbols.
For example, if there's a phrase that says [], I want to erase it all, whether it's [apple] or [basketball].
I have nothing to do with coding, so could you help me?

A: Is this something that could help you?
It explains find and replace with a regex.
https://superuser.com/questions/1003958/how-do-i-delete-text-between-2-characters
Ofcourse you need to change some things like:
Menu "Search" > "Replace" (or Ctrl + H)
Set "Find what" to [(.*?)]
Set "Replace with" to [] OR LEAVE BLANK
Enable "Regular expression"
Click "Replace All"
Good luck!

A: You can use replace with regular expression in replace dialog
Find  ([[^]]+])
Replace  []
Select "Regular expression" radiobutton
Click Replace All


text:
Q: Is there a Noetherian faithful module over a non-noetherian ring?
Let $R$ be a ring which is not Noetherian. Let $M$ be an $R$-module whose annihilator is trivial. Is it possible for $M$ to be Noetherian?

Intuitively, it seems like the answer should be no, as we should be able to somehow "embed" $R$ in $M$ via its action on $M$. However, I am not seeing a straightforward proof.

A: In the commutative case at least, if $M$ is faithful (trivial annihilator) and Noetherian, then $R$ is actually a Noetherian ring. So if $R$ is non-Noetherian, it cannot have a faithful Noetherian module.
The proof is basically as you suggest. Let $m_1,\ldots,m_n$ generate $M$ and define $j:R\rightarrow M^n$ by $j(r)=(rm_1,\ldots,rm_n)$. This is injective because the annihilator of $M$ in $R$ is zero. So $R$ is a submodule of the Noetherian module $M^n$, and thus is itself Noetherian as an $R$-module, i.e., $R$ is a Noetherian ring.
More generally, the same argument proves Theorem 3.5 of Matsumura's Commutative Ring Theory: if $M$ is Noetherian, then $R/\mathrm{ann}(M)$ is a Noetherian ring.
Though I'm rather incompetent with non-commutative rings, it seems to me that this argument works for non-commutative (unital) rings as well.


text:
Q: Getting value from a JSON file based on condition In python I'm trying to get the value(s) of the key "relativePaths" from a JSON element if that element contains the value "concept" for the key "tags". The JSON file has the following format.
    ]
  },
  {
    "fileName": "@Weizman.2011",
    "relativePath": "Text/@Weizman.2011.md",
    "tags": [
      "text",
      "concept"
    ],
    "frontmatter": {
      "authors": "Weizman",
      "year": 2011,
      "position": {
        "start": {
          "line": 0,
          "col": 0,
          "offset": 0
        },
        "end": {
          "line": 4,
          "col": 3,
          "offset": 120
        }
      }
    },
    "aliases": [
      "The least of all possible evils - humanitarian violence from Arendt to Gaza"
    ],

I have tried the following codes:
import json
with open("/Users/metadata.json") as jsonFile:
 data = json.load(jsonFile)
 for s in range(len(data)):
  if 'tags' in s in range(len(data)):
   if data[s]["tags"] == "concept":
    files = data[s]["relativePaths"]
    print(files)

Which results in the error message:
TypeError: argument of type 'int' is not iterable

I then tried:
with open("/Users/metadata.json") as jsonFile:
 data = json.load(jsonFile)
 for s in str(data):
  if 'tags' in s in str(data):
    print(s["relativePaths"])

That code seems to work. But I don't get any output from the print command. What am I doing wrong?

A: Figured it
import json

f = open("/Users/metadata.json")
# returns JSON object as
# a dictionary
data = json.load(f)

# Iterating through the json
# list
for i in data:
    if "tags" in i:
     if "concept" in i["tags"]:
      print(i["relativePaths"])

# Closing file
f.close()

A: Assuming your json is a list of the type you put on your question, you can get  those values like this:
with open("/Users/metadata.json") as jsonFile:
    data = json.load(jsonFile)
    for item in data:  # Assumes the first level of the json is a list
        if ('tags' in item) and ('concept' in item['tags']): # Assumes that not all items have a 'tags' entry
            print(item['relativePaths'])  # Will trigger an error if relativePaths is not in the dictionary

A: I think this will do what you want. It is more "pythonic" because it doesn't use numerical indices to access elements of the list — making it easier to write and read).
import json

with open("metadata.json") as jsonFile:
    data = json.load(jsonFile)
    for elem in data:
        if 'tags' in elem and 'concept' in elem['tags']:
            files = elem["relativePath"]
            print(files)


text:
Q: IBM MobileFirst 7.1 - Windows Phone Crashes We are developing a hybrid application using IBM MobileFirst 7.1 and testing on a Windows Phone device.
We are making a lot of tests and we have some random crashes on application startup
First crash log:
The header x-wl-clientlog-deviceId has an empty value.
   at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
   at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClasse.<EndGetResponse>b__d(Object sendState)
   at System.Net.Browser.AsyncHelper.<>c__DisplayClass1.<BeginOnUI>b__0(Object sendState)
   --- End of inner exception stack trace ---
   at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
   at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at IBM.Worklight.WLNativeXHRSender.responseCallback(IAsyncResult asyncResult)
   at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClass1d.<InvokeGetResponseCallback>b__1b(Object state2)}

Second crash log:
{System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
   at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.ValueCollection.Enumerator.MoveNext()
   at System.IO.IsolatedStorage.IsolatedStorageSettings.Save()
   at IBM.Worklight.WLConfig.writeWLPref(String prefName, String prefValue)
   at IBM.Worklight.WLCookieManager.storeCookiesInIsolatedStorage()
   at IBM.Worklight.WLNativeXHRSender.responseCallback(IAsyncResult asyncResult)
   at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClass1d.<InvokeGetResponseCallback>b__1b(Object state2)}

The device used for tests is a Nokia Lumia 1320 running on Windows Phone 8.1
The used IBM MobileFirst version is 7.1.0.00.20160513-1010
The used environment is Windows Phone (Silverlight)
These logs seems to be related to Worklight / MobileFirst native code. Can you confirm that ? Are there any fixes for that ?
Please advice

A: This question required opening an IBM support ticket, and is thus handled as PMR #74734,024,677. The IBM development team is investigating it using a sample application provided by the customer.


text:
Q: Save a Grid and it's contents in a file - WPF, C# I have a list of Grids with several rows and columns containing StackPanels. Each stack panel contains one or more Image objects, in some cases none at all and some Borders.
I would like to save these Grids to a file(sort of save functionality) and later get it back into memory and display it again.
What would be the best approach? Is there a way to do this operation in a simple way, or should I add every important data to the file, like the row and column count, StackPanel count, and how many Image objects are they having and each image with their position in the StackPanel and so on?
Edit:
These Grid objects are created and managed completely in code-behind.
I use the MVVM pattern throughout the project.
(in case these are important to informations)


text:
Q: How to install Docker with another Debian package? I have 2 images on Docker Registry, so my requirement is to create Debian package to pull those 2 images and run on the installed machine. My problem is if I want to use Docker command, Docker should be installed in the given machine. So Docker install already, then we can use it. Otherwise I have to install it when I install that Debian Package.
My DEBIAN/control file look like this,
Package: bla-bla
Version: 1.0
Architecture: all
Priority: optional
Maintainer: Bla Bla <bla.bla@bla.com>
Installed-Size: 327000
Depends: unzip, curl, sqlite3, libsqlite3-dev, xdg-utils, apt-transport-https, ca-certificates, software-properties-common
Homepage: https://www.example.com/
Section: Network, Databases, Web Servers, JavaScript, Python;
Description: bla bla bla

I added Docker and docker for Depends time to time, but it didn't work. so I added below lines to the preinst file,
function check_whether_docker_installed() {
  service=docker
  is_running=$(ps aux | grep -v grep | grep -v "$0" | grep $service | wc -l | awk '{print $1}')

  if [ $is_running != "0" ]; then
    echo -e "\nservice $service is running"
  else
    initd=$(ls /etc/init.d/ | grep $service | wc -l | awk '{ print $1 }')

    if [ $initd = "1" ]; then
      startup=$(ls /etc/init.d/ | grep $service)
      echo -e "\nStarting Docker service"
      /etc/init.d/${startup} start
      echo "Docker service successfully started"
    else
      echo -e "\nService $service not yet installed, going to install it"
      sudo apt update
      curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
      sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu bionic stable"
      sudo apt update
      apt-cache policy docker-ce
      sudo apt install -y docker-ce
      sudo chmod +x /var/run/docker.sock
      echo "Docker successfully installed, let's check it again"
      check_whether_docker_installed
    fi
  fi
}

function download_and_install_docker_compose() {
  which docker-compose

  if [ $? -eq 0 ]; then
    echo -e "\ndocker-compose is installed!"
  else
    echo -e "\ndocker-compose is not installed!"
    sudo curl -L "https://github.com/docker/compose/releases/download/1.27.3/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
    sudo chmod +x /usr/local/bin/docker-compose
    echo "docker-compose is successfully installed, let's check it again"
    download_and_install_docker_compose
  fi
}

check_whether_docker_installed
download_and_install_docker_compose

sudo apt install -y docker-ce this line wasn't able to run. It gave me below error.
E: Could not get lock /var/lib/dpkg/lock-frontend - open (11: Resource temporarily unavailable)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?
chmod: cannot access '/var/run/docker.sock': No such file or directory

Yes I know this happens because I'm running sudo apt install my_package.deb to install my package already, so cannot run another sudo apt install command inside my package. How can I sort it out this problem? This should be one time process.

A: There is one possible way.
Create one shell script that is divided into two sections.

*

*The first section covers all docker pre-requisites required.

*The second section covers the installation command of your custom debian package.

To make all of this run in one command, there are a few options:

*

*Host the shell script on an http/https server. Ensure that the client machine where you want the debian package to be installed has access to this http/https server. On your client machine run:
$ curl -s http://example.com/my_installation_script.sh | bash

*If you want this package installed on a Cloud server, you could host the shell-script inside the Cloud Provider's object storage(AWS: s3, Azure: Blob storage,GCP: Google Cloud Storage) and on you client machine run:
$ cloud_provider_cli service_name get object_file | cat object_file | bash

*If you are okay with keeping the script public, you could write the script as a gist on Github_gist and host it there for free. On your client machine :
$ curl -s https://gist.githubusercontent.com/long_url/shell_script.sh | bash
You can get the mentioned url by clicking raw option on github to download your shell script from github gist.


text:
Q: Cryptocode/falign: spacing between lines I'm using cryptocode to display some crypto-related things in a memoir document, but I'd like to decrease the default spacing, which is huge (especially when using one half spacing in the rest of the document):

I managed to make everything smaller but I still have a few issues, sometimes I've too much spacing (in red squares, sometimes it's even sometimes more than in the original picture), sometimes I've not enough (in green circles):

Any idea how to fix that?
MWE
\documentclass{memoir}

\checkandfixthelayout
%% Configure 1.5 spacing between lines
\OnehalfSpacing
% even if not documented, one must use checkandfixthelayout not to break the title template
% https://tex.stackexchange.com/questions/601273/memoir-checkandfixthelayout-required-for-single-onehalfspacing
\checkandfixthelayout

\usepackage [
lambda,
advantage,
operators,
sets,
adversary,
landau,
probability,
notions,
logic,
ff,
mm,
primitives,
events,
complexity,
asymptotics,
keys
] {cryptocode}
\createprocedureblock{interactGame}{center,boxed}{}{}{}

\begin{document}

What I managed to have (problem: still too much space between two arrows):

\NewExpandableDocumentCommand{\mysendmessageleft}{m}{\sendmessage{<-,inner sep=0pt}{topstyle={inner sep=2pt},top={$#1$}}}
\NewExpandableDocumentCommand{\mysendmessageright}{m}{\sendmessage{->,inner sep=0pt}{topstyle={inner sep=2pt},top={$#1$}}}
\NewDocumentEnvironment{gameInteract}{mb}{
\begin{Spacing}{0}%
  \interactGame[linenumbering]{#1}{#2\vspace{5mm}}
\end{Spacing}\par\vskip\baselineskip % Seems required or the next line will be eated up.
}{}

\begin{gameInteract}{My protocol}
    \textbf{Challenger}                           \>                                      \> \textbf{Adversary} \\
    \> \mysendmessageleft{(m^{(0)},m^{(1)})} \> \text{Compute $m^{(0)}$ and $m^{(1)}$} \\
    c \sample \bin                                  \>                                      \> \\
    (k, t_k) \gets \textsf{Gen}(1^\lambda, m^{(c)}) \>                                      \> \\
    \> \mysendmessageright{k}                \> \\
    \> \mysendmessageleft{\tilde{c}}         \> \\
    \pcreturn \tilde{c} = c                         \>                                      \>
\end{gameInteract}

What I have by default:
{\normalfont \interactGame[linenumbering]{My protocol}{
    \textbf{Challenger}                           \>                                      \> \textbf{Adversary} \\
                                                  \> \sendmessageleft*{(m^{(0)},m^{(1)})} \> \text{Compute $m^{(0)}$ and $m^{(1)}$} \\
  c \sample \bin                                  \>                                      \> \\
  (k, t_k) \gets \textsf{Gen}(1^\lambda, m^{(c)}) \>                                      \> \\
                                                  \> \sendmessageright*{k}                \> \\
                                                  \> \sendmessageleft*{\tilde{c}}         \> \\
  \pcreturn \tilde{c} = c                         \>                                      \>
}}

\end{document}

A: You can eliminate the "red boxes" by adding negative space to the appropriate newlines \\ of the  tabbing environment using the optional parameter \\[<vertical space>].
The space between the head line and the body is controlled by  bodylinesep. I am not sure if you want to increase or decrease the default (set to -3pt in the example to show the effect).
The "green circle" issue disappears after simplifying the gameInteract environment.

\documentclass{memoir}

\checkandfixthelayout
%% Configure 1.5 spacing between lines
\OnehalfSpacing
% even if not documented, one must use checkandfixthelayout not to break the title template
% https://tex.stackexchange.com/questions/601273/memoir-checkandfixthelayout-required-for-single-onehalfspacing
\checkandfixthelayout

\usepackage [
lambda,
advantage,
operators,
sets,
adversary,
landau,
probability,
notions,
logic,
ff,
mm,
primitives,
events,
complexity,
asymptotics,
keys
] {cryptocode}
\createprocedureblock{interactGame}{center,boxed}{}{}{}

\begin{document}

    What I managed to have (problem: still too much space between two arrows):

    \NewExpandableDocumentCommand{\mysendmessageleft}{m}{\sendmessage{<-,inner sep=0pt}{topstyle={inner sep=2pt},top={$#1$}}}
    \NewExpandableDocumentCommand{\mysendmessageright}{m}{\sendmessage{->,inner sep=0pt}{topstyle={inner sep=2pt},top={$#1$}}}
    \NewDocumentEnvironment{gameInteract}{mb}{
%       \begin{Spacing}{0}% Not needed
            \interactGame[linenumbering,bodylinesep=-3pt]{#1}{#2}  % changed <<<<<<<<<<<<<<<<<
%       \end{Spacing}\par\vskip\baselineskip % Seems required or the next line will be eated up.
    }{}

    \begin{gameInteract}{My new protocol}
        \textbf{Challenger}                           \>                                      \> \textbf{Adversary} \\
        \> \mysendmessageleft{(m^{(0)},m^{(1)})} \> \text{Compute $m^{(0)}$ and $m^{(1)}$} \\[-1.5ex]% changed <<<<<<<<<<<<<<<<<
        c \sample \bin                                  \>                                      \> \\
        (k, t_k) \gets \textsf{Gen}(1^\lambda, m^{(c)}) \>                                      \> \\
        \> \mysendmessageright{k}                \> \\[-1.5ex]% changed <<<<<<<<<<<<<<<<<
        \> \mysendmessageleft{\tilde{c}}         \> \\
        \pcreturn \tilde{c} = c                         \>                                      \>
    \end{gameInteract}

    What I have by default:
    {\normalfont \interactGame[linenumbering]{My protocol}{
            \textbf{Challenger}                           \>                                      \> \textbf{Adversary} \\
            \> \sendmessageleft*{(m^{(0)},m^{(1)})} \> \text{Compute $m^{(0)}$ and $m^{(1)}$} \\[-1.5ex]
            c \sample \bin                                  \>                                      \> \\
            (k, t_k) \gets \textsf{Gen}(1^\lambda, m^{(c)}) \>                                      \> \\
            \> \sendmessageright*{k}                \> \\[-2.5ex]
            \> \sendmessageleft*{\tilde{c}}         \> \\
            \pcreturn \tilde{c} = c                         \>                                      \>
    }}

\end{document}

A: The body of \gameInteract is not typeset with much attention to line spacing. You can get a uniform distance by setting Spacing to 1.2 and by smashing the labels above the arrows. I also reduced their size with \scriptstyle. Remove it if you don't like the style.
\documentclass{memoir}
\usepackage{amsmath}

\OnehalfSpacing
\checkandfixthelayout

\usepackage [
lambda,
advantage,
operators,
sets,
adversary,
landau,
probability,
notions,
logic,
ff,
mm,
primitives,
events,
complexity,
asymptotics,
keys
] {cryptocode}

\createprocedureblock{interactGame}{center,boxed}{}{}{}

\NewDocumentCommand{\mysendmessageleft}{m}{%
  \sendmessage{<-,inner sep=0pt}{
    topstyle={inner sep=2pt},
    top=\smash[t]{$\scriptstyle#1$},
  }%
}
\NewDocumentCommand{\mysendmessageright}{m}{%
  \sendmessage{->,inner sep=0pt}{
    topstyle={inner sep=2pt},
    top=\smash[t]{$\scriptstyle#1$},
  }%
}

\NewDocumentEnvironment{gameInteract}{m+b}
 {%
  \par\begin{Spacing}{1.2}
  \interactGame[linenumbering]{#1}{#2}
  \par\addvspace{\baselineskip}
  \end{Spacing}
 }{}

\begin{document}

What I managed to have (problem: still too much space between two arrows):

\begin{gameInteract}{My protocol}
  \textbf{Challenger} \> \> \textbf{Adversary} \\
    \> \mysendmessageleft{(m^{(0)},m^{(1)})} \> \text{Compute $m^{(0)}$ and $m^{(1)}$} \\
  c \sample \bin \\
  (k, t_k) \gets \textsf{Gen}(1^\lambda, m^{(c)}) \\
    \> \mysendmessageright{k} \\
    \> \mysendmessageleft{\tilde{c}} \\
  \pcreturn \tilde{c} = c
\end{gameInteract}

Some other text to see what happens after the game.

\end{document}


text:
Q: Strategy for displaying a progress indicator while loading data into an SQLite database? My app consists of the following components:

*

*a content provider for data stored in an SQLite database

*a ListFragment that uses CursorAdapter to display data from the content provider

*a service that runs in the background periodically polling a remote URI for new data, adding any to the database via the content provider

Here's the challenge. When the ListFragment is first displayed, the database is empty. I'm using LoaderManager / CursorLoader to fetch data from the provider while the ListFragment displays a progress indicator. The problem is that this will always result in an empty table since the service hasn't had time to poll the remote URI yet.
The user observes something like this:

*

*the ListFragment displays a progress indicator

*the progress indicator disappears and an empty list is displayed

*about 3 or 4 seconds later, the service finishes updating the data and it is displayed

This is not intuitive. I would like to keep the progress indicator displayed while the data is being loaded.

Here's an overview of what I've got right now.
public class ArticleListFragment extends ListFragment
        implements LoaderManager.LoaderCallbacks<Cursor> {

    //...

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        //...
        mAdapter = new SimpleCursorAdapter(...);
        setListAdapter(mAdapter);
        setListShown(false);
        getLoaderManager().initLoader(0, null, this);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return new CursorLoader(...);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        mAdapter.swapCursor(data);
        setListShown(true);
    }

    //...
}

A: Use ContentObserver technique and load cursor when data is changed. So you can hide the progress when you need, e.g. when Cursor.getCount() > 0.


text:
Q: ExtJs version upgrade What are the things to be done for upgrading ExtJs version 4.0.7 to 4.2.1?
I am getting many errors. But the error is in ext-all.js
So I cant detect the error. Also the eclipse is stuck after some time if I downloaded and copy the ExtJs folder into the workspace.

A: When you're debugging, you should include ext-all-debug.js or ext-debug-w-comments.js, or ext-all-dev.js instead of ext-all.js. All three versions will give you a readable version of the code (i.e. not minified), and the -dev one will also output useful warnings, etc.
Concerning Eclipse, that's just a guess but it seems that it get stuck trying to parsing and understanding the huge ext-all.js file. I know that Netbeans can't open it, but it won't try to parse it before one try to open the file. PHPStorm (WebSphere) can open it, but it is not free.
So, try to exclude the Ext source directory from the source Eclipse is parsing. In order to see Ext's code, try to open individual class files instead, any IDE should be able to handle these.
Anyway in your situation, the tool that will be the most useful to track down all you errors will be the browser debugger. In my experience, Chrome will be a lot faster than Firefox to debug huge JS files.


text:
Q: Adding checker on submit Button Here's the Button code
ButtonWidget(
                  text: 'Submit',
                  onClicked: () {
                    Navigator.pushAndRemoveUntil(
                        context, MaterialPageRoute(builder: (_) => SPAL()),
                          (Route<dynamic> route) => false,
                    );
                    print('Email: ${emailController.text}');
                    print('Password: ${password}');
                  },
                ),

How i can make the button check if the email and password is empty or not, if it is then button wont open next page but if it was filled then the button will open the next Screen

A: you need to add a validator in the email and password field, then when the user clicks on the button you can check for validation. the email and password field needs to be put inside a form with a key
final formKey = GlobalKey<FormState>();
final anotherKey= GlobalKey<FormState>();
Form(
   key: formKey,
        child: Column(
           children: <Widget>[
              emailField(),
              passwordField(),
              ButtonWidget(),
           ]
       ),
),

  Widget emailField(String value) {
    return TextFormField(
    //using controller
    controller: emailController,
      decoration: InputDecoration(
          labelText: 'Email',
          hintText: 'Enter Email',
      validator: (value) => value == null || value.isEmpty ? "enter your email" : null,
    //don't need onSaved when using controller
      //onSaved: (String value) {
      //  emailController.text = value.toLowerCase().trim();
      //},
    );
  }

ButtonWidget(
                  text: 'Submit',
                  onClicked: () {
                     if(formKey.currentState.validate() && anotherKey.currenState.validate()) {
                      formKey.currentState.save();
                      anotherKey.currentState.save();
                      Navigator.pushAndRemoveUntil(
                          context, MaterialPageRoute(builder: (_) => SPAL()),
                            (Route<dynamic> route) => false,
                      );
                    }
                    print('Email: ${emailController.text}');
                    print('Password: ${password}');
                  },
                ),