问:
tokio::timeout on Stream always occurs
I'm trying to accept a UDP message but only if it happens within 5 seconds, I have a Stream abstraction built with both manually implementing Stream and by using the combinators in the futures library. Each way, after the recv_from future resolves, the duration will expire and the stream will return an Err(Elapsed(())). This is not the expected behaviour, if a value is returned, no error is supposed to be returned.

The expected behaviour is that the stream will resolve either the timeout or the Vec, but not one, then the other 5 seconds later.

```<code>use futures::{pin_mut, ready, stream::unfold, FutureExt};
use tokio::{
    net::{udp, UdpSocket},
    stream::{Stream, StreamExt},
    time::{self, Duration},
};

use std::{
    io,
    net::SocketAddr,
    pin::Pin,
    task::{Context, Poll},
};

#[derive(Debug)]
pub(crate) struct UdpStream {
    stream: udp::RecvHalf,
}

impl UdpStream {
    fn new(stream: udp::RecvHalf) -> Self {
        Self { stream }
    }

    fn stream(self) -> impl Stream<Item = io::Result<(Vec<u8>, SocketAddr)>> {
        unfold(self.stream, |mut stream| async move {
            let mut buf = [0; 4096];
            match time::timeout(Duration::from_secs(5), stream.recv_from(&mut buf)).await {
                Ok(Ok((len, src))) => {
                    Some((Ok((buf.iter().take(len).cloned().collect(), src)), stream))
                }
                e => {
                    println!("{:?}", e);
                    None
                }
            }
        })
    }
}

impl Stream for UdpStream {
    type Item = io::Result<(Vec<u8>, SocketAddr)>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let socket = &mut self.stream;
        pin_mut!(socket);
        let mut buf = [0u8; 4096];
        let (len, src) = ready!(Box::pin(socket.recv_from(&mut buf)).poll_unpin(cx))?;
        Poll::Ready(Some(Ok((buf.iter().take(len).cloned().collect(), src))))
    }
}

async fn listen_udp(addr: SocketAddr) -> io::Result<()> {
    let udp = UdpSocket::bind(addr).await?;
    let (mut udp_recv, mut udp_send) = udp.split();

    let mut msg_stream = Box::pin(UdpStream::new(udp_recv).stream());
    // use the manually implemented stream with this:
    // let mut msg_stream = UdpStream::new(udp_recv).timeout(Duration::from_secs(5));

    while let Some(msg) = msg_stream.next().await {
        match msg {
            Ok((buf, src)) => {
                udp_send.send_to(&buf, &src).await?;
                println!("Message recv: {:?}", buf);
            }
            Err(e) => {
                eprintln!("timed out: {:?}", e);
            }
        }
    }
    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
    listen_udp("127.0.0.1:9953".parse()?).await?;
    Ok(())
}
</code>```

You can try by running this code and making udp requests with echo "foo" | nc 127.0.0.1 9953 -u or with dig

cargo.toml

```<code>[package]
name = "udp_test"
version = "0.1.0"
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
tokio = { version = "0.2", features = ["full"] }
futures = "0.3"
</code>```

答:
After your stream returns the first (and the only) element, it goes back to wait for the next; it never ends until the timeout.

Basically a stream abstraction is not necessary here. A future wrapped in a timeout will do:

```<code>use std::{io, net::SocketAddr};
use tokio::{
    net::UdpSocket,
    time::{self, Duration},
};

async fn listen_udp(addr: SocketAddr) -> io::Result<()> {
    let mut udp = UdpSocket::bind(addr).await?;
    let mut buf = [0; 4096];

    match time::timeout(Duration::from_secs(5), udp.recv_from(&mut buf)).await? {
        Ok((count, src)) => {
            udp.send_to(&buf[..count], &src).await?;
            println!("Message recv: {:?}", &buf[..count]);
        }
        Err(e) => {
            eprintln!("timed out: {:?}", e);
        }
    }
    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    listen_udp("127.0.0.1:9953".parse()?).await?;
    Ok(())
}
</code>```

Title: tokio::timeout on Stream always occurs

Body:
I'm trying to accept a UDP message but only if it happens within 5 seconds, I have a Stream abstraction built with both manually implementing Stream and by using the combinators in the futures library. Each way, after the recv_from future resolves, the duration will expire and the stream will return an Err(Elapsed(())). This is not the expected behaviour, if a value is returned, no error is supposed to be returned.

The expected behaviour is that the stream will resolve either the timeout or the Vec, but not one, then the other 5 seconds later.

use futures::{pin_mut, ready, stream::unfold, FutureExt};
use tokio::{
    net::{udp, UdpSocket},
    stream::{Stream, StreamExt},
    time::{self, Duration},
};

use std::{
    io,
    net::SocketAddr,
    pin::Pin,
    task::{Context, Poll},
};

#[derive(Debug)]
pub(crate) struct UdpStream {
    stream: udp::RecvHalf,
}

impl UdpStream {
    fn new(stream: udp::RecvHalf) -> Self {
        Self { stream }
    }

    fn stream(self) -> impl Stream<Item = io::Result<(Vec<u8>, SocketAddr)>> {
        unfold(self.stream, |mut stream| async move {
            let mut buf = [0; 4096];
            match time::timeout(Duration::from_secs(5), stream.recv_from(&mut buf)).await {
                Ok(Ok((len, src))) => {
                    Some((Ok((buf.iter().take(len).cloned().collect(), src)), stream))
                }
                e => {
                    println!("{:?}", e);
                    None
                }
            }
        })
    }
}

impl Stream for UdpStream {
    type Item = io::Result<(Vec<u8>, SocketAddr)>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let socket = &mut self.stream;
        pin_mut!(socket);
        let mut buf = [0u8; 4096];
        let (len, src) = ready!(Box::pin(socket.recv_from(&mut buf)).poll_unpin(cx))?;
        Poll::Ready(Some(Ok((buf.iter().take(len).cloned().collect(), src))))
    }
}

async fn listen_udp(addr: SocketAddr) -> io::Result<()> {
    let udp = UdpSocket::bind(addr).await?;
    let (mut udp_recv, mut udp_send) = udp.split();

    let mut msg_stream = Box::pin(UdpStream::new(udp_recv).stream());
    // use the manually implemented stream with this:
    // let mut msg_stream = UdpStream::new(udp_recv).timeout(Duration::from_secs(5));

    while let Some(msg) = msg_stream.next().await {
        match msg {
            Ok((buf, src)) => {
                udp_send.send_to(&buf, &src).await?;
                println!("Message recv: {:?}", buf);
            }
            Err(e) => {
                eprintln!("timed out: {:?}", e);
            }
        }
    }
    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
    listen_udp("127.0.0.1:9953".parse()?).await?;
    Ok(())
}

You can try by running this code and making udp requests with echo "foo" | nc 127.0.0.1 9953 -u or with dig

cargo.toml

[package]
name = "udp_test"
version = "0.1.0"
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
tokio = { version = "0.2", features = ["full"] }
futures = "0.3"

Body:
After your stream returns the first (and the only) element, it goes back to wait for the next; it never ends until the timeout.

Basically a stream abstraction is not necessary here. A future wrapped in a timeout will do:

use std::{io, net::SocketAddr};
use tokio::{
    net::UdpSocket,
    time::{self, Duration},
};

async fn listen_udp(addr: SocketAddr) -> io::Result<()> {
    let mut udp = UdpSocket::bind(addr).await?;
    let mut buf = [0; 4096];

    match time::timeout(Duration::from_secs(5), udp.recv_from(&mut buf)).await? {
        Ok((count, src)) => {
            udp.send_to(&buf[..count], &src).await?;
            println!("Message recv: {:?}", &buf[..count]);
        }
        Err(e) => {
            eprintln!("timed out: {:?}", e);
        }
    }
    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    listen_udp("127.0.0.1:9953".parse()?).await?;
    Ok(())
}


来源: stackexchange

问:
Pycharm pyautogui problem, cant start two line program
Just wanted to import PyAutoGUI, but got this error.

What am I supposed to do?

答:
The error is telling you that you have a  syntax error at the end of the line of code.
You don’t need the final semi colon in the init.py script.
Python does not need them.

ContentLicense: CC BY-SA 4.0


问:
CryptographicException 'Keyset does not exist', but only through WCF
I have some code that makes a call to a third party web service that is secured using X.509 certification.

If I call the code directly (using a unit test) it works without any problems.

When deployed, this code will be called via a WCF Service. I have added a second unit test that calls the WCF Service, however this fails with a CryptographicException, message "Keyset does not exist" when I call a method on the third party web service.

I presume that this is because my WCF Service will be attempting to call the third party web service using a different user to myself.

Can anyone shed any additional light on this issue?

答:
It will probably be a permissions problem on the certificate.

When running a unit test you are going to be executing those under your own user context, which (depending on what store the client certificate is in) will have access to that certificate's private key.

However if your WCF service is hosted under IIS, or as a Windows Service it's likely it will be running under a service account (Network Service, Local Service or some other restricted account).

You will need to set the appropriate permissions on the private key to allow that service account access to it. MSDN has the details

OwnerDisplayName: Richard E

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: blowdart

OwnerDisplayName: blowdart


问:
XML Schema - elementFormDefault is unqualified but namespace prefix is used
I am not an expert on XML Schema so I am wondering how can the following be correct:

In emma (http://www.w3.org/TR/emma/) all examples given are using fully qualified
emma (both at elements and attributes) like:

```<code><emma:emma version="1.0" xmlns:emma="http://www.w3.org/2003/04/emma"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.w3.org/2003/04/emma
    http://www.w3.org/TR/2009/REC-emma-20090210/emma.xsd"
    xmlns="http://www.example.com/example">
    <emma:interpretation id="r1" emma:medium="acoustic" emma:mode="voice">
        ...
    </emma:interpretation>
</emma:emma>
</code>```

but the http://www.w3.org/TR/emma/emma.xsd defines:

```<code>elementFormDefault="unqualified" attributeFormDefault="unqualified"
</code>```

And I don't see how prefixes are enabled on the element / attribute level either.

I wonder, how can that be correct? There must be a flaw in my understanding of XML Schema.

答: elementFormDefault and attributeFormDefault are only defaults. It's always possible to specify form="qualified" on individual element and attribute declarations. And global element and attribute declarations are qualified by the target namespace unconditionally.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am not an expert on XML Schema so I am wondering how can the following be correct:

In emma (http://www.w3.org/TR/emma/) all examples given are using fully qualified
emma (both at elements and attributes) like:

<emma:emma version="1.0" xmlns:emma="http://www.w3.org/2003/04/emma"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.w3.org/2003/04/emma
    http://www.w3.org/TR/2009/REC-emma-20090210/emma.xsd"
    xmlns="http://www.example.com/example">
    <emma:interpretation id="r1" emma:medium="acoustic" emma:mode="voice">
        ...
    </emma:interpretation>
</emma:emma>

but the http://www.w3.org/TR/emma/emma.xsd defines:

elementFormDefault="unqualified" attributeFormDefault="unqualified"

And I don't see how prefixes are enabled on the element / attribute level either.

I wonder, how can that be correct? There must be a flaw in my understanding of XML Schema.


问:
Progress colored with Dots/Stars in Java
This is a sample code. I want a progress bar / progress dots with message before printing output..

```<code>import java.util.Scanner;

public class Main {
  public static void main(String[] args)
  {
    Scanner input = new Scanner (System.in);
    System.out.print("Input your first name: ");
    String fname = input.next();
    System.out.print("Input your last name: ");
    String lname = input.next();
    System.out.println();
    System.out.println("Hello \n"+fname+" "+lname);
  }
}
</code>```

The output should be something like
Sample Output:

Input your first name:  James

Input your last name:  Smith

---Please wait for a few second.. Loading. . . . your name - with blinking dots or stars(or what do they say?)
Then Print the output

**Hello James Smith

答:
To print a "loading" like progress bar on the console, you may do something like what is being done in this block. (I have limited this example upto 30 characters; you may want to bring in your own logic to control that.)

```<code>int count = 1;
try{
    while( true ){
        Thread.sleep( 500 );

        for( int i = 0; i < count; i++ ) System.out.print( "-" );
        System.out.print( "\r" );

        count++;
        if( count >= 30 ) break;
    }
}
catch( Exception e ){
    e.printStackTrace();
}
</code>```

However, IDEs have settings on how to display the control characters. So, you may see that the dots are being printed on new lines instead of replacing the previous set. On Eclipse, you can control that with this setting, which comes on a right-click on the console.

Shortcoming: This doesn't solve the "coloured" dots problem. For this, there is some attempt at How to print color in console using System.out.println?. You may check that out.

Body:
This is a sample code. I want a progress bar / progress dots with message before printing output..

import java.util.Scanner;

public class Main {
  public static void main(String[] args)
  {
    Scanner input = new Scanner (System.in);
    System.out.print("Input your first name: ");
    String fname = input.next();
    System.out.print("Input your last name: ");
    String lname = input.next();
    System.out.println();
    System.out.println("Hello \n"+fname+" "+lname);
  }
}

The output should be something like
Sample Output:

Input your first name:  James

Input your last name:  Smith

---Please wait for a few second.. Loading. . . . your name - with blinking dots or stars(or what do they say?)
Then Print the output

**Hello James Smith

Body:
To print a "loading" like progress bar on the console, you may do something like what is being done in this block. (I have limited this example upto 30 characters; you may want to bring in your own logic to control that.)

int count = 1;
try{
    while( true ){
        Thread.sleep( 500 );

        for( int i = 0; i < count; i++ ) System.out.print( "-" );
        System.out.print( "\r" );

        count++;
        if( count >= 30 ) break;
    }
}
catch( Exception e ){
    e.printStackTrace();
}

However, IDEs have settings on how to display the control characters. So, you may see that the dots are being printed on new lines instead of replacing the previous set. On Eclipse, you can control that with this setting, which comes on a right-click on the console.

Shortcoming: This doesn't solve the "coloured" dots problem. For this, there is some attempt at How to print color in console using System.out.println?. You may check that out.


问:
Mariadb Scans all partitions in timestamp column
I have a table Partitioned by:

HASH(timestamp DIV 43200 )

When I perform this query

```<code>SELECT max(id)
  FROM messages
 WHERE timestamp BETWEEN 1581708508 AND 1581708807
</code>```

it scans all partitions while both numbers 1581708508 & 1581708807& numbers between them are in the same partition, how can I make it to scan only that partition?

答:
You can determine that individual partition by using modular arithmetic

MOD(<formula which's argument of hash function>,<number of partitions>)

assuming you have 2 partitions

```<code>CREATE TABLE messages(ID int, timestamp int)
PARTITION BY HASH( timestamp DIV 43200 )
PARTITIONS 2;
</code>```

look up partition names by

```<code>SELECT CONCAT( 'p',MOD(timestamp DIV 43200,2)) AS partition_name, timestamp
  FROM messages;
</code>```

and determine the related partition name for the value 1581708508 of timestamp column (assume p1). Then Use

```<code>SELECT MAX(id)
  FROM messages PARTITION(p1)
</code>```

to get all the records only in the partition p1 without need of a WHERE condition such as

WHERE timestamp BETWEEN 1581708508 AND 1581708807

Btw, all partitions might be listed through

```<code>SELECT *
  FROM INFORMATION_SCHEMA.PARTITIONS
 WHERE table_name='messages'
</code>```

Demo

Body:
I have a table Partitioned by:

HASH(timestamp DIV 43200 )

When I perform this query

SELECT max(id)
  FROM messages
 WHERE timestamp BETWEEN 1581708508 AND 1581708807

it scans all partitions while both numbers 1581708508 & 1581708807& numbers between them are in the same partition, how can I make it to scan only that partition?

Body:
You can determine that individual partition by using modular arithmetic

MOD(<formula which's argument of hash function>,<number of partitions>)

assuming you have 2 partitions

CREATE TABLE messages(ID int, timestamp int)
PARTITION BY HASH( timestamp DIV 43200 )
PARTITIONS 2;

look up partition names by

SELECT CONCAT( 'p',MOD(timestamp DIV 43200,2)) AS partition_name, timestamp
  FROM messages;

and determine the related partition name for the value 1581708508 of timestamp column (assume p1). Then Use

SELECT MAX(id)
  FROM messages PARTITION(p1)

to get all the records only in the partition p1 without need of a WHERE condition such as

WHERE timestamp BETWEEN 1581708508 AND 1581708807

Btw, all partitions might be listed through

SELECT *
  FROM INFORMATION_SCHEMA.PARTITIONS
 WHERE table_name='messages'

Demo


问:
How to convert a string of date and time in words to numbers?
I have the following string: January 1, 2020 /  12:04 AM / a month ago. How do I convert this into 1/1/2020 0:04:00? The code should ignore the a month ago. How do I do this?

答:
You could use dateutil. It is a third part extension of datetime module. You can add it with
python -m pip install python-dateutil

from dateutil.parser import parse

data = 'January 1, 2020 / 12:04 AM / a month ago'

resp = parse(data, fuzzy_with_tokens=True)
print(resp[0]) # the first index is datetime object
```

The parser is relatively powerful. Here is documentation to Parser.

dateutil is one among many that can help you solve your problem. Good summary of tools such as maya, arrow etc are found Stackabuse thanks to @WasabiMonster

Body:
You could use dateutil. It is a third part extension of datetime module. You can add it with
python -m pip install python-dateutil

from dateutil.parser import parse

data = 'January 1, 2020 / 12:04 AM / a month ago'

resp = parse(data, fuzzy_with_tokens=True)
print(resp[0]) # the first index is datetime object

The parser is relatively powerful. Here is documentation to Parser.

dateutil is one among many that can help you solve your problem. Good summary of tools such as maya, arrow etc are found Stackabuse thanks to @WasabiMonster


问:
Compiler infering the template argument
```<code>template<typename T>
class A
{
    public:

    A(T &t)
    : t_(t){}

    T t_;
};

int main()
{
    int value;
    A<decltype(value)> a(value);
    // what I wish for : A a(value);
    // which does not compile "missing template argument before 'a'"
}
</code>```

Is there a way in the declaration of A (or somewhere else) to hint the compiler that T should be automatically resolved to the type passed to the constructor ?

(ideally c++11, but happy to hear about less old versions)

答:
As answered by @Quentin, this is only possible starting in C++17. However, if you're fine with calling a function to create your A objects, the following should do what you want in C++11:

```<code>template <class T, class NonRefT = typename std::remove_reference<T>::type>
A<NonRefT> create_A (T && t) {
  return A<NonRefT>(std::forward<T>(t));
}

// Or even closer to your original code:
template <class T>
auto create_A (T && t) -> A<decltype(t)> {
  return A<decltype(t)>(std::forward<T>(t));
}
</code>```

I used std::remove_reference based on your use of decltype, though you might want to use std::decay instead.

```<code>int main () {
  int value = 5;
  auto a = create_A(value);
}
</code>```

If I remember correctly the example code has an edge-case where it does not work as expected pre-C++17. The compiler will elide the copy/move constructor to create a from the rvalue returned by create_A(). However, it will check during compilation whether A's copy/move constructor (which it won't use) is available/accessible. Starting from C++17 the copy/move elision is done "properly" and no copy/move constructor is necessary for such code. (Also, I might be misremembering and it might be checking for copy/move assignment instead.)

Title: Compiler infering the template argument

Body:
template<typename T>
class A
{
    public:

    A(T &t)
    : t_(t){}

    T t_;
};

int main()
{
    int value;
    A<decltype(value)> a(value);
    // what I wish for : A a(value);
    // which does not compile "missing template argument before 'a'"
}

Is there a way in the declaration of A (or somewhere else) to hint the compiler that T should be automatically resolved to the type passed to the constructor ?

(ideally c++11, but happy to hear about less old versions)

Body:
As answered by @Quentin, this is only possible starting in C++17. However, if you're fine with calling a function to create your A objects, the following should do what you want in C++11:

template <class T, class NonRefT = typename std::remove_reference<T>::type>
A<NonRefT> create_A (T && t) {
  return A<NonRefT>(std::forward<T>(t));
}

// Or even closer to your original code:
template <class T>
auto create_A (T && t) -> A<decltype(t)> {
  return A<decltype(t)>(std::forward<T>(t));
}

I used std::remove_reference based on your use of decltype, though you might want to use std::decay instead.

int main () {
  int value = 5;
  auto a = create_A(value);
}

If I remember correctly the example code has an edge-case where it does not work as expected pre-C++17. The compiler will elide the copy/move constructor to create a from the rvalue returned by create_A(). However, it will check during compilation whether A's copy/move constructor (which it won't use) is available/accessible. Starting from C++17 the copy/move elision is done "properly" and no copy/move constructor is necessary for such code. (Also, I might be misremembering and it might be checking for copy/move assignment instead.)


问:
Upcast in Java Difference
```<code>class A {
}

class B extends A {
}

class Main {
    public static void main(String[] args) {

        B b1 = new B();
        B b2 = new B();

        A a = b1;
        A c = (A) b2;
    }
}
</code>```

Is there any difference between a and c? b1 is directly referenced and b2 is upcasted to A and then referenced to c of type A.

答: The cast is redundant. b2 gets assigned to c regardless, and invoking any methods on it will invoke the methods of B if they exist.

Title: Upcast in Java Difference

Body:
class A {
}

class B extends A {
}

class Main {
    public static void main(String[] args) {

        B b1 = new B();
        B b2 = new B();

        A a = b1;
        A c = (A) b2;
    }
}

Is there any difference between a and c? b1 is directly referenced and b2 is upcasted to A and then referenced to c of type A.


问:
CHECKSUM_AGG Equivalent in Oracle
I have a query with

```<code>STANDARD_HASH(Column1|Column2|ColumnN, 'MD5') AS HashValue
</code>```

for each row in a table.

Is it possible to GROUP by ColumnX and produce a Aggregate of the hash values?

I've tried LISTAGG but unfortunately that results in too large a concatenation to hash without error (it's possible I'm not applying this correctly though).

PSEUDO ORACLE presentation of what I'd like to achieve:

```<code>SELECT ColumnX, <b>UNKNOWN_AGGREGATE_FUNC</b>(STANDARD_HASH(Column1|Column2|ColumnN, 'MD5'))
FROM TableY
GROUP BY ColumnX</code>```

Essentially my reasoning for this, is ideally I'd like to batch up, by ColumnX,the hash values so that I can transport the batch results over the wire for comparison with an external system and therefore not necessarily have to transport every row in the event the batches match.

答:
Oracle 20c supports CHECKSUM analytical/aggregate function:

Use CHECKSUM to detect changes in a table. The order of the rows in the table does not affect the result.

You can use CHECKSUM with DISTINCT, as part of a GROUP BY query, as a window function, or an analytical function.

Pseudocode:

```<code>SELECT ColumnX, CHECKSUM(STANDARD_HASH(Column1|Column2|ColumnN, 'MD5'))
FROM TableY
GROUP BY ColumnX;
</code>```

Title: CHECKSUM_AGG Equivalent in Oracle

Body:
I have a query with

STANDARD_HASH(Column1|Column2|ColumnN, 'MD5') AS HashValue

for each row in a table.

Is it possible to GROUP by ColumnX and produce a Aggregate of the hash values?

I've tried LISTAGG but unfortunately that results in too large a concatenation to hash without error (it's possible I'm not applying this correctly though).

PSEUDO ORACLE presentation of what I'd like to achieve:

SELECT ColumnX, UNKNOWN_AGGREGATE_FUNC(STANDARD_HASH(Column1|Column2|ColumnN, 'MD5'))
FROM TableY
GROUP BY ColumnX

Essentially my reasoning for this, is ideally I'd like to batch up, by ColumnX,the hash values so that I can transport the batch results over the wire for comparison with an external system and therefore not necessarily have to transport every row in the event the batches match.

Body:
Oracle 20c supports CHECKSUM analytical/aggregate function:

Use CHECKSUM to detect changes in a table. The order of the rows in the table does not affect the result.

You can use CHECKSUM with DISTINCT, as part of a GROUP BY query, as a window function, or an analytical function.

Pseudocode:

SELECT ColumnX, CHECKSUM(STANDARD_HASH(Column1|Column2|ColumnN, 'MD5'))
FROM TableY
GROUP BY ColumnX;


问:
Intstalling Android Studio on 64-bit version of Lubuntu fails installing some 32-bit libraries
Install Android Studio says:

If you are running a 64-bit version of Ubuntu, you need to install some 32-bit libraries with the following command:

sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386
lib32z1 libbz2-1.0:i386
```
</blockquote>
<p>See screenshot:
<img src="https://i.stack.imgur.com/PZijY.jpg" alt="enter image description here" /></p>
<p>The <code>apt-get install</code> fails:</p>
```$ sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386 lib32z1 libbz2-1.0:i386
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package libc6:i386
E: Unable to locate package libncurses5:i386
E: Unable to locate package libstdc++6:i386
E: Couldn't find any package by regex 'libstdc++6'
E: Unable to locate package libbz2-1.0:i386
E: Couldn't find any package by glob 'libbz2-1.0'
E: Couldn't find any package by regex 'libbz2-1.0'
```
<p>Version info:</p>
```$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 19.10
Release:        19.10
Codename:       eoan

$ uname -a
Linux frozen 5.3.0-18-generic #19-Ubuntu SMP Tue Oct 8 20:14:06 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
```

答:
I had also the same issue but this is how i solved mine. Installing 32-bit packages on 64-bit Linux needs you to enable or give instructions to the OS by telling it to allow installation of 32-bit packages/dependencies. In most cases when you install 64-bit Linux it will only have the 64-bit architecture configured. So its upon you to add 32-bit configuration.

First verify the architectures configured in your system;

```<code>sudo dpkg --print-architecture         //amd64
</code>```

Second look for any other foreign architectures

```<code>sudo dpkg --print-foreign-architectures      //response should be nothing
</code>```

Now proceed to add 32-bit architecture

```<code>sudo dpkg --add-architecture i386
</code>```

Verify 32-bit is added

```<code>sudo dpkg --print-foreign-architectures      //i386
</code>```

Then update your packages

```<code>sudo apt-get update
</code>```

Now you can install your 32-bit packages

```<code>sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386 lib32z1 libbz2-1.0:i386
</code>```

Body:
Install Android Studio says:

If you are running a 64-bit version of Ubuntu, you need to install some 32-bit libraries with the following command:

sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386
lib32z1 libbz2-1.0:i386

See screenshot:

The apt-get install fails:

$ sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386 lib32z1 libbz2-1.0:i386
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package libc6:i386
E: Unable to locate package libncurses5:i386
E: Unable to locate package libstdc++6:i386
E: Couldn't find any package by regex 'libstdc++6'
E: Unable to locate package libbz2-1.0:i386
E: Couldn't find any package by glob 'libbz2-1.0'
E: Couldn't find any package by regex 'libbz2-1.0'

Version info:

$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 19.10
Release:        19.10
Codename:       eoan

$ uname -a
Linux frozen 5.3.0-18-generic #19-Ubuntu SMP Tue Oct 8 20:14:06 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

Body:
I had also the same issue but this is how i solved mine. Installing 32-bit packages on 64-bit Linux needs you to enable or give instructions to the OS by telling it to allow installation of 32-bit packages/dependencies. In most cases when you install 64-bit Linux it will only have the 64-bit architecture configured. So its upon you to add 32-bit configuration.

First verify the architectures configured in your system;

sudo dpkg --print-architecture         //amd64

Second look for any other foreign architectures

sudo dpkg --print-foreign-architectures      //response should be nothing

Now proceed to add 32-bit architecture

sudo dpkg --add-architecture i386

Verify 32-bit is added

sudo dpkg --print-foreign-architectures      //i386

Then update your packages

sudo apt-get update

Now you can install your 32-bit packages

sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386 lib32z1 libbz2-1.0:i386


问:
How to determine MySQL / MariaDB version for Maven dependency?
I'm writing a simple Maven project to access my MySQL / MariaDB database. In order to download the proper database connector jar file, I'm adding the following Maven dependency:

```<code><dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
    <scope>provided</scope>
</dependency>
</code>```

I've got that 5.1.47 version above "by chance", based on a previous project which already worked on my computer.

However, when I type mysql -V (capital V) on terminal to check my MySQL/MariaDB version, I get the following:

```<code>>mysql -V
mysql  Ver 15.1 Distrib 10.4.6-MariaDB, for Win64 (AMD64), source revision b8e655ce029a1f182602c9f12c3cc5931226eec2
</code>```

But that 10.4.6 version doesn't mean much to me in terms of determining a proper version to set up my Maven dependency.

What's the procedure to determine MySQL version for Maven dependency based on my local MySQL / MariaDB server?

答:
I've checked MySQL connector MVN Repository for latest version, then I decided to replace 5.1.47 to 8.0.18.

However, after replacing to 8.x.x, I got "hibernate.dialect not set" error. So I added MySQL8Dialect to persistence.xml, then got "time zone value 'unknown' is unrecognized" error. So I added &serverTimezone=UTC to my connection parameters, than it worked.

Here is the updated persistence.xml after using 8.x.x:

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
    http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
    version="2.1">

    <persistence-unit name="myunit" transaction-type="RESOURCE_LOCAL">
        <properties>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/databasename?useSSL=false&serverTimezone=UTC" />
            <property name="javax.persistence.jdbc.user" value="user" />
            <property name="javax.persistence.jdbc.password" value="password" />

            <property name="hibernate.hbm2ddl.auto" value="update" />

            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL8Dialect" />
        </properties>
    </persistence-unit>
</persistence>
</code>```

Body:
I'm writing a simple Maven project to access my MySQL / MariaDB database. In order to download the proper database connector jar file, I'm adding the following Maven dependency:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
    <scope>provided</scope>
</dependency>

I've got that 5.1.47 version above "by chance", based on a previous project which already worked on my computer.

However, when I type mysql -V (capital V) on terminal to check my MySQL/MariaDB version, I get the following:

>mysql -V
mysql  Ver 15.1 Distrib 10.4.6-MariaDB, for Win64 (AMD64), source revision b8e655ce029a1f182602c9f12c3cc5931226eec2

But that 10.4.6 version doesn't mean much to me in terms of determining a proper version to set up my Maven dependency.

What's the procedure to determine MySQL version for Maven dependency based on my local MySQL / MariaDB server?

Body:
I've checked MySQL connector MVN Repository for latest version, then I decided to replace 5.1.47 to 8.0.18.

However, after replacing to 8.x.x, I got "hibernate.dialect not set" error. So I added MySQL8Dialect to persistence.xml, then got "time zone value 'unknown' is unrecognized" error. So I added &amp;serverTimezone=UTC to my connection parameters, than it worked.

Here is the updated persistence.xml after using 8.x.x:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
    http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
    version="2.1">

    <persistence-unit name="myunit" transaction-type="RESOURCE_LOCAL">
        <properties>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/databasename?useSSL=false&amp;serverTimezone=UTC" />
            <property name="javax.persistence.jdbc.user" value="user" />
            <property name="javax.persistence.jdbc.password" value="password" />

            <property name="hibernate.hbm2ddl.auto" value="update" />

            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL8Dialect" />
        </properties>
    </persistence-unit>
</persistence>


问:
When building chisel using sbt how do I turn off the progress bars etc. so that the output is clean?
When building chisel using sbt, when run as a batch process, how do I turn off the progress bars etc. so that the output is clean like I get with most compilers?

That is, I like to build chisel using sbt from within a makefile, like this:

```<code>${VLOG_DIR}/${NAME}.v: ${NAME}.scala
        setsid sbt \
          'runMain ${NAME}.${NAME} --top-name ${NAME} --target-dir ${VLOG_DIR}'
</code>```

However sbt/scala/chisel like to attempt to generate some sort of progress bars while building that emit terminal escape codes to attempt to update the output in place.  When run inside my shell this does not work very well, but when run inside emacs it makes a huge mess:

```<code>make
setsid sbt \
  'runMain HelloWorld.HelloWorld --top-name HelloWorld --target-dir Gen_HelloWor\
ld.verilog_dir'
^[[0m[^[[0m^[[0minfo^[[0m] ^[[0m^[[0mLoading project definition from /home/user/h\
ello-chisel/project^[[0m
^[[2K
^[[2K
^[[2K
^[[2K
^[[2K
^[[5A^[[2K
^[[2K
^[[2K
^[[2K
^[[2K
^[[2K  | => hello-chisel-build / update 0s
^[[6A^[[2K
^[[2K
</code>```

Especially when there is an error message:

```<code>^[[2K
^[[2K
^[[2K  | => hello-chisel / Compile / compileIncremental 1s
^[[6A^[[2K^[[0m[^[[0m^[[31merror^[[0m] ^[[0m^[[0m/home/user/hello-chisel/HelloWor\
ld.scala:46:17: overloaded method value apply with alternatives:^[[0m
^[[2K
</code>```

How do I turn all of that off and get normal looking output having clean error messages?

答:
Short answer

Pass -no-colors to sbt on the command line, per the
sbt FAQ:

```<code>$ sbt -no-colors 'test:runMain gcd.GCDMain'
</code>```

Despite the name "no colors", it suppresses all terminal escape stuff, including the progress bars.

Other alternatives

The option can also be spelled --no-colors (two hyphens), which is how it appears in the output of sbt --help (and sbt -help).

The same effect can be achieved by passing -Dsbt.log.noformat=true to sbt (or to java if invoking that directly) as indicated in this answer:

```<code>$ sbt -Dsbt.log.noformat=true 'test:runMain gcd.GCDMain'
</code>```

It can also be achieved by setting the JAVA_OPTS environment variable to -Dsbt.log.noformat=true:

```<code>$ JAVA_OPTS=-Dsbt.log.noformat=true sbt 'test:runMain gcd.GCDMain'
</code>```

If you are using sbt-launch.jar, then you have to use the -D switch because -no-colors is not recognized in that context (the sbt shell script is what recognizes -no-colors):

```<code>$ java -jar ~/opt/sbt-1.3.4/bin/sbt-launch.jar -Dsbt.log.noformat=true 'test:runMain gcd.GCDMain'
</code>```

Finally, when sbt detects that its stdout is not a TTY, it will suppress color output:

```<code>$ sbt 'test:runMain gcd.GCDMain' | cat
</code>```

That's not a good option in a Makefile though because you lose the exit status of sbt (without further shenanigans).

Unfortunately, sbt does not respect NO_COLOR.

Chisel output has some colors anyway

When using Chisel, for example the chisel template, even with -no-colors, some terminal escape codes appear in the output anyway:

```<code>$ sbt -no-colors 'test:runMain gcd.GCDMain' | cat -tev
[info] Loading settings for project chisel-template-build from plugins.sbt ...$
[info] Loading project definition from /home/scott/wrk/learn/chisel/chisel-template/project$
[info] Loading settings for project chisel-template from build.sbt ...$
[info] Set current project to chisel-module-template (in build file:/home/scott/wrk/learn/chisel/chisel-template/)$
[warn] Multiple main classes detected.  Run 'show discoveredMainClasses' to see the list$
[info] running gcd.GCDMain $
[^[[35minfo^[[0m] [0.001] Elaborating design...$
[^[[35minfo^[[0m] [1.064] Done elaborating.$
Total FIRRTL Compile Time: 512.0 ms$
file loaded in 0.114380184 seconds, 22 symbols, 17 statements$
[^[[35minfo^[[0m] [0.001] SEED 1581769687441$
test GCD Success: 168 tests passed in 1107 cycles in 0.047873 seconds 23123.91 Hz$
[^[[35minfo^[[0m] [0.037] RAN 1102 CYCLES PASSED$
[success] Total time: 3 s, completed Feb 15, 2020 4:28:09 AM$
</code>```

Note the [^[[35minfo^[[0m] output near the end.  This happens because chiselFrontend/src/main/scala/chisel3/internal/Error.scala unconditionally prints color escape sequences (see the tag function), which is arguably a bug in Chisel since its output is clearly meant to look similar to sbt output.

Effect of setsid

In your example Makefile, you're invoking sbt via setsid.  As far as I can tell, everything I've said applies equally to that circumstance.  However, you probably want to pass --wait to setsid so it will wait for sbt to complete before exiting.  In my testing, setsid will implicitly wait only when stdout is not a TTY, but I doubt you actually want that hidden variability.

Body:
When building chisel using sbt, when run as a batch process, how do I turn off the progress bars etc. so that the output is clean like I get with most compilers?

That is, I like to build chisel using sbt from within a makefile, like this:

${VLOG_DIR}/${NAME}.v: ${NAME}.scala
        setsid sbt \
          'runMain ${NAME}.${NAME} --top-name ${NAME} --target-dir ${VLOG_DIR}'

However sbt/scala/chisel like to attempt to generate some sort of progress bars while building that emit terminal escape codes to attempt to update the output in place.  When run inside my shell this does not work very well, but when run inside emacs it makes a huge mess:

make
setsid sbt \
  'runMain HelloWorld.HelloWorld --top-name HelloWorld --target-dir Gen_HelloWor\
ld.verilog_dir'
^[[0m[^[[0m^[[0minfo^[[0m] ^[[0m^[[0mLoading project definition from /home/user/h\
ello-chisel/project^[[0m
^[[2K
^[[2K
^[[2K
^[[2K
^[[2K
^[[5A^[[2K
^[[2K
^[[2K
^[[2K
^[[2K
^[[2K  | => hello-chisel-build / update 0s
^[[6A^[[2K
^[[2K

Especially when there is an error message:

^[[2K
^[[2K
^[[2K  | => hello-chisel / Compile / compileIncremental 1s
^[[6A^[[2K^[[0m[^[[0m^[[31merror^[[0m] ^[[0m^[[0m/home/user/hello-chisel/HelloWor\
ld.scala:46:17: overloaded method value apply with alternatives:^[[0m
^[[2K

How do I turn all of that off and get normal looking output having clean error messages?

Body:
Short answer

Pass -no-colors to sbt on the command line, per the
sbt FAQ:

$ sbt -no-colors 'test:runMain gcd.GCDMain'

Despite the name "no colors", it suppresses all terminal escape stuff, including the progress bars.

Other alternatives

The option can also be spelled --no-colors (two hyphens), which is how it appears in the output of sbt --help (and sbt -help).

The same effect can be achieved by passing -Dsbt.log.noformat=true to sbt (or to java if invoking that directly) as indicated in this answer:

$ sbt -Dsbt.log.noformat=true 'test:runMain gcd.GCDMain'

It can also be achieved by setting the JAVA_OPTS environment variable to -Dsbt.log.noformat=true:

$ JAVA_OPTS=-Dsbt.log.noformat=true sbt 'test:runMain gcd.GCDMain'

If you are using sbt-launch.jar, then you have to use the -D switch because -no-colors is not recognized in that context (the sbt shell script is what recognizes -no-colors):

$ java -jar ~/opt/sbt-1.3.4/bin/sbt-launch.jar -Dsbt.log.noformat=true 'test:runMain gcd.GCDMain'

Finally, when sbt detects that its stdout is not a TTY, it will suppress color output:

$ sbt 'test:runMain gcd.GCDMain' | cat

That's not a good option in a Makefile though because you lose the exit status of sbt (without further shenanigans).

Unfortunately, sbt does not respect NO_COLOR.

Chisel output has some colors anyway

When using Chisel, for example the chisel template, even with -no-colors, some terminal escape codes appear in the output anyway:

$ sbt -no-colors 'test:runMain gcd.GCDMain' | cat -tev
[info] Loading settings for project chisel-template-build from plugins.sbt ...$
[info] Loading project definition from /home/scott/wrk/learn/chisel/chisel-template/project$
[info] Loading settings for project chisel-template from build.sbt ...$
[info] Set current project to chisel-module-template (in build file:/home/scott/wrk/learn/chisel/chisel-template/)$
[warn] Multiple main classes detected.  Run 'show discoveredMainClasses' to see the list$
[info] running gcd.GCDMain $
[^[[35minfo^[[0m] [0.001] Elaborating design...$
[^[[35minfo^[[0m] [1.064] Done elaborating.$
Total FIRRTL Compile Time: 512.0 ms$
file loaded in 0.114380184 seconds, 22 symbols, 17 statements$
[^[[35minfo^[[0m] [0.001] SEED 1581769687441$
test GCD Success: 168 tests passed in 1107 cycles in 0.047873 seconds 23123.91 Hz$
[^[[35minfo^[[0m] [0.037] RAN 1102 CYCLES PASSED$
[success] Total time: 3 s, completed Feb 15, 2020 4:28:09 AM$

Note the [^[[35minfo^[[0m] output near the end.  This happens because chiselFrontend/src/main/scala/chisel3/internal/Error.scala unconditionally prints color escape sequences (see the tag function), which is arguably a bug in Chisel since its output is clearly meant to look similar to sbt output.

Effect of setsid

In your example Makefile, you're invoking sbt via setsid.  As far as I can tell, everything I've said applies equally to that circumstance.  However, you probably want to pass --wait to setsid so it will wait for sbt to complete before exiting.  In my testing, setsid will implicitly wait only when stdout is not a TTY, but I doubt you actually want that hidden variability.


答: There's no need for the cast there. In an assignment context, a widening reference conversion is allowed. No need for a casting context. (Now, if it were a narrowing reference conversion, you'd have to do that explicitly.)

Title: Upcast in Java Difference


问:
Parellel processes using fork() with command line parameters in C
I am trying to create a program that takes in command line a number of counts to do and does them in parallel.

I have one count.c file that is used to make the counting :

```<code>int main(int argc, char** argv)
{
   assert(argc>1);

   int length= atoi(argv[1]);
   assert(length>0);

   int pid = getpid();

   printf("%d : %s\n", pid, "start");

    for (unsigned int i=length; i>0; i--)
    {
      printf("%d : %d\n", pid, i);

      sleep(1);
    }

    printf("%d : %s\n", pid, "done");

    return 0;
}
</code>```

so if I enter "./count 5" in the bash, the program counts from 5 to 1.

I have another multiple.c file :

```<code>int main(int argc, char** argv)
{
   assert(argc>2);
   unsigned int i;

   char * nameExec = (char*) malloc(sizeof(char)*(strlen(argv[1])-1));

   char * time;

   int number = argc-2; // number of counting to do

    // name of programm
    for (i=2; i<strlen(argv[1]); i++)
    {
      nameExec[i-2]=argv[1][i];
    }
    nameExec[i-2]='\0';

    if(number==1) //  one counting there is no fork needed
    {
      execl(argv[1], nameExec, argv[2], NULL);
    } else
    {
      for (unsigned int i=2; i<number+1; i++) // if we have 2 counts to do, then we need 1 fork, if there is 3 counts to do then there is 2 forks...
      {
        if(fork()==0) // child process
        {
          time = argv[i];
        } else
        {
          time = argv[i+1];
          wait(NULL); // father process waits for child
        }

      }

      execl(argv[1], nameExec, time, NULL);

    }

    return 0;
}
</code>```

what I want to do with this program is that I enter in the command line I enter for instance "./multiple ./count 5 4 3" and that it starts 3 counts in parallel (3 parallel processes).

Tests I have done :
If I enter ./multiple ./count 5 4 it does two counts, one starting from 5 and the other from 4, but not simultaneously, one after the other.
If I enter ./multiple ./count 5 4 3 it does 4 counts, one starting from 4, then one starting from 3, then another one starting from 4, and another one starting from 3.

I really don't understand this behavior,
From what I understand, fork() is used to duplicate the process, and execl abandons the current process and start executing another one.

Please help!

(Also, I am trying to understand the use of fork() and execl(), so I would like to find I way to answer my problem using these two functions).

答:
First, if you analize the code in multiple.c, you'll see that it is composed of only a main if(){...}else{...} in which, in the then side, you make a single exec if argc == 2 (which is correct, if you just want to save a fork() call, but complicates things and makes you make mistakes) and in the else part, you have only one execl() call, after the for loop is fully executed.

First, you never do a fork() before the wait() calls you do in the loop, so all of them return -1 with an error of ENOCHLD.

you must put the fork()s and the execl()s inside the for loop, so a full new process is spawn for each parameter.

you do a lot of extra work in the arguments list to process it as you have it.  It is far better to specify the program to run as an option (-r could be a good one) and use a default program in case you don't specify one.  Using getopt(3) will be a good selection and will make your program more unix professional.

Below is an example of what I say:

count.c

```<code>/* YOU NEED TO POST COMPLETE, COMPILABLE CODE, DON'T TAKE OFF
 * YOUR INCLUDE FILES TO POST, AS SOME ERRORS CAN COME FROM THE
 * FACT THAT YOU HAVE FORGOTTEN TO #include THEM.  */
#include <assert.h> /* for assert */
#include <stdio.h>  /* for printf and stdio functions */
#include <stdlib.h> /* for atoi */
#include <unistd.h> /* for getpid() */

int main(int argc, char** argv)
{
   assert(argc == 2);

   int length= atoi(argv[1]);
   assert(length>0);

   int pid = getpid();

   printf("%d : %s\n", pid, "start");

   for (unsigned int i=length; i>0; i--)
   {
      printf("%d : %d\n", pid, i);

      sleep(1);
   }

   printf("%d : %s\n", pid, "done");

   return 0;
}

</code>```

multiple.c

```<code>/* SAME AS BEFORE :) */

#include <errno.h> /* for errno */
#include <stdio.h> /* for printf() and others */
#include <stdlib.h> /* for many standard functions */
#include <string.h> /* for strerror() */
#include <sys/wait.h> /* for wait() */
#include <unistd.h> /* for getpid() */
#include <getopt.h> /* for getopt() */

pid_t pid;

/* create the format string for printf with a pretty header,
 * showing pid, source file, source line, source function,
 * and the provided format string. */
#define F(_fmt) "[pid=%d]:"__FILE__":%d:%s: "_fmt,pid,__LINE__,__func__

/* fatal error macro */
#define ERROR(str) do {\
                fprintf(stderr, F("%s: %s\n"),\
                        (str), strerror(errno));\
                exit(EXIT_FAILURE);\
        } while(0)

int main(int argc, char** argv)
{
        char *program = "./a.out";  /* defaults to a.out in local dir */
        int opt;

        /* getopt use.  See getopt(3) for instructions */
        while ((opt = getopt(argc, argv, "r:")) != EOF) {
                switch (opt) {
                case 'r': program = optarg; break;
                }
        }

        /* shift all the processed parameters out */
        argc -= optind; argv += optind;

        /* get our pid to use in traces */
        pid = getpid();

        if (argc == 1) {
                /* only one parameter, save the fork() call */
                printf(F("about to exec: %s %s\n"),
                        program, argv[0]);
                execlp(program,
                        program, argv[0], NULL);
                ERROR("execlp()");
                /* NOTREACHED */
        } else {
                pid_t chld;
                int i;
                for (i = 0; i < argc; i++) {
                        chld = fork();
                        if (chld < 0) {
                                ERROR("fork()");
                                /* NOTREACHED */
                        }
                        if (!chld) { /* child */
                                printf(F("about to call: %s %s\n"),
                                        program, argv[i]);
                                execlp(program,
                                        program, argv[i], NULL);
                                ERROR("execlp()");
                                /* NOTREACHED */
                        }
                }
                /* NOW, AFTER ALL FORKS/EXECS HAVE BEEN DONE,
                 * JUST DO ALL THE WAITS.  wait() gives an
                 * error if no children exist to wait for, so
                 * we wait() until we get an error here.  */
                int status;
                while ((chld = wait(&status)) > 0) {
                        /* just change this printf to a continue;
                         * if you don't want to print the result. */
                        printf(F("wait() => child %d (status = %d)\n"),
                                chld, status);
                }
        }
        printf("%d: END OF PROGRAM\n", pid);
}
</code>```

Finaly, one run:

```<code>$ multiple -r count 3 5 2
[pid=78790]:multiple.c:61:main: about to call: count 3
[pid=78790]:multiple.c:61:main: about to call: count 2
78791 : start
78791 : 3
[pid=78790]:multiple.c:61:main: about to call: count 5
78793 : start
78793 : 2
78792 : start
78792 : 5
78791 : 2
78792 : 4
78793 : 1
78791 : 1
78792 : 3
78793 : done
[pid=78790]:multiple.c:77:main: wait() => child 78793 (status = 0)
78791 : done
78792 : 2
[pid=78790]:multiple.c:77:main: wait() => child 78791 (status = 0)
78792 : 1
78792 : done
[pid=78790]:multiple.c:77:main: wait() => child 78792 (status = 0)
78790: END OF PROGRAM
$ _
</code>```

the code presented above is available for download here

Body:
I am trying to create a program that takes in command line a number of counts to do and does them in parallel.

I have one count.c file that is used to make the counting :

int main(int argc, char** argv)
{
   assert(argc>1);

   int length= atoi(argv[1]);
   assert(length>0);

   int pid = getpid();

   printf("%d : %s\n", pid, "start");

    for (unsigned int i=length; i>0; i--)
    {
      printf("%d : %d\n", pid, i);

      sleep(1);
    }

    printf("%d : %s\n", pid, "done");

    return 0;
}

so if I enter "./count 5" in the bash, the program counts from 5 to 1.

I have another multiple.c file :

int main(int argc, char** argv)
{
   assert(argc>2);
   unsigned int i;

   char * nameExec = (char*) malloc(sizeof(char)*(strlen(argv[1])-1));

   char * time;

   int number = argc-2; // number of counting to do

    // name of programm
    for (i=2; i<strlen(argv[1]); i++)
    {
      nameExec[i-2]=argv[1][i];
    }
    nameExec[i-2]='\0';

    if(number==1) //  one counting there is no fork needed
    {
      execl(argv[1], nameExec, argv[2], NULL);
    } else
    {
      for (unsigned int i=2; i<number+1; i++) // if we have 2 counts to do, then we need 1 fork, if there is 3 counts to do then there is 2 forks...
      {
        if(fork()==0) // child process
        {
          time = argv[i];
        } else
        {
          time = argv[i+1];
          wait(NULL); // father process waits for child
        }

      }

      execl(argv[1], nameExec, time, NULL);

    }

    return 0;
}

what I want to do with this program is that I enter in the command line I enter for instance "./multiple ./count 5 4 3" and that it starts 3 counts in parallel (3 parallel processes).

Tests I have done :
If I enter ./multiple ./count 5 4 it does two counts, one starting from 5 and the other from 4, but not simultaneously, one after the other.
If I enter ./multiple ./count 5 4 3 it does 4 counts, one starting from 4, then one starting from 3, then another one starting from 4, and another one starting from 3.

I really don't understand this behavior,
From what I understand, fork() is used to duplicate the process, and execl abandons the current process and start executing another one.

Please help!

(Also, I am trying to understand the use of fork() and execl(), so I would like to find I way to answer my problem using these two functions).

Body:
First, if you analize the code in multiple.c, you'll see that it is composed of only a main if(){...}else{...} in which, in the then side, you make a single exec if argc == 2 (which is correct, if you just want to save a fork() call, but complicates things and makes you make mistakes) and in the else part, you have only one execl() call, after the for loop is fully executed.

First, you never do a fork() before the wait() calls you do in the loop, so all of them return -1 with an error of ENOCHLD.

you must put the fork()s and the execl()s inside the for loop, so a full new process is spawn for each parameter.

you do a lot of extra work in the arguments list to process it as you have it.  It is far better to specify the program to run as an option (-r could be a good one) and use a default program in case you don't specify one.  Using getopt(3) will be a good selection and will make your program more unix professional.

Below is an example of what I say:

count.c

/* YOU NEED TO POST COMPLETE, COMPILABLE CODE, DON'T TAKE OFF
 * YOUR INCLUDE FILES TO POST, AS SOME ERRORS CAN COME FROM THE
 * FACT THAT YOU HAVE FORGOTTEN TO #include THEM.  */
#include <assert.h> /* for assert */
#include <stdio.h>  /* for printf and stdio functions */
#include <stdlib.h> /* for atoi */
#include <unistd.h> /* for getpid() */

int main(int argc, char** argv)
{
   assert(argc == 2);

   int length= atoi(argv[1]);
   assert(length>0);

   int pid = getpid();

   printf("%d : %s\n", pid, "start");

   for (unsigned int i=length; i>0; i--)
   {
      printf("%d : %d\n", pid, i);

      sleep(1);
   }

   printf("%d : %s\n", pid, "done");

   return 0;
}

multiple.c

/* SAME AS BEFORE :) */

#include <errno.h> /* for errno */
#include <stdio.h> /* for printf() and others */
#include <stdlib.h> /* for many standard functions */
#include <string.h> /* for strerror() */
#include <sys/wait.h> /* for wait() */
#include <unistd.h> /* for getpid() */
#include <getopt.h> /* for getopt() */

pid_t pid;

/* create the format string for printf with a pretty header,
 * showing pid, source file, source line, source function,
 * and the provided format string. */
#define F(_fmt) "[pid=%d]:"__FILE__":%d:%s: "_fmt,pid,__LINE__,__func__

/* fatal error macro */
#define ERROR(str) do {\
                fprintf(stderr, F("%s: %s\n"),\
                        (str), strerror(errno));\
                exit(EXIT_FAILURE);\
        } while(0)

int main(int argc, char** argv)
{
        char *program = "./a.out";  /* defaults to a.out in local dir */
        int opt;

        /* getopt use.  See getopt(3) for instructions */
        while ((opt = getopt(argc, argv, "r:")) != EOF) {
                switch (opt) {
                case 'r': program = optarg; break;
                }
        }

        /* shift all the processed parameters out */
        argc -= optind; argv += optind;

        /* get our pid to use in traces */
        pid = getpid();

        if (argc == 1) {
                /* only one parameter, save the fork() call */
                printf(F("about to exec: %s %s\n"),
                        program, argv[0]);
                execlp(program,
                        program, argv[0], NULL);
                ERROR("execlp()");
                /* NOTREACHED */
        } else {
                pid_t chld;
                int i;
                for (i = 0; i < argc; i++) {
                        chld = fork();
                        if (chld < 0) {
                                ERROR("fork()");
                                /* NOTREACHED */
                        }
                        if (!chld) { /* child */
                                printf(F("about to call: %s %s\n"),
                                        program, argv[i]);
                                execlp(program,
                                        program, argv[i], NULL);
                                ERROR("execlp()");
                                /* NOTREACHED */
                        }
                }
                /* NOW, AFTER ALL FORKS/EXECS HAVE BEEN DONE,
                 * JUST DO ALL THE WAITS.  wait() gives an
                 * error if no children exist to wait for, so
                 * we wait() until we get an error here.  */
                int status;
                while ((chld = wait(&status)) > 0) {
                        /* just change this printf to a continue;
                         * if you don't want to print the result. */
                        printf(F("wait() => child %d (status = %d)\n"),
                                chld, status);
                }
        }
        printf("%d: END OF PROGRAM\n", pid);
}

Finaly, one run:

$ multiple -r count 3 5 2
[pid=78790]:multiple.c:61:main: about to call: count 3
[pid=78790]:multiple.c:61:main: about to call: count 2
78791 : start
78791 : 3
[pid=78790]:multiple.c:61:main: about to call: count 5
78793 : start
78793 : 2
78792 : start
78792 : 5
78791 : 2
78792 : 4
78793 : 1
78791 : 1
78792 : 3
78793 : done
[pid=78790]:multiple.c:77:main: wait() => child 78793 (status = 0)
78791 : done
78792 : 2
[pid=78790]:multiple.c:77:main: wait() => child 78791 (status = 0)
78792 : 1
78792 : done
[pid=78790]:multiple.c:77:main: wait() => child 78792 (status = 0)
78790: END OF PROGRAM
$ _

the code presented above is available for download here


问:
Form submissions lose idempotency when submitted rapidly in a row
I had a problem with people double clicking my form submit button and it submitting multiple times, so I wanted to allow only one submission. My first thought was javascript, but that's not absolutely instantaneous and I wanted something 100% guaranteed to work.

My solution was to make submissions idempotent, by giving each form load its own hash, and on each submission, checking whether that hash already exists, and if it does, not doing anything.

So this is the gist of my code:

```<code>#form
@hash = SecureRandom.urlsafe_base64(20)
f.hidden_field :hash, value: @hash
f.submit "submit"

#controller
existing = Submission.find_by(hash: params[:hash])
if existing.nil?
  #enter new Submission into the database with hash: params[:hash]
</code>```

This works if I allow some time between submissions, but when I do a double click on the submit button, two records are entered into my database, with the same hash value.

I'm using a simple Puma 3.7 server on localhost. I was under the impression that most servers would receive a request, execute it, then move on to the next request, but it's almost like there's some type of parallelism going on.

My question is: how is this possible? Each subsequent record has an ID value one greater than the previous record, so it's not like the server didn't know about the previous record. So how is it that if the requests are sent very rapidly, the unique hash requirement is ignored? Again, if I try again later with the same hash, nothing happens, as expected.

答:
Just use Rack::Throttle instead of reinventing the wheel.

```<code># config/application.rb
require 'rack/throttle'

class Application < Rails::Application
  config.middleware.use Rack::Throttle::Interval
end
</code>```

This applies a 1 second minimum interval between requests from the same client. You can customize this with the min: option.

This can be combined with javascript debouncing/throttling which will further reduce the load on your server (and the client).

I'm using a simple Puma 3.7 server on localhost. I was under the
  impression that most servers would receive a request, execute it, then
  move on to the next request, but it's almost like there's some type of
  parallelism going on.

Puma is multi-threaded. While you can configure it to be single-threaded, Ruby has mostly blocking IO so a single-threaded web server performs poorly under load.

My question is: how is this possible? Each subsequent record has an ID
  value one greater than the previous record, so it's not like the
  server didn't know about the previous record. So how is it that if the
  requests are sent very rapidly, the unique hash requirement is
  ignored?

Race conditions. What you are doing is an application level uniqueness validation where you run a query against the database and then later insert a row into the database.

If two (or more) processes are responding to duplicate requests at the exact same time both will get a green light by the Submission.find_by(hash: params[:hash]) query and then proceed to insert a record.

This is a well known issue with application validations in any language/framework and can be solved by adding a unique index in the database which will cause the database to reject the duplicate insert statement. This will raise a database driver error in Rails.

But I still believe that this should be handled on the middleware level.

Body:
I had a problem with people double clicking my form submit button and it submitting multiple times, so I wanted to allow only one submission. My first thought was javascript, but that's not absolutely instantaneous and I wanted something 100% guaranteed to work.

My solution was to make submissions idempotent, by giving each form load its own hash, and on each submission, checking whether that hash already exists, and if it does, not doing anything.

So this is the gist of my code:

#form
@hash = SecureRandom.urlsafe_base64(20)
f.hidden_field :hash, value: @hash
f.submit "submit"

#controller
existing = Submission.find_by(hash: params[:hash])
if existing.nil?
  #enter new Submission into the database with hash: params[:hash]

This works if I allow some time between submissions, but when I do a double click on the submit button, two records are entered into my database, with the same hash value.

I'm using a simple Puma 3.7 server on localhost. I was under the impression that most servers would receive a request, execute it, then move on to the next request, but it's almost like there's some type of parallelism going on.

My question is: how is this possible? Each subsequent record has an ID value one greater than the previous record, so it's not like the server didn't know about the previous record. So how is it that if the requests are sent very rapidly, the unique hash requirement is ignored? Again, if I try again later with the same hash, nothing happens, as expected.

Body:
Just use Rack::Throttle instead of reinventing the wheel.

# config/application.rb
require 'rack/throttle'

class Application < Rails::Application
  config.middleware.use Rack::Throttle::Interval
end

This applies a 1 second minimum interval between requests from the same client. You can customize this with the min: option.

This can be combined with javascript debouncing/throttling which will further reduce the load on your server (and the client).

I'm using a simple Puma 3.7 server on localhost. I was under the
  impression that most servers would receive a request, execute it, then
  move on to the next request, but it's almost like there's some type of
  parallelism going on.

Puma is multi-threaded. While you can configure it to be single-threaded, Ruby has mostly blocking IO so a single-threaded web server performs poorly under load.

My question is: how is this possible? Each subsequent record has an ID
  value one greater than the previous record, so it's not like the
  server didn't know about the previous record. So how is it that if the
  requests are sent very rapidly, the unique hash requirement is
  ignored?

Race conditions. What you are doing is an application level uniqueness validation where you run a query against the database and then later insert a row into the database.

If two (or more) processes are responding to duplicate requests at the exact same time both will get a green light by the Submission.find_by(hash: params[:hash]) query and then proceed to insert a record.

This is a well known issue with application validations in any language/framework and can be solved by adding a unique index in the database which will cause the database to reject the duplicate insert statement. This will raise a database driver error in Rails.

But I still believe that this should be handled on the middleware level.


问:
file renaming/deleting
I have a few files like this-

*.sss and  *_passive.sss

If I have a file called blah1.sss and blah1_passive.sss, i want to get rid of blah1.sss and rename blah1_passive.sss. However, if I don't have blah1_passive.sss I want to log the filename and keep blah1.sss.

I was able to locate all the *_passive.sss files but I would like to know the awk/sed etc command that could rename the *_passive.sss to *.sss.

Edit: Right now i have this but os.rename does not overwrite files, i need it to overwrite though.

```<code>import os, fnmatch

def locate(pattern, root=os.curdir):

    #ignore directories- uncomment to make ignore work
    #ignored = ["0201", "0306"]
  for path, dirs, files in os.walk(os.path.abspath(root)):
         #for dir in ignored:                  # if dir in dirs:                        #dirs.remove(dir)
    for filename in fnmatch.filter(files, pattern):
       yield os.path.join(path, filename)

for filename in locate("*_passive.sss"):
               #found the files that i want to rename, but os.rename() refuses to overwrite !!
    newfilename=filename.rstrip("_passive.sss") + ".sss"
    os.rename(filename,newfilename)
</code>```

答:
This shell script shoul do the trick:

```<code>while read f; do
    fp="`echo "$f" | sed -nr 's|(.*)(\.sss)|\1_passive\2| p'`"
    if [ -f "$fp" ]; then mv "$fp" "$f"
    else  echo "file $fp missing" >> missing.log
    fi
done<<<"`ls -1 *.sss | grep -v _passive.sss`"
</code>```

also will report missing _passive files to missing.log

Title: file renaming/deleting

Body:
I have a few files like this-

*.sss and  *_passive.sss

If I have a file called blah1.sss and blah1_passive.sss, i want to get rid of blah1.sss and rename blah1_passive.sss. However, if I don't have blah1_passive.sss I want to log the filename and keep blah1.sss.

I was able to locate all the *_passive.sss files but I would like to know the awk/sed etc command that could rename the *_passive.sss to *.sss.

Edit: Right now i have this but os.rename does not overwrite files, i need it to overwrite though.

import os, fnmatch

def locate(pattern, root=os.curdir):

    #ignore directories- uncomment to make ignore work
    #ignored = ["0201", "0306"]
  for path, dirs, files in os.walk(os.path.abspath(root)):
         #for dir in ignored:                  # if dir in dirs:                        #dirs.remove(dir)
    for filename in fnmatch.filter(files, pattern):
       yield os.path.join(path, filename)

for filename in locate("*_passive.sss"):
               #found the files that i want to rename, but os.rename() refuses to overwrite !!
    newfilename=filename.rstrip("_passive.sss") + ".sss"
    os.rename(filename,newfilename)

Body:
This shell script shoul do the trick:

while read f; do
    fp="`echo "$f" | sed -nr 's|(.*)(\.sss)|\1_passive\2| p'`"
    if [ -f "$fp" ]; then mv "$fp" "$f"
    else  echo "file $fp missing" >> missing.log
    fi
done<<<"`ls -1 *.sss | grep -v _passive.sss`"

also will report missing _passive files to missing.log


问:
How to mock test with ` func(w http.ResponseWriter, r *http.Request) `
I got problem when I want to get the respond body from my mocking,
currently I have create some mock like this :

```<code>func (m *MockCarService) GetCar(ctx context.Context, store store.Store, IDCar uint) (interface{}, error) {

    call := m.Called(ctx, store)
    res := call.Get(0)
    if res == nil {
        return nil, call.Error(1)
    }
    return res.(*models.Cars), call.Error(1)
}
</code>```

Then I create handler_test.go like this :

```<code>func TestGetCar(t *testing.T) {

    var store store.Store

    car := &models.Cars{
        ID:          12345,
        BrandID:     1,
        Name:        "Car abc",
        Budget:      2000,
        CostPerMile: 4000,
        KpiReach:    6000,
    }

    mockService := func() *service.MockCarService {
        svc := &service.MockCarService{}
        svc.On("GetCar", context.Background(), car.ID).Return(car, nil)
        return svc
    }

    handlerGet := NewCarHandler(mockService())
    actualResponse := handlerGet.GetCar(store)

    expected := `{"success":true,"data":[],"errors":[]}`
    assert.Equal(t, expected+"\n", actualResponse)
}
</code>```

What I got is some error (http.HandlerFunc)(0x165e020) (cannot take func type as argument)

I have no idea how to fix it. Since I'm using handler like this :

```<code>func (ah *CampaignHandler) GetCampaigns(store store.Store) func(w http.ResponseWriter, r *http.Request) {
    return func(w http.ResponseWriter, r *http.Request) {  .....
</code>```

答:
If you are making a HTTP call to an external service and wish to test that and get mock response, you can use httptest

http package in go comes with httptest to test all your external http call dependencies.

Please find an example here : https://golang.org/src/net/http/httptest/example_test.go

If this is not your usecase, it is better to use stubs and the way to do it can be found here : https://dev.to/jonfriesen/mocking-dependencies-in-go-1h4d

Basically, what is means is to use interface and have your own struct and stubbed function calls which will return the response you want.

If you want to add some syntactic sugar to your tests, you can use testify : https://github.com/stretchr/testify

Hope this helps.

Body:
I got problem when I want to get the respond body from my mocking,
currently I have create some mock like this :

func (m *MockCarService) GetCar(ctx context.Context, store store.Store, IDCar uint) (interface{}, error) {

    call := m.Called(ctx, store)
    res := call.Get(0)
    if res == nil {
        return nil, call.Error(1)
    }
    return res.(*models.Cars), call.Error(1)
}

Then I create handler_test.go like this :

func TestGetCar(t *testing.T) {

    var store store.Store

    car := &models.Cars{
        ID:          12345,
        BrandID:     1,
        Name:        "Car abc",
        Budget:      2000,
        CostPerMile: 4000,
        KpiReach:    6000,
    }

    mockService := func() *service.MockCarService {
        svc := &service.MockCarService{}
        svc.On("GetCar", context.Background(), car.ID).Return(car, nil)
        return svc
    }

    handlerGet := NewCarHandler(mockService())
    actualResponse := handlerGet.GetCar(store)

    expected := `{"success":true,"data":[],"errors":[]}`
    assert.Equal(t, expected+"\n", actualResponse)
}

What I got is some error (http.HandlerFunc)(0x165e020) (cannot take func type as argument)

I have no idea how to fix it. Since I'm using handler like this :

func (ah *CampaignHandler) GetCampaigns(store store.Store) func(w http.ResponseWriter, r *http.Request) {
    return func(w http.ResponseWriter, r *http.Request) {  .....


问:
How do I make new Google Search look like old Google Search using CSS or JavaScript?
So I am trying to make the new Google Search results look like the old Google Search results.

The new design has the domain link above the page title which is really confusing.  The domain link also used to be colored green which made the search results page much easier to read but now it isn't.

This is how I want the Google Search results page to look like:

So, as you can see, the weblink is green and positioned under the title for each result.  This is what I want.

So I have created an extension and so far I have changed the color of the domain link to green (as it used to be) using just CSS:

```<code>.iUh30{
    color:green !important;
}
</code>```

However, I want this domain link to be below the search title (as it used to be).

Is it possible to do this using CSS or JavaScript in my extension?

There is an existing extension here:

https://chrome.google.com/webstore/detail/bring-classic-back/klnhfpnhipgjannlklfcnhonncppnoae

But it doesn't work properly with the latest update from Google.

Thank you for reading.

Update:
I can achieve most of what I want by using this for my CSS file:

```<code>.iUh30{
    color:green !important;
}

.NJjxre {
    position: relative !important;
    width: 1000px;
}
</code>```

That displays the weblink perfectly.  The only problem is the dropdown menu (used for selecting cached pages).  How can I move this dropdown menu to the right of the green weblink (or remove it completely without leaving any vacant space where it would normally be?)

答:
Edit: My original answer is below.  However, since I made this answer, I have started using a Chrome extension called Make Google search great again which has been working great.  So I suggest you install that.

So I solved this (for the moment) with the extension code I will post below.  The code is based on a TamperMonkey script which you can see here.  So if you use TamperMonkey, there is no need to create an extension at all as the script works at this moment in time.

But if you prefer to create an extension for this, here is the code that I am using.

Note that the below works with Google.co.uk only.  If you use another Google country domain, change the matches and exclude_matches sections in manifest.json accordindly.

styles.css

```<code>.NJjxre {position: relative !important;}
.btrG {word-break: break-all; line-height: 18px;}
.btrG .btrAdd { display: inline-block; vertical-align: top;}
.btrG .btrLink {display: inline-block; vertical-align: top; line-height: 18px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-decoration: none !important;}
.btrG .btrLink cite.iUh30 {color: #006621; font-size: 16px;}
.B6fmyf {display:none;}
</code>```

manifest.json

```<code>{

    "manifest_version": 2,

    "name": "Google Search Classic",
    "version": "1.0.0",
    "description": "Classic Google Search.",

    "icons": {
           "48": "icon1.png",
          "128": "icon2.png"
    },

    "content_scripts": [{
        "css": ["styles.css"],
        "js": ["content.js"],
        "matches": ["https://www.google.co.uk/*"],
        "exclude_matches": ["https://www.google.co.uk/*tbm=vid*"],
        "run_at": "document_end"
    }]

}
</code>```

content.js

```<code>var el = document.querySelector('#rcnt');
if (el != null){document.querySelectorAll('.g .rc').forEach(function(el){

    var tbwUpd = el.querySelectorAll('.TbwUpd');
    if (tbwUpd.length > 0){

        var linkEl = el.querySelector('.r > a');
        var addEl = linkEl.nextSibling;
        var betterAddEl = document.createElement('div');
        betterAddEl.className = 'btrAdd';

        if (addEl){
            for (var i = 0; i < addEl.children.length; i++) {
                var _el = addEl.children[i];
                if (_el.className.indexOf('TbwUpd') == -1) {
                    betterAddEl.appendChild(_el);
                }
            }
        }

        var betterEl = document.createElement('div');
        betterEl.className = 'btrG';
        betterEl.appendChild(betterAddEl);

        el.querySelector('.r').appendChild(betterEl);

        var urlEl = document.createElement('a');
        urlEl.href = linkEl.href;
        urlEl.target = '_blank';
        urlEl.className = 'btrLink';

        var urlCiteEl = document.createElement('cite');
        urlCiteEl.innerText = linkEl.href;
        urlCiteEl.className = 'iUh30 bc';
        urlEl.appendChild(urlCiteEl);

        var maxWidth = el.clientWidth - betterAddEl.offsetWidth - 10;

        betterEl.insertBefore(urlEl, betterAddEl);
        if (urlEl.offsetWidth > maxWidth){
            urlEl.style.width = maxWidth.toString() + 'px';
        }

        tbwUpd.forEach(function(el){el.remove()});
        linkEl.querySelector('br:first-child').remove();

    }

});}
</code>```

Just put the above into a new folder, add icon1.png and icon2.png and use Chrome to pack it into an extension.  To avoid the Chrome developer warning, use the packed extension (not the unpacked one) and whitelist the extension ID in the registry.

The only downside to this is a small delay while the search results are reformatted.  Also the Ad results are not formatted but I don't think that matters since they are only ads.

Body:
So I am trying to make the new Google Search results look like the old Google Search results.

The new design has the domain link above the page title which is really confusing.  The domain link also used to be colored green which made the search results page much easier to read but now it isn't.

This is how I want the Google Search results page to look like:

So, as you can see, the weblink is green and positioned under the title for each result.  This is what I want.

So I have created an extension and so far I have changed the color of the domain link to green (as it used to be) using just CSS:

.iUh30{
    color:green !important;
}

However, I want this domain link to be below the search title (as it used to be).

Is it possible to do this using CSS or JavaScript in my extension?

There is an existing extension here:

https://chrome.google.com/webstore/detail/bring-classic-back/klnhfpnhipgjannlklfcnhonncppnoae

But it doesn't work properly with the latest update from Google.

Thank you for reading.

Update:
I can achieve most of what I want by using this for my CSS file:

.iUh30{
    color:green !important;
}

.NJjxre {
    position: relative !important;
    width: 1000px;
}

That displays the weblink perfectly.  The only problem is the dropdown menu (used for selecting cached pages).  How can I move this dropdown menu to the right of the green weblink (or remove it completely without leaving any vacant space where it would normally be?)

Body:
Edit: My original answer is below.  However, since I made this answer, I have started using a Chrome extension called Make Google search great again which has been working great.  So I suggest you install that.

So I solved this (for the moment) with the extension code I will post below.  The code is based on a TamperMonkey script which you can see here.  So if you use TamperMonkey, there is no need to create an extension at all as the script works at this moment in time.

But if you prefer to create an extension for this, here is the code that I am using.

Note that the below works with Google.co.uk only.  If you use another Google country domain, change the matches and exclude_matches sections in manifest.json accordindly.

styles.css

.NJjxre {position: relative !important;}
.btrG {word-break: break-all; line-height: 18px;}
.btrG .btrAdd { display: inline-block; vertical-align: top;}
.btrG .btrLink {display: inline-block; vertical-align: top; line-height: 18px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-decoration: none !important;}
.btrG .btrLink cite.iUh30 {color: #006621; font-size: 16px;}
.B6fmyf {display:none;}

manifest.json

{

    "manifest_version": 2,

    "name": "Google Search Classic",
    "version": "1.0.0",
    "description": "Classic Google Search.",

    "icons": {
           "48": "icon1.png",
          "128": "icon2.png"
    },

    "content_scripts": [{
        "css": ["styles.css"],
        "js": ["content.js"],
        "matches": ["https://www.google.co.uk/*"],
        "exclude_matches": ["https://www.google.co.uk/*tbm=vid*"],
        "run_at": "document_end"
    }]

}

content.js

var el = document.querySelector('#rcnt');
if (el != null){document.querySelectorAll('.g .rc').forEach(function(el){

    var tbwUpd = el.querySelectorAll('.TbwUpd');
    if (tbwUpd.length > 0){

        var linkEl = el.querySelector('.r > a');
        var addEl = linkEl.nextSibling;
        var betterAddEl = document.createElement('div');
        betterAddEl.className = 'btrAdd';

        if (addEl){
            for (var i = 0; i < addEl.children.length; i++) {
                var _el = addEl.children[i];
                if (_el.className.indexOf('TbwUpd') == -1) {
                    betterAddEl.appendChild(_el);
                }
            }
        }

        var betterEl = document.createElement('div');
        betterEl.className = 'btrG';
        betterEl.appendChild(betterAddEl);

        el.querySelector('.r').appendChild(betterEl);

        var urlEl = document.createElement('a');
        urlEl.href = linkEl.href;
        urlEl.target = '_blank';
        urlEl.className = 'btrLink';

        var urlCiteEl = document.createElement('cite');
        urlCiteEl.innerText = linkEl.href;
        urlCiteEl.className = 'iUh30 bc';
        urlEl.appendChild(urlCiteEl);

        var maxWidth = el.clientWidth - betterAddEl.offsetWidth - 10;

        betterEl.insertBefore(urlEl, betterAddEl);
        if (urlEl.offsetWidth > maxWidth){
            urlEl.style.width = maxWidth.toString() + 'px';
        }

        tbwUpd.forEach(function(el){el.remove()});
        linkEl.querySelector('br:first-child').remove();

    }

});}

Just put the above into a new folder, add icon1.png and icon2.png and use Chrome to pack it into an extension.  To avoid the Chrome developer warning, use the packed extension (not the unpacked one) and whitelist the extension ID in the registry.

The only downside to this is a small delay while the search results are reformatted.  Also the Ad results are not formatted but I don't think that matters since they are only ads.


问:
If Statement If A2 is Empty Dont Run Code - else run code if A2 has Data - Google Apps Script / GoogleSheets
I have tried to get this if statement to run as I am not yet experienced enough to know what I am doing wrong. (it runs perfectly if I manually run the script)

Expected result = if A2 has data - run the below code. if A2 is blank - dont run the code.

```<code>function IfStatement() {
var app = SpreadsheetApp;
var activeSheet = app.getActive().getActiveSheet();
var workingCell = activeSheet.getRange(2, 1).getValue();

if(workingCell === ""){
}

function kk() {
var sheet = SpreadsheetApp.getActive();
sheet.setActiveSheet(sheet.getSheetByName('TOP UP NEEDED'), true);
sheet.getRange('D2').activate();
sheet.getCurrentCell().setFormula('=QUERY({\'SKU & Qty\'!$A$3:$C},"SELECT * WHERE Col1 MATCHES \'" &
JOIN("|",FILTER(A:A, NOT(ISBLANK(A:A)))) & "\' ")');
addCheckboxToI2();
}}

Hoping I was close !
</code>```

答:
Do you mean something like this?

```<code>function doSomething() {

var app = SpreadsheetApp;

var activeSheet = app.getActive().getActiveSheet();
var workingCell = activeSheet.getRange(2, 1).getValue();

var otherSheet = app.getActive().getSheetByName('TOP UP NEEDED');
var otherCell = otherSheet.getRange('D2');

var formula = '=QUERY({\'SKU & Qty\'!$A$3:$C},"SELECT * WHERE Col1 MATCHES \'" & JOIN("|",FILTER(A:A, NOT(ISBLANK(A:A)))) & "\' ")';

  if(workingCell == ""){

  }
  else{

  otherCell.setFormula(formula);

  }

//addCheckboxToI2();
//ReferenceError: 'addCheckboxToI2' is niet gedefinieerd. (regel x, bestand 'y')

}
</code>```

I have some doubts about the formula but do not know enough of formula's to say something helpful about that.

Body:
I have tried to get this if statement to run as I am not yet experienced enough to know what I am doing wrong. (it runs perfectly if I manually run the script)

Expected result = if A2 has data - run the below code. if A2 is blank - dont run the code.

function IfStatement() {
var app = SpreadsheetApp;
var activeSheet = app.getActive().getActiveSheet();
var workingCell = activeSheet.getRange(2, 1).getValue();

if(workingCell === ""){
}

function kk() {
var sheet = SpreadsheetApp.getActive();
sheet.setActiveSheet(sheet.getSheetByName('TOP UP NEEDED'), true);
sheet.getRange('D2').activate();
sheet.getCurrentCell().setFormula('=QUERY({\'SKU & Qty\'!$A$3:$C},"SELECT * WHERE Col1 MATCHES \'" &
JOIN("|",FILTER(A:A, NOT(ISBLANK(A:A)))) & "\' ")');
addCheckboxToI2();
}}

Hoping I was close !

Body:
Do you mean something like this?

function doSomething() {

var app = SpreadsheetApp;

var activeSheet = app.getActive().getActiveSheet();
var workingCell = activeSheet.getRange(2, 1).getValue();

var otherSheet = app.getActive().getSheetByName('TOP UP NEEDED');
var otherCell = otherSheet.getRange('D2');

var formula = '=QUERY({\'SKU & Qty\'!$A$3:$C},"SELECT * WHERE Col1 MATCHES \'" & JOIN("|",FILTER(A:A, NOT(ISBLANK(A:A)))) & "\' ")';

  if(workingCell == ""){

  }
  else{

  otherCell.setFormula(formula);

  }

//addCheckboxToI2();
//ReferenceError: 'addCheckboxToI2' is niet gedefinieerd. (regel x, bestand 'y')

}

I have some doubts about the formula but do not know enough of formula's to say something helpful about that.


问:
elasticsearch-dsl Document field name serialization with a different name
How can I serialize the field name with a different name from what is defined in the Document object?

```<code>from elasticsearch_dsl import Document, Text

class MyDocument(Document):
     context = Text()
</code>```

When saving this document to ES, I want to write the 'context' key as '@context'.

答: Since @context is not a valid python identifier I am afraid this is not easily possible. You can always drop down to the raw json (by overriding the to_dict method) but I would definitely not recommend it.

Body:
How can I serialize the field name with a different name from what is defined in the Document object?

from elasticsearch_dsl import Document, Text

class MyDocument(Document):
     context = Text()

When saving this document to ES, I want to write the 'context' key as '@context'.


问:
update array of objects in localstorage without leaveing a null
So I have 3 text input fields, the input I store in local storage as an array of objects.
Looks like that:

```<code>[{name: " Name1", description: "Description1", comment: "Comment1"},…]
0: {name: " Name1", description: "Description1", comment: "Comment1"}
1: {name: " Name2", description: "Description2", comment: "Comment2"}
2: {name: " Name3", description: "Description3", comment: "Comment3"}
</code>```

I need to be able to delete any entry I choose and update local storage.

After JSON.parse I get an javascript object, not an array.
If I use delete[X] it leaves null -

```<code>[null, {name: " Name2", description: "Description2", comment: "Comment2"},…]
0: null
1: {name: " Name2", description: "Description2", comment: "Comment2"}
2: {name: " Name3", description: "Description3", comment: "Comment3"}
</code>```

Is there any way to avoid that, I need entry be completely gone and update indexes so "name2..." would gain index 0 and so on.

Is there any way to do it?
Thanks!

答:
You can use Filter to remove null array items.

let newVals = [null, {
  name: " Name2",
  description: "Description2",
  comment: "Comment2"
}, {
  name: " Name3",
  description: "Description3",
  comment: "Comment3"
}].filter(x => x);
console.log(newVals);```

Body:
So I have 3 text input fields, the input I store in local storage as an array of objects.
Looks like that:

[{name: " Name1", description: "Description1", comment: "Comment1"},…]
0: {name: " Name1", description: "Description1", comment: "Comment1"}
1: {name: " Name2", description: "Description2", comment: "Comment2"}
2: {name: " Name3", description: "Description3", comment: "Comment3"}

I need to be able to delete any entry I choose and update local storage.

After JSON.parse I get an javascript object, not an array.
If I use delete[X] it leaves null -

[null, {name: " Name2", description: "Description2", comment: "Comment2"},…]
0: null
1: {name: " Name2", description: "Description2", comment: "Comment2"}
2: {name: " Name3", description: "Description3", comment: "Comment3"}

Is there any way to avoid that, I need entry be completely gone and update indexes so "name2..." would gain index 0 and so on.

Is there any way to do it?
Thanks!


问:
Make a simple search algorithm more elegant
```<code>// temp data
var array = [1,2,function() { }, 3, function() { }];
var cb = function() { console.log("foo"); }

var found = false;
console.log(_.map(array, function(val) {
    if (_.isFunction(val) && !found) {
        return found = true, _.compose(cb, val);
    }
    return val;
}));
</code>```

This loops through the array and turns the first function it finds into a composed function.

I hate that found = false variable / counter. How do I get rid of it?

As an algorithm.

```<code>let found be 0
map value in array
    if value satisfies condition and found is 0
        let found be 1
        return mutate(value)
    else
        return value
</code>```

Update

Using a for loop

```<code>for (var i = 0; i < array.length; i++) {
    if (_.isFunction(array[i])) {
        array[i] = _.compose(cb, array[i]);
        break;
    }
}
</code>```

_.map, _, _.isFunction, _.compose

答:
assuming short-circuit evaluation: (which I promptly bastardise)

```<code>let found be 0
for each value in array
    if value satisfies condition and found is 0 and let found be not found
        let value be mutate(value)
</code>```

edited problem, edited answer:

```<code>let found be 0
for each value in array
  return ( value satisfies condition and found is 0 and let found be not found ) ? mutate(value) : value
</code>```

Body:
// temp data
var array = [1,2,function() { }, 3, function() { }];
var cb = function() { console.log("foo"); }

var found = false;
console.log(_.map(array, function(val) {
    if (_.isFunction(val) && !found) {
        return found = true, _.compose(cb, val);
    }
    return val;
}));

This loops through the array and turns the first function it finds into a composed function.

I hate that found = false variable / counter. How do I get rid of it?

As an algorithm.

let found be 0
map value in array
    if value satisfies condition and found is 0
        let found be 1
        return mutate(value)
    else
        return value

Update

Using a for loop

for (var i = 0; i < array.length; i++) {
    if (_.isFunction(array[i])) {
        array[i] = _.compose(cb, array[i]);
        break;
    }
}

_.map, _, _.isFunction, _.compose

Body:
assuming short-circuit evaluation: (which I promptly bastardise)

let found be 0
for each value in array
    if value satisfies condition and found is 0 and let found be not found
        let value be mutate(value)

edited problem, edited answer:

let found be 0
for each value in array
  return ( value satisfies condition and found is 0 and let found be not found ) ? mutate(value) : value