text:
Q: When class is called, it won't draw my new stage I've been having trouble adding my own custom font my game, and was wondering why libgdx doesn't like drawing my new stage i've set up once my class is called?
The class is called whenever an item intersects with another and the main class calls this class's .render() method.  I want it to draw the string "game over" to the screen, however i am getting an error at stage.act(delta):
Exception in thread "LWJGL Application" java.lang.NullPointerException
    at com.mygdx.game.GameOverScreen.render(GameOverScreen.java:70)
    at com.mygdx.game.MyGdxGame.render(MyGdxGame.java:191)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:214)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:120)

Here is my code:
class GameOverScreen implements Screen {
    Label gameoverstring;

    private Stage stage;
    SpriteBatch spritebatch;

    BitmapFont white;
    LabelStyle headingStyle;

    @Override
    public void show() {
        stage = new Stage();
        white = new BitmapFont(Gdx.files.internal("new.fnt"), false);
        headingStyle = new LabelStyle(white, Color.WHITE);

        gameoverstring = new Label("game ovaaaa!", headingStyle);
        gameoverstring.setFontScale(3);
        stage.addActor(gameoverstring);
    }

    @Override
    public void render(float delta) {
        //gameoverstring.setPosition(0, 0);
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        stage.act(delta);
        stage.draw();
    }

    @Override
    public void resize(int width, int height) {
    }

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }

    @Override
    public void hide() {
    }

    @Override
    public void dispose() {
    }
}

A: Something on line 70 (in your render method) is null.  See What is a NullPointerException, and how do I fix it? for some background.
I suspect your problem is that the stage in render is null.  Probably because your show method hasn't been invoked yet.


text:
Q: What is the right schema for this json data coming from kafka broker to a spark streaming application in python After executing this program I am recieving null values in all fields of the dataframe.If schema is the problem,Kindly me suggest me the right schema for this json format or else kindly provide me the right answer for reading this json data from kafka-topic using readStream api and print that to console.
Here is the sample json data in kafka-topic
        {
          "invoice_no": 154132541653705,
          "country": "United Kingdom",
          "timestamp": "2020-09-18 10:55:23",
          "type": "ORDER",
          "items": [
            {
              "SKU": "21485",
              "title": "RETROSPOT HEART HOT WATER BOTTLE",
              "unit_price": 4.95,
              "quantity": 6
            },
            {
              "SKU": "23499",
              "title": "SET 12 VINTAGE DOILY CHALK",
              "unit_price": 0.42,
              "quantity": 2
            }
          ]
        }

program  without errors,I am posting main part here
        spark = SparkSession.builder.appName('retaildata').getOrCreate()
        spark.sparkContext.setLogLevel("ERROR")
            jsonSchema=StructType([ \
            StructField("invoice_no",IntegerType()), \
            StructField("country",StringType()), \
            StructField("timestamp",TimestampType()), \
            StructField("type",StringType()), \
            StructField("items",StructType([StructField("SKU",IntegerType()), \
                                                    StructField("title",StringType()), \
                                                    StructField("unit_price",DoubleType()), \
                                                    StructField("quantity",IntegerType()) \
                                                     ])) \
                                  ])

        dfraw = spark \
          .readStream \
          .format("kafka") \
          .option("kafka.bootstrap.servers", "18.211.252.152:9092") \
          .option("subscribe", "real-time-project") \
          .option("includeHeaders","true") \
          .load() \
          .select(from_json(col("value").cast("string"),jsonSchema).alias("data")).select("data.*") \
          .writeStream \
          .format("console") \
          .start() \
          .awaitTermination() \

Output:
        =================================
        I am receiving the data as

        Batch: 0
        -------------------------------------------
        +----------+-------+---------+----+-----+
        |invoice_no|country|timestamp|type|items|
        +----------+-------+---------+----+-----+
        +----------+-------+---------+----+-----+

        -------------------------------------------
        Batch: 1
        -------------------------------------------
        +----------+-------+---------+----+-----+
        |invoice_no|country|timestamp|type|items|
        +----------+-------+---------+----+-----+
        |      null|   null|     null|null| null|
        |      null|   null|     null|null| null|
        |      null|   null|     null|null| null|
        |      null|   null|     null|null| null|
        +----------+-------+---------+----+-----+

A: You can just read the json string and convert as a DataFrame and then print the schema.
Code:
json_data = """
{
          "invoice_no": 154132541653705,
          "country": "United Kingdom",
          "timestamp": "2020-09-18 10:55:23",
          "type": "ORDER",
          "items": [
            {
              "SKU": "21485",
              "title": "RETROSPOT HEART HOT WATER BOTTLE",
              "unit_price": 4.95,
              "quantity": 6
            },
            {
              "SKU": "23499",
              "title": "SET 12 VINTAGE DOILY CHALK",
              "unit_price": 0.42,
              "quantity": 2
            }
          ]
        }
"""

df = spark.read.json(spark.sparkContext.parallelize([json_data]))

print(df.schema.json())
print(df.schema)
df.printSchema()
df.show(10, False)

Output:
{"fields":[{"metadata":{},"name":"country","nullable":true,"type":"string"},{"metadata":{},"name":"invoice_no","nullable":true,"type":"long"},{"metadata":{},"name":"items","nullable":true,"type":{"containsNull":true,"elementType":{"fields":[{"metadata":{},"name":"SKU","nullable":true,"type":"string"},{"metadata":{},"name":"quantity","nullable":true,"type":"long"},{"metadata":{},"name":"title","nullable":true,"type":"string"},{"metadata":{},"name":"unit_price","nullable":true,"type":"double"}],"type":"struct"},"type":"array"}},{"metadata":{},"name":"timestamp","nullable":true,"type":"string"},{"metadata":{},"name":"type","nullable":true,"type":"string"}],"type":"struct"}

StructType(List(StructField(country,StringType,true),StructField(invoice_no,LongType,true),StructField(items,ArrayType(StructType(List(StructField(SKU,StringType,true),StructField(quantity,LongType,true),StructField(title,StringType,true),StructField(unit_price,DoubleType,true))),true),true),StructField(timestamp,StringType,true),StructField(type,StringType,true)))

root
 |-- country: string (nullable = true)
 |-- invoice_no: long (nullable = true)
 |-- items: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- SKU: string (nullable = true)
 |    |    |-- quantity: long (nullable = true)
 |    |    |-- title: string (nullable = true)
 |    |    |-- unit_price: double (nullable = true)
 |-- timestamp: string (nullable = true)
 |-- type: string (nullable = true)

+--------------+---------------+--------------------------------------------------------------------------------------------------+-------------------+-----+
|country       |invoice_no     |items                                                                                |timestamp          |type |
+--------------+---------------+--------------------------------------------------------------------------------------------------+-------------------+-----+
|United Kingdom|154132541653705|[{21485, 6, RETROSPOT HEART HOT WATER BOTTLE, 4.95}, {23499, 2, SET 12 VINTAGE DOILY CHALK, 0.42}]|2020-09-18 10:55:23|ORDER|
+--------------+---------------+--------------------------------------------------------------------------------------------------+-------------------+-----+

redpajama_set_name: RedPajamaStackExchange


text:
Q: java.net.SocketException: Connection reset by peer. In custom twitch bot I created custom Twitch bot with using of cavariux library. I called this methods in main class.
bot.setOauth_Key("oauth:key_Value");
bot.connect();
bot.joinChannel(channel.toString());
bot.start();

Approximately one of the 5-6 launches of the bot is accompanied by an exception

java.net.SocketException: Connection reset by peer

. The stack trace indicates that the exception starts on this line.
while ((line = this.reader.readLine( )) != null && !stopped)

in TwitchBot class in method start(). I didn't change code of this library except adding utf encoding in method connect(String ip, int port).
this.writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));

I've tested my bot on different PCs. On some machines I don't have this issue. On some I got this exception more often.
This is code of method start() in TwitchBot class.
 public final void start()
        {
            if (isRunning()) return;
            String line = "";
            stopped = false;
            try {
                while ((line = this.reader.readLine( )) != null && !stopped) {
                    if (line.toLowerCase( ).startsWith("ping")) {
                        LOGGER.log(Level.INFO,"> PING");
                        LOGGER.log(Level.INFO,"< PONG " + line.substring(5));
                        this.writer.write("PONG " + line.substring(5) + "\r\n");
                        this.writer.flush();
                    } else if (line.contains("PRIVMSG"))
                    {
                        String str[];
                        str = line.split("!");
                        final User msg_user = User.getUser(str[0].substring(1, str[0].length()));
                        str = line.split(" ");
                        Channel msg_channel;
                        msg_channel = Channel.getChannel(str[2], this);
                        String msg_msg = line.substring((str[0].length() + str[1].length() + str[2].length() + 4), line.length());
                        LOGGER.log(Level.INFO,"> " + msg_channel + " | " + msg_user + " >> " +  msg_msg);
                        if (msg_msg.startsWith(commandTrigger))
                            onCommand(msg_user, msg_channel, msg_msg.substring(1));
                        if (msg_user.toString().equals("jtv") && msg_msg.contains("now hosting")) {
                            String hoster = msg_msg.split(" ")[0];
                            onHost(User.getUser(hoster), msg_channel);
                        }
                        onMessage(msg_user, msg_channel, msg_msg);
                    } else if (line.contains(" JOIN ")) {
                        String[] p = line.split(" ");
                        String[] pd = line.split("!");
                        if (p[1].equals("JOIN"))
                            userJoins(User.getUser(pd[0].substring(1)), Channel.getChannel(p[2], this));
                    } else if (line.contains(" PART ")) {
                        String[] p = line.split(" ");
                        String[] pd = line.split("!");
                        if (p[1].equals("PART"))
                            userParts(User.getUser(pd[0].substring(1)), Channel.getChannel(p[2], this));
                    } else if (line.contains(" WHISPER ")) {
                        String[] parts = line.split(":");
                        final User wsp_user = User.getUser(parts[1].split("!")[0]);
                        String message = parts[2];
                        onWhisper(wsp_user, message);
                    } else if (line.startsWith(":tmi.twitch.tv ROOMSTATE")) {

                    } else if (line.startsWith(":tmi.twitch.tv NOTICE"))
                    {
                        String[] parts = line.split(" ");
                        if (line.contains("This room is now in slow mode. You may send messages every"))
                        {
                            LOGGER.log(Level.INFO,"> Chat is now in slow mode. You can send messages every " + parts[15] + " sec(s)!");
                        } else if (line.contains("subscribers-only mode")) {
                            if (line.contains("This room is no longer"))
                                LOGGER.log(Level.INFO,"> The room is no longer Subscribers Only!");
                            else
                                LOGGER.log(Level.INFO,"> The room has been set to Subscribers Only!");
                        } else {
                            LOGGER.log(Level.INFO,line);
                        }
                    } else if (line.startsWith(":jtv MODE "))
                    {
                        String[] p = line.split(" ");
                        if (p[3].equals("+o")) {
                            LOGGER.log(Level.INFO,"> +o " + p[4]);
                        } else {
                            LOGGER.log(Level.INFO,"> -o " + p[4]);
                        }
                    } else if (line.toLowerCase().contains("disconnected"))
                    {
                        LOGGER.log(Level.INFO, line);
                        this.connect();
                    } else
                    {
                        LOGGER.log(Level.INFO,"> " + line);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

This is code of method connect() in TwitchBot class.
public void connect(String ip, int port)
    {
        if (isRunning()) return;
        try{
            if (user == null || user == "")
            {
                LOGGER.log(Level.SEVERE, "Please select a valid Username");
                System.exit(1);
                return;
            }
            if (oauth_key == null || oauth_key == "")
            {
                LOGGER.log(Level.SEVERE,"Please select a valid Oauth_Key");
                System.exit(2);
                return;
            }

            @SuppressWarnings("resource")
            Socket socket = new Socket(ip, port);
            this.writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
            this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream(),StandardCharsets.UTF_8));

            this.writer.write("PASS " + oauth_key + "\r\n");
            this.writer.write("NICK " + user + "\r\n");
            this.writer.write("USER " + this.getVersion() + " \r\n");
            this.writer.write("CAP REQ :twitch.tv/commands \r\n");
            this.writer.write("CAP REQ :twitch.tv/membership \r\n");
            this.writer.flush();

            String line = "";
            while ((line = this.reader.readLine()) != null)
            {
                 if (line.indexOf("004") >= 0) {
                        LOGGER.log(Level.INFO,"Connected >> " + user + " ~ irc.twitch.tv");
                        break;
                    }else {
                        LOGGER.log(Level.INFO,line);
                    }
            }
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

Thank you for the help

A: This error means that the peer (i.e. the Twitch server) closes abruptly your connection.  See this answer for more details.
I don't know if you can do something to fix that because it can have various external origins (peer crash...). Maybe you can wait and try to reconnect later (note that you might be blacklisted if you connect too often).


text:
Q: Sass Mixin multiple properties in a loop I'm lost and not sure why this compiles but doesn't output anything. Also not even sure if I'm approaching this correctly. I started using a mixin within a loop to define a bunch of colors. This works great, except that depending on the place I may need to pass the colors to the color, border-color, or background-color properties. Also, I may need to pass the same color to one of those properties in a :hover state. This compiles, yet doesn't actually output anything if called.

// Category Colors
$category-1: #29b473 !default;
$category-2: #60e2c9 !default;
$category-3: #25a9e0 !default;
$category-4: #2b52ff !default;
$category-5: #c5a0ff !default;
$category-6: #ea2f69 !default;
$category-7: #ec1c24 !default;
$category-8: #f6921e !default;
$category-9: #cccc00 !default;

$categories: () !default;
$categories: map-merge((
 "red": $category-1,
 "blue": $category-2,
 "black": $category-3,
 "green": $category-4,
 "yellow": $category-5,
 "pink": $category-6,
 "gray": $category-7,
 "orange": $category-8,
 "brown": $category-9,
), $categories);

// Mixins
@mixin category($parent, $color, $props, $hovers:null) {
 #{$parent} {
  @each $prop in $props {
   $prop:$color;
  }
  @if ($hovers) {
   &:hover {
    @each $hover in $hovers {
     $hover:$color;
    }
   }
  } @else {}
 }
}

// Testing
@each $color, $value in $categories {
 @include category('.xyz-#{$color}', $value, (color, border-color), background-color);
}

Ignore the oddities with the colors please and that they aren't actually the colors that they are labeled.

A: Figured it out, needed to change my statements being used for property names to this format:
{$prop}, and #{$hover}.


text:
Q: Powershell get-credentials fails PS C:\Windows\system32> $creds = Get-Credential

cmdlet Get-Credential at command pipeline position 1 Supply values for
  the following parameters: Credential

PS C:\Windows\system32> $ses = New-PSSession -ComputerName WIN-O4VC136J0E2 -Credential $creds

New-PSSession : [WIN-O4VC136J0E2] Connecting to remote server
  WIN-O4VC136J0E2 failed with the following error message : The user
  name or password is incorrect. For more information, see the
  about_Remote_Troubleshooting Help topic. At line:1 char:8
  + $ses = New-PSSession -ComputerName WIN-O4VC136J0E2 -Credential $creds
  +        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession],
  PSRemotin    gTransportException
      + FullyQualifiedErrorId : LogonFailure,PSSessionOpenFailed

The credentials I used are the same ones I used to login manually. Is there something else I am doing wrong? I've tried several different ways and never can seem to login.

A: Try the following, works very nicely with either a domain account or local account:
# Enter your pass and stores it securely:
$SecureString = Read-Host -AsSecureString 'Enter your password ' | ConvertFrom-SecureString | ConvertTo-SecureString
# Users you password securly
$MySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "MyLoCalMachine\MyUserID",$SecureString
# Sets yous credentials to be used
$RemoteConn = New-PSSession -ComputerName $ts -Credential $MySecureCreds -Authentication default


text:
Q: Problema ao verificar se usuário já existe antes de cadastrar Tô começando agora, e tenho uma dúvida. Eu tinha feito pra cadastrar uma categoria, até aí ok, mas percebi que estava cadastrando mesmo com uma categoria já existente, aí resolvi adicionar uma função pra verificar no banco de dados se o que foi digitado já tem lá, mas não estou conseguindo.
<?php
session_start();
$adicionar_categoria = $_POST['categoria'];
include_once("../../config/conexao.php");

//Verifica se a categoria já existe.
    $vcategoria = mysql_query("SELECT * FROM categorias(nomeCategoria) LIMIT 1");

//Se o retorno for maior que 0, diz que já existe uma categoria com o mesmo nome.
if(mysql_num_rows($vcategoria) > 0){
    $_SESSION['categoriaErro'] = "Categoria existente.";
    header("Location: ../adicionar_categoria.php");
}else{
$resultCategoria = mysql_query("INSERT INTO categorias(nomeCategoria) VALUES ('$adicionar_categoria')");
}
//echo "Categoria: ".$resultCategoria['nomeCategoria'];

if(empty($resultCategoria)){
    $_SESSION['categoriaErro'] = "Por favor, adicione uma categoria válida.";
    header("Location: ../adicionar_categoria.php");
}else{
    $_SESSION['categoriaSucesso'] = "Categoria adicionada com sucesso.";
    header("Location: ../adicionar_categoria.php");
}
?>

A: A sua query de busca está errada, deveria ser assim:
SELECT * FROM categorias WHERE nomeCategoria = '$adicionar_categoria' LIMIT 1

PORÉM: o seu código tem sérios problemas de compatibilidade e segurança. Sugiro fortemente consultar esta outra pergunta: Por que não devemos usar funções do tipo mysql_*?


text:
Q: React-slick specific carousel with css I got a problem with my carousel. In the picture below I want my carousel liked that, but I tried many times by editing css it doesn't work. It looks liked my carousel's items aren't centered. I setted on my setting variable to let them show  3 items, but they aren't show 3 items sometimes.

my css.
    .carousel {
    width: 500px;
    height: 200px;
    z-index: 2;
    .slick-list {
      .slick-track {
        .slick-slide {
          width: 100% !important;
        }
        .slick-slide,
        .slick-center {
          display: flex;
          justify-content: center;
          padding: 0px 100px 0px 100px;
          div img {
            width: 200px;
          }
        }
      }
    }
  }

my code.
 const adsElements = adsList.map((ads, index) => {
    return <Carousels key={`${index}`} value={ads} />;
      });

      const changeSlide = {
        beforeChange: function (currentSlide) {
          console.log(currentSlide);
        },
      };

      return (

          {!flag.isLoad && !hotel.isLoad && !ads.isLoad ? <></> : <Loading />}
          <Slider {...settings} {...changeSlide} className="carousel">
            {adsElements}
          </Slider>

            {flagList.length > 0 &&
{flagElements}
}

      );

My carousel's items those I used .map.
const Carousel = styled.img`
      width: 100%;
      text-decoration: none;
      color: black;
      cursor: pointer;
      @media screen and (max-width: 842px) {
        width: 325px;
        margin-top: 4rem;
      }
      @media screen and (max-width: 428px) {
        height: 650px;
      }
    `;

    export default function Carousels(props) {
      const { value, index } = props;

      const [currentIndex, setCurrentIndex] = useState(0);

      const handleSelect = (selectedIndex, e) => {
        setCurrentIndex(selectedIndex);
      };

      return (
        <Carousel
          src={value.photoURL}
          onClick={() => {
            window.open(value.adsURL, "");
          }}
        />
      );
    }

And my settings.
    const settings = {
  dots: true,
  infinite: true,
  slidesToShow: 3,
  slidesToScroll: 1,
  swipeToSlide: true,
  centerMode: true,
  arrows: true,
  autoplay: false,
  autoplaySpeed: 3000,
  speed: 500,
  responsive: [
    {
      breakpoint: 428,
      settings: {
        slidesToShow: 3,
        slidesToScroll: 1,
        infinite: true,
        dots: true,
        vertical: false,
      },
    },
  ],
};


text:
Q: Getting "ERROR! failed at splitting arguments, either an unbalanced jinja2 block or quotes" while passing regex expression as parameter in Ansible I need to pass regex expression as string such that it will be appended to a file.
Ansible command used ansible-playbook -i hosts local_prop.yml --extra-vars "local_prop='${local_props}'"
local_props : #issue fix
REGEXP=^[^\\t\\r\\n<>%\\"']*$
The local_props value is passed as parameter from Jenkins Job.
I am getting  error on running ansible playbook
ERROR! failed at splitting arguments, either an unbalanced jinja2 block or quotes: local_prop='##issue fix REGEXP=^[^\\\\t\\\\r\\\\n<>%\\\\"']*$'
I tried all combinations of single and double quotes but no success. I also tried declaring the parameters in var files still its not treating the regex as string.


text:
Q: Register a package service provider from within that package In all Laravel versions, if we want to register a new service provider, we can open the config/app.php file and add the new provider to the providers array, like so:
'providers' => [
    ...
    Path\To\New\ServiceProvider::class,
],

My idea is to install a package and have it automatically load its service provider, so without a need to add the new provider to the Laravel's app.php
I have two questions:

*

*Is this a good idea? In both cases, why is it good / not good?

*Is there a preferred way of doing this? My guess is to autoload a bootstrap file from the package's composer.json, and then $this->app->register('Path\To\New\ServiceProvider'); from there.

Is this how it should be done?
As advised by Sven, I'm adding information to clarify what I intend to achieve.
I'm planning to create a core package which would manage adding (installing) and removing its dependant auxiliary packages from a remote repository. For that I would like to have complete autonomy for the auxiliary packages, meaning that 100% of everything related to an auxiliary package should be stored within that package's folder, with an option for users to publish and customize its /resources, as expected in a Laravel app.


text: Q: nested-for-loop A logical structure used in computer programming where two or more for-loops are placed in a "nested" form (i.e., one for-loop is situated within the body of another). The inner loop is repeated in full on every pass through the outer loop.


text:
Q: How to configure Drools to run with JBOSS? I have a java application which is deployed in a jboss 5, and I m using drools in my application. so need some information on what i need to do to get the drools runtime environment in jboss.
Thanks

A: You can embed drools in your application, that means that you can create a web application add the drools dependencies and just use drools inside that application. There are several architectures and ways of working with drools inside jboss, can you specify a little bit more about what do you want to achieve?
Cheers


text:
Q: Query with Ruby on Rails Hi: I'm struggling with a rails query. Finally, I want to make a JSON response with the following contents: A listing of all countries which have at least one company, associated through "Address" and a count of how of how many companies reside in a country.
Here is my simple model structure:
class Country < ActiveRecord::Base
     has_many :addresses
end

class Address < ActiveRecord::Base
     belongs_to :country
     belongs_to :company
end

class Company < ActiveRecord::Base
     has_one :address
end

What's the most elegant way to solve this with Rails?

A: You need to overload the to_json method :
class Country < ActiveRecord::Base
     has_many :addresses
     def to_json
         # format your country as json with all the elements you need
     end
end

Then in your controller do something like that:
countries = Country.find(:all).select{|c| c.companies.size > 0 }
json = countries.collect{|c| c.to_json }

You'll have to use has_many throught to get the companies from a country. Documentation here: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
Sorry I don't have time for a more precise solution, but hopefully these pointers will help you. If you have specific problems, feel free to either comment or open a new question.

A: You might want to add a counter cache to Address
belongs_to :country, :counter_cache => :companies_count

It stores the number of companies in the country model, which saves you from the N+1 query issue.
Alternatively you could avoid it also by issuing a single query like this:
Country.find(:all, :select => 'countries.*, count(addresses.id) as companies_count', :joins => 'LEFT JOIN addresses ON addresses.country_id = countries.id', :group => 'countries.id')

This way all of the returned countries will have field companies_count containing the number of companies for that country.


text:
Q: mapping through object which is inside object in react I have roomFeature.js file inside which there is object named as roomFeature. Inside roomFeature there is another object named beds with childs "single: "1", double: "2",".
Here's what i am talking about:
const roomFeatures = {
 roomFeature: {
  bed: true,
  sleep: {
      single: "1",
      double: "3",
    },
 }
}

how can i access "1" if the "sleep" is available?
I have tried:
{roomFeatures.roomFeature.sleep.map((data) => {
 return (

    <BsFillPersonFill />
   {" "}
    sleeps {data.single}

 );
})}

A: If you only want to access to "1" one time then you can directly use {roomFeatures.roomFeature.sleep.single}
If you are trying to loop through the sleep object, you should convert it to an array before you use map function.
let temp_sleep = Object(roomFeatures.roomFeature.sleep);
temp_sleep.keys().map(key => {
    return (

        <BsFillPersonFill />
      {" "}
      sleeps {temp_sleep[key]}

  );
})

The keys function will return an array of keys in the object, so you can use the map function on the array.


text:
Q: In Rally how to fetch execution status of test cases in test set I want to fetch the execution status of test cases in a test set using Rally Java API.
The following snippet return the last execution status of test cases. But I want the execution status of that testcase in a specific test set.
    QueryRequest testSetRequest = new QueryRequest("TestSet");

    testSetRequest.setFetch(new Fetch(new String[] { "Name", "TestCases",
            "FormattedID", "LastVerdict","LastRun" }));

    testSetRequest.setQueryFilter(new QueryFilter("Name", "=", tsName));

    QueryResponse testSetQueryResponse = restApi.query(testSetRequest);
    System.out.println("Successful: "
            + testSetQueryResponse.wasSuccessful());
    System.out.println("Size: "
            + testSetQueryResponse.getTotalResultCount());
    for (int i = 0; i < testSetQueryResponse.getResults().size(); i++)
    {
        JsonObject testSetJsonObject = testSetQueryResponse.getResults()
                .get(i).getAsJsonObject();
        System.out.println("Name: " + testSetJsonObject.get("Name")
                + " ref: " + testSetJsonObject.get("_ref").getAsString()
                + " Test Cases: " + testSetJsonObject.get("TestCases"));
        int numberOfTestCases = testSetJsonObject.get("TestCases")
                .getAsJsonArray().size();
        System.out.println(numberOfTestCases);
        if (numberOfTestCases > 0)
        {
            for (int j = 0; j < numberOfTestCases; j++)
            {
                JsonObject tcObj = testSetJsonObject.get("TestCases")
                        .getAsJsonArray().get(j).getAsJsonObject();
                System.out.println(tcObj.get("FormattedID")+"----"+tcObj.get("LastVerdict"));
            }
        }
    }

A:     QueryRequest testCaseResultsRequest = new QueryRequest("TestCaseResult");
    testCaseResultsRequest.setFetch(new Fetch("Build","TestCase","TestSet", "Verdict","FormattedID"));
    testCaseResultsRequest.setQueryFilter(new QueryFilter("TestCase.FormattedID", "=", "TC8147").and(
            new QueryFilter("TestSet.FormattedID", "=", "TS363")));
    QueryResponse testCaseResultResponse = restApi.query(testCaseResultsRequest);
    int numberTestCaseResults = testCaseResultResponse.getTotalResultCount();
    System.out.println(numberTestCaseResults);
    if(numberTestCaseResults >0)
        System.out.println(testCaseResultResponse.getResults().get(0).getAsJsonObject().get("Verdict").getAsString());
    else
        System.out.println("Not executed");


text:
Q: Ability to calculate difference between time between two different rows in a table using SQL query I am trying to find a way to determine amount of time between two separate rows in a table.
for example, my table has user, date and time stamp , transaction type
example of data:
Joe    10/2/2020 9:01:30     Shipping
Joe    10/2/2020 9:01:55     Shipping
Joe   10/02/2020 9:05:30     Shipping

I would like to see in my output
user      date/time               time difference
 Joe    10/2/2020 9:01:30
Joe    10/2/2020 9:01:55          25 seconds
Joe   10/02/2020 9:05:30        3 min 35 seconds

The end goal would be to have different transaction type and find out how long the user worked at each transaction type, I only have the endtime to work with.

A: For MYSQL Server Version 8+
If you are using a recent version of MySQL Server like version 8.0, you can try to use the LAG() function.
Sample table:
CREATE TABLE WorkLog (
    employee_name varchar(10),
    Shipping_Time DATETIME,
    PRIMARY KEY (employee_name, Shipping_Time)
);

Sample Data:
INSERT INTO WorkLog(employee_name, Shipping_Time) VALUES("Joe","2020-10-02 12:00:00.000");
INSERT INTO WorkLog(employee_name, Shipping_Time) VALUES("Joe","2020-10-02 12:01:30.000");
INSERT INTO WorkLog(employee_name, Shipping_Time) VALUES("Joe","2020-10-02 12:05:30.000");
INSERT INTO WorkLog(employee_name, Shipping_Time) VALUES("Joe","2020-10-02 12:10:00.000");
INSERT INTO WorkLog(employee_name, Shipping_Time) VALUES("Joe","2020-10-02 12:20:00.000");

INSERT INTO WorkLog(employee_name, Shipping_Time) VALUES("Sue","2020-10-02 12:00:00.000");
INSERT INTO WorkLog(employee_name, Shipping_Time) VALUES("Sue","2020-10-02 12:01:30.000");
INSERT INTO WorkLog(employee_name, Shipping_Time) VALUES("Sue","2020-10-02 12:05:30.000");
INSERT INTO WorkLog(employee_name, Shipping_Time) VALUES("Sue","2020-10-02 12:10:00.000");
INSERT INTO WorkLog(employee_name, Shipping_Time) VALUES("Sue","2020-10-02 12:20:00.000");

SQL Query - to get result as Seconds:
SELECT employee_name,
Shipping_Time,
TIMESTAMPDIFF(SECOND, (LAG(Shipping_Time,1) OVER (PARTITION BY employee_name)),Shipping_Time) AS TimeDiffInSeconds
FROM WorkLog
ORDER BY employee_name, Shipping_Time;

Output:
| employee_name | Shipping_Time       | TimeDiffInSeconds |
| ------------- | ------------------- | ----------------- |
| Joe           | 2020-10-02 12:00:00 |                   |
| Joe           | 2020-10-02 12:01:30 | 90                |
| Joe           | 2020-10-02 12:05:30 | 240               |
| Joe           | 2020-10-02 12:10:00 | 270               |
| Joe           | 2020-10-02 12:20:00 | 600               |
| Sue           | 2020-10-02 12:00:00 |                   |
| Sue           | 2020-10-02 12:01:30 | 90                |
| Sue           | 2020-10-02 12:05:30 | 240               |
| Sue           | 2020-10-02 12:10:00 | 270               |
| Sue           | 2020-10-02 12:20:00 | 600               |

SQL Query - to get result as Time (hh:mm:ss):
SELECT employee_name,
Shipping_Time,
SEC_TO_TIME(TIMESTAMPDIFF(SECOND, (LAG(Shipping_Time,1) OVER (PARTITION BY employee_name)),Shipping_Time)) AS "TimeDiff hh:mm:ss"
FROM WorkLog
ORDER BY employee_name, Shipping_Time;

Output:
| employee_name | Shipping_Time       | TimeDiff hh:mm:ss |
| ------------- | ------------------- | ----------------- |
| Joe           | 2020-10-02 12:00:00 |                   |
| Joe           | 2020-10-02 12:01:30 | 00:01:30          |
| Joe           | 2020-10-02 12:05:30 | 00:04:00          |
| Joe           | 2020-10-02 12:10:00 | 00:04:30          |
| Joe           | 2020-10-02 12:20:00 | 00:10:00          |
| Sue           | 2020-10-02 12:00:00 |                   |
| Sue           | 2020-10-02 12:01:30 | 00:01:30          |
| Sue           | 2020-10-02 12:05:30 | 00:04:00          |
| Sue           | 2020-10-02 12:10:00 | 00:04:30          |
| Sue           | 2020-10-02 12:20:00 | 00:10:00          |

Ref: https://dev.mysql.com/doc/refman/8.0/en/window-function-descriptions.html#function_lag

For MS SQL Server
Using new information from OP's comments:
Sample table:
CREATE TABLE JSSHIPMENTTABLE (
    CREATEDBY varchar(10),
    CREATEDDATETIME DATETIME,
    PRIMARY KEY (CREATEDBY, CREATEDDATETIME)
);

Sample Data:
INSERT INTO JSSHIPMENTTABLE(CREATEDBY, CREATEDDATETIME) VALUES('Joe','2020-10-02 12:00:00.000');
INSERT INTO JSSHIPMENTTABLE(CREATEDBY, CREATEDDATETIME) VALUES('Joe','2020-10-02 12:01:30.000');

INSERT INTO JSSHIPMENTTABLE(CREATEDBY, CREATEDDATETIME) VALUES('Sue','2020-10-02 12:00:00.000');
INSERT INTO JSSHIPMENTTABLE(CREATEDBY, CREATEDDATETIME) VALUES('Sue','2020-10-02 12:01:30.000');

INSERT INTO JSSHIPMENTTABLE(CREATEDBY, CREATEDDATETIME) VALUES('Sam Colton','2020-10-01 12:00:00.000');
INSERT INTO JSSHIPMENTTABLE(CREATEDBY, CREATEDDATETIME) VALUES('Sam Colton','2020-10-01 12:01:30.000');
INSERT INTO JSSHIPMENTTABLE(CREATEDBY, CREATEDDATETIME) VALUES('Sam Colton','2020-10-01 12:05:30.000');
INSERT INTO JSSHIPMENTTABLE(CREATEDBY, CREATEDDATETIME) VALUES('Sam Colton','2020-10-01 12:10:00.000');
INSERT INTO JSSHIPMENTTABLE(CREATEDBY, CREATEDDATETIME) VALUES('Sam Colton','2020-10-01 12:20:00.000');

MS SQL Server Query - to get result as Seconds:
SELECT CREATEDBY,
CREATEDDATETIME,
datediff(second,(lag(CREATEDDATETIME,1) over (PARTITION by CREATEDBY ORDER BY CREATEDDATETIME)),CREATEDDATETIME) as TimeDiffinSeconds
from JSSHIPMENTTABLE
where convert(date,CREATEDDATETIME,23) = '2020-10-01' and CREATEDBY like '%Colton%' order by CREATEDBY,CREATEDDATETIME

Output:
CREATEDBY   CREATEDDATETIME              TimeDiffinSeconds
----------------------------------------------------------
Sam Colton  2020-10-01 12:00:00.000      NULL
Sam Colton  2020-10-01 12:01:30.000      90
Sam Colton  2020-10-01 12:05:30.000      240
Sam Colton  2020-10-01 12:10:00.000      270
Sam Colton  2020-10-01 12:20:00.000      600

A: Try this query out. You can edit the DATEDIFF function to give you the difference in minutes, hours, days, or whatever increment you would like.
SELECT a.user, a.[date/time], DATEDIFF(second, b.[date/time], a.[date/time]) AS [time difference]
FROM #YourTable a
OUTER APPLY (
    SELECT TOP 1 *
    FROM #YourTable b
    WHERE a.user = b.user
    AND b.[date/time] < a.[date/time]
    ORDER BY [date/time] DESC
) b
ORDER BY a.user, a.[date/time] ASC

A: -- Sample Table:
CREATE TABLE WorkLog (
    employee_name varchar(10),
    Shipping_Time DATETIME,
    PRIMARY KEY (employee_name, Shipping_Time)
);

-- Sample Data:
INSERT INTO WorkLog(employee_name, Shipping_Time) VALUES('Joe','2020-10-02 12:00:00.000');
INSERT INTO WorkLog(employee_name, Shipping_Time) VALUES('Joe','2020-10-02 12:01:30.000');
INSERT INTO WorkLog(employee_name, Shipping_Time) VALUES('Joe','2020-10-02 12:05:30.000');
INSERT INTO WorkLog(employee_name, Shipping_Time) VALUES('Joe','2020-10-02 12:10:00.000');
INSERT INTO WorkLog(employee_name, Shipping_Time) VALUES('Joe','2020-10-02 12:20:00.000');

Select *,
FORMAT(Shipping_Time - LAG(Shipping_Time) OVER (ORDER BY employee_name), 'mm:ss') As timeDiference
From WorkLog
Order By Shipping_Time ASC

-- Results:
employee_name   Shipping_Time   timeDiference
Joe 2020-10-02  12:00:00.000    NULL
Joe 2020-10-02  12:01:30.000    01:30
Joe 2020-10-02  12:05:30.000    04:00
Joe 2020-10-02  12:10:00.000    04:30
Joe 2020-10-02  12:20:00.000    10:00


text:
Q: level 3 nav not hiding when it should be I'm turning a 2 level nav into a 3 level and running into a few difficulties.
The 3rd level displays where and as predicted but when the 'grandparent' is hovered over, not the parent of the items I want displayed.
I've been fooling around with the css for a while and I cannot get it to respond how I'd like.
Any help is appreciated.
There is a fiddle as my explanation might be somewhat lacking.
http://jsfiddle.net/6TGaf/

Code from fiddle:
    #nav{
    background: #bada55;
    width: 99%;
    margin-top:-5px;
}

#nav ul{
    list-style: none;
    margin: 0;
    padding: 0;
    height: 40px;
}

#nav ul li{
    /*child elements positioned absolutley will be relative to this*/
    position: relative;
    border-top: 1px solid #e9e9e9;
    float: left;

}

#nav a{
    color: ghostwhite;
    padding: 12px 0px;
    /*fill hori space*/
    display: block;
    text-decoration: none;
/*apply transition to background property, taking 1s to change it
*/
    transition:padding 1s, background 1s;
    -moz-transition:padding 1s, background 1s;
    -webkit-transition:padding 1s, background 1s;
    -o-transition:padding 1s, background 1s;

    font-family:tahoma;

    font-size:13px;
    text-transform:uppercase;
    padding-left:20px;
}

/*hover pseduo class*/
#nav a:hover{
    /*
    RGBA background for transparancy:
    last number(0.05) is the transparency
    */
    padding-left:35px;
    background: RGBA(255,255,255,0.05);
    color:#fff;
}

#nav ul li:hover ul{
    /*diplay when hovered*/
    display: block;
}

#nav ul ul{
    position: absolute;
    left: 0px;
    top: 40px;
    border-top: 1px solid #e9e9e9;
    display: none;
    /*width: 304px;*/
    z-index: 1;
}

#nav ul ul li{
    width: 150px;
    background: #f1f1f1;
    border: 1px solid #e9e9e9;
    border-top: 0;
    /*float:left;*/

}

#nav ul ul li a{
    color:#000000;
    font-size:12px;
    text-transform:none;
}

#nav ul ul li a:hover {
    color:#929292;
}

/*3rd level...*/
#nav ul ul ul{
    position: absolute;
    left: 150px;
    top: 0px;
    border-top: 1px solid #e9e9e9;
    display: none;
    /*width: 304px;*/
    z-index: 1;
}

#nav ul ul ul li{
    width: 150px;
    background: #f1f1f1;
    border: 1px solid #e9e9e9;
    border-top: 0;
}

#nav ul ul ul li a{
    color:#000000;
    font-size:12px;
    text-transform:none;
}

#nav ul ul ul li a:hover {
color:#929292;
}

#nav ul ul li:hover ul{
/*diplay when hovered*/
display: block;
}

            1.1

                    1.1.1

1.1.1.a

1.1.1.b

1.1.2

1.1.3

A: in your css,
#nav ul li:hover ul{
   display: block;}

the above piece of code was displaying all the elements in the ul block on hover of 1st li element. In this case hovering 1.1. As the grandchild (1.1.1a) also belongs to the upper block ul, even that was getting displayed.
So to fix this, add the code piece:
#nav li:hover ul ul{
    display:none;
    }
#nav li:hover ul, #nav li li:hover ul{
    display:block;
    }

So what the above code is implying, when one hovers on the li element, the element 2 levels below needs to be blocked and when one hovers on the li element only the immediate ul element needs to be displayed.
check http://jsfiddle.net/sxzR8/1/ for a working sample.


text:
Q: Por que criar uma interface para cada DAO? Vejo muito na internet a criação de uma interface para cada DAO do sistema. Eu entendo a importância de se usar interface principalmente para uma troca fácil de implementação, já encontrei inclusive uma explicação dizendo se você usa um banco de dados e troca pra outro é só criar DAO's novos e avisar pra injeção de dependência quais são os novos que ela deve injetar... enfim, em tempos de ORM não vejo a necessidade de se trocar o DAO inteiro, dependendo como foi programado apenas uns ajustes na troca de BD.
Então se tenho um sistema com duas tabelas apenas Usuario e Pedido (por exemplo), qual seria a vantagem de eu criar as interfaces UsuarioDAO e PedidoDAO para depois criar as implementações delas UsarioDaoImlp e PedidoDaoImpl?

A: A principal vantagem está na evolução e na modularização do sistema.
Temos duas possíveis abordagens:

*

*Criar 20 interfaces DAO com 5 ou 6 métodos cada, você tem interfaces UsuarioDAO, PedidoDAO, ContaDAO, ClienteDAO... Quando você for criar o módulo de vendedores, você vai criar um VendedorDAO, alguns poucos métodos e um VendedorDAOImpl.

*Criar uma única gigantesca interface MegaDAO com uns 100 métodos lá. Quando você for criar o módulo de vendedores, você vai acrescentar mais alguns métodos lá e implementá-los no MegaDAOImpl.

Agora vamos analisar as vantagens e desvantagens de cada alternativa:
Observe que na abordagem 2, o seu MegaDAO não é uma interface estável no tempo, pois ela está sempre mudando. As implementações desta interface (MegaDAOImpl) também não são estáveis no tempo, pois estão sempre mudando. Sempre que você cria ou altera algum módulo de forma que o acesso ao banco de dados mude, o MegaDAO e o MegaDAOImpl vão sofrer alterações.
A abordagem 2 também dificulta a modularização, pois ela cria uma interface da qual todos os módulos do sistema dependem, e efetivamente ela amarra todas as partes do sistema umas com as outras em um único bloco monolítico, mesmo que as diferentes partes tenham pouca ou nenhuma relação entre si. Se você quiser depois separar o programa em dois, um para o setor de contabilidade e o outro para o setor de manutenção, o seu MegaDAO e todas as suas implementações (mesmo que seja uma só) vai te dar dor-de-cabeça, pois ele coloca todas as funcionalidades do sistema juntas, inclusive aquelas que forem dispensáveis para o cenário em questão. O resultado disso é o famoso software bloat.
Além disso, vamos supor que o módulo de consulta de nota fiscal tem uma peculiaridade: Ele utiliza dois bancos de dados distintos por qualquer razão especial. Na abordagem 1, este é um detalhe do ConsultaNotaFiscalDAO e de suas (possivelmente múltiplas) implementações. Se você tiver um único MegaDAO, vai precisar resolver isso com uma gambiarra ou com um refactoring completo, pois haverá uma grande quantidade de métodos aonde o uso de dois bancos de dados não faz nenhum sentido, e com isso há o risco (pode ser ou pode não ser que aconteça) de a gambiarra (ou a necessidade de refactoring completo) acabar cascateando uma série de mudanças em outras partes do sistema que não deveriam estar sofrendo alteração.
Normalmente a implementação da maioria dos DAOs será bem parecida: Ele vai no ORM e consulta, insere, altera e/ou exclui registros. No entanto "normalmente" e "a maioria" não é a mesma coisa do que "sempre" e "todos". Se houver uma exceção, digamos, o PrazoDeEntregaDAO que ao invés de ir no banco de dados relacional, vai em um serviço externo, ele trará problemas na abordagem 2 e vai complicar o seu MegaDAOImpl.
Talvez você argumente que neste caso o PrazoDeEntregaDAO nem sequer deveria ser um DAO. Mas vamos supor que originalmente ele era um DAO e com o tempo ele evoluiu para este comportamento especial. Na abordagem 1, tudo que você vai precisar fazer vai ser trocar a implementação do DAO por uma implementação especial diferente do normal. Na abordagem 2, você vai estar ferrado.
Vamos supor que você esteja rascunhando como será a implementação do ChatDAO. Para isso você criou um mock rápido que salva as informações apenas na memória, o ChatDAOMockImpl. Você também usa esta implementação para fazer testes de unidade. Isso é simples e natural na abordagem 1. Já na abordagem 2, você se ferra de novo.
Na abordagem 2, a medida que o seu sistema cresce, o MegaDAO e o MegaDAOImpl também crescem. Imagine que depois de 5 anos, você acrescentou mais de 40 módulos distintos e tem um sistema de grande porte com vários desenvolvedores trabalhando. E também tem um MegaDAOImpl com umas vinte mil linhas de código que a sua IDE até tem dificuldade para abrir e os desenvolvedores constantemente reclamando de problemas de merge com o git ou svn nesta classe.
Enfim, o problema do seu DAO único é que você viola vários princípios de programação orientada a objetos:

*

*A implementação do seu DAO único será uma god class, que consiste em um dos piores anti-padrões de programação orientada a objetos.

*O seu sistema terá um alto grau de acoplamento, pois o seu DAO (tanto a interface quanto a implementação) amarram tudo a tudo.

*O seu sistema terá um baixo grau de coesão, pois uma grande quantidade de funcionalidades não relacionadas entre si ou pouco relacionadas entre si estarão coexistindo na mesma classe.

*Você estará violando o princípio do aberto-fechado, aonde as funcionalidades devem ser estensíveis e reutilizáveis sem a necessidade de modificação de código já existente. Com um DAO único, qualquer tentativa de aumentar as funcionalidades implicam em uma alteração de código.

*Você estará violando o princípio da responsabilidade única, pois a sua interface DAO (bem como a implementação) terá um monte de responsabilidades distintas, e como resultado, será difícil de ser utilizada.

*Você estará violando, de forma bem direta, o princípio de segregação de interfaces, que diz que várias interfaces de propósito específico são melhores do que uma única grande interface de propósito genérico.

A única vantagem da abordagem 2 é ter o código todo em um só lugar e simplificar um pouco os métodos de gerenciamento de conexão com o banco de dados, consultas genéricas e coisas assim. E é só isso. Esta vantagem é facilmente derrotada pela grande quantidade de desvantagens.
Você talvez possa argumentar, ah mas eu só tenho dois módulos, Usuario e Pedido, preciso mesmo separar? A resposta é que todo o sistema que se torna grande começa pequeno, então quanto antes eles forem separados, mais fácil vai ser a evolução do sistema.

A: Isso depende mais da "tecnologia ao redor" e dos planos para o futuro, e não é necessariamente uma regra geral.
Por exemplo, o que eu quero dizer com "tecnologia ao redor"? Se você está falando de Java, era comum certas tecnologias mais antigas como o J2EE até o 1.4 (renomeado para JavaEE a partir da versão 5 e muito simplificado) exigirem a criação de várias interfaces e factories. Ou se não obrigava, a quantidade de boilerplate era tanta que o programador acabava separando as partes de qualquer jeito para reaproveitar código e separar responsabilidades.
Existe um livro justamente sobre "repensar" certas práticas que podem ter ficado obsoletas com o tempo em novas versões dos frameworks Java:
http://www.amazon.com/Real-World-Patterns-Rethinking-Practices/dp/0557078326
Um dos motivos para a criação de interfaces é para possibilitar chamadas remotas de métodos, algo muito mais enfatizado no início do JavaEE. Se chamadas remotas estiverem nos planos, uma interface separada para os clientes chamarem será útil em vez de amarrá-los diretamente a uma classe com implementação que deverá estar no mesmo projeto.
Outro motivo para a interface é para separar e abstrair a instanciação do DAO. Usando uma Factory, o DAO pode ser qualquer coisa: uma classe normal, um proxy para uma chamada remota, um pool de objetos reaproveitados, etc. sendo acessado apenas pela interface, sem tocar no objeto real. Esse padrão de design em JavaEE é menos necessário na presença do CDI: com @Inject você fica livre para decidir depois como será a instanciação da sua classe, sem precisar escrever factories, e também sem precisar criar uma interface separada.
Obs.: não tenho experiência com a injeção do Spring para comparar com CDI, mas bem... nem tenho certeza se a pergunta é sobre Java mesmo ou se é independente de linguagem.
E um terceiro motivo para ter uma interface aquele que você falou na sua pergunta: separação normal entre interface e implementação.
Agora, se alguma dessas situações se aplica ao seu caso, aí tem que pensar com cuidado (nenhuma regrinha fácil substitui o pensar!). Em geral eu prefiro seguir o YAGNI, e não codificar nada cuja utilidade não seja previsível visível. É importante separar os módulos da sua aplicação, mas raramente precisa fazer picadinho transformando cada classe em 3 (interface, implementação e factory).
Muitas vezes as necessidades futuras são tão diferentes do previsto que vale a pena ter algo mais simples. O que acontece com mais freqüência? Trocar todo o banco de dados ou adicionar uma coluna nova ou regra de validação? Codifique para deixar fácil o que acontece com mais freqüência.


text:
Q: Difference between "process.stdout.write" and "console.log" in node.js? What is the difference between "process.stdout.write" and "console.log" in node.js?
EDIT: Using console.log for a variable showed a lot of unreadable characters while using process.stdout.write showed an object.
Why is that?

A: I know this is a very old question but I didn't see anybody talking about the main difference between process.stdout.write and console.log and I just want to mention it.
As Mauvis Leford and TK-421 pointed out, the console.log adds a line-break character at the end of the line (\n) but that's not all what it does.
The code has not changed since at least 0.10.X version and now we have a a 5.X version.
Here is the code:
Console.prototype.log = function() {
  this._stdout.write(util.format.apply(this, arguments) + '\n');
};

As you can see, there is a part that says .apply(this, arguments) and that makes a big difference on functionality. It is easier to explain that with examples:
process.stdout.write has a very basic functionality, you can just write something in there, like this:
process.stdout.write("Hello World\n");

If you don't put the break line at the end you will get a weird character after your string, something like this:
process.stdout.write("Hello World"); //Hello World%

(I think that means something like "the end of the program", so you will see it only if you process.stdout.write was used at the end of your file and you didn't add the break line)
On the other hand, console.log can do more.

*

*You can use it in the same way
console.log("Hello World"); //You don't need the break line here because it was already formated and also that weird character did disappear

*You can write more than one string
console.log("Hello", "World");

*You can make associations
console.log("Hello %s", "World") //Useful when "World" is inside a variable
An that's it, that added functionality is given thanks to the util.format.apply part (I could talk a lot about what exactly this does but you get my point, you can read more here).
I hope somebody find this information useful.

A: console.log() calls process.stdout.write with formatted output. See format() in console.js for the implementation.
Currently (v0.10.ish):
Console.prototype.log = function() {
  this._stdout.write(util.format.apply(this, arguments) + '\n');
};

A: One big difference that hasn't been mentioned is that process.stdout only takes strings as arguments (can also be piped streams), while console.log takes any Javascript data type.
e.g:
// ok
console.log(null)
console.log(undefined)
console.log('hi')
console.log(1)
console.log([1])
console.log({one:1})
console.log(true)
console.log(Symbol('mysymbol'))

// any other data type passed as param will throw a TypeError
process.stdout.write('1')

// can also pipe a readable stream (assuming `file.txt` exists)
const fs = require('fs')
fs.createReadStream('file.txt').pipe(process.stdout)

A: Another important difference in this context would with process.stdout.clearLine() and process.stdout.cursorTo(0).
This would be useful if you want to show percentage of download or processing in the only one line. If you use clearLine(), cursorTo() with console.log() it doesn't work because it also append \n to the text. Just try out this example:
var totalTime = 5000;
var waitInterval = totalTime / 10;
var currentInterval = 0;

function showPercentage(percentage){
    process.stdout.clearLine()
    process.stdout.cursorTo(0)
    console.log(`Processing ${percentage}%...` ) // Replace this line with process.stdout.write(`Processing ${percentage}%...`)
}

var interval = setInterval(function(){
    currentInterval += waitInterval
    showPercentage((currentInterval / totalTime) * 100)
}, waitInterval)

setTimeout(function(){
    clearInterval(interval)
}, totalTime + 100)

A: The Simple Difference is:
console.log() methods automatically append new line character. It means if we are looping through and printing the result, each result get printed in new line.
process.stdout.write() methods don't append new line character. useful for printing patterns.

A: Looking at the Node docs apparently console.log is just process.stdout.write with a line-break at the end:
console.log = function (d) {
  process.stdout.write(d + '\n');
};

Source: http://nodejs.org/docs/v0.3.1/api/process.html#process.stdout

A: I've just noticed something while researching this after getting help with https.request for post method. Thought I share some input to help understand.
process.stdout.write doesn't add a new line while console.log does, like others had mentioned. But there's also this which is easier to explain with examples.
var req = https.request(options, (res) => {
    res.on('data', (d) => {
        process.stdout.write(d);
        console.log(d)
    });
});

process.stdout.write(d); will print the data properly without a new line. However console.log(d) will print a new line but the data won't show correctly, giving this <Buffer 12 34 56... for example.
To make console.log(d) show the information correctly, I would have to do this.
var req = https.request(options, (res) => {
    var dataQueue = "";
    res.on("data", function (d) {
        dataQueue += d;
    });
    res.on("end", function () {
        console.log(dataQueue);
    });
});

So basically:

*

*process.stdout.write continuously prints the information as the data being retrieved and doesn't add a new line.

*console.log prints the information what was obtained at the point of retrieval and adds a new line.
That's the best way I can explain it.

A:
Console.log implement process.sdout.write, process.sdout.write is a buffer/stream that will directly output in your console.
According to my puglin serverline : console = new Console(consoleOptions) you can rewrite Console class with your own readline system.
You can see code source of console.log:

*

*v14.x - lib/internal/console/constructor.js ;

*and for old version: v10.0.0 - lib/console.js.

See more :

*

*readline.createInterface to make your custom behavior or use console input.

A: console.log() adds tons of things and a new line every time you call it
process.stdout.write() is just plain text, no formatting
That's what I was taught at least

A: The answers here are great.  The following expands on the significance of the console.log formatting function. One of the features of formatting not yet mentioned are group levels, which log will honor, but stdout will not.
console.log('Begin...')

console.group()
console.log('Line 2 (console.log)')
process.stdout.write('Line 3 (process.stdout)\n')
console.log('Line 4 (console.log)')
process.stdout.write('Line 5 (process.stdout)') // no newline
console.groupEnd()

console.log('...done')

Output:
Begin...
  Line 2 (console.log)
Line 3 (process.stdout)
  Line 4 (console.log)
Line 5 (process.stdout)...done

Notice stdout does not honor the console.group formatting and always writes to the beginning of the line, where as console.log honors the grouping and indents appropriately.

The same performed only with log statements (and an additional group):
console.log('Begin...')

console.group()
console.log('Line 2 (console.log)')
console.log('Line 3 (console.log)')
console.log('Line 4 (console.log)')
console.log('Line 5 (console.log)')
console.group()
console.log('Line 6 (console.log)')
console.log('Line 7 (console.log)')
console.groupEnd()
console.groupEnd()

console.log('...done')

Output:
Begin...
  Line 2 (console.log)
  Line 3 (console.log)
  Line 4 (console.log)
  Line 5 (console.log)
    Line 6 (console.log)
    Line 7 (console.log)
...done

A: For those who like Deno, I was able to achieve this by using the following ANSI Escape Sequences in conjunction with Deno's version of process.stdout.write.
ESC[2K  clears entire line
ESC[#G  moves cursor to column #

Code
/*
    Console.log() to the same line
    Supported in Deno 1.8.1
*/

const myTextEncoder : TextEncoder = new TextEncoder();

let counter : number = 0;

while(counter < 100000) {

  // ESC[2K clears entire line
  await Deno.stdout.write(myTextEncoder.encode(`\x1b[2K`));
  // ESC[#G moves cursor to column #
  await Deno.stdout.write(myTextEncoder.encode(`\x1b[0G`));
  // OUTPUT incremented counter
  await Deno.stdout.write(myTextEncoder.encode(`COUNTER: ${counter++}`));

}


text:
Q: Properties behind an if statement within vuejs Sometimes I don't want to have a "rules" option/property in some input fields, is it possible within vuejs3 to set up a kind of if statement so that the property "rules" are only presented on certain fields? Because now i just do an empty array[]. But would rather see this differently.
So that I dont need to apply "rules" option in my form scheme when I dont need it.
This is my template code:
 <div v-for="(prop, key) in formSchema" :key="key">

      <q-input v-if="prop.component === 'input'"
         outlined
         v-model="dataRef[key]"
         :type="prop.type"
         :label="prop.label"
         maxlength="12"
         class="super-small"
         hint="Name and surname"
         lazy-rules
         :rules="prop.rules" (want this behind an if statement if not needed)
       >
      </q-input>

      <q-select v-else-if="prop.component === 'select'"
        outlined
        v-model="dataRef[key]"
        :type="prop.type"
        :options="prop.options"
        :label="prop.label">
      </q-select>

    </div>

A: Add a ternary condition within your attribute. When the attribute is set to null or undefined it gets omitted.
:rules="addRule ? prop.rules : null"


text:
Q: To install data to csv column wise I have tried this and it is perfectly working for row wise.
// output headers so that the file is downloaded rather than displayed
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="demo.csv"');

// do not cache the file
header('Pragma: no-cache');
header('Expires: 0');

// create a file pointer connected to the output stream
$file = fopen('php://output', 'w');

// send the column headers
fputcsv($file, array('Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5'));

// Sample data. This can be fetched from mysql too
$data = array(
    array('Data 11', 'Data 12', 'Data 13', 'Data 14', 'Data 15'),
    array('Data 21', 'Data 22', 'Data 23', 'Data 24', 'Data 25'),
    array('Data 31', 'Data 32', 'Data 33', 'Data 34', 'Data 35'),
    array('Data 41', 'Data 42', 'Data 43', 'Data 44', 'Data 45'),
    array('Data 51', 'Data 52', 'Data 53', 'Data 54', 'Data 55')
);

// output each row of the data
foreach ($data as $row)
{
    fputcsv($file, $row);
}

exit();

But i want it to install like column wise. Means, it is now
'Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5'
'Data 11', 'Data 12', 'Data 13', 'Data 14', 'Data 15'
'Data 21', 'Data 22', 'Data 23', 'Data 24', 'Data 25'

But i want like this
'Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5'
'Data 11', 'Data 21', 'Data 31', 'Data 41', 'Data 51'

Is this possible or is there any trick to do that ? Thanks in advance.

A: One way is to organize your array first to match desired result with nested foreach loops
$result = [];                        // Grouped result array
foreach ($data as $value) {          // Loop thru each data array
    foreach ($value as $k => $v) {   // Loop thru each data
        $result[$k][] = $v;          // Group all elements with same index
    }
}

// output each row of the data
foreach ($result as $row)            // Loop thru grouped result array
{
    fputcsv($file, $row);
}

Sample result array would be like this
$result = array (
    array ('Data 11', 'Data 21', 'Data 31', 'Data 41', 'Data 51'),
    array ('Data 12', 'Data 22', 'Data 32', 'Data 42', 'Data 52'),
    array ('Data 13', 'Data 23', 'Data 33', 'Data 43', 'Data 53'),
    array ('Data 14', 'Data 24', 'Data 34', 'Data 44', 'Data 54'),
    array ('Data 15', 'Data 25', 'Data 35', 'Data 45', 'Data 55')
);


text:
Q: How to configure unknown usb device as ethernet on Linux host? When my USB device was connected, I got the following:
$ dmesg | tail
[   79.612133] usb 2-2: new full-speed USB device number 3 using ohci-pci
[   79.937340] usb 2-2: New USB device found, idVendor=238b, idProduct=0a21
[   79.937343] usb 2-2: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[   79.937344] usb 2-2: Product: DMR Radio
[   79.937346] usb 2-2: Manufacturer: Hytera Communications
[   80.282770] cfg80211: Loading compiled-in X.509 certificates for regulatory database
[   80.286007] cfg80211: Loaded X.509 cert 'sforshee: 00b28ddf47aef9cea7'
[   80.399206] usbcore: registered new interface driver cdc_ether
[   80.404402] usbcore: registered new interface driver rndis_host
[   80.421516] usbcore: registered new interface driver rndis_wlan

There is no message like "cdc_subset 1-4.4.2:1.1: usb0: register 'cdc_subset' at usb-0000:00:02.1-4.4.2, Linux Device".
So there is no ethernet named as usb0.
$ uname -a
Linux VB1804 4.15.0-36-generic #39-Ubuntu SMP Mon Sep 24 16:19:09 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

It is shown as unknown device.
$ lsusb
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 003: ID 238b:0a21
Bus 002 Device 002: ID 80ee:0021 VirtualBox USB Tablet
Bus 002 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub

$ lsmod | grep usbnet
usbnet                 45056  3 rndis_host,cdc_ether,rndis_wlan
mii                    16384  1 usbnet

I got the same on physical Linux.
And,
$ usb-devices
--------- other usb devices ----

T:  Bus=02 Lev=01 Prnt=01 Port=01 Cnt=02 Dev#=  3 Spd=12  MxCh= 0
D:  Ver= 2.00 Cls=ff(vend.) Sub=fe Prot=fe MxPS= 8 #Cfgs=  1
P:  Vendor=238b ProdID=0a21 Rev=00.00
S:  Manufacturer=Hytera Communications
S:  Product=DMR Radio
C:  #Ifs= 3 Cfg#= 1 Atr=c0 MxPwr=4mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=02(commc) Sub=02 Prot=ff Driver=(none)
I:  If#= 1 Alt= 0 #EPs= 2 Cls=0a(data ) Sub=00 Prot=00 Driver=(none)
I:  If#= 2 Alt= 0 #EPs= 3 Cls=ff(vend.) Sub=ff Prot=ff Driver=(none)

A: I add the idVendor and idProduct to the white list of structure array prodocts[] in file rndis_host.c.
static const struct usb_device_id   products [] = {
{   /* DMR Radio*/
    USB_DEVICE_AND_INTERFACE_INFO(0x238b, 0x0a21,
                  USB_CLASS_COMM, 2 /* ACM */, 0x0ff),
    .driver_info = (unsigned long) &rndis_info,
}, {

And, It works.


text:
Q: syntax error on jsp update validation code After feeling the update database table form and submitting it I get this error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?, user_surname=?, email=?, phone_number=?, password=?, confirm_password=? wh...' at line 1. I am using JSP on Apache Netbeans 12.6, Here is my whole validation code.
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@page import="java.sql.*,java.util.*" %>

<% Class.forName("com.mysql.cj.jdbc.Driver"); %>
<%

   String user_role=request.getParameter("user_role");
   String user_name=request.getParameter("user_name");
   String user_surname=request.getParameter("user_surname");
   String email=request.getParameter("email");
   String phone_number=request.getParameter("phone_number");
   String password=request.getParameter("password");
   String confirm_password=request.getParameter("confirm_password");
   Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/simsdb","root","");
   Statement st=con.createStatement();
   int i=st.executeUpdate("update users set user_role=?, user_surname=?, email=?, phone_number=?, password=?, confirm_password=? where user_name=?");
   out.println("Updated");
   out.print("
<button type=\"button\">User Management</button>");
%>

I have tried many update validation codes but they just don't update anything at all. As for this code it worked on Delete and Insert so I believe it should work on update also.


text:
Q: How do I get the specific link under h3 tag?

male.celebs

      <img data-sizes="auto" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" data-srcset="/image/13663916/1x1/480/480/f957f70cc7d1c19a3b1d6ccef61118c4/Cp/ayden-sng-2020--tight-shot-.jpg 320w, /image/13663916/1x1/640/640/f957f70cc7d1c19a3b1d6ccef61118c4/Rb/ayden-sng-2020--tight-shot-.jpg 480w" class="lazyautosizes lazyloaded" alt="Ayden Sng 2020 (Tight Shot)" sizes="339px" srcset="/image/13663916/1x1/480/480/f957f70cc7d1c19a3b1d6ccef61118c4/Cp/ayden-sng-2020--tight-shot-.jpg 320w, /image/13663916/1x1/640/640/f957f70cc7d1c19a3b1d6ccef61118c4/Rb/ayden-sng-2020--tight-shot-.jpg 480w">

This is the information I get from the website and I'm trying to get the link from
from bs4 import BeautifulSoup

import requests

import re

def getHTMLdocument(url):

    response = requests.get(url)

    return response.text

url_to_scrape = "https://www.mediacorp.sg/en/your-mediacorp/our-artistes/tca/male-artistes"

html_document = getHTMLdocument(url_to_scrape)

soup = BeautifulSoup(html_document, 'lxml')

for link in soup.find_all('a',attrs={'href': re.compile("/en/")}):

    print(link.get('href'))

however the output from the code only gives me all the links on the page except for the ones under the h3 tag. is there anyway for me to access the codes under the h3 tag?

A: I'm assuming you are trying to get the "/en/your-mediacorp/our-artistes/tca/male-artistes/ayden-sng-12357686" links under the "card-media" attributes. That data is dynamic and what you are getting in the requests is the static html. You need to use the url that gets back that data.
from bs4 import BeautifulSoup
import requests
import re

def getHTMLdocument(url, payload):

    response = requests.get(url, params=payload)
    return response.text

url_to_scrape = 'https://www.mediacorp.sg/en/toggle/paginateLocalItems'
payload = {
'pageSize': '12',
'pageIndex': '0',
'contentId': '11831178',
'navigationId': '12302270',
'viewType': 'ajaxContentCardListing'}

html_document = getHTMLdocument(url_to_scrape, payload)
soup = BeautifulSoup(html_document, 'lxml')

links = []
for link in soup.find_all('a',attrs={'href': re.compile("/en/")}):
    if link.get('href') not in links:
        links.append(link.get('href'))
        print(link.get('href'))

You use those parameters in the payload to go get the other pages as well:
from bs4 import BeautifulSoup
import requests
import re

def getHTMLdocument(url, payload):

    response = requests.get(url, params=payload)
    return response.text

url_to_scrape = 'https://www.mediacorp.sg/en/toggle/paginateLocalItems'
links = []

page = 0
while True:
    #print('Page: %s' %(page+1))
    payload = {
    'pageSize': '12',
    'pageIndex': '%s' %page,
    'contentId': '11831178',
    'navigationId': '12302270',
    'viewType': 'ajaxContentCardListing'}

    html_document = getHTMLdocument(url_to_scrape, payload)
    soup = BeautifulSoup(html_document, 'lxml')

    if soup.find_all('a',attrs={'href': re.compile("/en/")}) == []:
        break

    for link in soup.find_all('a',attrs={'href': re.compile("/en/")}):
        if link.get('href') not in links:
            links.append(link.get('href'))
            print(link.get('href'))

    page+=1

Output:
/en/your-mediacorp/our-artistes/tca/male-artistes/ayden-sng-12357686
/en/your-mediacorp/our-artistes/tca/male-artistes/ben-yeo-12357544
/en/your-mediacorp/our-artistes/tca/male-artistes/benjamin-tan-12357684
/en/your-mediacorp/our-artistes/tca/male-artistes/brandon-wong-12357582
/en/your-mediacorp/our-artistes/tca/male-artistes/bryan-wong-12357546
/en/your-mediacorp/our-artistes/tca/male-artistes/cavin-soh-12357626
/en/your-mediacorp/our-artistes/tca/male-artistes/chen-han-wei-12357548
/en/your-mediacorp/our-artistes/tca/male-artistes/chen-shu-cheng-12357584
/en/your-mediacorp/our-artistes/tca/male-artistes/chen-tian-wen-12357586
/en/your-mediacorp/our-artistes/tca/male-artistes/chen-yi-xi-12357646
/en/your-mediacorp/our-artistes/tca/male-artistes/chew-chor-meng-12357588
/en/your-mediacorp/our-artistes/tca/male-artistes/desmond-ng-12357570
/en/your-mediacorp/our-artistes/tca/male-artistes/desmond-tan-12357590
/en/your-mediacorp/our-artistes/tca/male-artistes/edwin-goh-12357550
/en/your-mediacorp/our-artistes/tca/male-artistes/elvin-ng-12357552
/en/your-mediacorp/our-artistes/tca/male-artistes/glenn-yong-14218688
/en/your-mediacorp/our-artistes/tca/male-artistes/guo-liang-12357592
/en/your-mediacorp/our-artistes/tca/male-artistes/herman-keh-12357682
/en/your-mediacorp/our-artistes/tca/male-artistes/ian-fang-12357594
/en/your-mediacorp/our-artistes/tca/male-artistes/james-seah-12357596
/en/your-mediacorp/our-artistes/tca/male-artistes/jarrell-huang-12357654
/en/your-mediacorp/our-artistes/tca/male-artistes/jeffrey-xu-12357554
/en/your-mediacorp/our-artistes/tca/male-artistes/jeremy-chan-15172284
/en/your-mediacorp/our-artistes/tca/male-artistes/lee-teng--12357630
/en/your-mediacorp/our-artistes/tca/male-artistes/mark-lee-12357632
/en/your-mediacorp/our-artistes/tca/male-artistes/nick-teo-12357598
/en/your-mediacorp/our-artistes/tca/male-artistes/pierre-png--12357556
/en/your-mediacorp/our-artistes/tca/male-artistes/qi-yuwu-12357600
/en/your-mediacorp/our-artistes/tca/male-artistes/rayson-tan-12357562
/en/your-mediacorp/our-artistes/tca/male-artistes/richard-low-12357602
/en/your-mediacorp/our-artistes/tca/male-artistes/richie-koh-12357642
/en/your-mediacorp/our-artistes/tca/male-artistes/romeo-tan-12357558
/en/your-mediacorp/our-artistes/tca/male-artistes/shaun-chen-12357560
/en/your-mediacorp/our-artistes/tca/male-artistes/terence-cao-12357604
/en/your-mediacorp/our-artistes/tca/male-artistes/tyler-ten--12357694
/en/your-mediacorp/our-artistes/tca/male-artistes/yao-wen-long-12357564
/en/your-mediacorp/our-artistes/tca/male-artistes/zane-lim-12357692
/en/your-mediacorp/our-artistes/tca/male-artistes/zhai-siming--12357690
/en/your-mediacorp/our-artistes/tca/male-artistes/zhang-yao-dong-12357568
/en/your-mediacorp/our-artistes/tca/male-artistes/zhang-ze-tong--12357688
/en/your-mediacorp/our-artistes/tca/male-artistes/zheng-ge-ping-12357622
/en/your-mediacorp/our-artistes/tca/male-artistes/zhu-hou-ren-12358080

A: As alternativ approach to requests you can also go with selenium to get the urls.
Example
from bs4 import BeautifulSoup
from selenium import webdriver

driver = webdriver.Chrome('YOUR PATH TO DRIVER')
driver.get('https://www.mediacorp.sg/en/your-mediacorp/our-artistes/tca/male-artistes')

soup=BeautifulSoup(driver.page_source, 'html.parser')

[x['href'] for x in soup.select('div.card-item h3 > a')]

Output - List with urls
['/en/your-mediacorp/our-artistes/tca/male-artistes/ayden-sng-12357686',
 '/en/your-mediacorp/our-artistes/tca/male-artistes/ben-yeo-12357544',
 '/en/your-mediacorp/our-artistes/tca/male-artistes/benjamin-tan-12357684',
 '/en/your-mediacorp/our-artistes/tca/male-artistes/brandon-wong-12357582',
 '/en/your-mediacorp/our-artistes/tca/male-artistes/bryan-wong-12357546',
 '/en/your-mediacorp/our-artistes/tca/male-artistes/cavin-soh-12357626',
 '/en/your-mediacorp/our-artistes/tca/male-artistes/chen-han-wei-12357548',
 '/en/your-mediacorp/our-artistes/tca/male-artistes/chen-shu-cheng-12357584',
 '/en/your-mediacorp/our-artistes/tca/male-artistes/chen-tian-wen-12357586',
 '/en/your-mediacorp/our-artistes/tca/male-artistes/chen-yi-xi-12357646',
 '/en/your-mediacorp/our-artistes/tca/male-artistes/chew-chor-meng-12357588',
 '/en/your-mediacorp/our-artistes/tca/male-artistes/desmond-ng-12357570']


text:
Q: SQL Update values from multiple tables I have the following sql. I just want to update 2 fields from the table t1 and 1 field from t2. I tried to join the t2 but it doesnt work. Is it possible to update two tables?
And i want to update the t2.field with a const variable.
so that i get something like this
UPDATE test1_00 t1
                      SET (t1.field,
                           t1.field,
                           t2.field = 5)

UPDATE test1_00 t1
                      SET (t1.field,
                           t1.field,
                           t2.field) =
                        (SELECT test,
                                test,
                                test
                         FROM table(test_function(
                         02172,
                         'TEST',
                         date('2021-07-26'),
                         'TEST',
                         5455612)
                         )
                         join  test1 t1 on t1.id    = t2.id
                         where t2.test              = test
                         and   t2.test              = test
                         );

A: No.
An update can only update one table at a time.


text:
Q: Rails, param is missing or value:vote is empty i have a vote model which has a candidate_vote:integer which also has an association between a candidate. i tried creating a form and i get this error  param is missing or the value is empty: vote
this is the form
<%= form_for @vote do |f| %>

      <% Position.includes(:candidates).order(:name).each do |position| %>

          <%= position.name %>

        <% position.candidates.each do |candidate| %>

            <%= image_tag(candidate.image, :size => '50x50') if candidate.image.attached? %>
            <%= candidate.name %>
            <%= candidate.info %>
            <%= check_box_tag :candidate_votes, checked_value: '1', unchecked_value: '0' %>

        <% end %>
      <% end %>

  <%= f.submit "Submit" %>
<% end %>

and the controller
class VotesController < ApplicationController

    def new
        @vote = Vote.new
        @candidates = Candidate.all
    end

    def create
        @vote = Vote.create(vote_params)

        if @vote.save
            redirect_to @vote
        else
            render :new

        end
    end

    private

    def vote_params
        params.require(:vote).permit(:candidate_vote, :candidate_id)
    end

end

with its respective models
class Vote < ApplicationRecord
    belongs_to :candidate
end

class Candidate < ApplicationRecord

    belongs_to :position

    belongs_to :user

    has_many :votes

    has_one_attached :image

    validates :image, presence: true,  content_type: ['image/jpg', 'image/jpeg', 'image/png']

    validates :name, presence: true
    validates :info, presence: true
end

whats wrong please or what am i not doing right?

A: In your controller inside the create method change: @vote = Vote.create(vote_params) to  @vote = Vote.new(vote_params)
The rest is all looking good.

A: I hate ERB, have some nice HAML:
= form_for @vote do |f|
  %table
    %tbody
      - Position.includes(:candidates).order(:name).each do |position|
        %tr
          %th{colspan: 5}= position.name
      - position.candidates.each do |candidate|
        %tr
          %td= image_tag(candidate.image, :size => '50x50') if candidate.image.attached?
          %td= candidate.name
          %td= candidate.info
          %td= check_box_tag "vote[candidate_votes[#{candidate.id}]]", checked_value: '1', unchecked_value: '0'
  = f.submit "Submit"

as zhisme says, you aren't passing the id of the candidate through the form.
I'm assuming that you want the person to be able to vote for more than one candidate?  if you don't, it might be worthwhile looking at the "radio_button" object, and returning the candidate as the value. e.g.:
= form_for @vote do |f|
  %table
    %tbody
      - Position.includes(:candidates).order(:name).each do |position|
        %tr
          %th{colspan: 5}= position.name
      - position.candidates.each do |candidate|
        %tr
          %td= image_tag(candidate.image, :size => '50x50') if candidate.image.attached?
          %td= candidate.name
          %td= candidate.info
          %td= f.radio_button :candidate_votes, candidate.id
  = f.submit "Submit"


text:
Q: How do I make the entire citation a blue hyperlink Currently, I am using the following preamble on overleaf
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{booktabs}
\usepackage{outlines}
\usepackage{dirtytalk}
\usepackage{latexsym}
\usepackage{tabularx}
\usepackage[hidelinks,colorlinks=true,linkcolor=blue,citecolor=blue]{hyperref}
\usepackage{hyperref}
\usepackage{amsmath}
\usepackage{booktabs,caption}
\usepackage{longtable}
\usepackage{appendix}
\usepackage[para,online,flushleft]{threeparttable}
\usepackage[affil-it]{authblk}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage[a4paper]{geometry}
\renewcommand{\baselinestretch}{1.5}

\usepackage{url}
\renewcommand{\baselinestretch}{1.5}
\usepackage[backend=biber,style=bwl-FU,sorting=none]{biblatex}

\addbibresource{bibliography.bib}

\begin{document}

\title{Title}

\author{ABC}
\date{\today}

\maketitle
\section{Model}
In this context, healthcare utilization has two components that are important in justifying the estimation methods selected \cite{gerdtham1997equity}.

\printbibliography
\appendix
\setcounter{table}{0}

\end{document}

And the end result is in the image with the citation where only the year of publication is highlighted.

What I want out of the citation is the following:

Is there a way to edit the preamble to make my citations appear as shown in the second image?
Thanks!


text:
Q: Moving Footer to Top when ListView Above is Empty On my activity, I want to include a listview and a fragment that will always be included at the bottom of the listview. I initially tried using a scrollview with both inside, but since mixing a scrollview and a listview does not really work, I switched to using the fragment as a footer for the listview instead.
However, my listview is populated by entering data into the fragment and whenever the listview is empty, there's an empty space at the top of the page and the footer goes to the bottom of the screen. I want the footer to be initially at the top of the page when the listview is empty. When one entry is added, the entry should be at the top of the page with the footer right beneath it (not necessarily at the very bottom of the page yet), etc. I hope that makes sense!
Here's the code I'm using to set the footer:
 ListView listview = (ListView) findViewById(R.id.listview);
        View footer = getLayoutInflater().inflate(R.layout.frag_bottom, null);
        listview.addFooterView(footer);
        listview.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
        listview.setStackFromBottom(true);

Thanks!

A: Try setting your ListView's layout params height to wrap_content. This way the empty list would be 0 pixels high and the footer view at the top.
Maybe this post helps even better:
Height of ListView fills the whole screen, although set as wrap_content


text:
Q: set up a many-to-one relationship spring mvc im trying to learn some jsp as well as the spring framework.
My application has 2 sql tables. 'User' and 'Locations'
each Location belongs to a User. The location table has a foreign key referencing the id of the user.
I want to implement my application such that given a user (i.e 'user1') i can call user1.getLocations() to retrieve a list of the locations associated with that user, but i do not know where to implement this. (in the User class, on the UserDao, on the UserManager, on the controller for the page that should list all users and their , etc?)??
----edit:
On the controller:
    List<User> users = userManager.getUsers();
    for(User user:users) {
        user.setLocations(locationManager.getLocations(user));
    }

    myModel.put("users", users);
    return new ModelAndView("location", "model", myModel);
}

is this a conventional solution? locationManager.getLocations(user) returns a List of Locations with the same id as user.

A: Most likely in the UserDao class since it sounds like a DB operation. Also the method should be more like this signature userService.getLocations(userId) as opposed to user1.getLocation(), user2.getLocation()., etc.
You can get a quick overview of the MVC pattern, learn more about the Spring MVC and a tuotrial.
You will definitely need to chain your method calls to the dao from the view. So traditionally it's done this way: a request from the view (V in MVC)->controller dispatches (C in MVC)->service class (part of M in MVC)->dao class (also part of M in MVC) and sent back to view by flipping the directions.

A:
My application has 2 sql tables.
  'User' and 'Locations'
each Location belongs to a User. The
  location table has a foreign key
  referencing the id of the user.
  I want to implement my application such that given a user (i.e 'user1') i can call
  user1.getLocations() to retrieve a list of the locations associated with that user
  , but i do not know where to implement this.

I wouldn't create a separate DAO-method for handling this, the "user1.getLocations" is the right approach. Hibernate et al. support stuff like lazy-loading and mapping of table relations as Collections (like Lists and Sets) between entities, which are meant for these kind of situations. Here's a simple example,which might not work out-of-the-box, depending how your tables are named etc., but you'll get the idea:
@Entity
public class User
{
    @OneToMany(mappedBy="user")
    private List<Location> locations;

    public List<Location> getLocations()
    {
        return locations;
    }
}

@Entity
public class Location
{
    @ManyToOne
    @PrimaryKeyJoinColumn
    private User user;

    public User getUser()
    {
        return user;
    }
}

Note that you can get the locations from the User-side, even though the relation in the database is only from Location to User (the "mappedBy"-attribute in Users' @OneToMany actually tells which field on the "other side of the reference" (Location) points to this User).
I'd suggest looking up some JPA and/or Hibernate with Spring -tutorials for more in-depth information.


text:
Q: [Django]How to display a message(correct or incorrect) after submitting the form, without refreshing the page? I have a made a quiz page, which checks whether the answer of the user is correct or not using a "checkans" function. I want to return a "Correct" message if the answer is correct and an "Incorrect" message if the answer is not correct. Now I can "kind of" do it, but not exactly what I want. Now it returns the message after redirecting to a whole new page, with the Question Box and everything else totally disappeared, only with the message.
I want the message to be shown on the same original question page, somewhere under the question box or within the question box, without redirecting to another page or refreshing the page, after submitting the answer. I don't know how to do it.
Here is my view:
class QuizView(generic.ListView):
    template_name = 'geniusdennis/quiz.html'
    queryset = Spanish.objects.all()

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # grab the max id in the database
        max_id = Spanish.objects.order_by('-id')[0].id
        random_id = random.randint(1, max_id + 1)
        random_spanish_question = Spanish.objects.filter(id__gte=random_id)[0]
        context['random_spanish_question'] = random_spanish_question
        return context

Here is my function for checking the answer:
def checkans(request, spanish_id):
    random_spanish_question = get_object_or_404(Spanish, pk=spanish_id)
    query = request.GET.get('ans')
    coreng = random_spanish_question.english_set.get()
    if query == str(coreng):
        return render(request, 'geniusdennis/quiz.html',{
                'message': "Correct!",
            })
    else:
        return render(request, 'geniusdennis/quiz.html', {
                'message': "Incorrect.",
                'correct_answer': "The correct answer is " + str(coreng),
            })

And here is my HTML page:
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'geniusdennis/style.css' %}">

{% if random_spanish_question %}

Quiz time

{{ random_spanish_question }}

            <form action="/checkans/{{random_spanish_question.id}}/" method="get">{% csrf_token %}
                Answer:
                <input type="text" name="ans"/>
                <input type="submit" value="Submit"/>
            </form>
        <input type="submit" value="Skip"/>

{% else %}
{% if message %}

            {{ message }}

            {{ correct_answer }}

        {% endif %}
{% endif %}

A: What you need is ajax, so you need some js code here.
<scrip src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

html forms will go to action url. If you want some changes or functions in your page without reload, you need to use js.

A:
Quite commonly in web applications, you need to display a one-time
  notification message (also known as "flash message") to the user after
  processing a form or some other types of user input.
For this, Django provides full support for cookie- and session-based
  messaging, for both anonymous and authenticated users. The messages
  framework allows you to temporarily store messages in one request and
  retrieve them for display in a subsequent request (usually the next
  one). Every message is tagged with a specific level that determines
  its priority (e.g., info, warning, or error).

for implementing messages refer to: https://docs.djangoproject.com/en/1.11/ref/contrib/messages/


text:
Q: Drawer layout setBackgroundColor does not work I need to set the background color of my DrawerLayout at runtime.  Here's what I'm doing:
DrawerLayout drawerLayout = findViewById(R.id.drawer_layout);
drawerLayout.setBackgroundColor(Color.parseColor("#ffffff"));

I'm not really going to set it to a hard coded value, that's just for illustration. This seems to have no effect - the background stays a dark gray color that I think is picked up from a style somewhere.  I can set the background color of the ExpandableListView inside the DrawerLayout, but I can't get that to fill the vertical space, so some of the background is the correct color and the empty space is the wrong color.
Setting the background color of the ExpandableListView in XML works, but I need to be able to change it at run time.  If I don't set the ListView color in XML, the ListView will not fill the vertical space as I want it to do.  It just cuts off after displaying all the items. I've tried setting both the drawer layout and list background in Java, and the closest I can come to having any effect is the empty space below the list items changes color.  I cannot get the background of the actual list to change.  Any suggestions?
Layout XML:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".activities.MainActivity">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@color/primary"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                app:theme="@style/ToolBarStyle" />

            <FrameLayout
                android:id="@+id/frame_container"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </LinearLayout>
    </FrameLayout>

    <!-- The navigation drawer -->
    <ExpandableListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@color/drawer_background"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:groupIndicator="@null" />
</android.support.v4.widget.DrawerLayout>

Screen shot:

A: I think you need to set background for your NavigationView instead of DrawerLayout.
<android.support.design.widget.NavigationView
    android:id="@+id/navigationView"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:background="@android:color/white"        //set background here
    app:itemBackground="@android:color/transparent"
    app:menu="@menu/menu_navigation"/>

If you use ExpandableListView inside DrawerLayout. I think you should put the ExpandableListView inside a RelativeLayout. Like this:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".activities.MainActivity">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@color/primary"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                app:theme="@style/ToolBarStyle" />

            <FrameLayout
                android:id="@+id/frame_container"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </LinearLayout>

    </FrameLayout>

    <!-- The navigation drawer -->
    <RelativeLayout
        android:id="@+id/drawer_container"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@drawable/background"> //set background here

        <ExpandableListView
            android:id="@+id/left_drawer"
            android:layout_width="240dp"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:background="@color/drawer_background"
            android:choiceMode="singleChoice"
            android:divider="@android:color/transparent"
            android:dividerHeight="0dp"
            android:groupIndicator="@null" />

    </RelativeLayout>

</android.support.v4.widget.DrawerLayout>


text:
Q: Get average color of selected area in an image I have made some jQuery code, which can give average color of an image. But instead of getting average color of full image, I need to get the average color of circular custom selected area in that image. So that user can drag the custom circular area and get the average color of that specific area.

<img id="i" src="data:image/jpeg;base64,[encoded data, 14996 characters]" width="300" height="100"/>

<input type="file" id="upload">


text:
Q: Get large friend list profile pictures from LinkedIn using SocialAuth library I'm currently using the SocialAuth library to log into various social medias in my app, but i've run into an issue with LinkedIn.
I can easily get the profile image URL and use it to grab the image and put into an ImageView, but the image i get is 80x80 pixels, which is not ideal.
With both Facebook and Twitter, there was a distinction in the URL (small, normal, large) of some sort, where i could substring/replace to get the large image. But this option is not available for LinkedIn from the URLs i have available.
Is there some method that i'm missing, or is it simply not possible at the moment?

A: MAybe using ASNE library make your life easier?
Just add dependency to your project:
dependencies {
...
    compile 'com.github.asne:asne-facebook:0.2.0'
    compile 'com.github.asne:asne-twitter:0.2.0'
    compile 'com.github.asne:asne-linkedin:0.2.0'
...
}

setup and request any info like profile(with link and image socialNetwork.requestCurrentPerson();) or friends(just  socialNetwork.requestGetFriends();)


text:
Q: Get Hex Value From Farbtastic and convert to RGB for use in imagefilter in php I've got a working jquery code snippet that gets the hex value of my color picker farbtastic just fine. Problem I am having is taking that and applying it as a tint with  paintbrushjs. The Hex just does not transfer over to the id of the image and does not update the data-tint-pb-colour option. So I am possibly looking at a php option but would like input first on a possible fix as I've worked on this 3 days now and unable to get it to work.
JAVASCRIPT/JQUERY
$(document).ready(function() {
    $('#demo').hide();
    $('#picker').farbtastic('#color');
  });
     $(document).ready(function() {
        var picker = $.farbtastic('#picker');
        picker.linkTo(function onColorChange(color) {
        $('filter-tint').attr('data-pb-tint-colour',color)
        console.log(color, "hello world!");
        });
     });

HTML
<form action="" style="width: 400px;">

Color:<input type="text" id="color" name="color" value="#123456" />

</form>

I've basically hit a wall. Not sure how to make this work.
 fiddle.

A: If you don't mind not using PaintbrushJS, I found this answer which proposes to overlay a semitransparent div over your image. So basically, you set the div's dimensions and position equal to the image's dimensions and position. Then you set its background-color. Since you want the color to be transparent, you want to set a rgba value to the background-color. However, farbtastic returns a hex color, so you have to convert it to a rgba value.
First add the div:

The class overlay would have the following css at load:
.overlay
{
    display: block;
    position: absolute;
}

Then add the following code:
$(document).ready(function() {
    $('#picker').farbtastic('#color');
    var $picker = $.farbtastic('#picker');
    SetTintColor($("#color").val()); // Set tint at load too
    $picker.linkTo(function(hexColor) {
        SetTintColor(hexColor);
    });
});

function SetTintColor(hexColor) {
    var $filterImage = $('#filter-tint');
    var $overlay = $("#overlay");
    // Set the div's dimensions and position equal to the image's dimensions and position
    $overlay.css({
        "height": $filterImage.height(),
        "width": $filterImage.width(),
        "top": $filterImage.offset().top + "px",
        "left": $filterImage.offset().left + "px"
    });
    // The farbtastic plugin returns a hex color, but we want to set a rgba as the div's background-color,
    // so it can be transparent.
    var rgb = hexToRgb(hexColor);
    var opacity = 0.5; // This can be changed for a dynamic value
    // Concatenate the rgb's values + opacity to obtain a string representing the rgba
    var rgbaColor = "rgba(" + rgb.r + ", " + rgb.g + ", " + rgb.b + ", " + opacity + ")";
    $overlay.css("background-color", rgbaColor);

    // Change the color input's background-color
    var $colorInput = $("#color");
    $colorInput.val(hexColor);
    $colorInput.css("background-color", hexColor);
}

// Taken from https://stackoverflow.com/a/5624139/2835243
function hexToRgb(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}

So if you used PaintbrushJS only for the color tint, I suggest you simply do the above, because it's lighter, and because PaintbrushJS seems to have some problems.
JSFiddle example