问:
Could not find or load main class when trying to connect MariaDB
Error: Could not find or load main class...

What am I doing wrong when trying to connect Maria DB in java? I'm a novice developer in java so don't be rude...

Am I compiling in a wrong way this file? Also I tried to download mysql and mariaDb drivers but still had no success...I think the driver is not the problem, appreciate all the guidance and help.

This is all my code:

```<code>Panaderia.java

package proyecto;

import javax.swing.JFrame;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.awt.FlowLayout;
import java.sql.*;

public class Panaderia extends JFrame implements ActionListener{
    JTextArea tablas_ta;
    JTextArea registros_ta;
    JButton consultarTablas_btn;
    JButton consultarRegistros_btn;
    JTextField textField;

    /*
     * Método constructor
     **/
    public Panaderia(){

        super("Ejemplo de Java + MySQL");

        //Configurar la operación de salida por defecto para JFrame
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        this.setSize(800,750);

        setLayout(new FlowLayout());

        consultarTablas_btn = new JButton("Consultar tablas");
        consultarTablas_btn.setActionCommand("ConsultarTablas");
        add(consultarTablas_btn);

        tablas_ta = new JTextArea(10, 70);
        add(tablas_ta);

        textField = new JTextField(30);
        add(textField);

        consultarRegistros_btn = new JButton("Consultar registros");
        consultarRegistros_btn.setActionCommand("ConsultarRegistros");
        add(consultarRegistros_btn);

        registros_ta = new JTextArea(10, 70);
        add(registros_ta);

        // Usar este objeto como Manejador de eventos
        consultarTablas_btn.addActionListener(this);
        consultarRegistros_btn.addActionListener(this);
        textField.addActionListener(this);

        this.setVisible(true);
    }

    public static void main(String[] args) {

        Panaderia mjf = new Panaderia();
    }

    @Override
    public void actionPerformed(ActionEvent evento) {
        String db, dbuser, pass;
            db = "ejemplos";//cambiar por el nombre de la base de datos que desean utilizar
            dbuser = "root";
            pass = "";
        if(evento.getActionCommand()=="ConsultarTablas") {

            try {
                Class.forName("com.mysql.jdbc.Driver");

                Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/"+db, dbuser, pass);

                Statement stmt = con.createStatement();
                ResultSet rs = stmt.executeQuery("SHOW TABLES");

                while( rs.next() ) {
                    tablas_ta.append( rs.getString(1) + "\n");
                }

                tablas_ta.append("\n");

                con.close();

            } catch(Exception e) {
                System.out.println(e);
            }

        }

        if(evento.getActionCommand()=="ConsultarRegistros") {

            try {
                Class.forName("com.mysql.jdbc.Driver");

                Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/"+db, dbuser, pass);

                Statement stmt = con.createStatement();

                ResultSet rs = stmt.executeQuery("SELECT * FROM "+textField.getText());

                String registro = "";

                while( rs.next() ) {
                    for(int i=1;i<=rs.getMetaData().getColumnCount();i++){
                        registro = registro + "\t" + rs.getString(i);
                    }
                    registros_ta.append( registro +"\n");
                    registro = "";
                }

                registros_ta.append("\n");

                con.close();

            } catch(Exception e) {
                System.out.println(e);
            }

        }

    }
}

</code>```

The error showing in terminal is:

How should you fix it?

答: Your code seems correct. I had run on my eclipse. The only thing, you have not supplied a password for the database. I will advise you to move to one of these IDE - Eclipse or Netbeans. Compiling on the command line is time taking and not useful.</p>

Body:
Error: Could not find or load main class...

What am I doing wrong when trying to connect Maria DB in java? I'm a novice developer in java so don't be rude...

Am I compiling in a wrong way this file? Also I tried to download mysql and mariaDb drivers but still had no success...I think the driver is not the problem, appreciate all the guidance and help.

This is all my code:

Panaderia.java

package proyecto;

import javax.swing.JFrame;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.awt.FlowLayout;
import java.sql.*;

public class Panaderia extends JFrame implements ActionListener{
    JTextArea tablas_ta;
    JTextArea registros_ta;
    JButton consultarTablas_btn;
    JButton consultarRegistros_btn;
    JTextField textField;

    /*
     * Método constructor
     **/
    public Panaderia(){

        super("Ejemplo de Java + MySQL");

        //Configurar la operación de salida por defecto para JFrame
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        this.setSize(800,750);

        setLayout(new FlowLayout());

        consultarTablas_btn = new JButton("Consultar tablas");
        consultarTablas_btn.setActionCommand("ConsultarTablas");
        add(consultarTablas_btn);

        tablas_ta = new JTextArea(10, 70);
        add(tablas_ta);

        textField = new JTextField(30);
        add(textField);

        consultarRegistros_btn = new JButton("Consultar registros");
        consultarRegistros_btn.setActionCommand("ConsultarRegistros");
        add(consultarRegistros_btn);

        registros_ta = new JTextArea(10, 70);
        add(registros_ta);

        // Usar este objeto como Manejador de eventos
        consultarTablas_btn.addActionListener(this);
        consultarRegistros_btn.addActionListener(this);
        textField.addActionListener(this);

        this.setVisible(true);
    }

    public static void main(String[] args) {

        Panaderia mjf = new Panaderia();
    }

    @Override
    public void actionPerformed(ActionEvent evento) {
        String db, dbuser, pass;
            db = "ejemplos";//cambiar por el nombre de la base de datos que desean utilizar
            dbuser = "root";
            pass = "";
        if(evento.getActionCommand()=="ConsultarTablas") {

            try {
                Class.forName("com.mysql.jdbc.Driver");

                Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/"+db, dbuser, pass);

                Statement stmt = con.createStatement();
                ResultSet rs = stmt.executeQuery("SHOW TABLES");

                while( rs.next() ) {
                    tablas_ta.append( rs.getString(1) + "\n");
                }

                tablas_ta.append("\n");

                con.close();

            } catch(Exception e) {
                System.out.println(e);
            }

        }

        if(evento.getActionCommand()=="ConsultarRegistros") {

            try {
                Class.forName("com.mysql.jdbc.Driver");

                Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/"+db, dbuser, pass);

                Statement stmt = con.createStatement();

                ResultSet rs = stmt.executeQuery("SELECT * FROM "+textField.getText());

                String registro = "";

                while( rs.next() ) {
                    for(int i=1;i<=rs.getMetaData().getColumnCount();i++){
                        registro = registro + "\t" + rs.getString(i);
                    }
                    registros_ta.append( registro +"\n");
                    registro = "";
                }

                registros_ta.append("\n");

                con.close();

            } catch(Exception e) {
                System.out.println(e);
            }

        }

    }
}

The error showing in terminal is:

How should you fix it?


来源: stackexchange

问:
r data formatting with NAs
If I have a dataset with three columns like this below

```<code> Id    Date       Gender
 1     NA         F
 1     NA         NA
 1     03-11-1977 NA
 2     04-17-2005 NA
 2     NA         M
 3     NA         NA
 3     06-04-1999 NA
 3     NA         F
</code>```

How could I clean this data such that I see a dataset like this below ?

```<code>Id    Date        Gender
 1     03-11-1977 F
 2     04-17-2005 M
 3     06-04-1999 F
</code>```

Thanks.

答:
You may use na.omit in a by approach.

```<code>dat <- do.call(rbind, by(dat, dat$Id, function(x) cbind(x[1,1,drop=F], lapply(x[-1], na.omit))))
dat
#   Id       Date Gender
# 1  1 03-11-1977      F
# 2  2 04-17-2005      M
# 3  3 06-04-1999      F
</code>```

Data:

```<code>dat <- read.table(header=T,text=' Id    Date       Gender
 1     NA         F
 1     NA         NA
 1     03-11-1977 NA
 2     04-17-2005 NA
 2     NA         M
 3     NA         NA
 3     06-04-1999 NA
 3     NA         F')
</code>```

ContentLicense: CC BY-SA 4.0

Title: r data formatting with NAs

Body:
If I have a dataset with three columns like this below

 Id    Date       Gender
 1     NA         F
 1     NA         NA
 1     03-11-1977 NA
 2     04-17-2005 NA
 2     NA         M
 3     NA         NA
 3     06-04-1999 NA
 3     NA         F

How could I clean this data such that I see a dataset like this below ?

Id    Date        Gender
 1     03-11-1977 F
 2     04-17-2005 M
 3     06-04-1999 F

Thanks.

Body:
You may use na.omit in a by approach.

dat <- do.call(rbind, by(dat, dat$Id, function(x) cbind(x[1,1,drop=F], lapply(x[-1], na.omit))))
dat
#   Id       Date Gender
# 1  1 03-11-1977      F
# 2  2 04-17-2005      M
# 3  3 06-04-1999      F

Data:

dat <- read.table(header=T,text=' Id    Date       Gender
 1     NA         F
 1     NA         NA
 1     03-11-1977 NA
 2     04-17-2005 NA
 2     NA         M
 3     NA         NA
 3     06-04-1999 NA
 3     NA         F')


问:
Can I set up PYTHONPATH for Lambda Function of Cloud9?
I created 2 Lambda Functions from AWS Resources menu in Cloud9.

I wanna have common modules for these Functions.

I made New Folder for the common modules and add the path ~/environment/python/lib to PYTHONPATH of Preferences -> Python Support.

I did Run main function with Lambda(local).

But I got Unable to import module 'main/lambda_function': No module named 'common'.

Can I set up PYTHONPATH for Lambda Function in Cloud9?

Or is there a　better practice for having common modules for several Lambda Functions?

My folder tree:

```<code>root
|-python
  |-lib     <- for uploading to Lambda Layers
    common.py
|-app
  |-main
    |-lambda_function.py
  |-main2
    |-lambda_function.py
</code>```

my lambda_function.py:

```<code>import common
</code>```

答:
Just output the PYTHONPATH in your python file before you do anything else:

```<code>import os
print(os.environ['PYTHONPATH'])

import ...

def lambda_handler(event,context):
  ...
</code>```

You will see as part of the Function Logs that it outputs the environment variable as /var/runtime. Even if you set that path through the Cloud9 settings, you will discover just as I did that those settings do not hold.

I was hoping to setup all my layers under ~/environment/layers/layername, so I would have for example all my libraries and dependencies for scikit-learn under: ~/environment/layers/scikit-learn/python/... and I would use that same scikit-learn directory to actually create my layer with for deployment remotely.

But that did not work.

Body:
I created 2 Lambda Functions from AWS Resources menu in Cloud9.

I wanna have common modules for these Functions.

I made New Folder for the common modules and add the path ~/environment/python/lib to PYTHONPATH of Preferences -> Python Support.

I did Run main function with Lambda(local).

But I got Unable to import module 'main/lambda_function': No module named 'common'.

Can I set up PYTHONPATH for Lambda Function in Cloud9?

Or is there a　better practice for having common modules for several Lambda Functions?

My folder tree:

root
|-python
  |-lib     <- for uploading to Lambda Layers
    common.py
|-app
  |-main
    |-lambda_function.py
  |-main2
    |-lambda_function.py

my lambda_function.py:

import common

Body:
Just output the PYTHONPATH in your python file before you do anything else:

import os
print(os.environ['PYTHONPATH'])

import ...

def lambda_handler(event,context):
  ...

You will see as part of the Function Logs that it outputs the environment variable as /var/runtime. Even if you set that path through the Cloud9 settings, you will discover just as I did that those settings do not hold.

I was hoping to setup all my layers under ~/environment/layers/layername, so I would have for example all my libraries and dependencies for scikit-learn under: ~/environment/layers/scikit-learn/python/... and I would use that same scikit-learn directory to actually create my layer with for deployment remotely.

But that did not work.


问:
Removing all lines after blank line with sed and awk
I want to remove everything after a blank line INCLUDING the blank line. Is there a sed or awk command to do this?

I have a file that looks like:

```<code>text
text
moretext
evenmore text

sometexthere
text
</code>```

I want to remove everything after the first blank line. I want my output to be:

```<code>text
text
moretext
evenmore text
</code>```

I'm not sure how to do this though.

答:
You can do this fairly easily with awk</p>

```<code>awk '/^$/{exit}1' ./input/file
</code>```

Body:
I want to remove everything after a blank line INCLUDING the blank line. Is there a sed or awk command to do this?

I have a file that looks like:

text
text
moretext
evenmore text

sometexthere
text

I want to remove everything after the first blank line. I want my output to be:

text
text
moretext
evenmore text

I'm not sure how to do this though.

Body:
You can do this fairly easily with awk

awk '/^$/{exit}1' ./input/file


问:
Ballerina json datetime value
i have to index documents to elasticsearch to an index which has a date field mapping and i'm trying to build a json with this date value, but ballerina says this seems not possible.

I thought about storing this date value into an xml and after that to convert it to a json but xml has the same problem (i thought this might be a trick...).

I tried to store it into a string and after that to extract the json payload from that string but it gives me this error:

error: {ballerina/io}GenericError message=unrecognized token 'date=time=1591128342000'

I thought about dealing with this string to date conversion from inside elasticsearch but i would like to keep this scenario as the last one. I don't like it, beacause i have to do some queries based on timestamp after and storing date as a string would give me additional problems

So is there any way to trick ballerina in order to achive this json containing a date value ?

-----here is snapshot of the code giving me the error-----
It says:

incompatible types: expected 'json', found 'ballerina/time:Time'

答:
JSON is a text format that is completely language independent (see e.g. json.org).
time:Time is a Ballerina language specific type JSON knows nothing about. Because there is no implicit conversion (for a good reason) one have to provide the conversion.

In this case you most likely want to convert time:Time to a ISO 8601 string presentation with time:toString.

The following code (Ballerina 1.2):

```<code>import ballerina/io;
import ballerina/time;
public function main() {
    var btime = time:currentTime();
    var j = <json> {
        time: time:toString(btime)
    };

    io:println(j.toJsonString());
}
</code>```

Correctly prints:

```<code>{"time":"2020-06-03T08:39:07.897+03:00"}
</code>```

Maryam Ziyad has written a good introduction to Ballerina's JSON support.

Title: Ballerina json datetime value

Body:
JSON is a text format that is completely language independent (see e.g. json.org).
time:Time is a Ballerina language specific type JSON knows nothing about. Because there is no implicit conversion (for a good reason) one have to provide the conversion.

In this case you most likely want to convert time:Time to a ISO 8601 string presentation with time:toString.

The following code (Ballerina 1.2):

import ballerina/io;
import ballerina/time;
public function main() {
    var btime = time:currentTime();
    var j = <json> {
        time: time:toString(btime)
    };

    io:println(j.toJsonString());
}

Correctly prints:

{"time":"2020-06-03T08:39:07.897+03:00"}

Maryam Ziyad has written a good introduction to Ballerina's JSON support.


问:
How can I strip tab characters from a string in Ruby?
I have a program that loads some tab-separated lines into a MySQL table. One of the values has tabs in it, which is causing some problems. The data is created column by column, so I need to find a way to strip the tab character out of an individual field with gsub. I do not, however, want to get rid of anything else, like spaces.</p>

答: \t is the escape character for tabs within strings. So you can just search for "\t" and replace that by a space or something.

ContentLicense: CC BY-SA 3.0


问:
LinkedIn Video Analytics API - timeRange invalid
Using the linkedIn Video Analytics API, I want to gather analytics about my video post per day.

My request:

```<code>https://api.linkedin.com/v2/videoAnalytics?q=entity&entity=urn:li:ugcPost:6662300354706755584&type=VIEWER&timeRange=(start:1588416100,end:1590624000)&aggregation=DAY
</code>```

However, I keep receiving the following error:

```<code>{"message":"Parameter 'timeRange' is invalid","status":400}
</code>```

I tried changing the timeRange from miliseconds to epoch time, but that did not make a difference. Please, can anyone help to solve this issue here?

Thanks in advance.

答:
it depends on the version of Restli-Protocol-Version" you are using

if you are using Restli 1.0. then your request should look like this

```<code>&timeIntervals.timeGranularityType=DAY&timeIntervals.timeRange.start=1551398400000&timeIntervals.timeRange.end=1552003200000
</code>```

if you are using Restli 2.0 then your request should look like this

```<code>&timeIntervals=(timeRange:(start:1551398400000,end:1552003200000),timeGranularityType:DAY)
</code>```

Body:
Using the linkedIn Video Analytics API, I want to gather analytics about my video post per day.

My request:

https://api.linkedin.com/v2/videoAnalytics?q=entity&entity=urn:li:ugcPost:6662300354706755584&type=VIEWER&timeRange=(start:1588416100,end:1590624000)&aggregation=DAY

However, I keep receiving the following error:

{"message":"Parameter 'timeRange' is invalid","status":400}

I tried changing the timeRange from miliseconds to epoch time, but that did not make a difference. Please, can anyone help to solve this issue here?

Thanks in advance.

Body:
it depends on the version of Restli-Protocol-Version" you are using

if you are using Restli 1.0. then your request should look like this

&timeIntervals.timeGranularityType=DAY&timeIntervals.timeRange.start=1551398400000&timeIntervals.timeRange.end=1552003200000

if you are using Restli 2.0 then your request should look like this

&timeIntervals=(timeRange:(start:1551398400000,end:1552003200000),timeGranularityType:DAY)


问:
Binary operator '<' cannot be applied to two 'Int?' operands
Good evening lovely community,

this is my first post, please have mercy, if I do something wrong.

I know there are some similar questions here, but I doesn't understand it.

Maybe I understand, if someone explain it on my code.

// these are my two TextFields and the "finish"-Button.

```<code>@IBOutlet weak var goalPlayerOne: UITextField!
@IBOutlet weak var goalPlayerTwo: UITextField!
@IBOutlet weak var finishedGameButton: UIButton!
</code>```

// here are my function, it should tell me, which Player has won like A < B, so B has won.

```<code> @IBAction func finishedGameButtonPressed(_ sender: Any) {
    // define UITextField as Integer

let goalPlayerOne = "";
let goalOne = Int(goalPlayerOne);

let goalPlayerTwo = "";
let goalTwo = Int(goalPlayerTwo);
</code>```

// here is the problem:
"Binary operator '<' cannot be applied to two 'Int?' operands"

// if I make a '==' it works

```<code>if goalOne < goalTwo{
    displayMyAlertMessage(userMessage: "Player Two wins")
    return
}
</code>```

答:
Well, by using guard statement you can check if both values are not nil, and converting it to Int typ

```<code>    guard let value_one = Int(goalPlayerOne), let value_two = Int(goalPlayerTwo) else {
        print("Some value is nil")
        return
    }
</code>```

so you can safely compare two values.

```<code>    if value_one < value_two {
       //Do something
    }
</code>```

Body:
Good evening lovely community,

this is my first post, please have mercy, if I do something wrong.

I know there are some similar questions here, but I doesn't understand it.

Maybe I understand, if someone explain it on my code.

// these are my two TextFields and the "finish"-Button.

@IBOutlet weak var goalPlayerOne: UITextField!
@IBOutlet weak var goalPlayerTwo: UITextField!
@IBOutlet weak var finishedGameButton: UIButton!

// here are my function, it should tell me, which Player has won like A < B, so B has won.

 @IBAction func finishedGameButtonPressed(_ sender: Any) {
    // define UITextField as Integer

let goalPlayerOne = "";
let goalOne = Int(goalPlayerOne);

let goalPlayerTwo = "";
let goalTwo = Int(goalPlayerTwo);

// here is the problem:
"Binary operator '<' cannot be applied to two 'Int?' operands"

// if I make a '==' it works

if goalOne < goalTwo{
    displayMyAlertMessage(userMessage: "Player Two wins")
    return
}

Body:
Well, by using guard statement you can check if both values are not nil, and converting it to Int typ

    guard let value_one = Int(goalPlayerOne), let value_two = Int(goalPlayerTwo) else {
        print("Some value is nil")
        return
    }

so you can safely compare two values.

    if value_one < value_two {
       //Do something
    }


问:
UWP display name depending on environment
We have a UWP Application distributed to the Microsoft Windows Store.
For testing use, we also have a test and acceptance version in de appcenter.
When a user wants to have a, for ex, a acception version and released version side by side, it is not possible.
When installing the appxbundle file it says the app is already installed (probably because it has the same name).
Is it possible to have multiple display names depending on the environment, for ex, when you have app "MyApp", you can also have a "MyApp -Test"  and "MyApp - Acc" app.

thx

答: For your requirement, you could change the package name to make a project copy. Double-click the appx.manifest file => Click Packaging Tab => Modify the package name to a different one. Then run your project and it won't conflict with others.</p>


问:
Use pytest.lazy_fixture list values as parameters in another fixture
Im trying to use list of one fixture values as parameters into another. Here is my setup:

```<code>import pytest

d = {
    "first": [1, 2, 3],
    "second": [4, 5, 6]
}

@pytest.fixture(params=['first', 'second'])
def foo(request):
    return d.get(request.param)

@pytest.fixture(params=[pytest.lazy_fixture('foo')])
def bar(request):
    return request.param

def test_1(bar):
    pass
</code>```

The problem is bar() always get full list as request.param ([1, 2, 3] not values of the list. If in params of bar() fixture send data directly, e.g:

```<code>@pytest.fixture(params=[1, 2, 3])
def bar(request):
    return request.param

def test_1(bar):
    pass
</code>```

Then argument request will work properly (test starts three times). The same situation, if I pass arguments to params not directly, but from any method without fixture decorator, i.e:

```<code>def some():
    return [1, 2, 3]

@pytest.fixture(params=some())
def more(request):
    return request.param

def test_2(more):
    logging.error(more)
    pass
</code>```

So, my question is it possible to obtain data from list one by one and then use it in my test? I've try to 'unparse' list:

```<code>@pytest.fixture(params=[i for i in i pytest.lazy_fixture('foo')])
def bar(request):
    return request.param
</code>```

But in this case I get TypeError: 'LazyFixture' object is not iterable

答:
See this answer to a very similar question: by design, fixture values can not be used as lists of parameters to parametrize tests. Indeed parameters are resolved at pytest collection phase, while, fixtures are resolved later, during pytest nodes execution.

The best that you can do with lazy_fixture or with pytest_cases.fixture_ref is to use a single fixture value as a parameter. With lazy_fixture you have limitations (if I remember correctly, the fixture cannot be parametrized) while with pytest_cases you can do pretty much anything (using the fixture_ref in a parameter tuple, using several fixture_refs each with different parametrization, etc.). I'm the author of pytest_cases by the way ;)

See also this thread.

Body:
Im trying to use list of one fixture values as parameters into another. Here is my setup:

import pytest

d = {
    "first": [1, 2, 3],
    "second": [4, 5, 6]
}

@pytest.fixture(params=['first', 'second'])
def foo(request):
    return d.get(request.param)

@pytest.fixture(params=[pytest.lazy_fixture('foo')])
def bar(request):
    return request.param

def test_1(bar):
    pass

The problem is bar() always get full list as request.param ([1, 2, 3] not values of the list. If in params of bar() fixture send data directly, e.g:

@pytest.fixture(params=[1, 2, 3])
def bar(request):
    return request.param

def test_1(bar):
    pass

Then argument request will work properly (test starts three times). The same situation, if I pass arguments to params not directly, but from any method without fixture decorator, i.e:

def some():
    return [1, 2, 3]

@pytest.fixture(params=some())
def more(request):
    return request.param

def test_2(more):
    logging.error(more)
    pass

So, my question is it possible to obtain data from list one by one and then use it in my test? I've try to 'unparse' list:

@pytest.fixture(params=[i for i in i pytest.lazy_fixture('foo')])
def bar(request):
    return request.param

But in this case I get TypeError: 'LazyFixture' object is not iterable


问:
How to use Bootsrap4 for particular tag only
Hello Peeps

Thanks a lot for taking your time in reading this. I am new in Wordpress. I want to update my footer.

I wrote an HTML code for my footer which I was going to use on Customisation>Layout>Footer.
But I am unable to link bootstrap 4 with that as the code window automatically removes the linked bootsrap line,

So I tried to add a footer widget but it is affecting my whole page. I want to use bootstrap 4 to make my footer responsive.
I don't know how to use media libraries. I managed to make my footer responsive with grid system (col-sm-12 , col-lg-4) but whenever I import my bootstrap 4 link.

Can you please help me on how should I make my footer responsive?

If you want to check it live
You can see footer of this page : https://techdevio.com/about/
Do not check footer of homepage as it is made by thrive architect and I was just trying to replicate it by writing code.
If you have any suggestions on how to make that code responsive without using bootstrap I would appreciate that too. :)

Thanks In Advance

.bg {
  background-color: rgb(49, 65, 140);
  color: white;
}

a {
  color: white;
  text-decoration: none;
}

.container {
  text-align: center;
}

#social {
  margin: 60px 0px auto;
  overflow: hidden;
  text-align: center;
}

@media screen and (max-width: 768px) {
  #social {
    margin: 26px auto;
  }
}

#social ul {
  margin: 0px auto;
  list-style-type: none;
  padding: 0px;
}

#social ul.social,
#social ul.contact {
  display: inline-block;
}

#social li {
  margin: 0 17px 0 0;
  float: left;
  color: black;
}

@media only screen and (max-width: 495px) {
  #social li {
    margin: 0 0 10px 0;
    float: none;
    clear: both;
  }
}

#social li a {
  color: black;
}

#social ul.social,
#social ul.contact {
  display: inline-block;
}

.category {
  font-weight: bold;
  font-family: Literata !important;
  font-size: 19px !important;
  --g-regular-weight: 400;
  --g-bold-weight: 700;
}

.cat-2 {
  font-size: 18px;
  font-family: Muli;
  font-weight: 300 !important;
}

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

</head>

<body>

  <footer class="bg">
    <div class="container pt-3">

      <div class="row">

        <div class="col-xs-12 col-sm-12 col-md-12 col-lg-4">
          Tech Dev I/O
          <p>Tech Dev I/O Keeps You Updated With Latest Tech News & Gadgets. We Also provide Reviews Of Trending Gadgets </div>

        <div class="col-xs-12 col-sm-12 col-md-12 col-lg-4">
          <p class="category">Information</p>

          <p>➤ Contact us</p>

          <p>➤ About us</li>

            <p>➤ Privacy policy</p>

        </div>

        <div class="col-xs-12 col-sm-12 col-md-12 col-lg-4">
          <p class="category">Contact Us</p>

          <p> <i class="fa fa-phone" aria-hidden="true"></i> +91 89998 17454</p>
          <p><i class="fa fa-map-marker" aria-hidden="true"></i>
                             123, Society, Pune, MH 440013</li>
          </p>

          <p>
             <i class="fa fa-envelope" aria-hidden="true"></i>  techdevio20@gmail.com
          </p>

          </ul>
        </div>

      </div>

    </div>
    <div id="social">
      <ul class="social">
        <li>Facebook</li>
        <li>Twitter</li>
        <li>Instagram</li>
        <li class="last">Pintrest</li>
      </ul>
    </div>
    <div id="social" style="margin-top: 0px;">
      <p>©2020 Tech Dev I/O</p>
    </div>

  </footer>

</body>

</html></code>```

答:
You cannot apply stylesheets for specific HTML tags. You can scope them, for example - make all rules in the stylesheet related to the given tag/selector:

```<code>footer.bg {
 /* Some footer styles */
}
footer.bg .category{
 /* Some footer category styles */
}
</code>```

but these styles are applied globally. Whenever the rule is matched, its styles are applied accordingly.

In your case, from what I understand, you need the Bootstrap grid tools like col, row, etc., but the import of the whole Bootstrap CSS overrides and breaks the styles you already have on that page.

There is an official Bootstrap grid CSS, which will provide only those responsive grid utilities. Keep in mind that it also comes with some display and flexbox utilities as well, which may potentially clash with some of your styles if you happen to use the same classes.

Here's the link: https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap-grid.min.css

Body:
Hello Peeps

Thanks a lot for taking your time in reading this. I am new in Wordpress. I want to update my footer.

I wrote an HTML code for my footer which I was going to use on Customisation>Layout>Footer.
But I am unable to link bootstrap 4 with that as the code window automatically removes the linked bootsrap line,

So I tried to add a footer widget but it is affecting my whole page. I want to use bootstrap 4 to make my footer responsive.
I don't know how to use media libraries. I managed to make my footer responsive with grid system (col-sm-12 , col-lg-4) but whenever I import my bootstrap 4 link.

Can you please help me on how should I make my footer responsive?

If you want to check it live
You can see footer of this page : https://techdevio.com/about/
Do not check footer of homepage as it is made by thrive architect and I was just trying to replicate it by writing code.
If you have any suggestions on how to make that code responsive without using bootstrap I would appreciate that too. :)

Thanks In Advance

.bg {
  background-color: rgb(49, 65, 140);
  color: white;
}

a {
  color: white;
  text-decoration: none;
}

.container {
  text-align: center;
}

#social {
  margin: 60px 0px auto;
  overflow: hidden;
  text-align: center;
}

@media screen and (max-width: 768px) {
  #social {
    margin: 26px auto;
  }
}

#social ul {
  margin: 0px auto;
  list-style-type: none;
  padding: 0px;
}

#social ul.social,
#social ul.contact {
  display: inline-block;
}

#social li {
  margin: 0 17px 0 0;
  float: left;
  color: black;
}

@media only screen and (max-width: 495px) {
  #social li {
    margin: 0 0 10px 0;
    float: none;
    clear: both;
  }
}

#social li a {
  color: black;
}

#social ul.social,
#social ul.contact {
  display: inline-block;
}

.category {
  font-weight: bold;
  font-family: Literata !important;
  font-size: 19px !important;
  --g-regular-weight: 400;
  --g-bold-weight: 700;
}

.cat-2 {
  font-size: 18px;
  font-family: Muli;
  font-weight: 300 !important;
}

}

<!DOCTYPE html>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

          Tech Dev I/O

Tech Dev I/O Keeps You Updated With Latest Tech News & Gadgets. We Also provide Reviews Of Trending Gadgets

Information

➤ Contact us

➤ About us

➤ Privacy policy

Contact Us

  +91 89998 17454

                             123, Society, Pune, MH 440013

               techdevio20@gmail.com

Facebook

Twitter

Instagram

Pintrest

©2020 Tech Dev I/O

Body:
You cannot apply stylesheets for specific HTML tags. You can scope them, for example - make all rules in the stylesheet related to the given tag/selector:

footer.bg {
 /* Some footer styles */
}
footer.bg .category{
 /* Some footer category styles */
}

but these styles are applied globally. Whenever the rule is matched, its styles are applied accordingly.

In your case, from what I understand, you need the Bootstrap grid tools like col, row, etc., but the import of the whole Bootstrap CSS overrides and breaks the styles you already have on that page.

There is an official Bootstrap grid CSS, which will provide only those responsive grid utilities. Keep in mind that it also comes with some display and flexbox utilities as well, which may potentially clash with some of your styles if you happen to use the same classes.

Here's the link: https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap-grid.min.css


问:
javascript - Create Simple Dynamic Array
What's the most efficient way to create this simple array dynamically.

```<code>var arr = [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
</code>```

Let's say we can get the number 10 from a variable

```<code>var mynumber = 10;
</code>```

答:
updated = > june 2020

if are you using node js you can create or append a string value with " ," operator then  inside the loop you can

```<code>for (var j = 0; j <= data.legth -1; j++) {
                    lang += data.lang  +", " ;

                }

 var langs = lang.split(',')
 console.log("Languages =>",  lang, typeof(lang), typeof(langs), langs)
 console.log(lang[0]) // here access arrary by index value

</code>```

you can see the type of  string and object

Body:
What's the most efficient way to create this simple array dynamically.

var arr = [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];

Let's say we can get the number 10 from a variable

var mynumber = 10;

Body:
updated = > june 2020

if are you using node js you can create or append a string value with " ," operator then  inside the loop you can

for (var j = 0; j <= data.legth -1; j++) {
                    lang += data.lang  +", " ;

                }

 var langs = lang.split(',')
 console.log("Languages =>",  lang, typeof(lang), typeof(langs), langs)
 console.log(lang[0]) // here access arrary by index value

you can see the type of  string and object


问:
Using Intent.createChooser and getting error: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag
I want to open the share via option from the service class.
It is working fine in Android 7, but in 8+ OS it starts showing

android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

I have also included this flag to my Intent, but it's still showing the same error.

Is there any other way to open share via option from the service class?

```<code>                    Intent i = new Intent(Intent.ACTION_SEND);
                    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    i.putExtra(Intent.EXTRA_STREAM, rasta);  //rasta -> Uri obj
                    i.setType("image/*");
                    getApplicationContext().startService(Intent.createChooser(i,"Share karna..."));

</code>```

答:
Intent.createChooser creates an Intent, so you need to set the FLAG_ACTIVITY_NEW_TASK flag on that intent, e.g.,

```<code>                    Intent i = new Intent(Intent.ACTION_SEND);
                    i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    i.putExtra(Intent.EXTRA_STREAM, rasta);  //rasta -> Uri obj
                    i.setType("image/*");
                    Intent chooserIntent = Intent.createChooser(i,"Share karna...");
                    chooserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    getApplicationContext().startActivity(chooserIntent);

</code>```

You were also calling startService instead of startActivity - make sure to correct that as well.

Body:
I want to open the share via option from the service class.
It is working fine in Android 7, but in 8+ OS it starts showing

android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

I have also included this flag to my Intent, but it's still showing the same error.

Is there any other way to open share via option from the service class?

                    Intent i = new Intent(Intent.ACTION_SEND);
                    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    i.putExtra(Intent.EXTRA_STREAM, rasta);  //rasta -> Uri obj
                    i.setType("image/*");
                    getApplicationContext().startService(Intent.createChooser(i,"Share karna..."));

Body:
Intent.createChooser creates an Intent, so you need to set the FLAG_ACTIVITY_NEW_TASK flag on that intent, e.g.,

                    Intent i = new Intent(Intent.ACTION_SEND);
                    i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    i.putExtra(Intent.EXTRA_STREAM, rasta);  //rasta -> Uri obj
                    i.setType("image/*");
                    Intent chooserIntent = Intent.createChooser(i,"Share karna...");
                    chooserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    getApplicationContext().startActivity(chooserIntent);

You were also calling startService instead of startActivity - make sure to correct that as well.


问:
Git SSH in RStudio works using the GUI button, but not using shell
I have an RStudio project connected to a GitHub repository. I'm using SSH authentication and I can commit, push/pull using RStudio's GUI with no problem. However, when I try pushing using the shell by e.g. git push or git push -u origin master I get an error

```<code>Could not create directory 'c/Users/<user>/<path>/<reponame>/=/.ssh'
</code>```

I have checked many related questions, but none of them seems to solve this issue. How come the gui push button achieves the desired result, while the above code fails? If I change authentication to https, I can push/pull using the shell, so it is clear that it has something to do with ssh.

I'm on Win10, using RStudio 1.1.383  and Git 2.8.3.windows.1.

Any ideas?

答:
Check your git config -l for any SSH related setting.

Check also your environment variable (type 'set' in a CMD, or env in a git bash). I would double-check the value of %HOME% or $HOME in your bash session.

I suspect a variable or configuration with an incorrect value, including an '=' in it.

As seen in the comments:

set HOME=%USERPROFILE% changed the HOME path.

Body:
I have an RStudio project connected to a GitHub repository. I'm using SSH authentication and I can commit, push/pull using RStudio's GUI with no problem. However, when I try pushing using the shell by e.g. git push or git push -u origin master I get an error

Could not create directory 'c/Users/<user>/<path>/<reponame>/=/.ssh'

I have checked many related questions, but none of them seems to solve this issue. How come the gui push button achieves the desired result, while the above code fails? If I change authentication to https, I can push/pull using the shell, so it is clear that it has something to do with ssh.

I'm on Win10, using RStudio 1.1.383  and Git 2.8.3.windows.1.

Any ideas?


问:
WinAPI mouse move notification for full desktop
In WinAPI is there a mouse move notification for the full desktop (full screen) and not for a window only?

I would like to receive mouse screen coordinates in my main window procedure.

Edit:

What I try to do is getting the coordinates from the mouse when dragging from a button in my window to outside that window.

答: You can use GetCursorPos, or GetMessagePos that contains coordinate of the last message</p>


问:
What type is the input data in SPOJ for python? and how can I implement it in Jupyter notebook?
I'm new to programming and I've been trying to do problems in SPOJ.
I first solve them in a jupyter notebook to test them, and then copy the code.
This has costs me a lot of tries with errors.
I think SPOJ inputs are in stdin form, which I think I know how to "read".
However, if I want to try other inputs to test my code, what type of input should I use? lists?

Or how could I implement this stdin in jupyter?

Or how do you recommend I write my code tests before submitting?

Thanks!

答:
It depends on the specific problem. If you use python input() or raw_input(), you'll get the inputs as a string.

You need to typecast to the proper data type (int, float, str, etc.)

You should be able to test your code with the same input format as the problem statement.

For example:

this is the solution for problem HYPNOS:

https://www.spoj.com/problems/HPYNOS/

```<code>n=raw_input()
count=0
while True:
    sq=0
    for i in n:
    sq+=int(i)**2
    count+=1
    n=str(sq)

    if len(n)==1:
        if int(n)==1:
            print count
            break
    else:
       print "-1"
       break

</code>```

Here, to test on custom inputs, you have to repeatedly input multiple integers as input in the terminal/jupyter notebook.

If you want to parse a list of test cases at a time.

Write a solution() function, which takes an input and returns the answer.

Keep a mode varuable, if mode == "test", then pass a test set list, else just do the regular inputs and print solution.

Body:
It depends on the specific problem. If you use python input() or raw_input(), you'll get the inputs as a string.

You need to typecast to the proper data type (int, float, str, etc.)

You should be able to test your code with the same input format as the problem statement.

For example:

this is the solution for problem HYPNOS:

https://www.spoj.com/problems/HPYNOS/

n=raw_input()
count=0
while True:
    sq=0
    for i in n:
    sq+=int(i)**2
    count+=1
    n=str(sq)

    if len(n)==1:
        if int(n)==1:
            print count
            break
    else:
       print "-1"
       break

Here, to test on custom inputs, you have to repeatedly input multiple integers as input in the terminal/jupyter notebook.

If you want to parse a list of test cases at a time.

Write a solution() function, which takes an input and returns the answer.

Keep a mode varuable, if mode == "test", then pass a test set list, else just do the regular inputs and print solution.


问:
change button text winapi
I'm new to WINAPI programming. I want to make a simple tic-tac-toe game on windows forms, but i have a problem when i want to change button text. My code compiles, but that SendMessage function just don't work. My code :

```<code>#include <windows.h>
#include <windowsx.h>
#include <stdio.h>
#include <tchar.h>
#include <iostream>

#define __T(x) L ## x

#define BUTTON_1x1 1
#define BUTTON_1x2 2
#define BUTTON_1x3 3

#define BUTTON_2x1 4
#define BUTTON_2x2 5
#define BUTTON_2x3 6

#define BUTTON_3x1 7
#define BUTTON_3x2 8
#define BUTTON_3x3 9

HWND hWnd;
HWND _3x3;
HWND _3x2;
HWND _3x1;
HWND _2x3;
HWND _2x2;
HWND _2x1;
HWND _1x3;
HWND _1x2;
HWND _1x1;

LRESULT CALLBACK WindowProc(HWND hWnd,
                     UINT message,
                     WPARAM wParam,
                     LPARAM lParam);

int WINAPI WinMain(HINSTANCE hInstance,
               HINSTANCE hPrevInstance,
               LPSTR lpCmdLine,
               int nCmdShow)
{
HWND hWnd;
WNDCLASSEX wc;
ZeroMemory(&wc, sizeof(WNDCLASSEX));

wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
wc.lpszClassName = "WindowClass1";

RegisterClassEx(&wc);
hWnd = CreateWindowExW(NULL,
                      L"WindowClass1",    // name of the window class
                      L"Desas",   // title of the window
                      WS_OVERLAPPEDWINDOW,    // window style
                      300,    // x-position of the window
                      300,    // y-position of the window
                      380,    // width of the window
                      480,    // height of the window
                      NULL,    // we have no parent window, NULL
                      NULL,    // we aren't using menus, NULL
                      hInstance,    // application handle
                      NULL);    // used with multiple windows, NULL
ShowWindow(hWnd, nCmdShow);
MSG msg;

while(GetMessage(&msg, NULL, 0, 0))
{
    TranslateMessage(&msg);
    DispatchMessage(&msg);
}
return msg.wParam;
}

LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch(message)
{
    case WM_CREATE:
        {
            HWND _1x1 = CreateWindowEx(WS_EX_CLIENTEDGE,
                                        "BUTTON",
                                        "21",
                                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_TEXT,
                                        30, 100, 100, 100,
                                        hWnd,
                                        (HMENU) BUTTON_1x1,
                                        NULL,
                                        NULL);

            HWND _1x2 = CreateWindowEx(WS_EX_CLIENTEDGE,
                                        "BUTTON",
                                        "32",
                                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_TEXT,
                                        130, 100, 100, 100,
                                        hWnd,
                                        (HMENU) BUTTON_1x2,
                                        NULL,
                                        NULL);
            HWND _1x3 = CreateWindowEx(WS_EX_CLIENTEDGE,
                                        "BUTTON",
                                        "12",
                                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_TEXT,
                                        230, 100, 100, 100,
                                        hWnd,
                                        (HMENU) BUTTON_1x3,
                                        NULL,
                                        NULL);

            HWND _2x1 = CreateWindowEx(WS_EX_CLIENTEDGE,
                                        "BUTTON",
                                        "32",
                                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_TEXT,
                                        30, 200, 100, 100,
                                        hWnd,
                                        (HMENU) BUTTON_2x1,
                                        NULL,
                                        NULL);
            HWND _2x2 = CreateWindowEx(WS_EX_CLIENTEDGE,
                                        "BUTTON",
                                        "12",
                                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_TEXT,
                                        130, 200, 100, 100,
                                        hWnd,
                                        (HMENU) BUTTON_2x2,
                                        NULL,
                                        NULL);

            HWND _2x3 = CreateWindowEx(WS_EX_CLIENTEDGE,
                                        "BUTTON",
                                        "23",
                                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_TEXT,
                                        230, 200, 100, 100,
                                        hWnd,
                                        (HMENU) BUTTON_2x3,
                                        NULL,
                                        NULL);

            HWND _3x1 = CreateWindowEx(WS_EX_CLIENTEDGE,
                                        "BUTTON",
                                        "12",
                                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_TEXT,
                                        30, 300, 100, 100,
                                        hWnd,
                                        (HMENU) BUTTON_3x1,
                                        NULL,
                                        NULL);

            HWND _3x2 = CreateWindowEx(WS_EX_CLIENTEDGE,
                                        "BUTTON",
                                        "33",
                                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_TEXT,
                                        130, 300, 100, 100,
                                        hWnd,
                                        (HMENU) BUTTON_3x2,
                                        NULL,
                                        NULL);

            HWND _3x3 = CreateWindowEx(WS_EX_CLIENTEDGE,
                                        "BUTTON",
                                        "12",
                                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_TEXT,
                                        230, 300, 100, 100,
                                        hWnd,
                                        (HMENU) BUTTON_3x3,
                                        NULL,
                                        NULL);

            HWND _PLAYER_TXT = CreateWindowEx(NULL,
                                        "STATIC",
                                        "PLAYER :",
                                        WS_VISIBLE | WS_CHILD | SS_LEFT,
                                        230, 50, 100, 30,
                                        hWnd,
                                        (HMENU) 999,
                                        NULL,
                                        NULL);
        } break;

        case WM_COMMAND:
        {
                if (LOWORD(wParam) == BUTTON_3x3)
            {
                std::cout << "!!!!!" << std::endl; //test(if buttonclick message is  recived)

                SendMessage(_3x3, WM_SETTEXT, 0, (LPARAM) _T("NewText")); //not working
            }
        } break;

    case WM_DESTROY:
        {
            PostQuitMessage(0);
            return 0;
        } break;
}
return DefWindowProc (hWnd, message, wParam, lParam);
}
</code>```

Sorry for this bunch of code. I would make it shorter, if I knew which part is important. Sorry for my bad english. Thank you.

答:
try this:</p>

```<code>case WM_COMMAND:
{
   if(LOWORD(wParam) == BUTTON_3x3)
   {
         _3x3 = NULL;
         _3x3 = CreateWindowEx(0,
                                         WC_BUTTON,
                                        "Text",230, 300, 100, 100,
                                         hwnd,
                                        (HMENU)BUTTON_3x3,
                                         NULL, NULL);
   }
}
      break;
</code>```

Title: change button text winapi

Body:
I'm new to WINAPI programming. I want to make a simple tic-tac-toe game on windows forms, but i have a problem when i want to change button text. My code compiles, but that SendMessage function just don't work. My code :

#include <windows.h>
#include <windowsx.h>
#include <stdio.h>
#include <tchar.h>
#include <iostream>

#define __T(x) L ## x

#define BUTTON_1x1 1
#define BUTTON_1x2 2
#define BUTTON_1x3 3

#define BUTTON_2x1 4
#define BUTTON_2x2 5
#define BUTTON_2x3 6

#define BUTTON_3x1 7
#define BUTTON_3x2 8
#define BUTTON_3x3 9

HWND hWnd;
HWND _3x3;
HWND _3x2;
HWND _3x1;
HWND _2x3;
HWND _2x2;
HWND _2x1;
HWND _1x3;
HWND _1x2;
HWND _1x1;

LRESULT CALLBACK WindowProc(HWND hWnd,
                     UINT message,
                     WPARAM wParam,
                     LPARAM lParam);

int WINAPI WinMain(HINSTANCE hInstance,
               HINSTANCE hPrevInstance,
               LPSTR lpCmdLine,
               int nCmdShow)
{
HWND hWnd;
WNDCLASSEX wc;
ZeroMemory(&wc, sizeof(WNDCLASSEX));

wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
wc.lpszClassName = "WindowClass1";

RegisterClassEx(&wc);
hWnd = CreateWindowExW(NULL,
                      L"WindowClass1",    // name of the window class
                      L"Desas",   // title of the window
                      WS_OVERLAPPEDWINDOW,    // window style
                      300,    // x-position of the window
                      300,    // y-position of the window
                      380,    // width of the window
                      480,    // height of the window
                      NULL,    // we have no parent window, NULL
                      NULL,    // we aren't using menus, NULL
                      hInstance,    // application handle
                      NULL);    // used with multiple windows, NULL
ShowWindow(hWnd, nCmdShow);
MSG msg;

while(GetMessage(&msg, NULL, 0, 0))
{
    TranslateMessage(&msg);
    DispatchMessage(&msg);
}
return msg.wParam;
}

LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch(message)
{
    case WM_CREATE:
        {
            HWND _1x1 = CreateWindowEx(WS_EX_CLIENTEDGE,
                                        "BUTTON",
                                        "21",
                                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_TEXT,
                                        30, 100, 100, 100,
                                        hWnd,
                                        (HMENU) BUTTON_1x1,
                                        NULL,
                                        NULL);

            HWND _1x2 = CreateWindowEx(WS_EX_CLIENTEDGE,
                                        "BUTTON",
                                        "32",
                                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_TEXT,
                                        130, 100, 100, 100,
                                        hWnd,
                                        (HMENU) BUTTON_1x2,
                                        NULL,
                                        NULL);
            HWND _1x3 = CreateWindowEx(WS_EX_CLIENTEDGE,
                                        "BUTTON",
                                        "12",
                                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_TEXT,
                                        230, 100, 100, 100,
                                        hWnd,
                                        (HMENU) BUTTON_1x3,
                                        NULL,
                                        NULL);

            HWND _2x1 = CreateWindowEx(WS_EX_CLIENTEDGE,
                                        "BUTTON",
                                        "32",
                                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_TEXT,
                                        30, 200, 100, 100,
                                        hWnd,
                                        (HMENU) BUTTON_2x1,
                                        NULL,
                                        NULL);
            HWND _2x2 = CreateWindowEx(WS_EX_CLIENTEDGE,
                                        "BUTTON",
                                        "12",
                                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_TEXT,
                                        130, 200, 100, 100,
                                        hWnd,
                                        (HMENU) BUTTON_2x2,
                                        NULL,
                                        NULL);

            HWND _2x3 = CreateWindowEx(WS_EX_CLIENTEDGE,
                                        "BUTTON",
                                        "23",
                                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_TEXT,
                                        230, 200, 100, 100,
                                        hWnd,
                                        (HMENU) BUTTON_2x3,
                                        NULL,
                                        NULL);

            HWND _3x1 = CreateWindowEx(WS_EX_CLIENTEDGE,
                                        "BUTTON",
                                        "12",
                                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_TEXT,
                                        30, 300, 100, 100,
                                        hWnd,
                                        (HMENU) BUTTON_3x1,
                                        NULL,
                                        NULL);

            HWND _3x2 = CreateWindowEx(WS_EX_CLIENTEDGE,
                                        "BUTTON",
                                        "33",
                                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_TEXT,
                                        130, 300, 100, 100,
                                        hWnd,
                                        (HMENU) BUTTON_3x2,
                                        NULL,
                                        NULL);

            HWND _3x3 = CreateWindowEx(WS_EX_CLIENTEDGE,
                                        "BUTTON",
                                        "12",
                                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_TEXT,
                                        230, 300, 100, 100,
                                        hWnd,
                                        (HMENU) BUTTON_3x3,
                                        NULL,
                                        NULL);

            HWND _PLAYER_TXT = CreateWindowEx(NULL,
                                        "STATIC",
                                        "PLAYER :",
                                        WS_VISIBLE | WS_CHILD | SS_LEFT,
                                        230, 50, 100, 30,
                                        hWnd,
                                        (HMENU) 999,
                                        NULL,
                                        NULL);
        } break;

        case WM_COMMAND:
        {
                if (LOWORD(wParam) == BUTTON_3x3)
            {
                std::cout << "!!!!!" << std::endl; //test(if buttonclick message is  recived)

                SendMessage(_3x3, WM_SETTEXT, 0, (LPARAM) _T("NewText")); //not working
            }
        } break;

    case WM_DESTROY:
        {
            PostQuitMessage(0);
            return 0;
        } break;
}
return DefWindowProc (hWnd, message, wParam, lParam);
}

Sorry for this bunch of code. I would make it shorter, if I knew which part is important. Sorry for my bad english. Thank you.

Body:
try this:

case WM_COMMAND:
{
   if(LOWORD(wParam) == BUTTON_3x3)
   {
         _3x3 = NULL;
         _3x3 = CreateWindowEx(0,
                                         WC_BUTTON,
                                        "Text",230, 300, 100, 100,
                                         hwnd,
                                        (HMENU)BUTTON_3x3,
                                         NULL, NULL);
   }
}
      break;


问:
Is this a message bus based pub-sub pattern?
As per this answer,

A Message Bus is a messaging infrastructure to allow different systems to communicate through a shared set of interfaces(message bus).

Below is the createHub() function & Run() method launched by main() to create message hub to communicate a publisher with multiple subscribers:

```<code>type PubHub struct {
    subscribers map[*subscriptionmediator.HandlerSubscription]struct{}
    Register    chan *subscriptionmediator.HandlerSubscription
    Unregister  chan *subscriptionmediator.HandlerSubscription
    Broadcast   chan *events.Env
}

func createHub() *PubHub {

    return &PubHub{
        subscribers: map[*subscriptionmediator.HandlerSubscription]struct{}{},
        Register:    make(chan *subscriptionmediator.HandlerSubscription),
        Unregister:  make(chan *subscriptionmediator.HandlerSubscription),
        Broadcast:   make(chan *events.Envelope),
    }
}

func (h *PubHub) Run() {

    for {
        select {
        case subscriber := <-h.Register:
            h.subscribers[subscriber] = struct{}{}

        case subscriber := <-h.Unregister:
            if _, ok := h.subscribers[subscriber]; ok {
                delete(h.subscribers, subscriber)
            }
        case message := <-h.Broadcast:
            for subscriber := range h.subscribers {
                subscriber.DataChannel <- message
            }
        }
    }
}
</code>```

where each subscriber registers, as shown below:

```<code>    subscription := &subscriptionmediator.HandlerSubscription{
        conn,
        make(chan *events.Envelope),
    }
    hub.Register <- subscription
</code>```

DataChannel is used for communication between publisher & multiple subscribers

```<code>type HandlerSubscription struct {
    ConnInstance *websocket.Conn
    DataChannel  chan *events.Envelope
}
</code>```

1) Can the above code be considered following message bus based pub-sub pattern?

2) How to avoid one subscriber blocking rest all subscribers, from signalling on a channel? subscriber.DataChannel <- message

答:
Can the above code be considered following message bus based pub-sub pattern?

Yes.

Body:
As per this answer,

A Message Bus is a messaging infrastructure to allow different systems to communicate through a shared set of interfaces(message bus).

Below is the createHub() function & Run() method launched by main() to create message hub to communicate a publisher with multiple subscribers:

type PubHub struct {
    subscribers map[*subscriptionmediator.HandlerSubscription]struct{}
    Register    chan *subscriptionmediator.HandlerSubscription
    Unregister  chan *subscriptionmediator.HandlerSubscription
    Broadcast   chan *events.Env
}

func createHub() *PubHub {

    return &PubHub{
        subscribers: map[*subscriptionmediator.HandlerSubscription]struct{}{},
        Register:    make(chan *subscriptionmediator.HandlerSubscription),
        Unregister:  make(chan *subscriptionmediator.HandlerSubscription),
        Broadcast:   make(chan *events.Envelope),
    }
}

func (h *PubHub) Run() {

    for {
        select {
        case subscriber := <-h.Register:
            h.subscribers[subscriber] = struct{}{}

        case subscriber := <-h.Unregister:
            if _, ok := h.subscribers[subscriber]; ok {
                delete(h.subscribers, subscriber)
            }
        case message := <-h.Broadcast:
            for subscriber := range h.subscribers {
                subscriber.DataChannel <- message
            }
        }
    }
}

where each subscriber registers, as shown below:

    subscription := &subscriptionmediator.HandlerSubscription{
        conn,
        make(chan *events.Envelope),
    }
    hub.Register <- subscription

DataChannel is used for communication between publisher & multiple subscribers

type HandlerSubscription struct {
    ConnInstance *websocket.Conn
    DataChannel  chan *events.Envelope
}

1) Can the above code be considered following message bus based pub-sub pattern?

2) How to avoid one subscriber blocking rest all subscribers, from signalling on a channel? subscriber.DataChannel <- message


问:
Cannot set style-display of a div containing another component through a component in React.js
I am aiming to create a component containing a function, in which a button removes a separate div containing text, which is presented in React.js by another component in a separate div.

Below is the code for my app.js. I would like to set the style of "tweetSection" to "none" (contains Tweet component that provides the text), using the "TurnOff" component.

```<code>import logo from './logo.svg';
import Tweet from './Tweet';
import TurnOff from './TurnOff';

function App() {
  return (
    <div>
    <div id="tweetSection">

    <Tweet />
    </div>
    <div id="button">
    <TurnOff />

    </div>
    </div>
  );
}

export default App;```
```

<p>Here is the code for my TurnOff component</p>

```import React from 'react';

function TurnOff(){
  const toggle = () => {
    document.getElementById('tweetSection').style.display = "none";

  }

  return(

    <button onClick={toggle()}>this is a button</button>

  );
}

export default TurnOff;
```

When I run this, I get a type error stating "TypeError: Cannot read property 'style' of null". Is there a simplistic way, or program this in a different manner in order to hide the "tweetSection" div?

答:
A few things.

To answer why you are getting the error, it is because you are calling the function (toggle()) immeaditely with onClick={toggle()}.

Use this to avoid the problem of calling the function too early:

```<code>    <button onClick={toggle}>this is a button</button>
</code>```

Or:

```<code>    <button onClick={() => toggle()}>this is a button</button>
</code>```

It is being called as soon as it renders, which means document.getElementById('tweetSection') might be null.

You can check for this like:

```<code>const el = document.getElementById('tweetSection');
if (el) {
  el.style.display = "none";
} else {
  console.warn('No tweetSection element found');
}
</code>```

However, a more react way to solve this problem would be to pass props:

```<code>import logo from './logo.svg';
import Tweet from './Tweet';
import TurnOff from './TurnOff';
import React, {useState} from 'react';

function App() {
  const [showTweet, setShowTweet] = useState(true);
  return (
    <div>
     {showTweet && <div id="tweetSection">
      <Tweet />
     </div>}
    <div id="button">
       <TurnOff toggle={() => {
          setShowTweet(!showTweet);
        }}
       />
      </div>
    </div>
  );
}

export default App;
</code>```

```<code>import React from 'react';

function TurnOff({ toggle }){
  return(
    <div>
    <button onClick={toggle}>this is a button</button>
    </div>
  );
}

export default TurnOff;
</code>```

Body:
I am aiming to create a component containing a function, in which a button removes a separate div containing text, which is presented in React.js by another component in a separate div.

Below is the code for my app.js. I would like to set the style of "tweetSection" to "none" (contains Tweet component that provides the text), using the "TurnOff" component.

import logo from './logo.svg';
import Tweet from './Tweet';
import TurnOff from './TurnOff';

function App() {
  return (

    <Tweet />

    <TurnOff />

  );
}

export default App;```

Here is the code for my TurnOff component

import React from 'react';

function TurnOff(){
  const toggle = () => {
    document.getElementById('tweetSection').style.display = "none";

  }

  return(

    <button onClick={toggle()}>this is a button</button>

  );
}

export default TurnOff;

When I run this, I get a type error stating "TypeError: Cannot read property 'style' of null". Is there a simplistic way, or program this in a different manner in order to hide the "tweetSection" div?

Body:
A few things.

To answer why you are getting the error, it is because you are calling the function (toggle()) immeaditely with onClick={toggle()}.

Use this to avoid the problem of calling the function too early:

    <button onClick={toggle}>this is a button</button>

Or:

    <button onClick={() => toggle()}>this is a button</button>

It is being called as soon as it renders, which means document.getElementById('tweetSection') might be null.

You can check for this like:

const el = document.getElementById('tweetSection');
if (el) {
  el.style.display = "none";
} else {
  console.warn('No tweetSection element found');
}

However, a more react way to solve this problem would be to pass props:

import logo from './logo.svg';
import Tweet from './Tweet';
import TurnOff from './TurnOff';
import React, {useState} from 'react';

function App() {
  const [showTweet, setShowTweet] = useState(true);
  return (
    <div>
     {showTweet && <div id="tweetSection">
      <Tweet />
     </div>}
    <div id="button">
       <TurnOff toggle={() => {
          setShowTweet(!showTweet);
        }}
       />
      </div>
    </div>
  );
}

export default App;

import React from 'react';

function TurnOff({ toggle }){
  return(
    <div>
    <button onClick={toggle}>this is a button</button>
    </div>
  );
}

export default TurnOff;


问:
Firestore Update single item in array of objects

I have a document in Firebase Firestore like the above picture, i want to modify a single element in "order" array, i know there is no direct way to do it but is there any way?

i tryed the below code

```<code>    let ww = db.collection("collectionName").document("docName")

    let arrayElement = 0
    ww.updateData([
                           "order.\(arrayElement).isHasOffer": true,
                           "order.\(arrayElement).referenceID": self.referenceID,
                           "order.\(arrayElement).DosageForm": "dd",
                           "order.\(arrayElement).GenericName": "test",
                           "order.\(arrayElement).DISC": 33
                           ]) { err in
                               if let err = err {
                                   print("Error updating document: \(err)")
                               } else {
                                   print("Document successfully updated")
                               }
                           }
</code>```

it's override "order" array (remove all the element and adding only what i pass in the code) -> what if there is 100 elements? should i rewrite them all again

it's also convert it from "Array" type to "map", once converted to "map" i'm not able to read them back as an array

note: i have a unique id for every element in the array

答:
Whenever you want to modify individual elements of an array type field, you have to read the document, modify the array in memory, then update the modified array back to the document.

You will not be able to do this without reading the document first.  If you require an atomic update, you can perform this read-then-update procedure in a transaction.

Body:
I have a document in Firebase Firestore like the above picture, i want to modify a single element in "order" array, i know there is no direct way to do it but is there any way?

i tryed the below code

    let ww = db.collection("collectionName").document("docName")

    let arrayElement = 0
    ww.updateData([
                           "order.\(arrayElement).isHasOffer": true,
                           "order.\(arrayElement).referenceID": self.referenceID,
                           "order.\(arrayElement).DosageForm": "dd",
                           "order.\(arrayElement).GenericName": "test",
                           "order.\(arrayElement).DISC": 33
                           ]) { err in
                               if let err = err {
                                   print("Error updating document: \(err)")
                               } else {
                                   print("Document successfully updated")
                               }
                           }

it's override "order" array (remove all the element and adding only what i pass in the code) -> what if there is 100 elements? should i rewrite them all again

it's also convert it from "Array" type to "map", once converted to "map" i'm not able to read them back as an array

note: i have a unique id for every element in the array


问:
How can I check if the array of objects have all values duplicate?
```<code>var values = [
    { name: 'Car',Data:'Required',value:'Vehicle' },
    { name: 'Auto',Data:'Required',value:'Vehicle'},
    { name: 'Bike',Data:'Required',value:'Vehicle'},
    { name: 'Car',Data:'Required',value:'Vehicle' }
];
</code>```

Duplicate object will be:
                               { name: 'Car',Data:'Required',value:'Vehicle' }

答:
Working ahead from the answer in:
https://stackoverflow.com/a/840808/11057988

var findDuplicates = (arr) => {
  let sorted_arr = arr.slice().sort(sortFunc); // You can define the comparing function here.
  // JS by default uses a crappy string compare.
  // (we use slice to clone the array so the
  // original array won't be modified)
  let results = [];
  for (let i = 0; i < sorted_arr.length - 1; i++) {
    if (sortFunc(sorted_arr[i + 1], sorted_arr[i]) === 0) {
      results.push(sorted_arr[i]);
    }
  }
  return results;
}

var values = [
    { name: 'Car',Data:'Required',value:'Vehicle' },
    { name: 'Auto',Data:'Required',value:'Vehicle'},
    { name: 'Bike',Data:'Required',value:'Vehicle'},
    { name: 'Car',Data:'Required',value:'Vehicle' }
];

var sortFunc = (a, b) => {
  return   (a.name !== b.name) ? a.name.localeCompare(b.name)
         : (a.Data !== b.Data) ? a.Data.localeCompare(b.Data)
         : a.value.localeCompare(b.value);
};

console.log(`The duplicates are ${JSON.stringify(findDuplicates(values))}`);
// prints The duplicates are [{"name":"Car","Data":"Required","value":"Vehicle"}]```

Couple of differences from original answer:

 1. The sortFunc is defined as per your data.

 2. Since your input is array of objects, the sortFunc is reused for equality check.

Body:
var values = [
    { name: 'Car',Data:'Required',value:'Vehicle' },
    { name: 'Auto',Data:'Required',value:'Vehicle'},
    { name: 'Bike',Data:'Required',value:'Vehicle'},
    { name: 'Car',Data:'Required',value:'Vehicle' }
];

Duplicate object will be:
                               { name: 'Car',Data:'Required',value:'Vehicle' }

Body:
Working ahead from the answer in:
https://stackoverflow.com/a/840808/11057988

var findDuplicates = (arr) => {
  let sorted_arr = arr.slice().sort(sortFunc); // You can define the comparing function here.
  // JS by default uses a crappy string compare.
  // (we use slice to clone the array so the
  // original array won't be modified)
  let results = [];
  for (let i = 0; i < sorted_arr.length - 1; i++) {
    if (sortFunc(sorted_arr[i + 1], sorted_arr[i]) === 0) {
      results.push(sorted_arr[i]);
    }
  }
  return results;
}

var values = [
    { name: 'Car',Data:'Required',value:'Vehicle' },
    { name: 'Auto',Data:'Required',value:'Vehicle'},
    { name: 'Bike',Data:'Required',value:'Vehicle'},
    { name: 'Car',Data:'Required',value:'Vehicle' }
];

var sortFunc = (a, b) => {
  return   (a.name !== b.name) ? a.name.localeCompare(b.name)
         : (a.Data !== b.Data) ? a.Data.localeCompare(b.Data)
         : a.value.localeCompare(b.value);
};

console.log(`The duplicates are ${JSON.stringify(findDuplicates(values))}`);
// prints The duplicates are [{"name":"Car","Data":"Required","value":"Vehicle"}]

Couple of differences from original answer:

 1. The sortFunc is defined as per your data.

 2. Since your input is array of objects, the sortFunc is reused for equality check.


问:
How to fill contour of connected edge and crop the image out in python?
click to view the image

the left side is the original image and I've used canny edge detection method to only get the outer edge of the image as you can see from the right side image. Now is it possible to fill the connected edge with white color and crop the image? Sorry i'm quite new in image processing

答:
Always best if you provide separate images.

Here is one way to do that in Python/OpenCV.

Read the image as grayscale

Threshold

Apply morphology close

Get the one external contour

Get the bounding box coordinates of the contour

Draw the one white contour as filled on a black background

Crop the result

Save the results

Input:

```<code>import cv2
import numpy as np

# load image
img = cv2.imread("outline.png", cv2.IMREAD_GRAYSCALE)

# threshold
thresh = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY)[1]

# apply close morphology
#kernel = np.ones((5,5), np.uint8)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)

# get bounding box coordinates from the one filled external contour
filled = np.zeros_like(thresh)
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
the_contour = contours[0]
x,y,w,h = cv2.boundingRect(the_contour)
cv2.drawContours(filled, [the_contour], 0, 255, -1)

# crop filled contour image
result = filled.copy()
result = result[y:y+h, x:x+w]

# write result to disk
cv2.imwrite("outline_thresh.png", thresh)
cv2.imwrite("outline_filled.png", filled)
cv2.imwrite("outline_cropped.png", result)

# display results
cv2.imshow("THRESH", thresh)
cv2.imshow("FILLED", filled)
cv2.imshow("CROPPED", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

Threshold image:

Filled contour image:

Cropped image:

An alternate to using a filled contour would be to flood fill the interior.

Body:
Always best if you provide separate images.

Here is one way to do that in Python/OpenCV.

Read the image as grayscale

Threshold

Apply morphology close

Get the one external contour

Get the bounding box coordinates of the contour

Draw the one white contour as filled on a black background

Crop the result

Save the results

Input:

import cv2
import numpy as np

# load image
img = cv2.imread("outline.png", cv2.IMREAD_GRAYSCALE)

# threshold
thresh = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY)[1]

# apply close morphology
#kernel = np.ones((5,5), np.uint8)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)

# get bounding box coordinates from the one filled external contour
filled = np.zeros_like(thresh)
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
the_contour = contours[0]
x,y,w,h = cv2.boundingRect(the_contour)
cv2.drawContours(filled, [the_contour], 0, 255, -1)

# crop filled contour image
result = filled.copy()
result = result[y:y+h, x:x+w]

# write result to disk
cv2.imwrite("outline_thresh.png", thresh)
cv2.imwrite("outline_filled.png", filled)
cv2.imwrite("outline_cropped.png", result)

# display results
cv2.imshow("THRESH", thresh)
cv2.imshow("FILLED", filled)
cv2.imshow("CROPPED", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

Threshold image:

Filled contour image:

Cropped image:

An alternate to using a filled contour would be to flood fill the interior.


问:
JS- Change element class/id based on parent element class
I'm want to change the class of a child element class based on the parent element class.

For example

```<code><div class="change">
    <div class="show-more"></div>
</div>
</code>```

If parent class is class="change" then change the child class to class="show-none"

```<code><div class="change">
    <div class="show-none"></div>
</div>
</code>```

And how can I also do this to change the child id for example

```<code><div class="change">
    <div id="show-more"></div>
</div>
</code>```

to

```<code><div class="change">
    <div id="show-none"></div>
</div>
</code>```

How can this be done?

答:
You can use CSS selectors and the classlist property.

If you want to do this for one element:

let el = document.querySelector('.change .show-more')
el.classList.remove('show-more')
el.classList.add('show-none')
```

<p>If you want to do this for all the elements that match this selector:</p>

<pre class="lang-js prettyprint-override"><code>document.querySelectorAll('.change .show-more').forEach(el => {
    el.classList.remove('.show-more')
    el.classList.add('show-none')
})
</code>```

Body:
I'm want to change the class of a child element class based on the parent element class.

For example

If parent class is class="change" then change the child class to class="show-none"

And how can I also do this to change the child id for example

to

How can this be done?

Body:
You can use CSS selectors and the classlist property.

If you want to do this for one element:

let el = document.querySelector('.change .show-more')
el.classList.remove('show-more')
el.classList.add('show-none')

If you want to do this for all the elements that match this selector:

document.querySelectorAll('.change .show-more').forEach(el => {
    el.classList.remove('.show-more')
    el.classList.add('show-none')
})


问:
What I'm missing here? IsSuccessStatusCode not valid
In my code I'm trying to communicate with a php webservice.  In my Xamarin code in Csharp IsSuccessStatusCode it's invalid "'string' does not contain a definition for "isSuccessStatusCode'....  All codes i seen in the net includes this but i don't know it's not working for me.</p>

```<code>private async void GetDataAsync()
{
    //nota: para que await funcione hay que escribir en la rutina al lado de private async
    HttpClient httpClient = new HttpClient();
    var response = await httpClient.GetStringAsync("http://192.168.1.33:82/usuarios_xamarin/Usuarios.php");

    if (response.IsSuccessStatusCode)
    {
        var content = await response.Content.ReadAsStringAsync();
        var posts = JsonConvert.DeserializeObject<List<Posts>>(content);
    }
    //pertenece al nugget newtonsoft.json
    //si no esta instalado hay que instalarlo en los nuggets

    //var posts = JsonConvert.DeserializeObject<List<Posts>>(response);

}

</code>```

答:
Well, it's right. string does not have a property called IsSuccessStatusCode. HttpResponseMessage does.

You are calling the endpoint and converting the response directly to string. If you wanted to check the status code of the response, you want to do this in two parts:

HttpResponseMessage response = await client.GetAsync("http://192.168.1.33:82/usuarios_xamarin/Usuarios.php");
if (response.EnsureSuccessStatusCode)
{
    string responseBody = await response.Content.ReadAsStringAsync();
}
```

Body:
In my code I'm trying to communicate with a php webservice.  In my Xamarin code in Csharp IsSuccessStatusCode it's invalid "'string' does not contain a definition for "isSuccessStatusCode'....  All codes i seen in the net includes this but i don't know it's not working for me.

private async void GetDataAsync()
{
    //nota: para que await funcione hay que escribir en la rutina al lado de private async
    HttpClient httpClient = new HttpClient();
    var response = await httpClient.GetStringAsync("http://192.168.1.33:82/usuarios_xamarin/Usuarios.php");

    if (response.IsSuccessStatusCode)
    {
        var content = await response.Content.ReadAsStringAsync();
        var posts = JsonConvert.DeserializeObject<List<Posts>>(content);
    }
    //pertenece al nugget newtonsoft.json
    //si no esta instalado hay que instalarlo en los nuggets

    //var posts = JsonConvert.DeserializeObject<List<Posts>>(response);

}


问:
Fullcalendar timeGridWeek and timeGridDay not loading correctly
For my calendar, I'm trying to use the timeGridWeek and timeGridDay views. Instead of loading correctly like this:

it loads like this:

My calendar defaultview is dayGridMonth, which works fine. When I click the buttons that change the view to week or day, it doesn't render correctly AND also doesn't let me change the view further with button clicks (essentially I'm stuck in the view I selected).

Here is my code for the calendar element + imports:

```<code>import timeGridPlugin from "@fullcalendar/timegrid";
import FullCalendar from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";
import interactionPlugin, { Draggable } from "@fullcalendar/interaction";

          <FullCalendar
            ref={this.calendarRef}
            defaultView="dayGridMonth"
            height={"parent"}
            width={"parent"}
            droppable={true}
            drop={this.handleDrop}
            dateClick={this.handleDateClick}
            eventClick={this.handleEventClick}
            header={{
              left: "prev,next, today",
              center: "title",
              right: "dayGridMonth,timeGridWeek,timeGridDay"
            }}
            plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
            editable={true}
            events={this.state.events}
            eventLimit={true}
          />
</code>```

Thanks in advance :)

答: Nevermind, it's fixed! it seems to just be wonky rendering on the local side. When I hosted the app on heroku the timeGridWeek and day both rendered fine. It seems to have just been a faulty installation.</p>

Body:
For my calendar, I'm trying to use the timeGridWeek and timeGridDay views. Instead of loading correctly like this:

it loads like this:

My calendar defaultview is dayGridMonth, which works fine. When I click the buttons that change the view to week or day, it doesn't render correctly AND also doesn't let me change the view further with button clicks (essentially I'm stuck in the view I selected).

Here is my code for the calendar element + imports:

import timeGridPlugin from "@fullcalendar/timegrid";
import FullCalendar from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";
import interactionPlugin, { Draggable } from "@fullcalendar/interaction";

          <FullCalendar
            ref={this.calendarRef}
            defaultView="dayGridMonth"
            height={"parent"}
            width={"parent"}
            droppable={true}
            drop={this.handleDrop}
            dateClick={this.handleDateClick}
            eventClick={this.handleEventClick}
            header={{
              left: "prev,next, today",
              center: "title",
              right: "dayGridMonth,timeGridWeek,timeGridDay"
            }}
            plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
            editable={true}
            events={this.state.events}
            eventLimit={true}
          />

Thanks in advance :)


问:
Last added element value reflected in whole list in python - How to solve this problem?
The following is my data:

```<code>"Jay": 1, "Raj": 1,"Jay": 3,"Raj": 3,"Jay": 10,"Raj": 2,"Jay": 2
</code>```

I would like to put it into a list to make it look like this:

```<code>["Jay": 1,"Raj": 1,"Jay": 3,"Raj": 3,"Jay": 10,"Raj": 2,"Jay": 2]
</code>```

My issue is that only the final element is pushed to the entire list. The result looks like this:

```<code>["Jay": 2,"Raj": 2,"Jay": 2,"Raj": 2,"Jay": 2,"Raj": 2,"Jay": 2]
</code>```

How would I resolve this issue?

答:
tou use dict it has a unique key value par properties that why when you and new it will update last add key value par if not has any key it will add new key

It will work on list of list if you do want replace last element then try  following way may be your problem solve

```<code>list_var = []
list_var.append(['Jay',1])
print(list_var) #[['Jay',1]]

#you can append list using append method so list is ordered collection so add another one

list_var.append(['Raj',1])
print(list_var) #[['Jay',1],['Raj',1]]

#add another
list_var.append(['Jay',3])
print(list_var) #[['Jay',1],['Raj',1],['Jay',3]]

#using for you will print
for name,score in list_var:
    print(name,score)

#or you will access by index
list_var[0] #[['Jay',1]

</code>```

Or you can manipulate by map filter reduce method

Using this stuff may you understand if any problem let me know and if it's work then let me know

Body:
The following is my data:

"Jay": 1, "Raj": 1,"Jay": 3,"Raj": 3,"Jay": 10,"Raj": 2,"Jay": 2

I would like to put it into a list to make it look like this:

["Jay": 1,"Raj": 1,"Jay": 3,"Raj": 3,"Jay": 10,"Raj": 2,"Jay": 2]

My issue is that only the final element is pushed to the entire list. The result looks like this:

["Jay": 2,"Raj": 2,"Jay": 2,"Raj": 2,"Jay": 2,"Raj": 2,"Jay": 2]

How would I resolve this issue?

Body:
tou use dict it has a unique key value par properties that why when you and new it will update last add key value par if not has any key it will add new key

It will work on list of list if you do want replace last element then try  following way may be your problem solve

list_var = []
list_var.append(['Jay',1])
print(list_var) #[['Jay',1]]

#you can append list using append method so list is ordered collection so add another one

list_var.append(['Raj',1])
print(list_var) #[['Jay',1],['Raj',1]]

#add another
list_var.append(['Jay',3])
print(list_var) #[['Jay',1],['Raj',1],['Jay',3]]

#using for you will print
for name,score in list_var:
    print(name,score)

#or you will access by index
list_var[0] #[['Jay',1]

Or you can manipulate by map filter reduce method

Using this stuff may you understand if any problem let me know and if it's work then let me know


问:
Hide password on settings screen
I have easy problem, but I cannot find solution. Lets have settings page generated over Android studio. And here is one field - password.

```<code><EditTextPreference
    android:defaultValue="@string/pref_default_display_password"
    android:inputType="textPassword"
    android:key="password"
    android:maxLines="1"
    android:selectAllOnFocus="true"
    android:singleLine="true"
    android:password="true"
    android:title="@string/pref_title_display_password" />
</code>```

There is no problem with input which is with asterisks. But problem is, that I see saved password on screen:

How can I hide it?

Thank you very much.

答:
I resolved it as below.</p>

```<code>resolved code
getEditText().setInputType(
    TYPE_CLASS_NUMBER|
    TYPE_NUMBER_VARIATION_PASSWORD|
    TYPE_NUMBER_FLAG_DECIMAL);

related code

TextView class
private static boolean isPasswordInputType(int inputType) {
    int variation = inputType & 4095;
    return variation == 129 || variation == 225 || variation == 18;
}

variation == 18 ->
public static final int TYPE_TEXT_VARIATION_URI = 0x00000010;
public static final int TYPE_CLASS_NUMBER = 0x00000002;
</code>```

Title: Hide password on settings screen

Body:
I have easy problem, but I cannot find solution. Lets have settings page generated over Android studio. And here is one field - password.

<EditTextPreference
    android:defaultValue="@string/pref_default_display_password"
    android:inputType="textPassword"
    android:key="password"
    android:maxLines="1"
    android:selectAllOnFocus="true"
    android:singleLine="true"
    android:password="true"
    android:title="@string/pref_title_display_password" />

There is no problem with input which is with asterisks. But problem is, that I see saved password on screen:

How can I hide it?

Thank you very much.

Body:
I resolved it as below.

resolved code
getEditText().setInputType(
    TYPE_CLASS_NUMBER|
    TYPE_NUMBER_VARIATION_PASSWORD|
    TYPE_NUMBER_FLAG_DECIMAL);

related code

TextView class
private static boolean isPasswordInputType(int inputType) {
    int variation = inputType & 4095;
    return variation == 129 || variation == 225 || variation == 18;
}

variation == 18 ->
public static final int TYPE_TEXT_VARIATION_URI = 0x00000010;
public static final int TYPE_CLASS_NUMBER = 0x00000002;


答:
Using Javascript

```

Title: JS- Change element class/id based on parent element class

Body:
Using Javascript

<div class="change">
    <div class="show-more"></div>
</div>

<script>
    const allParentElement = document.getElementsByClassName('change');
    const child = document.querySelector('.show-more');

    for (const parentElement of allParentElement) {
        if (parentElement.contains(child)) {
            child.classList.add('show-none');
            child.classList.remove('show-more');
        }
    }
</script>


问:
r data formatting with NAs
If I have a dataset with three columns like this below

```<code> Id    Date       Gender
 1     NA         F
 1     NA         NA
 1     03-11-1977 NA
 2     04-17-2005 NA
 2     NA         M
 3     NA         NA
 3     06-04-1999 NA
 3     NA         F
</code>```

How could I clean this data such that I see a dataset like this below ?

```<code>Id    Date        Gender
 1     03-11-1977 F
 2     04-17-2005 M
 3     06-04-1999 F
</code>```

Thanks.

答:
fill the values by Id and filter NA values.

```<code>library(dplyr)
df %>%
  group_by(Id) %>%
  tidyr::fill(Gender, .direction = "updown") %>%
  filter(!is.na(Date))

#     Id Date       Gender
#  <int> <chr>      <chr>
#1     1 03-11-1977 F
#2     2 04-17-2005 M
#3     3 06-04-1999 F
</code>```

Title: r data formatting with NAs

Body:
If I have a dataset with three columns like this below

 Id    Date       Gender
 1     NA         F
 1     NA         NA
 1     03-11-1977 NA
 2     04-17-2005 NA
 2     NA         M
 3     NA         NA
 3     06-04-1999 NA
 3     NA         F

How could I clean this data such that I see a dataset like this below ?

Id    Date        Gender
 1     03-11-1977 F
 2     04-17-2005 M
 3     06-04-1999 F

Thanks.

Body:
fill the values by Id and filter NA values.

library(dplyr)
df %>%
  group_by(Id) %>%
  tidyr::fill(Gender, .direction = "updown") %>%
  filter(!is.na(Date))

#     Id Date       Gender
#  <int> <chr>      <chr>
#1     1 03-11-1977 F
#2     2 04-17-2005 M
#3     3 06-04-1999 F


问:
php xml XPath foreach returning all nodes instead of iterating
I have a XML file like this

```<code><Articles>
 <Article>
  <ArticleTitle>
   First Book
 </ArticleTitle>
</Article>
 <Article>
  <ArticleTitle>
   Second Book
 </ArticleTitle>
</Article>
</code>```

And using this type of php script to retrieve the contents of ArticleTitle in an iterative fashion

```<code>foreach ($xml->Article as $Article){
$title = $Article->xpath('//ArticleTitle');
echo $title[0];
}
</code>```

But this displays

```<code>First Book
First Book
</code>```

Instead of

```<code>First Book
Second Book
</code>```

I was assuming that when the foreach ($xml->Article as $Article) starts it will grab each Article node and then I can access the contents of that node but this is not what is happening. What am I doing wrong?

答:
Your issue is that the xpath you have used is an absolute path (it starts with /) so the fact that you are calling it from a child node has no effect. You should use a relative path, in this case either simply ArticleTitle will suffice or .//ArticleTitle to allow for other nodes between Article and ArticleTitle. For example:

```<code>foreach ($xml->Article as $Article){
    $title = $Article->xpath('ArticleTitle');
    echo $title[0];
}

foreach ($xml->Article as $Article){
    $title = $Article->xpath('.//ArticleTitle');
    echo $title[0];
}
</code>```

Output in both cases is:

```<code>First Book
Second Book
</code>```

Demo on 3v4l.org

Body:
I have a XML file like this

<Articles>

  <ArticleTitle>
   First Book
 </ArticleTitle>

  <ArticleTitle>
   Second Book
 </ArticleTitle>

And using this type of php script to retrieve the contents of ArticleTitle in an iterative fashion

foreach ($xml->Article as $Article){
$title = $Article->xpath('//ArticleTitle');
echo $title[0];
}

But this displays

First Book
First Book

Instead of

First Book
Second Book

I was assuming that when the foreach ($xml->Article as $Article) starts it will grab each Article node and then I can access the contents of that node but this is not what is happening. What am I doing wrong?

Body:
Your issue is that the xpath you have used is an absolute path (it starts with /) so the fact that you are calling it from a child node has no effect. You should use a relative path, in this case either simply ArticleTitle will suffice or .//ArticleTitle to allow for other nodes between Article and ArticleTitle. For example:

foreach ($xml->Article as $Article){
    $title = $Article->xpath('ArticleTitle');
    echo $title[0];
}

foreach ($xml->Article as $Article){
    $title = $Article->xpath('.//ArticleTitle');
    echo $title[0];
}

Output in both cases is:

First Book
Second Book

Demo on 3v4l.org