text:
Q: Geometrical interpretation of differentiability We check the differentiability of $f(x) = x\left| x \right| $ at $x=0$.
Evaluating derivatives from first principles, we find that the left hand and right hand derivatives both equate to $0$, which in principle proves that the function is differentiable at that point.
Now, let us try to interpret this geometrically.

More generally, if $x_{0}$ is a point in the domain of a function $f$, then $f$ is said to be differentiable at ${x}_{0}$ if the derivative $f ′(x_{0})$ exists. This means that the graph of $f$ has a non-vertical tangent line at the point $(x_{0}, f(x_{0}))$.

Source: Wikipedia
If so, where is the so-called unique tangent at $x=0$?

Source: WolframAlpha
Please find flaws in my interpretation, if any.
Thank you.

A: Geometrically the derivative at a point can be interpreted for strictly convex or strictly concave graphs easily: the derivative at a point $(c,f(c))$ of a strictly convex (or strictly concave) graph exists if there is a unique straight line $g(x):= ax+b$ that intersect the graph of $f$ at the point $(c,f(c))$ such that $f(x)\ge g(x)$ for all $x$ if $f$ is convex, or $f(x)\le g(x)$ for all $x$ when $f$ is concave. Then we says that $a$ is the derivative of $f$ at $c$, that is, that $f'(c)=a$.
For other functions, not necessarily strictly concave or strictly convex, the geometric interpretation is not so clear because there are infinite straight lines that can cut the graph of a function uniquely at a point as in the function of your picture.
But the geometric definition of the derivative at points of strictly convex or strictly concave graphs define analitically the derivative through a limit, and we can extend this definition to other cases not necessarily strictly concave or strictly convex.

Note that there are strictly convex and strictly concave graphs of functions that doesn't have derivative at some points, because such straight line doesn't exists or because there are more than one straight line that intersect the graph of the function uniquely in some point.

A: If you want to see the tangent at x=0, go to a graph plotter app (DESMOS), plot your graph (eg. x^3) and zoom it at x=0. Zoom upto that extent until the line becomes horizontal. This acts as the tangent at that point.
Isn't it amazing that a curve becomes parallel if zoomed to a large extent. Think it in a sense that Earth appears to be flat (because we are so small that Earth appears to be zoomed), but actually its not. So the flat surface acts as a tangent at any point where you are standing.
Hope you are clear with the geometrical approach.


text:
Q: Fiddler Get HTTP Response I am using Fiddler.Core to intercept HTTP Request.
Below is my code:
        static void Main(string[] args)
        {
            //Timer t = new Timer(TimerCallback, null, 0, 60000);
            Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
            FiddlerApplication.BeforeRequest += FiddlerApplication_BeforeRequest;
            FiddlerApplication.BeforeResponse += FiddlerApplication_BeforeResponse;
            FiddlerApplication.AfterSessionComplete += FiddlerApplication_AfterSessionComplete;
            FiddlerApplication.Startup(80, true, true, true);
               while (!_s_stop)
            {

            }
            Console.ReadLine();
        }

        static void FiddlerApplication_BeforeResponse(Session oSession)
        {
            Console.WriteLine(oSession.url);
        }

        static void FiddlerApplication_BeforeRequest(Session oSession)
        {
            Console.WriteLine(oSession.url);
        }

        static void FiddlerApplication_AfterSessionComplete(Session sess)
        {

            Console.WriteLine(sess.url);
        }

Why before response and after session complete not called?
Is it true I use port 80?
Thanks

A: I suspect port 80 is already in use by IIS. You will need to turn IIS off or change the port fiddler use.

redpajama_set_name: RedPajamaStackExchange


text:
Q: pass eventEmitter into a custom Angular Material component I'm looking to create a custom, reusable Angular Material component for a slide toggle. I want to be able to pass different click functions into it and get the MatSlideToggleChange object back. Instead I get 'undefined'.
Here is my custom component ts and html files:
<mat-slide-toggle
[id]="toggleId"
color="primary"
labelPosition="after"
[required]="isRequired"
[formControlName]="controlName"
(change)="toggleClick.emit($event)"
[tabIndex]="tabNumber"
[disabled]="isDisabled"
[matTooltip]="toolTip"
>{{toggleText}}</mat-slide-toggle>

export class CustomSlideToggleComponent {

  @Input() public toolTip: string = '';
  @Input() public isDisabled: boolean = false;
  @Input() public isRequired: boolean = false;
  @Input() public toggleText: string = '';
  @Input() public tabNumber: number = null;
  @Input() public toggleId: string;
  @Input() public controlName: string = '';

  @Output() public readonly toggleClick = new EventEmitter<MatSlideToggleChange>();

  public constructor() { }
}

I've tried to implement it this way using this html:
<custom-slide-toggle
        [toggleId]="'enable_user'"
        [controlName]="'enableUser'"
        [toggleClick]="onEnableUser(toggleEvent)"
        [tabNumber]="5"
        [toggleText]="'A custom slide toggle'"
      ></custom-slide-toggle>

and this in the typescript:
public toggleEvent: MatSlideToggleChange;

public onEnableUser($event: MatSlideToggleChange) {
   console.log('toggle was clicked' + $event);
}

When I click on the slide toggle $event always comes back 'undefined'. How can I use different click functions with this custom component?

A: I see two potential issues with your usage of the custom-slide-toggle:

*

*toggleClick should be binded with (toggleClick) as it's only an Output:

        (toggleClick)="onEnableUser(toggleEvent)"

*toggleEvent is not the event variable, it should be $event:

        (toggleClick)="onEnableUser($event)"

A: Event binding is with parentheses so i think that
(toggleClick)="onEnableUser(toggleEvent)"

should work.


text:
Q: Aptana project types not available I have recently installed the Aptana plugin for Eclipse as I wish to learn Ruby and Ruby on Rails, it doesn't seem to have changed anything. Usually when I install a plugin of the sort, there will be new project types under the "New Project" menu, but none appeared. I checked tutorials online and they suggest that there should be new project types as seen in the image below, taken from a tutorial.

Instead, I see the same options I did before.

I wondered if the plugin didn't install, but when I try to install it again, It says it's already installed. I am using Eclipse Juno Service Release 2 with a 64-bit Windows 7 operating system and the version of the plugin from the URL given on the Aptana website (http://download.aptana.com/studio3/plugin/install). Any help would be much appreciated.

A: I don't know why that's happening. Here's a suggestion for how to get around it.
You might be better off installing and running the standalone Aptana Studio product. It would be a separate installation on your desktop, and thus wouldn't have the same settings as any Eclipse installation you already had, and would be more space on your hard drive. But probably there isn't much you would share between Ruby/Rails development and other development, and it's not that much space.
I've done it both ways - installed Aptana into an Eclipse I've already got, and installed the standalone version - and now I would only do standalone.

A: I don't know what was wrong in the first place, but after I installed the Aptana plugin, I installed the PyDev plugin. I think this removed the Aptana plugin because of conflicting dependencies (I don't know why it wouldn't tell me, though). I tried installing the Aptana plugin again and it told me there was a conflicting dependency with the PyDev plugin, so I uninstalled it and reinstalled the Aptana plugin. It works now.


text:
Q: Разбить строку с использованием Regex я пытаюсь разбить строку через пробелы, но не разбивать всё что заключено в скобки ()
Данный код работает нормально для (a + b) * c * (x - y) ==>
(a + b),
*,
c,
*,
(x - y)
Regex.Matches(expression, @"[\(].+?[\)]|[^ ]+")
                                        .Cast<Match>()
                                        .Select(m => m.Value)
                                        .ToArray();

Но этот пример разбивается не так как я ожидаю...
(a * (x - y)) * c

Получается: (a * (x - y), ), *, с
Ожидается: (a * (x - y)), *, с
Я уже второй день ломаю голову, что бы правильно разбить, но никак не получается. Я думаю надо сделать что бы закрывающая скобка [\)] засчитывалась только если после нее нету такой же скобки без открывающей перед ней :-)
Но вот не могу написать такое выражение...

A: Используйте "balanced construct":
Regex.Matches(s, @"(?x)
      \(                    # открывающая круглая скобка
      (?>                   # начало группы, которая находит...
         [^()]+|            # 1+ символов, отличных от круглых скобок
         (?<o>)\(|          # открывающая круглая скобка (пустая строка добавляется в стек группы `o`)
         (?<-o>)\)          # закрывающая круглая скобка (пустая строка удаляется из стека группы `o`)
       )*                   #  повторить 0 и более раз
       (?(o)(?!))           # если в стеке группы `o` остались значения, отменить совпадение
      \)                    # закрывающая круглая скобка
     |                      # или
      [^\s()]+              # 1+ символов, отличных от пробельных и круглых скобок
     ")
    .Cast<Match>()
    .Select(m => m.Value)
    .ToArray();

См. демо регулярного выражения, а здесь демо C#.
Подробности

*

*\( - открывающая круглая скобка

*(?> - начало группы, которая находит...

*

*[^()]+| - 1+ символов, отличных от круглых скобок

*(?<o>)\(| - открывающая круглая скобка (пустая строка добавляется в стек группы o)

*(?<-o>)\) - закрывающая круглая скобка (пустая строка удаляется из стека группы o)

*)* - повторить 0 и более раз

*(?(o)(?!)) - если в стеке группы o остались значения, отменить совпадение

*\) - закрывающая круглая скобка

*| - или

*[^\s()]+ - 1+ символов, отличных от пробельных и круглых скобок.

A: Если задача просто разбить строку по пробелам, то можно попробовать и без регулярок это сделать. Например так
IEnumerable<string> Split(string input)
{
    var counter = 0;
    var startPos = 0;
    List<string> parts = new List<string>();

    for (var i = 0; i < input.Length; i++)
    {
        var c = input[i];
        if (c == ' ' && counter == 0)
        {
            var len = i - startPos;
            if (len > 0)
            {
                parts.Add(input.Substring(startPos, len));
            }
            startPos = i+1;
        }
        if (c == '(') counter++;
        if (c == ')') counter--;
    }

    var lastInd = input.Length;
    var lastLen = lastInd - startPos;
    if (lastLen > 0) parts.Add(input.Substring(startPos, lastLen ));

    return parts;
}

Да, кода больше, но имхо он понятней, чем регулярка, да и работает в теории побыстрее.
Вариант с ленивым вычислением. Пользоваться можно также, как первым вариантом.
IEnumerable<string> Split(string input)
{
    var counter = 0;
    var startPos = 0;

    for (var i = 0; i < input.Length; i++)
    {
        var c = input[i];
        if (c == ' ' && counter == 0)
        {
            var len = i - startPos;
            if (len > 0)
            {
                yield return input.Substring(startPos, len);
            }
            startPos = i+1;
        }
        if (c == '(') counter++;
        if (c == ')') counter--;
    }

    var lastInd = input.Length;
    var lastLen = lastInd - startPos;
    if (lastLen > 0) yield return input.Substring(startPos, lastLen);
}


text:
Q: pdflush hanging on Amazon EBS drives when using multi-GB files - any workaround? When I run gunzip on a 1.7GB file (which generates an 8GB file) on an EBS volume, pdflush freezes after gunzip runs and the CPU hangs indefinitely at 100% IO Wait. Here's the output from 'ps aux | grep pdflush'. Note the D status
root 87 0.0 0.0 0 0 ? D 06:18 0:00 pdflush
root 88 0.0 0.0 0 0 ? D 06:18 0:00 pdflush
The only solution is to kill the pdflush processes. The processes don't die immediately either.
This problem is repeatable and happens with new instances. I'm running 2xlarge instances and I have way more RAM free than is being used (i.e. /proc/meminfo shows 20+GB MemFree)
Has anyone found a workaround to this problem in the past?
Thanks for any thoughts.
Robert

A: Are you using a single ebs volume ? You can try using a striped set of 4. This will give you better io performance.


text:
Q: One-Click application moving from Windows Forms to WPF I have a Windows Forms application that I recently re-wrote in WPF, and I need to release it to my end users. I'd like to be able to have the users go to the ClickOnce install point for the WPF application and have their Windows Forms application removed, so they don't have both on their machine.
What's the best way (read: easiest for users) of accomplishing this?
I have thought about creating an prerequisite command line to detect the old version and uninstall, but I would like to avoid having to write something like that where it only gets run once.

A: I think you actually SHOULD be able to deploy the WPF version as a new version of the Windows Forms application.
What version of the .NET Framework do each of the applications target?
Is the assembly name on both projects the same, and is the installation URL the same? (For ClickOnce, it has nothing to do with the projectGUID.)

A: I haven't tried it, but could you make your WPF app directly replace your WinForms app? If you publish to the same folder, copy the right GUID's from the old project to the new project, it might just install seamlessly.
That won't remove the old versions, but every update to a ClickOnce app leaves the old versions in place.
Alternatively, can you transform your existing WinForms project into a WPF project? Is it just a different set of assembly references? I've never written a WPF app, so forgive me if this is obviously wrong.

A: Why not simply give the new WPF application the same <ProjectGuid>, <PublishUrl>, etc and a higher major version number?
ClickOnce won't even be aware you switched from WinForms to WPF technology.
Normal ClickOnce version update functionality will automatically replace the old code with the new the next time the application is updated (which can be set to happen automatically if desired).


text:
Q: Multiple tablix for report i have the following scenario i am trying to simplify using Visual Studio and Microsoft BI Stack (SSRS).
I have a Dataset as follows.
Year    Employee    Sales
1       A           5,000,000
2       A           7,500,000
3       A           6,500,000
1       B           3,500,000
2       B           5,000,000
3       B           8,000,000
1       C           5,750,000
2       C           7,500,000
3       C           6,500,000
1       D           4,500,000
2       D           5,500,000
3       D           6,100,000

I am trying to create a report whereby, a single report would span 3 Tablix inside report body when run to display as follows.
Year 1
Year    Employee    Sales
1       A           5,000,000
1       B           3,500,000
1       C           5,750,000
1       D           4,500,000

Year 2
Year    Employee    Sales
2       A           7,500,000
2       B           5,000,000
2       C           7,500,000
2       D           5,500,000

Year 3
Year    Employee    Sales
3       A           6,500,000
3       B           8,000,000
3       C           6,500,000
3       D           6,100,000

Now i know i could replicate the Tablix 3 times in the report body, but that would be a bad idea when it comes to maintaining this report.
In the effort to avoid repeating myself, is there a way to loop the Tablix (N Times) in SSRS where condition would be the Year column (values 1, 2, 3.....)?

A: What you want to do is to NEST two tables.
First, create your table that gives you all the results like you want.
Then create a second table with one column and one row and Group it by your Year field.
Place your first table in the second table's so that it repeats for each year.

A: Following are the steps :-

*

*Insert a List. Group it by the Year.

*Put your tablix inside the list.

This should do it.


text:
Q: is a good idea to use spring repository inside component? I was wondering, from the architectural point of view, if there is a good idea to use a Spring @Repository inside a Spring @Component?
I believe that in a service oriented architecture the DAOs must be accessed only through a @Service.

A: I believe it is valid to call the DAO from the @Component class. I always follow this when creating/writing an application.
DAO or Repository layers are the lowest layer and are responsible for all logic related to persisting/retrieving to/from a Data Store. Repositories or DAOs may also consume other repositories but should not consume resources in higher level like Services or Controllers.
Service layer is above Repository layer and encapsulates the business logic of the application. It may consume Repositories and other Services too. Like Repositories, they do not consume higher level resources.
Controller layer is above Service and Repository layers. It may consume Services but never consumes Repositories directly and other controllers. It should only control the user interface using the business layer aka Service.


text:
Q: Prove $m \text{ mod } n < m/2$ How do I prove $m \text{ mod } n < m/2$. Seems true for values I tested but how do I prove it in general?

A: It's not true for general $m$ and $n$. Take $m=1$ and $n=2$.
More seriously, clearly it is true if $m > 2n$, so you only need to concern yourself with $m \leq 2n$. If $m < n$ then it is clearly false, so the only interesting case is $n \leq m <2n$. But then $m/2 < n$ so $m/2 = m - m/2 > m-n = m$ mod $n$.
So $m$ mod $n < m/2$ if and only if $m \geq n$.

A: It's not true. 2 mod 3 = 2 > 2/2.

A: I would say the values in the question are ill-defined, as $m \mod n$ is the set $\{r\cdot n + m |r \in \Bbb Z\}$, and no such set is less than any specific number.


text:
Q: Ajax POST FormData not working in https(Secured Link) We are trying upload pictures to our server. Its working fine in http sites, but not in https sites.
It throws following: Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Here is the code which is used for ajax
Java Script
function fnTest(){
var iTaskID = $("#hdnCurTaskID").val();
var files = $("#TaskImg")[0].files;
if (files.length > 0) {
    if (files.length > 3) {
        alert("Maximum 3 files Allowed");
        return;
    }
    if (typeof FormData == "undefined") {
        var postdata = [];
        for (var i = 0; i < files.length; i++) {
            postdata.push("UploadedFile", files[i]);
        }
        postdata.push("TaskID", iTaskID);
    }
    else {
        var postdata = new FormData();
        for (var i = 0; i < files.length; i++) {
            postdata.append("UploadedFile", files[i]);
        }
        postdata.append("TaskID", iTaskID);
    }
    $.ajax({
        type: "POST",
        url: "TaskStatus.asmx/UploadExecTaskPic",
        contentType: false,
        processData: false,
        async: false,
        responseType: "json",
        data: postdata,
        success: function (result) {
            var MaxFile = GetSessionValuecurrent(iTaskID);
            if (MaxFile == "MaxFile") {
                alert("Maximum 3 Files only Allowed to Upload");
            }
            else {

                $("#TaskImg").val("");
                $("#TaskImg").replaceWith($("#TaskImg").clone());
                DoCloseFileSelector();
                DoShowTaskImages(iTaskID, '');
            }
        },
        error: function () {
            alert("Upload Error");
        }
    });
}
}

Web Method:
[WebMethod(EnableSession = true)]
public string UploadExecTaskPic()
{
    string sResult = string.Empty;
    return sResult;
}

A: I came across this information in a google search
FIX Request format is unrecognized for URL unexpectedly ending in

Add the following to web.config since GET and POST are disabled by default in ASP.NET 2.0 and greater:

<configuration>
    <system.web>
    <webServices>
        <protocols>
            <add name="HttpGet"/>
            <add name="HttpPost"/>
        </protocols>
    </webServices>
    </system.web>
</configuration>


text:
Q: WPF Storyboarded Animation Freezes If Clicked Too Quickly I am currently having an annoying issue with the simple XAML code below.  The animation does fire correctly, and will always fire correctly if I click the button after the animation has completed.  If I click quickly a few times, the animation will freeze, and the animation will never run again.
Thanks so much for the help!
<!-- Admin Login Button /-->
    <ToggleButton Name="LoginButton" IsChecked="{Binding ElementName=LoginPopup, Path=IsOpen, Mode=TwoWay}" HorizontalAlignment="Right" Margin="0,35,32.334,0" VerticalAlignment="Top" Width="97" Height="77" BorderThickness="0" Grid.Column="1" Grid.ColumnSpan="2">
        <ToggleButton.Background>
            <ImageBrush ImageSource="/Resources/Images;component/Resources/titleAboutIcon.png"/>
        </ToggleButton.Background>
        <!--  <Frame x:Name="AdminFrame" Height="77" Width="97"/> /-->
        <ToggleButton.RenderTransform>
            <ScaleTransform x:Name="Buttonscale" ScaleX="1" ScaleY="1" CenterX="0" CenterY="{Binding ElementName=LoginButton, Path=ActualHeight}" />
        </ToggleButton.RenderTransform>
        <ToggleButton.Triggers>
            <EventTrigger RoutedEvent="Button.Click">
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetName="Buttonscale" Storyboard.TargetProperty="(ScaleTransform.ScaleX)" To="1.25" Duration="0:0:0.25" AutoReverse="True"/>
                        <DoubleAnimation Storyboard.TargetName="Buttonscale" Storyboard.TargetProperty="(ScaleTransform.ScaleY)" To="1.25" Duration="0:0:0.25" AutoReverse="True"/>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </ToggleButton.Triggers>
    </ToggleButton>
    <!-- Admin Login Button /-->

A: You can add FillBehavior="Stop" to your Storyboard so it will stop and reset animated properties values instead of freezing them (HoldEnd is the default value of FillBehavior, so it won't change values back to their default).
From MSDN:

Set an animations FillBehavior property to HoldEnd when you want the animation to hold its value after it reaches the end of its active period. An animation that has reached the end of its active period that has a FillBehavior setting of HoldEnd is said to be in its fill period. When you don't want an animation to hold its value after it reaches the end of its active period, set its
  FillBehavior property to Stop.

https://msdn.microsoft.com/en-us/library/system.windows.media.animation.timeline.fillbehavior(v=vs.110).aspx


text:
Q: call an sql function by name returned by select I would like to find out how to call a function the name of which is returned from a select query. So let's say, I have a select query:
SELECT function_name FROM functions WHERE id=1;

Now let's say, the returned functions name is fce1
and now I want to execute:
SELECT fce1(parameters);

Now my initial idea would be:
SELECT CONCAT(SELECT function_name FROM functions WHERE id=1;, "(params)");

I am quite certain that the idea is wrong. But I was trying to figure that out some time ago and I remember that at least MS SQL was able to achieve my goal and also POSTGRESQL. Anyway, neither do I remember or am I able to find how to do it. Ideas would be appreciated.

A: DECLARE @func NVARCHAR(50);

SELECT @func = function_name FROM functions WHERE id=1;

EXEC ('select ' + @func + '()')

A: Assuming all functions return the same data type, you could build a wrapper function in Postgres that you pass the ID of the function to be called:
create or replace function call_func(p_id integer)
  returns integer
as
$$
declare
  l_result integer;
  l_name   text;
  l_params text;
begin
  select function_name, parameters
    into l_name, l_params
  from functions
  where id = p_id;

  execute 'select '||l_name||'('||l_params||')'
    into l_result;

  return l_result;
end;
$$
language plpgsql;

Note: the above is just an example.
It's wide open to SQL injection and does not do any error checking or sanitizing the parameters! But it might point you into the right direction.
Assume you have the functions:
create or replace function foo(p_arg_1 integer, p_arg_2 integer)
  returns integer
as
$$
  select p_arg_1 + p_arg_2;
$$
language sql;

create or replace function bar(p_value integer)
  returns integer
as
$$
  select p_value * 4;
$$
language sql;

And the functions table looks like this:
id | function_name | parameters
---+---------------+-----------
 1 | fce           | 42
 2 | foo           | 1,2

You can then do
select call_func(2);

or
select call_func(1);

But again: this will only work if all functions return the same result. e.g. scalar functions returning a single value, or set returning functions returning the same table definition.


text:
Q: Calling Method represented by string I am being passed a string similar to below.
"Users_Controller.login"

"Users_Controller" represents the object below.
And "login" a method within it.
var Users_Controller = ( function () {
return{

  login : function(vo, callback)
   {......}

 }
 })();

Given only the string as a pointer,is it possible call the method?

A: You can use this function:
function getPropertyFromString(str, start) {
    str = str.split(".");
    var prop = start || window;
    for (var i = 0; i < str.length; i++) {
        if(prop == undefined)
          return prop;
        else
          prop = prop[str[i]];
    }
    return prop;
}
getPropertyFromString("Users_Controller.login");

However, this does not allow bracket syntax.

A: Something like this?
var Users_Controller = (function () {
    return {

        login: function (name) {
            alert("hello " + name);
        },
        logout: function (name) { alert("goodbye "+name); }

    }
})();

var methods = {};

for (method in Users_Controller) {
    methods["Users_Controller." + method] = Users_Controller[method];
}

methods["Users_Controller.login"]('john');
methods["Users_Controller.logout"]('john');


text:
Q: Java exporting images with runnable jar getClass().getClassLoader().getResource("path") returns null I am trying to export an image inside my runnable jar. After some research i have come across this method:
ImageIO.read(getClass().getClassLoader().getResource("image path"));

After following several response and looking at the API, i have attempted this myself. My current directory set up is as follows:

This is my code:
cherryImg = ImageIO.read(getClass().getClassLoader().getResource("/res/cherry.png"));

which is being called from the Snake.java source file.
This is the error message:
Exception in thread "main" java.lang.IllegalArgumentException: input == null!
    at javax.imageio.ImageIO.read(Unknown Source)
    at cje.chris.edwards.snake.game.Snake.<init>(Snake.java:51)
    at cje.chris.edwards.snake.game.Snake.main(Snake.java:156)

Snake.java:51 is the line of code posted above. I understand this is because it cannot find the resource, what am i doing wrong? I have added the res folder to my build path.
I have also tried:
cherryImg = ImageIO.read(getClass().getClassLoader().getResource("res/cherry.png"));

This produces the same error message.
Answer:
cherryImg = ImageIO.read(getClass().getClassLoader().getResource("cherry.png"));

Thanks.

A: I think your problem is the leading "/"
"/res/cherry.png"

Will make it an absolute path (from your root of your drive) not a relative path from your starting from the root of your jar
Making it "res/cherry.png" should work


text:
Q: PDFKit how to erase Ink annotation I have followed some examples on the internet and I was able to draw Ink annotation using PDFKit . the problem now is that if I toggle button and choose eraser, how can I erase the annotation that I draw . I searched on the internet and tried some examples but nothing worked .
here is the code I'm using
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        if let touch = touches.first,
            let numberOfTouches = event?.allTouches?.count,
            numberOfTouches == 1 {
            state = .began

            let position = touch.location(in: pdfView)

            let convertedPoint = pdfView.convert(position, to: pdfView.currentPage!)
            lastPoint = convertedPoint

        } else {
            state = .failed
        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        state = .changed

        guard let position = touches.first?.location(in: pdfView) else { return }
        let convertedPoint = pdfView.convert(position, to: pdfView.currentPage!)

        let path = UIBezierPath()
        path.move(to: lastPoint)
        path.addLine(to: convertedPoint)
        lastPoint = convertedPoint
        let page = pdfView.page(for: position, nearest: true)!
        if currentAnnotation == nil {
            let border = PDFBorder()
            border.lineWidth = width
            border.style = style
            currentPDFPage = pdfView.page(for: position, nearest: true)!

            let rect = page.bounds(for: .mediaBox)

            currentAnnotation = PDFAnnotation(bounds: rect, forType: .ink, withProperties: [
                PDFAnnotationKey.border: border,
                PDFAnnotationKey.color: color,
                PDFAnnotationKey.interiorColor: UIColor.red,
                ])
            if inkType == .eraser {
                // TO DO
            }else {
                pdfView.currentPage?.addAnnotation(currentAnnotation!)
            }

        }

        currentAnnotation!.add(path)

   }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let position = touches.first?.location(in: pdfView) else {
            state = .ended
            return
        }

        let convertedPoint = pdfView.convert(position, to: pdfView.currentPage!)

        let path = UIBezierPath()
        path.move(to: lastPoint)
        path.addLine(to: convertedPoint)
        currentPDFPage = pdfView.page(for: position, nearest: true)!

        if inkType == .eraser {
            // TO DO
        }

        if currentAnnotation != nil {
            self.registerUndo(annotations: [self.currentAnnotation])
        }

        currentAnnotation?.add(path)
        currentAnnotation = nil

        state = .ended
    }


text:
Q: Doctrine OneToMany Relation based on entityUid field i'me working on a project with alot of the entities have string uid LIKE ENTITY.XXXX.
I'm seaching a way to relate some entities using doctrine annotations.
In particular the entity Media that contains all the links to the media files, to other entities becouse the relations between Media and the other entities like Document, Building  etc is based on a field entityUid inside the Media entity, so the field entityUid is promiscuous becouse can contain the uid form different other entities.
I realize that cannot do a reverse mapping becouse i cant populate correctoy the reversed entity becouse is promiscuous, what i'm trying to do is a direct relation between for example Document 1:n Media based on Document.uid 1:n Media.entityUid and Bulding 1:n Media based on Document.uid 1:n Media.entityUid.
I write the entities:

class Media(){
   /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     *
     */
  private $id;
  /**
    * @var string
    * @ORM\Column(name="entityUid", type="string", nullable=false)
    */
  private $entityUid;
  /**
    * @var string
    *
    * @ORM\Column(name="link", type="string", nullable=true)
    */
  private $link;
  ... other stuff.
}

class Document(){
  /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     *
     */
  private $id;
  /**
    *@var Media[]
    *
    */
  private $medias;

  /**
    * @var string
    * @ORM\Column(name="uid", type="string", nullable=false)
    */
   protected $uid;

  ... other stuff
}

class Building(){
  /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     *
     */
  private $id;
  /**
    *@var Media[]
    *
    */
  private $medias;

  /**
    * @var string
    * @ORM\Column(name="uid", type="string", nullable=false)
    */
   protected $uid;

  ... other stuff
}

The problem is on the definition on the relation OneToMany, based not form the id fiels but uid fileds.
I was not able to find a correct annotation to create an unidirection OneToMany relation without creating a support table like a ManyToMany document_media , building_media, that would make useless the entities uids.
Tx for your time.


text:
Q: Combine all arrays in object into one array. I'm developing an extension for Google chrome and I'd like to combine all arrays in a certain object into one array instead of them being split. So right now, my console o
chrome.storage.sync.get(null, function(all) {
// this returns everything in chrome's storage.
}

It looks something like this in my console:

However, I'd like it to actually have all the arraries combined into one, as such:
Object
feed_0: Array[364]
I've tried this:
    chrome.storage.sync.get(null, function(all) {
  var test = {}; test = all;
  delete test['currently.settings'];

console.log(test);

var alpha = [];

var result = 0;
  for(var prop in test) {
    if (test.hasOwnProperty(prop)) {
       var second = alpha.concat(prop);

      console.log(second);
    // or Object.prototype.hasOwnProperty.call(obj, prop)
      result++;
    }
  }

   });

But this returns this:

A: Here is how to get one array from the all object:
var test = Object.values(all).flat();

In older JavaScript versions, that do not support these functions, go for:
var test = Object.keys(all).reduce( (acc, a) => acc.concat(all[a]), [] );

To assign it to a feed_0 property, is of course not the difficulty:
test = { feed_0: test };

A: You can combine your feed_N arrays into one property using Object.keys and Array#reduce:

var data = {
  feed_0: [0, 1, 2],
  feed_1: [3, 4, 5],
  feed_2: [6, 7, 8],
  feed_3: [9, 10, 11]
}

data = Object.keys(data).reduce(function(result, k) {
  [].push.apply(result.feed_0, data[k])
  return result
}, { feed_0: [] })

console.log(data)


text:
Q: JSP Bean class atribute is invalid Имеется такой класс:
package jsp;

public class Person
{
  private String name;
  private int age;

  public Person()
  {}

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }
}

и имеется такой JSP файл:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <jsp:useBean id="person" scope="request" class="jsp.Person" type="jsp.Person"
    beanName="jsp.Person"/>
    <jsp:setProperty name="person" property="name" value="Test"/>
    <jsp:getProperty name="person" property="name"/>
</body>
</html>

при запуске сервера и перехода на данную JSP страницу получается ошибка:

The value for the useBean class attribute is invalid

используется Tomcat версии 9.0.7
Бьюсь над этим уже пару дней. Облазил и забугорный stackoverflow и русский. Ни создание конструктора по умолчанию, ничего другого не помогло. Надеюсь, вы сможете помочь мне.

A: Файл Person.class должен находиться в папке /WEB-INF/classes/jsp.

Для создания бина
<jsp:useBean id="person" class="jsp.Person" scope="request" />


text:
Q: Rotating an image around a reference point I'm trying to rotate the image around a reference point in Java using BufferedImage and AffineTransform, at first it seemed exactly what I needed, but it turns out it doesn't behave as expected. I need to do some rudimentary rotations, in multiples of 90, so I tried to do getQuadrantRotateInstance, but, if the reference point is at 0,0 then I get a RasterFormatException: Transformed height (0) is less than or equal to 0.
var rotation = switch (transform) {
    case TRANS_NONE -> 0;
    case TRANS_ROT90 -> 1;
    case TRANS_ROT180 -> 2;
    case TRANS_ROT270 -> 3;
    default -> throw new NotImplementedException();
};
var transform = AffineTransform.getQuadrantRotateInstance(rotation, referenceX, referenceY);
var operation = new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
var rotated = operation.filter(source, null);

By the looks of it the image gets rotated out of the canvas (into negative coordinates), resulting in exception above.
What would be the proper solution to create a rotated variant of the image without cropping or rotating around a center point like existing solutions do?

A: Rotating an image by an angle around the center point:
private BufferedImage rotateImage(BufferedImage buffImage, double angle) {
    double radian = Math.toRadians(angle);
    double sin = Math.abs(Math.sin(radian));
    double cos = Math.abs(Math.cos(radian));

    int width = buffImage.getWidth();
    int height = buffImage.getHeight();

    int nWidth = (int) Math.floor((double) width * cos + (double) height * sin);
    int nHeight = (int) Math.floor((double) height * cos + (double) width * sin);

    BufferedImage rotatedImage = new BufferedImage(nWidth, nHeight, BufferedImage.TYPE_INT_ARGB);

    Graphics2D graphics = rotatedImage.createGraphics();

    graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    graphics.translate((nWidth - width) / 2, (nHeight - height) / 2);
    // This is the rotation around the center point - change this line
    graphics.rotate(radian, (double) (width / 2), (double) (height / 2));
    graphics.drawImage(buffImage, 0, 0, null);
    graphics.dispose();

    return rotatedImage;
}

To change the origin point of the rotation see javadoc of the method rotate.

Source: Creating simple captcha.


text:
Q: How to read files in Chrome devtools Sources tab programmatically? I do this manually a lot so I want to automate the process. Basically I always have to open up Chrome DevTools, go to Sources tab, then find the file I'm looking for and copy a particular value from it.
Is there any way to do this using code? I'm trying to retrieve a value from external sources loaded by the website.

A: I can't answer for sure without knowing what type of value you're trying to retrieve, but how about a snippet?


text:
Q: Spark lazy loading not working I am learning Spark. Below is the file content I created in HUE.
This is a first line
Spark, Spark, Spark, Spark, Spark
HadoopExam, HadoopExam, HadoopExam
Google.com, HadoopExam

I create a RDD lines using lambda approach.
val Lines = line.filter(a => a.contains("HadoopExam"))

I then used count() and first() functions got results as 2 and HadoopExam, HadoopExam, HadoopExam respectively.
Now I modified the file as below.
    Google.comHadoopExam
    This is a first line
    Spark, Spark, Spark, Spark, Spark
    HadoopExam, HadoopExam, HadoopExam
    Google.com, HadoopExam
    HadoopExam

I didnot reload the RDD Lines.
However when I call functions count , the count shown is 3.
The first line is considred but the last line is not considered.
Can someone explain this behaviour?


text:
Q: How do I using Mongo aggregation to get the total "page views" for each group of days I have tried for a few days now to come up with a working aggregate but I'm just not getting it.
I have a collection that looks similar to the following.
_id: ObjectId("52672ca368a56f481d000045"),
totalviews: 5,
views: [
  {date: ISODate("2013-10-23T01:55:47Z") },
  {date: ISODate("2013-10-23T01:55:50Z") },
  {date: ISODate("2013-10-23T23:31:08Z")},
  {etc.}
]

What I'm trying to do is get a total number of views for each day so I can display a list of dates (from "views") and the total for those days.
Can someone show me how this can be done?
Thank you
Edit - Below Code Works Correctly
Here is the php code for the solution provided in case it helps someone else:
$ops = array(
array('$unwind' => '$views'),
array('$project' => array('date'=>array(
    'day'=>array('$dayOfMonth'=>'$views.date'),
    'month'=>array('$month'=>'$views.date'),
    'year'=>array('$year'=>'$views.date'))
)),
array('$group'=>array('_id'=>'$date','views'=>array('$sum'=>1)))
);

$data = $collection->aggregate($ops);

A: This should do the trick.
db.foo.aggregate(
    {$unwind: "$views"},
    {$project: {date: {
        day: {$dayOfMonth: "$views.date"},
        month: {$month: "$views.date"},
        year: {$year: "$views.date"},
    }}},
    {$group: {_id: {id: "$_id", date: "$date"}, views: {$sum: 1}}}
 )

If you want total number of views per day for collection replace group phase with this one:
{$group: {_id: "$date", views: {$sum: 1}}}


text:
Q: Break statement is not in loop or switch statement? I am having trouble with my code, I have read other forums this site about this problem but they don't really relate to my situation. I am new to C++, I barely have about 3 weeks into the course. I do not know why my break statement isn't working, to me it is in the loop. What am I missing?
float a[60][7];
int row;
cout << "How many students would you like to grade?" << endl;

cin >> studentNum;

cout << "Enter grades for the first student" << endl;

row = 0;
n = studentNum - 2;

while (row < studentNum)
{
    a[row][0]=k;
    a[row][0] = row;
    cout << "Enter grade for test 1: ";
    cin >> a[row][1];
    cout << "Enter grade for test 2: ";
    cin >> a[row][2];
    cout << "Enter grade for test 3: ";
    cin >> a[row][3];
    cout << "Enter grade for test 4: ";
    cin >> a[row][4];

    a[row][5] = (a[row][1] + a[row][2] + a[row][3] + a[row][4]) / 4;
    a[row][6] = a[row][1] * 0.2 + a[row][2] * 0.3 + a[row][3] * 0.3 + a[row][4] * 0.2;

    row++;
}
if (row == n)
{
    cout << "Enter Grades for the last Student" << endl;
    cout << "Enter grade for test 1: ";
    cin >> a[row][1];
    cout << "Enter grade for test 2: ";
    cin >> a[row][2];
    cout << "Enter grade for test 3: ";
    cin >> a[row][3];
    cout << "Enter grade for test 4: ";
    cin >> a[row][4];
    break;
}
else
{
   cout << "Enter grades for the next student" << endl;
   row = row + 1;
}

cout << "Stdnt" << "\t" << "Grade1" << "\t" << "Grade2" << "\t" << "Grade3" << "\t" << "Grade4" << "\t" << "Avg1" << "\t" << "Avg2" << endl;
printarray(a, studentNum);

cin.get();
return 0;

A: Something like this?
float a[60][7];
int row = 0;

std::cout << "How many students would you like to grade?" << std::endl;
std::cin >> studentNum;

n = studentNum - 2;

std::cout << "Enter grades for the first student" << std::endl;
while (row <= n)
{
  a[row][0] = k;
  a[row][0] = row;
  std::cout << "Enter grade for test 1: ";
  std::cin >> a[row][1];
  std::cout << "Enter grade for test 2: ";
  std::cin >> a[row][2];
  std::cout << "Enter grade for test 3: ";
  std::cin >> a[row][3];
  std::cout << "Enter grade for test 4: ";
  std::cin >> a[row][4];

  a[row][5] = (a[row][1] + a[row][2] + a[row][3] + a[row][4]) / 4;
  a[row][6] = a[row][1] * 0.2 + a[row][2] * 0.3 + a[row][3] * 0.3 + a[row][4] * 0.2;

  if (row==n)
  {
    std::cout << "Enter Grades for the last Student" << std::endl;
    std::cout << "Enter grade for test 1: ";
    std::cin >> a[row][1];
    std::cout << "Enter grade for test 2: ";
    std::cin >> a[row][2];
    std::cout << "Enter grade for test 3: ";
    std::cin >> a[row][3];
    std::cout << "Enter grade for test 4: ";
    std::cin >> a[row][4];
  }
  else
  {
    std::cout << "Enter grades for the next student" << std::endl;
  }

  row++;
}

std::cout << "Student" << "\t" << "Grade1" << "\t" << "Grade2" << "\t" << "Grade3" << "\t" << "Grade4" << "\t" << "Avg1" << "\t" << "Avg2" << std::endl;
printarray(a, studentNum);

std::cin.get();
return 0;

P.S. edit with fixed while


text:
Q: JSOUP - doc cannot be resolved and doc cannot be resolved to a variable I'm attempting to implement a JSOUP query however I'm getting an error stating "doc cannot be resolved" and "doc cannot be resolved to a variable" I know I'll need to call doc before I can use it I'm just not sure how to do so yet - It's my first time building a parser with JSOUP - I'm sure it's pretty simple - I just need a quick pointer.
public class MainActivity extends Activity {

    TextView tv;
    String url = "http://microsoft.com";
String tr;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = (TextView) findViewById(R.id.TextView01);
        new MyTask().execute(url);
    }

    private class MyTask extends AsyncTask<String, Void, String> {
        ProgressDialog prog;
        String title = "";

        @Override
        protected void onPreExecute() {
            prog = new ProgressDialog(MainActivity.this);
            prog.setMessage("Loading....");
            prog.show();
        }

        @Override
        protected String doInBackground(String... params) {
             try {
                    doc = Jsoup.connect(params[0]).get();
                    Element tableElement = doc.select(".datagrid").first();

                    Elements tableRows = tableElement.select("tr");
                    for (Element row : tableRows) {
                        Elements cells = row.select("td");
                        if (cells.size() >0) {
                            System.out.println(cells.get(0).text()+"; "+cells.get(1).text()+"; "+cells.get(2).text()+"; "+cells.get(3).text());
                        }
                    }}   catch (IOException e) {
                e.printStackTrace();
            }
            return title;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            prog.dismiss();
            tv.setText(result);
        }
    }
}

A: You are trying to use a variable that has not been declared. Just as you have done with
TextView tv;

you will have to declare the variable doc.
Document doc;

Don't forget to import the following package org.jsoup.nodes.Document.


text:
Q: Open Source - ARIES implementation Does someone know an Open Source implementation of the ARIES method for transaction recovery? Seems to be rather easy to implement, but most probably like always the devil is in the details and a "stable" implementation would be great.
For instance are all transaction operations/updates cached at first and only written to persistent storage once the cache evicts entries or are they written immediately to persistent storage. Thus, is it basically usually ok, on a power failure if some entries haven't been written to persistent storage in the log to improve performance (or maybe issuing a NIO call)? I've read some literature but nothing about the implementations themselves. Nonetheless it seems nothing can control if all updates have been persisted in case of a system failure / crash. So basically how is it ensured that all updates from transactions after a crash are reapplied? I think this can never be ensured (just the ones in the log which have to be reapplied)? And to go back to the original question: Is someone aware of a "proven" working open source variant?

A: ARIES is just a basic idea to ensure atomicity and durability. You could refer to PostgreSQL and MySQL innodb, but those codes include lots of details, so that you will be get confuse.


text:
Q: put custom css in vue.js/webpack I am trying to link my css to my vue.js file. I was building this out without the webpack. So I had many style worked out.. However, when I decided to move it to a webpack none of my custom css is even calling. I did research that said to include the css in the index.html as a link so that is what I have done. Is there a better way to do this that I didn't see? Any help would be much appreciated. It is also worth mentioning that I tried to use Include in the App.vue as well as require as I had seen in other suggestions but both pulled up errors and refused to compile any of my files....
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="shortcut icon" href="<%= webpackConfig.output.publicPath %>favicon.ico">
    <link rel="stylesheet" type="text/css" href="../src/assets/css/main.css">
    <title>my-project</title>

      We're sorry but my-project doesn't work properly without JavaScript enabled. Please enable it to continue.

this is test script


text:
Q: How to read multiple worksheets from a single .csv file? I want to read multiple worksheets in a single .csv file using PHP. I have done it for one worksheet:
$file_handle = fopen("widgets.csv", "r");

while (!feof($file_handle) ) {
    $line_of_text = fgetcsv($file_handle, 1024);
    print $line_of_text[0] . $line_of_text[1]. $line_of_text[2] . "<BR>";
}

fclose($file_handle);

But how can I read multiple worksheets from the same .csv file?

A: There is no such thing as multiple sheets in .csv files.
This is something unique to .xls/.xlsx files.
.csv files contain only a single worksheet*.
* actually they don't contain any worksheets, since there is no concept of worksheets


text:
Q: No overload for method 'ToDictionary' takes 0 arguments Actually i should work, from my point of view, I don't know whats wrong,the problem is that itemand valuedo not have a ToDictionary().
Maybe you can take a look ?!
Method signature:
public static IDictionary<string, object> ListO(this object instance)
My Code:
 if (instance == null)
                throw new NullReferenceException();

            var result = instance as IDictionary<string, object>;
            if (result != null)
                return result;

            return instance.GetType()
                .GetProperties()
                .ToDictionary(x => x.Name, x =>
                {
                    object value = x.GetValue(instance);

                    if (value != null)
                    {
                        var valueType = value.GetType();

                        // Whe should manually check for string type because IsPrimitive will return false in case of string
                        if (valueType.IsPrimitive || valueType == typeof(string))
                        {

                            return value;
                        }
                        else if (valueType.GetInterfaces().Any(t => t == typeof(IEnumerable)))
                        {
                            List<object> elements = new List<object>();

                            foreach (var item in value as IEnumerable)
                            {
                                elements.Add(item.ToDictionary());//problem here
                            }

                            return elements;
                        }
                        else
                        {
                            return value.ToDictionary();//problem here
                        }

                    }
                    return null;
                });

I get :

No overload for method 'ToDictionary' takes 0 arguments

What did I wrong ?

A: elements.Add(item.ToDictionary(e => e.Key,e => e.Value))


text:
Q: Use the new Express Checkout view with Adaptive Payments I have a website that uses adaptive payments to act as the middle man between sellers and buyers, and I have been using the standard PayPal view for a while now that looks like this:

This view has always been fine for me, although it is pretty ugly.. but I've started noticing websites with checkout pages that look like this:

This checkout page looks way better, and I have searched everywhere to find out how to implement it into my adaptive payments api. Based off of what I've found it is only available on express checkouts.
Is there any way I could get my checkout page to look like this without having to rework the whole PayPal API for my site?

A: Unfortunately, as of now, the checkout experience you're seeing with Adaptive is all you're going to get.  The Express Checkout experience is indeed much better, and it always has been.  I've always recommended to stick with EC as much as possible.
There's really nothing you can do in Adaptive that you can't do in EC, it's just a different series of steps to get it done.


text:
Q: Php mysql обернуть массив mysql_fetch_array $q=mysql_query("SELECT * FROM chat where limit 2");  //пример, записей на много больше
while($row=mysql_fetch_array($q)){
         echo '
'.$row['msg'].$row['login'].'
';
}

Записи

msg1,msg2,msg3,msg4

Как сделать, чтобы вывело в таком порядке? Именно msg3, потом msg4. Пробовал order by id desc и array_reverse, но не помогло.
A: Вот теперь уже ясно
Вариант 1
$res=mysql_query("SELECT count(id) FROM `chat`");
$row=mysql_fetch_row($res);
$total_rows=$row[0];
//Получили количество срок в таблице

$q=mysql_query("SELECT * FROM chat order by id asc limit".($total_rows-100).",100");
while($row=mysql_fetch_array($q)){
         echo '
'.$row['msg'].$row['login'].'
';
}

Вариант 2
$q=mysql_query("SELECT * FROM chat order by id desc limit 100");
$array_of_row = array()
while($row=mysql_fetch_array($q)){
  $array_of_row[] = $row;
}
 $array_of_row = array_reverse($array_of_row);

foreach ($array_of_row as $row) {
         echo '
'.$row['msg'].$row['login'].'
';
}

A: 'SELECT * FROM  mytable ORDER BY  mytable.id DESC LIMIT 0,10'
Вернет последние 10 записей из таблицы


text: Q: Xcode Project splash screen images location pointing to wrong location I moved my Xcode project to another mac . When i build it,  its throwing an error which shows previous location of splash screen images saying 'No such file or directory'. My splash screen images are in the Resources folder. Where should i change the path to the current location of splash images?


text:
Q: Java : Unable to change 'Content-Disposition' attribute in the Header for a response Below is the code:
Resource resource = getResource(request, requestUrl, userInfo, objectIdParam,
        rootFolderId, pathInfo, overrideCharset, isThumbnailResource);

// New line added to change Content-Disposition
response.setHeader( "Content-Disposition", "attachment;filename=" + pathInfo );

if (resource != null && resource.isServable()) {
    resource.serve(request, response);
}

As you can see, I have explicitly tried to change the 'Content-Disposition' to 'attachment' in the Header. But still, when I open an MS Office document, the HTTP Header data shows it as 'inline':
Content-Disposition: inline; filename="New%20Microsoft%20Office%20Word%20Document.docx"
Do you think I should do anything else to set this right?

A: I suspect that the resource.serve method call internally overwrites the header with its own value.
The javadoc says :

If the header had already been set, the new value overwrites the
  previous one. The containsHeader method can be used to test for the
  presence of a header before setting its value.


text:
Q: "variables in the training data missing in newdata" when predicting caretStack with svmRadial in R I am comparing a selection of ML methods to try and see which best fit my data.  For reproducibility, I have used the Occupancy data from UCI ML repository - available here:  http://archive.ics.uci.edu/ml/machine-learning-databases/00357/
on the last line, the predict function fails, with the following error:

Error in predict.randomForest(modelFit, newdata) :    variables in the
  training data missing in newdata

Here is my code:
rm(list=ls()) # remove all variables from workspace
set.seed(01010)
# data from http://archive.ics.uci.edu/ml/machine-learning-databases/00357/
a<-read_csv("~/Documents/PhD/Analysis/1. Risk Score/occupancy_data/datatest.csv")
b<-read_csv("~/Documents/PhD/Analysis/1. Risk Score/occupancy_data/datatest2.csv")
c<-read_csv("~/Documents/PhD/Analysis/1. Risk Score/occupancy_data/datatraining.csv")
data <- rbind(a,b,c)
data$class<-as.factor(data$class)
data <- data %>% select(-Temperature,-date)
levels(data$class) <- c("A", "B")    # classprob=true makes a variable for each class, with the class probs, but '0' and '1' aren't valid variable names
data_perm<-data[sample(nrow(data)),]
  train <- data_perm[1:floor(0.6*nrow(data_perm)),]
  xvalidate <- data_perm[(floor(0.6*nrow(data_perm))+1):floor(0.8*nrow(data_perm)),-ncol(data)]
  yvalidate <- data_perm[(floor(0.6*nrow(data_perm))+1):floor(0.8*nrow(data_perm)),ncol(data)]

### Ensemble: Setting up training controls
# for the weak trainers
control_stacking <- trainControl(method="repeatedcv",
                                 index = createFolds(train$class, 5),
                                 savePredictions = "final",
                                 classProb=TRUE)
# for the model combiner
stackControl <- trainControl(method="repeatedcv",
                             number=3,
                             repeats=2,
                             savePredictions=TRUE)

# define the hyperparameter list for each of the weak models to be included in the stack
models <- caretList(class~., data=train, trControl=control_stacking,
                    methodList=c('naive_bayes'),
                    tuneList=list(test=caretModelSpec(method='svmRadial')),
                    verbose=F)

temp <- caretStack(models, method="rf", metric="Accuracy", trControl=stackControl,verbose=F)
table(predict(temp, newdata=xvalidate))

Please note that without the tuneList line it works fine, and it also works for the methods gbm and rf.
Any help greatly appreciated!


text:
Q: When to use SQL Server or MySQL and when to manage data myself If I have a small database with fixed table layouts can I get any kind of performance benefit from handling the data myself rather than using a backend like MySQL? What are the benefits to using such a database backend?

A: Handling the data yourself usually means saving them in flat file and accessing them with custom code.  In this case they are easier to migrate and deploy, sometimes with better performance but not always, and performance should not be a concern for small data set much less the concern.
Using a database make it harder to corrupt the data when multiple users change the data at the same time, easier to filter/sort the data, easier for other programmers to maintain, more data tools to integrate with (charts, data forms, reports, etc.), data is less likely to be tampered by user, and your hosting company may backup database more frequently then files.

A: Databases provide ACID features (http://en.wikipedia.org/wiki/ACID) which are hard to deliver when rolling your own solution.
In addition, databases tend to scale to larger volumes of data with better performance characteristics.

A: Main benefit is automatic data handling - storing, retrieving, querying.
If you only have very small amount of simple data then you can of course just use INI files or Windows registry or just text file. This saves you from having to handle the MySQL installation and configuration and managing.

A: Theoretically, you could get more performance for specialized data structures.
On the other hand, you have more flexibility wrt data structures with a database.
You might want to look into the NoSQL options available.


text:
Q: While installing PyQt5-tools "Preparing metadata (project.toml) ... error" error occurs on Windows This is the command line that I used to install my PyQt5-tools from the pip
C:\WINDOWS\system32>pip install PyQt5-tools

After the command line is inserted into my command prompt
These messages and errors were returned
Collecting PyQt5-tools
  Using cached pyqt5_tools-5.15.4.3.2-py3-none-any.whl (29 kB)
  Using cached pyqt5_tools-5.15.4.3.1-py3-none-any.whl (28 kB)
  Using cached pyqt5_tools-5.15.4.3.0.3-py3-none-any.whl (28 kB)
  Using cached pyqt5_tools-5.15.3.3.2-py3-none-any.whl (29 kB)
Collecting pyqt5==5.15.3
  Using cached PyQt5-5.15.3.tar.gz (3.3 MB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... error
  ERROR: Command errored out with exit status 1:
   command: 'C:\Users\Legion\AppData\Local\Programs\Python\Python310\python.exe' 'C:\Users\Legion\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py' prepare_metadata_for_build_wheel 'C:\Users\Legion\AppData\Local\Temp\tmp8airx5rn'
       cwd: C:\Users\Legion\AppData\Local\Temp\pip-install-i87e0y1q\pyqt5_fde282425e8e4e089b79c62a0b021979
  Complete output (29 lines):
  Traceback (most recent call last):
    File "C:\Users\Legion\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 156, in prepare_metadata_for_build_wheel
      hook = backend.prepare_metadata_for_build_wheel
  AttributeError: module 'sipbuild.api' has no attribute 'prepare_metadata_for_build_wheel'

  During handling of the above exception, another exception occurred:

  Traceback (most recent call last):
    File "C:\Users\Legion\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 363, in <module>
      main()
    File "C:\Users\Legion\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 345, in main
      json_out['return_val'] = hook(**hook_input['kwargs'])
    File "C:\Users\Legion\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 160, in prepare_metadata_for_build_wheel
      whl_basename = backend.build_wheel(metadata_directory, config_settings)
    File "C:\Users\Legion\AppData\Local\Temp\pip-build-env-m1wogts2\overlay\Lib\site-packages\sipbuild\api.py", line 51, in build_wheel
      project = AbstractProject.bootstrap('pep517')
    File "C:\Users\Legion\AppData\Local\Temp\pip-build-env-m1wogts2\overlay\Lib\site-packages\sipbuild\abstract_project.py", line 83, in bootstrap
      project.setup(pyproject, tool, tool_description)
    File "C:\Users\Legion\AppData\Local\Temp\pip-build-env-m1wogts2\overlay\Lib\site-packages\sipbuild\project.py", line 587, in setup
      self.apply_user_defaults(tool)
    File "C:\Users\Legion\AppData\Local\Temp\pip-install-i87e0y1q\pyqt5_fde282425e8e4e089b79c62a0b021979\project.py", line 63, in apply_user_defaults
      super().apply_user_defaults(tool)
    File "C:\Users\Legion\AppData\Local\Temp\pip-build-env-m1wogts2\overlay\Lib\site-packages\pyqtbuild\project.py", line 70, in apply_user_defaults
      super().apply_user_defaults(tool)
    File "C:\Users\Legion\AppData\Local\Temp\pip-build-env-m1wogts2\overlay\Lib\site-packages\sipbuild\project.py", line 234, in apply_user_defaults
      self.builder.apply_user_defaults(tool)
    File "C:\Users\Legion\AppData\Local\Temp\pip-build-env-m1wogts2\overlay\Lib\site-packages\pyqtbuild\builder.py", line 67, in apply_user_defaults
      raise PyProjectOptionException('qmake',
  sipbuild.pyproject.PyProjectOptionException
  ----------------------------------------
WARNING: Discarding https://files.pythonhosted.org/packages/6e/86/d715e71771cece0e060f2ebab20f3ded067b08a0927dfb3143530cae8098/PyQt5-5.15.3.tar.gz#sha256=965ba50e7029b37f218a54ace24e87c77db3e5a9f0b83baeb21fb57b4154b838 (from https://pypi.org/simple/pyqt5/) (requires-python:>=3.6). Command errored out with exit status 1: 'C:\Users\Legion\AppData\Local\Programs\Python\Python310\python.exe' 'C:\Users\Legion\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py' prepare_metadata_for_build_wheel 'C:\Users\Legion\AppData\Local\Temp\tmp8airx5rn' Check the logs for full command output.

What should I do to fix the error stated above.
Thank you.


text:
Q: Using a via to strengthen surface mount connector on or near pad I am trying to design a board that has a surface mount connector.  I was shown a picture of an example board that has vias on the pads of the connector.  I don't believe the via is for connecting to a layer necessarily. Meaning I was told that they were used for strengthening the mechanical structure near the connector so that it would be more difficult to yank off when pulling and pushing in the plug.
Has anyone ever heard of this? I believe I have heard of putting a plugged via right next to a mechanical pad so that the board is stronger there.  But I'm not sure what the implications are for putting a via on the pad?  I've been searching the web and I can't find much.  Maybe I just don't know the proper terminology for this application.
So is there a standard for adding strength to surface mount connectors? Is putting a via on the pad a good or bad practice, other than expense? Does putting a via directly next to the pad help?

A: That's a new one on me!  There are other reasons for putting a via in the pad, but strengthening a connector is a new one.
The weakest part of an SMD pad is that the copper could delaminate from the fiberglass, and lift off the PCB itself.  Anything you could do to prevent that would help, including making the pad larger or putting a via in the pad itself.
But you have to be careful, since putting a via in the pad can cause other issues.  The first problem is that it might make the pads not flat enough, so a connector pin won't make good contact with the pad and thus not get soldered well.  The second issue is that the solder could get wicked down the via and leave nothing left for the connector pin.  This isn't a big issue if you are hand soldering, but can be a problem when doing it with automation.
Honestly, if connector strength is an issue then seriously consider going to a through-hole connector or some type of connector that gets strength from some other means.  Maybe a connector that gets bolted to the chassis itself (and stress on the PCB is minimal).  Or even a different connector entirely.


text:
Q: Node.js Canno't GET or POST users from route I am doing backend login and register project with Nodejs and Express but somehow I cannot login or register anymore or even fetch data from my usersRoute and I don't know why. I am lost..
My index.ts file:
import express from "express";
const https = require("https");
import cors from "cors";
import mongoose from "mongoose";
const app = express();

//import Routes
const usersRoute = require("./routes/users");

//Middleware
app.use(cors());
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

//Route middlewares
app.use("api/users", usersRoute);

//connect to db
mongoose
.connect("mongodb://localhost:27017/containerlab")
.then(() => {
  console.log("connected to database");
})
.catch(() => {
console.log("connection failed!");
});

const PORT = 5000;

app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});

My users.ts file
import express from "express";
const router = express.Router();
const User = require("../models/User");
 const {
registerValidation,
loginValidation,
} = require("../middleware/validation");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const secretKey = "f43g34gergeerg";
const verifyToken = require("../middleware/verifyToken");

//REGISTER user
router.post("/register", async (req, res) => {
//VALIDATE DATA from Joi, before register
const { error } = registerValidation(req.body);
if (error) return res.status(400).send(error.details[0].message);

//check if user is alredy in database
const emailExist = await User.findOne({ email: req.body.email });
if (emailExist) return res.status(400).send("Email already exists");

//encrypt password z bcryptjs modulom
const salt = await bcrypt.genSalt(10);
const hashPassword = await bcrypt.hash(req.body.password, salt);

//create new user
const user = new User({
email: req.body.email,
password: hashPassword,
});
try {
//save new user
const savedUser = await user.save();
//res.json(savedUser);
res.json({ user: user._id });
} catch (err) {
res.json({ message: err });
}
});

//LOGIN
router.post("/login", async (req, res) => {
 //VALIDATE DATA from Joi, before register
const { error } = loginValidation(req.body);
if (error) return res.status(400).send(error.details[0].message);

//check if email exists.. če NE obstaja mail dobiš da ne ustreza
const user = await User.findOne({ email: req.body.email });
if (!user) return res.status(400).send("Email doesn't exist");

const validPass = await bcrypt.compare(req.body.password, user.password);
if (!validPass) return res.status(400).send("Invalid password");

 //create and send a json web token
const token = jwt.sign({ _id: user._id }, secretKey, { expiresIn: "1h" });
res.header("auth-token", token).send(token);

res.send("Logged in!");
});

 //get users
router.get("/", async (req, res) => {
try {
  const users = await User.find();
res.json(users);
} catch (err) {
  res.json({ message: err });
}
});

module.exports = router;

And my verifyToken.ts middleware
const jwt = require("jsonwebtoken");
const secretKey = "f43g34gergeerg";

module.exports = (req: any, res: any, next: any) => {
const token = req.header("auth-token");
if (!token) return res.status(401).send("Access denied");

try {
  const verified = jwt.verify(token, secretKey);
  req.user = verified;
  next();
} catch (err) {
  res.status(400).send("Invalid token");
}
};

Somehow I can't fetch ANY data from users.ts (from usersRoute). Thank you for your help


text:
Q: Simplify the category of  finite abelian groups Consider the category $\mathsf{FinAb}$ of finite abelian groups. The structure theorem tells us that we can write down a skeleton for this category (a set of representatives for the isomorphism classes), which consists of the groups $\mathbb{Z}/n_1 \oplus \cdots \oplus  \mathbb{Z}/n_s$ with positive integers satisfying $n_1 | \cdots | n_s$. But this does not tell us anything about the morphisms between finite abelian groups.
Question. Can we improve the structure theorem in such a way that we find an explicit and easy to describe (this also includes the morphisms), countable category $\mathcal{C}$ together with an equivalence of categories $\mathcal{C} \cong \mathsf{FinAb}$?
Of course, "the full subcategory consisting of all $\mathbb{Z}/n_1 \oplus \cdots \oplus  \mathbb{Z}/n_s$" is no answer.
Variants:
a) There is an equivalence of categories $\mathsf{FinAb} \cong \mathsf{FinAb}^{op}$, given by $\hom(-,\mathbb{Q}/\mathbb{Z})$. We could require that $\mathcal{C}$ also comes equipped with an explicit anti-equivalence and that $\mathcal{C} \cong \mathsf{FinAb}$ is compatible.
b) Actually $\mathsf{FinAb}$ is a symmetric monoidal (abelian) category with the usual tensor product $\otimes_{\mathbb{Z}}$ (without unit). It would be great if we can set up an equivalence of symmetric monoidal categories $\mathcal{C} \cong \mathsf{FinAb}$; in particular $\mathcal{C}$ should be symmetric monoidal.
c) Probably everything may be reduced to $\mathsf{FinAb}_p$, the category of finite abelian $p$-groups, where $p$ is a prime number.
d) I am also happy with the category of finitely generated abelian groups. This is the initial finitely cocomplete symmetric monoidal abelian category.

A: As you notice in a comment, $FinAb$ is the direct sum of the $FinAb_p$, so we need only deal with the latter.
It should not be difficult to describe the full subcategory $S_p$ of $FinAb_p$ spanned by the set $\{\mathbb Z/p^r\mathbb Z:r\geq0\}$, which is a skeleton, by generators and relations as a category enriched in abelian groups. Once you do that, $FinAb_P$ is (equivalent to) what I would write $S^\oplus$, the category whose objects are finite sequences of objects of $S$ and whose morphisms are matrices.
The tensor product "comes" from the functor on $S$ which we can write $\min$ for hopefully obvious reasons. In the generating set for $S$ there will be one map $\alpha_k:\mathbb Z/p^r\mathbb Z\to \mathbb Z/p^{r+1}\mathbb Z$ and one map $\beta_r:\mathbb Z/p^r\mathbb Z\to\mathbb Z/p^{r-1}\mathbb Z$ (which can be taken to be the maps such that $1\mapsto p$ and $1\to 1$, respectively): the Pontryagin duality is induced by a functor on $S$ which is the identity on objects and on endomorphism rings, and which swaps the $\alpha$s and the $\beta$s.
Later. I think $S_p$ can be presented as the quotient of the $\mathbb Z$-span of the category generated by the graph $$
0\underset{\alpha_0}{\overset{\beta_1}\leftrightarrows}
1\underset{\alpha_1}{\overset{\beta_2}\leftrightarrows}
2\underset{\alpha_2}{\overset{\beta_3}\leftrightarrows}
3\underset{\alpha_3}{\overset{\beta_4}\leftrightarrows}
\cdots$$
modulo the relations $$p^rI_r=0, \qquad \alpha_{r-1}\beta_r=pI_r=\beta_{r+1}\alpha_r,$$ with $I_r$ the identity of the object $r$. I did not really check, but the tensor product seems to be the unique $\mathbb Z$-linear functor which acts like $\min$ on objects.


text:
Q: Finding out how many words are in the text input of JTextField I'm having the hardest time finding out how to code how many words there are in the input for the JTextField, I have a set a clear input button, and once I figure out how to find out how many words there are, I'll be able to clear that as well.  Thanks guys here's my code!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class CopyTextPanel extends JPanel
{
private JTextField input;
private JLabel output, inlabel, outlabel;
private JButton compute, clear;
private JPanel panel;

public CopyTextPanel()
{
    inlabel = new JLabel("Input Text:  ");
    outlabel = new JLabel("Text Statistics Results: ");
    input = new JTextField (" ", 25);
    output = new JLabel();
    compute = new JButton("Compute Statistics");
    compute.addActionListener (new ButtonListener());
    clear = new JButton("Clear Text");
    clear.addActionListener (new ButtonListener());
    panel = new JPanel();

    output.setPreferredSize (new Dimension(550, 30));
    panel.setPreferredSize (new Dimension(620, 100));
    panel.setBackground(Color.gray);
    panel.add(inlabel);
    panel.add(input);
    //panel.add(outlabel);
    //panel.add(output);
    panel.add(compute);
    panel.add(clear);
    panel.add(outlabel);
    panel.add(output);

    setPreferredSize (new Dimension(700, 150));
    setBackground(Color.cyan);
    add(panel);
}

private class ButtonListener implements ActionListener
{
    public void actionPerformed (ActionEvent event)
    {
        if (event.getSource()==compute)
        {
            {
                output.setText (input.getText());
            }
        }
        else
            input.setText("");
    }
}

A: For small piece of text like that one in an inputText you could use split to generate a string array with the string break into words and so read the array's length:
String test = "um dois      tres quatro        cinco ";
String [] splitted = test.trim().split("\\p{javaSpaceChar}{1,}");
System.out.println(splitted.length);

//output 5
So, for your input:
String inputText = input.getText();
String [] splitted = inputText.trim().split("\\p{javaSpaceChar}{1,}");
int numberOfWords = splitted.length;


text:
Q: Best way to write a simple boolean method with good C# syntax Hey all, I seem to have these types of methods everywhere.
The method below wants to do these simple tasks:

*

*Open a DB connection (IntLMPDB object)

*Read a simple record off a small DB table (the DB table is keyed with strings, because each string is the name of method, so I want just one row of each in the table), the rest of the row is a series of timestamps that tell me when things happned.

*If you can't find the record, then return an exception because there's nothing that can be done.

*If you find the record, look at the second date if it's just plain missing, then set to true because this is the first ever run.

*Or finally get to the meat, if the first date is greater than the second set to True because it's been updated and it's time to run. Else if not, set to False because there's no update yet.

So here's the code... What I am trying to do is pare this down to the best and quickest way to run through these checks. I am not concerned about like DB connection issues or anything like that.
    private static bool isLastIntervalNewerThanDB(string muiMethod)
    {
       using (var db = new IntLMPDB())
        {
            // Try to load a matching record.
            LastIntervalUpdated liRec = db.LastIntervalUpdateds.FirstOrDefault(rec => rec.method == muiMethod);
            // If it could not be loaded, exit because there's no way to determine if we should run.
             if (liRec == null) { throw new Exception(string.Format("Could NOT find LastIntervalUpdated record for muiMethod: {0}", muiMethod)); }
            else
            {
                // we have a valid interval record, so lets check that it has been updated since the last webPostTime.
                // put another way, there are three datetime values in the LastIntervalUpdated table. First is the
                // interval itself, second is the retrievalTime and third is the webPostTime. Whenever the MUI is
                // checked for a new interval if one is found then the code updates the retrievalTime to the current
                // instant in time. This tells us what the last interval this application found on its last run was.
                // The thrid value is the webPostTime, this time instant is only updated by this very method we're in
                // right here. We can use this logic: if the retrievalTime is greater than the webPostTime then there's
                // a newer interval that we haven't yet processed and inserted into the databse. So we should run the
                // method below and update ALL of the syncable values into the databse. Then we'll set the dbPostTime to
                // the current instance. As it goes, if this program then runs again before the interval is updated
                // then the dbPostTime will be greater than the retrieval time and we'll know to do nothig. Simple Right? :)

                // or check here includes a NULL check on dbPostTime because it's possible that dbPostTime is NULL,
                // in the example of the first time the system runs. It might have run a LastUpdate sync and not yet
                // done this method, so dbPostTime would be NULL. None of the other columns are allowed to be null.
                if (liRec.dbPostTime_EST == null || liRec.retrievalTime_EST > liRec.dbPostTime_EST)
                { return true; }
                else { return false; }
            }
       }
    }

A: private static bool isLastIntervalNewerThanDB(string muiMethod)
    {
       using (var db = new IntLMPDB())
        {
            // Try to load a matching record.
            LastIntervalUpdated liRec = db.LastIntervalUpdateds.FirstOrDefault(rec => rec.method == muiMethod);
            // If it could not be loaded, exit because there's no way to determine if we should run.
             if (liRec == null) {
                     throw new Exception(string.Format("Could NOT find LastIntervalUpdated record for muiMethod: {0}", muiMethod));
             }

                // we have a valid interval record, so lets check that it has been updated since the last webPostTime.
                // put another way, there are three datetime values in the LastIntervalUpdated table. First is the
                // interval itself, second is the retrievalTime and third is the webPostTime. Whenever the MUI is
                // checked for a new interval if one is found then the code updates the retrievalTime to the current
                // instant in time. This tells us what the last interval this application found on its last run was.
                // The thrid value is the webPostTime, this time instant is only updated by this very method we're in
                // right here. We can use this logic: if the retrievalTime is greater than the webPostTime then there's
                // a newer interval that we haven't yet processed and inserted into the databse. So we should run the
                // method below and update ALL of the syncable values into the databse. Then we'll set the dbPostTime to
                // the current instance. As it goes, if this program then runs again before the interval is updated
                // then the dbPostTime will be greater than the retrieval time and we'll know to do nothig. Simple Right? :)

                // or check here includes a NULL check on dbPostTime because it's possible that dbPostTime is NULL,
                // in the example of the first time the system runs. It might have run a LastUpdate sync and not yet
                // done this method, so dbPostTime would be NULL. None of the other columns are allowed to be null.

               return liRec.dbPostTime_EST == null
                      || liRec.retrievalTime_EST > liRec.dbPostTime_EST;

       }
    }

A: I think the logic is fine.  I would suggest that you do something like this to improve readability*:
private static bool isLastIntervalNewerThanDB(string muiMethod)
{
   using (var db = new IntLMPDB())
    {
        LastIntervalUpdated liRec
            = db.LastIntervalUpdateds
                    .FirstOrDefault(rec => rec.method == muiMethod);

        if (liRec == null)
        {
            throw new Exception(
                string.Format("Could NOT find LastIntervalUpdated record for muiMethod: {0}", muiMethod));
        }

        return liRec.dbPostTime_EST == null
            || liRec.retrievalTime_EST > liRec.dbPostTime_EST;
   }
}

*While readability is subjective I would argue that an else after if (liRec == null) only adds unnecessary nesting and the final conditional can be collapsed into a single expression. Also never underestimate a well-placed newline within a long expression - it can make all the difference betwee readable and unreadable code.

A: Keep the first if get rid of the first else and condense the last into a single line if/else
if (liRec == null) { throw new Exception(string.Format("Could NOT find LastIntervalUpdated record for muiMethod: {0}", muiMethod)); }

liRec.dbPostTime_EST == null || liRec.retrievalTime_EST > liRec.dbPostTime_EST ? return true : return false

A: I would move the boolean logic to the LastIntervalUpdated class:
public class LastIntervalUpdated
{
    public bool IsLastIntervalNewer
    {
        get
        {
            return this.dbPostTime_EST == null || this.retrievalTime_EST > this.dbPostTime_EST
        }
    }
    //other properties...
}

Then you can put the comment in closer to the definition. It also allows you to simplify the query to:
private static bool isLastIntervalNewerThanDB(string muiMethod)
{
    using (var db = new IntLMPDB())
    {
        LastIntervalUpdated liRec = db.LastIntervalUpdateds.FirstOrDefault(rec => rec.method == muiMethod);
        if(liRec == null) throw new Exception(string.Format("Could NOT find LastIntervalUpdated record for muiMethod: {0}", muiMethod))
        return liRec.IsLastIntervalNewer;
    }
}

I would also consider creating an exception type for failed lookups such as ObjectNotFoundException rather than throwing Exception directly.


text:
Q: Nuxt3 nuxi build ERROR [commonjs--resolver] Nuxt project info:

*

*Operating System: Windows_NT

*Node Version:     v16.18.0

*Nuxt Version:     3.0.0

*Nitro Version:    1.0.0

*Package Manager:  yarn@1.22.19

*Builder:          vite

*User Config:      buildModules, modules, http, strapi, i18n, runtimeConfig

*Runtime Modules:  @nuxtjs/tailwindcss@6.1.3, @nuxt/content@2.2.2, @pinia/nuxt@0.4.4, nuxt-icon@0.1.7, @nuxtjs/i18n@8.0.0-alpha.1

*Build Modules:    @vueuse/nuxt@9.5.0, @nuxtjs/strapi@1.6.3

When i run nuxi dev everything is Ok, but nuxi build occurred this error
> @ build E:\everyday-action\webprint
> nuxi build

Nuxi 3.0.0
Nuxt 3.0.0 with Nitro 1.0.0

 ERROR  [commonjs--resolver] Missing "./dist/pages/runtime" export in "nuxt" package                                                                                07:04:30

 ERROR  Missing "./dist/pages/runtime" export in "nuxt" package                                                                                07:04:30

  at bail (/E:/everyday-action/webprint/node_modules/.pnpm/vite@3.2.4_@types+node@14.18.33/node_modules/vite/dist/node/chunks/dep-67e7f8ab.js:32675:8)
  at resolve (/E:/everyday-action/webprint/node_modules/.pnpm/vite@3.2.4_@types+node@14.18.33/node_modules/vite/dist/node/chunks/dep-67e7f8ab.js:32752:10)
  at resolveExports (/E:/everyday-action/webprint/node_modules/.pnpm/vite@3.2.4_@types+node@14.18.33/node_modules/vite/dist/node/chunks/dep-67e7f8ab.js:34128:12)
  at resolveDeepImport (/E:/everyday-action/webprint/node_modules/.pnpm/vite@3.2.4_@types+node@14.18.33/node_modules/vite/dist/node/chunks/dep-67e7f8ab.js:34146:31)
  at tryNodeResolve (/E:/everyday-action/webprint/node_modules/.pnpm/vite@3.2.4_@types+node@14.18.33/node_modules/vite/dist/node/chunks/dep-67e7f8ab.js:33838:20)
  at Object.resolveId (/E:/everyday-action/webprint/node_modules/.pnpm/vite@3.2.4_@types+node@14.18.33/node_modules/vite/dist/node/chunks/dep-67e7f8ab.js:33598:28)
  at /E:/everyday-action/webprint/node_modules/.pnpm/rollup@2.79.1/node_modules/rollup/dist/es/shared/rollup.js:22748:40

 ELIFECYCLE  Command failed with exit code 1.

I tried to go to the debugger but I can't。


text:
Q: Add data into table with many to many relationship I just need to create a new Article with many to many relationship for tags. I have 3 tables:
 public class Article
{
    public int Id {get; set; }

    public string Name { get; set; }
    public string ShortDescription { get; set; }
    public string Description { get; set; }
    public byte[] HeroImage { get; set; }
    public DateTime Date { get; set; }
    public string Category { get; set; }

    public virtual List<ArticleTag> ArticlesTags { get; set; }
    public Article()
    {
        ArticlesTags = new List<ArticleTag>();
    }
}

public class Tag
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual List<ArticleTag> ArticlesTags { get; set; }

    public Tag()
    {
        ArticlesTags = new List<ArticleTag>();
    }
}

public class ArticleTag
{
    public int ArticleId { get; set; }
    public Article Article { get; set; }

    public int TagId { get; set; }
    public Tag Tag { get; set; }
}

This is my Controller:
 public IActionResult CreateNewArticle()
    {
        return View();
    }
    [HttpPost]
    public async Task<IActionResult> CreateNewArticle(ArticlesView av)
    {

        Article artical = new Article { Name = av.Name, Category = av.Category,
            ShortDescription =av.ShortDescription, Description=av.Description, Date = av.Date };

           // some code to add Tags from View

        db.Add(artical);
        await db.SaveChangesAsync();

        return RedirectToAction("AdminView");

My Model for creation:
public class ArticlesView
{
    public IEnumerable
 Articles { get; set; }
    public string Name { get; set; }
    public string Category { get; set; }
    public string ShortDescription { get; set; }
    public string Description { get; set; }
    public DateTime Date { get; set; }
    public IFormFile Image { get; set; }
}

}
And View:
<form asp-action="CreateNewArticle" asp-controller="home" method="post" enctype="multipart/form-data">

    The name of article
    <input type="text" asp-for="Name" class="form-control" />

    Short description
    <input type="text" asp-for="ShortDescription" class="form-control" />

    Description
    <input type="text" asp-for="Description" class="form-control" />

    Category
    <input type="text" asp-for="Category" class="form-control" />

    Date of creation
    <input type="date" asp-for="Date" class="form-control" />

As I get it right I just need to add data to my 3rd table ArticleTag (ArticleId, TagId columns), but I don't understand what type of data should be inputed in View's fields and what I should do in my Controller. Thanks in advance

A: If you want to add a new Article and add the existing tags to the article, and save the relationship to the database table ArticleTag, you could refer to the following :

*

*Add List<int> Tags to save the id of choosed tags in ArticlesVM
public class ArticlesVM
{
  public IEnumerable
 Articles { get; set; }
  public string Name { get; set; }
  public string Category { get; set; }
  public string ShortDescription { get; set; }
  public string Description { get; set; }
  public DateTime Date { get; set; }
  public List<int> Tags { get; set; }
}

2.Get the existing tags and then show them in select tag helper
public IActionResult CreateNewArticle()
    {
        ViewBag.Tags = new SelectList( _context.Tags.ToList(),"Id","Name");
        return View();
    }

@model EFCoreManyToMany.Models.ArticlesVM

<form asp-action="CreateNewArticle" asp-controller="home" method="post" enctype="multipart/form-data">

    The name of article
    <input type="text" asp-for="Name" class="form-control" />

    Short description
    <input type="text" asp-for="ShortDescription" class="form-control" />

    Description
    <input type="text" asp-for="Description" class="form-control" />

    Category
    <input type="text" asp-for="Category" class="form-control" />

    Date of creation
    <input type="date" asp-for="Date" class="form-control" />

    <select asp-for="Tags" asp-items="@ViewBag.Tags" multiple></select>

  <input type="submit" value="Create"/>
</form>

3.Save data to the database
[HttpPost]
    public async Task<IActionResult> CreateNewArticle(ArticlesVM av)
    {
        Article artical = new Article
        {
            Name = av.Name,
            Category = av.Category,
            ShortDescription = av.ShortDescription,
            Description = av.Description,
            Date = av.Date

        };
       _context.Add(artical);

        foreach(var tagId in av.Tags)
        {
            var tag = _context.Tags.Find(tagId);
            ArticleTag articleTag = new ArticleTag { Article = artical, Tag = tag };
            _context.Add(articleTag);
        }
        await _context.SaveChangesAsync();

        return RedirectToAction("AdminView");
    }


text:
Q: Calculate a sum from hidden columns I have a table which looks like:

The Strike Rate basically works out the OrdersTaken - OrdersFrom, but I don't want these two columns to show, so I would like just the Code + Strike Rate Calls
But when I disable show, it prompts me asking to enter in the numbers for it, so it's not being able to find it anymore?

My query looks like something like:
SELECT T_Temp_RestrictedDiaryCalls.AccreditedDomainCode,
    Count(T_Temp_RestrictedProductSalesHistory.CustomerCode)
        AS OrdersTaken, qry_TargetReports.CountOfCustomerCode
        AS OrdersFrom, [OrdersTaken]-[OrdersFrom]
        AS [Strike Rate (Calls)]

    FROM qry_TargetReports
        INNER JOIN (T_Temp_RestrictedDiaryCalls
        INNER JOIN T_Temp_RestrictedProductSalesHistory
            ON (T_Temp_RestrictedDiaryCalls.CallDate = T_Temp_RestrictedProductSalesHistory.EntryDate)
                AND (T_Temp_RestrictedDiaryCalls.CustomerCode = T_Temp_RestrictedProductSalesHistory.CustomerCode))
            ON qry_TargetReports.AccreditedDomainCode = T_Temp_RestrictedDiaryCalls.AccreditedDomainCode

    GROUP BY T_Temp_RestrictedDiaryCalls.AccreditedDomainCode, qry_TargetReports.CountOfCustomerCode;

But to be honest, MsAccess Generated it for me. I just need a method on how I can hide two columns while still calculating the sum, cheers.

A: Use everything you have now except [OrdersTaken]-[OrdersFrom] as a subquery and calculate that difference in the parent query.
The problem was that [OrdersTaken] and [OrdersFrom] are both aliases for field expressions, and the original query attempted to use those alias names in the SELECT clause when computing [Strike Rate (Calls)].  Generally Access won't let you do that.
SELECT
    sub.AccreditedDomainCode,
    (sub.OrdersTaken - sub.OrdersFrom) AS [Strike Rate (Calls)]
FROM
    (
        SELECT
            rdc.AccreditedDomainCode,
            Count(rpsh.CustomerCode) AS OrdersTaken,
            tr.CountOfCustomerCode AS OrdersFrom
        FROM
            qry_TargetReports AS tr
            INNER JOIN (T_Temp_RestrictedDiaryCalls AS rdc
            INNER JOIN T_Temp_RestrictedProductSalesHistory AS rpsh
            ON
                    (rdc.CallDate = rpsh.EntryDate)
                AND (rdc.CustomerCode = rpsh.CustomerCode))
            ON tr.AccreditedDomainCode = rdc.AccreditedDomainCode
        GROUP BY rdc.AccreditedDomainCode, tr.CountOfCustomerCode
    ) AS sub;

A: Look at the SELECT : there are 4 parts corresponding to the 4 result columns
T_Temp_RestrictedDiaryCalls.AccreditedDomainCode,
Count(T_Temp_RestrictedProductSalesHistory.CustomerCode) AS OrdersTaken,
qry_TargetReports.CountOfCustomerCode AS OrdersFrom
[OrdersTaken]-[OrdersFrom] AS [Strike Rate (Calls)]

If you want only the 1st and the 4th, just drop the 2nd and 3st line :
T_Temp_RestrictedDiaryCalls.AccreditedDomainCode,
[OrdersTaken]-[OrdersFrom] AS [Strike Rate (Calls)]

BUT, you also have to replace OrdersTaken and OrdersFrom by their definitions :
T_Temp_RestrictedDiaryCalls.AccreditedDomainCode,
Count(T_Temp_RestrictedProductSalesHistory.CustomerCode) # this is what OrdersTaken stands for
    - qry_TargetReports.CountOfCustomerCode # this is what OrdersFrom stands for
AS [Strike Rate (Calls)]

Note that you can also set
Strike Rate (Calls):Count(T_Temp_RestrictedProductSalesHistory.CustomerCode)-qry_TargetReports.CountOfCustomerCode

in the query definition of your editor, this will do the same.


text:
Q: How to save a 'refPath' component collection MODELS:
 const layout = new schema({
            children: [{
                    type: schema.ObjectId,
                    required: true,
                    ref: "component"
                }]
        },{ timestamps: true })

    const row = new schema({
        children: [{
            type: schema.Types.ObjectId,
            required: true,
            ref: 'component'
        }]
    },{ timestamps: true })

    const column = new schema({
        children: [{
            type: schema.Types.ObjectId,
            required: true,
            ref: 'component'
        }]
    },{ timestamps: true })

const component = new schema({
    item: {
        type: schema.Types.ObjectId,
        required: false,
        refPath: 'itemType'
    },

    itemType: {
        type: String,
        required: false,
        enum: ["myText","row", "column"]
    }
},{ timestamps: true })

AND LAST MODEL
const myText = new schema({
    title: { type: String, required: false },
    text: { type: String, required: false },
    media: {
        type: schema.Types.ObjectId,
        required: false,
        refPath: 'mediaType'
    },

    mediaType: {
        type: String,
        required: false,
        enum: 'myImage'
    }

},{ timestamps: true })

CONTROLLER - don't correct work
    const setLayout = async (req, res) => {
  const { body } = req;
  if (!body) {
    return res.status(400).json({
        success: false,
        error: "You must provide a Room",
    });
}
     component.collection.insertMany(body.children, function (err, docs) {
      if (err){
         conasolw.log(err);
      } else {
        var ids =  docs.ops.map(doc=>{ return doc._id});
        let newParent = Layout({
          children : ids
         });
         newParent.save((err, result) => {
           console.log('parent save');
        })
      }
    });

OBJECT TO SAVE
let layout = {
    "children": [
        {
            "item": {
                "children": [
                    {
                        "item": {
                            "children": [
                                {
                                    "item": {
                                        "item": {
                                            "title": "12345",
                                            "text": "dsfkd",
                                            "media": {
                                                "name": "gfdgdsada",
                                                "src": "2",
                                                "type": "jpg"
                                            },
                                            "mediaType": "myImage"
                                        },
                                        "itemType": "myText"
                                    },
                                    "itemType": "component"
                                }
                            ]
                        },
                        "itemType": "column"
                    }
                ]
            },
            "itemType": "row"
        }
    ]
}

Save DB result
When I save objects sequentially from myText to Layout everything works fine
Normal state
{
_id: ObjectId('624ddd442997df031a019b80'),
item: '624ddbaf34e91302a50ad292',
itemType: 'row'
}
Broken state
When I save complete object with all nested objects it breaks
{
    _id: ObjectId('624d7fc255b73404586836c5'),
    item: {
        children: [
            {   ...   },
                itemType: 'column'
            }
        ]
    },
    itemType: 'row'
}

What is correct way to save it?