问:
Python RSA key, recieved the key but getting error "This is not a private key"
code for cilent

```<code>import socket, json
from Cryptodome.Cipher import PKCS1_OAEP, PKCS1_v1_5
from Cryptodome.Random import get_random_bytes
from Cryptodome.PublicKey import RSA

def getnewsocket():
    return socket.socket(socket.AF_INET, socket.SOCK_STREAM)

clientsocket = getnewsocket()
clientsocket.connect(('localhost', 8089))

rsa_public = clientsocket.recv(99999)
encyrpted = clientsocket.recv(99999)

print(rsa_public)
rsakey = RSA.import_key(rsa_public.decode())
print(rsakey)
cipher = PKCS1_OAEP.new(rsakey)
decrypted = cipher.decrypt(encyrpted)
print(decrypted)
</code>```

code for server

```<code>from Cryptodome.Cipher import PKCS1_OAEP, PKCS1_v1_5
from Cryptodome.Random import get_random_bytes
from Cryptodome.PublicKey import RSA
import socket
import json

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('0.0.0.0', 8089)) # 0.0.0.0 is a special address
print("Server activated, waiting for client to connect")
serversocket.listen(5)
connection, address = serversocket.accept()

rsakey_pair=RSA.generate(2048)
rsa_private = rsakey_pair
rsa_public = rsakey_pair.publickey().export_key()

hi = b"this is a plain text"
print(rsa_public)
cipher = PKCS1_OAEP.new(rsa_private)
encyrpted = cipher.encrypt(hi)
connection.sendall(rsa_public)
connection.sendall(encyrpted)
</code>```

tried alot of ways but is either getting bytes cannot be n or this is not a private key. Always unable to decrypt the content of ciper text at client. I guess the error is something related to socket only can send bytes, so when the key had send through the socket, although it is still in bytes but is a different kind of bytes

error :

```<code>  File "C:\Users\shang\AppData\Local\Programs\Python\Python37-32\lib\site-packages\Cryptodome\Cipher\PKCS1_OAEP.py", line 171, in decrypt
    m_int = self._key._decrypt(ct_int)
  File "C:\Users\shang\AppData\Local\Programs\Python\Python37-32\lib\site-packages\Cryptodome\PublicKey\RSA.py", line 151, in _decrypt
    raise TypeError("This is not a private key")
TypeError: This is not a private key
</code>```

答:
Well, yes, that's because it is a public key.

```<code>rsakey = RSA.import_key(rsa_public.decode())
cipher = PKCS1_OAEP.new(rsakey)
decrypted = cipher.decrypt(encyrpted)
</code>```

It is not possible to encrypt with a private key by definition. Encryption is performed using the public key, decryption using the private key. Public and private keys are not interchangeable for RSA. Maybe you want to generate a signature instead?

The only reason why the encryption with the private key succeeds is that it is likely that it also contains the public exponent and therefore the public key. Of course, the public key doesn't contain the private key as that needs to be kept private.

Note that even if it would be secure to encrypt with a private key if both keys (and thus the modulus) are kept private then you might as well use symmetric encryption, e.g. using the hash over the modulus as AES key.

Body:
code for cilent

import socket, json
from Cryptodome.Cipher import PKCS1_OAEP, PKCS1_v1_5
from Cryptodome.Random import get_random_bytes
from Cryptodome.PublicKey import RSA

def getnewsocket():
    return socket.socket(socket.AF_INET, socket.SOCK_STREAM)

clientsocket = getnewsocket()
clientsocket.connect(('localhost', 8089))

rsa_public = clientsocket.recv(99999)
encyrpted = clientsocket.recv(99999)

print(rsa_public)
rsakey = RSA.import_key(rsa_public.decode())
print(rsakey)
cipher = PKCS1_OAEP.new(rsakey)
decrypted = cipher.decrypt(encyrpted)
print(decrypted)

code for server

from Cryptodome.Cipher import PKCS1_OAEP, PKCS1_v1_5
from Cryptodome.Random import get_random_bytes
from Cryptodome.PublicKey import RSA
import socket
import json

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('0.0.0.0', 8089)) # 0.0.0.0 is a special address
print("Server activated, waiting for client to connect")
serversocket.listen(5)
connection, address = serversocket.accept()

rsakey_pair=RSA.generate(2048)
rsa_private = rsakey_pair
rsa_public = rsakey_pair.publickey().export_key()

hi = b"this is a plain text"
print(rsa_public)
cipher = PKCS1_OAEP.new(rsa_private)
encyrpted = cipher.encrypt(hi)
connection.sendall(rsa_public)
connection.sendall(encyrpted)

tried alot of ways but is either getting bytes cannot be n or this is not a private key. Always unable to decrypt the content of ciper text at client. I guess the error is something related to socket only can send bytes, so when the key had send through the socket, although it is still in bytes but is a different kind of bytes

error :

  File "C:\Users\shang\AppData\Local\Programs\Python\Python37-32\lib\site-packages\Cryptodome\Cipher\PKCS1_OAEP.py", line 171, in decrypt
    m_int = self._key._decrypt(ct_int)
  File "C:\Users\shang\AppData\Local\Programs\Python\Python37-32\lib\site-packages\Cryptodome\PublicKey\RSA.py", line 151, in _decrypt
    raise TypeError("This is not a private key")
TypeError: This is not a private key

Body:
Well, yes, that's because it is a public key.

rsakey = RSA.import_key(rsa_public.decode())
cipher = PKCS1_OAEP.new(rsakey)
decrypted = cipher.decrypt(encyrpted)

It is not possible to encrypt with a private key by definition. Encryption is performed using the public key, decryption using the private key. Public and private keys are not interchangeable for RSA. Maybe you want to generate a signature instead?

The only reason why the encryption with the private key succeeds is that it is likely that it also contains the public exponent and therefore the public key. Of course, the public key doesn't contain the private key as that needs to be kept private.

Note that even if it would be secure to encrypt with a private key if both keys (and thus the modulus) are kept private then you might as well use symmetric encryption, e.g. using the hash over the modulus as AES key.


来源: stackexchange

问:
FirebaseRecyclerAdapter is not displaying data in my RecyclerView layout
Please note there are lot of questions like these but none of them worked for me.
I have been trying to display data in a recycler view and it isnt displaying the data and not throwing any errors
Here is my code.

I have included the latest version of Firebase Dependencies and Latest version of Firebase UI Database

Dependencies Version

```<code>// Firebase
implementation 'com.google.firebase:firebase-auth:19.2.0'
implementation 'com.google.firebase:firebase-database:19.2.1'
implementation 'com.google.firebase:firebase-storage:19.1.1'

// Firebase UI
implementation 'com.firebaseui:firebase-ui-database:6.0.2'
</code>```

This is the Films class
Films.java

```<code>package com.dipeshpatil.in;

public class Films {

    public String name, year;

    public Films(String name, String year) {
        this.name = name;
        this.year = year;
    }

    public Films() {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }
}
</code>```

This is the ViewHolder Class FilmsViewHolder.java

```<code>package com.dipeshpatil.in;

import android.view.View;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

public class FilmsViewHolder extends RecyclerView.ViewHolder {
    public TextView mFilmName;
    public TextView mFilmYear;

    public FilmsViewHolder(View itemView){
        super(itemView);

        mFilmName = itemView.findViewById(R.id.user_single_name);
        mFilmYear = itemView.findViewById(R.id.user_single_status);
    }
}
</code>```

This is the activity where i am supposed to display the data in recycler view FilmsActivity.java

```<code>public class FilmsActivity extends AppCompatActivity {

    private RecyclerView mFilmsList;
    private DatabaseReference mFilmsDatabase;
    private FirebaseRecyclerOptions<Films> options;
    private FirebaseRecyclerAdapter<Films, FilmsViewHolder> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_films);

        mFilmsList = findViewById(R.id.films_list);
        mFilmsList.setHasFixedSize(true);

        mFilmsDatabase = FirebaseDatabase.getInstance().getReference().child("Films");

        options = new FirebaseRecyclerOptions.Builder<Films>()
                .setQuery(mFilmsDatabase, Films.class)
                .build();

        adapter = new FirebaseRecyclerAdapter<Films, FilmsViewHolder>(options) {
            @Override
            protected void onBindViewHolder(FilmsViewHolder filmsViewHolder, int i, Films films) {

                filmsViewHolder.mFilmName.setText(films.getName());
                filmsViewHolder.mFilmYear.setText(films.getYear());
            }

            @NonNull
            @Override
            public FilmsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

                View mView = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.users_single_layout, parent, false);

                return new FilmsViewHolder(mView);
            }
        };
        mFilmsList.setAdapter(adapter);
    }

    @Override
    protected void onStart() {
        super.onStart();
        adapter.startListening();
    }

    @Override
    protected void onStop() {
        super.onStop();
        adapter.stopListening();
    }
}
</code>```

Now honestly i am not getting any kind of error which would help me debug the code and check for problems and at the same time it is also not displaying my desired output

Firebase Database for Films

```<code>"Films" : {
    "01" : {
      "name" : "The Prestige",
      "year" : 2002
    },
    "02" : {
      "name" : "Fight Club",
      "year" : 1999
    }
}
</code>```

Layout File activity_films.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    tools:context=".FilmsActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="16dp"
        android:id="@+id/films_list" />
</LinearLayout>
</code>```

答:
I think there's usually a delay in when you get a response back from the Firebase query. Thats probably whats happening. By the time you initialize the adapter, the "options" list is still empty.

You will most likely need to use thread synchronization to do this.

ContentLicense: CC BY-SA 4.0

Body:
Please note there are lot of questions like these but none of them worked for me.
I have been trying to display data in a recycler view and it isnt displaying the data and not throwing any errors
Here is my code.

I have included the latest version of Firebase Dependencies and Latest version of Firebase UI Database

Dependencies Version

// Firebase
implementation 'com.google.firebase:firebase-auth:19.2.0'
implementation 'com.google.firebase:firebase-database:19.2.1'
implementation 'com.google.firebase:firebase-storage:19.1.1'

// Firebase UI
implementation 'com.firebaseui:firebase-ui-database:6.0.2'

This is the Films class
Films.java

package com.dipeshpatil.in;

public class Films {

    public String name, year;

    public Films(String name, String year) {
        this.name = name;
        this.year = year;
    }

    public Films() {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }
}

This is the ViewHolder Class FilmsViewHolder.java

package com.dipeshpatil.in;

import android.view.View;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

public class FilmsViewHolder extends RecyclerView.ViewHolder {
    public TextView mFilmName;
    public TextView mFilmYear;

    public FilmsViewHolder(View itemView){
        super(itemView);

        mFilmName = itemView.findViewById(R.id.user_single_name);
        mFilmYear = itemView.findViewById(R.id.user_single_status);
    }
}

This is the activity where i am supposed to display the data in recycler view FilmsActivity.java

public class FilmsActivity extends AppCompatActivity {

    private RecyclerView mFilmsList;
    private DatabaseReference mFilmsDatabase;
    private FirebaseRecyclerOptions<Films> options;
    private FirebaseRecyclerAdapter<Films, FilmsViewHolder> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_films);

        mFilmsList = findViewById(R.id.films_list);
        mFilmsList.setHasFixedSize(true);

        mFilmsDatabase = FirebaseDatabase.getInstance().getReference().child("Films");

        options = new FirebaseRecyclerOptions.Builder<Films>()
                .setQuery(mFilmsDatabase, Films.class)
                .build();

        adapter = new FirebaseRecyclerAdapter<Films, FilmsViewHolder>(options) {
            @Override
            protected void onBindViewHolder(FilmsViewHolder filmsViewHolder, int i, Films films) {

                filmsViewHolder.mFilmName.setText(films.getName());
                filmsViewHolder.mFilmYear.setText(films.getYear());
            }

            @NonNull
            @Override
            public FilmsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

                View mView = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.users_single_layout, parent, false);

                return new FilmsViewHolder(mView);
            }
        };
        mFilmsList.setAdapter(adapter);
    }

    @Override
    protected void onStart() {
        super.onStart();
        adapter.startListening();
    }

    @Override
    protected void onStop() {
        super.onStop();
        adapter.stopListening();
    }
}

Now honestly i am not getting any kind of error which would help me debug the code and check for problems and at the same time it is also not displaying my desired output

Firebase Database for Films

"Films" : {
    "01" : {
      "name" : "The Prestige",
      "year" : 2002
    },
    "02" : {
      "name" : "Fight Club",
      "year" : 1999
    }
}

Layout File activity_films.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    tools:context=".FilmsActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="16dp"
        android:id="@+id/films_list" />
</LinearLayout>


问:
Deprecated "getBitmap" with API 29. Any alternative codes?
My onActivityResult is not working because getBitmap is deprecated. Is there any alternative code to achieve this?

Here is the code that needs to be changed (any suggestions?):

```<code>val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, selectedPhotoUri)
</code>```

The getBitmap is crossed out in my tooling with a message that says it's deprecated.

答:
It was evident that the getBitmap API doesn't work with the latest Android SDK - 29. So, this worked for me

```<code>Uri contentURI = data.getData();
try {
    imageView.setImageURI(contentURI);
} catch (Exception e) {
    e.printStackTrace();
}
</code>```

Please let me know if this doesn't work for any of you, shall other options!

Body:
My onActivityResult is not working because getBitmap is deprecated. Is there any alternative code to achieve this?

Here is the code that needs to be changed (any suggestions?):

val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, selectedPhotoUri)

The getBitmap is crossed out in my tooling with a message that says it's deprecated.

Body:
It was evident that the getBitmap API doesn't work with the latest Android SDK - 29. So, this worked for me

Uri contentURI = data.getData();
try {
    imageView.setImageURI(contentURI);
} catch (Exception e) {
    e.printStackTrace();
}

Please let me know if this doesn't work for any of you, shall other options!


问:
Reshape by only two columns in pandas
This should be a simple question, but I think I'm just missing the keyword for what I should be searching for.

Suppose I have a two-column long dataset, like follows:

```<code>test = pd.DataFrame(
       {
          'color': ['white', 'white', 'white',
                    'red', 'red', 'red',
                    'black', 'black', 'black'],
           'value': [1,2,3,4,5,6,7,8,9]
       })
</code>```

How can I get it into the following format:

```<code>    white   red    black
    1        4       7
    2        5       8
    3        6       9
</code>```

I realize this should be a simple pivot function like:

test.pivot('color', 'value'), but this produces the values in the diagonal with surrounding NaN. Is there any way around this?

答:
I have done some quick solution using the group by function using the pandas library

```<code> for i in test.groupby('color'):
     print(i[0])
     for j in range(len(i[1])):
         for k in i[1].values:
             print(k[1])
         break
</code>```

Output:

```<code>black
7
8
9
red
4
5
6
white
1
2
3
</code>```

Title: Reshape by only two columns in pandas

Body:
This should be a simple question, but I think I'm just missing the keyword for what I should be searching for.

Suppose I have a two-column long dataset, like follows:

test = pd.DataFrame(
       {
          'color': ['white', 'white', 'white',
                    'red', 'red', 'red',
                    'black', 'black', 'black'],
           'value': [1,2,3,4,5,6,7,8,9]
       })

How can I get it into the following format:

    white   red    black
    1        4       7
    2        5       8
    3        6       9

I realize this should be a simple pivot function like:

test.pivot('color', 'value'), but this produces the values in the diagonal with surrounding NaN. Is there any way around this?

Body:
I have done some quick solution using the group by function using the pandas library

 for i in test.groupby('color'):
     print(i[0])
     for j in range(len(i[1])):
         for k in i[1].values:
             print(k[1])
         break

Output:

black
7
8
9
red
4
5
6
white
1
2
3


问:
Call an object in another method
I want to use an object of a method in an another method.
How can i do this ?

I got an object named "cell". I custom it in cellForRowAtIndexPath.
I want to custom it in didSelectRowAtIndexPath.

Thanks for help!

Flo

答:
You can get the selected cell in didSelectRowAtIndexPath as

```<code>YourCustomCell *selectedCell = (YourCustomCell *)[tableView cellForRowAtIndexPath:indexPath];
</code>```

EDIT:

```<code>-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    YourCustomCell *selectedCell = (YourCustomCell *) [tableView cellForRowAtIndexPath:indexPath];
    selectedCell.selected = YES; // Calls setSelected:(BOOL)selected animated:(BOOL)animated function of table view cell.
}
</code>```

Following should be in your table view cell class.

```<code>- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    // Configure the view for the selected state
    if (selected) {
        // set background for selected state...
    }else {
        // set background for unselected state...
    }

    [super setSelected:selected animated:animated];
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Call an object in another method

Body:
You can get the selected cell in didSelectRowAtIndexPath as

YourCustomCell *selectedCell = (YourCustomCell *)[tableView cellForRowAtIndexPath:indexPath];

EDIT:

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    YourCustomCell *selectedCell = (YourCustomCell *) [tableView cellForRowAtIndexPath:indexPath];
    selectedCell.selected = YES; // Calls setSelected:(BOOL)selected animated:(BOOL)animated function of table view cell.
}

Following should be in your table view cell class.

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    // Configure the view for the selected state
    if (selected) {
        // set background for selected state...
    }else {
        // set background for unselected state...
    }

    [super setSelected:selected animated:animated];
}


问:
call method with parameter of type class and check class type
I have the following classes:

```<code>class Permission {
  name: string;
}

class EditBasketPermission extends Permission {
  basketId: number;
}

class EditProductPermission extends Permission {
  basketId: number;
  projectId: number;
}
</code>```

Then I have a method that authorizes, or not, the permission:

```<code>authorize(permission: Permission) : boolean {

  // 1 - Check the permission type
  // 2 - Authorize the request based on the permission data

}
</code>```

How to check the permission type so I can decide how to evaluate it?

And in my HTML I have the following:

```<code><button *ngIf="authorize(???)">Edit</button>
</code>```

How to pass an EditProductPermission when calling the method authorised?

The problem is that permission type has different types of inputs.

答:
Maybe this approach?</p>

```<code>authorize(permission: Permission) : boolean {

  // 1 - Check the permission type
  // 2 - Authorize the request based on the permission data

  const props = []
  for (const key in permission) {
    if (permission.hasOwnProperty(key)) {
      props.push[key]
  }
  // props is now an array of the specialised permission object keys

}

</code>```

Body:
I have the following classes:

class Permission {
  name: string;
}

class EditBasketPermission extends Permission {
  basketId: number;
}

class EditProductPermission extends Permission {
  basketId: number;
  projectId: number;
}

Then I have a method that authorizes, or not, the permission:

authorize(permission: Permission) : boolean {

  // 1 - Check the permission type
  // 2 - Authorize the request based on the permission data

}

How to check the permission type so I can decide how to evaluate it?

And in my HTML I have the following:

<button *ngIf="authorize(???)">Edit</button>

How to pass an EditProductPermission when calling the method authorised?

The problem is that permission type has different types of inputs.

Body:
Maybe this approach?

authorize(permission: Permission) : boolean {

  // 1 - Check the permission type
  // 2 - Authorize the request based on the permission data

  const props = []
  for (const key in permission) {
    if (permission.hasOwnProperty(key)) {
      props.push[key]
  }
  // props is now an array of the specialised permission object keys

}


问:
A program to send an image file from client to server in python using TCP
This is my code. Currently it transfers about 75% of the image file (cropped at the bottom). I want it transferred as a whole. This is how I've been working on it:

Create a folder in server pc called "server"

Create a folder in client pc called "client"

Also include the image file you want to transfer in the same "client" folder

Client side ask "name of the file you want to send", I type in the name of the image file in the folder

Aerver side ask me "name of the file you want to receive", I type any random name.

The file transfers and gets saved to "server" folder in the server PC.

client.py

```<code>from socket import *

def establish_connection(server_IP, server_port):
    client_socket = socket(AF_INET, SOCK_STREAM)
    client_socket.connect((server_IP, server_port))
    return client_socket

def send_recv_message(client_socket, message, buffer_size):
    file = open(filename,'rb')
    file_data = file.read(buffer_size)
    client_socket.send(file_data)
    text=print("File transfered")
    return text

server_IP = input("Please, enter server IP address: ")
server_port = input("Please, enter server TCP connection port number: ")
client_socket = establish_connection(server_IP, int(server_port))
print("Connection established\n")

filename= input(str("enter filename"))

received_message = send_recv_message(client_socket,filename,1048576)
</code>```

server.py

```<code>from socket import *

def create_socket(server_port):
    server_socket = socket(AF_INET, SOCK_STREAM)
    server_socket.bind(('', server_port))
    server_socket.listen(1)
    return server_socket

def recv_message(server_socket, buffer_size):
    file = open(filename, 'wb')
    connection_socket, address = server_socket.accept()
    file_data= connection_socket.recv(buffer_size)
    file.write(file_data)
    file.close()
    text=("file recieved")
    return text

server_port = input("Please, enter TCP connection port number: ")
server_socket = create_socket(int(server_port))

while (True):
    filename=input(str("enter filename for the incoming file:"))
    incoming_message = recv_message(server_socket,  1048576)
    print ("{}" .format(incoming_message))
</code>```

答:
this is because the picture is more than the buffer size.
you have to send the size of the pic form client to server..example for text sending this can be used for image to...

eg

```<code> send_message = input()
</code>```

mess = f'{len(send_message)}'.ljust(buffer_size) + send_message
soc.send(mess.encode())

at the server side find the size of picture and while size is not equal to your message recieved keep appending the msg.

```<code>  message = ''
    mes_len = 0
    new_msg = True
    print('got the connection: {}'.format(self.request))
    while True:
        data = self.request.recv(buffer_size)
        if new_msg:
            mes_len = int(data.decode())
            new_msg = False
        message += data.decode()
</code>```

Body:
This is my code. Currently it transfers about 75% of the image file (cropped at the bottom). I want it transferred as a whole. This is how I've been working on it:

Create a folder in server pc called "server"

Create a folder in client pc called "client"

Also include the image file you want to transfer in the same "client" folder

Client side ask "name of the file you want to send", I type in the name of the image file in the folder

Aerver side ask me "name of the file you want to receive", I type any random name.

The file transfers and gets saved to "server" folder in the server PC.

client.py

from socket import *

def establish_connection(server_IP, server_port):
    client_socket = socket(AF_INET, SOCK_STREAM)
    client_socket.connect((server_IP, server_port))
    return client_socket

def send_recv_message(client_socket, message, buffer_size):
    file = open(filename,'rb')
    file_data = file.read(buffer_size)
    client_socket.send(file_data)
    text=print("File transfered")
    return text

server_IP = input("Please, enter server IP address: ")
server_port = input("Please, enter server TCP connection port number: ")
client_socket = establish_connection(server_IP, int(server_port))
print("Connection established\n")

filename= input(str("enter filename"))

received_message = send_recv_message(client_socket,filename,1048576)

server.py

from socket import *

def create_socket(server_port):
    server_socket = socket(AF_INET, SOCK_STREAM)
    server_socket.bind(('', server_port))
    server_socket.listen(1)
    return server_socket

def recv_message(server_socket, buffer_size):
    file = open(filename, 'wb')
    connection_socket, address = server_socket.accept()
    file_data= connection_socket.recv(buffer_size)
    file.write(file_data)
    file.close()
    text=("file recieved")
    return text

server_port = input("Please, enter TCP connection port number: ")
server_socket = create_socket(int(server_port))

while (True):
    filename=input(str("enter filename for the incoming file:"))
    incoming_message = recv_message(server_socket,  1048576)
    print ("{}" .format(incoming_message))

Body:
this is because the picture is more than the buffer size.
you have to send the size of the pic form client to server..example for text sending this can be used for image to...

eg

 send_message = input()

mess = f'{len(send_message)}'.ljust(buffer_size) + send_message
soc.send(mess.encode())

at the server side find the size of picture and while size is not equal to your message recieved keep appending the msg.

  message = ''
    mes_len = 0
    new_msg = True
    print('got the connection: {}'.format(self.request))
    while True:
        data = self.request.recv(buffer_size)
        if new_msg:
            mes_len = int(data.decode())
            new_msg = False
        message += data.decode()


问:
Using javascript variables from another function

Possible Duplicate:

  How to know variables from different…“namespaces” ?

I have a webphone integrated into our webpage, and when a call comes in, a javascript function records the caller's number (e.g. 01234 123456) and saves it as the variable inCallingNum.

I need to use this variable in a different function which sends information to a php page and stores it on our database.

Is it possible to access the javascript variable from another function at all, and if not what is the easiest way to get around it?

Edit: This is the code I have, which currently captures the inCallingNum variable

```<code>    function webphonetojs(varr)
        {
            var eventNotify = '' + varr;
            //alert("eventNotify = "+eventNotify);
            displaystatus('WEBPHONE SAY: '+eventNotify);

            initcheck();
            var chanelStat = applethandle.API_GetStatus(1); //  get line status
            var chanelStatus = chanelStat.replace(/\s+/g,'');
            if (chanelStatus == 'Ringing')
            {
                var incomming = eventNotify.slice(eventNotify.lastIndexOf(",")+1, eventNotify.length);
                if (incomming == '2')
                {
                    var inCallingNum = eventNotify.split(",", 4); inCallingNum = inCallingNum.toString();
                    inCallingNum = inCallingNum.slice(inCallingNum.lastIndexOf(",")+1, inCallingNum.length);
                    displaystatus('CALLER IS: '+inCallingNum);

}
}
}
</code>```

答: Of course you can. You just have to store the value in a variable that is outside of the scope of a function. So you declare a global javascript variable by putting the "var varName = '';" outside the braces of a function and use that variable.</p>

Body:
Possible Duplicate:

  How to know variables from different…“namespaces” ?

I have a webphone integrated into our webpage, and when a call comes in, a javascript function records the caller's number (e.g. 01234 123456) and saves it as the variable inCallingNum.

I need to use this variable in a different function which sends information to a php page and stores it on our database.

Is it possible to access the javascript variable from another function at all, and if not what is the easiest way to get around it?

Edit: This is the code I have, which currently captures the inCallingNum variable

    function webphonetojs(varr)
        {
            var eventNotify = '' + varr;
            //alert("eventNotify = "+eventNotify);
            displaystatus('WEBPHONE SAY: '+eventNotify);

            initcheck();
            var chanelStat = applethandle.API_GetStatus(1); //  get line status
            var chanelStatus = chanelStat.replace(/\s+/g,'');
            if (chanelStatus == 'Ringing')
            {
                var incomming = eventNotify.slice(eventNotify.lastIndexOf(",")+1, eventNotify.length);
                if (incomming == '2')
                {
                    var inCallingNum = eventNotify.split(",", 4); inCallingNum = inCallingNum.toString();
                    inCallingNum = inCallingNum.slice(inCallingNum.lastIndexOf(",")+1, inCallingNum.length);
                    displaystatus('CALLER IS: '+inCallingNum);

}
}
}


问:
ASP.net if else FluentValidation condition
I tried to do if else condition in Fluent Validation, I found that Fluent Validation have When Otherwise , now my Type is equal to 2, so it should go for do something B, but it keep go in to do something A

```<code>When(x => x.Type == 1, () => {
    //do something A
}).Otherwise(() => {
    //do something B
});
</code>```

答:
You will notice that the debug point is indeed going into both the blocks but errors are not shown for the same.

For example following code,

```<code>        When(x => x.Type == 1, () =>
        {
            RuleFor(y => y.Type).LessThanOrEqualTo(1);
        })
        .Otherwise(() => {
            RuleFor(y => y.Type).GreaterThan(10);
        });
</code>```

will work for Type = 1 (i.e. no error will be shown) but for Type = 0 and Type = 2 (to 10), the following error will be shown:

```<code>{
    "Type": [
        "'Type' must be greater than '10'."
    ]
}
</code>```

Body:
I tried to do if else condition in Fluent Validation, I found that Fluent Validation have When Otherwise , now my Type is equal to 2, so it should go for do something B, but it keep go in to do something A

When(x => x.Type == 1, () => {
    //do something A
}).Otherwise(() => {
    //do something B
});

Body:
You will notice that the debug point is indeed going into both the blocks but errors are not shown for the same.

For example following code,

        When(x => x.Type == 1, () =>
        {
            RuleFor(y => y.Type).LessThanOrEqualTo(1);
        })
        .Otherwise(() => {
            RuleFor(y => y.Type).GreaterThan(10);
        });

will work for Type = 1 (i.e. no error will be shown) but for Type = 0 and Type = 2 (to 10), the following error will be shown:

{
    "Type": [
        "'Type' must be greater than '10'."
    ]
}


问:
Does the number of brokers and no of partitions would affect the partition leader election?
I'm trying to understand how does the no of partitions would affect the partition leader (broker)?

Let's say, I've a kafka cluster with 1 zookeeper, 3 brokers and 1 schema registry. My topic replication factor is 1. Now, If I've two topics A and B with 5 partitions.

Now, let's say if i send a message to topic A with key key1 and assume that based on the partitioning strategy, it is ended up being redirected to partition 5 of topic A and the leader for the partition 5 of topic A is broker 2.

In this scenario, If i send a message to topic B with key key1 (same as key as the message that was sent onto Topic A), then can we assume that it would go to partition 5 on the broker 2?

答:
There is no correlation between leadership and partitioning

You can guarantee that the same key will be hashed the same, and go to the same partition (assuming matching counts), but you cannot guarantee which broker will be the leader


问:
Advice sought on deriving optimal configuration parameters for C# app - possibly a learning problem
Here is my situation:

My company has a little C# console app, with a config file. In that config file is approximately 20 calibration parameters for our equipment (a vibration measurement device). We go through a manual process where we use in-house knowledge to manually tweak the calibration parameters, do a test run, tweak again, and iterate until we get correct calibration parameters. It's effectively a human loop.

Now this is a bit inefficient and time consuming, and I can't help thinking that this process is something we can automate. However, I'm not sure if I'm thinking about this properly and what techniques are available to me to try and solve this issue.

I can for example, just write some code that loops through every parameter combination, and brute force finds the most accurate parameter set, however this is ugly and we quickly get to billions of iterations.

It seems to me this is some kind of learning or neural network problem, and I could possibly refactor the code to somehow use this. However I'm not sure if this is actually the case.

Based on the above, what is an appropriate technique to use here? What is available in C# to facilitate this?

Thanks in Advance!

答: Sounds like a version of 'hyper-parameter tuning'. You could use for instance the hyperopt library to help you come to the optimal solution faster. You can see an example here.</p>


问:
SHC Compiled script fails to run using systemctl
I've got a very simple bash script called test.

```<code>#!/bin/bash

while true
do
    currdate=$(date +%d/%m/%Y-%H:%M:%S)
    echo -e "\n$currdate ..."
    sleep 1
done
</code>```

Running this from the command line works exactly as expected.

I've compiled this with SHC has follows:
shc -r -U -f test.sh -o test

Running this from the command line works as expected.

I've setup to run this using systemctl, added my config file to /etc/init.d and this references test

If test is my un complied bash script, then systemclt start test works fine.
If I swap test and replace it with the complied version, then it fails.

systemctl status shows:

```<code>test.service - LSB: Test
   Loaded: loaded (/etc/init.d/test; generated; vendor preset: disabled)
   Active: failed (Result: exit-code) since Tue 2020-02-18 15:38:05 GMT; 6s ago
     Docs: man:systemd-sysv-generator(8)
  Process: 18089 ExecStart=/etc/init.d/test start (code=exited, status=7)
    Tasks: 2
   CGroup: /system.slice/test.service
           ├─18096 /home/rocket/test -c                                                                                >
           └─18142 sleep 1

Feb 18 15:38:05 linux-c0a9 systemd[1]: test.service: Control process exited, code=exited status=7
Feb 18 15:38:05 linux-c0a9 systemd[1]: Failed to start LSB: Test.
Feb 18 15:38:05 linux-c0a9 systemd[1]: test.service: Unit entered failed state.
Feb 18 15:38:05 linux-c0a9 systemd[1]: test.service: Failed with result 'exit-code'.
</code>```

journalctl shows:

```<code>Feb 18 15:38:05 linux-c0a9 systemd[1]: Starting LSB: Test...
Feb 18 15:38:05 linux-c0a9 test[18089]: Starting test
Feb 18 15:38:05 linux-c0a9 test[18089]: 18/02/2020-15:38:05 ...
Feb 18 15:38:05 linux-c0a9 test[18089]: ..failed
Feb 18 15:38:05 linux-c0a9 systemd[1]: test.service: Control process exited, code=exited status=7
Feb 18 15:38:05 linux-c0a9 systemd[1]: Failed to start LSB: Test.
Feb 18 15:38:05 linux-c0a9 systemd[1]: test.service: Unit entered failed state.
Feb 18 15:38:05 linux-c0a9 systemd[1]: test.service: Failed with result 'exit-code'.
</code>```

Does anyone know why this fails and how to stop it failing ?

I'm only using SHC to stop users editing the script, not for any security etc.

Thanks

答:
I think I may have solved this.

My script in /etc/init.d was calling /home/rocket/test

When that is a bash file it's fine, when it's compiled it stops working.

To get it to work I changed test to always be a bash file that calls the compiled test which is in in /home/rocket/bin/test

Body:
I've got a very simple bash script called test.

#!/bin/bash

while true
do
    currdate=$(date +%d/%m/%Y-%H:%M:%S)
    echo -e "\n$currdate ..."
    sleep 1
done

Running this from the command line works exactly as expected.

I've compiled this with SHC has follows:
shc -r -U -f test.sh -o test

Running this from the command line works as expected.

I've setup to run this using systemctl, added my config file to /etc/init.d and this references test

If test is my un complied bash script, then systemclt start test works fine.
If I swap test and replace it with the complied version, then it fails.

systemctl status shows:

test.service - LSB: Test
   Loaded: loaded (/etc/init.d/test; generated; vendor preset: disabled)
   Active: failed (Result: exit-code) since Tue 2020-02-18 15:38:05 GMT; 6s ago
     Docs: man:systemd-sysv-generator(8)
  Process: 18089 ExecStart=/etc/init.d/test start (code=exited, status=7)
    Tasks: 2
   CGroup: /system.slice/test.service
           ├─18096 /home/rocket/test -c                                                                                >
           └─18142 sleep 1

Feb 18 15:38:05 linux-c0a9 systemd[1]: test.service: Control process exited, code=exited status=7
Feb 18 15:38:05 linux-c0a9 systemd[1]: Failed to start LSB: Test.
Feb 18 15:38:05 linux-c0a9 systemd[1]: test.service: Unit entered failed state.
Feb 18 15:38:05 linux-c0a9 systemd[1]: test.service: Failed with result 'exit-code'.

journalctl shows:

Feb 18 15:38:05 linux-c0a9 systemd[1]: Starting LSB: Test...
Feb 18 15:38:05 linux-c0a9 test[18089]: Starting test
Feb 18 15:38:05 linux-c0a9 test[18089]: 18/02/2020-15:38:05 ...
Feb 18 15:38:05 linux-c0a9 test[18089]: ..failed
Feb 18 15:38:05 linux-c0a9 systemd[1]: test.service: Control process exited, code=exited status=7
Feb 18 15:38:05 linux-c0a9 systemd[1]: Failed to start LSB: Test.
Feb 18 15:38:05 linux-c0a9 systemd[1]: test.service: Unit entered failed state.
Feb 18 15:38:05 linux-c0a9 systemd[1]: test.service: Failed with result 'exit-code'.

Does anyone know why this fails and how to stop it failing ?

I'm only using SHC to stop users editing the script, not for any security etc.

Thanks


问:
Read/write to Windows registry using Java
How is it possible to read/write to the Windows registry using Java?</p>

答:
I prefer using java.util.prefs.Preferences class.

A simple example would be

```<code>// Write Operation
Preferences p = Preferences.userRoot();
p.put("key","value");
// also there are various other methods such as putByteArray(), putDouble() etc.
p.flush();
//Read Operation
Preferences p = Preferences.userRoot();
String value = p.get("key");
</code>```

OwnerDisplayName: Dichkaun

LastEditorDisplayName: mmyers

Body:
I prefer using java.util.prefs.Preferences class.

A simple example would be

// Write Operation
Preferences p = Preferences.userRoot();
p.put("key","value");
// also there are various other methods such as putByteArray(), putDouble() etc.
p.flush();
//Read Operation
Preferences p = Preferences.userRoot();
String value = p.get("key");


问:
Merge Pandas Dataframe based on boolean function
I am looking for an efficient way to merge two pandas data frames based on a function that takes as input columns from both data frames and returns True or False. E.g. Assume I have the following "tables":

```<code>import pandas as pd

df_1 = pd.DataFrame(data=[1, 2, 3])
df_2 = pd.DataFrame(data=[4, 5, 6])

def validation(a, b):
    return ((a + b) % 2) == 0
</code>```

I would like to join df1 and df2 on each row where the sum of the first column is an even number. The resulting table would be

```<code>       1 5
df_3 = 2 4
       2 6
       3 5
</code>```

Please think of it as a general problem not as a task to return just df_3. The solution should accept any function that validates a combination of columns and return True or False.

THX Lazloo

答:
You can do with merge on parity:

```<code>(df_1.assign(parity=df_1[0]%2)
     .merge(df_2.assign(parity=df_2[0]%2), on='dummy')
     .drop('parity', axis=1)
)
</code>```

output:

```<code>   0_x  0_y
0    1    5
1    3    5
2    2    4
3    2    6
</code>```

Body:
I am looking for an efficient way to merge two pandas data frames based on a function that takes as input columns from both data frames and returns True or False. E.g. Assume I have the following "tables":

import pandas as pd

df_1 = pd.DataFrame(data=[1, 2, 3])
df_2 = pd.DataFrame(data=[4, 5, 6])

def validation(a, b):
    return ((a + b) % 2) == 0

I would like to join df1 and df2 on each row where the sum of the first column is an even number. The resulting table would be

       1 5
df_3 = 2 4
       2 6
       3 5

Please think of it as a general problem not as a task to return just df_3. The solution should accept any function that validates a combination of columns and return True or False.

THX Lazloo

Body:
You can do with merge on parity:

(df_1.assign(parity=df_1[0]%2)
     .merge(df_2.assign(parity=df_2[0]%2), on='dummy')
     .drop('parity', axis=1)
)

output:

   0_x  0_y
0    1    5
1    3    5
2    2    4
3    2    6


问:
Get Text Input WITHOUT UITextField Swift
I'm making an app and I want the user to be able to input text without having them actually click on a UITextField (have it open after the game ends for a scoreboard), is there some way to do that?</p>

答:
Yes, just:

```<code><#your_text_field#>.becomeFirstResponder()
</code>```

after the game ends.

This will produce the "same" effect as a tap on the UITextField. If this is on a new UIViewController you can place it on viewDidAppear, otherwise you can assume everything is already loaded and simply call it anywhere.

Body:
Yes, just:

<#your_text_field#>.becomeFirstResponder()

after the game ends.

This will produce the "same" effect as a tap on the UITextField. If this is on a new UIViewController you can place it on viewDidAppear, otherwise you can assume everything is already loaded and simply call it anywhere.


问:
Cypress issue running a feature file on my machine
I am trying to get cypress to work on my machine with very basic feature file, however I keep getting the following error in my console output,

Oops...we found an error preparing this test file:

cypress\integration\login.feature

The error was:

Error: Cannot find module 'C:cypress-bdd-example
ode_modulescypress-cucumber-preprocessorlib/resolveStepDefinition' from 'C:\cypress-bdd-example\cypress\integration'

This occurred while Cypress was compiling and bundling your test code. This is usually caused by:

A missing file or dependency

A syntax error in the file or one of its dependencies

Fix the error in your code and re-run your tests

Everything seems to be installed correctly, here are my files,

cypress.json

{
  "ignoreTestFiles": "*.js",
  "testFiles": "**/*.{feature,features}"
}

package.json

```<code>{
  "name": "cypress-bdd-example",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "cypress run --spec \"**/*.feature\"",
    "test:all": "cypress run --spec \"**/*.features\"",
    "cypress: open": "cypress open",
    "cypress: run": "cypress run"
  },
  "dependencies": {
    "cypress": "^3.8.1",
    "cypress-cucumber-preprocessor": "^1.19.0",
    "react-scripts": "^3.3.0"
  },
  "cypress-cucumber-preprocessor": {
    "nonGlobalStepDefinitions": true
  }
}
</code>```

login.feature

```<code>Feature: Login Feature

As a valid customer
In order to purchase items
I want to login successfully to Swag Labs

Scenario: Login Validation

Given I am in the Swag Labs login page
When I enter valid credentials
Then I should be able to login successfully
</code>```

login.js

```<code>import { Given, When, Then } from "cypress-cucumber-preprocessor/steps";

Given("I am in the demo site", () => {
  cy.visit("https://www.saucedemo.com/index.html");
});

When("I enter valid credentials", () => {
  cy.get("[data-test=username]").type("standard_user");
  cy.get("[data-test=password]").type("secret_sauce");
  cy.get(".btn_action").click();
});

Then("I should be able to login successfully", () => {
  cy.get(".bm-burger-button > button").click();
  cy.get("#logout_sidebar_link").click();
});
</code>```

the file structure is as follows,

```<code>C:\cypress-bdd-example\cypress\integration
login.feature

C:\cypress-bdd-example\cypress\integration\login
login.js
</code>```

答: I was getting this issue on Windows while my co-workers on macOS were not. I was able to fix this issue by upgrading cypress-cucumber-preprocessor to 2.0.1.</p>

Body:
I am trying to get cypress to work on my machine with very basic feature file, however I keep getting the following error in my console output,

Oops...we found an error preparing this test file:

cypress\integration\login.feature

The error was:

Error: Cannot find module 'C:cypress-bdd-example
ode_modulescypress-cucumber-preprocessorlib/resolveStepDefinition' from 'C:\cypress-bdd-example\cypress\integration'

This occurred while Cypress was compiling and bundling your test code. This is usually caused by:

A missing file or dependency

A syntax error in the file or one of its dependencies

Fix the error in your code and re-run your tests

Everything seems to be installed correctly, here are my files,

cypress.json

{
  "ignoreTestFiles": "*.js",
  "testFiles": "**/*.{feature,features}"
}

package.json

{
  "name": "cypress-bdd-example",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "cypress run --spec \"**/*.feature\"",
    "test:all": "cypress run --spec \"**/*.features\"",
    "cypress: open": "cypress open",
    "cypress: run": "cypress run"
  },
  "dependencies": {
    "cypress": "^3.8.1",
    "cypress-cucumber-preprocessor": "^1.19.0",
    "react-scripts": "^3.3.0"
  },
  "cypress-cucumber-preprocessor": {
    "nonGlobalStepDefinitions": true
  }
}

login.feature

Feature: Login Feature

As a valid customer
In order to purchase items
I want to login successfully to Swag Labs

Scenario: Login Validation

Given I am in the Swag Labs login page
When I enter valid credentials
Then I should be able to login successfully

login.js

import { Given, When, Then } from "cypress-cucumber-preprocessor/steps";

Given("I am in the demo site", () => {
  cy.visit("https://www.saucedemo.com/index.html");
});

When("I enter valid credentials", () => {
  cy.get("[data-test=username]").type("standard_user");
  cy.get("[data-test=password]").type("secret_sauce");
  cy.get(".btn_action").click();
});

Then("I should be able to login successfully", () => {
  cy.get(".bm-burger-button > button").click();
  cy.get("#logout_sidebar_link").click();
});

the file structure is as follows,

C:\cypress-bdd-example\cypress\integration
login.feature

C:\cypress-bdd-example\cypress\integration\login
login.js


问:
Shopify Collection Page Layout - Image, Video, then Text + Add to Cart Button
I essentially brand new to the Liquid engine. However, I program in several languages so I figure I can conquer Liquid with a few pointers.

I want my collection page to layout products like they are laid out here:
http://www.boombycindyjoseph.com/pages/store

It's a 3 column layout with an Product Image on the left, Product Video in the Middle, and Text + Add to Cart on the right. I won't have a video for every product so I'll need to have some form of default placeholder in the middle.

Note that the Product Image is not the same as the Product Image in the Product Page. While optional, this would also be nice.

My Googling just led to simple answers like how to add a video to your product page.

So I could use a little help on where to start editing this. My guess is that it would be in either the collections-template.liquid, collections-grid-item.liquid, or collections-grid-collage.liquid files.

From there, do I need to add my Product Image and Product Video for the Collection Page to the Asset list or (better) somehow add a couple of fields to the product.liquid file that allows me to enter them when I have them.

答:
On my site, the file called product-grid-item.liquid, in the Snippets folder, is what controls the layout on the Collections pages or a section containing a collection. The below is the code that controls which images are shown on the preview, normally it's the first and last image (product.images.last) by default. I changed mine to show the master (first) image and second image. To make things simple, put the main product image first when uploading a new product. If you want a collections page to only show one preview image you can comment out the 'reveal' class and the first span below.</p>

```<code><div class="ImageOverlayCa"></div>
        {% if product.images.size > 1 %}
        <div class="reveal">
          <span class="product-additional">
            <img class="" src="{{ product.images[1] | product_img_url: 'master' }}" alt="{{ product.images[1].alt | escape }}" />
          </span>
         <img src="{{ product.featured_image.src | img_url: 'master' }}" class="featured-image" alt="{{ product.featured_image.alt | escape }}">
        </div>
        {% else %}
        <img src="{{ product.featured_image.src | img_url: 'master' }}" class="featured-image" alt="{{ product.featured_image.alt | escape }}">
        {% endif %}
</code>```

Body:
On my site, the file called product-grid-item.liquid, in the Snippets folder, is what controls the layout on the Collections pages or a section containing a collection. The below is the code that controls which images are shown on the preview, normally it's the first and last image (product.images.last) by default. I changed mine to show the master (first) image and second image. To make things simple, put the main product image first when uploading a new product. If you want a collections page to only show one preview image you can comment out the 'reveal' class and the first span below.

<div class="ImageOverlayCa"></div>
        {% if product.images.size > 1 %}
        <div class="reveal">
          <span class="product-additional">
            <img class="" src="{{ product.images[1] | product_img_url: 'master' }}" alt="{{ product.images[1].alt | escape }}" />
          </span>
         <img src="{{ product.featured_image.src | img_url: 'master' }}" class="featured-image" alt="{{ product.featured_image.alt | escape }}">
        </div>
        {% else %}
        <img src="{{ product.featured_image.src | img_url: 'master' }}" class="featured-image" alt="{{ product.featured_image.alt | escape }}">
        {% endif %}


问:
java force an extending class
In Java, can I somehow force a class that extends an abstract class to implement its constructor with a Object as a parameter?

Something like

```<code>public abstract class Points {

    //add some abstract method to force constructor to have object.
}

public class ExtendPoints extends Points {

    /**
     * I want the abstract class to force this implementation to have
     *  a constructor with an object in it?
     * @param o
     */
    public ExtendPoints(Object o){

    }
}
</code>```

答:
You can use a constructor with a parameter in your abstract class (make it protected if you want to dis-allow anonymous subclasses).

```<code>public abstract class Points{
    protected Points(Something parameter){
        // do something with parameter
    }
}
</code>```

Doing that, you force the implementing class to have an explicit constructor, as it must call the super constructor with one parameter.

However, you cannot force the overriding class to have a constructor with parameters. It can always fake the parameter like this:

```<code>public class ExtendPoints extends Points{
    public ExtendPoints(){
        super(something);
    }
}
</code>```

Title: java force an extending class

Body:
In Java, can I somehow force a class that extends an abstract class to implement its constructor with a Object as a parameter?

Something like

public abstract class Points {

    //add some abstract method to force constructor to have object.
}

public class ExtendPoints extends Points {

    /**
     * I want the abstract class to force this implementation to have
     *  a constructor with an object in it?
     * @param o
     */
    public ExtendPoints(Object o){

    }
}

Body:
You can use a constructor with a parameter in your abstract class (make it protected if you want to dis-allow anonymous subclasses).

public abstract class Points{
    protected Points(Something parameter){
        // do something with parameter
    }
}

Doing that, you force the implementing class to have an explicit constructor, as it must call the super constructor with one parameter.

However, you cannot force the overriding class to have a constructor with parameters. It can always fake the parameter like this:

public class ExtendPoints extends Points{
    public ExtendPoints(){
        super(something);
    }
}


问:
SSRS Service unavailable HTTP 503
This Wednesday our report server stopped working.
When I open the URL http://ourdomain/ReportServer as set in Report Server Configuration Manager,

it writes HTTP Error 503. The service is unavailable.

I already tried to restart the service SQL Server Reporting Services.

I also tried in Report Server Configuration Manager under Web Service URL tab to rename the Virtual Directory to ReportServer2 than apply. The new URL wasn't working as well.

I noticed in one log from 12. 2. 2020
library!WindowsService_31!a94!02/12/2020-02:12:42:: e ERROR: Throwing Microsoft.ReportingServices.Diagnostics.EvaluationCopyExpiredException: , Microsoft.ReportingServices.Diagnostics.EvaluationCopyExpiredException: The evaluation period for this instance of Microsoft SQL Server Reporting Services has expired.  A license is now required.;
servicecontroller!WindowsService_31!a94!02/12/2020-02:12:42:: e ERROR: StartService: Error Starting Service: Microsoft.ReportingServices.Diagnostics.EvaluationCopyExpiredException: The evaluation period for this instance of Microsoft SQL Server Reporting Services has expired.  A license is now required.
appdomainmanager!DefaultDomain!a94!02/12/2020-02:12:42:: e ERROR: Exiting process because windows service failed to start.

答:
Regardless of whether this is a root cause or not - I think you will be better off crossing this licesing error off your list to continue troubleshooting (I do however suspect this is it).

In short:

Before doing anything, make sure you back up ReportServer DB!

Try reinstalling SSRS edition to match your SQL Server and enter the same licence key (find your SQL key and check the key on SSRS installation media \..\x64\DefaultSetup.ini before running it)

There's a few forums around discussing the issue and highlighting different issues users had while trying to reinstall SSRS (I'll just link a few most relevant in my opinion - none of them are mine).

A thread on social.microsoft.com

One seemingly successful experience from community.spiceworks.com

And another one from the same site

Hopefully that resolves your issue

Title: SSRS Service unavailable HTTP 503


答:
Call the following in the viewDidLoad of scoreboard, or whatever the entry point of that view is.

```<code>yourTextField.becomeFirstResponder()
</code>```

Title: Get Text Input WITHOUT UITextField Swift

Body: I'm making an app and I want the user to be able to input text without having them actually click on a UITextField (have it open after the game ends for a scoreboard), is there some way to do that?

Body:
Call the following in the viewDidLoad of scoreboard, or whatever the entry point of that view is.

yourTextField.becomeFirstResponder()


答:
You can create series, reset indexes, and recreate a dataframe from the 3 series :

```<code>df = pd.DataFrame({'color': ['white', 'white', 'white', 'red', 'red', 'red', 'black', 'black', 'black'],
'value': [1,2,3,4,5,6,7,8,9]})

serie_white = df['value'][df['color'] == "white"].reset_index(drop=True)
serie_red = df['value'][df['color'] == "red"].reset_index(drop=True)
serie_black = df['value'][df['color'] == "black"].reset_index(drop=True)

result = pd.DataFrame({'white': serie_white, 'red': serie_red, 'black': serie_black})
print(result)
</code>```

Output :

```<code>   white  red  black
0      1    4      7
1      2    5      8
2      3    6      9
</code>```

Title: Reshape by only two columns in pandas

Body:
This should be a simple question, but I think I'm just missing the keyword for what I should be searching for.

Suppose I have a two-column long dataset, like follows:

test = pd.DataFrame(
       {
          'color': ['white', 'white', 'white',
                    'red', 'red', 'red',
                    'black', 'black', 'black'],
           'value': [1,2,3,4,5,6,7,8,9]
       })

How can I get it into the following format:

    white   red    black
    1        4       7
    2        5       8
    3        6       9

I realize this should be a simple pivot function like:

test.pivot('color', 'value'), but this produces the values in the diagonal with surrounding NaN. Is there any way around this?

Body:
You can create series, reset indexes, and recreate a dataframe from the 3 series :

df = pd.DataFrame({'color': ['white', 'white', 'white', 'red', 'red', 'red', 'black', 'black', 'black'],
'value': [1,2,3,4,5,6,7,8,9]})

serie_white = df['value'][df['color'] == "white"].reset_index(drop=True)
serie_red = df['value'][df['color'] == "red"].reset_index(drop=True)
serie_black = df['value'][df['color'] == "black"].reset_index(drop=True)

result = pd.DataFrame({'white': serie_white, 'red': serie_red, 'black': serie_black})
print(result)

Output :

   white  red  black
0      1    4      7
1      2    5      8
2      3    6      9


问:
port 7071 is unavailable. Close the process using that port, or specify another port using --port [-p]
I try to run the azure function app (Http Triggerd API) from my local (using VS code). But I'm getting an error "port 7071 is unavailable. Close the process using that port, or specify another port using --port [-p]." I checked the list of ports used using cmd prompt.But 7071 is not in used list. Also tried to run with different port using "func host start --port [p1]", but it throws the same error as above. For all ports it throws the same error. How to resolve this problem?</p>

答:
Goto Project Properties -> Debug -> Application Argument -> paste this -> host start --pause-on-error --port 5800

you will have new port for your Azure Function:
http://localhost:5800/api/Function1


答:
Disclaimer : Populating the global scope is a bad idea. Better to return the variable from the method you are using and working with it. Having said that, this is how you put it in the global scope

```<code>var bVar = '';

function a() {
  alert(bVar);
}

function b() {
  bVar = 'B just used it';
}

b();
a();
</code>```

Since bVar is in global scope, any method can now access it.

Title: Using javascript variables from another function

Body:
Disclaimer : Populating the global scope is a bad idea. Better to return the variable from the method you are using and working with it. Having said that, this is how you put it in the global scope

var bVar = '';

function a() {
  alert(bVar);
}

function b() {
  bVar = 'B just used it';
}

b();
a();

Since bVar is in global scope, any method can now access it.


问:
Why is my tabulator custom header filter changing on keyup?
To reproduce:

Run the Code Snippet (recommend Full Page mode)

Hold Ctrl or Shift while clicking to select multiple 'species' in the table column header

Note that while the key is held down, the table data is filtered according to selected 'species'

Release the key, observe changes in filtered table data

I think this is probably related to https://github.com/olifolkerd/tabulator/issues/975 and that I need to do something to override default tabulator keypress events.

JSFiddle: https://jsfiddle.net/jjech/3th28pv0/229/

const speciesTypes = [ 'Human', 'Android', 'Betazoid', 'Klingon', 'Ferengi', 'Tamarian' ];

function multiSelectHeaderFilter(cell) {

 var values = speciesTypes;

 const filterFunc = (rowData) => {
   return values.includes(rowData['species']);
 }

  const getSelectedValues = (multiSelect) => {
    var result = [];
    var options = multiSelect && multiSelect.options;
    var opt;

    for (var i=0, iLen=options.length; i<iLen; i++) {
      opt = options[i];

      if (opt.selected) {
        result.push(opt.value || opt.text);
      }
    }
    return result;
  }

 const onChange = () => {
   var editor = document.getElementById('speciesSelector');
    values = getSelectedValues(editor);
    console.log("values: "+values);
    cell.getColumn().getTable().removeFilter(filterFunc);
    cell.getColumn().getTable().addFilter(filterFunc);
  }

 var select = document.createElement("select");
  select.multiple = "multiple";
 select.id = 'speciesSelector';
  select.style = 'width: 100%';
  speciesTypes.forEach(species => {
   select.innerHTML += "<option id='"+species+"' value='"+species+"' selected='selected'>"+species+"</option>";
  });
  cell.getColumn().getTable().addFilter(filterFunc);
  select.addEventListener('change',onChange);
  return select;
}

var table = new Tabulator("#tabulator", {
 layout:"fitColumns",
 data:[ {name:'Geordi La Forge',species:'Human'}, {name:'Dathon', species:'Tamarian'}, {name:'Jean-Luc Picard', species:'Human'}, {name:'Worf, son of Mogh', species:'Klingon'}, {name:'Tasha Yarr', species:'Human'}, {name:'Data', species:'Android'}, {name:'Wesley Crusher', species:'Human'}, {name:'Jalad', species:'Tamarian'}, {name:'Lwaxana Troi', species:'Betazoid'}, {name:'Temba', species:'Tamarian'}, {name:'T\'Kuvma', species:'Klingon'}, {name:'Lore', species:'Android'}, {name:'Noonian Soongh', species:'Human'}, {name:'Darmok', species:'Tamarian'}, {name:'Reittan Grax', species:'Betazoid'}, {name:'Quark', species:'Ferengi'} ],
 headerSort:true,
 columns:[ {title:'Name',field:'name',sorter:'string'},{title:'Species',field:'species',sorter:'string',headerFilter:multiSelectHeaderFilter }, ],
});

//document.multiselect('#speciesSelector');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<link href="https://unpkg.com/tabulator-tables@4.5.3/dist/css/tabulator.min.css" rel="stylesheet">
<script type="text/javascript" src="https://unpkg.com/tabulator-tables@4.5.3/dist/js/tabulator.min.js"></script>
<link href="https://cdn.jsdelivr.net/gh/mneofit/multiselect/styles/multiselect.css" rel="stylesheet">
<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/mneofit/multiselect/multiselect.min.js"></script>
<script></script>
<style>
.tabulator .tabulator-header,
.tabulator .tabulator-header .tabulator-col
{
  overflow: unset;
}
</style>
</head>
<body>
<div id="tabulator"></div>
</body>
</html></code>```

答:
Fixed by adding headerFilterLiveFilter:false to the column definition.

columns:[ {title:'Name',field:'name',sorter:'string'},{title:'Species',field:'species',sorter:'string',headerFilter:multiSelectHeaderFilter,headerFilterLiveFilter:false }, ],
```

https://jsfiddle.net/jjech/3th28pv0/237/

Body:
To reproduce:

Run the Code Snippet (recommend Full Page mode)

Hold Ctrl or Shift while clicking to select multiple 'species' in the table column header

Note that while the key is held down, the table data is filtered according to selected 'species'

Release the key, observe changes in filtered table data

I think this is probably related to https://github.com/olifolkerd/tabulator/issues/975 and that I need to do something to override default tabulator keypress events.

JSFiddle: https://jsfiddle.net/jjech/3th28pv0/229/

const speciesTypes = [ 'Human', 'Android', 'Betazoid', 'Klingon', 'Ferengi', 'Tamarian' ];

function multiSelectHeaderFilter(cell) {

 var values = speciesTypes;

 const filterFunc = (rowData) => {
   return values.includes(rowData['species']);
 }

  const getSelectedValues = (multiSelect) => {
    var result = [];
    var options = multiSelect && multiSelect.options;
    var opt;

    for (var i=0, iLen=options.length; i<iLen; i++) {
      opt = options[i];

      if (opt.selected) {
        result.push(opt.value || opt.text);
      }
    }
    return result;
  }

 const onChange = () => {
   var editor = document.getElementById('speciesSelector');
    values = getSelectedValues(editor);
    console.log("values: "+values);
    cell.getColumn().getTable().removeFilter(filterFunc);
    cell.getColumn().getTable().addFilter(filterFunc);
  }

 var select = document.createElement("select");
  select.multiple = "multiple";
 select.id = 'speciesSelector';
  select.style = 'width: 100%';
  speciesTypes.forEach(species => {
   select.innerHTML += "<option id='"+species+"' value='"+species+"' selected='selected'>"+species+"</option>";
  });
  cell.getColumn().getTable().addFilter(filterFunc);
  select.addEventListener('change',onChange);
  return select;
}

var table = new Tabulator("#tabulator", {
 layout:"fitColumns",
 data:[ {name:'Geordi La Forge',species:'Human'}, {name:'Dathon', species:'Tamarian'}, {name:'Jean-Luc Picard', species:'Human'}, {name:'Worf, son of Mogh', species:'Klingon'}, {name:'Tasha Yarr', species:'Human'}, {name:'Data', species:'Android'}, {name:'Wesley Crusher', species:'Human'}, {name:'Jalad', species:'Tamarian'}, {name:'Lwaxana Troi', species:'Betazoid'}, {name:'Temba', species:'Tamarian'}, {name:'T\'Kuvma', species:'Klingon'}, {name:'Lore', species:'Android'}, {name:'Noonian Soongh', species:'Human'}, {name:'Darmok', species:'Tamarian'}, {name:'Reittan Grax', species:'Betazoid'}, {name:'Quark', species:'Ferengi'} ],
 headerSort:true,
 columns:[ {title:'Name',field:'name',sorter:'string'},{title:'Species',field:'species',sorter:'string',headerFilter:multiSelectHeaderFilter }, ],
});

//document.multiselect('#speciesSelector');

<link href="https://unpkg.com/tabulator-tables@4.5.3/dist/css/tabulator.min.css" rel="stylesheet">

<link href="https://cdn.jsdelivr.net/gh/mneofit/multiselect/styles/multiselect.css" rel="stylesheet">

Body:
Fixed by adding headerFilterLiveFilter:false to the column definition.

columns:[ {title:'Name',field:'name',sorter:'string'},{title:'Species',field:'species',sorter:'string',headerFilter:multiSelectHeaderFilter,headerFilterLiveFilter:false }, ],

https://jsfiddle.net/jjech/3th28pv0/237/


问:
How do you connect a git repo to gerrit?
I have installed git and setup gerrit on my local PC.

In my folder C:\git\Gerrit\git I have created a repo.  I made come changes to the contained file, added and committed it.

I then pushed it to gerrit using the command:

git push origin head:refs/for/master

and I get the reply:

Enumerating objects: 5, done.   Counting objects: 100% (5/5), done.

  Writing objects: 100% (3/3), 273 bytes | 273.00 KiB/s, done.  Total 3
  (delta 0), reused 0 (delta 0)  To origin     71f7b5d..0375419  head ->
  refs/for/master

Whereas in documentation I have followed the reply was supposed to be of the form

$ git commit [master 3cc9e62]  Change to a proper, yeast based pizza
  dough.    1 file changed, 10 insertions(+), 5 deletions(-)   $ git
  push origin HEAD:refs/for/master Counting objects: 3, done.  Delta
  compression using up to 8 threads.   Compressing objects: 100% (2/2),
  done.   Writing objects: 100% (3/3), 532 bytes | 0 bytes/s, done.
  Total 3 (delta 0), reused 0 (delta 0)  remote: Processing changes:
  new: 1, done remote:  remote: New Changes:  remote:

  http://gerrithost/#/c/RecipeBook/+/702 Change to a proper, yeast based
  pizza dough.   remote: To ssh://gerrithost:29418/RecipeBook  * [new
  branch]      HEAD -> refs/for/master

But nothing appears in gerrit.  I am looking on the page identified as the CannonicalWebURL in the config file.

I presume I need to link the repo and gerrit together somehow but I cannot seem to work out how to do it.
Has anyone gone through this?

答:
I don't know how did you get the remote "gerrit MyMachineName.MyDomain.local:TestProject" using just "git init" (is there any configuration in your .gitconfig file?) but if you want to create a new repository in Gerrit you must do the following steps:

Log in the Gerrit web tool

Create the repository in the Gerrit UI at
BROWSE > Repositories > CREATE NEW

Clone the empty repository using
the "git clone" command available in the Gerrit UI at BROWSE >
Repositories >

Create whatever you want and commit
your changes

Push to Gerrit executing: "git push origin
HEAD:refs/for/master"

See more info in the Gerrit documentation here


问:
How to click and hold using the webdriverio
I am trying to figure out how to click and hold using webdriverio. In selenium it is like this:

```<code>WebElement elementToInteractWith = driver.findElement(By.id("myElement"));

Actions holdClick = new Actions(driver);

holdClick.clickAndHold(elementToInteractWith).perform();

//wait for however long you need to hold

holdClick.release().perform();
</code>```

However i am not sure how to do that in webdriver io but cannot find anything on the documentation

答:
I believe you can try this.

https://webdriver.io/docs/api/jsonwp.html#buttondown

You can have a pause after this for the time you need to and then buttonup should follow.

Cheers!

Body:
I am trying to figure out how to click and hold using webdriverio. In selenium it is like this:

WebElement elementToInteractWith = driver.findElement(By.id("myElement"));

Actions holdClick = new Actions(driver);

holdClick.clickAndHold(elementToInteractWith).perform();

//wait for however long you need to hold

holdClick.release().perform();

However i am not sure how to do that in webdriver io but cannot find anything on the documentation


问:
Can a validator be associated with more than one rule set?
Using the (MS) Enterprise Library, Validation Application Block (VAB), you can include attributes in your code to define rule sets. I have applied the attributes to the properties of a class and I have defined two rule sets (the properties fall into two validation groups). Unfortunatly there is some overlap between the two rule sets (some properties are in both groups).

Can a validation attribute belong to multiple rule sets and what does the syntax look like? If this is not possible, is there a work-around?

答: The work-around is simply to duplicate every validation attribute for every rule set. </p>

OwnerDisplayName: Seventh Element

ContentLicense: CC BY-SA 2.5


问:
Banner and top of page has blank space in between
there's this space between the transparent banner and top of the page. all the margin and padding options have been set to 0. i don't know what i'm doing wrong, any ideas?

image: https://imgur.com/a/XQMsOVT

Body:

```<code><video autoplay muted loop id="myVideo">
  <source src="sparkle.mp4" type="video/mp4">
  Your browser does not support HTML5 video.
</video>

        <div class="hero-image" >
            <h1 align="center" style="color:white; font-size:50px; font-family:Sofia;">Sparkle</h1>
        </div>

        <div id="ok">
            <H1 style="padding:0; margin:0; overflow:hidden;" align="center"> </h1>
        </div >
    <p style="position:relative;"> okok <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br>  <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> okoks </p>
</code>```

css:

```<code>body, html {
  margin: 0px 0px 0px 0px ;
  padding:0px 0px 0px 0px ;
  font-family: Arial, Helvetica, sans-serif;

  background-repeat:no-repeat;
  background-size:cover;
}

#myVideo {
  position: absolute;
  right: 0;
  bottom: 0;
  min-width: 100%;
  min-height: 100%;
  z-index:-10
}

.hero-image {
  overflow:scroll
  margin:0;
  top:0;
  width: 100vw;
  position: sticky;
  background-color: rgba(0, 0, 0, 0.3);
}
</code>```

答:
Missing a comma after "overflow:scroll" which affects the next line of CSS</p>

```<code>.hero-image {
  overflow:scroll; // semi-colon added
  margin:0;
  top:0;
  width: 100vw;
  position: sticky;
  background-color: rgba(0, 0, 0, 0.3);
}
</code>```

Body:
there's this space between the transparent banner and top of the page. all the margin and padding options have been set to 0. i don't know what i'm doing wrong, any ideas?

image: https://imgur.com/a/XQMsOVT

Body:

<video autoplay muted loop id="myVideo">
  <source src="sparkle.mp4" type="video/mp4">
  Your browser does not support HTML5 video.
</video>

Sparkle

 okok

 okoks

css:

body, html {
  margin: 0px 0px 0px 0px ;
  padding:0px 0px 0px 0px ;
  font-family: Arial, Helvetica, sans-serif;

  background-repeat:no-repeat;
  background-size:cover;
}

#myVideo {
  position: absolute;
  right: 0;
  bottom: 0;
  min-width: 100%;
  min-height: 100%;
  z-index:-10
}

.hero-image {
  overflow:scroll
  margin:0;
  top:0;
  width: 100vw;
  position: sticky;
  background-color: rgba(0, 0, 0, 0.3);
}

Body:
Missing a comma after "overflow:scroll" which affects the next line of CSS

.hero-image {
  overflow:scroll; // semi-colon added
  margin:0;
  top:0;
  width: 100vw;
  position: sticky;
  background-color: rgba(0, 0, 0, 0.3);
}


问:
Using FontAwesome with Nativescript-Vue
I'm just not succeeding in using FontAwesome icons in my Nativescript-Vue app. If I just want to use a regular icon, it works fine:

```<code><Label col="0" text.decode="" class="fa"></Label>
</code>```

But when I want a Solid (or I suppose any of the others), no love.

```<code><Label col="0" text.decode="" class="fa fas"></Label>
</code>```

I've looked at so many instructions now that my eyes are crossed.
Today I upgraded to v5. But I don't thing I was able to get the solid ones to work before.

Title: Using FontAwesome with Nativescript-Vue

Body:
I'm just not succeeding in using FontAwesome icons in my Nativescript-Vue app. If I just want to use a regular icon, it works fine:

But when I want a Solid (or I suppose any of the others), no love.

I've looked at so many instructions now that my eyes are crossed.
Today I upgraded to v5. But I don't thing I was able to get the solid ones to work before.

Body:
I work with Nativescript-Vue and I use Nathan Walker plugin nativescript-fonticon. It works very fine with FontAwesome 5.

It's very easy to use.

Install the plugin:

npm install nativescript-fonticon --save

Place font icon .ttf files in app/fonts

fa-brands-400.ttf
 fa-regular-400.ttf
 fa-solid-900.ttf

Create base class (my css file is placed in  assets/scss/global.scss):

.fa,
 .far {
   font-family: 'Font Awesome 5 Free', 'fa-regular-400';
   font-weight: 400;
  }
 .fas {
   font-family: 'Font Awesome 5 Free', 'fa-solid-900';
   font-weight: 900;
  }
 .fab {
   font-family: 'Font Awesome 5 Free', 'fa-brands-400';
   font-weight: 400;
  }

Copy css to app somewhere. I place my files in assets\css folder (I use minified format):

assets/css/all.min.css
 assets/css/brands.min.css
 assets/css/fontawesome.min.css
 assets/css/regular.min.css
 assets/css/solid.min.css

Add and load the plugin in main.js

import { TNSFontIcon, fonticon } from 'nativescript-fonticon'

// Load TNSFonticon
 TNSFontIcon.debug = true
 TNSFontIcon.paths = {
   fa: './assets/css/fontawesome.min.css',
   far: './assets/css/regular.min.css',
   fas: './assets/css/solid.min.css',
   fab: './assets/css/brand.min.css'
 }
 TNSFontIcon.loadCss()
 Vue.filter('fonticon', fonticon)

Use the component in your code:

<Label class="fas" text="fa-chess-knight | fonticon"></Label>


问:
Search into MySQL PDO PHP
I have JSON 'https://jsonplaceholder.typicode.com/todos/' from where I take data and populate MySQL. Then I connect to MySQL and display data. I made a search box and button to serch inside my table and it works perfectly. The result I display it in table in mt php page. But i have one problem. This is how I insert JSON data into MySQL and here is the table where I display data from DB in to my php page:

```<code>     function getDati()
        {
            $url = 'https://jsonplaceholder.typicode.com/todos/';
            $cURL = curl_init();
            curl_setopt($cURL, CURLOPT_URL, $url);
            curl_setopt($cURL, CURLOPT_HTTPGET, true);
            curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);

            curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Accept: application/json'
            ));

            $result = curl_exec($cURL);
            curl_close($cURL);
            $all_items = json_decode($result);
            return $all_items;
        }
    //DB CONECTION
    class Database
    {
        private $db_host;
        private $db_name;
        private $db_username;
        private $db_password;

        public function dbConnection()
        {
            $this->db_host = 'localhost';
            $this->db_name = 'items';
            $this->db_username = '*****';
            $this->db_password = '****';
            try {
                $conn = new PDO('mysql:host=' . $this->db_host . ';dbname=' . $this->db_name, $this->db_username, $this->db_password);
                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                return $conn;
            } catch (PDOException $e) {
                echo "Connection error " . $e->getMessage();
                exit;
            }
        }
    }
//connecto to DB to displayit into my php page
<?php
            $database = new Database;
            $db = $database->dbConnection();
            $stmt = $db->query("SELECT * FROM posts ");
            $stmt->execute();
            ?>
 <table class="table table-hover">
                    <hr>
                    <div style="text-align: center"> <label class="badge badge-light" style="font-size:30px; background-color: #2196F3;">All Items</label></div>
                    <hr>
                    <thead>
                        <tr>
                            <th>User ID</th>
                            <th>ID</th>
                            <th>Title</th>
                            <th>Compiled</th>
                        </tr>
                    </thead>
                    <?php foreach ($stmt as $item) : ?>
                        <tr>
                            <td><?php echo $item['userId'] ?> </td>
                            <td><?php echo $item['id'] ?> </td>
                            <td><?php echo $item['title'] ?></td>
                            <td><?php echo $item['completed'] ? 'Compiled' : 'Not Compiled' ?></td> //completed is boolean so I used "? 'Compiled' : 'Not Compiled'" to not be displayed 0 or 1
</tr>
                    <?php endforeach ?>
                </table>
</code>```

And here is HTML code for search box and button:

```<code><form method="post" class="form-inline my-2 my-lg-0 navbar navbar-expand-lg navbar-light bg-dark">
            <input name="search" class="form-control mr-sm-2" placeholder="Search" aria-label="Search">
            <button name="submit-search" class="btn  my-2 my-sm-0 bg-white" type="submit">Search</button>
        </form>
</code>```

And code for  function Search():

```<code>function search()
{
    $keyword = '%' . $_POST['search'] . '%';
    $database = new Database;
    $db = $database->dbConnection();
    $stmt = $db->query("SELECT * FROM posts WHERE id LIKE '$keyword' OR userId LIKE '$keyword' OR title LIKE '$keyword'  OR completed LIKE  '$keyword'");
    $stmt->execute();
 <div class="container" style=" margin-top:5%;">
        <table class=" table table-hover" id="search-table" style="font-size: 18px;">
            <hr>
            <div style="text-align:center;"> <label style="text-shadow: 5px 5px 5px rgba(0, 0, 0, 0.1), 10px 10px 10px rgba(0, 0, 0, 0.2); font-size:30px;border-radius: 45px; "> Results from search : </label></div> <br>
            <tr>
                <th>User ID:</th>
                <th> ID: </th>
                <th> Title: </th>
                <th> Compiled: </th>
            </tr>

            <?php while ($row = $stmt->fetch()) : ?>
                <tr>
                    <td> <?php echo $row['userId'] ?> </td>
                    <td> <?php echo $row['id'] ?> </td>
                    <td> <?php echo $row['title'] ?> </td>
                    <td> <?php echo $row['completed'] ? 'Compiled' : 'Not Compiled' ?> </td>
                </tr>
            <?php endwhile ?>
        </table>
    </div>
<?php } ?>
</code>```

The problem is that JSON file have one array with 200 objects and those 200 objects have properties like userId, id, title, completed. Completed is boolean type and inside MySQL it is saved like 0 or 1 (false / true). So obviously when I type Completed or Not completed in my search box it results nothing.

How can I display all Completed or Not completed items that are  in my MySQL table when I type Completed or Not completed in the search box.

UPDATE:
My HTML search from 2 inputs :

```<code><div class="container bg-light " style=" margin-top:8%; width:30%;" id="searcform">
    <form method="post">
        <div class="text-center">
            <label class="h3 font-weight-bold">SEARCH BY:</label>
        </div>
        <hr>
        <div class="form-group">
            <label for="formGroupExampleInput">User ID: </label>
            <input type="text" name="userId" class="form-control" id="formGroupExampleInput" required>
        </div>
        <div class="form-group ">
            <label for="formGroupExampleInput2">Title</label>
            <input type="text" name="title" class="form-control" id="formGroupExampleInput2" required>
        </div>
        <button type="submit" name="search-btn2" class="btn btn-primary">Search</button>
        <hr>
    </form>
</div>
</code>```

And PHP search from 2 inputs :

```<code>if (isset($_POST['search-btn2'])) {

    $values = [];
    $conditions = [];
    $conditions[] = "1";  /* trivial condition that is True */

    $userId = $_POST['userId'];
    if ($userId != '') {
        $values[] = $userId;
        $conditions[] = "userId = ?";
    }
    $title = $_POST['title'];
    if ($title  != '') {
        $values[] = $title;
        $conditions[] = "title like concat('%', ?, '%')";
    }

    $database = new Database;
    $db = $database->dbConnection();
    $cond = join(' AND ', $conditions);
    $sql = "SELECT * FROM posts WHERE $cond";
    $stmt = $db->prepare($sql);
    $stmt->execute($values);
}
?>
</code>```

答:
I would recommend that your search box contain a separate input widget for each parameter the user can supply.

You should use a <select> HTML tag for specifying the completed search parameter as follows:

```<code><select name="completed">
    <option value=''>-- Select a Completion Value --</option>
    <option value="0">Not Completed</option>
    <option value="1">Completed</option>
</select>
</code>```

You could have a <select> tag for the id parameter:

```<code><select name="id">
    <option value=''>-- Select an id value --</option>
    <option value="id-value-1">id-value-1</option>
    <option value="id-value-2">id-value-2</option>
    . . .
    <option value="id-value-N">id-value-N</option>
</select>
</code>```

The above would have to be initialized in a loop. Or else you could have a simple text box where the user has to type in the id of the row of interest.

You should have text input fields userId and title:

```<code>User Id: <input type="text" name="userId">
Title: <input type="text" name="title">
</code>```

Your PHP code then should be:

```<code>$values = [];
$conditions = [];
$conditions[] = "1";
$completed = $_POST['completed'];
if ($completed != '') {
    $values[] = $completed;
    $conditions[] = "completed = ?";
}
$id = $_POST['id'];
if ($id != '') {
    $values[] = $id;
    $conditions[] = "id = ?";
}
$userId = $_POST['userId'];
if ($userId != '') {
    $values[] = $userId;
    $conditions[] = "userId = ?";
}
$title = $_POST['title'];
if ($title  != '') {
    $values[] = $title;
    $conditions[] = "title like concat('%', ?, '%')";
}
$cond = join(' AND ', $conditions);
$db = $database->dbConnection();
$stmt = $db->prepare("SELECT * FROM posts WHERE $cond");
$stmt->execute($values);
</code>```

Note that the above code used a prepared statement to prevent SQL Injection attacks. If you can ensure that there is always at least one input criteria specified such that the $conditions array is not empty, then the 1 condition can be removed from the SELECT statement.

Title: Search into MySQL PDO PHP

Body:
I have JSON 'https://jsonplaceholder.typicode.com/todos/' from where I take data and populate MySQL. Then I connect to MySQL and display data. I made a search box and button to serch inside my table and it works perfectly. The result I display it in table in mt php page. But i have one problem. This is how I insert JSON data into MySQL and here is the table where I display data from DB in to my php page:

     function getDati()
        {
            $url = 'https://jsonplaceholder.typicode.com/todos/';
            $cURL = curl_init();
            curl_setopt($cURL, CURLOPT_URL, $url);
            curl_setopt($cURL, CURLOPT_HTTPGET, true);
            curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);

            curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Accept: application/json'
            ));

            $result = curl_exec($cURL);
            curl_close($cURL);
            $all_items = json_decode($result);
            return $all_items;
        }
    //DB CONECTION
    class Database
    {
        private $db_host;
        private $db_name;
        private $db_username;
        private $db_password;

        public function dbConnection()
        {
            $this->db_host = 'localhost';
            $this->db_name = 'items';
            $this->db_username = '*****';
            $this->db_password = '****';
            try {
                $conn = new PDO('mysql:host=' . $this->db_host . ';dbname=' . $this->db_name, $this->db_username, $this->db_password);
                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                return $conn;
            } catch (PDOException $e) {
                echo "Connection error " . $e->getMessage();
                exit;
            }
        }
    }
//connecto to DB to displayit into my php page
<?php
            $database = new Database;
            $db = $database->dbConnection();
            $stmt = $db->query("SELECT * FROM posts ");
            $stmt->execute();
            ?>

 All Items

                            User ID
                            ID
                            Title
                            Compiled

                    <?php foreach ($stmt as $item) : ?>

                            <?php echo $item['userId'] ?>
                            <?php echo $item['id'] ?>
                            <?php echo $item['title'] ?>
                            <?php echo $item['completed'] ? 'Compiled' : 'Not Compiled' ?>	 //completed is boolean so I used "? 'Compiled' : 'Not Compiled'" to not be displayed 0 or 1

                    <?php endforeach ?>

And here is HTML code for search box and button:

<form method="post" class="form-inline my-2 my-lg-0 navbar navbar-expand-lg navbar-light bg-dark">
            <input name="search" class="form-control mr-sm-2" placeholder="Search" aria-label="Search">
            <button name="submit-search" class="btn  my-2 my-sm-0 bg-white" type="submit">Search</button>
        </form>

And code for  function Search():

function search()
{
    $keyword = '%' . $_POST['search'] . '%';
    $database = new Database;
    $db = $database->dbConnection();
    $stmt = $db->query("SELECT * FROM posts WHERE id LIKE '$keyword' OR userId LIKE '$keyword' OR title LIKE '$keyword'  OR completed LIKE  '$keyword'");
    $stmt->execute();

  Results from search :

                User ID:
                 ID:
                 Title:
                 Compiled:

            <?php while ($row = $stmt->fetch()) : ?>

                     <?php echo $row['userId'] ?>
                     <?php echo $row['id'] ?>
                     <?php echo $row['title'] ?>
                     <?php echo $row['completed'] ? 'Compiled' : 'Not Compiled' ?>

            <?php endwhile ?>

<?php } ?>

The problem is that JSON file have one array with 200 objects and those 200 objects have properties like userId, id, title, completed. Completed is boolean type and inside MySQL it is saved like 0 or 1 (false / true). So obviously when I type Completed or Not completed in my search box it results nothing.

How can I display all Completed or Not completed items that are  in my MySQL table when I type Completed or Not completed in the search box.

UPDATE:
My HTML search from 2 inputs :

    <form method="post">

            SEARCH BY:

            User ID:
            <input type="text" name="userId" class="form-control" id="formGroupExampleInput" required>

            Title
            <input type="text" name="title" class="form-control" id="formGroupExampleInput2" required>

        <button type="submit" name="search-btn2" class="btn btn-primary">Search</button>

    </form>

And PHP search from 2 inputs :

if (isset($_POST['search-btn2'])) {

    $values = [];
    $conditions = [];
    $conditions[] = "1";  /* trivial condition that is True */

    $userId = $_POST['userId'];
    if ($userId != '') {
        $values[] = $userId;
        $conditions[] = "userId = ?";
    }
    $title = $_POST['title'];
    if ($title  != '') {
        $values[] = $title;
        $conditions[] = "title like concat('%', ?, '%')";
    }

    $database = new Database;
    $db = $database->dbConnection();
    $cond = join(' AND ', $conditions);
    $sql = "SELECT * FROM posts WHERE $cond";
    $stmt = $db->prepare($sql);
    $stmt->execute($values);
}
?>

Body:
I would recommend that your search box contain a separate input widget for each parameter the user can supply.

You should use a <select> HTML tag for specifying the completed search parameter as follows:

<select name="completed">
    <option value=''>-- Select a Completion Value --</option>
    <option value="0">Not Completed</option>
    <option value="1">Completed</option>
</select>

You could have a <select> tag for the id parameter:

<select name="id">
    <option value=''>-- Select an id value --</option>
    <option value="id-value-1">id-value-1</option>
    <option value="id-value-2">id-value-2</option>
    . . .
    <option value="id-value-N">id-value-N</option>
</select>

The above would have to be initialized in a loop. Or else you could have a simple text box where the user has to type in the id of the row of interest.

You should have text input fields userId and title:

User Id: <input type="text" name="userId">
Title: <input type="text" name="title">

Your PHP code then should be:

$values = [];
$conditions = [];
$conditions[] = "1";
$completed = $_POST['completed'];
if ($completed != '') {
    $values[] = $completed;
    $conditions[] = "completed = ?";
}
$id = $_POST['id'];
if ($id != '') {
    $values[] = $id;
    $conditions[] = "id = ?";
}
$userId = $_POST['userId'];
if ($userId != '') {
    $values[] = $userId;
    $conditions[] = "userId = ?";
}
$title = $_POST['title'];
if ($title  != '') {
    $values[] = $title;
    $conditions[] = "title like concat('%', ?, '%')";
}
$cond = join(' AND ', $conditions);
$db = $database->dbConnection();
$stmt = $db->prepare("SELECT * FROM posts WHERE $cond");
$stmt->execute($values);

Note that the above code used a prepared statement to prevent SQL Injection attacks. If you can ensure that there is always at least one input criteria specified such that the $conditions array is not empty, then the 1 condition can be removed from the SELECT statement.


问:
rephrase definition for android orientation angle "roll"
The definition of 'roll' in android is:

angle between a plane perpendicular to the device's screen and a plane perpendicular to the ground

See here.

Maybe I'm missing something, but there seem to be many planes perpendicular to the ground giving many different angles.

Could someone please rephrase this definition using e.g planes parallel to ground or screen, north direction, gravity direction?

NB! I am asking for a rephrasing using different words. I know the official definition as I have stated. Please don't repost the official definition.

答:
From the mentioned docs:

Roll, angle of rotation about the y axis. This value represents the
angle between a plane perpendicular to the device's screen and a plane
perpendicular to the ground.

From another doc:

Roll (degrees of rotation about the y axis). This is the angle between
a plane perpendicular to the device's screen and a plane perpendicular
to the ground. If you hold the device parallel to the ground with the
bottom edge closest to you and tilt the left edge of the device toward
the ground, the roll angle becomes positive. Tilting in the opposite
direction—moving the right edge of the device toward the ground—
causes the roll angle to become negative. The range of values is -90
degrees to 90 degrees.

You may also have a look at that picture

The important point is about the y-axis. The y-axis is the one that goes positive from the bottom edge to the upper edge of the screen.

----EDIT----

A may be much more explicit picture here.


问:
Why am I getting an ArraIndexOutOfBoundException?
I am trying to copy an byte array (fileData), which I read from a file, into another byte array (subdata) (below the code):

```<code>                ByteBuffer inputBuffer = decoderInputBuffers[intBufIndex];
                int limit = inputBuffer.capacity();
                int pos = frameIndex * limit;
                byte[] subData = new byte[limit];

                System.arraycopy(fileData, pos, subData, 0, subData.length);
</code>```

My question is why I am gettng this error?

```<code>java.lang.ArrayIndexOutOfBoundsException: src.length=732542 srcPos=0 dst.length=1572864 dstPos=0 length=1572864
</code>```

How ist that even possible since I say explicitly say what the size of the array should be.

答:
If you look at the docs (which you have linknd in comments) it says that the last parameter of the function is:

length − This is the number of array elements to be copied.

so if you look closely you are trying to copy 1572864 from an array of 732542 and that's why you are getting the exception

Body:
I am trying to copy an byte array (fileData), which I read from a file, into another byte array (subdata) (below the code):

                ByteBuffer inputBuffer = decoderInputBuffers[intBufIndex];
                int limit = inputBuffer.capacity();
                int pos = frameIndex * limit;
                byte[] subData = new byte[limit];

                System.arraycopy(fileData, pos, subData, 0, subData.length);

My question is why I am gettng this error?

java.lang.ArrayIndexOutOfBoundsException: src.length=732542 srcPos=0 dst.length=1572864 dstPos=0 length=1572864

How ist that even possible since I say explicitly say what the size of the array should be.


问:
Purpose of using sub routines over functions
I've been working with Access for a while now, and although I understand the obvious benefit of a Function over a Sub, been that it can return values as a result, I'm not sure as to why I should use a Sub over a Function. After all unless I'm mistaken; Functions can do everything Subs can do?

Note: I'm fully aware of how to use both Sub's and Function's so not looking for an explanation of how they work.

答:
I found one other difference, at least on Excel but likely other Office apps. If you want to customize the ribbon by adding a button to launch a VB program, when you choose Macros in the "Choose commands from" dropdown menu, it lists any Subs in your code but not Functions. Note that a Private Sub will also be hidden from the customize ribbon selection, as will a Public Function.

So to summarize, these will be available to add as buttons on the ribbon:
   Sub, Public Sub

And these will not be available to add:
   Function, Public Function, Private Function, Private Sub