text:
Q: Linked List reversal algorithm not working I'm trying to write a simple function that reverses a linked list in Python:
def reverse(head):
    prev = None
    nxt = head.next
    head.next = prev
    while nxt:
        prev = head
        head = nxt
        head.next = prev
        nxt = nxt.next
    return head

The logic seemed fine when I thought through it.:
First move prev to head, then shuffle head forward so it points to the same node as nxt, before setting head.next to where it was. Finally moving nxt forward by one. Iterate until nxt reaches the end of the list.
However when I tried to reverse a linked list 0->1->2->3->4->5 with the following code:
def traverse(head):
    while head:
        print(head.val)
        head = head.next

it repeatedly printed 0 and 1 endlessly.

A: In the while-loop:
head = nxt   # head and nxt now refer to the same node
head.next = prev   # head.next now points to previous node but nxt.next does as well
nxt = nxt.next   # this is same as: nxt = head.next  therefore same as: nxt = prev

A: As Michael pointed out, your code makes first and the second element in the linked list to point to each other.
The fix is pretty simple, here is what I did:
def reverse(head):
    nxt = head.next
    head.next = None
    while nxt:
        temp1 = nxt.next
        temp2 = head
        head = nxt
        nxt.next = temp2
        nxt = temp1

This code initially initially does the same thing as yours. The while loop however, uses 2 temporary variables temp1 and temp2 to hold the addresses of the variables surrounding nxt (on either sides). This prevents the conflict that happened in your code.
Hope this helps!
Cheers!


text:
Q: Issue in Exporting SSRS Reports to CSV I have an SSRS Report in which few columns will be made visible programmatically. The Report gets generated succesfully, but when it's exported to CSV, the columns whose "visible" attribute has been handled programmatically doesn't get exproted to CSV.

*

*Is there a work-around for this
issue?

*What is the best way to implement
    hide logic for columns in SSRS so
    that there are no issues while
    exproting to CSV/Excel?

A: See http://blogs.msdn.com/b/bimusings/archive/2007/02/07/reporting-services-why-aren-t-all-my-report-columns-exporting-to-csv-and-or-xml.aspx which explains that CSV (and XML) is a data format rather than a layout format. If the visibility is toggled via a formula as you're doing, it won't be rendered at all in CSV (even if the visibility setting makes it visible).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Was Caesar Flickerman based on any real TV presenter? In the Hunger Games books and films, Caesar Flickerman, the host of the pre-Games tribute interviews and in some ways the 'face of the Games', seems like a realistic depiction of a modern talk show host. But that's about as much as I can tell; I don't watch enough TV to be able to tell one such host from another in real life. So I was wondering:
was Caesar inspired by any television presenter in real life?
Either in Suzanne Collins's imagination of him, or in Stanley Tucci's excellent on-screen depiction.

A: According to this source (emphasis and links mine), Tucci's portrayal was inspired by at least three other presenters:

Tucci plays flamboyant presenter Caesar Flickerman in the hit film franchise and his portrayal was inspired by American entertainer Wayne Newton, fictional presenter Jiminy Glick, and camp Irish chat show host [Graham] Norton.
In an appearance on Norton's programme this week (ends12Apr15), Tucci admitted the host had been a big influence on the development of Flickerman, telling him, "When you create a character, you steal and cull from all sources. He's a cross between Wayne Newton and Jiminy Glick and there's a little piece of you Graham - the intelligence!"

And according to another interview, Tucci's inspiration for the look of Caesar (as opposed to the performance, presumably?) was based on George Hamilton and Karl Lagerfeld.

The only reference I can find to any inspiration by Suzanne Collins in writing her character was in the notoriously unreliable Hunger Games Wikia, which claims "one might think his last name to be a reference to David Letterman. However, his portrayal is perhaps closer to Leno, which if intentional would mean that Ms. Collins is subtly mocking Jay." However, this may well be completely made up as an excuse to get a nice bit of wordplay in ("mocking Jay"). I definitely wouldn't put any faith in this totally unsourced claim.

A: According to this interview it appears that Stanley Tucci was inspired in his rendition of Caesar Flickerman by Graham Norton Interview Otherwise I have yet to find a quote from Suzanne Collins on her inspiration, but the search is still underway.

From the video interview,

"When you create a character, you steal and cull from all sources. He's a cross between Wayne Newton and Jiminy Glick and there's a little piece of you Graham - the intelligence!"


text:
Q: Sympy- matplotlib: x and y must have same first dimension I using sympy and matplotlib to draw a graph, but I have an error.
I use sympy to solve the equation, and use matplotlib to draw graphs
What am I doing wrong?
Here is the code:
import numpy as np
import sympy
import math
from mpmath import *
from sympy import *
import matplotlib.pyplot as plt

x= symbols('x')
f, g, h = symbols('f g h', cls=Function)
A, C1, C2 = symbols('A C1 C2')
input = C1 * sin(5*x) + C2 * cos(5*x) + x/25
ex1 = input.subs({x:0})
ex2 = input.subs({x:4})
kq = solve((ex1, ex2), C1, C2)
pttq = input.subs({C1:kq[C1], C2: kq[C2]})
print(pttq)

x = np.arange(0, 5, 1)
y = pttq

fig, ax = plt.subplots()

plt.xlabel('(m)')
plt.ylabel('(KN)')
plt.title('NEO')

plt.plot(x, y)

plt.show()

Error message:
Traceback (most recent call last):
  File "\Text", line 31, in <module>
  File "C:\Blender\2.78\python\lib\site-packages\matplotlib\pyplot.py", line 3318, in plot
    ret = ax.plot(*args, **kwargs)
  File "C:\Blender\2.78\python\lib\site-packages\matplotlib\__init__.py", line 1892, in inner
    return func(ax, *args, **kwargs)
  File "C:\Blender\2.78\python\lib\site-packages\matplotlib\axes\_axes.py", line 1406, in plot
    for line in self._get_lines(*args, **kwargs):
  File "C:\Blender\2.78\python\lib\site-packages\matplotlib\axes\_base.py", line 407, in _grab_next_args
    for seg in self._plot_args(remaining, kwargs):
  File "C:\Blender\2.78\python\lib\site-packages\matplotlib\axes\_base.py", line 385, in _plot_args
    x, y = self._xy_from_xy(x, y)
  File "C:\Blender\2.78\python\lib\site-packages\matplotlib\axes\_base.py", line 244, in _xy_from_xy
    "have shapes {} and {}".format(x.shape, y.shape))
ValueError: x and y must have same first dimension, but have shapes (5,) and (1,)

A: OK, there are a few thing going wrong here.
First, the variable x:
After the imports you define it as a sympy variable which is then used in your expressions. But then you overload it as an array containing the x values for plotting. So you probably want to change that to
x_vals = np.arange(0, 5, 1)

Second, as mentioned in the comments above, y has to be a list or numpy array. To generate that you would have to do something like
y = np.empty(x_vals.shape)
for i in range(len(x_vals)):
    y[i] = pttq.subs(x,x_vals[i]).evalf()

Finally, you probably want to have a smaller step size in x for the plot:
x_vals = np.arange(0, 5, .1)


text:
Q: allocate a float vector with subscript range v[nl..nh] Ok so i want to understand what this does:
#define NR_END 1

float *vector(long nl, long nh)
/* allocate a float vector with subscript range v[nl..nh] */
{
    float *v;

    v=(float *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(float)));
    if (!v) nrerror("allocation failure in vector()");
    return v-nl+NR_END;
}

i mean it creates a pointer to a malloc space of the size given there. so v[0] is the first unit ... and so on till the end of the block.
but why is some term returned in the end.
I thought you couldn't move anywhere on the stack with a pointer but just be able to access the space given?
int main()
{
    printf("Hello world\n\n");

    float* f = vector(3,5);

    f[0]=1;
    f[1]=2;
    f[2]=3;
    f[7] = 5;

    printf("%f", f[7]);

    return 0;

}

i did these tests and it compiles whithout errors or warnings when gcc filename.c -o filename.
and why does v[7]=5 work when it shouldn't?
and what is a subscript range?
and how are you supposed to use this correctly?
i am very confused. Please help me understand this.
the file seems to be also viewable at https://www.cfa.harvard.edu/~sasselov/rec/code/nrutil.c

A: That is some pretty sketchy-looking code, this is not a good idea.
The function seems to allocate a vector where the caller promises to only use indexes in the closed interval [nl, nh], e.g. vector(100, 104) would try to allocate a 5-element vector indexed 100, 101, 102, 103 and 104. Any other index results in undefined behavior. This includes 0 which typically is the first valid index of a C array.
The two core lines of code are:
// 1
v=(float *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(float)));

This can be re-written a bit cleaner without the pointless casts:
v = malloc((nh - nl + 1 + NR_END) * sizeof *v);

This then computes the size of the desired index interval (nh - nl + 1 would result in 104 - 100 + 1 which is 5 in our example). It adds an extra NR_END elements, no idea why.
And then there's:
// 2
return v - nl + NR_END;

This returns the base pointer v, but first adjusts it by going backwards nl elements, i.e. 100 in our example. This causes indexing by 100 to hit the first actual allocated element. The addition of NR_END biases the use of the allocated vector towards the end, again I have no idea why.
So in memory it would look like this, with 6 elements allocated:
   +---+---+---+---+---+---+
v: | 0 | 1 | 2 | 3 | 4 | 5 |
   +---+---+---+---+---+---+

But by subtracting, we return a pointer to lower addresses, relying on the caller indexing with at least nl to back up into the allocated space.
All that said, I'm pretty sure this is undefined behavior and assumes a bit much about address computations. You're not supposed to work with addresses outside the range [0,N] for an array of N elements, which would rule out dealing with addresses to before the array starts.

A: In order to see the code you wrote actually fails, you need to do more than just compiling the code without any extra flags. If you use clang MemorySantizer and disable compiler optimisations, you will see that there is a problem with the memory access done with f[0].
C does not do bounds checking and leaves it to the programmer. The vector() function returns a memory location which can only be addressed through v[nl] ... v[nh]
Line 23 in the a.c. is f[0]=1;
% clang -fsanitize=memory -fno-omit-frame-pointer -g -O0 a.c
% ./a.out
Hello world

MemorySanitizer:DEADLYSIGNAL
==26321==ERROR: MemorySanitizer: SEGV on unknown address 0x600ffffffff8 (pc 0x0000010a9670 bp 0x7fffffffeaa0 sp 0x7fffffffea10 T101363)
==26321==The signal is caused by a WRITE memory access.
    #0 0x10a966f in main /home/fnoyanisi/a.c:23:9
    #1 0x1060b5a in __sanitizer::ReportDeadlySignalImpl(__sanitizer::SignalContext const&, unsigned int, void (*)(__sanitizer::SignalContext const&, void const*, __sanitizer::BufferedStackTrace*), void const*) /usr/src/contrib/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_report.cc:211:3
    #2 0x1060b5a in __sanitizer::ReportDeadlySignal(__sanitizer::SignalContext const&, unsigned int, void (*)(__sanitizer::SignalContext const&, void const*, __sanitizer::BufferedStackTrace*), void const*) /usr/src/contrib/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_report.cc:225
    #3 0x1060e8e in __sanitizer::HandleDeadlySignal(void*, void*, unsigned int, void (*)(__sanitizer::SignalContext const&, void const*, __sanitizer::BufferedStackTrace*), void const*) /usr/src/contrib/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_report.cc:234:3

MemorySanitizer can not provide additional info.
SUMMARY: MemorySanitizer: SEGV /home/fnoyanisi/a.c:23:9 in main
==26321==ABORTING
% sed '23q;d' a.c
    f[0]=1;
% clang a.c
% ./a.out
Hello world

5.000000
%

A: What the vector(long nl, long nh) function does is create an array of the necessary size to hold the given range of numbers, and adds an 'extra' element (possibly, in order to permit the C practice of taking an address "one beyond the bounds"). So, if you call it with values of 3 and 5, it allocates space for 4 float variables at the address in v.
However, simply using this v address, one would have to access the elements using indexes in the range 0 thru 2. So, before returning an address, the function subtracts your lower index (nl) from it. Now, although this value will now point to an invalid memory address, if you only ever access elements from your specified range, then the pointer arithmetic used in calculating, say f[3] in your main function, will add a suitable offset to this "invalid" pointer, so that your are then actually accessing the v[0] variable.


text:
Q: MySQL error "Cannot add foreign key constraint" Estou iniciando na linguagem SQL. Estou com o seguinte erro:
Table 'linces.controlos' doesn't exist

Ainda não encontrei a solução, alguém pode ajudar?
Drop Database if Exists Linces;
Create Database Linces;
Use Linces;

Create Table Linces(
Id_lince int NOT NULL,
Nome_lince char(50),
Genero char(50),
Data_obito datetime,
Id_pai int NOT NULL,
Id_mae int NOT NULL,
Primary Key (Id_lince)
);

Create Table Localizacoes(
Id_lince int NOT NULL,
Datahora datetime NOT NULL,
latitude double,
longitude double,
Constraint pk_Localizacoes Primary Key (Id_lince, Datahora),
Constraint ch_estr_Id_lince
Foreign Key (Id_lince)
References Linces (Id_lince)
On Update Cascade
On Delete Cascade
);

Create Table Tecnicos(
Id_func int NOT NULL,
Nome_func char(50) Not Null,
Primary Key (Id_func)
);

Create Table Controlos(
Id_lince int NOT NULL,
Dat datetime NOT NULL,
Id_func int Not Null,
Peso double,
Estado_saude char(50) Not Null,
Constraint pk_Controlos Primary Key (Id_lince, dat, Id_func),
Constraint ch_estr_Id_lince
Foreign Key (Id_lince)
References Linces (Id_lince)
On Update Cascade
On Delete Set Null,
Constraint ch_estr_Id_func
Foreign Key (Id_func)
References Tecnicos (Id_func)
On Update Cascade
On Delete Cascade
);

A: O problema está em:
Constraint ch_estr_Id_lince Foreign Key (Id_lince) References Linces (Id_lince) On Update Cascade On Delete Set Null

Nessa linha você quer setar uma coluna NULL quando ela está com a propriedade NOT NULL
Id_lince int NOT NULL,

A solução é mudar o On Delete, mesmo depois de mudar ele, você está criando duas chaves estrangeiras com o mesmo nome:
Create Table Localizacoes(
Constraint ch_estr_Id_lince Foreign Key (Id_lince) References Linces (Id_lince) On Update Cascade On Delete Cascade
...
Create Table Controlos(
Constraint ch_estr_Id_lince Foreign Key (Id_lince) References Linces (Id_lince) On Update Cascade On Delete Set Null

A solução é mudar o nome de uma key.
Para checar os erros específicos, você pode rodar a query SHOW ENGINE INNODB STATUS e procurar por LATEST FOREIGN KEY ERROR.


text:
Q: how to find out where the error at in MYSQL version 5.7 i have 3 tables like this
create table order_match
(
id int(10) PRIMARY KEY not null,
order_status_id int(10) not null
);

create table order_match_detail
(
 id int(10) PRIMARY KEY not null,
 order_match_id int(10) not null,
 product_id int(10) NOT NULL
);

create table product
(
id int(10) PRIMARY KEY not null,
name varchar(255) not null
);

Insert into order_match (id, order_status_id)
select 1, 6 union all
select 2, 7 union all
select 3, 6 union all
select 4, 6;

Insert into order_match_detail (id, order_match_id, product_id)
select 1, 1, 147  union all
select 2, 2, 148 union all
select 3, 3, 147 union all
select 4, 4, 149 union all
select 5, 4, 147;

Insert into product (id, name)
select 147, 'orange' union all
select 148, 'carrot' union all
select 149, 'Apple';

with order_match.id = order_match_detail.order_match_id
and order_match_detail.product_id = product.id
i want to make the data where order_status_id not in 7 then it's success transaction and from that success transaction, if the transaction buy apple, then the column of apple contain 1 else if not buying, then 0 and this is my expected results, i want to make this data to analyze in
 id (in order_match)    |    Orange  |  Carrot  |   Apple

    1                           1            0           0
    3                           1            0           0
    4                           1            0           1

the real problem is i've just fit in whether the version of mysql, and fit in with the same data type for every table, i dont really know why in my fiddle it's work, but on mysql it's contain

error code :1064.you have an error in your sql syntax near ' '' at
line 1

this is my Fiddle
new UPDATE
after take a look with the data, i assume the product name in field have format that cant be acceted mysql. so i've made the new query like this
SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'count(case when name = ''',
      name,
      ''' then 1 end) AS ',
      concat('product', id)
    )
  ) INTO @sql
from product;

SET @sql1 = CONCAT('SELECT omd.order_match_id, ', @sql, ' from order_match_detail omd
left join order_match om
  on omd.order_match_id = om.id
left join product p
  on omd.product_id = p.id
where om.order_status_id in (4, 5, 6, 8)
group by omd.order_match_id');

PREPARE stmt FROM @sql1;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

This is the new fiddle
but in my new mysql it's said

Error Code: 1064. You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near 'from order_match_detail omd left join order_match
om   on omd.order_match_id = o' at line 1


text:
Q: Download link error image from firebase storage Please help me i don't understand where is the problem
@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == Gallery_Pick && resultCode == RESULT_OK && data!=null){
            Uri imageUri = data.getData();
            CropImage.activity()
                    .setGuidelines(CropImageView.Guidelines.ON)
                    .setAspectRatio(1,1)
                    .start(this);
    }

    if(requestCode ==CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE){
        CropImage.ActivityResult result = CropImage.getActivityResult(data);

        if(resultCode == RESULT_OK){
            loadingBar.setTitle("Profile Image");
            loadingBar.setMessage("Please wait...");
            loadingBar.show();
            loadingBar.setCanceledOnTouchOutside(true);

            Uri resultUri = result.getUri();

            StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");

            filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                    if(task.isSuccessful()){
                        Toast.makeText(SetupActivity.this,"Profile image uploaded successfully...",Toast.LENGTH_SHORT).show();

                        final String downloadUrl = task.getResult().getStorage().getDownloadUrl().toString();

                        userRef.child("profileimage").setValue(downloadUrl)
                                .addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {
                                        if(task.isSuccessful()){

                                            Intent selfIntent = new Intent(SetupActivity.this,SetupActivity.class);
                                            startActivity(selfIntent);

                                            loadingBar.dismiss();
                                            Toast.makeText(SetupActivity.this,"Profile image uploaded successfully...",Toast.LENGTH_SHORT).show();
                                        }

                                        else{

                                            loadingBar.dismiss();
                                            String message = task.getException().getMessage();
                                            Toast.makeText(SetupActivity.this,"Error..."+message,Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });

                    }
                }
            });

        }

        else {
            loadingBar.dismiss();
            Toast.makeText(SetupActivity.this,"Please try again...",Toast.LENGTH_SHORT).show();
        }

    }

}


text:
Q: limit registered user to 1 comment per post in WordPress I want to limit registered users to 1 comment per post in WordPress.
I used this code below, but in this case of this it displays the message "You have commented" on the top bar of my site and does nothing.
global $current_user, $post;
if ( !is_user_logged_in() ) {
    comment_form();
} else {
    $usercomment = get_comments(array('user_id' => $current_user->ID, 'post_id'=>$post->ID) );
    if($usercomment) {
        echo '
You have commented
';
    } else {
        comment_form();
    }
}


text:
Q: changing multiple state value - react I have a state object that represents rows and columns that looks something like this.

  const [state, setState] = useState([
    { firstName: "example", lastName: "example", petName: "example" },
    { firstName: "example", lastName: "example", petName: "example" },
    { firstName: "example", lastName: "example", petName: "example" },
  ]);

how can I set my state to change the key of all the petName values whilst keeping the original state?

A: You can use map and spread operator:
const [state, setState] = useState([
    { firstName: "example", lastName: "example", petName: "example" },
    { firstName: "example", lastName: "example", petName: "example" },
    { firstName: "example", lastName: "example", petName: "example" },
  ]);

{...}

const changePetNames = (newValue) => setState(state => state.map(obj => {...obj, petName: newValue}))

A: You can use a Array.map() to change all the values as it's an array:

console.log([{
    firstName: "example1",
    lastName: "example1",
    petName: "example"
  },
  {
    firstName: "example2",
    lastName: "example2",
    petName: "example"
  },
  {
    firstName: "example3",
    lastName: "example3",
    petName: "example"
  },
].map((p, i) => ({
  ...p,
  petName: "New Name " + (i + 1)
})));

A: Here's a simple way to do it. This will keep the value of the key just update the name.
setState((prevState) =>
      prevState.map((state) => {
        state["newKey"] = state.petName;
        delete state["petName"];
      })
    );


text:
Q: In the CSharp component in Grasshopper for Rhino how to use Rhino's or Grasshopper's methods from my own class? I've got a problem when working with C# Component in Grasshopper. I'm not familiar with it, so I cannot understand the logic. For example, I have introduced a class:
  public class MyClass
  {
    public void TestFoo()
    {
      Print("it works!");
    }
  }

It contains the only method, that has to use the "Print" function and show the string message. But I get an error: Error (CS0038): Cannot access a non-static member of outer type 'Script_Instance' via nested type 'Script_Instance.MyClass' (line 762). As I understand I can't use Rhino's function within my own class. But how can I fix it? Thank you! I ask this question because I need to write the class that contains method of NurbsSurface creation, but I also cannot use Rhino's method doc.Objects.AddSurface...
I tried to implement C# inheritance from Rhino's methods, but it doesn't work...

A: The issue with accessing the Script_Instance from your custom class is independent of accessing the Rhino libraries from a custom class.
To access the Script_Instance methods, you can pass the object into your method and add the static tag.
For accessing rhino libraries there is no special inheritance.
The example blow demonstrates both implementations:

  private void RunScript(List<Point3d> PointsList, ref object NurbSrf, ref object SrfArea)
  {
    Print("Example:");

    //Access script object from custom class.
    MyClass.TestFoo(this);

    //Access Rhino doc in custom class.
    string docName = NurbsHelpers.ActiveDocName();
    string objectCount = NurbsHelpers.ActiveDocObjectCount();
    Print("doc '" + docName + "' has [" + objectCount + "] objects in it");

    //Use Nurbs Methods in custom class.
    NurbsSurface surface = NurbsHelpers.MakeNurbs(PointsList);
    double area = NurbsHelpers.NurbsArea(surface);

    //Assign script component outputs.
    NurbSrf = surface;
    SrfArea = area;

    //Bake surface into active doc
    NurbsHelpers.bakeNurbSrf(surface);
  }

  // <Custom additional code>
  public class MyClass
  {
    public static void TestFoo(Script_Instance script)
    {
      script.Print("it works!");
    }
  }

  public class NurbsHelpers
  {

    public static NurbsSurface MakeNurbs(List<Point3d> Points){
      NurbsSurface surface = NurbsSurface.CreateFromCorners(
        Points[0],
        Points[1],
        Points[2],
        Points[3]
        );
      return (surface);
    }

    public static double NurbsArea(NurbsSurface surface){
      Brep surfaceBrep = surface.ToBrep();
      return surfaceBrep.GetArea();
    }

    public static string ActiveDocName(){
      return Rhino.RhinoDoc.ActiveDoc.Name;
    }

    public static string ActiveDocObjectCount(){
      return Rhino.RhinoDoc.ActiveDoc.Objects.Count.ToString();
    }

    public static void bakeNurbSrf(NurbsSurface nurbSrf){
      Rhino.RhinoDoc doc = Rhino.RhinoDoc.ActiveDoc;
      doc.Objects.AddSurface(nurbSrf);
    }

  }


text:
Q: Novel where the protagonist (and other space-going agents) wear a clear amorphous "skin" or "hide" May have been published by TSR, definitely a smaller (US — maybe game-related) publisher trying to establish itself.  I think the novel even opens with the scene where the protagonist gets his "suit," which invades his nasal passages and mouth and forms a protective barrier.  Everyone in the service (society?) gets this suit.  It may have been symbiotic organism, not unlike Venom (Spiderman) or the symbiotic suit in Their Master's War by Mick Farren — except this one was clear.
Standard paperback, aimed at adults, may have had a white cover.  Mid-1980s to mid-1990s. Used to see it in used bookstores a lot.
UPDATE: Defintely not Varley, although I have since discovered those stories (part on Ten Worlds) and enjoy them. Don't think it was Janet Morris; I would have known her at the time, and it was a standalone novel.


text:
Q: Let $X$ an infinite $T_1$ space, then exist some subspace homeomorphic to $(\Bbb N,\tau)$ where $\tau$ is discrete or cofinite My attempt to prove the statement of the title: if $X$ is infinite and $T_1$ with topology $\tau_1$ then any basis for $X$ is infinite too.
If $X$ is $T_1$ then for any $x, y\in X$ with $x\ne y$ exists some open sets $U$ and $V$ such that $x\in U \land y\notin U$ and $x\notin V \land y\in V$.
$\color{red}{(1)}$ If you extend this analysis for a finite subset $F\subset X$ you can create a collection $\mathcal{U}$ of open sets where $\forall x_i,x_j\in F,\ i\ne j,\ \exists U_i\in\mathcal{U}:\ (x_i\in U_i)\land (x_j\notin U_i)$. Then $F\bigcap(\bigcap_{i=0}^{n} U_i)=\varnothing$ and $\mathcal {U}=\{U_i\}$ but $\bigcap_{i=0}^{n} U_i\in\tau_1$ due the definition of topology (and remember $F$ is finite).
Then:

*

*If exists some countable infinite collection of disjoint open sets for the basis of $X$ then if we take some point belonging to any of these disjoint basic open sets then the resulting subspace is obviously homeomorphic to $\Bbb N$ with the discrete topology.

*If doesnt exist an infinite collection of disjoint basic open sets we have that exist an infinite collection of non-disjoint open sets. If we take infinite countable points each one belonging to a different but non-disjoint open set and cause the space is $T_1$ we have that for every open set at most a finite number of points ($F$ in the expression $\color{red}{(1)}$) not belong to them cause the statement on $\color{red}{(1)}$, so the subspace is homeomorphic to $\Bbb N$-cofinite.
Question:

*

*I feel my proof correct but not enough clear, maybe you can point how to clear it or if it lacks something?

*The expression on $\color{red}{(1)}$ is enough understandable?
Thank you in advance.

EDITION: the expression $\color{red}{(1)}$ is very hard to write it correctly to me by now, so Im going to describe in words: you can extend the definition of $T_1$-space not only to some $x,y\in X$ if not to $x_1,x_2,x_3,...,x_n\in X$. If you make all considerations then exist some $U_i$ for every $x_i$ where $x_i\in U_i$ but the others points does not belong to $U_i$. These collection of $U_i$ I call $\mathcal{U}$.
The intersection of every $U_i$ belongs to $\tau_1$ because is a finite intersection of open sets, and no one $x_i$ belongs to this intersection, obviously, and these $x_i$ are finite. This is what I wanted express on $\color{red}{(1)}$, sorry for the inconvenience :S

A: Personally, I don't understand the $2.$ in your approach. The expression $\color{red}{(1)}$ is understandable, but the second part of your proof I do not understand.
An attempt, which is quite possibly wrong, so please take it with a grain of salt:
1st case - there exists a countable infinite subset $A$, such that it has cofinite topology, in that case we are done.
2nd case - such a subset does not exist, therefore in each infinite countable subset, there exists an element and open neightborhood of that element, such that it is not cofinite.
When we now take any countable infinite subset $A$, we can pick an element that has a non-cofinite open neightborhood, and we can call these $a_1$ and $U_1$.  Consider the set $A \setminus U_1$ - it is still an infinite, countable subset, so we can again pick an element $a_2$ and an open neightborhood $U_2$, such that $(A \setminus U_1) \setminus U_2$ is infinite. By taking $U_2' = U_2 \cap (X \setminus \{a_1\} )$ ($(X \setminus \{a_1\} )$ is an open set in $T_1$) and $U_1' = U_1$ we have open neightborhoods of $a_1$ and $a_2$ that do not contain the other respective element.
We repeat this process, and define in this way a sequence $\{a_i: i \in \mathbb{N} \}$ of distinct points in $X$. For any element $a_i$ in this sequence, we have an open neightborhood $U_i'$, such that $U_i'$ contains no prior elements in the sequence (because there's finitely many of them, we can get rid from $U_i$ by using $T_1$ property of $X$), and all the further elements are defined to be from $A\setminus U_i$, therefore it doesn't contain any of them either. So the sequence has discrete topology with respect to $X$ - therefore, we have found an infinite countable subset with discrete topology, and so we are done.

A: To address the questions you asked (sorry to be so late with this, but I've only had very limited time the last couple of days):
First, your expression $\color{red}{(1)}$ can be stated as:
Given a finite set $F\subseteq X$, for each $x \in F$, there is an open neighborhood $U_x$ of $x$ such that for all $y \in F, y \ne x \implies y \notin U_x$.
You can define $\mathcal U_F = \{U_x\ |\ x \in F\}$. I put the $F$ subscript on to remind you that $\mathcal U$ is defined from knowing $F$ first.
In point 2, you seem to be saying that in the case where $X$ does not contain an infinite collection of pairwise-disjoint empty sets, we can choose a countably infinite collection of open sets $\mathcal A$ and for each $A \in \mathcal A$, a point $x_A \in A$, such that if $A \ne B$, then $x_A \ne x_B$. However, like Jake1234, I don't see how $\color{red}{(1)}$ shows that $\{x_A\ |\ A \in \mathcal A\}$ has a cofinite subspace topology.


text:
Q: Have always a margin-bottom of 10px below my last list item "See more links" I have 4 columns in my footer.
My column at right have some list items, and my last list item "See more links", when I click in it Im changing my first list of items to other list using jQuery slideToggle().
But using this slideToggle, Im with, when I click in "See more links" my footer goes up a bit and then down again.
This problem was solved using in my column div (#col), max-height:227px; and min-height:227px; proprierties.
The problem Im having now is, that I want always margin-bottom of just 10px of my last item "See more links", but Im having different margins in different browsers and different resolutions.
Do you know how can I solve this? Im trying to "play" with position absolute or a container with fixed height, but Im not able to have the same result in different browsers and resolutions.
I have my example here: http://jsfiddle.net/vb63n9vg/4/
My html:

LINKS

Link 0

Link 1

Link 2

Link 3

Link 4

see more links

Link 0

Link 1

Link 2

Link 3

Link 4

Ver mais Links

© copyright

My css:
*{margin:0; padding:0;}

#list2
{
    display:none;
}

#footer-container
{
    width:100%;
    height:auto;
    float:left;
    background:#ff9900;
    border-top:0;
}
#footer1
{
    width:1160px;
    margin:0 auto 0 auto;
}

#footer1 ul
{
    list-style:none;
}

#footer1 ul li
{
    margin:0 0 7px 0;
}

#footer1 ul li a
{
    text-decoration:none;
    color:#444;
    font-family: 'Open Sans', sans-serif;
    font-size:15px;
}

#footer1 ul li a:hover
{
    color:#fff;
}

#col
{
    float:left;
    margin-right:40px;
    margin:10px 53px 10px 0;
    width:250px;
    max-height:227px;
    min-height:227px;
}

#footer2-container
{
    width:100%;
    float:left;
    background:#ECECEA;
    border-top:0;
    border-top: 2px solid #e0e0e0;
}

#footer2
{
    width:1160px;
    margin:10px auto 10px auto;
    background:#ECECEA;
    height:40px;

}

#footer2 .copyright
{
    float:left;
    font-family: 'Open Sans', sans-serif;
    color:#2F3083;
    font-size:14px;
    line-height:40px;
}

A: I think if you want a consistent distance of an item inside your column container and the bottom of the container itself, what you want is:
#col
{
  padding: 0 0 10px 0;
}

A: One way to accomplish this is to use the last-child selector. Then you won't need to add a class to the last element in the html.
#footer1 ul li:last-child
{
    margin-bottom: 10px;
}


text:
Q: Passing offset difference or constants inside macro It's a university assignment, so emu8086 must be used. With no emu8086.inc
Let's say I have
msg db "Hello"
msgend:
msglen1 equ $ - msg
msglen2 db $ - msg

Then:
mov ax, msgend - offset msg ; ax gets the correct length
mov ax, msglen1             ; correct length
mov ax, msglen2             ; correct length

; same names as offsets to make it clear,
; how which parameters would be passed.
; But not the same in real code.
TESTMACRO macro msg msgend msglen1 msglen2
    mov ax,    msg ; correct offset
    mov ax, msgend ; correct offset
    mov ax, msgend - offset msg ; zero length
    mov ax, msglen1             ; again zero length
    mov ax, msglen2             ; correct length, but it used up a word
endm

So. I can't pass the length of the string inside the macro in any way, except by passing the length allocated in a word.
But I'm interested, if I can do it with a equ constant.

A: Use = to define your equate instead of equ.
The value of an equ equate is evaulated at the point of usage, which in your case means that the $ in msglen1 is replaced by the address of the mov ax, msgLen1 instruction.
The value of an = equate is evaulated at the point of definition, which should give you the value you want in this case.


text:
Q: How to type multiple similar python functions with the same overload signature I have two functions that are quite similar, the second one calles the first one (and in the actual code does something else afterwards).
Both take two arguments that can take multiple types, bot only certain combinations make sense, therefore I use overload to indicate that (the actual code will also raise for invalid combinations).
See the following example:
from typing import overload

@overload
def x(k: int, m: float) -> int:
    ...

@overload
def x(k: str, m: bytes) -> str:
    ...

def x(k: int | str, m: float | bytes) -> int | str:
    return k

@overload
def y(k: int, m: float) -> int:
    ...

@overload
def y(k: str, m: bytes) -> str:
    ...

def y(k: int | str, m: float | bytes) -> int | str:
    return x(k, m)

Now mypy complains that:
error: No overload variant of "x" matches argument type "Union[int, str]"  [call-overload]
note: Possible overload variants:
note:     def x(k: int, m: float) -> int
note:     def x(k: str, m: bytes) -> str

What would be the correct way to type such a problem?

A: I think you've hit a limitation in python's overload, that while
def y(k: int | str, m: float | bytes) -> int | str:

is the recommended way to write this, it isn't strictly true. It's too broad and I don't believe there's any way round that. You're going to have to narrow the types again at some point between the implementation signature of y and calling x. You could do isinstance checks but since that costs something, I'd personally just # type: ignore[call-overload] this.


text:
Q: Get a products from bigcommerce store based on date? i would like to get some products in my Bigcommerce store based on date using api. So i have followed the following api code like this. But no luck
$filter = array('date_created' => 'Sat, 25 Jan 2014 16:43:15 +0000');//query filter

$products = Bigcommerce::getProducts($filter);

But in the same way following one is working good.

$filter = array('sku' => 'CST-120');//query filter

$products = Bigcommerce::getProducts($filter);

So please any help me how can i change the date variable would be better


text:
Q: Display bluetooth name instead of MAC address in ListView when passing adapter with ArrayList of type BluetoothDevice as last argument The following code shows the MAC address of each bluetooth found on the listview since I am passing ArrayList of type BluetoothDevice.  I know I can get the name of each bluetooth device by using BlueToothDevice.EXTRA_NAME and then put all of them in an ArrayList of type String then pass this ArrayList to get what I want.  However, I can't do that because ArrayList of type BluetoothDevice are those devices (with the MAC address) that I need to connect to when user clicks on it.  This way I can connect to each of the bluetooth device but on the listview only the MAC address of each bluetooth device is shown.  How can I make it to show the bluetooth's name instead of its MAC address and still able to connect. Thank You.
private ArrayList<BluetoothDevice> deviceList = new ArrayList<BluetoothDevice>();

ArrayAdapter adapter = new ArrayAdapter<BluetoothDevice>(this, android.R.layout.simple_list_item_1, deviceList);

btListView.setAdapter(adapter);


text:
Q: Using readonly structs as Dictionary Key I was wondering how readonly structs behave when used a key in a Dictionary. I'm aware the combition of readonly and 'in' is to prevent copies of large structs being made unnecessarily and that the scenario described below is hardly considered 'large'. However I am curious and I want to keep code simple.
For example
public readonly struct MyStruct
{
    public int Value1 { get; }
    public int Value2 { get; }

    public MyStruct(int val1, int val2)
    {
        Value1 = val1;
        Value2 = val2;
    }

    //also overries GetHashCode and Equals
}

Now if I was to create a method that took one of these structs and used it's data, because it is marked readonly, I can mark that parameter as an 'in' parameter
public int MyMethod(in MyStruct mystruct)
{
    //do stuff
    return 0;
}

It is my understanding that doing this stops the struct having a protective copy created to ensure that it is not modified inside the method.
So far so good I hope.
Now to the meat of the question.
What happens when I use a readonly struct as a key in my dictionary?
public Dictionary<MyStruct, string> MyDict;

when doing
var myStruct = new MyStruct(1,2);
mydict.Add(myStruct,"value");

Is a copy of my readonly struct made? Since the method signature does not use 'in' for the key parameter.
Also when attempting to do some thing like TryGetValue
myDict.TryGetValue(myStruct, out var myString);

Will this again make a copy of myStruct?
And lastly what about using the index to look up into the Dictionary?
var myVal = myDict[myStruct]

If copies are made and the primary use case of my struct is to be used as a key is it pointless marking it with the readonly keyword?


text:
Q: Git and merging commits I have several commits, some related to similar tasks, for instance:
eedf6b3 Task A (Continue)
12364e5 Task D
da77ed3 Task C
9e1991a Taks B (Continue)
cb345c1 Task A (Continue)
83b1c27 Task B
9b3c83c Task A

I would like to merge similar tasks into a single task with a new comment.
I came across 'git rebase -i ' but for some reason it didnt (or I misunderstood it....) do the trick.

A: git rebase is a very powerful tool, so be careful while using it. It is generally not a good idea to rebase shared commits (i.e. ones that you've pushed to GitHub, or shared with collaborators in some other way).
Here is how you can use rebase -i to re-arrange your commits, assuming they go from oldest at the bottom to newest at the top:

*

*git rebase -i HEAD~7
This will dump you into your default text editor with a buffer containgint something like this:
pick 9b3c83c Task A
pick 83b1c27 Task B
pick cb345c1 Task A (Continue)
pick 9e1991a Taks B (Continue)
pick da77ed3 Task C
pick 12364e5 Task D
pick eedf6b3 Task A (Continue)

*First, modify the buffer so that the commits are in the order you want. That is, cut and paste until you get something like:
pick 9b3c83c Task A
pick cb345c1 Task A (Continue)
pick eedf6b3 Task A (Continue)
pick 83b1c27 Task B
pick 9e1991a Taks B (Continue)
pick da77ed3 Task C
pick 12364e5 Task D

*Now, change commits that are part of a previous commit from pick to squash:
pick 9b3c83c Task A
squash cb345c1 Task A (Continue)
squash eedf6b3 Task A (Continue)
pick 83b1c27 Task B
squash 9e1991a Taks B (Continue)
pick da77ed3 Task C
pick 12364e5 Task D

*Once you're happy with what you've got, save the file and exit your editor. Git will look at the file you saved and reorder the commits as you did, squashing the ones marked squash into the previous commit.
This can cause conflicts, but if the different tasks were well separated they shouldn't be terribly complex ones. Just resolve those conflicts as normal. Git will prompt you with how to do this if it comes up.
The Changing Multiple Commit Messages section of Pro Git is a useful reference.

A: First, to get the terminology clear:
You can't merge commits, you can only merge branches.
If you have a branch called dev and you want to have some (not all) commits in your master branch, you will have to use cherry-picking.
That means, you take some commits from the dev-branch to your master-branch.
For that check out master then use
git cherry-pick <commit>

For further reading, see the manpage of git cherry-pick


text:
Q: Sum attributes in rails I have a rails model that has a 'percentage' attribute
I would like to make sure the sum of of all 'percentage' is not > 100 when adding new values.
In my model, I have
validate :sum_can_not_exceed_hundred
def sum_can_not_exceed_hundred
  if Result.all.sum(:percentage) > 100
    errors.add(:base, :sum_can_not_exceed_hundred)
  end
end

But this does not work for adding the records that are not on the db and those are are already saved.
Update:
    The following seems to work, using a hint from Coderhs
if Result.where.not(id: self.id).sum(:percentage_share) + self.percentage_share > 100
    errors.add(:base, :sum_can_not_exceed_hundred)
end

A: Since your table is new it won't be available on Result.all. Try modifying the code like so
validate :sum_can_not_exceed_hundred
  def sum_can_not_exceed_hundred
    sum = if self.id
       Result.all.sum(:percentage)
    else
      self.percentage + Result.all.sum(:percentage)
    end
    errors.add(:base, :sum_can_not_exceed_hundred) if sum > 100
  end
end


text:
Q: How do you access browser information from an AIR application? I am trying to build an Adobe AIR application that will run on Linux/Mac OS/Windows, which monitors user's browsing history.
How can my AIR application find out which browsers are installed? In other words, the list of browsers' history to monitor.
Also is there any way to know if a browser is running or not at run time?
As for the history file, I've got some information on Firefox, so any information/link on reading/parsing history file of IE/Safari/Opera/Chrome will be appreciated.

A: *

*There is no API with which to do this.  I think your best bet is to look in the common locations where they are installed, i.e. "program files" or "applications" on Windows, Mac, etc.  If you absolutely need to find the browsers, you could walk the entire filesystem looking for the binaries, although that obviously has performance implications.

*AIR offers basically no integration with the operating system, so there is no real way to determine what is running and what's not.  If any of the browsers create temp files while running, you could check for the existence of them.


text:
Q: Convert any object to a byte[] I am writing a prototype TCP connection and I am having some trouble homogenizing the data to be sent.
At the moment, I am sending nothing but strings, but in the future we want to be able to send any object.
The code is quite simple at the moment, because I thought everything could be cast into a byte array:
void SendData(object headerObject, object bodyObject)
{
  byte[] header = (byte[])headerObject;  //strings at runtime,
  byte[] body = (byte[])bodyObject;      //invalid cast exception

  // Unable to cast object of type 'System.String' to type 'System.Byte[]'.
  ...
}

This of course is easily enough solved with a
if( state.headerObject is System.String ){...}

The problem is, if I do it that way, I need to check for EVERY type of object that can't be cast to a byte[] at runtime.
Since I do not know every object that can't be cast into a byte[] at runtime, this really isn't an option.
How does one convert any object at all into a byte array in C# .NET 4.0?

A: Like others have said before, you could use binary serialization, but it may produce an extra bytes or be deserialized into an objects with not exactly same data. Using reflection on the other hand is quite complicated and very slow.
There is an another solution that can strictly convert your objects to bytes and vise-versa - marshalling:
var size = Marshal.SizeOf(your_object);
// Both managed and unmanaged buffers required.
var bytes = new byte[size];
var ptr = Marshal.AllocHGlobal(size);
// Copy object byte-to-byte to unmanaged memory.
Marshal.StructureToPtr(your_object, ptr, false);
// Copy data from unmanaged memory to managed buffer.
Marshal.Copy(ptr, bytes, 0, size);
// Release unmanaged memory.
Marshal.FreeHGlobal(ptr);

And to convert bytes to object:
var bytes = new byte[size];
var ptr = Marshal.AllocHGlobal(size);
Marshal.Copy(bytes, 0, ptr, size);
var your_object = (YourType)Marshal.PtrToStructure(ptr, typeof(YourType));
Marshal.FreeHGlobal(ptr);

It's noticeably slower and partly unsafe to use this approach for small objects and structs comparing to your own serialization field by field (because of double copying from/to unmanaged memory), but it's easiest way to strictly convert object to byte[] without implementing serialization and without [Serializable] attribute.

A: Using Encoding.UTF8.GetBytes is faster than using MemoryStream.
Here, I am using NewtonsoftJson to convert input object to JSON string and then getting bytes from JSON string.
byte[] SerializeObject(object value) =>Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(value));

Benchmark for @Daniel DiPaolo's version with this version
Method                    |     Mean |     Error |    StdDev |   Median |  Gen 0 | Allocated |
--------------------------|----------|-----------|-----------|----------|--------|-----------|
ObjectToByteArray         | 4.983 us | 0.1183 us | 0.2622 us | 4.887 us | 0.9460 |    3.9 KB |
ObjectToByteArrayWithJson | 1.548 us | 0.0309 us | 0.0690 us | 1.528 us | 0.3090 |   1.27 KB |

A: Use the BinaryFormatter:
byte[] ObjectToByteArray(object obj)
{
    if(obj == null)
        return null;
    BinaryFormatter bf = new BinaryFormatter();
    using (MemoryStream ms = new MemoryStream())
    {
        bf.Serialize(ms, obj);
        return ms.ToArray();
    }
}

Note that obj and any properties/fields within obj (and so-on for all of their properties/fields) will all need to be tagged with the Serializable attribute to successfully be serialized with this.

A: Combined Solutions in Extensions class:
public static class Extensions {

    public static byte[] ToByteArray(this object obj) {
        var size = Marshal.SizeOf(data);
        var bytes = new byte[size];
        var ptr = Marshal.AllocHGlobal(size);
        Marshal.StructureToPtr(data, ptr, false);
        Marshal.Copy(ptr, bytes, 0, size);
        Marshal.FreeHGlobal(ptr);
        return bytes;
   }

    public static string Serialize(this object obj) {
        return JsonConvert.SerializeObject(obj);
   }

}

A: How about something simple like this?
return ((object[])value).Cast<byte>().ToArray();

A: What you're looking for is serialization.  There are several forms of serialization available for the .Net platform

*

*Binary Serialization

*XML Serialization: Produces a string which is easily convertible to a byte[]

*ProtoBuffers

A: public static class SerializerDeserializerExtensions
{
    public static byte[] Serializer(this object _object)
    {
        byte[] bytes;
        using (var _MemoryStream = new MemoryStream())
        {
            IFormatter _BinaryFormatter = new BinaryFormatter();
            _BinaryFormatter.Serialize(_MemoryStream, _object);
            bytes = _MemoryStream.ToArray();
        }
        return bytes;
    }

    public static T Deserializer<T>(this byte[] _byteArray)
    {
        T ReturnValue;
        using (var _MemoryStream = new MemoryStream(_byteArray))
        {
            IFormatter _BinaryFormatter = new BinaryFormatter();
            ReturnValue = (T)_BinaryFormatter.Deserialize(_MemoryStream);
        }
        return ReturnValue;
    }
}

You can use it like below code.
DataTable _DataTable = new DataTable();
_DataTable.Columns.Add(new DataColumn("Col1"));
_DataTable.Columns.Add(new DataColumn("Col2"));
_DataTable.Columns.Add(new DataColumn("Col3"));

for (int i = 0; i < 10; i++) {
    DataRow _DataRow = _DataTable.NewRow();
    _DataRow["Col1"] = (i + 1) + "Column 1";
    _DataRow["Col2"] = (i + 1) + "Column 2";
    _DataRow["Col3"] = (i + 1) + "Column 3";
    _DataTable.Rows.Add(_DataRow);
}

byte[] ByteArrayTest =  _DataTable.Serializer();
DataTable dt = ByteArrayTest.Deserializer<DataTable>();

A: checkout this article :http://www.morgantechspace.com/2013/08/convert-object-to-byte-array-and-vice.html
Use the below code
// Convert an object to a byte array
private byte[] ObjectToByteArray(Object obj)
{
    if(obj == null)
        return null;

    BinaryFormatter bf = new BinaryFormatter();
    MemoryStream ms = new MemoryStream();
    bf.Serialize(ms, obj);

    return ms.ToArray();
}

// Convert a byte array to an Object
private Object ByteArrayToObject(byte[] arrBytes)
{
    MemoryStream memStream = new MemoryStream();
    BinaryFormatter binForm = new BinaryFormatter();
    memStream.Write(arrBytes, 0, arrBytes.Length);
    memStream.Seek(0, SeekOrigin.Begin);
    Object obj = (Object) binForm.Deserialize(memStream);

    return obj;
}

A: I'd rather use the expression "serialization" than "casting into bytes". Serializing an object means converting it into a byte array (or XML, or something else) that can be used on the remote box to re-construct the object. In .NET, the Serializable attribute marks types whose objects can be serialized.

A: You could use the built-in serialization tools in the framework and serialize to a MemoryStream. This may be the most straightforward option, but might produce a larger byte[] than may be strictly necessary for your scenario.
If that is the case, you could utilize reflection to iterate over the fields and/or properties in the object to be serialized and manually write them to the MemoryStream, calling the serialization recursively if needed to serialize non-trivial types. This method is more complex and will take more time to implement, but allows you much more control over the serialized stream.

A: Alternative way to convert object to byte array:
TypeConverter objConverter = TypeDescriptor.GetConverter(objMsg.GetType());
byte[] data = (byte[])objConverter.ConvertTo(objMsg, typeof(byte[]));

A: One additional implementation, which uses Newtonsoft.Json binary JSON and does not require marking everything with the [Serializable] attribute. Only one drawback is that an object has to be wrapped in anonymous class, so byte array obtained with binary serialization can be different from this one.
public static byte[] ConvertToBytes(object obj)
{
    using (var ms = new MemoryStream())
    {
        using (var writer = new BsonWriter(ms))
        {
            var serializer = new JsonSerializer();
            serializer.Serialize(writer, new { Value = obj });
            return ms.ToArray();
        }
    }
}

Anonymous class is used because BSON should start with a class or array.
I have not tried to deserialize byte[] back to object and not sure if it works, but have tested the speed of conversion to byte[] and it completely satisfies my needs.


text:
Q: Angular 4 + PrimeNG Menu - Multiple menu items shown as active I am using

Angular 4.1.2 and PrimeNG 4.3.0

Issue I have having is with the PanelMenu i.e. p-panelMenu control.
The following is the structure of my Menu
{
    label: 'Demo',
    icon: 'fa-shield',
    items: [{
        label: 'Proposal',
        items: [
            { label: 'New', icon: 'fa-plus', routerLink: ['/proposal/create'], routerLinkActiveOptions: "{exact:true}" },
            { label: 'Open', icon: 'fa-search', routerLink: ['/proposal'] },
        ]
},

The issue I have is that whenever "New" is clicked, both "Open" and "New" get selected.
I have tried to avoid that by putting routerLinkActiveOptions: "{exact:true}" but it seems to not have any effect either.
Any pointers to documentation regarding API for routerLinkActiveOptions will be appreciated as well. Currently, i am unable to understand what properties / values I can set as options using routerLinkActiveOptions

A: To resolve this issue please make below changes to your menu model:

{
      label: 'Demo',
      icon: 'fa-shield',
      items: [{
        label: 'Proposal',
        items: [
          { label: 'New', icon: 'fa-plus', routerLink: ['/proposal/create'], routerLinkActiveOptions: { exact: true } },
          { label: 'Open', icon: 'fa-search', routerLink: ['/proposal'], routerLinkActiveOptions: { exact: true } },
        ]
      }]
}

For complete example follow: https://stackblitz.com/edit/angular-a27wca

A: It seems like issue with your route /proposal/create and /proposal/. when you click on New it first invoke proposal and then create that may be the reason of selecting both New and Open
Can you try with totally different routes something like /New and /Open in these case it should work fine.
If this doesn't work then i create a jsfiddle and give it a try :)


text:
Q: Should I keep the Apple Developer Team ID secret? Is it safe for me to post the Apple Team ID to a public forum (as in, for example, somebody is helping me to troubleshoot an issue and I post my .mobileprovision file, or a generated entitlements file that contains the team id, or I paste snippets of these to Stack Overflow)? Or should I obfuscate it first?

A: It probably doesn't matter. This information is generally obtainable in some cases anyway. For instance, to support certain web integrations, an app's site must host a apple-app-site-association file with all of the related apps and their bundle ids/ team ids listed.
For example, here is Facebook's:
https://www.facebook.com/apple-app-site-association


text:
Q: Export mosaic to Google Drive, generating more than just one file and can't download this I'm exporting a mosaic via google earth engine to google drive, however it has generated many files inside a folder.
// Create a geometry representing an export region.
var roi = ee.FeatureCollection('ft:15Y2IjO7bMc-COe8xOm3x1tfZdgb7GO4hK1TDWxGg');

// Load the Sentinel-2 ImageCollection.
var sentinel = ee.ImageCollection('COPERNICUS/S2').filterBounds(roi);
var s2 = sentinel.filterDate('2017-01-01', '2017-12-31');
var s3 = s2.filterMetadata('CLOUDY_PIXEL_PERCENTAGE', 'less_than', 0.1).sort("ascending");

// Mosaic

var mosaic = s3.median()
var bands = mosaic.select('B2', "B3", "B4", "B8")
Map.addLayer(bands,{}, "mosaic")

// Export
var task = Export.image.toDrive({
  image: bands,
  region: roi.getInfo()["coordinates"],
  scale: 10,
  description:'MOSAIC',
  folder: 'MOSAIC',
  fileNamePrefix: 'MOSAIC',
  maxPixels: 1e13
})

How to export to generate fewer files. How to download large files as mosaics to your computer?

Result from export

A: You do not get a valid export geometry by using .getInfo(). As a result it looks like Earth Engine is exporting your image globally and thus creates a multitude of subsets (called shards).
If you take the bounding box of your MultiPolygon the export produces a single file of about 11MB in size.
// Export
var task = Export.image.toDrive({
  image: bands,
  region: roi.geometry().bounds(),
  description:'MOSAIC',
  folder: 'MOSAIC',
  fileNamePrefix: 'MOSAIC',
  maxPixels: 1e13
})


text:
Q: Select chart within userform I am looking to write a macro which copies formatting from one graph and applies it to multiple other graphs.
What I am struggling to do is determine a way to allow the user to set the template chart and then select the multiple other charts.  While this could be done with a combo box if the user knew the chart name, I am trying to do it without them knowing the chart name.
As such I was thinking of having a user dialog box where the user can select the base chart, and then select the charts to apply the formatting to.  Just like refedit for a range.  However I cannot figure out how to reference to a graph from within a user form.
Can this be done, and if so, how?

A: Here is what will get you started.
Place Two ComboBoxes and two Image Controls on the userform.

Let's say your worksheet looks like this

In the UserForm_Initialize() event populate the Chart names in both the comboboxes. For example
Dim ws As Worksheet

'~~> Prepare your form
Private Sub UserForm_Initialize()
    Set ws = ThisWorkbook.Sheets("Sheet1")

    Dim ChartObj As ChartObject

    For Each ChartObj In ActiveSheet.ChartObjects
        ComboBox1.AddItem ChartObj.Name
        ComboBox2.AddItem ChartObj.Name
    Next ChartObj
End Sub

So when you run the form, it will look like this

In the click event of the comboboxes, use the Stephen Bullen's PastePicture code from HERE to show the chart in the userform. For example
Private Sub ComboBox1_Click()
    ws.Shapes(ComboBox1.Value).CopyPicture
    Set Me.Image1.Picture = PastePicture(xlPicture)
End Sub

Private Sub ComboBox2_Click()
    ws.Shapes(ComboBox2.Value).CopyPicture
    Set Me.Image2.Picture = PastePicture(xlPicture)
End Sub

This is how the form will look.
From there on, Now you have the names of the charts. Simply use them to work as you please.
Hope this helps.

A: The following code should allow you to do stuff with the selected chart area(s), where you can either select one or many charts:
Public Sub ProcessSelectedCharts()
    Dim i As Integer
    Dim chart_obj As ChartObject
    Dim chart_area As chartArea

    If TypeOf Selection Is DrawingObjects Then
        For i = 1 To Selection.Count
            If TypeOf Selection(i) Is ChartObject Then
                Set chart_obj = Selection(i)
                Set chart_area = chart_obj.Chart.chartArea
                Call ProcessChart(chart_area)
            End If
        Next i
    ElseIf TypeOf Selection Is chartArea Then
        Set chart_area = Selection
        Call ProcessChart(chart_area)
    End If

End Sub

Public Sub ProcessChart(obj As chartArea)
    ' Do something...
End Sub

You may want to refine this a little, i.e. this should work if the user selects the actual charts, but may fail if he only selects a particular element within the chart.
Ok, the next question is, when do you invoke this from your user form. So first of all, your user form should be modal of course, to allow the user the select anything. So how do you notice when the users actually selects anything?
I can think of three methods, and I'll list them from best to worst (the last 2 only described very briefly as I wouldn't recommend using them):

*

*Use the "Worksheet_SelectionChange" event on your worksheet, and have it call a method within your userform to inform it that the selection has changed. Now you'll just need to check if, and which charts have been selected (see code above), and run your algorithm.

*Run a timer in your userform and regularly check the active selection.

*Hook mouse events by DLL calls and register any mouse clicks, then check for selection changes.
That should allow you to create a ref-edit like feature for selecting charts on your worksheet from a userform.


text:
Q: Joe Eames tutorial Multivision -- Jade convert I am following Joe Eames tutorial - Buiding Angular JS and Node.js Apps withe MEAN stack-- and got stuck on the part of 'Persistinh Login between page refreshed'
This project done with .Jade but I went with just html. So, there is jade file showing
if !!boostrappedUser
script.
window.bootstrappedUserObject = !{JSON.stringify(bootstrappedUser)}

I converted
<script>

if(!!boostrappedUser){window.bootstrappedUserObject = !{JSON.stringify(bootstrappedUser)}

}
unfortunately, it did not go through.
what is the exact conversion that jade code to html?

A: this one doesn't require any conversion, the result will be generated one the run time something like  this
    <script>
    window.bootstrappedUserObject = {
"_id":"53f00772eea207ab2f164332",
"firstName":"asdf",
"lastName":"asdf",
"userName":"jl",
"salt":"1y5kZRC+0IuWLFKvmiZ3miO1X4WOyloOYDhgQmhaEEZ4Ioji0AYCDMTZmvYd7yO/8QVRk4gsq7PrJ7XjbZJyJRCm1T6ejCDEin2R+6eN+QOu6pLdC/mOWvbxsAcaxI5Ko6t511OYDyw6I1OxoNMCadme2rMYmsczJOvSVPG6Okw=",
"hashed_password":"e7dbd23b3d71c4348c6708e7f07e446332275d80","__v":0,
"roles":[]}
</script>

just to ensure that the system would get the same user information if you refreshed the brower


text:
Q: How to compile linux kernel subdirectory? I want to compile linux kernel subdirectory just like this:
make M=drivers/staging/comedi/

Unfortunately when I do this I get this error:
  ERROR: Kernel configuration is invalid.
         include/generated/autoconf.h or include/config/auto.conf are missing.
         Run 'make oldconfig && make prepare' on kernel src to fix it.

Makefile:648: include/config/auto.conf: Nie ma takiego pliku ani katalogu
make: *** [Makefile:719: include/config/auto.conf] Błąd 1

It may be fixed by this command:
make oldconfig

After executing it, I have to press enter for 2 minutes to select the default options everywhere, and then I get this error anyway:
  AR      drivers/staging/comedi//built-in.a
WARNING: Symbol version dump "Module.symvers" is missing.
         Modules may not have dependencies or modversions.
  MODPOST drivers/staging/comedi//Module.symvers
/bin/sh: scripts/mod/modpost: Nie ma takiego pliku ani katalogu
make[1]: *** [scripts/Makefile.modpost:111: drivers/staging/comedi//Module.symvers] Błąd 127
make: *** [Makefile:1701: modules] Błąd 2

I have seen many times in the videos people just building a subdirectory with one make M=somedir command. Why doesn't it work for me?


text: Q: Scraping the last tweets of a selected user I'm using the function searchTwitter of package twitteR to retrieve any authorized tweets which match the search criteria. My question is: Is it possible to scrape the tweets that a selected user posted in the last week? E.g., I would like to download the last tweets of @CNN user.


text:
Q: How to sort an array of objects by a key and then push the other key to a new array in the sorted order? Let's say we have an array of objects called result:
{ "name": "C:\\file.json", "relevance": 0.5 }

{ "name": "C:\\folder", "relevance": 0.5454545454545454 }

{ "name": "C:\\file_1.txt", "relevance": 0.1 }

How do we sort it by relevance key and push the name values into a new array in the sorted order, so that we get the following arr:
["C:\\folder", "C:\\file.json", "C:\\file_1.txt"]

UPDATE
It's not a duplicate! I don't know why people in js threads always marking answers as duplicate, even when they very much aren't

A: You can do it like this;

var result = [ { "name": "C:\\file.json", "relevance": 0.5 }, { "name": "C:\\folder", "relevance": 0.5454545454545454 }, { "name": "C:\\file_1.txt", "relevance": 0.1 } ]
var newArray = result.sort((a, b) => parseFloat(b.relevance) - parseFloat(a.relevance)).map(item => item.name);
console.log(newArray);


text:
Q: Activity Monitor Log: Default Browser On clicking a notification below the menu bar in VS2019 16.8.2, the Activity Monitor Log opens in Internet Explorer.
The Web Browser section in Options=>Environment only has an Internet Options link for IE. Internet Explorer will be retired soon, is there, or will there be provision for sending the log to an alternative browser, or even another program, e.g. this viewer?

A: One thing not attempted before posting the question was to try the suggestion at MS Docs:

By default, the log file is located here:
%APPDATA%\Microsoft\VisualStudio<Version>\ActivityLog.xml
where  is the Visual Studio version. However, you may specify
a different path and file name.

And also here:

For example, the command devenv /log output.txt opens the IDE and
outputs all log information for that session to output.txt.

Clicking on the IDE to launch the log is as per file association. The xml extension was for some reason defaulted to IE on this rig.
So, not really a problem, VS launches the file correctly by default, and as per file extension settings.


text:
Q: Spring Boot + Angular assets I have a project in Spring Boot which is using the in-built web-server and angular as a front-end. When the Angular application is started, it reads the configuration from env.json which lies in the assets folder.
Now, I want to tell spring boot from outside, like env variables or a file as mount-point to propagate it to the assets folder. I want that the env.json within the assets folder contains the value corresponding to the outside env-variable I define.
With that approach I can use one container image and tell the app in which env it is.
This app is gonna be containerized and has to run in K8s.
Can someone give me a tip or approach to tackle this problem?
Here was a similar question
Single build multi deployment for docker image created from Springboot+Angular Jar
Pass Angular environment variables to compiled static angular files in spring boot


text:
Q: Use a Tiledmap service as basemap instead of an Arcgis.com map in AMD style coding How will I define a arcgisTiled map service as the base map (instead of "topo") as against using arcgis.com map services while defining a new map in AMD style?
map = new Map("map", {
          basemap: "topo",
          center: [-122.445, 37.752],
          zoom: 14
        });

I would like to replace "topo" with a map tiledservice from my server:
http://ourserver/arcgis/rest/services/tiledmapservice/MapServer

Any thoughts?

A: You can simply not set the basemap in the Map constructor and add an ArcGISTiledMapServiceLayer pointing to your endpoint.
API Reference:
https://developers.arcgis.com/en/flex/api-reference/com/esri/ags/layers/ArcGISTiledMapServiceLayer.html
Example:
<script>
  var map;

  require(["esri/map", "esri/layers/ArcGISTiledMapServiceLayer", "dojo/domReady!"],
    function(Map, Tiled) {
      map = new Map("map");

      var tiled = new Tiled("http://ourserver/arcgis/rest/services/tiledmapservice/MapServer");
      map.addLayer(tiled);
    }
  );
</script>

A full sample is available at:
https://developers.arcgis.com/en/javascript/jssamples/layers_ags_tiled.html


text:
Q: How do I know when download from a URL is completed? On my project I use something like the following function to redirect users in order to download a file
function promptDownload(file){
      location.href = "http://example.com/downloads/"+file;
}

As we all know, when I call this function, browser only prompts a download dialog and does not interrupt my application flow. What I would like to do is to determine when this download completed or cancelled.
There should be something like onLoad, onFinishedLoading, onConnectionEnd or etc but I couldn't find anything.

A: You can't determine download progress if you download the file that way.
If you download the file using XMLHttpRequest, then you can listen for load, error and progress events like this:
function log(message) {
  return function () {
    alert(message);
  };
}

function download(file, callback) {
  var request = new XMLHttpRequest();
  request.responseType = 'blob';
  request.open('GET', file);
  request.addEventListener('load', log('load ' + file));
  request.addEventListener('error', log('error ' + file));
  request.addEventListener('progress', log('progress ' + file));
  request.addEventListener('load', function () {
    callback(request.response);
  });
  request.send();
}

function save(object, mime, name) {
  var a = document.createElement('a');
  var url = URL.createObjectURL(object);
  a.href = url;
  a.download = name;
  a.click();
}

document.querySelector('#download').addEventListener('click', function () {
  download('test.pdf', function (file) {
    save(file, 'application/pdf', 'test.pdf');
  });
});

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
  </head>
  <body>
    <button id="download">Download</button>
    <script src="script.js"></script>
  </body>
</html>


text:
Q: How to pull from private docker repository on docker hub? I create a automated build repository on dockerhub (via github) and try to pull the image which is automatically built onto cloud server.
using things like
docker pull com.company/project:tag
but it gives me
Error: image com.company/project:tag not found

it usually works for public repository, do I have to do something else for private repository ?

A: You just need to use the command docker login with your sign parameters from docker hub.

A: Another way to do this is to create a docker config.json file. The file should be placed in ~/.docker/config.json and the Docker Hub authorization token can be specified in the file.
{
    "auths": {
        "https://index.docker.io/v1/": {
            "auth": "my-docker-hub-generated-auth-token"
        }
    }
}

This is a useful strategy if you are working with servers that need the ability to run scripts that pull images from Docker Hub.
Resources and further infomration:

*

*https://docs.docker.com/engine/reference/commandline/login/#privileged-user-requirement

*docker unauthorized: authentication required - upon push with successful login


text:
Q: `eval` in chrome extension in mv3 I'm looking for a way to use eval within a popup chrome extension using mv3.
Looking this up, I found this link. Of course, I wanted more info on sandbox, which led me here, and it states:

Warning: Starting in version 57, Chrome will no longer allow external web content (including embedded frames and scripts) inside sandboxed pages. Please use a webview instead.

So I visited the webview page and it says:

This API is part of the deprecated Chrome Apps platform. Learn more about migrating your app.

I am now a bit unsure of what to do, specially since the webview page was last updated on 2018.
Does anyone know how I should go about using eval in a MV3 popup chrome extension?


text:
Q: выдвигающееся боковое меню pyqt У меня есть код приложения, я хочу сделать так, чтобы при нажатии pushButton_13 слева  на право открывалось или выдвигалось меню, с пунктами 1, 2, 3, и.т.д.
Можно ли это как-то осуществить?
код nvutimain.py
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from nvutidesign import Ui_MainWindow

class ExampleApp(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

if __name__=="__main__":
    app = QtWidgets.QApplication(sys.argv)
    window = ExampleApp()
    window.show()
    sys.exit(app.exec_())

nvutidesign.py
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'e:/nvuti/nvutidesign.ui'
#
# Created by: PyQt5 UI code generator 5.14.0
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(870, 569)
        MainWindow.setMinimumSize(QtCore.QSize(870, 569))
        MainWindow.setMaximumSize(QtCore.QSize(870, 569))
        font = QtGui.QFont()
        font.setStyleStrategy(QtGui.QFont.PreferAntialias)
        MainWindow.setFont(font)
        MainWindow.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
        MainWindow.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0.011, y1:1, x2:1, y2:0, stop:0 rgba(182, 29, 212, 255), stop:1 rgba(48, 7, 182, 255));\n"
"")
        MainWindow.setAnimated(True)
        MainWindow.setDocumentMode(False)
        MainWindow.setTabShape(QtWidgets.QTabWidget.Rounded)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setStyleSheet("")
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(170, 380, 221, 71))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(20)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton.setFont(font)
        self.pushButton.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.pushButton.setStyleSheet("background-color: rgb(141, 142, 161);\n"
"border-radius: 10px;\n"
"color: rgb(255, 255, 255);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
"    background-color: rgb(138, 138, 138);\n"
"\n"
"\n"
"")
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(470, 380, 221, 71))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(20)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_2.setFont(font)
        self.pushButton_2.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.pushButton_2.setStyleSheet("background-color: rgb(141, 142, 161);\n"
"border-radius: 10px;\n"
"color: rgb(255, 255, 255);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
"    background-color: rgb(138, 138, 138);\n"
"")
        self.pushButton_2.setObjectName("pushButton_2")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(330, 220, 201, 23))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.label_3.setFont(font)
        self.label_3.setStyleSheet("background-color: rgb(alpha 0.5);\n"
"color: rgb(255, 255, 255);")
        self.label_3.setAlignment(QtCore.Qt.AlignCenter)
        self.label_3.setObjectName("label_3")
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(20, 80, 781, 141))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(72)
        self.label_4.setFont(font)
        self.label_4.setStyleSheet("background-color: rgb(alpha 0.5);\n"
"color: rgb(97, 118, 255);\n"
"\n"
"")
        self.label_4.setAlignment(QtCore.Qt.AlignCenter)
        self.label_4.setObjectName("label_4")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(170, 260, 221, 51))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(15)
        font.setStyleStrategy(QtGui.QFont.PreferAntialias)
        self.lineEdit.setFont(font)
        self.lineEdit.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"border-radius: 10px;\n"
"border: 2px solid gray;           \n"
"border-radius: 10px;\n"
"pIntValidator.setRange(1, 95)")
        self.lineEdit.setMaxLength(99999)
        self.lineEdit.setAlignment(QtCore.Qt.AlignCenter)
        self.lineEdit.setReadOnly(False)
        self.lineEdit.setClearButtonEnabled(True)
        self.lineEdit.setObjectName("lineEdit")
        self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_3.setGeometry(QtCore.QRect(210, 460, 61, 21))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(9)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_3.setFont(font)
        self.pushButton_3.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.pushButton_3.setStyleSheet("background-color: rgb(162, 162, 162);\n"
"border-radius: 5px;\n"
"color: rgb(255, 255, 255);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
"    background-color: rgb(138, 138, 138);\n"
"")
        self.pushButton_3.setObjectName("pushButton_3")
        self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_4.setGeometry(QtCore.QRect(280, 460, 61, 21))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(9)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_4.setFont(font)
        self.pushButton_4.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.pushButton_4.setStyleSheet("background-color: rgb(162, 162, 162);\n"
"border-radius: 5px;\n"
"color: rgb(255, 255, 255);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
"    background-color: rgb(138, 138, 138);\n"
"")
        self.pushButton_4.setObjectName("pushButton_4")
        self.pushButton_5 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_5.setGeometry(QtCore.QRect(230, 490, 41, 21))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(9)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_5.setFont(font)
        self.pushButton_5.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.pushButton_5.setStyleSheet("background-color: rgb(162, 162, 162);\n"
"border-radius: 5px;\n"
"color: rgb(255, 255, 255);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
"    background-color: rgb(138, 138, 138);\n"
"")
        self.pushButton_5.setObjectName("pushButton_5")
        self.pushButton_6 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_6.setGeometry(QtCore.QRect(280, 490, 41, 21))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(9)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_6.setFont(font)
        self.pushButton_6.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.pushButton_6.setStyleSheet("background-color: rgb(162, 162, 162);\n"
"border-radius: 5px;\n"
"color: rgb(255, 255, 255);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
"    background-color: rgb(138, 138, 138);\n"
"")
        self.pushButton_6.setObjectName("pushButton_6")
        self.pushButton_7 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_7.setGeometry(QtCore.QRect(590, 460, 61, 21))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(9)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_7.setFont(font)
        self.pushButton_7.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.pushButton_7.setStyleSheet("background-color: rgb(162, 162, 162);\n"
"border-radius: 5px;\n"
"color: rgb(255, 255, 255);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
"    background-color: rgb(138, 138, 138);\n"
"")
        self.pushButton_7.setObjectName("pushButton_7")
        self.pushButton_8 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_8.setGeometry(QtCore.QRect(520, 460, 61, 21))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(9)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_8.setFont(font)
        self.pushButton_8.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.pushButton_8.setStyleSheet("background-color: rgb(162, 162, 162);\n"
"border-radius: 5px;\n"
"color: rgb(255, 255, 255);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
"    background-color: rgb(138, 138, 138);\n"
"")
        self.pushButton_8.setObjectName("pushButton_8")
        self.pushButton_9 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_9.setGeometry(QtCore.QRect(590, 490, 41, 21))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(9)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_9.setFont(font)
        self.pushButton_9.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.pushButton_9.setStyleSheet("background-color: rgb(162, 162, 162);\n"
"border-radius: 5px;\n"
"color: rgb(255, 255, 255);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
"    background-color: rgb(138, 138, 138);\n"
"")
        self.pushButton_9.setObjectName("pushButton_9")
        self.pushButton_10 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_10.setGeometry(QtCore.QRect(540, 490, 41, 21))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(9)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_10.setFont(font)
        self.pushButton_10.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.pushButton_10.setStyleSheet("background-color: rgb(162, 162, 162);\n"
"border-radius: 5px;\n"
"color: rgb(255, 255, 255);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
"    background-color: rgb(138, 138, 138);\n"
"")
        self.pushButton_10.setObjectName("pushButton_10")
        self.label_5 = QtWidgets.QLabel(self.centralwidget)
        self.label_5.setGeometry(QtCore.QRect(10, 500, 841, 61))
        font = QtGui.QFont()
        font.setPointSize(50)
        font.setStyleStrategy(QtGui.QFont.PreferAntialias)
        self.label_5.setFont(font)
        self.label_5.setStyleSheet("background-color: rgb(alpha 0.5);\n"
"color: rgb(255, 255, 255);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
"    background-color: rgb(138, 138, 138);\n"
"")
        self.label_5.setAlignment(QtCore.Qt.AlignCenter)
        self.label_5.setObjectName("label_5")
        self.label_6 = QtWidgets.QLabel(self.centralwidget)
        self.label_6.setGeometry(QtCore.QRect(400, 480, 61, 16))
        font = QtGui.QFont()
        font.setPointSize(13)
        font.setStyleStrategy(QtGui.QFont.PreferAntialias)
        self.label_6.setFont(font)
        self.label_6.setStyleSheet("background-color: rgb(alpha 0.5);\n"
"color: rgb(231, 231, 231);")
        self.label_6.setObjectName("label_6")
        self.pushButton_11 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_11.setGeometry(QtCore.QRect(320, 20, 101, 31))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(9)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_11.setFont(font)
        self.pushButton_11.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.pushButton_11.setStyleSheet("background-color: rgb(162, 162, 162);\n"
"border-radius: 5px;\n"
"color: rgb(255, 255, 255);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
"    background-color: rgb(138, 138, 138);\n"
"")
        self.pushButton_11.setObjectName("pushButton_11")
        self.pushButton_12 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_12.setGeometry(QtCore.QRect(440, 20, 101, 31))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(9)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_12.setFont(font)
        self.pushButton_12.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.pushButton_12.setStyleSheet("background-color: rgb(170, 170, 170);\n"
"border-radius: 5px;\n"
"color: rgb(255, 255, 255);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
"    background-color: rgb(138, 138, 138);\n"
"")
        self.pushButton_12.setObjectName("pushButton_12")
        self.label_7 = QtWidgets.QLabel(self.centralwidget)
        self.label_7.setGeometry(QtCore.QRect(0, 550, 61, 21))
        self.label_7.setStyleSheet("background-color: rgb(alpha 0.5);\n"
"color: rgb(255, 255, 255);")
        self.label_7.setObjectName("label_7")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(260, 350, 28, 23))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.label_2.setFont(font)
        self.label_2.setStyleSheet("background-color: rgb(alpha 0.5);\n"
"color: rgb(255, 255, 255);")
        self.label_2.setAlignment(QtCore.Qt.AlignCenter)
        self.label_2.setObjectName("label_2")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(507, 350, 161, 23))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.label.setFont(font)
        self.label.setStyleSheet("background-color: rgb(alpha 0.5);\n"
"color: rgb(255, 255, 255);")
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName("label")
        self.spinBox = QtWidgets.QSpinBox(self.centralwidget)
        self.spinBox.setGeometry(QtCore.QRect(470, 260, 221, 51))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(15)
        self.spinBox.setFont(font)
        self.spinBox.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"border-radius: 10px;\n"
"border: 2px solid gray;\n"
"border-radius: 10px;")
        self.spinBox.setWrapping(False)
        self.spinBox.setAlignment(QtCore.Qt.AlignCenter)
        self.spinBox.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
        self.spinBox.setPrefix("")
        self.spinBox.setMinimum(1)
        self.spinBox.setMaximum(95)
        self.spinBox.setSingleStep(1)
        self.spinBox.setProperty("value", 90)
        self.spinBox.setObjectName("spinBox")
        self.label_8 = QtWidgets.QLabel(self.centralwidget)
        self.label_8.setGeometry(QtCore.QRect(490, 310, 211, 16))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(10)
        font.setStyleStrategy(QtGui.QFont.PreferAntialias)
        self.label_8.setFont(font)
        self.label_8.setStyleSheet("background-color: rgb(alpha 0.5);\n"
"color: rgb(255, 255, 255);")
        self.label_8.setObjectName("label_8")
        self.label_9 = QtWidgets.QLabel(self.centralwidget)
        self.label_9.setGeometry(QtCore.QRect(480, 310, 47, 21))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_9.setFont(font)
        self.label_9.setStyleSheet("background-color: rgb(alpha 0.5);\n"
"color: rgb(255, 255, 255);")
        self.label_9.setObjectName("label_9")
        self.lineEdit_3 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_3.setGeometry(QtCore.QRect(0, 0, 21, 20))
        self.lineEdit_3.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"border-radius: 1px;")
        self.lineEdit_3.setReadOnly(True)
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.pushButton_13 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_13.setGeometry(QtCore.QRect(0, 0, 51, 41))
        self.pushButton_13.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"border-radius: 5px;\n"
"}\n"
"\n"
"QPushButton:hover {\n"
"    background-color: rgb(191, 191, 191);\n"
"}\n"
"\n"
"QPushButton:clicked {\n"
"    background-color: rgb(255, 255, 0);\n"
"\n"
"")
        self.pushButton_13.setText("")
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("e:/nvuti\\123.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.pushButton_13.setIcon(icon)
        self.pushButton_13.setIconSize(QtCore.QSize(55, 55))
        self.pushButton_13.setFlat(False)
        self.pushButton_13.setObjectName("pushButton_13")
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Nvuti"))
        self.pushButton.setText(_translate("MainWindow", "Меньше"))
        self.pushButton_2.setText(_translate("MainWindow", "Больше"))
        self.label_3.setText(_translate("MainWindow", "Возможный выигрыш"))
        self.label_4.setText(_translate("MainWindow", "0.00"))
        self.lineEdit.setPlaceholderText(_translate("MainWindow", "Сумма"))
        self.pushButton_3.setText(_translate("MainWindow", "Удвоить"))
        self.pushButton_4.setText(_translate("MainWindow", "Половина"))
        self.pushButton_5.setText(_translate("MainWindow", "Макс."))
        self.pushButton_6.setText(_translate("MainWindow", "Мин."))
        self.pushButton_7.setText(_translate("MainWindow", "Половина"))
        self.pushButton_8.setText(_translate("MainWindow", "Удвоить"))
        self.pushButton_9.setText(_translate("MainWindow", "Мин."))
        self.pushButton_10.setText(_translate("MainWindow", "Макс."))
        self.label_5.setText(_translate("MainWindow", "700"))
        self.label_6.setText(_translate("MainWindow", "Баланс"))
        self.pushButton_11.setText(_translate("MainWindow", "Пополнить"))
        self.pushButton_12.setText(_translate("MainWindow", "Вывести"))
        self.label_7.setText(_translate("MainWindow", "Nvuti 2020©"))
        self.label_2.setText(_translate("MainWindow", "0-0"))
        self.label.setText(_translate("MainWindow", "999999 - 999999"))
        self.spinBox.setSuffix(_translate("MainWindow", "%"))
        self.label_8.setText(_translate("MainWindow", "Максимальный процент - 95%"))
        self.label_9.setText(_translate("MainWindow", "*"))

На примере скайпа

A: Вы не используете Layouts, поэтому говорить о чем-то выдвигающемся преждевременно.
А на счет меню - пожалуйста, только уберите из модуля nvutidesign.py все что связано с pushButton_13 и обратите внимание на lineEdit_3, который был спрятан за pushButton_13 и я его немного выдвинул, чтобы вы обратили внимание.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from nvutidesign import Ui_MainWindow

class ExampleApp(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.menu_bar = QtWidgets.QMenuBar(self.centralwidget)
        self.menu_bar.setGeometry(QtCore.QRect(1, 1, 51, 21))

        self.menu     = QtWidgets.QMenu('MENU', self)

        self.menu_action = QtWidgets.QAction('Option #1', self)
        # setData - Устанавливает внутренние данные действия в данные userData.
        self.menu_action.setData('option1')

        self.menu_action2 = QtWidgets.QAction('Option #2', self)
        self.menu_action3 = QtWidgets.QAction('Option #3', self)

        self.menu_action.triggered.connect(self.actionClicked)
        self.menu_action2.triggered.connect(self.actionClicked)
        self.menu_action3.triggered.connect(self.actionClicked)

        self.menu.addAction(self.menu_action)
        self.menu.addAction(self.menu_action2)
        self.menu.addAction(self.menu_action3)

        self.menu_bar.addMenu(self.menu)

    def actionClicked(self):
        action = self.sender()
        print(action.text())
        print(action.data())

if __name__=="__main__":
    app = QtWidgets.QApplication(sys.argv)
    window = ExampleApp()
    window.show()
    sys.exit(app.exec_())

можно ли изменить размер Option #1,2 и 3? в ширину и длину?

Да, все возможно.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from nvutidesign import Ui_MainWindow

class ExampleApp(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.menu_bar = QtWidgets.QMenuBar(self.centralwidget)
        self.menu_bar.setNativeMenuBar(False)                      # ???
        self.menu_bar.setGeometry(QtCore.QRect(1, 1, 51, 21))

        self.menu     = QtWidgets.QMenu('MENU', self)

        self.menu_action = QtWidgets.QAction('Option #1', self)
        # setData - Устанавливает внутренние данные действия в данные userData.
        self.menu_action.setData('option1')

        self.menu_action2 = QtWidgets.QAction('Option #2', self)
        self.menu_action3 = QtWidgets.QAction('Option #3', self)

        self.action4     = QtWidgets.QWidgetAction(self)
        self.label4 = QtWidgets.QLabel('Hello \nWorld')
        self.action4.setDefaultWidget(self.label4);
        self.action4.setText('Hello World')
        self.label4.setStyleSheet("""
            QLabel {
                background-color : red;
                padding: 10px 12px 10px 12px;
                min-width: 200px;
                color: #000;
                font: italic bold 16px;
            }
            QLabel:hover { background-color: #C10000; color: #fff;}
            """)

        self.menu_action.triggered.connect(self.actionClicked)
        self.menu_action2.triggered.connect(self.actionClicked)
        self.menu_action3.triggered.connect(self.actionClicked)
        self.action4.triggered.connect(self.actionClicked)

        self.menu.addAction(self.menu_action)
        self.menu.addAction(self.menu_action2)
        self.menu.addAction(self.menu_action3)
        self.menu.addAction(self.action4)

        self.menu_bar.addMenu(self.menu)

    def actionClicked(self):
        action = self.sender()
        print(action.text())
        print(action.data())

if __name__=="__main__":
    app = QtWidgets.QApplication(sys.argv)
    window = ExampleApp()
    window.show()
    sys.exit(app.exec_())


text:
Q: Slim PHP : Fatal error: Using $this when not in object context I am working on a php application using slim micro framework
That is my index.php file:
<?php

require 'Slim/Slim.php';
include 'db.php';

\Slim\Slim::registerAutoloader();

$app = new \Slim\Slim();

$app->get("/", function () {
    echo "
HELLO USER
";
});

    //Registration view

    $app->post("/reg", function (){

        $request = $this->app->request();
        $username = $request->post('username');
        $password = $request->post('password');
        $name = $request->post('name');
        $email = $request->post('email');
        try {
            $sql = "INSERT INTO users (username, hash, name, email) VALUES (:username, :password, :name, :email)";
            $s = $this->dbh->prepare($sql);
            $s->bindParam("username", $username);
            $s->bindParam("hash", $password);
            $s->bindParam("name", $name);
            $s->bindParam("email", $email);
            $s->execute();
        } catch(\PDOException $e) {
            echo 'Exception: ' . $e->getMessage();
        }

    }); // Login Function End

$app->get('/updates', function () {
    //Display users

});

// run the Slim app

$app->run();

?>

and i have index.html file with ajax cross domain request like this one:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>INDEX</title>
<link href='css/style.css' rel='stylesheet' type='text/css'/>

<form id="put">
    Registration

    username: <input type="text" name="username" id="username"/>

    password: <input type="password" name="hash" />

    name: <input type="text" name="name" />

    email: <input type="text" name="email" />

    <input type="submit" />
</form>

the problem is that when i try and submit the form in my index.html file i always get:

Fatal error: Using $this when not in object context in C:\wamp\www\slim\index.php on line 19

A: $request = $this->app->request();

This is most likely line #19 and it's not inside an instance method, not even within a class definition. So, there is no instance reference and therefore no $this.
What do you expect $this to be? Apparently you need an app and an dbh. What is providing those properties/instances?
app could be $app = new \Slim\Slim();. But what is dbh supposed to be? (a database handle, ok, but what is providing this database connection handle?)

A: Basically the problem is what @VolkerK mentioned.
If you want your closure method to know about variables defined outside the scope of your method you'll want to use the use keyword.
$app->post("/reg", function () use ($app) {
    $request = $app->request();
}

A: Solution:
The full working index.php now look like:
<?php

require 'Slim/Slim.php';
include 'db.php';

\Slim\Slim::registerAutoloader();

$app = new \Slim\Slim();
$app->contentType('application/json');

$app->get('/', 'home');
$app->post('/adduser', 'addUser');
$app->get('/users', 'getUsers');

// Home view

function home() {echo "Welcome to the platform !";}

// Add users
function addUser() {
  global $app;
  $req = $app->request();

  $sql = "INSERT INTO users (username, password, fullname, email) VALUES (:username, :password, :fullname, :email)";
  try {
    $db = getDB();
    $stmt = $db->prepare($sql);
      $stmt->bindParam("username", $_POST['username']);
      $password = md5($_POST['password']);
      $stmt->bindParam("password", $password);
      $stmt->bindParam("fullname", $_POST['fullname']);
      $stmt->bindParam("email", $_POST['email']);
      $stmt->execute();
      $db = null;
  } catch(PDOException $e) {
      echo "Connection Error";
  }
}

// Get Users

function getUsers() {
    $sql = "SELECT username,fullname,email FROM users ORDER BY id";
    try {
        $db = getDB();
        $stmt = $db->query($sql);
        $users = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
        echo '{"users": ' . json_encode($users) . '}';
    } catch(PDOException $e) {
        //error_log($e->getMessage(), 3, '/var/tmp/php.log');
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }
}

// run the Slim app

$app->run();

?>