text:
Q: Call multiple functions from one function in Postgres I have three functions that receive no arguments and just return the most recent data from 3 different tables in 3 different schemas.  Each function returns 4 columns of data, all of the same type.  How do I create 1 function that calls all three functions and gives the output of each function?
I tried using Perform "function1"; Perform "function2"; then select * from function3(); roughly speaking and nothing worked.


text:
Q: DataGridView - WinForms - Header text wraps too soon I have a DataGridView, and I want my columns to be as small as they can be so I can fit a lot of  columns on. However, I'm finding that the columns wrap when they don't need to.
Does anyone know how to work around this? I've tried looking at the Padding properties on the column.HeaderCell.Style property but it's actually set to 0 already, so I'm confused!

A: To change a whole row:
 dataGridView.Rows[0].DefaultCellStyle.Padding = new Padding(0, 0, 0, 0);

To change a column:
 dataGridView.Columns[0].DefaultCellStyle.Padding = new Padding(0, 0, 0, 0);

To change a single cell:
 dataGridView[0, 2].Style.Padding = new Padding(0, 0, 0, 0);

Change wrapmode:
dataGridView.Columns[0].DefaultCellStyle.WrapMode = DataGridViewTriState.True;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problema com um modal button Bom estou com um problema eu fiz um modal button, mas só está abrindo a primeira foto, a do cliente 1, as outras 3 ( cliente 2 3 4) não acontece nada qnd clica ..

.nav.nav-justified > li > a { position: relative; }
.nav.nav-justified > li > a:hover,
.nav.nav-justified > li > a:focus { background-color: transparent; }
.nav.nav-justified > li > a > .quote {
    position: absolute;
    left: 0px;
    top: 0;
    opacity: 0;
    width: 30px;
    height: 30px;
    padding: 5px;
    background-color: #13c0ba;
    border-radius: 15px;
    color: #fff;
}
.nav.nav-justified > li.active > a > .quote { opacity: 1; }
.nav.nav-justified > li > a > img { box-shadow: 0 0 0 5px #13c0ba; }
.nav.nav-justified > li > a > img {
    max-width: 100%;
    opacity: .3;
    -webkit-transform: scale(.8,.8);
            transform: scale(.8,.8);
    -webkit-transition: all 0.3s 0s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            transition: all 0.3s 0s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
.nav.nav-justified > li.active > a > img,
.nav.nav-justified > li:hover > a > img,
.nav.nav-justified > li:focus > a > img {
    opacity: 1;
    -webkit-transform: none;
            transform: none;
    -webkit-transition: all 0.3s 0s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            transition: all 0.3s 0s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
.tab-pane .tab-inner { padding: 30px 0 20px; }

@media (min-width: 768px) {
    .nav.nav-justified > li > a > .quote {
        left: auto;
        top: auto;
        right: 20px;
        bottom: 0px;
    }
}

#myImg {
    border-radius: 5px;
    cursor: pointer;
    transition: 0.3s;
}

#myImg:hover {opacity: 0.7;}

/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
}

/* Modal Content (image) */
.modal-content {
    margin: auto;
    display: block;
    width: 100%;
    max-width: 700px;
}

/* Caption of Modal Image */
#caption {
    margin: auto;
    display: block;
    width: 80%;
    max-width: 700px;
    text-align: center;
    color: #ccc;
    padding: 10px 0;
    height: 150px;
}

/* Add Animation */
.modal-content, #caption {
    -webkit-animation-name: zoom;
    -webkit-animation-duration: 0.6s;
    animation-name: zoom;
    animation-duration: 0.6s;
}

@-webkit-keyframes zoom {
    from {-webkit-transform:scale(0)}
    to {-webkit-transform:scale(1)}
}

@keyframes zoom {
    from {transform:scale(0)}
    to {transform:scale(1)}
}

/* The Close Button */
.close {
    position: absolute;
    top: 15px;
    right: 35px;
    color: #FFAE00;
    font-size: 40px;
    font-weight: bold;
    transition: 0.3s;
}

.close:hover,
.close:focus {
    color: #FF0004;
    text-decoration: none;
    cursor: pointer;
}

/* 100% Image Width on Smaller Screens */
@media only screen and (max-width: 700px){
    .modal-content {
        width: 100%;
    }
}
.fotdepoi{
 background-color: #DCDADA;
}
.fotdepoi h2{
  font-family: "Lato", sans-serif;
 text-shadow: 1px 2px 1px #000;
 font-size: 60px;
 font-weight: 700;
 letter-spacing: 4px;
 color:#0D9ECB;
}
.fotdepoi p{
 color:#000;
}

 <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">

    <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
 <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

Depoimento  de Clientes

Depoimentos de clientes
Navegue clicando nos icones.

Cliente 1 : - Cara empresa de responsa msm.
Garantiu o 10/0 da minha md10 rápido, e olha que duvidei...
Sem dúvidas foi um dinheiro bem aplicado!
Agora aproveitar a season livre dos trolls kkk..
Obrigado mesmo pessoal, ja tem um cliente e pode crer que vai ter bem mais, pq eu vou indicar pra vários brothers meus desde ja.
Obrigado mesmo... sucesso ai!

O Cliente comprou MD10 elo: Prata .

  ×

Clique na imagem acima para ver as FOTOS do serviço.

Cliente 2: - Maravilhosos! equipe de profissionais, super seguro e confiáveis, trabalho rápido e profissional...super recomendado.

O Cliente comprou MD10 ELO : GOLD 5.

  ×

Clique na imagem acima para ver as FOTOS do serviço.

Cliente 3: - Serviço muito bom, em menos de um dia já tive minha MD10 completa com 10 vitórias, recomendo está empresa 100%..

O cliente comprou MD10 Elo: Bronze 3

  ×

Clique na imagem acima para ver as FOTOS do serviço.

Cliente 4: - Serviço bom e rápido com preço justo, recomendo a todos que quiserem sair do hell elo o trabalho dessa empresa, 100% confiavel.

O cliente comprou MD10 Elo: Platina 4

  ×

Clique na imagem acima para ver as FOTOS do serviço.


text:
Q: Reproduce llvm IR type error programatically By sheer chance, I ran llc on some code dumped from a working llvm backend. By working I mean, there is production-level code, that compiles this example successfully and the result executes correctly.
Here is a (shortened and abstracted) excerpt:
%s = type { i8* }

define double @foo(i8*) { ret double 0.0 }

@"foo" = constant %s { double (i8*)* @"foo" }

llc complains:

error: element 0 of struct initializer doesn't match struct element
  type

How do I trigger the same error with the C++ API? The verifyModules setting does not produce any error.

A: llc is correct. Your struct has elements of type i8*, but your initializer has type (i8*)*, so you'd need explicit bitcast here. You could easily re-create the same code via C++ API, however, I believe you will receive an assert here with C++ API.


text:
Q: SVCUTIL excluding an endpoint of a multi-endpoint service I have a service that contains two endpoints.  I have a client that wants to use just the methods in one of the endpoints.  If I use Add Service Reference both endpoints and all their methods are imported.
I am working on defining an svcutil command and it appears the /et option is what I need to exclude the first endpoint and it's methods, but I can't find a clear example of a fully qualified type name.  Plus I'm not sure the /et switch is the switch I need to use.  The connection is being done through a wsdl for a C# implementation.
I've tried /et:namespace.class.interface name and every variation of this that I can think of, but the generated .cs file still contains all the methods for the endpoint that I don't need.
For example
namespace a.b.c
{
   public interface InterfaceToExclude
   {
     [OperationContract]
     bool MethodToExclude()
my service definition is
public class MyService: InterfaceToExclude, InterfaceToInclude
{
so would the /et switch be
1) /et:a.b.c.InterfaceToExclude   or
2) /et:a.b.c.InterfaceToExclude.MethodToExclude
sadly neither of these two options actually caused the generated .cs code to exclude the first endpoints interfaces, methods or data definitions.
my current svcutil command is
svcutil /target:code   http://machine.domain/path/MyService.svc /language:CS /et:a.b.c.InterfaceToExclude
Can you exclude the generation of the methods and support for one of the endpoints using the svcutil command?  If so what switches do this?  Is it includes or excludes?
Thanks!


text:
Q: Netty - Best way to transmit strings with line breaks? I am working on a protocol that uses a DelimiterBasedFrameDecoder for decoding, that splits the bytebuf whenever a line break is received.
Unfortunately, there must be the possibility to transmit strings with line breaks. By now the line breaks in the strings are read by the decoder and frames are created accordingly.
My idea is to encode those strings with Base64 and decode them after the framedecoder has done its work. My question is now, is there a better solution to this problem? Base64 brings overhead as well as additional encoding/decoding work.
Using another delimiter is not possible because i need it for the header fields of my protocol.

A: Use NUL delimiter based frame decoder and encoder for this in your pipeline. The delimiter documentation is here. For e.g in the decoder pipeline add the following.
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.nulDelimiter()));

same should be used while encoding for e.g.
@Sharable
public class NulEncoder extends OneToOneEncoder {

@Override
protected Object encode(ChannelHandlerContext ctx, Channel channel,
        Object msg) throws Exception {
    ChannelBuffer buffer = ChannelBuffers.wrappedBuffer((ChannelBuffer)msg, Delimiters.nulDelimiter());
    return buffer;
}
}


text:
Q: How can I do a migration on codeigniter? I'm using the migration codes which works on CodeIgniter 2 but they won't work on CodeIgniter 3
I have read most of the questions here similar to my problem but I could not find an answer.
........
class Migration_Create_users extends CI_Migration
{
   public function up()
   {
       $this->dbforge->add_field([
           'id'       => [
               'type'           => 'INT',
               'constraint'     => 11,
               'unsigned'       => true,
               'auto_increment' => true,
           ],
           'email'    => [
               'type'       => 'VARCHAR',
               'constraint' => '100',
           ],
           'password' => [
               'type'       => 'VARCHAR',
               'constraint' => '128',
           ],
           'name'     => [
               'type'       => 'VARCHAR',
               'constraint' => '100',
           ],
       ]);
       $this->dbforge->add_key('id', true);
       $this->dbforge->create_table('users');
   }
   public function down()
   {
       $this->dbforge->drop_table('users');
   }
}

class Migration extends Admin_Controller
{
    public function __construct()
    {
        parent::__construct();
    }
    public function index()
    {
        $this->load->library('migration');
        if (!$this->migration->current()) {
            show_error($this->migration->error_string());
        } else {
            echo 'Migration worked!';
        }
    }
}

//migration config
defined('BASEPATH') or exit('No direct script access allowed');
$config['migration_enabled']     = true;
$config['migration_type']        = 'sequential';
$config['migration_table']       = 'migrations';
$config['migration_auto_latest'] = false;
$config['migration_version']     = 001;
$config['migration_path']        = APPPATH . 'migrations/';

I expect to run the code then I get the table created in the database

A: Please do with the below function

class Migrate extends CI_Controller{

    public function index($version){
        $this->load->library("migration");

      if(!$this->migration->version($version)){
          show_error($this->migration->error_string());
      }
    }
}


text:
Q: cron.yaml, dae-nonrel, gae I managed to get my django project running on gae using djangoappengine-nonrel.  It is able to use sqlite3 which was my db in django project to start with.
Now I am trying to do a background schedule script which some one suggested to use cron.yaml but it seems my cron entry and app.yaml handler entry are not being scheduled.
any one using gae cron.yaml + app.yaml for scheduling and dae-nonrel for running django project ?
Regards,
Miten.

A: Cron jobs don't run automatically on the dev_appserver, you'll have to hook up cron manually.  But if it's visible in the dev_appserver admin interface, they should launch ok in production.
Remember there's also a separate "appcfg.py update_cron" to deploy the cron jobs as well.
https://developers.google.com/appengine/docs/python/config/cron#Cron_Support_in_the_Development_Server


text:
Q: What is the point of GLSL when there is OpenCL? Consider this the complete form of the question in the title: Since OpenCL may be the common standard for serious GPU programming in the future (among other devices programming), why not when programming for OpenGL - in a future-proof way - utilize all GPU operations on OpenCL? That way you get the advantages of GLSL, without its programmatic limitations.

A: In the future OpenCL might be able to replace GLSL. In the meantime there are still some issues with OpenGL interop, at least with the most important (NVidia/ATI) implementations.
OpenCL will not completely replace OpenGL, though. OpenGL does a whole lot more when it comes to raster graphics. The only raster graphics primitives in OpenCL are textures/images and it can't render graphics at all.

A: GLSL is a "shading language". It is used for 3D rendering and has special datatypes particularly useful for that purpose (e.g. length-4 vectors and rank-4x4 matrices). The vertex and fragment shaders sit in a well-defined location inside the rendering pipeline, and they are automatically triggered on data flowing through this pipeline. The shaders also have direct access to the tranformation and projection matrices of the 3D pipeline.
OpenCL is a "compute language". It is not specially designed for the compute tasks we see in 3D rendering, but is rather a subset of C. OpenCL does have data types similar to the vectors and matrices in GLSL (float4, float16), but they are less convinient to use. Also you don't have a graphics context (which can be an advantage or a disadvantage), and the OpenCL kernel does not reside inside a 3D rendering pipeline.
If you want compute modules that are plugged into the 3D rendering pipeline and are triggered by the rendering pipeline, use GLSL. If you want general computation on the GPU outside the 3D rendering pipeline use OpenCL.
That does not mean OpenCL cannot be used to render 3D graphics. It can. In fact, you can implement your own pipeline solely in OpenCL, and then copy your drawing to the framebuffer. But if you just want to draw some 3D graphics, duplicating all the work by SGI, Nvidia, Intel and AMD engineers is probably not worth the hassle. Then it is easier to just use GLSL and get the shader plugged into a ready-to-use and fully performant OpenGL pipeline. Just consider that it was a major undertaking to write Mesa, the open-source OpenGL implementation.

A: GLSL is OpenGL Shading Language.  It is intended, originally, for controlling the graphics pipeline.
OpenCL, on the other hand, is the Open Computing Language.  It does not control graphics, but rather computation.
The two technologies are targetting different capabilities and functionality.
That being said, moving forward, they may be very little reason to use GLSL for computation purposes.  However, as of today, more vendors fully support GLSL than OpenCL, so it is still useful for computation purposes even though it is limited as that is not its core purpose, at least right now.

A: @dietr: let me Eco you here! the CL/GL interoperability can harm considerably the overall performance, specially when handling a big number of object buffers (>100, for example). The context changing overhead and the lack of support for structures of buffer or pointers to buffers will just kill my apps, in such a way that I'm seriously considering the use of geometry shader to replace my opencl code. And don't fool yourself, a complete replacement of the entire opengl by opencl would require a whole recoding process which would not only be real long but also not that advantageous. Besides, as well said by the folks up-here, opengl does much more than just pipeline computation. I would say that if you intend to use CL/GL iterop, try to rewrite your code on vertex/geometry shader if you can.


text:
Q: SQL select statement avoiding duplicated rows based on primary key I have a table employee with two columns-empid(primary key), name. Suppose it has below three rows.
EmpID   Name
---------------
11      Name1
12      Name2
11      Name3

How would I write a select statement to select records avoiding the two rows which have duplicating empid. I used query like:
select empid, name
from(select empid, name, row_number() over(partition by empid order by empid desc) rnk
    from t)a
where a.rnk=1

But this query will give
EmpID   Name
---------------
11      Name1
12      Name2

As the result. But all I need is
EmpID   Name
---------------
12      Name2

A: Would not SELECT max(empid) as empid, name from employee group by name having count(distinct empid) < 2 work?

A: try this query, this will work and give you the row 12 Name2
select empid, name from employee a
join (
select empid , count(empid) as count1 from employee
group by empid
having count(empid)=1 ) b on a.empid=b.empid

A: select empid, name
from(select empid, name,count(*) over(partition by empid) cnt from t) t
where cnt=1

A: An anti join using NOT EXISTS might be the fastest approach:
SELECT  empID, Name
FROM    T
WHERE   NOT EXISTS (SELECT 1 FROM T AS T2 WHERE T2.EmpID = T.EmpID AND T2.Name <> T.Name);

I have done no testing, so it is possible that the optimiser might be able to generate a anti semi-join using a count = 1 operation, but this gives it the best possible chance of getting to that plan.


text:
Q: Filter out duplicates from two lists and change object property value if duplicate I have two lists AuthorList & AuthorList2. At the moment I am using union with simple IEqualityComparer class.
I expect to have a result list without any duplicates from AuthorList & AuthorList2 and if there are any duplicates in those lists, they need to be removed from the lists and the Author class Assigned property needs to be set true for the duplicate item.
Existing information from both AuthorLists:
ProductID & Assigned

*

*1, false

*2, false

*3, false

*1, false
Result list:
ProductID & Assigned

*

*1, true

*2, false

*3, false

The logic needs to filter out duplicates and if both of those lists have the same element, change false -> true.
namespace HelloWorld
{
     class Hello
      {
        static void Main()
        {

            List<Author> AuthorList = new List<Author>
            {
                new Author(1, false),
                new Author(2, false),
                new Author(3, false)
            };

            List<Author> AuthorList2 = new List<Author>
            {
                new Author(1, false)
            };

            var compareById = new AuthorComparer(false);

            var result = AuthorList.Union(AuthorList2, compareById);

            foreach (var item in result)
            {
                Console.WriteLine("Result: {0},{1}", item.ProductId, item.Assigned);
            }

            Console.ReadKey();
        }

        public class AuthorComparer : IEqualityComparer<Author>
        {
            private bool m_withValue;

            public AuthorComparer(bool withValue)
            {
                m_withValue = withValue;
            }

            public bool Equals(Author x, Author y)
            {
                return (x.ProductId == y.ProductId);
            }

            public int GetHashCode(Author x)
            {
                return x.ProductId.GetHashCode();
            }
        }

        public class Author
        {
            private int productId;
            private bool assigned;

            public Author(int productId, bool assigned)
            {
                this.productId = productId;
                this.assigned = assigned;
            }

            public int ProductId
            {
                get { return productId; }
                set { productId = value; }
            }

            public bool Assigned
            {
                get { return assigned; }
                set { assigned = value; }
            }
        }
      }
    }

A: The code you're looking for is this:
AuthorList.ForEach(a => a.Assigned = AuthorList2.Exists(b => b.ProductId == a.ProductId));

You don't need the IEqualityComparer at all.
Full, working code:
namespace HelloWorld
{
    class Hello
    {
        static void Main()
        {

            List<Author> AuthorList = new List<Author>
            {
                new Author(1, false),
                new Author(2, false),
                new Author(3, false)
            };

            List<Author> AuthorList2 = new List<Author>
            {
                new Author(1, false)
            };

            AuthorList.ForEach(a => a.Assigned = AuthorList2.Exists(b => b.ProductId == a.ProductId));

            foreach (var item in AuthorList)
            {
                Console.WriteLine("Result: {0},{1}", item.ProductId, item.Assigned);
            }

            Console.ReadKey();
        }

        public class Author
        {
            public Author(int productId, bool assigned)
            {
                this.ProductId = productId;
                this.Assigned = assigned;
            }

            public int ProductId { get; set; }

            public bool Assigned { get; set; }
        }
    }
}

A: With your comparer, you can use:
foreach (var author in AuthorList.Intersect(AuthorList2, compareById))
{
    author.Assigned = true;
}

You can do it without that easily enough as well if you don't need the comparer for anything else:
var author2Ids = new HashSet<int>(AuthorList2.Select(a => a.ProductId));
foreach (var author in AuthorList.Where(a => author2Ids.Contains(a.ProductId)))
{
    author.Assigned = true;
}

... but if you need the comparer for anything else, or if it may get more complex, I'd stick to using that.

A: Try with something like this. Please look at ! carefully
       //Separate out different entries from both the lists
        var diffList = AuthorList.Where(x => !AuthorList2.Any(y => y.ProductId== x.ProductId && y.Assigned== x.Assigned)).ToList();
       //Separate out common entries from both the list
        var commonList = AuthorList.Where(x => AuthorList2.Any(y => y.ProductId== x.ProductId && y.Assigned== x.Assigned)).ToList();
        //Change value of Assigned
        commonList.ForEach(x => x.Assigned = !x.Assigned);
       //Merge both the lists
       diffList.AddRange(commonList);

POC: DotNetFiddler

A: This will produce a new List of elements without altering the source:
private static List<Author> FilterDuplicates(List<Author> x, List<Author> y)
{
     return x.Select(author => new Author(author.ProductId, y.Exists(a => a.ProductId == author.ProductId))).ToList();
}


text:
Q: Eclipse - Will configuration and projects still work if moved to another computer/platform I am currently working on a homework project (Composed of several projects in the same workspace) and I am quite new to Eclipse.
From my experience, and what I have heard that the workspace of Eclipse is not designed to be portable. However, for the homework, I am asked to put all my projects from the workspace into a zip file and submit it.
I want to ask if I make sure I copy all the folders from the workspace (including .metadata folder, which I know is where the configurations are stored), will someone (i.e the professor) be able to use that folder (after unzipping) as a workspace and run them directly with configuration that I set up ? (Of course, we will ignore other potential incompatibilities for now. I just don't know if Eclipse will still load up the configurations).
Is there any requirements for this to work (Same version of eclipse, etc.)? Actually, the most important for me are the running configurations which are vital for my projects to work.


text:
Q: payment system intergration for custom epos software I'm trying my hand in the food industry. I'm going to be developing my epos system in house. All the fancy touch screen systems cost an arm and a leg. I was wondering what are my options if I wanted to integrate a chip and pin device as well? Could I use something like paypal? I doubt supermarkets use such a system though.

A: Have you considered Openbravo POS? It's great for a basic EPOS system, and has features such as Restaurant Mode (tables etc), as well as reporting facilities etc.  It's also free :-)
If you want to use Chip & Pin though, you'll need to write a custom Java module to compile into Openbravo, to link between whatever software your C&P device provides, and Openbravo itself.  I've done this for a custom Openbravo installation, but it is specific to the C&P device provider.
PayPal is an online web payment service provider - this is different to the hardware-based C&P.
Edit you're probably also better off talking to your bank about their options regarding C&P - they may be able to offer you such a service, or recommend a partner to lease you the hardware and provide support etc.

A: Ocius for PC, is a pre-approved chip and pin solution from Commidea, which you can integrate with your software.  You will need to have your integration tested by Commidea before you can deploy to any live sites.
Changing your software to work with Ocius should take a few days of coding and testing.
YESpay also offer chip and pin solutions, but I have no experience with them.

A: I would suggest ERPLY POS , its also free, usable over WWW and its really nice UI


text:
Q: How to prevent pyinstaller from giving error? I have made a script that basically does what grep on Linux does for Windows.
# grep.py

import re
import sys

class EnterArguments(Exception):
    pass

arguments = sys.argv

if len(arguments) == 2:
    contents = sys.stdin.readlines()
elif len(arguments) == 3:
    file = arguments[2]
    with open(file) as f:
        contents = f.read().split("\n")
else:
    raise EnterArguments("Arguments Were Not Given")

for line in contents:
    output = re.search(arguments[1], line)
    if output is not None:
        output = output[0]
        others = line.split(output)
        print(f"\033[92m{output}\033[0m".join(others), end="")

And when I make an executable using pyinstaller (pyinstaller --onefile grep.py) and run it using the Command Prompt I get:
$ grep.exe

Traceback (most recent call last):
  File "grep.py", line 20, in <module>
    raise EnterArguments("Arguments Were Not Given")
__main__.EnterArguments: Arguments Were Not Given
[1576] Failed to execute script grep

How can I prevent [1576] Failed to execute script grep from coming (is there any flags I can put)?


text:
Q: Create a Line graph with Dots and Labels using 2 different data sets I would like to create a line graph that also has dots with labels on it similar to:  I want to use 2 different data sets though because one of them is coming from an API.
Here are the two data sets:
Data set 1
09/01/17, 55.65
09/02/17, 63.88
09/03/17, 57.49
09/04/17, 58.59

Data set 2
09/01/17, 55.65, Label 1 here
09/02/17, 63.88, Label 2 here
09/03/17, 57.49, Label 3 here
09/04/17, 58.59, Label 4 here

Here's what I have so far (from this tutorial):
// Set the dimensions of the canvas / graph
var margin = {top: 30, right: 20, bottom: 30, left: 50},
width = 600 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;

// Parse the date / time
var parseDate = d3.time.format("%d-%b-%y").parse;

// Set the ranges
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);

// Define the axes
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(5);

var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);

// Define the line
var valueline = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); });

// Adds the svg canvas
var svg = d3.select("body")
.append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
.append("g")
    .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");

// Get the data
d3.csv("data.csv", function(error, data) {
data.forEach(function(d) {
    d.date = parseDate(d.date);
    d.close = +d.close;
});

// Scale the range of the data
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([0, d3.max(data, function(d) { return d.close; })]);

// Add the valueline path.
svg.append("path")
    .attr("class", "line")
    .attr("d", valueline(data));

// Add the scatterplot
svg.selectAll("dot")
    .data(data)
  .enter().append("circle")
    .attr("r", 3.5)
    .attr("cx", function(d) { return x(d.date); })
    .attr("cy", function(d) { return y(d.close); });

// Add the X Axis
svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

// Add the Y Axis
svg.append("g")
    .attr("class", "y axis")
    .call(yAxis);

});

function addLabels(){
    d3.csv("dataset2.csv", function(error, data){
        svg.append('g')
        .classed('labels-group', true)
        .selectAll('text')
        .data(data)
        .enter()
        .append('text')
        .classed('label', true)
        .attr({
        'x': function(d, i) {
                return x(d.date);
            },
            'y': function(d, i) {
                return y(d.data);
            }
        })
        .text(function(d, i) {
            return d.label;
        });
    });
}

addLabels();

Question: Can someone help me add labels to this the dots on this graph? Keep in mind I am using two different data sets.

A: OK, so it looks like your current function is creating the scatterplot from dataset1, what I'd do is add a second, entirely separate function for the labels:
function addLabels(){
d3.csv("dataset2.csv", function(error, data2){
svg.append('g')
.classed('labels-group', true)
.selectAll('text')
.data(data2)//this should have been data2, to reflect data coming from the second request.
.enter()
.append('text')
.classed('label', true)
.attr({
'x': function(d, i) {
return x(d.date);
},
'y': function(d, i) {
return y(d.data);
 }
})
.text(function(d, i) {
return d.label;
});
}
}

then call this function from the end of the function that draws the line (if it starts to slow things down, use a timer to allow the rest of the data to plot first).
Credit to this other user for the labels code. It's what I was thinking, but neater.
Edit: I forgot to change the dataset being used, see comment above.


text:
Q: python cant find packages on ec2 instance I am trying to run a python-script on an aws ec2-instance using jenkins.
I get the following error:
[ProdTest] $ /bin/sh -xe /tmp/jenkins14047325752732522807.sh
+ python3 prod.py
Traceback (most recent call last):
  File "prod.py", line 2, in <module>
    import base
  File "/home/jenkins-slave-strat/workspace/ProdTest/base.py", line 3, in <module>
    import boto3
ModuleNotFoundError: No module named 'boto3'
Build step 'Execute shell' marked build as failure
Finished: FAILURE

on the ec2 instance:
$ python3 --version
Python 3.7.9

$ pip3 install boto3 --user
WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip.
Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue.
To avoid this problem you can invoke Python with '-m pip' instead of running pip directly.
Requirement already satisfied: boto3 in /usr/local/lib/python3.7/site-packages (1.16.25)
Requirement already satisfied: jmespath<1.0.0,>=0.7.1 in /usr/local/lib/python3.7/site-packages (from boto3) (0.10.0)
Requirement already satisfied: s3transfer<0.4.0,>=0.3.0 in /usr/local/lib/python3.7/site-packages (from boto3) (0.3.3)
Requirement already satisfied: botocore<1.20.0,>=1.19.25 in /usr/local/lib/python3.7/site-packages (from boto3) (1.19.25)
Requirement already satisfied: urllib3<1.27,>=1.25.4; python_version != "3.4" in /usr/local/lib/python3.7/site-packages (from botocore<1.20.0,>=1.19.25->boto3) (1.26.2)
Requirement already satisfied: python-dateutil<3.0.0,>=2.1 in /usr/local/lib/python3.7/site-packages (from botocore<1.20.0,>=1.19.25->boto3) (2.8.1)
Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/site-packages (from python-dateutil<3.0.0,>=2.1->botocore<1.20.0,>=1.19.25->boto3) (1.15.0)

How do i get python to access the packages in /usr/local/lib/python3.7/site-packages ?
Thanks to everyone taking the time!

A: Before I give a short answer, a few cautions:

*

*I don't know what version of Linux (I assume) the EC2 instance is running.

*As a result, it's unclear if Python 2 is installed, but since you used pip3 and not just pip, it seems like it might be.

You could try altering your $PATH variable, but it's generally considered a good practice to use virtual environments for Python. I'm personally a fan of Conda, but you can find guides for Pipenv as well. My advice is; install Conda via Miniconda, then do the following:
$ conda create --name myAppEnv python=your.python.version
$ conda activate myAppEnv
$ conda install [your libraries]


text:
Q: Receiving an AJAX response in Node.js local server I am succesfully posting an AJAX Post request to my MongoDB.
However I cannot seem to grasp how to receive back a response.
I scoured for info and I got the impression that this has to do with the same-origin policy when running a local server.
I am trying to log the code that is sent via Ajax in the console.
PS: I am a complete beginner in Node.js.

Here is my code in users.js file
router.post('/adduser', function(req, res) {
    var db = req.db;
    db.collection('userlist').insert(req.body, function(err, result){
        res.send(
            (err === null) ? { msg: '',code:'1234' } : { msg: err }
        );
    });
});

And this is the Ajax call in global.js file
$.ajax({
            type: 'POST',
            data: newUser,
            url: '/users/adduser',
            dataType: 'JSON'
        }).done(function( response ) {

            // Check for successful (blank) response

            if (response.msg === '') {
                 console.log(response.code);
                // Clear the form inputs
                $('#addUser fieldset input').val('');

                // Update the table
                populateTable();

            }
            else {

                // If something goes wrong, alert the error message that our service returned
                alert('Error: ' + response.msg);

            }


text:
Q: If a vector subspace is in a union of other subspaces, then it's contained in one of them
Problem: Let $V$ be a finite dimensional vector space and $V_1,\ldots,V_n\subset V$ vector subspaces. Show that if $W\subset V$ is a vector subspace and
  $$W\subset V_1\cup\cdots\cup V_n,$$
  then
  $$W\subset V_k$$
  for some $1\le k\le n$.

I get the intuitive idea of why this should hold by drawing pictures, but I can't prove it rigorously. I know that if $V_1,V_2$ are two subspaces and $V_1\cup V_2$ is also a subspace, then $V_1\subset V_2$ or $V_2\subset V_1$. Does that help?


text:
Q: Using custom JSTL tags in a Struts tag attribute I have a custom JSTL tag say foo which writes a said property to the writer. Now I want to use the value that the tag wrote in a Struts tag. As an example, the custom tag is invoked as
<foo:property name="bar"/>

The Struts tag here is say <s:form/>. I want to be able to determine the value of the action attribute of the <s:form/> using the value from <foo:property/> like:
<s:form action="<foo:property name='bar'/>"/>

I understand that Struts tag attributes by default evaluate from objects on the ValueStack and we can use OGNL to precisely access those. The question really is if there is a way that we can put the value obtained from the custom JSTL on the ValueStack and then use OGNL to access it in the expression used to interpolate the action attribute.
Overall, is this possible at all? If so, a quick code snippet would really help clarify the solution.
Please let me know if I should clarify something.

A: The value that is written by the custom tag can be use as a body of the set tag, which put the value in the ValueStack, then you can access it via OGNL in the form tag attribute.

If the tag is used with body content, the evaluation of the value parameter is omitted. Instead, the String to which the body evaluates is set as value for the scoped variable.

<s:set var="foo"><foo:property name="bar"/></s:set>
<s:form action="%{#foo}">


text:
Q: How to evaluate methods timing in Visual Studio I developed a very complex webservice that performs a lot of operation, in particular operation on SqlServer.
Is it possible, while I'm attached to the deployed webservice, to monitor timing of every methods to understand where are the most time consuming ones?
Otherwise I've to put in my code a lot of stopwatches, and write somewhere the result.
Any idea to achieve my goal within visual studio?
Thanks!

A: Logging with stopwatches is good idea especially for undefined-time operations like calling a web service. This will enable you to investigate issues in release environment.
But if you have to investigate some performance issue locally, nothing is better than a specialized performance profiler. Visual studio 2010 (and I believe 2013) has a very good performance analyzer (included in Developer, Team and Ultimate editions as I remember). Here is beginner guide on it.
There are plenty other profilers, but for the needs you've described integrated Visual studio profiler will be more than fine.


text:
Q: Replace link location (jQuery) link

How do I replace link location from google.com to say "#"? $('a').attr( 'href', '#' ); isn't working.

A: It works for me.
Test code:

jQuery:
$("#MyLink").attr("href", "#");
alert($("#MyLink").attr("href")); //alerts "#"

Is it possible you are trying to do this before the DOM has loaded?
Also, what browsers are you using?
EDIT:
To ensure this is only done when the DOM is loaded completely, use the document .ready() function:
$(document).ready(function(){
    $("#MyLink").attr("href", "#");

    //other initialisation, e.g. event binding
});

A: Take a look at this question - How to change the href for a hyperlink using jQuery


text:
Q: Api complains no-referrer-when-downgrade with Keycloak I am trying to secure my api service that is running on jetty with Keycloak according to the documentation on https://www.keycloak.org/docs/latest/securing_apps/index.html#_jetty9_adapter.
I have created a clients user-svc that has the following installation in Keycloak:
{
  "realm": "databaker",
  "bearer-only": true,
  "auth-server-url": "http://localhost:8080/auth/",
  "ssl-required": "external",
  "resource": "user-svc",
  "confidential-port": 0
}

The jetty-web.xml configuration:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC "-//Mort Bay Consulting//DTD Configure//EN" "http://www.eclipse.org/jetty/configure_9_0.dtd">
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
    <Get name="securityHandler">
        <Set name="authenticator">
            <New class="org.keycloak.adapters.jetty.KeycloakJettyAuthenticator">
                <Set name="adapterConfig">
                    <New class="org.keycloak.representations.adapters.config.AdapterConfig">
                        <Set name="realm">databaker</Set>
                        <Set name="resource">user-svc</Set>
                        <Set name="authServerUrl">http://localhost:8080/auth/</Set>
                        <Set name="sslRequired">external</Set>
                        <Set name="bearerOnly">true</Set>
                        <Set name="confidentialPort">0</Set>
                    </New>
                </Set>
            </New>
        </Set>
    </Get>
</Configure>

and web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
    <servlet>
        <servlet-name>user-svc</servlet-name>
        <servlet-class>io.databaker.UserSvcServlet</servlet-class>
        <async-supported>true</async-supported>
    </servlet>
    <servlet-mapping>
        <servlet-name>user-svc</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

    <security-constraint>
        <web-resource-collection>
            <web-resource-name>user-svc</web-resource-name>
            <url-pattern>/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>user</role-name>
        </auth-constraint>
        <user-data-constraint>
            <transport-guarantee>CONFIDENTIAL</transport-guarantee>
        </user-data-constraint>
    </security-constraint>

    <login-config>
        <auth-method>BASIC</auth-method>
        <realm-name>this is ignored currently</realm-name>
    </login-config>

    <security-role>
        <role-name>admin</role-name>
    </security-role>
    <security-role>
        <role-name>user</role-name>
    </security-role>

    <filter>
        <filter-name>cross-origin</filter-name>
        <filter-class>org.eclipse.jetty.servlets.CrossOriginFilter</filter-class>
        <init-param>
            <param-name>allowedOrigins</param-name>
            <param-value>http://localhost:3000</param-value>
        </init-param>
        <init-param>
            <param-name>allowedMethods</param-name>
            <param-value>GET,POST,HEAD,PUT,HEAD,OPTIONS</param-value>
        </init-param>
        <init-param>
            <param-name>allowedHeaders</param-name>
            <param-value>X-Requested-With,Content-Type,Accept,Origin,Cache-Control</param-value>
        </init-param>
        <init-param>
            <param-name>chainPreflight</param-name>
            <param-value>false</param-value>
        </init-param>
        <async-supported>true</async-supported>
    </filter>
    <filter-mapping>
        <filter-name>cross-origin</filter-name>
        <url-pattern>/*</url-pattern>
        <url-pattern>/user/*</url-pattern>
        <url-pattern>/genders</url-pattern>
        <url-pattern>/interests</url-pattern>
    </filter-mapping>
</web-app>

The user-svc service is running on http://localhost:9090
java -jar start.jar -Djetty.http.port=9090
2020-07-13 10:20:16 INFO  log:169 - Logging initialized @230ms to org.eclipse.jetty.util.log.Slf4jLog
2020-07-13 10:20:17 WARN  HomeBaseWarning:72 - This instance of Jetty is not running from a separate {jetty.base} directory, this is not recommended.  See documentation at http://www.eclipse.org/jetty/documentation/current/startup.html
2020-07-13 10:20:17 INFO  Server:360 - jetty-9.4.29.v20200521; built: 2020-05-21T17:20:40.598Z; git: 77c232aed8a45c818fd27232278d9f95a021095e; jvm 11.0.7+10-LTS
2020-07-13 10:20:17 INFO  ScanningAppProvider:128 - Deployment monitor [file:///home/developer/playground/user-svc-env/jetty-svc/webapps/] at interval 1
2020-07-13 10:20:18 INFO  AnnotationConfiguration:473 - Scanning elapsed time=588ms
2020-07-13 10:20:18 INFO  session:334 - DefaultSessionIdManager workerName=node0
2020-07-13 10:20:18 INFO  session:339 - No SessionScavenger set, using defaults
2020-07-13 10:20:18 INFO  session:140 - node0 Scavenging every 600000ms
2020-07-13 10:20:18 INFO  ContextHandler:849 - Started o.e.j.w.WebAppContext@14dd7b39{root,/,file:///tmp/jetty-0_0_0_0-9090-root_war-_-any-934191447021540237.dir/webapp/,AVAILABLE}{/home/developer/playground/user-svc-env/jetty-svc/webapps/root.war}
2020-07-13 10:20:18 INFO  AbstractConnector:331 - Started ServerConnector@18ca3c62{HTTP/1.1, (http/1.1)}{0.0.0.0:9090}
2020-07-13 10:20:18 INFO  Server:400 - Started @1892ms

When calling the api service from the webapp, I have got the following error message

What am I doing wrong?


text:
Q: second remote git repo with submodules I am working with a git repository that contains a few submodules. In fact most of the work happens in the submodules and the root repo is just a way to keep things together.
What I would like to do is to copy the root (and all its folders) into another repository.
In the end, I would like to be able to push and pull from multiple remotes where one of the remote maintains the submodules (this means that the repository will use other repositories as submodules) and the other ones just keeps everything together as if its 1 repo.
Repository A
- folder A (this is a submodule)
- folder B (this is a submodule)
- folder C (this is a submodule)

Repsitory B
- folder A
- folder B
- folder C

Both repositories contain the exact same files and folders. The only difference is that one of them contains submodules whereas the other does not.
Is this even possible to do and if so - how can I achieve this ?


text:
Q: htaccess without redirect HTTP & HTTPS non-www to HTTPS www i have SEO problem for http to https and non-www to https://www
Please help me how to solve this problem?
this is my htaccess code:
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} somefolder
RewriteRule ^(.*)$ https://www.domain.com/somefolder/$1 [R,L]
# Ensure we are using HTTPS version of the site.
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http://www\.%{HTTP_HOST}/$1 [R=301,L]

A: For the latter rule, use:
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.(.+)$ [NC]
RewriteRule ^(.*)$ https://www\.%{HTTP_HOST}/$1 [R=301,L]

So now it redirects from all non-www. hosts to https://www, because the destination URL is changed.


text:
Q: Ajax upload PDF in iframe with jQuery I have a problem and i need some help. I just want to upload a file in Ajax with an input type file. And then without reload the page, show this pdf under my form on an iframe. I started like that :
$('#myform').on('submit.pdf-add', function(e){
    e.preventDefault();
    var $form = $(this);
    var url= $form.attr('action');
    $.ajax({
        type: "POST",
        url: url,
        data: {},
        dataType: 'json'
    })
    .done(function(data){
        if ($('input[type=file]').val().length != 0) {
            data_parsed = data;
            $('
Le pdf a été uploadé avec succès !
').append($form);
            $form.append('');
            $form.off('submit.pdf-add');
        } else {
            $('
Le pdf est inexistant !
').append($form);
        }
    })
    .fail(function(data){
        console.log(data);
        $("
Le fichier n'a pas été uploadé
").append($form);
    });
});*

I know File API is better but i need a cross browser support ! Thanks !


text:
Q: OpenGL the problem of figure rotation (the figure begins to shift) I draw two figures, in this method I rotate only one of them.but applying successive transformations over these two figures, I ran into a rotation problem.I can consistently apply scaling, offset to these figures separately and everything works fine, in the sense that by changing one figure, the previous one retains its previous state. But it doesn't work the same way with rotations. I do the displacement of the figure, and then the rotation of the other, then again the transformation over the first figure, and the second figure that I rotated begins to change its position too, although it should not do this. Tell me, what is the problem?
    private void rotateARL(float x)
    {
        Gl.glClear(Gl.GL_COLOR_BUFFER_BIT);
        Gl.glPushMatrix();
        Gl.glMatrixMode(Gl.GL_MODELVIEW);
        Gl.glScaled(s2, s2, 1);
        Gl.glRotated(ang2, 0, 0, 1);
        Gl.glTranslatef(dx2, dy2, dz2);
        draw2();
        Gl.glPopMatrix();
        Gl.glPushMatrix();
        Gl.glMatrixMode(Gl.GL_MODELVIEW);
        Gl.glScaled(s1, s1, 1);
        Gl.glTranslatef(dx1, dy1, dz1);
        ang1 += x;
        Gl.glRotated(ang1, 0, 0, 1);
        draw1(points1);
        Gl.glPopMatrix();

        simpleOpenGlControl1.Invalidate();
    }


text:
Q: Java Head First Chapter 7 MonsterTestDrive Exercise

I've got a problem with exercise in Java Head First. Basically I don't understand why output changes based on return true or false. Why does return value have anything to do with print?
public class MonsterTestDrive {
    public static void main(String [] args) {
        Monster [] ma = new Monster[3];
        ma[0] = new Vampire();
        ma[1] = new Dragon();
        ma[2] = new Monster();
        for(int x = 0; x < 3; x++) {
            ma[x].frighten(x);
        }
    }
}
class Monster {

// A

}
class Vampire extends Monster {

// B

}
class Dragon extends Monster {
    boolean frighten(int degree) {
        System.out.println("breath fire");
        return true;
    }
}

Which of the A-B pairs of methods listed on the right, if inserted into the classes on the left, would compile and produce the output shown?
(The A method inserted into class Monster, the B method inserted into class Vampire.)
//1
boolean frighten(int d) {
    System.out.println("arrrgh"); //A
    return true;
}
boolean frighten(int x) {
    System.out.println("a bite?");//B
    return false;
}

//2
boolean frighten(int x) {
    System.out.println("arrrgh");//A
    return true;
}
int frighten(int f) {
    System.out.println("a bite?");//B
    return 1;
}

//3
boolean frighten(int x) {
    System.out.println("arrrgh"); //A
    return false;
}
boolean scare(int x) {
    System.out.println("a bite?");//B
    return true;
}

//4
boolean frighten(int z) {
    System.out.println("arrrgh");//A
    return true;
}
boolean frighten(byte b) {
    System.out.println("a bite?");//B
    return true;
}

The correct answer is option /1.

A:
I don't understand why output changes based on return true or false

Because that's not the important difference between the examples. The point here is that Vampire (i.e. B) inherits from Monster (i.e. A) and we want the behavior of calling frighten to change from the default of printing "arrrgh" and print "a bite?" instead. To do that we need to override frighten in the Vampire class.
The catch is that the base method and the overriding one must have

*

*the same name

*the same return type and

*the same arguments (meaning same number and same type, not necessarily same name).

All three of these conditions must be true.

*

*This satisfies all three conditions
boolean frighten(int d) {
    System.out.println("arrrgh"); //A
    return true;
}
boolean frighten(int x) {
    System.out.println("a bite?");//B
    return false;
}

*Here B has a different return type, so it doesn't satisfy condition 2
boolean frighten(int x) {
    System.out.println("arrrgh");//A
    return true;
}
int frighten(int f) {
    System.out.println("a bite?");//B
    return 1;
}

*Here B has another name entirely, so it doesn't satisfy condition 1.
boolean frighten(int x) {
    System.out.println("arrrgh"); //A
    return false;
}
boolean scare(int x) {
    System.out.println("a bite?");//B
    return true;
}

*Here the argument type for B is byte instead of int, so it doesn't satisfy condition 3.
boolean frighten(int z) {
    System.out.println("arrrgh");//A
    return true;
}
boolean frighten(byte b) {
    System.out.println("a bite?");//B
    return true;
}


text:
Q: Remove padding on the left and right of a grid system I have a grid system with 10px padding between columns. But i don't want that padding on the left and right side of the whole grid. I have tried putting the columns in a big wrapper and adding margin-left: -10px and margin-right:-10px but it just moves the grid left.

CSS:
.row,
.column {
  box-sizing: border-box;
}
.column {
  position: relative;
  float: left;
  display: inline-block;
}
.column-1 {
  width: 33.3333333%;
}
.column-2 {
  width: 66.6666666%;
}
.column-3 {
  width: 100%;
}
.column {
  min-height: 60px;
  padding: 10px;
}
.inner {
  height: 100px;
  width: 100%;
  background: black;
  display:block;
  position: relative;
}

JS Fiddle

A: I notice you have a .row class defined in your css, but aren't using it.
If you start using it, and embed your columns within a row, you can use :first-child and :last-child selectors to change the margins on the end columns.
Like so
.row .column:first-child {
  padding-left: 0;
}

.row .column:last-child {
  padding-right: 0;
}

Fiddle


text:
Q: Workaround for UnsupportedAudioFileException? I'm in a very early stage of writing a small music/rhythm game in Java (via Slick framework, which in turns uses OpenAL, but that's probably irrelevant here). The game needs to read (and playback) several sound files in WAV format, but some of the files are throwing [javax.sound.sampled.UnsupportedAudioFileException] exceptions.
at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1102)
at org.newdawn.slick.openal.WaveData.create(WaveData.java:123)
at org.newdawn.slick.openal.SoundStore.getWAV(SoundStore.java:713)
at org.newdawn.slick.openal.SoundStore.getWAV(SoundStore.java:683)
at org.newdawn.slick.Sound.<init>(Sound.java:33)

The files can be played back just fine in Winamp or Foobar2000, so this means Java just don't recognize some variants of the file format. What are my options at this point?
Note: The files in question are user-supplied, so i cannot just convert them beforehand (using something like audacity). Any conversion steps must be done at runtime.

A: One thing that needs to be recognized about WAV files are, is that it is a container format -- it can hold data in many different formats, including uncompressed PCM to MP3.
In this case, I am going to guess that the library that is being used is hooking into the Java Sound API, and the implementation of the API does not support the format of the data contained in the WAV file, leading to an UnsupportedAudioFileException exception.

The files can be played back just fine
  in Winamp or Foobar2000, so this means
  Java just don't recognize some
  variants of the file format.

The reason why Winamp and other programs can playback the WAV file is because it is probably using the Windows Audio Compression Manager or (if I understand correctly) DirectShow, which is used to manage different types of audio codecs.
Winamp itself does not need to know how to decode the audio data inside the WAV file; it asks ACM or DirectShow to return the raw audio data on which it can handle. (Or also possibly, the data is directly send to the audio output.)

What are my options at this point?

An alternative does seem to exist in the form of the Java Media Framework, which appears to have support many multimedia formats.
It says that it will hook into the Windows ACM when using the "JMF 2.1.1 Windows Performance Pack", so it might be able to playback the WAV files which can't be played back by the Java Sound API.


text:
Q: декодировка изображений в WinForms cli в мне нужна помощь. В моем мессенджере требуется отправка не только сообщений, но и изображений разных форматов. Посоветуйте библиотеки или в принципе как декодировать изображения, а также как собрать из байтов изображение на другой стороне сети.

A: Через консоль (system) преобразуй расширение командой ren в .txt затем читай файл и отправляй текст. На обратной стороне аналогично


text:
Q: Counting data points in each 'pixel' I am having issue writing a function that will scan a (for example) 10×10 pixel area for the amount of data points with a certain average.
My issue is getting a 10×10 area across the x axis while keeping the y axis at a constant and then once the x axis 'scan' is complete moving up 10 pixels on the y axis and repeating the scan on the x axis.
# creating a standard to compare images against.
# from corner dark region with a lack of sources.
baseline = np.mean(
           M91_master_image[0].data[1800:2000, 1800:2000]
    + 4 * (M91_master_image[0].data[1800:2000, 1800:2000].std())
)

mst_image_data = M91_master_image[0].data

o_y = 400
o_y2 = 2000
o_x = 400
o_x2 = 2000
s = 10  # pixel increments

x_array = []
y_array = []

while o_x < o_x2:
    # print(o_x)
    counts = mst_image_data[o_x:o_x + s, o_y:o_y + s]
    if counts.mean() > baseline:
        x_pos_c = (o_x + (o_x + s))/2
        # print(x_pos_c)
        x_array = np.append(x_array, x_pos_c)
        # print(o_x)
        y_pos_c = (o_y + (o_y + s))/2
        y_array = np.append(y_array, y_pos_c)
    o_y += s
    o_x += s

print(x_array, y_array)

From the image you can see what I get is a diagonal:


text:
Q: Apply CSS style within .js var I'm currently building a game which relies on a random number to show a particular string from an array within a .js file. What I want to do is effectively apply a span element to certain text within the array - eg. make positive outcomes green & negative red, however I can't figure out how to do this outside of html. Eg:
var data = [
  {"label": "Question 1", "value": 1, "question": "Awareness: High, Consistency: Low."},
  {"label": "Question 2", "value": 1, "question": "Consistency: High, Awareness: Low."},
]

A separate set of code, after selecting a random number, returns data[i].label. How would I set a span within js so that the "High" strings return in green, and "Low" return in red?
Cheers.

A: You have not specified much, but I went and did what I could.
First, your span
here we go

The CSS file, minimalist, I did not include Bootstrap for this.
span {color:green}
.red{color:red}

The JS, the is no event, or event handler.
var data = [

{"label": "Question 1", "value": 1, "question": "Awareness: High, Consistency: Low."},
{"label": "Question 2", "value": 1, "question": "Consistency: High, Awareness: Low."}
]
The array, I have removed the trailing comma after the second object.
let outputs = data[0].question; This will hold the result from the array, data[0] targets the first object, you can also get map over the properties, but you have not entirely specified the scope and desired functionality.

 var output = document.getElementById('result'); // the span element
 output.innerText = outputs;                     // i prefer innerText to innerHTML
 if (outputs.includes("Consistency: Low")) {     // new string method includes, you can pass the whole ("Consistency: Low")in with no worries.
  output.classList.toggle("red");    // if condidtion is true, toggle the red class

  }

Codepen
https://codepen.io/damPop/pen/ZwvvGV?editors=0010

A: Uses classes

var data = [
  {label: "Question 1", value: 1, awareness: 'High', consistency: 'Low' },
  {label: "Question 2", value: 1, awareness: 'Low', consistency: 'High' },
  {label: "Question 3", value: 1, awareness: 'Low', consistency: 'Low' },
  {label: "Question 4", value: 1, awareness: 'High', consistency: 'High' }
];

const questionElement = document.getElementById('question');
const awarenessElement = document.getElementById('awareness');
const consistencyElement = document.getElementById('consistency');

document.getElementById('select').addEventListener('click', select);

select();

function select() {
  const question = data[Math.floor(Math.random() * 4)];
  questionElement.innerText = question.label;
  awarenessElement.innerText = `Awareness: ${question.awareness}`;
  awarenessElement.className = question.awareness;
  consistencyElement.innerText = `Consistency: ${question.consistency}`;
  consistencyElement.className = question.consistency;
}
.High {
  background-color: green;
}

.Low {
  background-color: red;
}

<button id="select">Select</button>


text:
Q: ReactJS - component does not load with url parameter Component does not load when I manually enter a url with parameter in the browser's search bar and naturally it says 'not working' in the console but when I click on a button going to '/:username' url from my index page, I don't get any error, it works pretty well. Where am I wrong?
router.js
const Main = () => (

<Switch>
  <Route exact path="/login" component={FrontLogin} />
  <Route path="/register" component={FrontRegister} />
    <IndexRoute exact path="/home" component={FrontHome} />
    <IndexRoute exact path="/:username" component={FrontProfile} />
    <Redirect to="/home" />
  </Switch>

)

index.js
class Index extends Component{
    render(){
        return(
            <Provider {...Store}>
                <BrowserRouter>
                    <Route component= {Main}/>
                </BrowserRouter>
            </Provider>
        )
    }
}

ReactDOM.render(<Index/>,document.getElementById('index'))

profile.index.js
const Profile = (props) => {
    const {params} = props.match;
    const [data, setData] = useState({});
    const history = useHistory();
    const [refresh, setRefresh] = useState(false);

console.log(props);
if(!props.location.key){
    console.log('not working');
}

if (props.location.key) {
    useEffect(() => {
        axios
            .get(
                `/api/${params.username}`,

                {
                    headers: {
                        Authorization:
                            "Bearer " +
                            props.AuthStore.appState.user.access_token,
                    },
                }
            )
            .then((res) => {
                if (res.data.username) {
                    setData(res.data);
                    setRefresh(true);
                }
            })
            .catch((error) => {
                console.log(error);
            });
    }, [refresh]);
}

console.log(refresh);

ProvideRoute.js
const PrivateRoute = ({
    component:Component,
    path,
    ...rest
}) => (
    <Route path= {path} {...rest}
    render={
        props => isLoggedIn ? (
            <Component {...props}/>
        ) : (
            <Redirect to={{
                pathname:"/login",
                state:{
                    prevLocation:path,
                    error:'Giriş yapmalısın.'
                }
            }}/>
        )
    } />
)

export default withRouter(PrivateRoute);


text:
Q: How can I trim a WAV file? I need to trim a .wav file in wp7. I have some some code but it's not working. Does anyone know how to trim a wav file in windows phone 7?
Below is the code that I have that doesn't work.
    public IsolatedStorageFileStream TrimWavFile(string FileName, TimeSpan cutFromStart, TimeSpan cutFromEnd)
    {
        long start = Convert.ToInt64((16 / 8) * 16000 * cutFromStart.TotalSeconds);
        long end = Convert.ToInt64((16 / 8) * 16000 * cutFromEnd.TotalSeconds);

        IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
        IsolatedStorageFileStream stream = storage.OpenFile(FileName as string, FileMode.Open, FileAccess.Read);

        byte[] buffer = new byte[stream.Length];
        stream.Read(buffer, 0, buffer.Length);

        return TrimWavFile(stream, start, end);
    }

    private IsolatedStorageFileStream TrimWavFile(IsolatedStorageFileStream reader, long startPos, long endPos)
    {
        IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
        IsolatedStorageFileStream writer = new IsolatedStorageFileStream("t",  FileMode.OpenOrCreate,storage);

        reader.Position = startPos;
        byte[] buffer = new byte[1024];
        while (reader.Position < endPos)
        {
            int bytesRequired = (int)(endPos - reader.Position);
            if (bytesRequired > 0)
            {
                int bytesToRead = Math.Min(bytesRequired, buffer.Length);
                int bytesRead = reader.Read(buffer, 0, bytesToRead);
                if (bytesRead > 0)
                {
                    writer.Write(buffer, 0, bytesRead);
                }
            }
            Makewav.WriteHeader(writer, (int)writer.Length - 44, 1, 16000);
        }
        return writer;
    }

A: First, it doesn't look like you are accounting for the wav header when you are skipping to your startPos, so your placement will be off.
Secondly I'm guessing there may be a block alignment issue. Does it come out as static when you try to play it? Some sample code from NAudio showing how to trim a wav file ( http://mark-dot-net.blogspot.com/2009/09/trimming-wav-file-using-naudio.html ) shows this:
startPos = startPos - startPos % reader.WaveFormat.BlockAlign;

So you just need to figure out your block align size and calculate it like that, most likely. Same with your end position.

A: I had the wave header in the loop, I moved it out of the loop, removed the -44 in the writer.length.
I just had to seek the stream back to the beginning and it worked.

A: In order to find the header information such as sample rate, num samples... etc, you may need to read the WAV File Specification https://ccrma.stanford.edu/courses/422/projects/WaveFormat/
This open source project http://code.google.com/p/musicg/ may give a reference for you. It's written in Java but the trimming logic is the same.


text:
Q: Paste IF value in target I want to create a macro to copy a range (C2:C22) where there are formulas and paste it on column range (D2:D22) as values. My problem is that every 6 cells I have a formula and I don't want the macro to override it.
I have been trying with this macro, but it doesn't copy formulas, only values and I need to paste on values, not on formulas.
Thanks!
Sub example()
    Dim source As Range
    Dim target As Range
    Set source = ActiveSheet.Range("c2:c22")
    Set target = ActiveSheet.Range("d2:d22")
    copy_formulas source:=source, target:=target

End Sub

Public Sub copy_formulas(source As Range, target As Range)
    'Assumes that all formulas start with '=' and all non formulas do not
    Dim i As Long
    Dim j As Long
    Dim c As Range

    For i = 1 To source.Rows.Count
        For j = 1 To source.Columns.Count
            Set c = source(RowIndex:=i, ColumnIndex:=j)
            If Left(c.Formula, 1) <> "=" Then
                target(RowIndex:=i, ColumnIndex:=j).Value = c.Value
            End If
        Next j
    Next i
End Sub

A: Change the inside of your loop to:
Set c = target(RowIndex:=i, ColumnIndex:=j)
If Left(c.Formula, 1) <> "=" Then
    c.Value = source(RowIndex:=i, ColumnIndex:=j).Value
End If

Your current code is testing whether there is a formula in the source cell, but your question implies that you should be testing for a formula in the target cell.

A: This loop might be more efficient:
Dim rSource As Range
Dim rTarget As Range
Set rSource = Worksheets("Sheet1").Range("C2:C22")
Set rTarget = Worksheets("Sheet1").Range("D2:D22")
For Item = 1 To rSource.Count
   If Not rTarget.Cells(Item).HasFormula Then
      rTarget.Cells(Item).Value = rSource.Cells(Item).Value
   End If
Next Item


text:
Q: Is $\Phi(-a(x+b))+\Phi(-a(x-b))$ log-concave in $x$ over the interval $x \in [0, \infty)$? Let $f(x)=\Phi(-a(x+b))+\Phi(-a(x-b))$, where $\Phi(\cdot)$ is the c.d.f of the standard normal, and $a>0$.
I would like to know if $\partial^2 \ln(f(x))/\partial x^2<0$  over the interval $x \in [0, \infty)$. I believe this is true, but I am having difficulty proving it. I would be immensely thankful to anyone who might help.

A: $\newcommand\num{\operatorname{num}}\newcommand\den{\operatorname{den}}$This is not true in general. E.g.,
$$\frac{\partial^2 \ln f(x)}{\partial x^2}=0.16522\ldots>0$$
at $(a,b,x)=(1,-5,-4)$.

The OP has changed the question, by adding the condition $x\ge0$, thus invalidating the answer above.
After the change, the answer becomes positive.
Indeed, by a horizontal rescaling of the graph of $f$, without loss of generality (wlog) $a=1$.  Also, wlog $b>0$, since $f$ is even in $b$.
It is enough to show that
\begin{equation}
    r:=L'=\frac\num\den
\end{equation}
is decreasing on $[0,\infty)$, where
\begin{equation}
    L:=\ln f,
\end{equation}
\begin{equation}
    \num(x):=-h(-b-x)-h(b-x),\quad\den(x):=H(-b-x)+H(b-x),
\end{equation}
and $h$ and $H$ denote, respectively, the pdf and the cdf of the standard normal distribution.
Consider the "derivative ratio"
\begin{equation}
    \rho(x):=\frac{\num'(x)}{\den'(x)}= \frac{b \left(e^{2 b x}-1\right)}{e^{2 b x}+1}-x.
\end{equation}
Note that
\begin{equation}
    \rho''(x)=-\frac{8 b^3 e^{2 b x} \left(e^{2 b x}-1\right)}{\left(e^{2 b
   x}+1\right)^3}<0
\end{equation}
(for $x>0$). So, the function $\rho$ is concave. Also, $\rho(0)=0$. Hence, $\rho$ is up-down on $[0,\infty)$ -- that is, for some $c\in[0,\infty]$ the function $\rho$ is increasing on $[0,c]$ and decreasing on $[c,\infty)$. Note also that $\num(\infty-)=0=\den(\infty-)$.
The crucial point of this proof is the use of the l'Hospital-type rule for monotonicity given in line 3 of Table 4.1, which now implies that, just as the "derivative ratio" $\rho$, the function $r$ is up-down on $[0,\infty)$. But
\begin{equation}
    r'(0)=-\frac{4h(b)^2}{(H(-b)+H(b))^2}<0.
\end{equation}
Thus, $r$ decreasing on $[0,\infty)$. $\quad\Box$


text:
Q: Need shell script to trigger .py(python script) which is in remote machine I'm having total 2 servers:

*

*Server1 -> Splunk server(Splunk Monitoring tool)

*Server2 -> Server that has python scripts.

In Server1 if any alter triggers there is an option to run a script. So when alert triggers I need a shell script which can login into Server2(which has python code located in C:\abc\pythonscripts\xyz.py) and execute it.
I don't have any coding knowledge and I need help in getting shell query which can trigger python script which is located in different server.


text:
Q: Spring Java Mongodb Aggregation check userId in array I have a MongoDB database with users and questions.
My Question document:
{
"_id" : "b943d57a-f4c3-4394-86f7-dd1d1b5e2563",
"_class" : "org.company.app.model.Question",
"statement" : "First question for testing purposes",
"userMail" : "themail@mail.com",
"responses" : [
    {
        "responseId" : "6b60e900-0fec-47d2-8853-e1ea3508abe6",
        "responseType" : "TEXT",
        "mail" : "themail2@mail.com",
        "responseTime" : ISODate("2017-11-22T11:23:10.848Z"),
        "data" : "New Response 1",
        "likes" : [
            "themail3@mail.com",
            "themail5@mail.com"
        ],
        "dislikes" : [],
        "state" : "PUBLISHED",
        "stateTime" : ISODate("2017-11-22T11:23:10.848Z")
    }
  ],
"categories" : [
    "Category1",
    "Category2",
    "Category3"
],
"creationTimestamp" : ISODate("2017-10-26T14:50:12.717Z"),
"lastUpdateTimestamp" : ISODate("2017-11-02T15:35:20.818Z"),
"deleted" : false,
"active" : true,
"state" : "PUBLISHED"
}

and the user document:
{
"_id" : "1f4b5091-c755-4083-880e-e1c4696f7236",
"_class" : "org.company.app.model.User",
"allowsComms" : true,
"registrationConfirmed" : false,
"placeOfWork" : "Urban records",
"name" : "John",
"surname" : "Doe",
"mail" : "themail3@mail.com",
"phone" : "[ \"1111111111\" , \"2222222222222\"]",
"birthDate" : ISODate("1971-12-10T23:00:00.000Z"),
"gender" : "MALE",
"nationality" : "US",
"language" : "en",
"socialNetworks" : {
    "INSTAGRAM" : "@instagram",
    "TWITTER" : "@twitter"
},
"specialty" : "alternative rock",
"subspecialty" : "sub_3",
"creationTimestamp" : ISODate("2017-10-31T10:13:12.131Z"),
"lastUpdateTimestamp" : ISODate("2017-11-13T10:23:37.637Z"),
"deleted" : false,
"active" : true,
"profileImage" : "image"
}

From that point, I'm creating a new aggregation to join both collections, get user information and count likes and dislikes instead of return all the user ids at that array.
public List<JoinedResponse> getResponses(String userId, String questionId, long itemsPerPage, long requestedPage) {

    Assert.hasLength(questionId, "questionId cannot be null or empty");

    MatchOperation questionIdMatch = Aggregation.match(new Criteria("_id").is(questionId));
    MatchOperation responsesStateMatch = Aggregation.match(Criteria.where("responses.state")
            .in(QuestionState.PUBLISHED.toString(), QuestionState.APPROVED.toString()));

    LookupOperation userInfoLookUpOperation = LookupOperation.newLookup().from("User").localField("$responses.mail").foreignField("mail")
            .as("userInfo");

    ProjectionOperation fieldsProjectionOperation = Aggregation.project(Fields.from(
            Fields.field("responseId", "$responses.responseId"),
            Fields.field("responseType", "$responses.responseType"),
            Fields.field("mail", "$responses.mail"),
            Fields.field("responseTime", "$responses.responseTime"),
            Fields.field("data", "$responses.data"),
            Fields.field("state", "$responses.state"),
            Fields.field("userName", "$userInfo.name"),
            Fields.field("userSurname", "$userInfo.surname"),
            Fields.field("profileImage", "$userInfo.profileImage")))
            .and("$responses.likes").size().as("likes")
            .and("$responses.dislikes").size().as("dislikes");

    // Creates the Aggregation: THE ORDER IS IMPORTANT!!!
    Aggregation ag = Aggregation.newAggregation(
            questionIdMatch,
            Aggregation.unwind("responses"),
            responsesStateMatch,
            userInfoLookUpOperation,
            Aggregation.unwind("userInfo"),
            fieldsProjectionOperation,
                Aggregation.project("responseId", "userName", "userSurname", "mail", "responseType", "responseTime",
                    "data", "likes", "dislikes", "profileImage", "state"/*, "isLiked"*/),
            Aggregation.skip((long) ((requestedPage - 1) * itemsPerPage)),
            Aggregation.limit(itemsPerPage));

    logger.debug(ag.toString());
    AggregationResults< JoinedResponse > output = mongoTemplate.aggregate(ag, "Question",
            JoinedResponse);

Well, at this point, I need to know if the userId is in the liked or disliked list and I have spend a lot of hours investigating with no result. Of course, I would like to do it with aggregation.
Any help will be appreciated.
Thank you!


text:
Q: Slow decreasing function that exhibits asymptotic behaviour I am currently doing some work on modelling the effects of treated nets usage on mosquito populations. Nets do not retain their maximum efficacy forever. They lose their chemical efficacy after about three years and all that is left is the physical protection offered by the net which I estimate to be $20\%$ of the original efficacy.
I am trying to model this behaviour. I need a continuous function over the interval $[0,1095]$ which decreases slowly  from 1 when $x=0$ and asymptotically approaches $0.2$ when $x \to 1095 $.
I tried an ellipse of the form $y=\sqrt{1-\dfrac{x^2}{(1095)^2}}$, but I realized the function is equal to zero when $x=1095$, which is not what I want.
Any help will be appreciated.

A: From you question, it is unclear exactly what shape you are looking for, and there are many functions that could describe the behaviour you're after. However, two possible options could be the negative exponential and a negative Gompertz function. Possible forms of these could be:
Negative exponential
$y(x)=e^{−ax+\ln{(1-b)}}+b,$
where $b=0.2$ and a is a rate parameter.
Negative Gompertz
$y(x) = 1-\alpha e^{-\beta e^{-\gamma x}},$
where $\alpha=0.8$ (describing the asymptote), $\beta$ in an inflection parameter (given a displacement along the $x$-axis), and $\gamma$ is a rate parameter.
These functions can give results such as:

In these examples, $a = 0.005$ for the negative exponential and $\beta = 150$, $\gamma = 0.008$ for the gompertz v1 and $\beta = 5$, $\gamma = 0.005$ for the gompertz v2.
An alternative parametrization of the Gompertz, which might be easier to understand, is:
$y(x) = 1-\alpha e^{-e^{-\gamma (x-\beta)}},$
where the inflection point ($\beta$) is directly related to the scale of the $x$-axis (so $\beta = 400$ would give an inflection at $x = 400$).
I hope these examples are interesting for you, and they can maybe provide a starting point.

Note: This answer was originally posted at Biology-SE, where this question was first posted.

A: How about something like
$$
y=1-0.8\,\frac{e^{ax}-1}{e^{1095a}-1}?
$$
The sign of $a$ determines concavity or convexity; $a=-0.005$ gives a nice graph.


text:
Q: Eclipse Operation Failure When Using Periods For some reason after I type a period "." my eclipse instance gives me a "Cannot Perform Operation - This compilation unit is not on the build path of a Java project" Error. I understand the issue, but can't seem to get it working again...
The current project that I'm busy with is a java file imported via Maven.
Eclipse Version:
Eclipse Java EE IDE for Web Developers.
Version: Oxygen.2 Release (4.7.2)
Build id: 20171218-0600
Java Advanced Preferences

A: Thanks to both @nitind and @howlger. The issue I had was due to the fact that I had to many "Content Assist" options selected which was causing for an unnecessarily long scroll between content. This coupled with the fact that my project was imported as a Maven project and not a Java project cause the issue.
Because of it not being seen as a Java project, some of the Java "Content Assists" didn't recognize the project, which gave me the error above and because I had so many assists selected it kept giving me the error no matter how many times I scrolled.
I fixed the issue by converting the project back to java type as well as removing all the extra "Control Assist" options.

A: I have the same problem and I just solved it. Thanks

*

*First, type " . " (period) on eclipse the error will appear then click the content assist

*Click on Content Assist Settings and you will see " Auto activation triggers for Java ",then delete the " . " (period) click apply to save.


text:
Q: Bizarre Arduino C++ compile error depends on file location I recently posted this as a possible bug in the Arduino forum (https://forum.arduino.cc/index.php?topic=656968), but I suspect they are going to "ho-hum, so what?" it because it goes outside of their standard rules for Arduino library organisation. However, I still want to understand why it is failing and I suspect this is the only place I will get decent and/or definitive answers:
( For the record, an arduino library normally sits in a folder which has a library.properties metadata "manifest" and a src folder containing all the files. Their build system automatically compiles (and links!) all the .cpp files in src  - whether they are used or not. Obviously in 99% of cases all of them are used /needed, but for various reasons...)

BEGIN INCLUSION
Version 1.8.10
ESP8266 core 2.6.2
Before we start, I have written several several successful libraries and I am familiar with the "standard" way of doing things. I say this because what follows may be considered "non-standard" although it is syntactically valid and in all but one instance, compiles and runs successfully. I came across it by accident while experimenting to try and get round the restriction of compiling everything in src folder whether you want it or not
In the failing instance, I get a compilation error that I have never seen before,don't understand and makes no sense; but worse: it should not be happening at all as it is a) valid code b) functionally identical to the working cases - and compiles cleanly when not in a separate folder as is the current case...
The fundamental problem then is that the only significant difference between failure or success of this piece of valid C++ code is its physical location in the file system, which baffles me.
First the sketch:
#include <H4P_WiFiX.h>

void f1(){}
void f2(){}
/*
 * H4P_WiFi has defaults of [](){}, [](){}
 */
//H4P_WiFi h4wifi(f1,f2); // compiles OK
//H4P_WiFi h4wifi([](){},f2); // compiles OK
//H4P_WiFi h4wifi(f1,[](){}); // compiles OK
//H4P_WiFi h4wifi(f1); // compiles OK
//H4P_WiFi h4wifi([](){},[](){}); // compiles OK
//H4P_WiFi h4wifi([](){}); // compiles OK
H4P_WiFi h4wifi; // using BOTH defaults (and ONLY that case), fails with the "helpful":
/*
C:\Users\phil\AppData\Local\Temp\ccnwDwvr.s: Assembler messages:

C:\Users\phil\AppData\Local\Temp\ccnwDwvr.s:21: Error: symbol `_ZNSt17_Function_handlerIFvvEZN8H4P_WiFiC1ESt8functionIS0_ES3_Ed_NUlvE_EE9_M_invokeERKSt9_Any_data' is already defined

C:\Users\phil\AppData\Local\Temp\ccnwDwvr.s:97: Error: symbol `_ZNSt14_Function_base13_Base_managerIZN8H4P_WiFiC1ESt8functionIFvvEES4_Ed_NUlvE_EE10_M_managerERSt9_Any_dataRKS7_St18_Manager_operation' is already defined

*/

void setup() {}

void loop() {}

Now the bizarre stuff:
The "odd" folder structure is:
libraries/H4Pwtf
|--optional
     |
     |--H4P_WiFi.cpp
     |--H4P_WiFi.h
     |--H4Plugins.h

!--src
     |
     |--H4P_WiFiX,h
     |--H4Plugins.cpp
library.properties

src/H4P_WiFiX.h
#ifndef H4P_WiFi2_H
#define H4P_WiFi2_H
// Yes, I know, I know! See above - it's valid even though weird
#include"../optional/H4P_WiFi.cpp"

#endif

src/H4Plugins.cpp
#include"../optional/H4Plugins.h"

H4PluginService::H4PluginService(H4P_FN_VOID onConnect,H4P_FN_VOID onDisconnect){}

optional/H4P_Plugins.h
#ifndef H4P_HO
#define H4P_HO

#include<functional>

using H4P_FN_VOID = std::function<void()>;

class H4Plugin {};

class H4PluginService: public H4Plugin {
    public:
        H4PluginService(H4P_FN_VOID onConnect=[](){},H4P_FN_VOID onDisconnect=[](){});
};

#endif // H4P_HO

optional/H4P_WiFi.h
#ifndef H4P_WiFi_HO
#define H4P_WiFi_HO

#include"H4Plugins.h"

class H4P_WiFi: public H4PluginService{
    public:
        H4P_WiFi(H4P_FN_VOID onConnect=[](){},H4P_FN_VOID onDisconnect=[](){});
};

#endif // H4P_WiFi_HO

optional/H4P_WiFi.cpp
#include"H4P_WiFi.h"

H4P_WiFi::H4P_WiFi(H4P_FN_VOID onC,H4P_FN_VOID onD): H4PluginService(onC,onD){}

Needless to say, if I move this all to src and edit the "weird" includes back to < > variants instead of " " versions and don't do the bizarre inclusion of .cpp (obvs because it will get compiled anyway by virtue of just "being there") then the line that shouldn't fail doesn't fail and everything compiles and runs 100% as expected.
But that's not the point: It looks to me as if the build system is including something twice when it shouldn't be...and I just cannot fathom that error! Any ideas?
END INCLUSION

So, overflowers: can anyone explain the bug and when it only happens when both defaults are used?

SOLVED thanks to "walnut". A residual issue is that he compiler bug only manifests when the two-identical-lambdas-as-defaults function is defined out-of-class. I moved it back inside, recompiled using my much-derided (but working) non-standard file organisation and: Bingo! Code now running exactly as expected and compiling in only #included modules. I'm a happy bunny. Thanks to others who contributed also. Case closed. +1 to stackoverflow

A: You can boil down the problematic code to the following minimal reproducible testcase, after substituting the #include directives and removing parts that do not affect the resulting error:
#include<functional>

using H4P_FN_VOID = std::function<void()>;

class H4P_WiFi{
    public:
        H4P_WiFi(H4P_FN_VOID onConnect=[](){}, H4P_FN_VOID onDisconnect=[](){});
};

H4P_WiFi::H4P_WiFi(H4P_FN_VOID, H4P_FN_VOID) {}

H4P_WiFi h4wifi;

int main() {}

Compiling this as a single compilation unit does indeed still generate the error messages with GCC, even on the most recent release 9.2, while Clang has no problem with it, see this godbolt.
The error messages GCC 9.2 gives during assembly are very similar to yours:
/tmp/cceVlRkg.s: Assembler messages:
/tmp/cceVlRkg.s:77: Error: symbol `_ZNSt14_Function_base13_Base_managerIZN8H4P_WiFiC4ESt8functionIFvvEES4_Ed_UlvE_E10_M_managerERSt9_Any_dataRKS7_St18_Manager_operation' is already defined
/tmp/cceVlRkg.s:131: Error: symbol `_ZNSt17_Function_handlerIFvvEZN8H4P_WiFiC4ESt8functionIS0_ES3_Ed_UlvE_E9_M_invokeERKSt9_Any_data' is already defined

Demangling the symbol names we get:
std::_Function_handler<void (), H4P_WiFi::H4P_WiFi(std::function<void ()>, std::function<void ()>)::{default arg#1}::{lambda()#1}>::_M_invoke(std::_Any_data const&)
std::_Function_base::_Base_manager<H4P_WiFi::H4P_WiFi(std::function<void ()>, std::function<void ()>)::{default arg#1}::{lambda()#1}>::_M_manager(std::_Any_data&, std::_Function_base::_Base_manager<H4P_WiFi::H4P_WiFi(std::function<void ()>, std::function<void ()>)::{default arg#1}::{lambda()#1}> const&, std::_Manager_operation)

I am pretty sure this is a compiler bug in GCC. On GCC trunk (on godbolt), we even get an ICE (internal compiler error):
<source>:12:16: error: Two symbols with same comdat_group are not linked by the same_comdat_group list.
   12 | H4P_WiFi h4wifi;
      |                ^
_ZNSt9_Any_data9_M_accessIZN8H4P_WiFiC4ESt8functionIFvvEES4_Ed_UlvE_EERT_v/1079 (_Tp& std::_Any_data::_M_access() [with _Tp = H4P_WiFi::<lambda()>]) @0x7f019ddbd000
  Type: function definition analyzed
  Visibility: public weak comdat comdat_group:_ZNSt9_Any_data9_M_accessIZN8H4P_WiFiC4ESt8functionIFvvEES4_Ed_UlvE_EERT_v one_only visibility_specified
  previous sharing asm name: 1078
  References:
  Referring:
  Function flags: body
  Called by: static void std::_Function_base::_Base_manager<_Functor>::_M_destroy(std::_Any_data&, std::true_type) [with _Functor = H4P_WiFi::<lambda()>]/1077
  Calls: void* std::_Any_data::_M_access()/217
_ZNSt9_Any_data9_M_accessIZN8H4P_WiFiC4ESt8functionIFvvEES4_Ed_UlvE_EERT_v/1078 (_Tp& std::_Any_data::_M_access() [with _Tp = H4P_WiFi::<lambda()>]) @0x7f019ddb7e10
  Type: function definition analyzed
  Visibility: public weak comdat comdat_group:_ZNSt9_Any_data9_M_accessIZN8H4P_WiFiC4ESt8functionIFvvEES4_Ed_UlvE_EERT_v one_only visibility_specified
  next sharing asm name: 1079
  References:
  Referring:
  Function flags: body
  Called by: static void std::_Function_base::_Base_manager<_Functor>::_M_destroy(std::_Any_data&, std::true_type) [with _Functor = H4P_WiFi::<lambda()>]/1073
  Calls: void* std::_Any_data::_M_access()/217
<source>:12:16: internal compiler error: symtab_node::verify failed
Please submit a full bug report,
with preprocessed source if appropriate.
See <https://gcc.gnu.org/bugs/> for instructions.
Compiler returned: 1

A similar bug has been reported in this GCC bug report. Apparently it only manifests for an out-of-class-defined member function of a class when called using at least two default arguments, each containing a lambda of equal signature.
Indeed if I e.g. add a parameter to one of the lambda's parameter list (e.g. [](auto...){} or [](int=0){}), but not the other ones, then there is no error.
But if I add the same to both, we have again the same error.

A: Most interactive build systems would create a compile module for each .cpp file unless explicitly instructed otherwise. I don't know an IDE which would not assume this as the only possible way. This would lead to breach of ODR rule, because HP4_WiFi module would contain same definitions as as HP4_Plugins module. In your case that is definition of that constructor.
Why it doesn't happen when constructor is not called? Undefined, but compiler likely just done some optimization and excluded unreferenced symbols.
Playing with <> and "" you likely introduce another uncertainity because that does nothing but to tell preprocesser to check default folders first instead of folder where including file is located. Your code may pick up something else from outside!
You either have to avoid including .cpp file (duh!) or, if reason to include it to be inlined (or templated), rename it to someting else, e.g.  .inl.


text:
Q: Accuracy of sys.dm_exec_procedure stats I am trying to trend some system performance over time, but I've hit a couple of stumbling blocks with sys.dm_exec_procedure_stats that I can't reconcile.
If I take sys.dm_exec_procedure_stats and join it to sys.dm_exec_query_stats matching on plan_Handle, I am getting some data that doesn't make sense to me.
Execution_Count - Sometimes this matches very well between the two and other times it is off by tens of thousands of executions. Looking at procedure stats I have one procedure that has 771 executions.   It has 4 matching query plans, all of which show 1 execution_count.
Total_Worker_Time - Procedure_Stats is reporting 2x-3x what summing the query_plans do.  295,977 versus 130,212.
Last_Worker_Time - Procedure_Stats versus sum of query_stats matches almost exactly.
Min_Worker_Time - Procedure_Stats versus a min of query_stats is close
Max_Worker_Time - Procedure_Stats versus a sum of query_stats is close
Total_Elapsed_Time - Procedure_Stats versus a sum of query_stats is off.  Procedure_Stats is 7x longer
Last_Elapsed_Time - Procedure_Stats versus a sum of query_stats is very close
min_Elapsed_time - Procedure_Stats versus a min of query_stats is close.
Max_Elapsed_Time - Procedure_Stats versus a sum of query_stats is off.  Procedure_Status is 4x longer.
I find it odd that some of these match up and other do not, but the mismatches here make me distrust this data in general.   I'm most interested in the total times, the execution_counts (to get averages) and the min/max times.
Could anyone explain why these mismatch or which is best to use and how do I know I can trust it?  Does the max time and total time in procedure_stats include client wait times or something else that skews these?


text:
Q: Move/rename project in Visual Studio 2008 with TFS Our team is developing a new product on the base of the old one and I received an honorable task of renaming old projects to the new name. For example:

*

*project OldProductLib.vcproj must become NewProductLib.vcproj

*\main\OldLib must become \main\NewLib

... and such.
Does anyone have a methodology and/or tool that would help me do this? What I'm looking for is a tool which will rename directory, update solution, correctly update TFS.

A: You can rename the projects in Visual Studio, and it'll fix up a lot of stuff for you.  It won't, however, fix the folder names.  Here's what I do when renaming a project.
1) Remove the project from the solution.
2) Rename the folder the project is in.
3) Re-add the project to the solution.
4) Rename the project in Visual Studio.
This will leave behind some items, like dlls with the old name in the bin folders.
Now, for the TFS problem.  I think when you add the projects back into the solution they will want to create new entries in TFS.  This probably isn't what you want.  I don't have a TFS available to me in order to test this right now, so I might have this part wrong, but I think if you were to update the "working folder" for a project between steps 2 and 3 it might hook it back up correctly.  Try this with a small sample solution before doing it with anything terribly important.

A: I understand this is possible but it is a painful experience. An easier option is to create a new project and branch everything into it.

A: You have to use the TFS "Source Control Explorer" view for renaming.

A: This is possible in Visual Studio 2012 and Team Foundation Server 2012. Take a look at my answer to a related question, for a step-by-step guide on how to rename the project folder and keeping your TFS source control history for both the files and the project.

A: Have you tried doing it in visual studio...
It can rename your project and I think creates the folders and the like for you.

A: Renaming project folders in Visual Studio 2008 has been discussed here, and the accepted solution was very useful to me.
Unfortunately, I am unable to help with TFS, but if you use Visual Studio to change the path to the project, perhaps it will handle the situation gracefully (one would expect it would).

A: For the TFS part, I think you can use "Change Source Control" command at File->Source Control to rebind the projects after moving.


text:
Q: Converting CSS Matrix3d Transform into Euler Angles I'm unsure if this is possible, given that the order rotations are applied can affect the form of the rotational matrix; but I'd like get the Euler angles from a CSS matrix3d Transform. I'm finding a dearth of documentation on the format of the matrix3d and how transformations are applied. Here's my code so far:
getRotation: function (el) {
    var matrix = Esprit.getTransform(el);
    // 2d matrix
    if (matrix.length === 6) {
        return {
            x: 0,
            y: 0,
            z: Math.round(Math.atan2(matrix[1], matrix[0]) * (180 / Math.PI))
        };
    }
    // 3d matrix
    else {
        // incorrect calculations
        // only work for a single rotation
        // return {
        //      x: Math.round(Math.atan2(matrix[6], matrix[5]) * (180/Math.PI)),
        //      y: Math.round(Math.atan2(-matrix[2], matrix[0]) * (180/Math.PI)),
        //      z: Math.round(Math.atan2(matrix[1], matrix[0]) * (180/Math.PI))
        // };

        // convert from string to number
        // for (var i = 0, len = matrix.length; i < len; i++) {
        //      matrix[i] = Number(matrix[i]);
        // }

        // gimball lock for positive 90 degrees
        if (matrix[2] === 1) {
            return {
                x: Esprit.toDegrees(Math.atan2(matrix[0], matrix[1])),
                y: Esprit.toDegrees(Math.PI / 2),
                z: 0
            }
        }
        // gimball lock for negative 90 degrees
        else if (matrix[2] === -1) {
            return {
                x: Esprit.toDegrees(-Math.atan2(matrix[0], matrix[1])),
                y: Esprit.toDegrees(-Math.PI / 2),
                z: 0
            }
        }
        // no gimball lock
        else {
            return {
                x: Esprit.toDegrees(Math.atan2(matrix[6], matrix[10])),
                y: Esprit.toDegrees(Math.asin(matrix[2])),
                z: Esprit.toDegrees(Math.atan2(-matrix[1], matrix[0]))
            }
        }

    }
},

getTransform: function (el) {
    var transform = getComputedStyle(el).webkitTransform;
    return transform !== 'none' ? transform.split('(')[1].split(')')[0].split(',') : Esprit.create3dMatrix();
},

toDegrees: function (radians) {
    return Math.round(radians * 180 / Math.PI);
}

Any help or ideas would be greatly appreciated. Thanks!

A: John Schulz (@jfsiii) posted this response:
https://gist.github.com/4119165


text:
Q: Declaring singletons in kotlin I have this code for getting a singleton intance of my Room database but all over my code i get lint warnings when using the Dao that it could cause a null pointer exception because getInstance can return a nullable value
abstract class DatabaseInstance : RoomDatabase() {

    // ... Dao's

    companion object {
        private var INSTANCE: DatabaseInstance? = null

        fun getInstance(context: Context): DatabaseInstance? {
            if (INSTANCE == null) {
                synchronized(DatabaseInstance::class) {
                    INSTANCE = Room.databaseBuilder(context.applicationContext,
                        DatabaseInstance::class.java, "my_database.db")
                        .allowMainThreadQueries().fallbackToDestructiveMigration().build()
                }
            }
            return INSTANCE
        }

        fun destroyInstance() {
            INSTANCE = null
        }
    }
}

I tried seeing if I could use a private and public instance variable where the public would have a custom getter and do what getInstance does but I cant pass context into it.
Since getInstance is really never going to return null how can I adjust things so that the lint error's are gone?
And no I don't want to just suppress the lint error

A: Your getInstance(Context) returns an optional type. Instead make it return DatabaseInstance using the !! operator on INSTANCE.
fun getInstance(context: Context): DatabaseInstance {
    if (INSTANCE == null) {
        synchronized(DatabaseInstance::class) {
            INSTANCE = Room.databaseBuilder(context.applicationContext,
                DatabaseInstance::class.java, "my_database.db")
                .allowMainThreadQueries().fallbackToDestructiveMigration().build()
        }
    }
    return INSTANCE!!
}

But keep in mind that your overall implementation is not thread-safe.

A: I think you can do it like this:
companion object {
    private val instance: DatabaseInstance = DatabaseInstance()
    fun getInstance(): DatabaseInstance {
        return instance
    }
}

Correct me if I'm worng, but I think your instance only will be initialized once.

A: You can take advantage of the Elvis operator to return a non-null DatabaseInstance and avoid using the !! operator:
private var INSTANCE: DatabaseInstance? = null

fun getInstance(context: Context): DatabaseInstance {
    return INSTANCE ?: synchronized(DatabaseInstance::class) {
        INSTANCE ?: Room.databaseBuilder(context.applicationContext, DatabaseInstance::class.java, "my_database.db")
                .allowMainThreadQueries()
                .fallbackToDestructiveMigration()
                .build()
                .also { INSTANCE = it }
    }
}

Source: Pro-tips for Room


text:
Q: undefined method / for 15 ruby I get an error NoMeathodError undefined method / for 15 with this code:
tts = gets.chomp
2 * (tts / Math.sqrt(2)) + tts

where I set the tts value to 15. If I change the first line to
tts = 15

The program successfully executes the equation. Where am I going wrong?

A: So when you get a value from gets.chomp, it defaults it to a string. What you are getting back when you enter 15 into the terminal is the string "15" instead of the integer 15. In order to fix this, you can do the following:
tts = gets.chomp.to_i