text:
Q: UIScrollView doesn't show scrollers (scroll indicators) I have UIScrollView which i populate with UIImageViews programmatically. After that I change contentSize of scrollview so I can scroll it. It works fine, but I don't see scrollers and it bothers me. I've set to show them in .xib, and I've even set "showHorizontalScrollIndicator" property programmatically, but I still can't see scrollers.
Does anyone have any idea why I can't see scrollbars and how I can make them appear?
BTW I don't mean I wan't to see them at all times, I just want standard behavior, but they aren't shown even when I'm scrolling.

A: I was removing subviews and scroll indicators were of them.
I fixed it at first by checking type of subviews I was removing,
then I changed the logic and didn't remove subviews at all.


text:
Q: Template to add in most Classes to create Migration Models with EF Core Template to add in most Classes to create Migration Models with EF Core
With DataAnnotations there is one point at Base Class to declare using Attributes for example ...TypeName...
Every Model which inherits from that BaseClass is scaffolded correct and all Attributes are taken

With FluentAPI you have to declare Property attributes  for example ...HasColumnTypes... on each Model you want to create.
Or loop through after ModelBuilder is finished or create a Convention for ModelFinalizer
Every Model inherited from BaseClass has to be modified manually/looped for each property, regardless of defining a Grouped SetupClass for that BaseClass

How to use FluentAPI to get same results as DataAnnotation with a single Point of Definition ?
expected result
CREATE DATABASE [BlogsMS];

CREATE TABLE [LogEntries] (
    [Id] int NOT NULL IDENTITY,
    [CreatedAt]  smalldatetime NOT NULL,    -- from DataAnnotations
    [UpdatedAt]  smalldatetime NOT NULL,    -- from FluentAPI with SingleConfigPoint ?
);

Source
template class
public abstract class DefaultAuditColumns
{
    [Column(TypeName = ("smalldatetime"))]
    public DateTime CreatedAt { get; set; }  // DB Type defined with DataAnnotations

    public DateTime UpdatedAt { get; set; }  // DB Type defined FluentAPI Grouped OnModelCreating
}

first example class/entity
public class TableLogged : DefaultAuditColumns
{
    public int Id { get; set; }
    public string? Description { get; set; }
}

second example class/entity
public class AnotherTableLogged : DefaultAuditColumns
{
    public int Id { get; set; }
    public string? Description { get; set; }
}

Sql table results
  CREATE DATABASE [BlogsMS];

      CREATE TABLE [AnotherLogEntries] (
          [Id] int NOT NULL IDENTITY,
          [Description] nvarchar(200) NULL,
          [CreatedAt] smalldatetime NOT NULL,
          [UpdatedAt] datetime2 NOT NULL,
          CONSTRAINT [PK_AnotherLogEntries] PRIMARY KEY ([Id])
      );

      CREATE TABLE [LogEntries] (
          [Id] int NOT NULL IDENTITY,
          [Description] nvarchar(200) NULL,
          [CreatedAt] smalldatetime NOT NULL,
          [UpdatedAt] datetime2 NOT NULL,
          CONSTRAINT [PK_LogEntries] PRIMARY KEY ([Id])
      );

How to use FluentAPI to get same results as DataAnnotation with a single Point of Definition ?
The Suggestion Entity Framework Core 2.0: How to configure abstract base class once Ivan Stoev – grek40 does the job but
Some of the Property Attributes then still are missing in scaffolded Model/Classes.
The Modified Class look now like, all works as expected :-)
public  class TableLoggedConfiguration :  DefaultAuditColumnsConfiguration<TableLogged>, IEntityTypeConfiguration<TableLogged>
 {
     public void Configure(EntityTypeBuilder<TableLogged> entity)
     {
         base.Configure(entity); // <--
         // entity.Property(e => e.ReviewedAt).HasColumnType("smalldatetime");
         // entity.Property(e => e.CreatedBy).HasMaxLength(30);
         // entity.Property(e => e.UpdatedBy).HasMaxLength(30);
         entity.Property(e => e.DecimalType).HasColumnType("decimal(18,5)").HasPrecision(18, 5);
     }
 }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Discord.py music bot's play command throws a TypeError import discord
from discord import Intents
from discord import guild
from discord import permissions
from discord import member
from discord.ext import commands
from discord.ext.commands.core import has_permissions
import DiscordUtils
from discord.user import User

intents = discord.Intents().all()
client=commands.Bot(command_prefix='-', intents = intents)

 #['dislike_count']
 @client.command()
 async def join(ctx):
          voiceTrue = ctx.author.voice
if voiceTrue is None:
    return await ctx.send("You are not in a voice channel")
await ctx.author.voice.channel.connect()
await ctx.send('Joined your voice channel')

@client.command()
async def leave(ctx):
         voiceTrue = ctx.author.voice
mevoiceTrue = ctx.guild.me.voice

if voiceTrue is None:
    return await ctx.send('You are not in a voice channel')

if mevoiceTrue is None:
    return await ctx.send('I already left')
await ctx.voice_client.disconnect()
await ctx.send('Left your voice channel')

@client.command()
async def play(ctx, *, url):
         player = music.get_player(guild_id = ctx.guild.id)
if not player:
    player = music.create_player(ctx, ffmpeg_error_betterfix=True)
if not ctx.voice_client.is_playing():
    await player.queue(url, search=True)
    song = await player.play()
    await ctx.send(f'Started playing{song.name}')

else:
    song = await player.queue(url, search=True)
    await ctx.send(f'Added {song.name} to the queue')

I have tried the above code, and this TypeError keeps popping up whenever I use the play() command:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'NoneType' object is not subscriptable

I was following this YouTube tutorial by
Glowstik, and it worked perfectly for him in the video. Any solutions?


text:
Q: flash as3 Fadein fadeout xml slideshow I am new to as3.0 and want to complete my project.
I am using the below code for my xml slideshow but I want the pictures to fade into each other it should never fade to complete white. Hope any expert can help me.
import gs.*;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import fl.transitions.easing.*;

stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
//hides the description box until the image is loaded
//hides the image until it is loaded

theImage.alpha=0;
loadingBar.visible = false;

//variables to hold the final coordinates of the image tween
var finalX:Number;
var finalY:Number;

//variable to hold the number of images in the XML
var listLength:Number;

//keeps track of what image should be displayed
var currPainting:Number=0;

//arrays to hold the contents of the XML, using this to allow
//for the random order of the images
var imageArray:Array = new Array();

//Loader event for the XML
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onLoaded);

var xml:XML;

loader.load(new URLRequest("galleries/xml/maingallery.xml"));

function onLoaded(e:Event):void {
//load XML
xml=new XML(e.target.data);
var il:XMLList=xml.images;
listLength=il.length();

populateArray();
}

function populateArray():void {
//takes the properties defined in the XML and stores them
//into arrays
var i:Number;
for (i = 0; i < listLength; i++) {
    imageArray[i]=xml.images[i].pic;

}

beginImage();
}

function beginImage():void {
//grabs a random number between 0 and the number
//of images in the array

//load description

var imageLoader = new Loader();

//catches errors if the loader cannot find the URL path
imageLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, catchFunction);
//actually loads the URL defined in the image array
imageLoader.load(new URLRequest(imageArray[currPainting]));
//adds a listener for while the image is loading
imageLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, imgLoading);
//adds a listener for what to do when the image is done loading
imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imgLoaded);

function catchFunction(e:IOErrorEvent) {
    trace("Bad URL: " + imageArray[currPainting] + " does not exist");
    //take out the bad URL from the array
    imageArray.splice(currPainting,1);
    //check to see if there are images left,
    //else restart the slideshow
    if (imageArray.length==0) {
        populateArray();
    } else {
        beginImage();
    }
}

function imgLoading(event:ProgressEvent):void{
    //show the loading bar, and update the width
    //based on how much is loaded
    loadingBar.visible = true;
    loadingBar.bar.scale = (event.bytesLoaded/event.bytesTotal)*100;
    loadingBar.x = stage.stageWidth/2;
    loadingBar.y = stage.stageHeight - 400;

}

var widthRatio:Number;
var heightRatio:Number;
function imgLoaded(event:Event):void {
    loadingBar.visible = false;

    //add the image and get the dimensions to center the image
    theImage.addChild(imageLoader);
    if (imageLoader.width > stage.stageWidth){
     widthRatio=imageLoader.width/stage.stageWidth;
     trace(widthRatio)
     trace(imageLoader.width);
        }
    if (imageLoader.height > stage.stageHeight - 207){
     heightRatio=imageLoader.height/(stage.stageHeight - 207) ;
     trace(heightRatio)
    trace(imageLoader.height)
    }

    if (widthRatio > heightRatio){
        imageLoader.width = stage.stageWidth;
        imageLoader.height = imageLoader.height/widthRatio;
    } else {
      imageLoader.height = stage.stageHeight - 207;
      imageLoader.width = imageLoader.width/heightRatio;
 }

    imageLoader.x = (imageLoader.stage.stageWidth / 2) - (imageLoader.width / 2);
    imageLoader.y = 0

    //take the contents of the loaded image and cast it as bitmap data
    //to allow for bitmap smoothing

    var image:Bitmap = imageLoader.content as Bitmap;
    image.smoothing=true;
    //start tween function
    easeIn();
}
}

function easeIn():void {

TweenLite.to(theImage, 5, {onComplete:hideStuff});
TweenLite.to(theImage, 1, {alpha:1, overwrite:0});
}

function hideStuff():void {
TweenLite.to(theImage, 1, {alpha:0, onComplete:nextImage});

}

function nextImage():void {
//take out the image that was just displayed
imageArray.splice(currPainting,1);

//remove the picture
theImage.removeChildAt(0);

//start over
if (imageArray.length==0) {
    populateArray();
} else {
    beginImage();
}
}

A: Ok, first you need to create a variable for the image you wish to fade in. Let's organise it so it is clear which is which.
var theCurrentImage:DisplayObject;
var theNextImage:DisplayObject;

Load in the first image (now theCurrentImage) in the same way as before.
Now here's how you could load in the next image in the array:
function loadNextImage():void {
    currPainting++;
    // you should also make sure currPainting is not out of bounds here
    loadImage();
}

function loadImage():void {
    imageLoader = new Loader();
    imageLoader.addEventListener(Event.COMPLETE, onImageLoaded);
    // other listeners go here too
    imageLoader.load(new URLRequest(imageArray[currPainting]));
}

function onImageLoaded(e:Event):void {
    theNextImage = imageLoader; // stores the next image ready to be faded in
    theNextImage.alpha = 0;
    addChild(theNextImage); // now ready to be cross-faded in
    crossFade();
}

function crossFade():void {
    TweenLite.to(theCurrentImage, 1, {alpha:0});
    TweenLite.to(theNextImage, 1, {alpha:1});
    // remove theCurrentImage (now invisible) from the stage
    removeChild(theCurrentImage);
    // theNextImage is now the displayed image so...
    theCurrentImage = theNextImage;
    theNextImage = null;
    // ready to load the next image by calling loadNextImage()
}


text:
Q: Strategy to update previous screens in react native when new form entries added I have a use case where I am using stack navigator. I have a homepage where I have some aggregated data and a list which are retrieved from an API.
On clicking on a list item I move to a screen which has more details of that item. There I can add entries for that item. When entries are added using a form, both the homepage as well as the item specific screen need to be updated, which means I need to call the API's again to fetch data. In case no transactions are added I was to avoid this.
What should be the best practice here? should I pass a state variable from homepage and whenever it is updated refresh the screens?
Currently, I am using a willFocus listener, and it makes an API call each time I am on one of these screens. I believe that there can be a better approach than this.


text:
Q: Hibernate - map weird multidirectional relationship (without foreign keys) Suppose I have three tables set up like so (not my design):
Tables 'Foo' & 'Bar':
----------   ----------
| FOO_ID |   | BAR_ID |
----------   ----------
|      1 |   |      1 |
|      2 |   |      3 |
----------   ----------

*Nothing special here, they are just two tables with ids
Table 'Annotation':
------------------------------------------------------------
| ANNOTATION_ID | ANNOTATION_TEXT | OTHER_TABLE | OTHER_ID |
------------------------------------------------------------
|             1 |  'annotation a' |       'foo' |        1 |
|             2 |  'annotation b' |       'foo' |        2 |
|             3 |  'annotation c' |       'baz' |        1 |
|             4 |  'annotation d' |       'baz' |        3 |
------------------------------------------------------------

Ok, so this 'annotaion' table is literally referencing the foo and baz tables by name and primary key. There's absolutely no referential integrity here. It's not my design.
Disclaimers aside, in SQL the join would be like:
select *
from foo
left join annotation
on (other_table = 'foo' and other_id = foo_id)

I want to map this relationship using Hibernate with annotations. I'm afraid it's not possible but wanted to ask, you never know. My Annotation class would look like so:
@Entity
@Table(name = "ANNOTATION")
public class Annotation {

    @Id
    @Column(name = "ANNOTATION_ID")
    private Integer id;
    @Column(name = "ANNOTATION_text")
    private String text;
    @Column(name = "OTHER_TABLE")
    private Integer other_table;
    @Column(name = "OTHER_ID")
    private Integer other_id;

    // getters & setters

}

Any ideas how do I set up this one-to-many (one Foo to many Annotations) mapping in Hibernate?
@Entity
@Table(name = "FOO")
public class Foo {

    @Id
    @Column(name = "FOO_ID")
    private Integer id;
    @OneToMany
    @Column // how would I configure this?
    private Collection<Annotation> annotations;

    // getters & setters

}


text:
Q: PyQt5: Get GL parameters from QtOpenGLWidget without showing first Is it possible to use GL functions like glGetString without showing the widget first?
The basic use case would be taking this helloworld and instead of showing the widget, maybe I want to print a command line usage message with the GPU information and GL version. The script currently does this already after showing the widget.
In my own application I have a subclass of a QOpenGLWidget and I've tried manually creating a QOpenGLContext, setting the format, and making it current (with and without .create()), but that didn't seem to work. The subclass seems to work fine when shown.
Any help is much appreciated.
Further details: I'm one of the maintainers of the python library vispy and I'm trying to update our PyQt5 backend to use QOpenGLWidget instead of QGLWidget. The pull request is here if anyone wants to tell us what we're doing wrong: https://github.com/vispy/vispy/pull/1394

A: A OpenGL context needs a "window" (exactly needs a "Device Contex" or a "Display", depending on the OS) to render to. That window doesn't need to be visible, just that the gl context is current to it.
The easiest way is to hide() (or don't call show()) the window at its creation. You can make it visible later.


text:
Q: I got an error in "local variable 'current_name' referenced before assignment" "Main CLI"
    import argparse

    from cloud_pricing.data.core import CloudProcessor

    def main():
        parser = argparse.ArgumentParser(description="Compare cloud pricing on the command line. Set the required compute and receive a table of compatible prices. For some services (like AWS) the instance type reflects the best fit given the input constraints.")
        parser.add_argument("--cpus", "-c", default=4, type=int,
            help="Number of CPUs to request.")
        parser.add_argument("--gpus", "-g", default=0, type=int,
            help="Number of GPUs to request.")
        parser.add_argument("--ram", "-r", default=8, type=int,
            help="Amount of RAM in Gb.")
        parser.add_argument("--gpuram", "--gr", default=10, type=int,
            help="Amount of total GPU RAM in Gb.")
        parser.add_argument("--verbose", "-v", default=False, action='store_true',
            help="Increase verbosity, showing all info columns.")
        parser.add_argument("-n", default=10, type=int,
            help="The number of results to show.")
        parser.add_argument("--unk_price", "-P", default=False, action='store_true',
            help="Exclude products that don't have a known price.")
        parser.add_argument("--out", "-o", default=None, type=str,
            help="Save the outputs to a file. {csv | json}")
        parser.add_argument("--spot", "-s", default=False, action='store_true',
            help="Use spot (preemptible) prices.")
        parser.add_argument("--update", "-U", default=False, action='store_true',
            help="Force an update to the database of prices.")
        parser.add_argument("--providers", default='ALL',
            help=("List of providers to search over. Comma separated string "
                  "of 'AWS', 'Azure', 'GCP', or 'All'. Example: 'aws,gcp' "))
    args = parser.parse_args()
    print(args)
    proc = CloudProcessor(args.providers.upper())

    if args.update:
        proc.update()

    data = proc.filter(args.cpus, args.ram, args.gpus, args.gpuram, args.n, args.verbose, args.unk_price, args.spot)

    if args.out is not None:
        if args.out.endswith('csv'):
            data.to_csv(args.out)
        elif args.out.endswith('json'):
            data.to_json(args.out)
    else:
        print(data)

    if __name__ == "__main__":
      main()

I got this error. I was trying to solve this problem, but I could not.

When I run "cloud-pricing --cpus 8 --ram 32 --gpus 1 --gpuram 16", I get this massege.
Namespace(cpus=8, gpus=1, ram=32, gpuram=16, verbose=False, n=10, unk_price=False, out=None, spot=False, update=False, providers='ALL')
Downloading latest GCP data...

Traceback (most recent call last):

  File "C:\Program Files\Python39\Scripts\cloud-pricing-script.py", line 33, in <module>
    sys.exit(load_entry_point('cloud-pricing==0.0.1', 'console_scripts', 'cloud-pricing')())
  File "c:\program files\python39\lib\site-packages\cloud_pricing\main.py", line 35, in main
    proc = CloudProcessor(args.providers.upper())
  File "c:\program files\python39\lib\site-packages\cloud_pricing\data\core.py", line 22, in __init__
    self._tables.append(t())
  File "c:\program files\python39\lib\site-packages\cloud_pricing\data\gcp.py", line 33, in __init__
    super().__init__(table_name)
  File "c:\program files\python39\lib\site-packages\cloud_pricing\data\interface.py", line 20, in __init__
    self.setup()
  File "c:\program files\python39\lib\site-packages\cloud_pricing\data\gcp.py", line 156, in setup
    print(current_name)
UnboundLocalError: local variable 'current_name' referenced before assignment

A: In your git code https://github.com/Hmh4575/cloud-pricing-2/blob/master/cloud_pricing/data/gcp.py , You have a line 152-153 like this.
if i.name.lower() in {'h2', 'h3', 'h4'}:
   current_name = i.get('data-text')

This is the only place variable current_name is getting assigned. So if the i.name is not matching h1/h3/h4 , there is no variable current_name. So the error.
You can initialize like current_name='' before the loop starts, and it should avoid this. Or, ensure the data matches h1/h3/h4


text:
Q: How to validate an XML document against a schema in a Windows Store App? I am trying to figure out how I could validate an XML document when reading it against a XML Schema in a Windows Store app.
With the full .NET API I can use ValidationType = ValidationType.Schema on a XmlReaderSettings instance that is passed to an XmlReader and add Schemas using Schemas.Add. Unfortunately in the .NET API for Windows Store Apps XmlReaderSettings does neither have a ValidationType property nor a Schemas property.
Using XElement I could use the extension method Validate and an XmlSchemaSet in full .NET but both are also not available in the .NET API for Windows Store Apps.
Did not find anything related to Schemas in the XmlDocument class either (found
XmlLoadSettings.ValidateOnParse but according to the documentation this is for DTDs).
So: How could I validate an XML document against a Schema in WinRT or with the .NET API for Windows Store Apps? Or was this feature simply forgotten by the WinRT team?
Update:
XML Schema seems not to be supported, according to an answer to a similar quetion on answers.flyppdevportal.com. See http://answers.flyppdevportal.com/categories/metro/csharpvb.aspx?ID=b0df7a08-23c7-4adf-96c9-608d237cb024. It's hard to believe though. Did the WinRT team think XML validation is not important for Windows Store Apps?


text:
Q: Owl Carousel not working in Wordpress I'm using Owl Carousel 1 and this problem shows up:
In the HTML page, there is no problem, see here:
(clients section)
Link: http://exibirhost.com.br/supplypaper/front/sobre-nos.html
But, when I've started the WordPress, this problem happened:
(clients section)
http://exibirhost.com.br/supplypaper/sobre-nos/
As you can see, the carousel broke. I have already tried to use jQuery No Conflict, and some other things, but the I can't figure out why is this bug is showing up..

A: it seems that you are missing owl.*.css files on the second server
I've added these lines and it works
<link rel="stylesheet" href="http://exibirhost.com.br/supplypaper/front/css/owl.theme.css">
<link rel="stylesheet" href="http://exibirhost.com.br/supplypaper/front/css/owl.transitions.css">
<link rel="stylesheet" href="http://exibirhost.com.br/supplypaper/front/css/owl.carousel.css">


text:
Q: How to write Webpack plugin which adds modules to the bundle on the fly based on other modules? I have a problem with writing a Webpack plugin for a translation service.
The goal is to:

*

*Get names (and source code) of all required modules during compilation. I need to be able to scan the included source code for special t() function usage but I want to scan only those modules which will be included in the bundle (which, depending on build configuration, can be a subset of all project modules).

*Based on the gathered modules, I want to create additional modules (with translations) on the fly and add them to the bundle. Those modules need to be able to import their own dependencies.

An additional requirement is that the Webpack's code splitting feature should work with the modules created on the fly (I want to extract them to separate files – e.g. bundle.[lang].js). Also, which may be out of the scope of this question, I must make those chunks with translations optional (so you don't have to load all languages, but just one).
More details can be found in https://github.com/ckeditor/ckeditor5/issues/387.
I've been trying multiple solutions, but Webpack 2's documentation is not very helpful. I can get all the modules by listening to module resolution hooks (before-resolve), but I don't know when all the dependencies are resolved and I don't know if I can add more modules after that (and how to do that – is addEntry ok and when I can use it?).
I was also thinking on connecting Webpack plugin and Webpack loader (because the feature I need is pretty similar to Webpack's style-loader), but from the plugin level I can only add path to the loader, not the loader itself, so I can't pass the config object as a parameter – am I wrong?
PS. I use Webpack 2. If the requirements seem strange to you, please see https://github.com/ckeditor/ckeditor5/issues/387 :).

A: This is a really complex question, but I can show how you can add additional dependencies to specific modules as if those were required from that module. This ensures that your added modules will be in the correct chunks and will also be removed if the parent module is removed from the bundle.
const CommonJsRequireDependency = require("webpack/lib/dependencies/CommonJsRequireDependency")

class MyPlugin {
  apply(compiler) {
    compiler.plugin("compilation", compilation => {
      compilation.plugin("succeed-module", module => {
        // this will be called for every successfully built module, but before it's parsed and
        // its dependencies are built. The built source is available as module._source.source()
        // and you can add additional dependencies like so:
        module.dependencies.push(new CommonJsRequireDependency("my-dependency", null))
      }
    }
  }
}

This is just one part of it. You'll also likely need to write your own loader to actually generate the translations (you can replace my-dependency above with my-loader!path/to/module to invoke it immediately) and some step after the chunks are created to perhaps extract them into a new asset and load them since they aren't actually required anywhere.


text:
Q: how to send mail using handler? i want to send mail so i wrote one method in handler.ashx but i got error as
The "SendUsing" configuration value is invalid. what does it mean pls help me
public bool Sendmail()
    {
        bool strResult = false;
        try
        {
        email.Subject = " Registration";

        email.To = "ravivarma_07d@yahoo.com";
        email.From = "giribhushan.svg@gmail.com";
        email.Cc = "ravivarma_07d@yahoo.com";
        email.Bcc = "ravivarma_07d@yahoo.com";
        email.BodyFormat = MailFormat.Html;

        email.Body = "" +
                       "" +
                      "Hi ravi"+
                       "" +
                       "";
        email.Priority = MailPriority.Normal;

       SmtpMail.Send(email);
        strResult = true;
    }
    catch (Exception ex)
    {
        //FTEHelper.SendEmail("ticketupload@whohastwo.com", "Ticket Upload Batch Error",
        //   ex.ToString());

        strResult = false;

    }

    return strResult;

}

A: You should specify an SMTP server.
SmtpMail.SmtpServer = "yourservername";

Also you should consider using System.Net.Mail namespace instead of System.Web.Mail. (If you aren't forced to use .NET 1, of course.)


text:
Q: compute standard deviation in R by sector i'm new to R and I'm sorry if this question is already answered.
This is an example of my dataset:
idnumber SIC(1-digit) Year   Ebit
198       A           2019   2344
196       A           2019   6383
374       A           2019   5628
281       A           2019   2672
274       A           2018   2792
196       A           2018   3802
374       A           2018   3892
468       B           2019   6372
389       B           2019   3829
493       C           2019   2718
928       C           2019   2628
278       C           2019   3672

I want to compute the standard deviation for "Ebit" by the industrial sector "SIC(1-digit)".
In this way I would like to find a volatility measure of operating revenue "Ebit" by industry.
Thanks in advance, for your kind answer..

A: Let's load your data to reproduce your example:
dat <- data.frame(
  idnumber = c(198, 196, 374, 281, 274, 196, 374, 468, 389, 493, 928, 278),
  `SIC(1-digit)` =  c('A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'C', 'C', 'C'),
  Year = c(2019, 2019, 2019, 2019, 2018, 2018, 2018, 2019, 2019, 2019, 2019, 2019),
  Ebit = c(2344, 6383, 5628, 2672, 2792, 3802, 3892, 6372, 3829, 2718, 2628, 3672),
  check.names = FALSE
)

You see SIC(1-digit) is surrounded by back-ticks and the argument check.names = FALSE. This is because your column name has the special characters ( and ); you can read more about this here and here

Once your data is loaded, you can use dplyr:
library(dplyr)

dat %>%
  group_by(`SIC(1-digit)`) %>%
  summarise(standard_deviation = sd(Ebit))

# A tibble: 3 x 2
  `SIC(1-digit)` standard_deviation
* <chr>                       <dbl>
1 A                           1544.
2 B                           1798.
3 C                            579.

Or data.table:
library(data.table)

setDT(dat)
dat[, .(standard_deviation = sd(Ebit)), by = `SIC(1-digit)`]

   SIC(1-digit) standard_deviation
1:            A          1544.4116
2:            B          1798.1725
3:            C           578.5257


text:
Q: How can I draw a half arrow with asterisks in java? I am in my first java class, and I am trying to draw a half arrow using asterisks. I am supposed to use a nested loop where the inner loop draws the *s and the outer loop iterates the number of times equal to the height of the arrow base. I have learned if-else, while loops, and for loops.
So far, I have been able to correctly draw the arrow for input values of
arrow base height: 5
arrow base width: 2
arrow head width: 4
When I try to add a while loop as the outer loop, the program times out. I am at a loss.
The next input I need to use is 2, 3, 4. My code gets the height of the base right (2), but not the width.
The last input I need is 3, 3, 7. My code gets none of that right at all. This is what I have so far.
What kind of loops should I be using to get the widths correct?
  Scanner scnr = new Scanner(System.in);
  int arrowBaseHeight = 0;
  int arrowBaseWidth  = 0;
  int arrowHeadWidth = 0;
  int i = 0;

  System.out.println("Enter arrow base height: ");
  arrowBaseHeight = scnr.nextInt();

  System.out.println("Enter arrow base width: ");
  arrowBaseWidth = scnr.nextInt();

  System.out.println("Enter arrow head width: ");
  arrowHeadWidth = scnr.nextInt();

  for (i = 1; i <= arrowBaseHeight; ++i) {
      // Draw arrow base (height = 3, width = 2)
      System.out.println("**");
  }

  // Draw arrow head (width = 4)
  System.out.println("****");
  System.out.println("***");
  System.out.println("**");
  System.out.println("*");

Example of how the output arrow may look:
**
**
**
**
****
***
**
*

A: You have to make two nested loops. Inner loops will be printing characters in single line and outer loops will be printing multiple lines.
This is solution for your question with 'for' loops.
//printing arrow base
for (int h = 0; h < arrowBaseHeight; ++h)
{
  //printing single line - every line is the same
  for(int w = 0; w < arrowBaseWidth; w++)
    System.out.print("*");
  //finishing line
  System.out.println();
}

//printing arrow head
//starting with provided width and decreasing it with every iteration
for (int a = arrowHeadWidth; a > 0 ; a--)
{
  //printing single line - now every line is different
  //you have to count how many asterisks you are printing
  for(int i = 0; i < a; i++)
    System.out.print("*");
  //finishing line
  System.out.println();
}

You don't need to use brackets in loops if they contain only one line. For example:
for(int i = 0; i < a; i++)
    System.out.print("*");

is equivalent to:
for(int i = 0; i < a; i++)
{
    System.out.print("*");
}

A: Could use two for the first to print the number of rows with the entered width entered using the substring method to capture the amount of printing *
then the second printing for the head of the arrow and go decreasing the width of the arrow
for (int i = 0;i < arrowBaseHeight; i++)
 //when there is more than one instruction within a structure can be written without {}
    System.out.println("*************************".substring(0, arrowBaseWidth));

System.out.println("");
for (int i = arrowHeadWidth; i>=0; i-=1)  // head
    System.out.println("*************************".substring(0, i));

A: For this problem, you would want to use for-loops since you know the exact number of times it should repeat. You know this because the user inputs the size of each part of the arrow.
Scanner scnr = new Scanner(System.in);

int arrowBaseHeight = 0;
int arrowBaseWidth  = 0;
int arrowHeadWidth = 0;
int i = 0;

System.out.println("Enter arrow base height: ");
arrowBaseHeight = scnr.nextInt();

System.out.println("Enter arrow base width: ");
arrowBaseWidth = scnr.nextInt();

System.out.println("Enter arrow head width: ");
arrowHeadWidth = scnr.nextInt();

//Your code above | Below is the modified code

String ast = ""; //String ast will contain how many asterisk we want for the base width;

for (int x = 1; x <= arrowBaseWidth; x++) //Loop forms the base width of the arrow
{
    ast += "*"; //This adds as many asterisks as we need to make the base width. SO if they enter 4, we get 4 *;
}

for (i = 1; i < arrowBaseHeight; ++i)
{
    System.out.println(ast); //Prints out the base width, which is now a String object
}

int tempHeadWidth = arrowHeadWidth; //Added this tempHeadWidth variable since we will be modifying it directly and
                                    //we don't want to modify the original data and variable (it will cause problems if we do.

for (int y = 1; y <= arrowHeadWidth; y++)
{
    for(int z = tempHeadWidth; z > 0; z--) //This loop prints the amount of asterisks we need per line in the arrowHead
    {
        System.out.print("*");
    }
    // Once the loop above is finished, the rest of the code will execute in the main for-loop and then scheck if it will run again.
    tempHeadWidth -= 1; //So we are lowering the tempHeadWidth by one so the next time it enters
                        //the nested (2nd) for loop it will be one asterisk smaller

    System.out.println(); //This makes a new line to keep adding more stars for the next row
}

This method allows the user to input any size for the arrow (while staying in the value boundaries of an int of course)

A: I know this is a bit late but I am going through this same challenge on zybooks (which happens to be a lab activity). The above code marked solved is right but there are a few things that are off in the code that I thought I would clarify for everyone. Below is the code I used to pass 100%, and I will comment on the areas that needed to be modified. I also made the indentation a little easier to read. I hope this helps anyone needing a little push in the right direction.
import java.util.Scanner;

public class DrawHalfArrow {
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);
      int arrowBaseHeight = 0;
      int arrowBaseWidth  = 0;
      int arrowHeadWidth = 0;

  System.out.println("Enter arrow base height: ");
  arrowBaseHeight = scnr.nextInt();

  System.out.println("Enter arrow base width: ");
  arrowBaseWidth = scnr.nextInt();

/* The while loop below needed to be added for the user input to make sure
** that their input never exceeded that of the arrowHeadWidth */

  while (arrowHeadWidth <= arrowBaseWidth) {
     System.out.println("Enter arrow head width: ");
     arrowHeadWidth = scnr.nextInt();
  }

  String ast = "";
  for (int x = 1; x <= arrowBaseWidth; x++) {
     ast+= "*";
  }

/* Here 'i' needed to be intialized as an integer ('int'). Also the '=' needed
** to be added to i<= arrowBaseHeight */

  for (int i = 1; i <= arrowBaseHeight; ++i) {
        System.out.println(ast);
  }
  int tempHeadWidth = arrowHeadWidth;
  for (int y =1; y <= arrowHeadWidth; y++) {
     for (int z = tempHeadWidth; z > 0; z--) {
        System.out.print("*");
     }
     tempHeadWidth -= 1;
     System.out.println();
  }

  return;
   }
}

A: My Full Solution based off @dev joels answer
import java.util.Scanner;

public class DrawHalfArrow {
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);
      int arrowBaseHeight = 0;
      int arrowBaseWidth  = 0;
      int arrowHeadWidth = 0;

      System.out.println("Enter arrow base height: ");
      arrowBaseHeight = scnr.nextInt();

      System.out.println("Enter arrow base width: ");
      arrowBaseWidth = scnr.nextInt();

      //System.out.println("Enter arrow head width: ");

      while (arrowHeadWidth <= arrowBaseWidth) {
        System.out.println("Enter arrow head width: ");
        arrowHeadWidth = scnr.nextInt();
      }

      for (int h = 0; h < arrowBaseHeight; ++h) {
         for(int w = 0; w < arrowBaseWidth; w++)
            System.out.print("*");
        System.out.println();
      }

       for (int a = arrowHeadWidth; a > 0 ; a--) {
          for(int i = 0; i < a; i++)
             System.out.print("*");
         System.out.println();
       }
      return;
   }
}

A: import java.util.Scanner;

public class DrawHalfArrow {
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);
      int arrowBaseHeight;
      int arrowBaseWidth;
      int arrowHeadWidth;

      System.out.println("Enter arrow base height:");
      arrowBaseHeight = scnr.nextInt();

      System.out.println("Enter arrow base width:");
      arrowBaseWidth = scnr.nextInt();

      do {
         System.out.println("Enter arrow head width:");
         arrowHeadWidth = scnr.nextInt();
      } while (arrowHeadWidth <= arrowBaseWidth);

      System.out.println("");

      // Draw arrow base
      int row;
      int column;
      for (row = 0; row < arrowBaseHeight; ++row) {
         for (column = 0; column < arrowBaseWidth; ++column) {
            System.out.print("*");
         }
         System.out.println("");
      }

      // Draw arrow head
      for (row = 0; row < arrowHeadWidth; ++row) {
         int thisRowWidth = arrowHeadWidth - row;
         for (column = 0; column < thisRowWidth; ++column) {
            System.out.print("*");
         }
         System.out.println("");
      }

   }
}


text:
Q: В чем причина ошибки std@bad_function_call при создании потока Есть следующий код:
std::function<void()> f=[](){std::cout<<"Yaha";};

std::thread thr1(f);
std::thread thr2(f); //Здесь возникает ошибка std@bad_function_call

Прошу подсказать причину возникновения данной ошибки. Как я понимаю объект f становится пустым (не пойму почему).
И второй вопрос:
void thr1_f()
 {
  std::cout<<"Yaha";
 }

в чем разница в std::thread(thr1_f) и std::thread(&thr1_f) и когда какой вариант следует использовать? Почему нельзя вызвать std::thread(&f) (а нужно использовать std::thread(std::ref(f))?
Заранее благодарю!

A: std@bad_function_call можно получить, если внутри фукнции лежит nullptr.
Смотрим снова в документацию и видим такое
template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );

ага, нужно, что бы move конструктор отработал и можно получить такой эффект. Так как автор вопроса упоминает о передаче по ссылке и по std::ref, сделаем маленький шаг в сторону
std::function<void()> f=[](){std::cout<<"Yaha";};

std::thread thr1(std::move(f));
std::thread thr2(f);
thr1.join();
thr2.join();

и получим желаемую ошибочку. std::move провоцирует вызов move конструктора, который в случае std::function зануляет указатель.
А возможно, компилятор у  Embarcadero RAD Studio такой хитрый, что вызывает move конструктор. или там сам std::thread объявлен с std::forward, надо смотреть в сам код. я этого проверить не могу.


text:
Q: Is this a valid transformation of a expression? I need to check if this function is continuous:
$$f(x)= \lim_{n\to\infty}\sqrt[n]{4+x^{6n}}$$
So I did this:
$$f(x)= \lim_{n\to\infty}\sqrt[n]{4+x^{6n}} = \lim_{n\to\infty}(4+x^{6n})^{1/n} =\lim_{n\to\infty} \left(x^{6n}\cdot \left(\frac{4}{x^{6n}}+ 1 \right) \right)^{1/n}$$
$$f(x) = \lim_{n\to\infty}x^6 \cdot \left(\frac 4 {x^{6n}}+ 1\right)^{1/n} = x^6$$
Is this valid? Can I now just check the continuity of:
$$f(x) = x^6$$

A: Hint
Your function $f$ is defined by
$f(x)=1$ if $|x|\leq 1$  and
$f(x)=x^6$ if $|x|>1$.
so, it is continuous at $\mathbb R$.

A: When you did the $$\lim_{n\to\infty}({4+x^{6n})^{1/n}} =\lim_{n\to\infty}(x^{6n}\cdot({\frac{4}{x^{6n}}+ 1))^{1/n}}$$
step, you introduced a discontinuity at $f(0)$, due to the $\frac4{x^{6n}}$ which is a div$/0$ error that was not accounted for. See if you can find a different way around this issue.


text:
Q: How to modify the query that is used when autoloading related entities? Assume there's a very basic structure: A Category can contain multiple items of Product:
/**
 * @ORM\OneToMany(targetEntity="Product", mappedBy="category", cascade="remove")
 */
protected $products;

/**
 * @ORM\ManyToOne(targetEntity="Category", inversedBy="products")
 * @ORM\JoinColumn(name="product_id", referencedColumnName="id")
 */
protected $category;

I get all products, when I access them through the category like this:
$category->products;

Let's say a Product has an attribute invisible. How can I force Doctrine to only load the products that are visible. Where do I put this query? Into the repository? But than: How Do I call it or switch between "load all" and "load certain"? I could of course request the products separately, but this seems not like a good solution.

A: In my opinion a better solution would be the usage of Doctrine Filters (if you are using Doctrine 2.2 or higher)
Doctrine Filter manual
You can define a custom filter for you invisible property and enable/disable it whenever you want through the Entity Manager.

A: The easiest way is to simple add a visibility parameter to your category->getProducts() method:
class Category
{
public function getProducts($invisible = false)
{
    if ($invisible) return $this->products;

    $visibleProducts = array();
    foreach($this->products as $product)
    {
        if ($product->isVisible()) $visibleProducts[] = $product;
    }
    return $visibleProducts;
}

This does not prevent the loading of all products but it does give you an easy way to decide which products you want.  And it's very easy to implement.  You can refine it later.
A second approach would be to create a query to load all your categories with the products.  That will avoid the lazy loading of products and allow you to specify exactly which products you want.
And finally, you could follow @w1cked's suggestion and make a D2 filter.  Takes a little bit of effort to understand the process.

A: One solution is to create a "visibleProduct"-Entity, use Single-Table-Inheritance ( http://docs.doctrine-project.org/en/2.0.x/reference/inheritance-mapping.html#single-table-inheritance ) and make a second relation from categories.


text:
Q: Create a new database without using MySQL Workbench There is MySQL installed on machine but MySQL Workbench is not installed. Generally, we do create the DB using the workbench.
Is there any way to create a new Database without using MySQL Workbench?

A: It can be easily done by using the below command. You can do this via CLI via execute option:
mysql -u username -p -e "CREATE DATABASE `new_database_name_to_create`";


text:
Q: Fatal error: Uncaught PDOException when running php site I'm trying to run a php site that use mysql but i get error
Fatal error: Uncaught PDOException: could not find driver in C:\Users\aoshe\OneDrive\Desktop\test\includes\config.php:3 Stack trace: #0 C:\Users\aoshe\OneDrive\Desktop\test\includes\config.php(3): PDO->__construct('mysql:host=sql7...', 'sql7595523', Object(SensitiveParameterValue)) #1 C:\Users\aoshe\OneDrive\Desktop\test\account\login.php(3): include('C:\\Users\\aoshe\\...') #2 {main} thrown in C:\Users\aoshe\OneDrive\Desktop\test\includes\config.php on line 3

I'm running from windows


text:
Q: How to change string into JSON format structure using PHP? I have these code to pull data from two different database.
And I need to eliminate the same row by 'staffid'.
So far I can eliminate the duplicate. But the output is not what I want it to be.
index.php
<?php

    // PART A
    require 'conn.php';
    $query = "SELECT STAFFID FROM TABLE";
    $result = oci_parse($conn, $query);
    oci_execute($result);
    while ($row = oci_fetch_array($result,OCI_NUM)){
        $arr[] = $row[0];
    }

    // PART B
    $url="http://localhost/fetch_data.php";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL,$url);
    $result=curl_exec($ch);
    curl_close($ch);

    foreach(json_decode($result) as $result2)
    {
        if(!in_array($result2[0],$arr))
        {
            $total = "".$result2[0].",".$result2[1].",".$result2[2]."
";
            echo json_encode($total);
        }
    }
?>

The output for far for the above code as below
"A001","BILLY","email1@mail.com"
"A002","JOHN","email2@mail.com"
"A003","SALLY","email3@mail.com"

fetch.php
<?php
    include_once('conn.php');

    $arr        = array();
    $query      = "SELECT * FROM TABLE ";
    $stmt       = sqlsrv_prepare($conn, $query);
    $result     = sqlsrv_execute($stmt);
    $row        = sqlsrv_fetch_array($stmt);

    $array  = array();
    while( $self = sqlsrv_fetch_array( $stmt)) {

        $array2 = array();
        $array2[]= $self['ID'];
        $array2[]= $self['NAME'];
        $array2[]= $self['EMAIL'];

        $array[] =  $array2;
    }
    echo json_encode($array);
?>

My goal is to change it into JSON as below. I'm missing the bracket and the coma.
[
    ["A001","BILLY","email1@mail.com"],
    ["A002","JOHN","email2@mail.com"],
    ["A003","SALLY","email3@mail.com"]
]

Appreciate if someone can help me to fix this issue. Thanks.

A: Try changing
foreach(json_decode($result) as $result2)
{
    if(!in_array($result2[0],$arr))
    {
        $total = "".$result2[0].",".$result2[1].",".$result2[2]."
";
        echo json_encode($total);
    }
}

into
foreach(json_decode($result) as $result2)
{
    if(!in_array($result2[0],$arr))
    {
        $total[] = $result2;
    }
}
echo json_encode($total);


text:
Q: compoment is not displaying i am working with angular lazy loading and not able to display the child1,child2, and child3 in main compoment.
here is the code for your referance
what i am trying to do is
display child1, child2 and child3 in main component which is in sharemodule
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { APP_BASE_HREF, LocationStrategy, PathLocationStrategy } from '@angular/common';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeModule } from './home/home.module';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HomeModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

--- app.component.html
<button routerLink="/home">home</button>
<button routerLink="/login">login</button>
<router-outlet></router-outlet>

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { SharedModule } from './shared/shared.module';

const routes: Routes = [
  { path: '', component: HomeComponent, pathMatch: 'full'},
  { path: 'login', component: LoginComponent},
  { path: 'home', component: HomeComponent},
  { path: '**', component: HomeComponent }
];

@NgModule({
  imports: [SharedModule, RouterModule.forRoot(routes, {useHash: false})],
  exports: [RouterModule],
})
export class AppRoutingModule {}

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HomeRoutingModule } from './home-routing.module';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClientModule } from '@angular/common/http';
import { SharedModule } from '../shared/shared.module';
import { HomeComponent } from './home.component';

@NgModule({
  declarations: [HomeComponent],
  imports: [
    BrowserModule,
    CommonModule,
    BrowserAnimationsModule,
    HttpClientModule,
    HomeRoutingModule,
    SharedModule
  ],
  exports: [HomeComponent]
})

export class HomeModule { }

I am home

child1
child2
child3

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { MainComponent } from '../shared/main/main.component';

const homeRoutes: Routes = [
  {
      path: '', component: MainComponent,
      children: [
          { path: '', redirectTo: 'cust', pathMatch: 'full'},
          { path: 'cust',
          loadChildren: () => import('../features/features.module').then(m => m.FeaturesModule)},
      ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(homeRoutes)],
  exports: [RouterModule]
})
export class HomeRoutingModule { }

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  { path: '', pathMatch: 'full', redirectTo: 'features' },
  { path: 'features', loadChildren: () =>
    import('./childrens/childrens.module').then((m) => m.ChildrensModule)
  },
];

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    RouterModule.forChild(routes)
  ]
})
export class FeaturesModule { }

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';
import { Child1Component } from './child1/child1.component';
import { Child2Component } from './child2/child2.component';
import { Child3Component } from './child3/child3.component';

const routes: Routes = [
  { path: '', pathMatch: 'full', redirectTo: 'child1' },
  {path: 'child1', component: Child1Component},
  {path: 'child2', component: Child2Component},
  {path: 'child3', component: Child3Component},
  {path: '**', component: Child1Component},
];

@NgModule({
  declarations: [Child1Component, Child2Component, Child3Component],
  imports: [
    CommonModule,
    RouterModule.forChild(routes)
  ]
})
export class ChildrensModule { }

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { MainComponent } from './main/main.component';
import { RouterModule } from '@angular/router';

@NgModule({
  declarations: [MainComponent],
  imports: [
    CommonModule,
    RouterModule
  ],
  exports: [MainComponent]
})
export class SharedModule { }

—main.html
<router-outlet></router-outlet>

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-main',
  templateUrl: './main.component.html'
})
export class MainComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

}

--child1.html

i am child 1

--child2.html

i am child 2

--child3.html

i am child 3

I am trying very hard to fix it.
Any solution
Thanks In advance

A: remove { path: '**', component: HomeComponent } from AppRoutingModule and see the magic happens.

When you define path: '**' it means every path except what I defined before!

By clicking on childComponents you are changing the path of home to cust and the AppRouting triggers the path: ** then it rerender the home components and you stuck in a loop.


text:
Q: Is running a query directly from an Axon aggregate's command handler OK with CQRS? This is more of a theoretical question related to CQRS and Axon. Below is a self-explanatory setup, the code is a pseudo-code, it is not meant to compile.
Assuming that in order to process a command from an aggregate "Foo" we need first to query a state of another aggregate "Bar" for validation (from another bounded context, so it's not a question of a simple lookup of the "Foo"'s member aggregates).
We have two choices here as illustrated in the pseudo-code. Choice (1), we just run the query from the command handler in the "Foo" aggregate using the query gateway.
Choice (2), we apply an event asking a dedicated service to handle the querying instead of "Foo". The service then will dispatch a command back to "Foo" after it has queried the system for the state of "Bar".
Does the first choice (querying directly from the command handler) seems to go against the whole idea of Command-Query separation -- after all, this way we are executing a query during a command processing, right?
The second choice seems more in the spirit of CQRS: the command just results in an event (which later will result in an another command, etc.). But obviously, this comes at a cost: there are more steps involved, 2a, 2b, 2c, 2d...
I would like to hear what the community thinks about this. For me, it seems bizarre if we are strict about not mixing commands with query processing but are allowing executing queries with command processing. Or am I missing something?
@Aggregate
class AggregateFoo {

    private QueryGateway queryGateway;

    @CommandHandler
    public void on(UpdateFooCommand command){

        /*
            Assume that in order to validate this command we first need
            to query the state of another aggregate, "Bar".
        */

        // 1. We can just issue the query directly from the command handler.

        queryGateway
            .query(new AskForStateOfBarQuery(command.getBarId()))
            .then(queryResponse -> {
                // Proceed with original command execution depending
                // the result of the query response.
            });

        // 2a. Or we can issue an intermediate EVENT offloading the query handling
        //     to a dedicated service ("FooBarService", see below).

        AggregateLifecycle.apply(new FooUpdateValidationRequestedEvent(command.getBarId()));

    }

    // 2d. "Foo" aggregate will react to the validation command from the
    //     dedicated service effectively executing the original command.

    @CommandHandler
    public void on(ProceedWithFooUpdateCommand command){

        // Do other validations, issue events here. At this
        // point we know that UpdateFooCommand was validated.
    }

}

@Service
class FooBarService {

    private QueryGateway queryGateway;
    private CommandGateway commandGateway;

    @EventHandler
    public void on(FooUpdateValidationRequestedEvent event){

        // 2b. The dedicated service will run the corresponding query,
        //     asking for the state of "Bar".

        queryGateway
            .query(new AskForStateOfBarQuery(command.getBarId()))
            .then(queryResponse -> {

                // 2c. And will issue a COMMAND to the "Foo" aggregate
                //     indicating that it shoud proceed with the original
                //     command's (UpdateFooCommand) execution.

                commandGateway.send(new ProceedWithFooUpdateCommand(command.getFooId()));

            });

    }

}

UPDATE:
This is an update after the discussion of the informative answer given by 91stefan (see below).
class AggregateFoo {
    int f = 9;

    // reference to the related Bar aggregate
    UUID bar;

    on(UpdateFooCommand){
        // Assume we must execute ONLY IF f < 10 AND bar.b > 10.
        // So we apply event to Saga (with f = 9),
        // Saga will ask Bar: (b = 15), so the condition holds
        // and Saga issues ConfirmValidBarStateCommand
    }

    // Meanwhile, when Saga is busy validating, we process another
    // command CHANGING the state of Foo
    on(AnotherCommand) { f++; }

    // or "ConfirmValidBarStateCommand" as in 91stefan's example
    on(ProceedWithFooUpdateCommand){
        // So when we get back here (from Saga), there is no guarantee
        // that the actual state of Foo (f < 10) still holds,
        // and that we can proceed with the execution of the
        // original UpdateFooCommand
    }

}

class AggregateBar {
    int b = 15;
}

So looks like the question still holds: how to validate and execute a command consistently in Foo if its validation depends on the state of Bar from another bounded context? Looks like we may have several choices here:

*

*direct query from Foo's command handler for a projected state of Bar

*event to a (stateless) service which queries Bar for a projected state

*(91stefan's suggestion) event to a Saga which sends validation command to Bar

A: You might face issues, querying from the command handler is not considered a good practice as your projection might not be up-to-date due to eventual consistency. Also, command handlers from same aggregate are executed sequentially/synchronously. You just want to do quick stuff, calling external services will block and prevent other commands from aggregate from executing until the current command handler finishes execution.
What you need in this case is Saga.
https://docs.axoniq.io/reference-guide/v/3.3/part-ii-domain-logic/sagas
Simplify flow would be:

*

*commandHandler(UpdateFooCommand) -> applyEvent(AskedForStateOfBarEvent)

*AskedForStateOfBarEvent starts Saga

*Inside saga, send command to Bar aggregate -> ConfirmYourStateBar(barAggregateId)

*commandHandler(ConfirmYourStateBar) -> validate state -> applyEvent(StateIsValidatedEvent)

*Saga reacts to StateIsValidatedEvent, sends command to AggregateFoo -> (ConfirmValidBarStateCommand(aggreageFooId) & saga is closed (end event is StateIsValidatedEvent)

*In commandHandler(ConfirmValidBarStateCommand) you proceed your execution, as your state BAR state is valid

A: What I know is like below:
For the first option : Query side may not be up2date, so this may cause wrong business decision, as it is already mentioned.
For the second and third options : A query is a query, event is a fact. Triggering events for query result seems like to misuse/hacky. I cant imagine how many events will be stored in the aggregate after a while. Using a saga also for this purpose seems like to be misuse. Sagas should be processing chain of events(AskedForStateOfBarEvent does not seems like to be state change(event) for an aggregate)
There are some hints for Command Handlers here


text:
Q: Php script performing differently on Chrome as oppose to IE & FF I have a php script that returns posts from tumblr. The posts are determined by a number. The number is incremented by 1 every time I hit the go button on my website. This seems t work perfectly in Firefox and Internet explorer but not chrome.
My code:
My index.php file.
<?php
     session_start();
     $_SESSION['views'] = 0;
 ?>
 <?php include 'blogFunction.php';?>

my blogFunction.php
function blogreturn(){
    $request_url = "http://retrovate.tumblr.com/api/read?type=posts";
    $xml = simplexml_load_file($request_url);

    $a = $_SESSION['views'];
    $b = $a+4;
    echo "A = ".$a;
    echo "B = ".$b;
    $_SESSION['views'] = $_SESSION['views']+ 1;
    for ($i = $a; $i <= $b; $i=$i+1) {
            echo '
'.$xml->posts->post[$i]->{'regular-title'}.'
';
            echo '
';
            echo $xml->posts->post[$i]->{'regular-body'};
            echo '
';
            echo '
';
    }
}

My website can be foundhere to test.
The website should also print the values of A and B under the 'Go' Button.
Any idea why it doesn't work in chrome. Thanks in advance!


text:
Q: undefined reference of a function but already defined in header main cpp
#include "utility.h"
#include <windows.h>

int main()
{
    do
    {
        changeColor();
        system("pause");
    } while (true);
}

utility cpp
#include "utility.h"
#include "variables.h"
#include <windows.h>

namespace utility
{
    void changeColor()
    {
        if (var::colorCounter == 0)
        {
            system("color af");
        }
        else if (var::colorCounter == 1)
        {
            system("color cf");
        }
        else if (var::colorCounter == 2)
        {
            system("color df");
        }
        else if (var::colorCounter == 3)
        {
            system("color 6f");
        }
        else
        {
            system("color 9f");
            var::colorCounter = -1;
        }

        var::colorCounter++;
    }
}

utility header
#ifndef utility

#define utility

void changeColor();

#endif

variables
#ifndef variables
#define variables

namespace var
{
    inline int colorCounter{};
}

#endif

idk whats causing it to produce the changeColor() to not define what should i do? also is may coding right?

A: There are many problems with your code which are shown through the comments in the modified program below.
main.cpp
#include "utility.h"
int main()

{
        utility::changeColor();//used utility:: because you've to be in the scope of namespace utility to call function changeColor()
}

utility.h
#ifndef UTILITY_H  //USED INCLUDE GUARDS
#define UTILITY_H

namespace utility {
void changeColor(); //this function declaration is now inside the utitliy namespace

}
#endif

variables.h
#ifndef VARIABLES_H //USED INCLUDE GUARDS
#define VARIABLES_H

namespace var
{
    //NOTE the extern keyword here instead of inline keyword
    extern int colorCounter; //this is a nondefininig declaraiton for colorCounter.

}

#endif

variables.cpp
#include "variables.h"

namespace var
{
    int colorCounter = 0; //this is definition of colorCounter
}

The output of the above program can be seen here.
Modifications
Some of the modifications that i made include:

*

*In main.cpp, you have to be in the scope of the namespace utility to call function changeColor(). This is achieved using utility::.

*In utility.h, header guards are used. This is a recommended practice.

*In utility.h, the function declaration for changeColor is placed inside the namespace utility.

*In variables.h, extern keyword is used instead of inline keyword to make the declaration of colorCounter a declaration that is not a definition. This essentially means, colorCounter has external linkage.

*In variables.cpp, the variable colorCounter has been initialized with value 0.

Note
If you still want to use inline instead of extern you can do so from C++17 and onward as can be seen here. So if you use inline your program will work for C++17 and onwards. But if you use extern as in my above code, then your program will work in all C++ versions. You can choose whichever version you want.


text:
Q: How can i pointer char variable add to list char variable in C Programming i stucked, need to add pointer char value to list char value. pointer char value includes username (windows machine) and list char value includes startup path. I tried to strcat but it breaks the first ";" part.
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
    char *username = getenv("USERNAME");
    //printf("%s\n", username);

    char shortcutpath[100] = "C:\\Users\\";"\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup";  //2 ; is weird, i just tried

    strcat(shortcutpath, username);
    printf("%s\n",shortcutpath);
    return 0;
}

Output = C:\Users%username%    ,needs to continue
Need to assign a variable "C:\Users\%username%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup" this path
Is there any easy way to do that? Or something other usefull things?

A: char shortcutpath[255] = "C:\\Users\\";
strcat(shortcutpath, username);
strcat(shortcutpath, "\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup");

A: You probably want this:
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
  char* username = getenv("USERNAME");
  char shortcutpath[100] = "C:\\Users\\";
  strcat(shortcutpath, username);
  strcat(shortcutpath, "\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup");

  printf("%s\n", shortcutpath);
  return 0;
}

But the more correct way would probably be to get directly the APPDATA environnement variable:
int main(void)
  {
    char shortcutpath[100];
    char* appdata = getenv("APPDATA");  // C:\Users\<yourusername>\AppData\Roaming
    strcpy(shortcutpath, appdata);
    strcat(shortcutpath, "\\Microsoft\\Windows\\Start Menu\\Programs\\Startup");
    ...


text:
Q: Vector subspace of polynomials If I have a set of polynomials of degree at most $2$, such that $p(x) \geq 0$ for any real $x$.
It isn't a vector subspace because I can multiply by a negative number such that $p(x) < 0$?

A: The bound on the degree is irrelevant. If $S$ is a set of polynomials such that $p(x)\ge 0$ for all $x$ and all $p\in S$, then $S$ is not a subspace so long as it contains a nonzero polynomial: for that polynomial you would have $p(x_0)>0$ for some $x_0$ and therefore $-p(x_0)<0$, so $-p\notin S$.
So the only choice is $S=\{0\}$.


text:
Q: Contract Testing for AWS Lambdas Is there any way to do Contract testing for the AWS lambdas.
Pact is being used for normal APIs, But I am trying to implement Contract Testing on AWS SAM. Is there any tool for this or Pact can be used with any modifications?

A: Yes, you can use Pact to do contract testing with Lambda.
For example, Pact JS has support for asynchronous programming and has an example for Lambda using the serverless framework [1].
There is a good intro article [2] on the matter also.

*

*[1] https://github.com/pact-foundation/pact-js/#asynchronous-api-testing

*[2] https://dius.com.au/2017/09/22/contract-testing-serverless-and-asynchronous-applications/

A: You can use the amazon-cli if you want to test it.
amazon-cli will help you to manually trigger your lamda via aws lambda invoke the command.
Please install amazon-cli at your local from this link.
After that you can invoke the amazon 1st lamda from your cli with aws lamda command. It comes with many options like you can pass payload (supposed to be pass from SNS in actual scenario).
Executing AWS Lamda from Amazon-CLI Command details description
Example command:
aws lambda invoke --function-name your_function_name --invocation-type RequestResponse outfile.txt --payload file:requestFile.txt

I hope it helps.


text:
Q: Loading .css file from inside a component in React I have a component that determines the location of the desired .css file via an ajax call in componentDidMount(), that I want to then load before render. I've tried just adding a <link> element in the render return (didnt work), I've also tried directly injecting the  tag into the head using vanilla JS, but this also didnt work:
async componentDidMount() {
    await this.fetchPanelInfo().then(result => {
        console.log(this.state);

        const link = document.createElement("link");
        link.href= this.state.stylePath;
        link.rel = "stylesheet";
        link.type="text/css";
        document.head.appendChild(link);
        //const style = document.getElementById("style-direction");
        //style.href = this.state.stylePath;
    })
}

The shortened component:
class Panel extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        token: "f0be0f7d231305a832fd1eef4bcb0e9ba18f2d65",
        error: null,
        errmsg: null,

        menuContent: null,
        stylePath: null,
        services: null,

        loading: true
    }
    isLoggedIn().then(logged => {
        //Nothing for now
    })
}
//Gets all information about the panel
async fetchPanelInfo() {
    await axios({
        method: 'post',
        url: `${ENDPOINT}`,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        data: this.state
    }).then(result => {
        console.log(result.data);
        this.setState({
            error: result.data.error,
            menuContent: result.data.menu,
            stylePath: result.data.stylePath,
            services: result.data.services,
            loading: false
        });
    }).catch(err => {
        console.log("error");
        console.log(err);
        this.setState({error: err.error})
    });
}

async componentDidMount() {
    await this.fetchPanelInfo().then(result => {
        console.log(this.state);

        const link = document.createElement("link");
        link.href= this.state.stylePath;
        link.rel = "stylesheet";
        link.type="text/css";
        document.head.appendChild(link);
        //const style = document.getElementById("style-direction");
        //style.href = this.state.stylePath;
    })
}

render() {
    if(this.state.loading) return null;
    return (

Hello

            <Menu items={this.state.menuContent} />

    );
}
}

This is a page that <Router> navigates to, so I cant explicitly pre-fetch the name of the stylesheet and import separately, because the stylesheet loaded depends on the supplied token (i.e., it varies from token to token).
Any ideas?

A: I managed to load and apply the dynamic .css file, as follows:
async componentDidMount() {
    await this.fetchPanelInfo().then(result => {
        console.log(this.state);

        if(this.state.stylePath === undefined) {
            require("../" + "core/data/default/styles.css");
        } else {
            require("../" + this.state.stylePath);
        }
        const React = require('react');
    })
}

Basically using the require() module.


text:
Q: How to get certain parts of a perl hash I'm learning perl and using Weather::NOAA::Alert and am wanting to figure out how to capture only a certain part of its output.
It outputs a hash, but I only want a certain part, for example the urgency part... what should I do?
Sample output

A: It's not array is a hash of hashes of hashes. You can access values by
$result->{'US'}->{'http://alerts.weather.gov/cap/wwacapget.php?x=MT124CAB8F109C.WinterWeatherAdvisory.124CAB90FBA0MT.TFXWSWTFX.c906fc319cc9f5b747e95ac455f8c2f0'}->{'certainty'}

will contain the string
Likely

Check http://www.cs.mcgill.ca/~abatko/computers/programming/perl/howto/hash/ for an introduction on Perl hashes.


text:
Q: How can one estimate a new λ for a Poisson Distribution after changing circumstances? To fit the question to a problem lets say you have a store in a mall where the rate of customers visiting the store can be modelled as a Poisson Distribution where λ = 3.
Now lets say next month because of an effort by the mall to bring more shoppers to it the effective population of customers within the mall doubles. How would the store estimate the new λ that would result from this change?
If these new shoppers were expected to visit the store at the same rate should λ just be doubled to 6? If the rate of these new shoppers was expected to differ could I utilize Bayesian statistics to calculate a posterior distribution for the new shoppers and add it onto my already existing Poisson Distribution?
old_rate = 3
n_obs = 10,000
poisson_shoppers = np.random.poisson(old_rate, 10000)

# fit a pymc3 model to get the rate
basic_model = pm.Model()

with basic_model:
    lambda_prior = pm.Uniform('lambda_prior',1,4)

    #likelihood
    Y_obs = pm.Poisson('Y_obs',mu = lambda_prior, observed = poisson_shoppers)

with basic_model:
    trace = pm.sample(2000)
    pm.traceplot(trace)
    plt.show()

From the distribution generated could I just add up my counts for both distributions to then generate an estimate what the rate would be for the doubled population of shoppers?
If anything is to vague or needs further details please let me know and I will try to better explain or add them.


text:
Q: Migration issue - broken path links SharePoint 2010 --> SharePoint 2013 After Mount databases every path links /sites broken, what can I do to fix it?
In the farm there is only standard link path /sites, no custom path?

A: Even we faced the same issue when migrating from 2007 to 2010. It was rectified when the port of 2010 environment was set to be same port number of 2007. I am not sure why and how it solved the issue but can any one of SharePoint experts out there can shed some light onto it?
Thanks


text:
Q: Aggregation of time-series data on multiple columns                      rand_val  new_val           copy_time
2020-10-15 00:00:00         7       26 2020-10-15 00:00:00
2020-10-15 00:00:10         8       29 2020-10-15 00:00:10
2020-10-15 00:00:20         1       53 2020-10-15 00:00:20
2020-10-15 00:03:50         6       69 2020-10-15 00:03:50
2020-10-15 00:04:00         3       19 2020-10-15 00:04:00

I am using the method resample to downsample the time-series. I have found I cannot call the specific columns when applying a function on the aggregated data.
Let's say I want to do some operation that involves calling the name of a column:
df.resample("1min").apply(lambda x: sum(x.rand_val) if len(x)>1 else 0)

I get an error:
AttributeError: 'Series' object has no attribute 'rand_val'

This would be possible if I had done groupby on some other variable. I guess the resample function is not the same. Any ideas?

A: That's a good question!. When we do groupby certain columns, each chunk of data is treated as a pandas DataFrame. So, we can access a column like how we normally do. But, in this case of resample, it's a series.
One way of obtaining only for rand_val would be to pass that series directly as follows:
df.resample("1min")['rand_val'].apply(lambda x: sum(x) if len(x)>1 else 0)

I'm assuming your index is in date-time format. Else please convert it using pd.to_datetime as follows:
df.index=pd.to_datetime(df.index)

A: With on=copy_time, i got the following output.
a = df.resample('1min',on='copy_time').apply(lambda x: sum(x.rand_val) if len(x)>1 else 0)
print (a)

resample is looking for an object that must have a datetime-like index. In your example, I didn't see that. Passing copy_time would give that datatime series to process.
             org_time  rand_val  new_val           copy_time
0 2020-10-15 00:00:00         7       26 2020-10-15 00:00:00
1 2020-10-15 00:00:10         8       29 2020-10-15 00:00:10
2 2020-10-15 00:00:20         1       53 2020-10-15 00:00:20
3 2020-10-15 00:03:50         6       69 2020-10-15 00:03:50
4 2020-10-15 00:04:00         3       19 2020-10-15 00:04:00

copy_time
2020-10-15 00:00:00    16
2020-10-15 00:01:00     0
2020-10-15 00:02:00     0
2020-10-15 00:03:00     0
2020-10-15 00:04:00     0
Freq: T, dtype: int64


text:
Q: Transparent Alert Dialog box I have few doubts regarding transparent AlertDialog box in android.I have created the alert dialog box using AlertDialog.builder in the camera surface view but i want Transparent alert dialog box is it possible. please help me
Regards
Raj

A: Yes, this is possible.  I believe you can do it by creating a custom alert dialog:
http://developer.android.com/guide/topics/ui/dialogs.html#CustomDialog
you can then set the background of your custom dialog to transparent like so:
this.getWindow().setBackgroundDrawableResource(R.drawable.transparent);

(where "R.drawable.transparent" is a reference to the color "#00000000")

A: Use  this
The code is as follows
Dialog mDialog = new Dialog(mContext, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);

Answer taken from a similar answer here


text:
Q: Who might I have to defend my title against? In Pokémon Sun/Moon, since you're the first Pokémon League champion, you're set to defend your title as Pokémon League Champion, rather than repeatedly taking the title from your rival or whoever the champion before you was. Unlike previous iterations in the series, who you fight in the championship match changes.
So far, after beating

 Professor Kukui,

I've had to defend my title against

 Hau and Molayne.

This leads me to believe that there are a vast number of challengers I could have to defend my title against. However, at least one captain is also a member of the Elite Four, so not all captains could be challengers. That said, is there a list of who all could potentially challenge me? I know Red and Blue are in this game, so could they challenge me?

A: Serebii has compiled a challenger list. They state that there are 10 potential challengers you will face, chosen at random. This is excluding the first time you beat the league which is fixed. According to Bulbapedia, the first title defense (second time in the league) is also a fixed challenger. And one challenger only appears on a certain day of the month.
Challenger names listed in spoiler below.

 Hau (First title defence/second time at the league)
 Sophocles
 Ryuki
 Gladion
 Molayne
 Plumeria
 Hapa
 Faba  (Always appears on the first of the month)
 Tristan
 Kukui (First time in the league)

A: It is random. I mostly get

Molayne.

I dont think Red or Blue are challengers, sadly. They are just battle tree guys. They are really strong, though.

A: Trust me, beat the elite 4 53 times then you'll be facing challengers from the other previous games. If you don't think its true check out the youtube videos then you'll have proof.


text:
Q: Help identify this connector What is the name of this connector ?
I need to replace it but I don't know what to search for.

Edit : I added 2 photos. If it can help, the card is an SW200D1 from Advisen.

A: That is a single wall, wire-to-board connector, 3.96 mm pitch (my site). Manufacturers include:

*

*MANUF. - SERIES

*Adam tech - LHB LHC LHD + MTB (crimp)

*Molex - KK 171813 KK 171814 KK 41671 KK 41672 KK41681 KK41682 KK41791 KK41792 KK42491 KK42492 KK42891 KK42892 KK5273 KK5274 KK5277 KK8619 MV-396 + KK 2139 KK 3069 kk 5239 KK 6442 KK 41695 SPOX 43061 SPOX 5195 SPOX 5196

*Molex - KK 3190 + KK 2139 KK 3069 kk 5239 KK 6442 KK 41695 SPOX 43061 SPOX 5195 SPOX 5196

*OnShore - 8673-xx-S + 8639-xx

*TE - MTA-156 + SL-156 (1w crimp)

*Wurth - WR-WTB 645

You can buy the housing here but you also may need to buy crimp contacts for it, which depend on the wire size.


text:
Q: Is it possible to use async/await in MVC 4 AuthorizeAttribute? The only override I see exposed on MVC's AuthorizeAttribute is public override void OnAuthorization( AuthorizationContext filterContext ) which is not suitable for use with async/await because it doesn't return a Task. Is there another way to create an AuthorizeAttribute in MVC that allows the use of async/await?

A: With asp.net core being released, Stephen Cleary's answer is correct and the ideal way to go if you are running the latest asp.net core.
For those that haven't updated yet, I was able to work around my issue using an async HttpModule that passes state into the AuthorizationFilter via HttpContext.Items. I added more detail about my solution here - http://evandontje.com/2017/08/15/solutions-for-async-await-in-mvc-action-filters/

A: For those who do not yet have the joy of being on .NET core, you can use this method from ASP.NET Web API 2 :
OnAuthorizationAsync override :
public override async Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellation)

for example, you can call an async webapi service like this :
 public override async Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellation)
    {
        await base.OnAuthorizationAsync(actionContext, cancellation);

        if (await IsUserAdminAsync()) /* call any async service */
            return;
        this.HandleUnauthorizedRequest(actionContext);
    }

A: ASP.NET MVC today does not support asynchronous filters. Please vote.
However, ASP.NET "vNext", announced at TechEd this week, will support asynchronous filters for MVC.


text:
Q: Use DISTINCT as filter when calculating SUM Software: MS Excel 2016
Here is a table

Given, there will alway be same number of triggers for a particular ID. But I don't want to count those triggers multiple times.
I tried the following DAX. My expected answer is 72, but I get 143 instead. How to fix?
Distinct_Matches:=CALCULATE(sum(Incidents[Triggers]),DISTINCT(Incidents[Incident_ID]))

A: Use this:
=SUMPRODUCT(B2:B7/COUNTIF(A2:A7,A2:A7))

Here is the formula with structured references:
=SUMPRODUCT(Incidents[Triggers]/COUNTIFS(Incidents[Incident_ID],Incidents[Incident_ID]))

A: The below would work, assuming that Incident_ID's trigger value is the same across the ID Number.
Measure 1:=SUMX( DISTINCT(Table1[Incident_ID]), CALCULATE(AVERAGE(Table1[Triggers])))

Table1 just being the name I used as part of the quick test.
The idea being that the sumx would iterate though every unique Incident_ID and sum the result of the calculate statement.  The calculate statement is using average, since it will return the unique value.  E.g. Average(41+41) = 41.  You could also use MIN or MAX as well.


text:
Q: "RTP over UDP" packet loss analysis with Wireshark I am running Application A on Machine A and Application B on Machine B. Both machines are running Windows7. Application A sends RTP packets over UDP to Application B through a private LAN. We are experiencing UDP packet loss between the 2 machines and we are trying to determine if the packet loss is occurring at the network level or on the network stack of the machine.
We are running Wireshark on both machines with WinPcap. By analyzing the RTP stream in Wireshark, we can see that all the RTP packets are sent from Machine A but some packets are not received on Machine B. I understand that the UDP packets can be dropped by the network stack of the OS if for example an application don't read fast enough from its socket and the socket's buffer gets filled. But what I would like to know is this:
If I see that an RTP packet is missing with Wireshark on machine B, does it necessarily mean that the packet was not received from the network? Or is it possible that the packet was dropped at some point in the OS before Wireshark "intercepts" the packet?


text:
Q: Detect App Killed or Terminated in Flutter I want to insert data to local database when user terminates the app. So far, I found AppLifecycleState but the there's no equivalent for state when App Killed (the closest to it is AppLifecycleState.paused but the execution is more like onActivityPaused in Android).
Is it possible to detect user when terminate the app? If it's possible, how can I do so? Any help would be so appreciated, thank you!


text:
Q: Google Analytics Event Tracking not Appearing in Real Time This event and all onclick events like it are not tracking in Google Analytics Real Time.  Any idea why not?
email@domain.com

This is not specific to mailto links.  This is for any link where I'm trying to use onclick event tracking.
In case you're wondering I do not have an IP filter set.

A: We're using gatag.js (newer version of ga.js). I was still using the syntax from ga.js  The syntax for tracking an event is slightly different in the newer gatag.js.  That was my issue.


text:
Q: How does O(log log N) complexity loop look like? I have a very basic question here
for(int i = 1; i < N/2; i++) {

}

My initial understanding was the time-complexity for the above loop would O(logn) but after reading through some articles it is pretty much evident that it's simply O(n) and O(logn) would look like for (i = 1; i <= n; i *= 2)
Now my question is how does O(log log N) loop look like?

A: O(log n) loop:
for (i = 1; i <= n; i *= 2)

So you double i at each step. Basically:

*

*Increment => O(n)

*Doubling => O(log n)

*??? => O(log log n)
What comes after multiplication? Exponentiation. So this would be O(log log n):
for (i = 2; i <= n; i *= i) // we are squaring i at each step

Note: your loop is O(n), not O(log n). Keeping in line with the increment / double / exponentiate idea above, you can rewrite your loop using incrementation:
for(int i = 1; i < n; i += 2)

Even if you increment by more, it's still incrementation, and still O(n).

A: That loop doesn't look like O(log N). It is what it is, an O(N/2) loop. To quote the definition:
Function f(x) is said to be O(g(x)) iff (if and only if) there exists a positive real number c, and a real number x0 such that |f(x)| <= c|g(x)| for all x >= x0. For example, you could also call that loop O(N), O(N^2), O(N^3) as you can find the required parameters easily. But, you cannot find parameters that will make O(log N) fit.
As for O(log log N), I suppose you could rewrite Interpolation search implementation given here https://en.wikipedia.org/wiki/Interpolation_search to use a for loop. It is O(log log N) on the average!

A: Your cost is not O(logN) your cost is O(N*logN).
Read the link you will see a function example like :

No matter the number in the beginning of the polynomial cost is the biggest polynomial.
In your case it is
1/2 * n * log(n) , which 1/2 makes no difference your complexity is O(N*logN)


text:
Q: How to addforce in a random direction to a rigidbody2d game object How can I add a force to a rigidbody2D game object and keep it moving at a fixed velocity? The game object also has a bounce material attached.
private Rigidbody2D rb2D;
private float thrust = 10.0f;

void Start() {
}

void FixedUpdate() {
        rb2D.AddForce(new Vector2(0, 1) * thrust);
    }

This is what i got off of the Unity documentations website but this doesn't seem to do anything.
Here is the code I ended up going with and it appears to be functioning properly. The Vector2 direction and speeds can be adjusted depending on mass/ gravity.
float topSpeed = 15;
private Rigidbody2D rb2D;
private float thrust = 0.1f;
void Start()
{
    rb2D = gameObject.GetComponent<Rigidbody2D>();
    rb2D.AddForce(new Vector2(0, 1) * thrust);
}

void Update()
{
    if (rb2D.velocity.magnitude > topSpeed || rb2D.velocity.magnitude < topSpeed)
        rb2D.velocity = rb2D.velocity.normalized * topSpeed;
}

A: Your code as written, once it works will accelerate the rigidbody infinitely. You'll want to cap the velocity at its maximum speed: http://answers.unity.com/answers/330805/view.html
 rigidbody.AddForce(new Vector2(0, 1) * thrust * Time.deltaTime);

 if (rigidbody.velocity.magnitude > topSpeed)
     rigidbody.velocity = rigidbody.velocity.normalized * topSpeed;

If you want it to immediately set the velocity to the fixed value, then you can just set the velocity on every frame:
https://docs.unity3d.com/ScriptReference/Rigidbody-velocity.html
void FixedUpdate()
{
    if (Input.GetButtonDown("Jump"))
    {
        // the cube is going to move upwards in 10 units per second
        rb2D.velocity = new Vector3(0, 10, 0);
        moving = true;
        Debug.Log("jump");
    }

    if (moving)
    {
        // when the cube has moved over 1 second report it's position
        t = t + Time.deltaTime;
        if (t > 1.0f)
        {
            Debug.Log(gameObject.transform.position.y + " : " + t);
            t = 0.0f;
        }
    }
}

Your code doesn't show it so in case you aren't doing it yet, you'll want to make sure that rb2D is actually set to the Rigidbody2d on the object you want to manipulate. E.g. by doing in the start method:
void Start()
{
    rb2D = gameObject.GetComponent<Rigidbody2D>();
}


text:
Q: Meaning of "hammer a socket on it and pop it off" In a discussion on a pick-up truck car wheel theft, one person gave an advice to the victim that he "should have bought some locking lugs". This advice was disapproved by someone else in the discussion and said that it's not useful, "all you have to do is hammer a socket on it and pop it off, not hard to do."
I'm trying to visualize how this works. What is a socket, how does it look like? All I know of a socket is the ones on a wall that you put a plug into in order to connect electrical equipment. Another relevant definition I found is "a device intended to hold an electric light bulb mechanically and connect it electrically to circuit wires." I'm not sure what this is, but I don't think it's what he's describing.
So you hammer this socket on the locking lugs, by the way, after looking it up I realized that the person may have misunderstood about locking lugs and I think he meant locking lug nuts, which is a fastener used to secure a wheel on a vehicle that requires a special wrench to remove it. So you pop off this lug nut after you hammered a socket on it. Pop I checked means "to suddenly break open or come away from something often with a short, loud noise". So I'm assuming this involves some kind of tool as well in order to pop it off? How does this work, what am I visualizing? What is a socket?

A: The person who wrote about hammering a socket onto a locking lug and popping it off probably should have more precisely referred to  locking lug nuts, which is what the original poster meant by locking lugs.  Here are pictures (from alltradetools.com, jegs.com, and elementauto.com) of a small socket set and several kinds of locking lug nuts:

Note that sockets are made to fit fairly closely onto certain sizes of nuts.  The reason for hammering a socket on is to force a slightly-too-small socket onto the locking lug.  Apparently that will work on some of the  locking lug nuts shown above, but some will be immune to that approach.
Once the socket is firmly attached to the lug nut, by applying enough torque to the socket (via a cheater bar) one can break the lock, or break the lug the lug nut is screwed onto; ie can
"pop off" the nut.

A: They mean the sockets you get with a socket set. If you don't have the key socket you can get the nuts of by hammering a normal socket on.
This damages the socket (and the lug) so it wouldn't be cost-free to the thief. Really, that technique is more use to someone who has lost their key as it is then worth the hassle of damaging a tool if they can't change their tire otherwise. A thief can just go and look for someone with more easily stolen tyres.


text:
Q: W3C Validator error: Parse Error opacity=60 I've run a stylesheet through the CSS validator at W3C... The only error I get is
"Parse Error Opacity=60"
It's in this bit of the CSS:
/*Navigation Link styling */
#Nav a:link, a:visited {
display: inline-block;
width: 150px;
height: 150px;
font-weight: bold;
color: #FFFFFF;
background-color: #99FFFF;
text-align: center;
padding:5px;
text-decoration:none;
text-transform:uppercase;
filter:alpha(opacity=60);
opacity:0.6;

}
I'm assuming that the validator isn't happy with the "filter:alpha(opacity=60);" part - Is this just because it is not a standard function? And can this error be ignored.
Cheers

A: Yes, that is a non-standard property used by Microsoft (the SVG working group is reusing the name so it may appear in a new specification, but that will be a completely different thing). The error can safely be ignored.

A: It's not standard CSS, no. It can be ignored if it's doing what you want it to do and you're not bothered about validating your CSS.


text:
Q: Kotlin Collection: indexOfFirst vs find It might be a stupid question, but I am not sure whether to use indexOfFirst() or find() as both "Returns the first element matching the given [predicate]". The only difference is that one returns -1 and other null. When should I use indexOfFirst() or find(). Is there any advantage of one over other. Consider the following code snippet.
private val mPersonList = mutableListOf<Person>()

private fun findPerson(person: Person) {
    val position = mPersonList.indexOfFirst { it.name == person.name }
    if (position != -1) {
        doSomethingWithPerson(mPersonList[position])
    }
}

private fun findPersonWithFind(person: Person) {
    val foundPerson = mPersonList.find { it.name == person.name }
    foundPerson?.let { doSomethingWithPerson(it) }
}

private fun doSomethingWithPerson(foundPerson: Person) {
    //Do something
}

A: Both functions do nearly the same thing: they both locate the first matching item in a list or array (i.e. the first one for which the given predicate returns true).
The differences between them are subtle:
Most obviously, indexOfFirst() gives the index of the matching item, while find() gives the item itself.
Obviously, if you have the index, you can easily get the matching item.  (And, if the list is random-access, such as an ArrayList, then that's very efficient — much less so if it's not, such as a LinkedList.)  Whereas if you only have the item, then you can't find its index without calling find, indexOf, or indexOfFirst again!
So if you need to know the index, then only indexOfFirst() will do; but if you don't, then find() may be marginally simpler.
The code in the question falls into the latter category: findPerson() gets the position but uses it only to index into the list.  So that's a little more long-winded, and (if the list isn't random-access) potentially a lot slower, than findPersonWithFind().
Second, as you say, if no matching item is found, indexOfFirst() returns -1, while find() returns null.
Kotlin provides many ways to use nulls safely (such as the safe-call ?. operator, the elvis ?: operator, smart-casting, extension functions on nullable receivers, and many helpful functions in the standard library).  But there are no equivalents for dealing with -1, so using find() is likely to make it easier to safely handle the not-found case.
By the way, the nullability is made clear in the alternative name for find(), which is firstOrNull() — though that also has overloads which take no predicate and simply return the very first item in the list if it's not empty.  (The standard library is moving toward …OrNull() function names, probably because it makes the nullability very clear, especially when it's a common naming convention.)
So, which one you use depends on your needs.
It's also worth being aware of some related functions.  All of them have equivalents which find the last matching item: findLast()/lastOrNull(), and indexOfLast().
There's also the older indexOf() function, which checks for (equality with) a given object, instead of using a predicate.  (That, too, returns -1 if not found, which is probably why indexOfFirst() and indexOfLast() do the same.)  Though if the list is sorted, a binarySearch() or binarySearchBy is likely to be a lot faster than a full scan.


text:
Q: Howto implement table / -detail with customizable javascript-code in the detail with Webcomponents I'm not a particular clever frontend-dev but i need to maintain and enhance two webcomponents which are used to show a table and rows in that table.
It worked fine so far. The table-element is querying a json-api on the server-side and it's creating <tx-row> elements on the fly like:
for (let tx of txlist) {
       let txRow = document.createRange().createContextualFragment(`
         <tx-row
          data-price="${this.price ? this.price : 0}"
          // many more attributes here
         </tx-row>
       `)
       this.tbody.append(txRow);
       // ...
}

So now i want to adjust that and make it reusable. In my case i want to add an optional first column where each row gets a checkbox which should call some javascript code.
If this would only be one component, slots would probably already solved my issue. However here i would need to somehow pass the slot further down in the tx-row and it doesn't sound like rocket-science but rather something very simple but i can't figure it out.
If this is easy if i would use XYZ-framework, i really hope that this framework is pretty slim. You know ... frontend-developmenet doesn't look to me as it would have evolved much from the state of 2016.
But nevertheless, any hint highly appreciated! E.g. if anyone can point to a place where something similiar is solved already.


text:
Q: How to remove http response header in mvc? I want to remove http response header in mvc.

HTTP/1.1 404 Not Found Cache-Control: private Content-Type: text/html;
  charst=utf-8 Server: Microsoft-IIS/8.0 X-Powered-By: ASP.NET Date:
  Mon, 23 Feb 2015 12:43:58 GMT Content-Length: 4898 Connection:
  Keep-Alive

I remove Connection, X-Powered-By, Server, Cache-Control with this code:
> protected void Application_PreSendRequestHeaders(object sender,EventArgs e)
> {
> HttpContext.Current.Response.Headers.Remove("X-Powered-By");
> HttpContext.Current.Response.Headers.Remove("X-AspNet-Version");
> HttpContext.Current.Response.Headers.Remove("X-AspNetMvc-Version");
> HttpContext.Current.Response.Headers.Remove("Server");
> HttpContext.Current.Response.Headers.Remove("Cache-Control");
> }

but how can i do remove all http response header?

A: Please update your question with more information on the reasons driving you to remove those headers, since this looks to me as a quite unusual need, especially for content-type. It may turn out you need to do something else.
Otherwise, read on.
Try with IISRewrite module. It should allow you to get them blank.
See this answer or this more detailed one.
If removing them is really what you require, you may have to write your own custom isapi filter. There is some information about this solution on this other answer.
For many of them, you may also consider disabling what adds them rather than removing them after they have been added. See my answer on this subject for a bunch of them.


text:
Q: Multiple tables with same model I am using Active JDBC. I have a use case where I wanted to read from table_date on any given date where the structure/model of the table will be same for all the tables of this type. eg: registrations_29_10_2015, registrations_10_11_2015, etc.. where all the tables that start with registrations will have the same model/structure. How should I dynamically bind the table name with the model? I mean on 29th of Oct I want to use registrations_29_10_2015 and 10th of Nov I want to use registrations_10_11_2015. Also: Is it possible to create a table at the start of the next day using active jdbc? And FYI, this is basically for sharding the tables and drop the old tables.

A: technically speaking the framework was designed to detect table names according to conventions. However, that information is stored in a class called MetaModel: http://javalite.github.io/activejdbc/org/javalite/activejdbc/MetaModel.html#getTableName()
Each model is backed by a MetaModel. While you cannot just set the table name to the MetaModel, it is not that hard to add this feature. Please, open an issue on the project repo for consideration.
Edit: we released the sharding in ActiveJDBC a few days ago: http://javalite.io/sharding. It does exactly what you need, enjoy.