text:
Q: Strange NetworkOnMainThreadException in Android app? The idea is to start a chat. So I have this properties in my class:
private MulticastSocket so;
private EditText messageBoard;
private InetAddress serverAddress;
private int port;

Then I have this code in the onCreate() method:
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.second);

    // connect to server
    connect();

    // Associate a variable with the Button on the interface
    final Button sendButton = (Button) findViewById(R.id.button2);
    sendButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // when the button is clicked the next screen is loaded
            sendMessage();
        }
    });

}   // end of onCreate

Here is my connect() method:
private void connect() {

    port = 4456;

    // convert the host name to InetAddress
    try {
        serverAddress = InetAddress.getByName("my server address is here");
    } catch (Exception e) {}

    // create socket and start communicating
    try {
        so = new MulticastSocket(port);
        so.joinGroup(serverAddress);
    } catch (IOException e) {}

    // start listening for incoming messages
    new Receiver(so, messageBoard);
}

Everything looks right to me but this is what it says:
01-24 23:33:16.277: W/dalvikvm(569): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
01-24 23:33:16.357: E/AndroidRuntime(569): FATAL EXCEPTION: main
01-24 23:33:16.357: E/AndroidRuntime(569): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.regeduser00x.proj1/com.regeduser00x.proj1.Second}: android.os.NetworkOnMainThreadException
01-24 23:33:16.357: E/AndroidRuntime(569):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
01-24 23:33:16.357: E/AndroidRuntime(569):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
01-24 23:33:16.357: E/AndroidRuntime(569):  at android.app.ActivityThread.access$600(ActivityThread.java:123)
01-24 23:33:16.357: E/AndroidRuntime(569):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
01-24 23:33:16.357: E/AndroidRuntime(569):  at android.os.Handler.dispatchMessage(Handler.java:99)
01-24 23:33:16.357: E/AndroidRuntime(569):  at android.os.Looper.loop(Looper.java:137)
01-24 23:33:16.357: E/AndroidRuntime(569):  at android.app.ActivityThread.main(ActivityThread.java:4424)
01-24 23:33:16.357: E/AndroidRuntime(569):  at java.lang.reflect.Method.invokeNative(Native Method)
01-24 23:33:16.357: E/AndroidRuntime(569):  at java.lang.reflect.Method.invoke(Method.java:511)
01-24 23:33:16.357: E/AndroidRuntime(569):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-24 23:33:16.357: E/AndroidRuntime(569):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-24 23:33:16.357: E/AndroidRuntime(569):  at dalvik.system.NativeStart.main(Native Method)
01-24 23:33:16.357: E/AndroidRuntime(569): Caused by: android.os.NetworkOnMainThreadException
01-24 23:33:16.357: E/AndroidRuntime(569):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
01-24 23:33:16.357: E/AndroidRuntime(569):  at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
01-24 23:33:16.357: E/AndroidRuntime(569):  at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
01-24 23:33:16.357: E/AndroidRuntime(569):  at java.net.InetAddress.getByName(InetAddress.java:295)
01-24 23:33:16.357: E/AndroidRuntime(569):  at com.regeduser00x.proj1.Second.connect(Second.java:99)
01-24 23:33:16.357: E/AndroidRuntime(569):  at com.regeduser00x.proj1.Second.onCreate(Second.java:38)
01-24 23:33:16.357: E/AndroidRuntime(569):  at android.app.Activity.performCreate(Activity.java:4465)
01-24 23:33:16.357: E/AndroidRuntime(569):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
01-24 23:33:16.357: E/AndroidRuntime(569):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
01-24 23:33:16.357: E/AndroidRuntime(569):  ... 11 more

That Second.java:99 happens to be serverAddress = InetAddress.getByName("my server address is here"); and line 38 happens to be connect(); What's the matter with it? I have tested the line with the InetAddress in a small test program and it works perfectly but here something happens.

A: this line:
Caused by: android.os.NetworkOnMainThreadException

Tells you what is going on.
You are attempting to access a network function on the Main(UI) thread. starting with Honeycomb the system raises an Exception when you do this.
To fix you just need to move any thing that is touching the network to its own thread.

A: This is done to make sure you do not block the UI thread from handling any input events from the user.By blocking the UI thread your application cannot perform any event handling routines.
Normally most UI systems have a watchdog timer,which keeps watching for any long operation on the UI thread and if the UI thread is blocked for more than a threshold(probably 10-20 seconds in android devices varying by manufacturer/OS version) the watchdog interrupts and causes a 'Application Not responding'(a.k.a ANR) to pop-up.

A: If you just want an easy work-around this, specify a minimum SDK version of Froyo or Gingerbread and omit the targetSdkVersion:
android:minSdkVersion="8"


text:
Q: ECONNREFUSED error in terminal when installing express with npm
I am running following command
npm install express

A: In terms of diagnosis, the error message is very clear. 199.27.76.162 is one of npmjs.org IP adresses. The net.js module failing with ECONNREFUSED implies that there is no connectivity from NPM to the npmjs.org server.
You should try do to a ping on that IP adress and verify general connectivity to that server.
If you run ping 199.27.76.162 from the terminal you should get an output confirming there is connectivity:
PING 199.27.76.162 (199.27.76.162): 56 data bytes
64 bytes from 199.27.76.162: icmp_seq=0 ttl=51 time=131.795 ms
64 bytes from 199.27.76.162: icmp_seq=1 ttl=51 time=138.581 ms
64 bytes from 199.27.76.162: icmp_seq=2 ttl=51 time=132.076 ms
64 bytes from 199.27.76.162: icmp_seq=3 ttl=51 time=130.904 ms
64 bytes from 199.27.76.162: icmp_seq=4 ttl=51 time=132.261 ms
64 bytes from 199.27.76.162: icmp_seq=5 ttl=51 time=131.167 ms

If you are using a proxy make sure to setup npm properly:
https://docs.npmjs.com/misc/config
Based on all evidence, the problem seems to be with your networking settings.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Declaring document-wide font size outside of the document class command I have a document, where I want two versions: one versions 10pt size and another version, 2 page to a side 12pt. So I currently have:
\documentclass[10pt,a4paper,oneside,openany,article]{memoir}
\newif\ifprintver
%\printvertrue

\ifprintver
\usepackage{pgfpages}
\pgfpagesuselayout{2 on 1}[a4paper,border shrink=1mm,landscape]
\fi

But I have to change the font size by hand. What can I put inside my \if that would change the font size document wide?

A: You can define your printver boolean before \documentclass and then use \documentclass inside an \ifprintver conditional:
\newif\ifprintver
%\printvertrue

\ifprintver
\documentclass[12pt,a4paper,oneside,openany,article]{memoir}
\else
\documentclass[10pt,a4paper,oneside,openany,article]{memoir}
\fi

% ... other code

\ifprintver
\usepackage{pgfpages}
\pgfpagesuselayout{2 on 1}[a4paper,border shrink=1mm,landscape]
\fi

\usepackage{lipsum}

\begin{document}

\lipsum[1-100]

\end{document}

A: The KOMA-Script-classes feature the macro \changefontsizes which allows you to change the main font size mid-document. This macro is also part of the scrextend package, which can (or at least it seems so) be made compatible with the memoir class.
\documentclass[10pt,a4paper,oneside,openany,article]{memoir}

\makeatletter
\let\@textsubscript\relax
\let\setfootnoterule\relax
\let\multiplefootnotemarker\relax
\makeatother

\usepackage{scrextend}

\newif\ifprintver
\printvertrue

\ifprintver
\usepackage{pgfpages}
\pgfpagesuselayout{2 on 1}[a4paper,border shrink=1mm,landscape]
\changefontsizes{12}
\fi

\usepackage{blindtext}

\begin{document}

\blindtext

\end{document}

A: use a variable for the font size setting, e.g.
\documentclass[\FontSize, a4paper]{article}

and then run pdflatex with
pdflatex '\def\FontSize{12pt}\input{<your_file>.tex}'

now you can simply change the fontsize

A: I am not sure if it is a good idea, just to set the font-size. There are more subtle differences, such as setting equation number sizing etc. What LaTeX does when processing the options is that it imports a file with the sizing and other related definitions with the extension .clo. You can try this:
\input{size12.clo}

For each class LaTeX uses slightly different conventions, for example in the book class, it uses
bk10.clo.


text:
Q: How to create a master page for SharePoint application and add sitemap to it? I am new to SharePoint,can anyone tell me how can i create a master page in my SharePoint application and add sitemap to it?
I am using Visual Studio 2012.
I saw many links however things didn't worked out for me?

A: You could use the following technet Visual Studio 2012/2013 solution as a starter project for provisioning a sample master page. Edit the master page and add the code sitemap code using the following post


text:
Q: WPF Image only updates in run-time on last frame I'm new to XAML. I wrote following routine to rotate an image by a given angle (0 to 360). I put in a slider control to set the angle based on slider value. Works great! However, when running the program and clicking the 'spin' button,a For/Next loop goes from 0 to 360 and the image will only display the last angle rotation (360). I did put in a Sleep command to slow, just in case I wasn't catching the previous updates. Any help with why it won't update continuously would be greatly appreciated. Thank you.
Imports System.Threading.Thread
Imports System.Windows.Media.Imaging.BitmapImage

Class MainWindow

    Private Sub Slider1_ValueChanged(sender As System.Object, e As System.Windows.RoutedPropertyChangedEventArgs(Of System.Double)) Handles Slider1.ValueChanged
' ---- when I adjust manually, this works perfectly
        Dim rotateTransform1 As New RotateTransform
        rotateTransform1.Angle = Slider1.Value
        lblAngle.Content = rotateTransform1.Angle
        Image1.RenderTransform = rotateTransform1
    End Sub

    Private Sub btnSpin_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles btnSpin.Click
    Dim spinAngle as Double
    For SpinAngle 0 to 360
            spinWheel(spinAngle)
            Sleep(50)
        Next spinAngle
    End Sub

    Private Sub spinWheel(ByVal spinAngle)
        Dim rotateTransform1 As New RotateTransform
        rotateTransform1.Angle = SpinAngle 'Slider1.Value
       Image1.RenderTransform = rotateTransform1
        lblAngle.Content = rotateTransform1.Angle
        Image1.InvalidateVisual()

    End Sub

    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        ' Image1.createOption = BitmapCreateOptions.IgnoreImageCache

    End Sub

End Class

XAML

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="677" Width="910">
    <Grid Background="#FF006903">
        <Grid.RowDefinitions>
            <RowDefinition Height="238*" />
            <RowDefinition Height="178*" />
        </Grid.RowDefinitions>
        <Button Content="SPIN!" Height="23" HorizontalAlignment="Left" Margin="521,101,0,0" Name="btnSpin" VerticalAlignment="Top" Width="75" Grid.Row="1" FontFamily="Tahoma" FontSize="15" FontWeight="ExtraBold" />
        <Image Height="615" Margin="32,7,0,0" Name="Image1" Stretch="None" VerticalAlignment="Top"
               RenderTransformOrigin=" 0.5,0.5"    Source="/rotatePicture;component/Images/purp_wheel_cropped.png"
               Grid.RowSpan="2" HorizontalAlignment="Left" Width="619" />

        <Slider Height="25" HorizontalAlignment="Left" Margin="127,188,0,0" Name="Slider1" VerticalAlignment="Top" Width="350" Maximum="360" Grid.Row="1" />
        <Label Content="Label" Height="28" HorizontalAlignment="Left" Margin="521,175,0,0" Name="lblAngle" VerticalAlignment="Top" Width="75" Grid.Row="1" FontFamily="Tahoma" FontSize="15" FontWeight="ExtraBold" />
        <Image Height="29" HorizontalAlignment="Left" Margin="535,252,0,0" Name="Image2" Stretch="Fill" VerticalAlignment="Top" Width="55" Source="/rotatePicture;component/Images/wheel_pointer.png" />
    </Grid>
</Window>

A: The problem with your approach is that you are blocking the UI thread by repeatedly calling Sleep in a Click handler. WPF provides a very elegant mechanism for what you are trying to do. It's called Animation.
A method that animates the rotation of a FrameworkElement may look like shown below in C# (sorry, but I don't speak VB).
private void RotateElement(
    FrameworkElement element, double from, double to, TimeSpan duration)
{
    var transform = element.RenderTransform as RotateTransform;
    if (transform != null)
    {
        var animation = new DoubleAnimation(from, to, duration);
        transform.BeginAnimation(RotateTransform.AngleProperty, animation);
    }
}

Note that the RotateTransform must already be contained in the RenderTransform property of the FrameworkElement. It could for example be assigned in XAML like this:
<Image RenderTransformOrigin="0.5,0.5" ...>
    <Image.RenderTransform>
        <RotateTransform/>
    </Image.RenderTransform>
</Image>

You would call the RotateElement method in a Button Click handler like this:
private void btnSpin_Click(object sender, RoutedEventArgs e)
{
    RotateElement(Image1, 0, 360, TimeSpan.FromMilliseconds(360 * 50));
}

Note also that in your Slider1_ValueChanged it is also not necessary to create a new RotateTransform every time.
Moreover, there is rarely any need to call InvalidateVisual, as you do in spinWheel.

A: Clemens answer is good. Do not forget that you can pause/resume animations but only if you create them in code-behind. If I remember correctly you can't control animations if you start them in XAML.


text:
Q: How can I count the number of elements in a vector that fall within a particular range using r? Let's say we a vector a = (10,23,57,37,59,25,63,33) and we want to calculate the frequency in the bins 10-19,20-29,30-39,40-49,50-59,60-69.The output should be in the form of a vector, in this case (1,2,2,2,1).

A: Another base R solution is to use hist, i.e.,
hist(a,plot = FALSE,breaks = seq(10,70,by=10))$counts
# [1] 1 2 2 0 2 1

A: Here is the solution:
a <- c(10, 23, 57, 37, 59, 25, 63, 33)
low_val  <- 10
high_val <- 70
a_breaks <- seq(low_val, high_val, 10)
res <- cut(a, a_breaks, include.lowest = T)
as.vector(table(res))
[1] 1 2 2 0 2 1

A: We can use cut with table
table(cut(a, breaks = c(-Inf, seq(10, 70, by = 10), Inf)))

Or another option is
table(findInterval, seq(10, 70, by = 10)))


text:
Q: Unable to find vcvarsall.bat even if there is in my computer I am trying to install hcluster library link with easy_install but I have an error "error: Setup script exited with error: Unable to find vcvarsall.bat"
The problem is that if I search in my pc, the file is here "C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC"
I google it but every site I found, send that they don't have the file at all.


text:
Q: 'module' object has no attribute 'celery' I've been reading through the answers to some previous questions as well as the celery docs and I just can't quite fix this issue. My task.py, celery.py, and settings.py are all contained within the same app RBWebfiles which is contained within the project called recruiting board. I'm attempting to creating a periodic-task that will run using celery beat's scheduler.
This is the portion of my settings.py that deals with celery:
from __future__ import absolute_import
import os
from datetime import timedelta

CELERY_IMPORTS = ('RBWebfiles.tasks')

CELERYBEAT_SCHEDULE = 'djcelery.schedulers.DatabaseScheduler'
CELERYBEAT_SCHEDULE = {
    'schedule-name':{
        'task': 'RBWebfiles.tasks.requestRefresher',
        'schedule': timedelta(seconds = 30),
    },
}

BROKER_URL = 'django://'

I also added 'djcelery' to my installed apps within that file
This is my tasks.py file:
from __future__ import absolute_import
import datetime
from celery.task.base import periodic_task
from student.models import StudentAccount
from celery import Celery
from celery.utils.log import get_task_logger
import os

celery = Celery('tasks', broker='django://')
logger = get_task_logger(__name__)

os.environ['DJANGO_SETTINGS_MODULE'] = 'RBWebfiles.settings'

@periodic_task(run_every=datetime.timedelta(seconds=30))
def requestRefresher(self):
    logger.info("start task")
    for s in StudentAccount.objects.all():
        s.requestLimit = 0
        s.save()
    return None

and lastly this is my celery.py file:
from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'conf.settings')
app = Celery('RBWebfiles.celery')
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda : settings.INSTALLED_APPS)

app.conf.update(
    CELERY_RESULT_BACKEND ='djcelery.backends.database:DatabaseBackend',
)

@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))

I've tried uninstalling and reinstalling both celery and django-celery, I'm not sure if I just don't understand something or I'm making a massive error. I attempt to run it using the command : celery beat -A RBWebfiles
this is the traceback:
C:\Users\Lexie Infantino\PycharmProjects\recruitingboard>celery beat -A   RBWebfiles
Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\celery\app\utils.py", line 235, in     find_app
    found = sym.app
AttributeError: 'module' object has no attribute 'app'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python34\lib\runpy.py", line 170, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\Python34\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Python34\Scripts\celery.exe\__main__.py", line 9, in <module>
  File "C:\Python34\lib\site-packages\celery\__main__.py", line 30, in main
    main()
  File "C:\Python34\lib\site-packages\celery\bin\celery.py", line 81, in     main
    cmd.execute_from_commandline(argv)
  File "C:\Python34\lib\site-packages\celery\bin\celery.py", line 769, in     execute_from_commandline
    super(CeleryCommand, self).execute_from_commandline(argv)))
  File "C:\Python34\lib\site-packages\celery\bin\base.py", line 309, in     execute_from_commandline
   argv = self.setup_app_from_commandline(argv)
  File "C:\Python34\lib\site-packages\celery\bin\base.py", line 469, in     setup_app_from_commandline
    self.app = self.find_app(app)
  File "C:\Python34\lib\site-packages\celery\bin\base.py", line 489, in     find_app
    return find_app(app, symbol_by_name=self.symbol_by_name)
  File "C:\Python34\lib\site-packages\celery\app\utils.py", line 240, in     find_app
    found = sym.celery
AttributeError: 'module' object has no attribute 'celery'

A: Make sure djcelery is in your INSTALLED_APPS and try starting celery beat with manage.py celerybeat instead.


text:
Q: Recovering data from hard disk after an accidental Ubuntu reinstallation My computer got wiped accidentally due to a fresh Ubuntu installation.
Since the drive contains very important data and codes, it would be really great if the same could be recovered.
It is a 2TB hard drive which had Ubuntu 10.10 earlier. It now has a Ubuntu 12.04 installed on it (which I understand occupies ~4GB). The machine has been powered off since.
The installation was done using a usb with the option where the previous ubuntu installation is removed.
Since installation doesn't take a lot of time, I'm inclined to think that the disk wasn't completely formatted and that most of the data is still there.
I have no experience with recovery and hence a detailed explanation is very helpful.
NOTE: I can arrange an additional 2TB hard disk for copying data. My computer has a fast internet connection and I have other computers connected to the network which I may use to access the previous one as well.

A: Exactly the same thing happened to me. I managed to recover all my data with testdisk.
In my case I had 2 partitions - the Ubuntu install formatted my drive and deleted my second partition with all my data.
I simply re-enabled the partition (I think I set it from deleted to logical..) and I could access everything from Ubuntu again.
It was also possible to copy the files from within testdisk to another drive/partition.
Good luck!


text:
Q: How to check the integrity of a file in SQL Server 2005 inserted into a BLOB - varbinary(max)? I'm trying to do a check for a file uploaded to a varbinary column in SQL Server 2005.
I uploaded the file and using
SELECT DATALENGTH(thefile) FROM table

I get the same number of bytes that the file has.
CHECKSUM is not the better way and HASHBYTES only takes the first 8000 bytes, and my files are so more great than that.
I can only use T-SQL.
Any tip will be helpful.
Thanks a lot :)

A: You can use hash over hash, it has the same strength as single-pass hash:
CREATE FUNCTION dbo.GetMyLongHash(@data VARBINARY(MAX))
RETURNS VARBINARY(MAX)
WITH RETURNS NULL ON NULL INPUT
AS
BEGIN
    DECLARE @res VARBINARY(MAX) = 0x
    DECLARE @position INT = 1, @len INT = DATALENGTH(@data)

    WHILE 1 = 1
    BEGIN
        SET @res = @res + HASHBYTES('MD5', SUBSTRING(@data, @position, 8000))
        SET @position = @position+8000
        IF @Position > @len
          BREAK
    END
    RETURN @res
END
GO

declare @theHash varbinary(max)

select @theHash = dbo.GetMyLongHash(thefile) from table

WHILE DATALENGTH(@thehash) > 16 SET @TheHash = dbo.GetMyLongHash(@theHash)

Of course you can modify the function for returning already final-pass hash


text:
Q: Sequencing records in SQL I wish to develop a query that will update the sequence column of a table to groups of sequential values based on the tmr_id and the batch_id. The Should Be column reflects the results I am looking for.
So, for all instances of a batch_id (34E5, for example), all records with a tmr_id of 61114 should have the sequence set to 1 with the 61117 records being set to 2 and so on. Often (as shown in the example), I am presented with data out of order. For example, I might get some of batch 34E5, then some 34DE, and then the rest of 34E5. I should never see a situation where there are more than four sequences in a batch group.
I hope I am explaining the situation well enough. The things I have tried have not even been close and I hate to resort to a regular program if an SQL query works.

tmr_id
trans_id
batch_id
load_time
mix_name
ingredient
sequence
Should Be

61114
502673
34E5
11-29-22 7:03
BEF300-27
HAND
0
1

61114
502674
34E5
11-29-22 7:03
BEF300-27
GRCORN
0
1

61114
502675
34E5
11-29-22 7:03
BEF300-27
SOYHUL
0
1

61114
502676
34E5
11-29-22 7:04
BEF300-27
SBM
0
1

61114
502677
34E5
11-29-22 7:04
BEF300-27
CITRUS
0
1

61114
502678
34E5
11-29-22 7:04
BEF300-27
CALCAR
0
1

61114
502679
34E5
11-29-22 7:04
BEF300-27
WCS
0
1

61114
502680
34E5
11-29-22 7:04
BEF300-27
CSH
0
1

61114
502681
34E5
11-29-22 7:04
BEF300-27
DDGS
0
1

61114
502682
34E5
11-29-22 7:04
BEF300-27
MOLASS
0
1

61115
502683
34DE
11-29-22 7:23
HIG100-7
HAND
0
1

61116
502684
34DE
11-29-22 7:29
HIG100-7
HAND
0
1

61117
502685
34E5
11-29-22 7:50
BEF300-27
HAND
0
2

61117
502686
34E5
11-29-22 7:52
BEF300-27
GRCORN
0
2

61117
502687
34E5
11-29-22 7:53
BEF300-27
SOYHUL
0
2

61117
502688
34E5
11-29-22 7:55
BEF300-27
SBM
0
2

61117
502689
34E5
11-29-22 7:56
BEF300-27
CITRUS
0
2

61117
502690
34E5
11-29-22 7:57
BEF300-27
CALCAR
0
2

61117
502691
34E5
11-29-22 7:58
BEF300-27
WCS
0
2

61117
502692
34E5
11-29-22 8:00
BEF300-27
CSH
0
2

61117
502693
34E5
11-29-22 8:02
BEF300-27
DDGS
0
2

61117
502694
34E5
11-29-22 8:02
BEF300-27
MOLASS
0
2

61118
502695
34DE
11-29-22 8:17
HIG100-7
HAND
0
1

61118
502696
34DE
11-29-22 8:19
HIG100-7
GRCORN
0
1

61118
502697
34DE
11-29-22 8:20
HIG100-7
SOYHUL
0
1

61118
502698
34DE
11-29-22 8:22
HIG100-7
SBM
0
1

61118
502699
34DE
11-29-22 8:23
HIG100-7
CITRUS
0
1

61118
502700
34DE
11-29-22 8:23
HIG100-7
BICARB
0
1

61118
502701
34DE
11-29-22 8:25
HIG100-7
CALCAR
0
1

61118
502702
34DE
11-29-22 8:26
HIG100-7
WCS
0
1

61118
502703
34DE
11-29-22 8:27
HIG100-7
CSH
0
1

61118
502704
34DE
11-29-22 8:27
HIG100-7
MOLASS
0
1

61119
502705
34DE
11-29-22 8:45
HIG100-7
HAND
0
2

61119
502706
34DE
11-29-22 8:47
HIG100-7
GRCORN
0
2

61119
502707
34DE
11-29-22 8:48
HIG100-7
SOYHUL
0
2

61119
502708
34DE
11-29-22 8:49
HIG100-7
SBM
0
2

61119
502709
34DE
11-29-22 8:51
HIG100-7
CITRUS
0
2

61119
502710
34DE
11-29-22 8:52
HIG100-7
BICARB
0
2

61119
502711
34DE
11-29-22 8:53
HIG100-7
CALCAR
0
2

61119
502712
34DE
11-29-22 8:54
HIG100-7
WCS
0
2

61119
502713
34DE
11-29-22 8:55
HIG100-7
CSH
0
2

61119
502714
34DE
11-29-22 8:55
HIG100-7
MOLASS
0
2

61120
502715
34DE
11-29-22 9:07
HIG100-7
HAND
0
3

61120
502716
34DE
11-29-22 9:09
HIG100-7
GRCORN
0
3

61120
502717
34DE
11-29-22 9:10
HIG100-7
SOYHUL
0
3

61120
502718
34DE
11-29-22 9:11
HIG100-7
SBM
0
3

61120
502719
34DE
11-29-22 9:12
HIG100-7
CITRUS
0
3

61120
502720
34DE
11-29-22 9:13
HIG100-7
BICARB
0
3

61120
502721
34DE
11-29-22 9:15
HIG100-7
CALCAR
0
3

61120
502722
34DE
11-29-22 9:16
HIG100-7
WCS
0
3

61120
502723
34DE
11-29-22 9:17
HIG100-7
CSH
0
3

61120
502724
34DE
11-29-22 9:17
HIG100-7
MOLASS
0
3

61121
502725
34DF
11-29-22 9:44
AD200-66
HAND
0
1

61121
502726
34DF
11-29-22 9:46
AD200-66
BICARB
0
1

61121
502727
34DF
11-29-22 9:48
AD200-66
CALCAR
0
1

61121
502728
34DF
11-29-22 9:49
AD200-66
AMINO
0
1

61121
502729
34DF
11-29-22 9:51
AD200-66
MINAD
0
1

61121
502730
34DF
11-29-22 9:51
AD200-66
MOLASS
0
1

61121
502731
34DF
11-29-22 9:51
AD200-66
ALIMET
0
1

61122
502732
34DF
11-29-22 10:22
AD200-66
HAND
0
2

61122
502733
34DF
11-29-22 10:23
AD200-66
BICARB
0
2

61122
502734
34DF
11-29-22 10:25
AD200-66
CALCAR
0
2

61122
502735
34DF
11-29-22 10:26
AD200-66
AMINO
0
2

61122
502736
34DF
11-29-22 10:27
AD200-66
MINAD
0
2

61122
502737
34DF
11-29-22 10:29
AD200-66
MOLASS
0
2

61122
502738
34DF
11-29-22 10:29
AD200-66
ALIMET
0
2

61123
502739
34DF
11-29-22 10:56
AD200-66
HAND
0
3

61123
502740
34DF
11-29-22 10:58
AD200-66
BICARB
0
3

61123
502741
34DF
11-29-22 10:59
AD200-66
CALCAR
0
3

61123
502742
34DF
11-29-22 11:06
AD200-66
AMINO
0
3

61123
502743
34DF
11-29-22 11:07
AD200-66
MINAD
0
3

61123
502744
34DF
11-29-22 11:07
AD200-66
MOLASS
0
3

61123
502745
34DF
11-29-22 11:07
AD200-66
ALIMET
0
3


text:
Q: How to unit test a private static/shared method? As per this answer to Unit testing private methods in C# I am using a PrivateObject to unit test private methods. This generally works really well and is quite easy to use, however it doesn't appear to work if the method is Shared or Static.
I don't really want to make the method public (otherwise I wouldn't even be bothering with PrivateObjects but I'm failing to see another way.
Example vb methods in class being tested:
    Private Sub SampleInstanceMethod(arg as Object)
        'Do something
    End Sub
    Private Shared Sub SampleSharedMethod(arg as Object)
        'Do something
    End Sub

Unit test code
    Dim fooBarPO = New PrivateObject(GetType(FooBar))
    fooBarPO.Invoke("SampleInstanceMethod", {arg1}) ' Works
    fooBarPO.Invoke("SampleSharedMethod", {arg1}) ' Doesn't work

Interested in answers in either C# or VB

A: You could use PrivateType and InvokeStatic for this:
    Dim foo = New PrivateType(GetType(TestClass))
    foo.InvokeStatic("SampleSharedMethod", {arg1})

If you want to pass parameters ByRef - for instance if the method under test looked something like this:
    Private Shared Sub SampleSharedMethod(ByRef arg As String)
       arg += "abc"
    End Sub

You can use this overload of InvokeStatic to get the results back:
    Dim foo = New PrivateType(GetType(TestClass))
    Dim params() As Object = {"123"}
    foo.InvokeStatic("SampleSharedMethod", params)

    Dim updatedValue = params(0) ' This would be 123abc in this example


text:
Q: Calculate residuals but from other slope and intercept in R Here I have two dataframes called model1 and model2:
class1<-c(1,2,3,4,5,6,7)
abund1<-c(10.4,8.9,9.1,7.5,7.1,5.1,3.2)
model1<-data.frame(class1,abund1)
class2<-c(1,2,3,4,5,6,7)
abund2<-c(9.5,8.4,8,6.3,6,2.4,1.2)
model2<-data.frame(class2,abund2)

Firstly, I use lm to extract the slope and intercept for the model1:
model1_lm<-lm(abund1~class1, data=model1)
model1_lm$coefficients[1]
11.7857                    #intercept from the model1
model1_lm$coefficients[2]
-1.1143                    #slope from the model1

What I would like to know if it is possible to calculate the residuals (i.e. ovserved value - predicted value) for the plot class2-abund2 from model2 but using the slope and intercept from model1.
Here I show you the graphs for both models with the same slope and intercept from the model1:

My purpose would be to calculate the residuals in the model2 but, as you may see, the slope and intercept come from the model1.
Hope to be clear and any help is welcome!

A: Simply use predict with the fitted model and model2 as your new data:
# predict will look for a column called "class1" in the newdata argument, so we need to provide it.
# observed - predicted
model2$abund2 - predict(model1_lm, data.frame(class1 = model2$class2))
#         1          2          3          4          5          6          7
#-1.1714286 -1.1571429 -0.4428571 -1.0285714 -0.2142857 -2.7000000 -2.7857143


text:
Q: Firebase Auth Apple Sign In for Web "INVALID_CLIENT" error? I'm using firebase to implement Sign in with Apple on my React web application. I have created an AppID, Service ID with Sign in with Apple enabled. Created a Key, configured  and completed the required steps as outlined here. However  I still get the following error response when signing in with apple. I have implemented both Facebook and Google signin with no issues.
 {
  "error": {
    "code": 400,
    "message": "INVALID_IDP_RESPONSE : Error getting access token from https://appleid.apple.com, OAuth2 redirect uri is: https://rideup-984a6.firebaseapp.com/__/auth/handler, response: OAuth2TokenResponse{params: error=invalid_client, httpMetadata: HttpMetadata{status=400, cachePolicy=NO_CACHE, cacheDurationJava=null, cacheImmutable=false, staleWhileRevalidate=null, filename=null, lastModified=null, retryAfter=null, headers=HTTP/1.1 200 OK\r\n\r\n, contentSecurityPolicies=[], originTrials=[], cookieList=[]}}",
    "errors": [
      {
        "message": "INVALID_IDP_RESPONSE : Error getting access token from https://appleid.apple.com, OAuth2 redirect uri is: https://rideup-984a6.firebaseapp.com/__/auth/handler, response: OAuth2TokenResponse{params: error=invalid_client, httpMetadata: HttpMetadata{status=400, cachePolicy=NO_CACHE, cacheDurationJava=null, cacheImmutable=false, staleWhileRevalidate=null, filename=null, lastModified=null, retryAfter=null, headers=HTTP/1.1 200 OK\r\n\r\n, contentSecurityPolicies=[], originTrials=[], cookieList=[]}}",
        "domain": "global",
        "reason": "invalid"
      }
    ]
  }
}

Please help me solve this isssue.

A: I was also facing this issue.
For me the error message "invalid_client" was a little bit misleading.
By following the docs of firebase on how to setup the apple signin method, you also need to create a private key in the apple developer console and paste it into your firebase settings.
What it fixed for me was, that I provided the private key Name instead of the key ID in the firebase settings.
You can find the Key ID, besides the name, in the detail view of the key, you created.
Key ID in Firebase Settings


text:
Q: Is it possible to define n-point functions in classical field theory? I want to show that n-point functions in classical field theory (say phi fourth theory) are given by tree diagrams, but I do not know how to proceed without using dZ/dJdJdJ which seems to be valid only for quantum theory.

A: In quantum theory,
$$ Z[J] = \int D \varphi \exp \left( i \, S[\varphi] + \int d^4 x \, J(x) \, \varphi(x) \right). $$
The corresponding classical quantity (in the stationary phase approximation) is given by
$$ Z_c [J] = \exp \left( i \, S[\varphi_0] + \int d^4 x \, J(x) \, \varphi_0(x) \right), $$
where $\varphi_0(x)$ is the solution of the classical equations of motion.
The definition of the $n$-point correlation functions is straightforward, the only difference being that we plug $Z_c$ instead of $Z$.
These correspond to tree graphs (without closed loops).


text:
Q: Trying to write variable to text file but it shows no errors but doesn't work I am trying to make a bit of code so when someone visits my website it logs their public ip onto my server for access for something else. I have this code below
<?php
    //gets the users public ip
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];
    if(filter_var($client, FILTER_VALIDATE_IP))
    {
        $ip = $client;
    }
    elseif(filter_var($forward, FILTER_VALIDATE_IP))
    {
        $ip = $forward;
    }
    else
    {
        $ip = $remote;
    }
    //access the file on server
    $file = fopen("../../UserData/AccountDetails.txt", "a");
    $found = false;
    if ($file) {
        while(!feof($file) or $found) {//if it isnt the end of the file or found is found is false loop again
            $line = fgets($file);
            if ($line != $ip) {
                $found = false;
            } elseif ($line == $ip) {
                $found = true;
            }
        }
        if (!$found) {
            fwrite($file, $ip);
        }
        fclose($file);
    } else {
        echo "<script>alert('error somewhere');</script>";
    }
?>

This gets the users public ip, however when it checks the txt file is it already exists and if it doesnt to write the ip onto it, it just doesnt work but no errors arise. Im not sure on what ive done wrong or right.

A: You are opening the file in append mode a, this means that you are at EOF already and can't seek back. You should open it in read/write mode like r+, remember also to add a newline character when you fwrite the new IP address. Another bug is that if you find the IP and it's not the last, at the next iteration found will be false again, change the if/elseif and leave only the condition of the elseif.
PS: Http headers like X-Forwarded-For can be spoofed easily, I suggest to stick with REMOTE_ADDR.


text:
Q: Windows installation through http URL We have created a http URL and stored the windows setup files. Our requirements is to execute this setup files through HTTP.
we tried with command CURL http://192.168.2.20/win2k12/setup.exe but it shows only the ASCII characters.
Also is it possible to execute the .exe files through wget?
Can anyone help us how to execute the setup.exe file from command prompt?


text:
Q: Error while inserting into an AVL tree I am getting an error while doing insertion in an AVL tree. The program crashes when it enters the insert function. I am reading some file names from a text file and passing them to this insert_data function which then calls insert_node. These are my functions
void DataStructure::insert_data(char * &fileName, long int address)
{
    this->root =  this->insert_node(this->root, fileName, address);
}

node * DataStructure::insert_node( node *t, char * &file_name, long int address)
    {
        if(t==NULL)
{
    t = new node;
    t->address = address;
    strcpy(t->buffer, file_name);
    t->height = 0;
    t->left = NULL;
    t->right = NULL;
}
else if(atoi(file_name) < atoi(t->buffer))
{
    t->left = insert_node(t->left, file_name, address);
    if(get_height(t->left) - get_height(t->right) == 2)
    {
        if(atoi(file_name) < atoi(t->left->buffer))
            t=SingleRotationLeft(t);
        else
            t=DoubleRotationLeft(t);
    }
}
else if( atoi(file_name) > atoi(t->buffer))
{
    t->right = insert_node(t->right, file_name, address);
    if(get_height(t->right) - get_height(t->left) == 2)
    {
        if(atoi(file_name) > atoi(t->right->buffer))
            t= SingleRotationRight(t);
        else
            t=DoubleRotationRight(t);
    }
}

t->height = max_height(get_height(t->left), get_height(t->right)) + 1;
return t;
}

and my construction function is
DataStructure::DataStructure(void)
{
    root = NULL;
}

A: strcpy(t->buffer, file_name);

is writing to an uninitialised pointer.  You need to allocate memory for buffer.  If you're on a Posix-compatible system, the easiest way to do this is by using strdup
t->buffer = strdup(file_name);

Otherwise, you need to allocate memory then copy separately
t->buffer = malloc(strlen(file_name)+1);
strcpy(t->buffer, file_name);

In either case, you'll need to free(t->buffer) when you free memory for each node


text:
Q: ASP.NET MVC Security Model / Database - What are my options? We have several projects (ASP.NET MVC) that will require a Role / User / Permissions security model.  We want to keep this data in tables in our database.  How to do your recommend we go about implementing this security model with our ASP.NET MVC projects?  Use custom authroization attributes that will determine if a user is authorized by interacting with data model in our database?
Are there third party / open source options available?

A: If you are willing to use Entity Framework, there's an EF Membership provider for MVC.
Here http://efmembership.codeplex.com/

A: The way i approached this is to reflect on controller actions, i still use the normal asp.net membership provider, but then have a actions table that stores all my controller/actions.
Secondly i created  a base controller and added the authorize attribute on the base controller, i then override the authorization "event" and did a check there if a user has access to that specific action, i did the same with onactionexecuting.

A: I use Rhino Security for a complex MVC site and love it.
http://ayende.com/Blog/archive/2008/01/22/Rhino-Security-Overview-Part-I.aspx
Security calls end up looking like this:
     permissionBuilderService
                .Allow("/[Controller]", 1)
                .For("GAAdmins", 1)
                .OnEverything()
                .DefaultLevel()
                .Save();

authorizationRepository.AssociateUserWith(user, "GAAdmins");

if (authService.IsAllowed(user, "/[Controller]/[Action]"))
 ...;


text:
Q: Keep leading zeroes when exporting data from R to excel I am running a SQL query in R, where the MemberID column has 9 or 10 characters. When I manually copy and paste this in excel as text format, the MemberID column retains leading zero for those members who have 9 digits. But when I automate R to run script and export data to excel, it doesn't retain leading zeroes in the MemberID column. It is a numeric column and I tried changing it to a character but it doesn't work. is there a way to keep the leading zeroes in excel?
Data <- sqlQuery(odbcChannel,
"Select distinct
PlanName,
MemberName,
MemberID,
PlanID
From Member
where PlanID ='AR'")
Data$MemberID <-as.character(Data$MemberID)
WB<-createWorkbook()
addWorksheet(WB,sheetname="Plan_AR")
writeData(WB,"Plan_AR",Data)
saveWorkbook(WB,file="MemberByPlan", overwrite =TRUE)


text:
Q: Rename variable names with tidyverse I've been struggling with a problem for a while so I was hoping to find some help here ;)
On R, I want to create a data table with two columns from a data set, modify the values of one of the two columns and calculate the number of people in the grouping for each group of variables.
I want to extract these two columns:

*

*REF_YEAR : a column with the years : '2000' '2001' '2002' .

*NAVLC9_COD : a column for my ship sizes : '[0-6[ m' '[10-12[ m' '[12-15[ m' ...

I want to modify NAVLC9_COD by renaming several variables from 0 to 12 meters with one variable and by renaming several variables over 12 meters with one variable.
STEP 1. With the idea that my script is reproducible I have created the values :
key_segment_size <- c("[0-6[ m","[6-10[ m","[10-12[ m")
other_size_segment <- c("[12-15[ m", "[15-18[ m", "[18-24[ m", "[24-40[ m", "[40-80[ m",">= 80 m")

STEP 2. Then I create my data table:
data_all_size <- data %>%
    dplyr::select(REF_YEAR,NAVLC9_COD) %>%
    str_replace(key_segment_size, "Inf. 12 m") %>%
    str_replace(other_segment_size, "Sup. 12 m") %>%
    droplevels() %>%
    group_by(REF_YEAR,NAVLC9_COD) %>%
    summarize(
      number = n()
    )

Error in type(pattern) : object 'other_segment_size' not found

in the case where I replace my values by a vector, it gives :
data_all_size <- data %>%
    dplyr::select(REF_YEAR,NAVLC9_COD) %>%
    str_replace(c("[0-6[ m","[6-10[ m","[10-12[ m"),"Inf. 12 m") %>%
    str_replace(c("[12-15[ m", "[15-18[ m", "[18-24[ m", "[24-40[ m", "[40-80[ m",">= 80 m"),"Sup. 12 m") %>%
    droplevels() %>%
    group_by(REF_YEAR,NAVLC9_COD) %>%
    summarise(
      effectif = n()
    )

Error in stri_replace_first_regex(string, pattern, fix_replacement(replacement),  :
Missing closing bracket on a bracket expression. (U_REGEX_MISSING_CLOSE_BRACKET, context=[0-6[ m)
In addition: Warning messages:
1: In stri_replace_first_regex(string, pattern, fix_replacement(replacement),  :
argument is not an atomic vector; coercing
2: In stri_replace_first_regex(string, pattern, fix_replacement(replacement),  :
longer object length is not a multiple of shorter object length

I also tried with the mutate and recode functions :
data_all_size <- data %>%
    dplyr::select(REF_YEAR,NAVLC9_COD) %>%
    mutate(Taille = recode("Inf. 12 m" = key_segment_size)) %>%
    mutate(Taille = recode("Inf. 12 m" = other_segment_size)) %>%
    droplevels() %>%
    group_by(REF_YEAR,NAVLC9_COD) %>%
    summarise(
      effectif = n()
    )

Error in mutate():
! Problem while computing Taille = recode(Inf. 12 m = key_segment_size).
Caused by error in recode.character():
! argument ".x" is missing, with no default

Can anyone tell me what I'm doing wrong/what I should do instead? I'm using tidyverse, idk if that helps at all. Thank you for any help, I'm frustrated to tears.

A: I finally achieve it thanks to  @Gregor Thomas comment with :
data_all_size <- data_sacrois %>%
 dplyr::select(REF_YEAR,NAVLC9_COD) %>%
 mutate(Taille = case_when(NAVLC9_COD %in% key_segment_size ~ "Inf. 12 m",
                           NAVLC9_COD %in% other_size_segment ~ "Sup. 12 m",
                           TRUE ~  "other")) %>%
 droplevels() %>%
 group_by(REF_YEAR,Taille) %>%
 summarise(
      effectif = n()
)


text:
Q: Verb used with word million Can anyone help me please?
Why the verb was is used here rather than were?

Two million (pounds) was withdrawn from the account.

also why verb has is used here rather than have?

*5 million settlement has to do

Does the verb adapt with the word million or settlement?
Thank for help


text:
Q: How remove registry from Many To Many relationship - Doctrine 2 I'm trying remove a registry from my database using doctrine 2, but I'm getting the follow error:
Catchable fatal error: Argument 1 passed to Doctrine\ORM\Mapping\DefaultQuoteStrategy::getJoinTableName() must be an array, null given, called in /home/triangulum/www/pedal/vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php on line 1020 and defined in /home/triangulum/www/pedal/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/DefaultQuoteStrategy.php on line 86

I have 3 tables:
grupo = id, name
permissao = id, name
grupo_permissao = grupo_id, permissao_id
My entitys:
Grupo:
    <?php

namespace User\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity
 * @ORM\Table(name="grupo")
 * @ORM\Entity(repositoryClass="User\Entity\GrupoRepository")
 */
class Grupo {

    public function __construct($options=null) {
        Configurator::configure($this, $options);
        $this->permissoes = new ArrayCollection();
    }

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue
     * @var int
     */
    protected $id;

    /**
     * @ORM\Column(type="text")
     * @var string
     */
    protected $nome;

    /**
     * @ORM\ManyToMany(targetEntity="User\Entity\Permissao", mappedBy="grupo", cascade={"remove"})
     */
    protected $permissoes;

    public function getPermissoes()
    {
        return $this->permissoes;
    }

    public function getId() {
        return $this->id;
    }

    public function setId($id) {
        $this->id = $id;
    }

    public function getNome() {
        return $this->nome;
    }

    public function setNome($nome) {
        $this->nome = $nome;
    }

    public function toArray()
    {
        return array
        (
            'id' => $this->getId(),
            'nome' => $this->getNome()
        );
    }
}

?>

Permissao:
<?php

namespace User\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity
 * @ORM\Table(name="permissao")
 * @ORM\Entity(repositoryClass="User\Entity\PermissaoRepository")
 */
class Permissao {

    public function __construct($options=null) {
        Configurator::configure($this, $options);
        $this->grupos = new ArrayCollection();

    }

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue
     * @var int
     */
    protected $id;

    /**
     * @ORM\Column(type="text")
     * @var string
     */
    protected $nome;

     /**
     * @ORM\ManyToMany(targetEntity="User\Entity\Grupo", inversedBy="permissao",  cascade={"persist", "remove"})
     * @ORM\JoinTable(name="grupo_permissao",
      * joinColumns={@ORM\JoinColumn(name="permissao_id", referencedColumnName="id")},
      * inverseJoinColumns={@ORM\JoinColumn(name="grupo_id", referencedColumnName="id")}
      * )
     */
    protected $grupos;

    public function getGrupos() {
        return $this->grupos;
    }
    public function getId() {
        return $this->id;
    }

    public function setId($id) {
        $this->id = $id;
    }

    public function getNome() {
        return $this->nome;
    }

    public function setNome($nome) {
        $this->nome = $nome;
    }

    public function toArray()
    {
        return array
        (
            'id' => $this->getId(),
            'nome' => $this->getNome()
        );
    }
}

?>

remove:
 public function delete($id)
    {

        $entity = $this->entityManager->find('User\Entity\Grupo', $id);

        if($entity)
        {
            $this->entityManager->remove($entity);

            $this->entityManager->flush();
            return $id;
        }
    }

What am I doing wrong?

A: I think you have a problem with your mappedBy and inversedBy attributes in the manyToMany annotations. They should match the other entities property name, grupos and permissoes. Try this:
/**
 * @ORM\ManyToMany(targetEntity="User\Entity\Permissao", mappedBy="grupos", cascade={"remove"})
 */
protected $permissoes;

/**
 * @ORM\ManyToMany(targetEntity="User\Entity\Grupo", inversedBy="permissoes", cascade={"persist", "remove"})
 * @ORM\JoinTable(name="grupo_permissao",
 * joinColumns={@ORM\JoinColumn(name="permissao_id", referencedColumnName="id")},
 * inverseJoinColumns={@ORM\JoinColumn(name="grupo_id", referencedColumnName="id")}
 * )
 */
protected $grupos;


text:
Q: Building Yocto on Pandaboard I am  building  yocto-poky with meta-ivi on Pandaboard. I have seen this thread saying that only denzil or earlier  versions of poky is supporting pandaboard.
I tried "denzil" but got this error
Bitbake version 1.19.1 is required and version 1.15.1 was found Failed to fetch test data from the network and the message Please ensure your network is configured correctly is printed.

then I tried with "dora" and  got this error
error: implicit declaration of function 'wl_proxy_marshal_constructor' [-Werror=implicit-function-declaration]

Any suggestion for implementation of of poky,meta-ivi,meta-ti versions for running in image on the Pandaboard?
I am using Ubuntu 14.04.


text:
Q: How to upload video as multipart request using OkHTTP? [ Android ] I need to upload video to an API, and this is how I've implemented the OKHTTP request:
 private void makeRequest(Uri uri)
{
    pr1.show();

    try
    {
        String path = uri.toString();
        Log.e("PATH",path);
        File file = new File(new URI(path));
        try {

            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("file", file.getName(),
                            RequestBody.create(MediaType.parse("video/mp4"), file))
                    .addFormDataPart("title", "damn")
                    .build();

            Request request = new Request.Builder()
                    .url(URL)
                    .header("SproutVideo-Api-Key","XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
                    .post(requestBody)
                    .build();

            client.newCall(request)
                    .enqueue(new Callback() {
                        @Override
                        public void onFailure(final Call call, IOException e)
                        {

                        }

                        @Override
                        public void onResponse(Call call, final Response response) throws IOException {
                            String res = response.body().string();
                            Log.e("SUCCESS",""+res);
                            pr1.dismiss();

                        }
                    });

        } catch (Exception ex) {
            // Handle the error
        }
    }
    catch (Exception e){}

}

However, I am unable to complete a successful request.
Log at this line Log.e("PATH",path); shows :

content://com.android.providers.media.documents/document/video%3A75611

And when I add a line break at this line : client.newCall(request), and run the debugger, the app doesn't end at any point, so I assume the request is not getting completed. What is possibly causing this? Is this the correct way of implementation?

A: I'm not familiar with the OkHTTP library, but one thing I noticed that will cause a problem is that the field for the video should be source_video, not file as outlined here.
You might also want to add some logging to your catch statements to see what, if anything might be failing silently since you seem to be ignoring any potential failures.


text:
Q: A normed space with a Schauder basis is separable. I am trying to prove the theorem: A normed space $X$ with a Schauder basis is separable.
I tried to do it the following way.
Let $X$ be a real space. Suppose that $(e_n), e_n\in X\,\forall n\in \mathbb N$ be a Schauder basis for $X$.
Let $A:=\{\sum_{i=1}^n r_i e_i: r_i\in \mathbb Q, n\in \mathbb N\}$. $A$ is countable: for a given $n$, the linear combination $\sum_{i=1}^n r_i e_i$ can be written in $\aleph^n=\aleph$ ways as $r_i\in \mathbb Q$ and the cardinality of $\mathbb Q=\aleph$. So $A$ is a countable union of such linear combinations (countably many) hence $A$ is countable.
I claim that $A$ is dense in $X$. To prove that it is so, take any $\epsilon>0$ and any $x\in X$. It is enough to show that there is some $a\in A$ such that $\|x-a\|<\epsilon.$
By definition of Schauder basis, there exists $N\in \mathbb N, (c_i)_{i=1}^\infty\subset \mathbb R$ such that $\|\sum_{i=N+1}^\infty c_ie_i\|\lt \frac \epsilon 2.$
Using density of rationals, choose $r_i\in \mathbb Q$ such that $\sum_{i=1}^N\| (-r_i+c_i)e_i\|\lt \frac \epsilon 2$.
Setting $a:= \sum_{i=1}^N r_i e_i$, it follows that $$\|x-a\|=\|\sum_{i=1}^N(-r_i+c_i)e_i+\sum_{i=N+1}^\infty c_ie_i\|\le \|\sum_{i=1}^N(-r_i+c_i)e_i\|+\| \sum_{i=N+1}^\infty c_ie_i\| <\epsilon.$$
QED.
Please let me know in case there is any error in it. Thanks a lot for your time.


text:
Q: need to pass a variable from client side to server side JS file using plain javascript I need to pass a variable from client side to server side JS file using plain javascript
Hi,
I need to pass a variable from client-side JS file to server-side JS file.
my function on client-side looks like this
function functionName(){
    var http = new XMLHttpRequest();
    var url = 'http://localhost:5500/token';
    http.open("POST",url);
    http.send("pass value from client");
    http.onreadystatechange=(e)=>{
         if(http.status === 200){
            console.log(http.responseText)
            return true;
         }
    }
}

function on server-side JS looks like this
`
app.post("/token", async function(req,res){
    console.log(req.body)    //this is not working
    var url = '<some URL>';
    http.open("POST",url);
    http.setRequestHeader("Content-Type","application/json;charset=UTF-8");
    http.send();

http.onreadystatechange=()=>{
    if(http.readyState === 4 && http.status === 200){
        res.send(http.responseText);
        res.end
    }
}

})`
when I try to print the value from server-side, it prints empty value ''.
Note- Im new to Javascript ;)

A: If you're using express, there are three ways to receive parameters from the client. See this code:
server.js
const express = require('express')
// required to actually receive data. See https://expressjs.com/en/resources/middleware/body-parser.html
const bodyParser = require('body-parser')

const app = express()

app.listen(5500, () => {
  console.log('Listening on port 5500')
})

// Receive parameter by URL
app.get('/token/:token', function (req, res) {
  const token = req.params.token
  console.log(`token is ${token}`)
  res.status(200).send(`token is ${token}`)
})

// Receive parameter by query string
app.get('/token', function (req, res) {
  const token = req.query.token
  console.log(`token is ${token}`)
  res.status(200).send(`token is ${token}`)
})

// Receive parameter by post
app.post('/token', bodyParser.text(), function (req, res) {
  const token = req.body
  console.log(`token is ${token}`)
  res.status(200).send(`token is ${token}`)
})

client.js
function getValue (method, uri, data) {
    var http = new XMLHttpRequest()
    var url = `http://localhost:5500${uri}`
    http.open(method, url);
    console.log(data)
    http.send(data)
    http.onreadystatechange=(e)=>{
        if (http.status === 200){
            console.log(http.responseText)
            return true
        }
    }
}

getValue('GET', '/token/mytoken')
getValue('GET', '/token?token=mytoken')
getValue('POST', '/token', 'mytoken')

Hope this helps.

A: I have coded a minimal working example using node.js packages http and express on the server-side and and old CommonJS version of node-fetch. Install those via npm install http express node-fetch@2
client.js:
const fetch = require('node-fetch');

let data = { foo : 'bar' };

fetch('http://localhost/test', {
    method : 'POST',
    body : JSON.stringify(data)
});

server.js:
const express = require("express");
const http = require('http');
var app = express();

var serverHTTP = http.createServer(app);
serverHTTP.listen(80);

let httpHandler = (request, response) => {
    let body = '';
    request.on('data', function (data) {
        body += data;
    });
    request.on('end', async () => {
       console.log(body);
    });
};

app.post('/test', httpHandler);

When I run the server and then the client afterwards this works for me. I would generally recommend not using XMLHttpRequest but the newer fetch, no matter whether you are on node.js or in a browser. If you get this example to work I think you should be able to adopt your code to work in a similar fashion. Please let me know if you have any further questions.

A: You mentioned that you are new to JavaScript, and I assume that you are new to web development in general (Please correct me if I'm wrong, and ignore the rest of this answer).

The expression of "Passing a variable from client-side JavaScript to server-side (back-end)" might not be correct, we would rather say that we want to pass a value, since the client is running in a completely different environment than the server.
Even though you are running both applications in your computer now, but later when you deploy it, the backend application might be sitting on a different server than the one who serves the front-end (client side) JavaScript, then that very "front-end" JavaScript will run from the users' machines.
I would invite you to read more about How the web works.
In short, the clients needs to talk to the server through protocols like HTTP (like the one you are using with XMLHttpRequest).
Note that you can now use the fetch API since it's highly supported now. But let's continue looking into your code using XMLHttpRequest.
From your backend application code, I see that you are expecting a JSON body sent by a POST request, so your client should send something that should be serialised to JSON, i.e it needs a key/value pair.
function functionName(){
    var http = new XMLHttpRequest();
    var url = 'http://localhost:5500/token';
    http.open("POST",url);
    // tells the server your content-type
    http.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    // makes your send a JSON response with { key: value }
    http.send(JSON.stringify({ message: "pass value from client" }));
    http.onreadystatechange=(e)=>{
         if(http.status === 200){
            console.log(http.responseText)
            return true;
         }
    }
}

I used this example to refresh my memory: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send#example_post.
Now from the server side, I suppose you use ExpressJS framework, make sure that your application can parse application/JSON bodies by adding app.use(express.json() before your app.post() line, so your code will look like the following:
const express = require('express');

app.use(express.json();

app.post("/token", function(req,res){
    console.log(req.body);
    return res.json({ data: req.body.message })
});

And if you want your Node.js+Express server application to perform another HTTP call to another third-party application, you can use either the core-library (tutorial) or use other libraries like axios or superagent. Also note that this approach may have a high cost on your application performance and your user-experience in some cases, especially when your future applications grows :)


text:
Q: rufus-scheduler gem not working in rails I am using the state_machine gem and the rufus-scheduler gem.  State machine is working perfectly.  Rufus-scheduler, however, is not.  I am building this program just to get used to rufus gem.  10 seconds after :accepted is transitioned to :both, it should then transition to :only_employer.  However, rufus-scheduler for some reason is not working.  The transition to :both works, but then it does not transition to :only_employer.  How do I fix this?  Thanks.
class Schedule < ActiveRecord::Base
    require 'rufus-scheduler'
    scheduler = Rufus::Scheduler.new

    def set_schedule
        scheduler.in '10' do #documentation says this should be 10 seconds
          self.change_to_done
        end
    end

    state_machine :accepted, :initial => :none do
         after_transition :any => :both, :do => :set_schedule
         event :change_to_done do
             transition :both => :only_employer
         end
    end

end

A: Using rufus-scheduler for this is overkill.
def set_schedule
  Thread.new do
    sleep 10
    self.change_to_done
  end
end

should be sufficient.
But then is the "server" you run Rails on top of thread-friendly? If not, you'd better pass the task to something like resque or sidekick.


text:
Q: Google People API, return last modified date? Is there a way to retrieve the last modified timestamp for this endpoint GET https://people.googleapis.com/v1/{resourceName=people/*}/connections
I am unable to see anything close to resembling this in the Person object fields described here https://developers.google.com/people/api/rest/v1/people#Person

A: Recently an updateTime was added to the Source field https://developers.google.com/people/api/rest/v1/people#Person.Source.
You can get it by iterating over the person.metadata.sources


text:
Q: https POST result in different response - python(w/ requests returns 200) works well whereas Javascript(w/ axios returns 500) doesn't I've made a simple https POST code snippet using python and javascript.
I expected that all results will be same but the results are not.
Python result(w/ requests) returns 200 whereas javascript(w/ axios) returns 500.
I think all conditions including headers are exactly equal but I wonder why this situation happens.
Please let me know if I'm mistaken.

[Python code] / python 3.9.6
import requests
import json
s = requests.Session()

_url = 'https://graphql.bitquery.io/'
_data = {
        "variables": json.dumps({
        "limit": 1,
        "offset": 0,
        "network": "ethereum",
        "token": "0xB8c77482e45F1F44dE1745F52C74426C631bDD52",
        "from": "2021-06-01",
        "till": "2022-01-02T23:59:59",
        "dateFormat": "%Y-%m-%d"
        })
}

r = s.post(url=_url, data=_data)
r.text

Its response returns 200 and the result is below.
'{"data":{"ethereum":{"transfers":[{"block":{"timestamp":{"time":"2022-01-02 23:59:50"},"height":13929166},"sender":{"address":"0xf60c2ea62edbfe808163751dd0d8693dcb30019c","annotation":null},"receiver":{"address":"0x7b60d1c03cda03952bebc58d7a64c2e15f738356","annotation":null},"transaction":{"hash":"0x09be49c24fc639572a6dcc4e338ce57c5f2d206c983935f6c21df522276dc875"},"amount":0.24,"currency":{"symbol":"BNB"},"external":true}]}}}'

I also wrote another simple snippet using javascript w/ axios and I expected the same result but...
[Javascript code] / node.js v16.13.1
const axios = require('axios')

const _url = 'https://graphql.bitquery.io/'
const _data = {
        "variables": JSON.stringify({
        "limit": 1,
        "offset": 0,
        "network": "ethereum",
        "token": "0xB8c77482e45F1F44dE1745F52C74426C631bDD52",
        "from": "2021-06-01",
        "till": "2022-01-02T23:59:59",
        "dateFormat": "%Y-%m-%d"
        })
}

const r = async () => {
    const resp = await axios.post(_url, {
        data: _data
    })
    console.log(resp)
}
r()

Its response returns 500 and the result is below.
Uncaught Error: Request failed with status code 500

A: @CBoe Thank you for your help.
It was due to an axios syntax mistake.
const r = async () => {
    const resp = await axios.post(_url, {
        data: _data
    })
    console.log(resp)
}
r()

-> it should be revised as below.
const r = async () => {
    const resp = await axios.post(_url, _data)
    console.log(resp)
}
r()

Its response returns 200.
{status: 200, statusText: 'OK', headers: {…}, config: {…}, request: ClientRequest, …}


text:
Q: How to add a custom component in Ionic (3)? I have a sign up page module, where I am attempting to include a custom component: "EaterSignUpModule" (soon to be a module with two custom components, for the different user roles)
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { SignupPage } from './signup';
// components
import { EaterSignupModule } from './components/eater-signup/eater_signup.module';
// services
import { SignUpService } from './services/signup.service';

@NgModule({
  declarations: [
    SignupPage,
  ],
  imports: [
    IonicPageModule.forChild(SignupPage),
    EaterSignupModule
  ],
  exports: [
    SignupPage
  ],
  providers: [
    SignUpService
  ]
})
export class SignupPageModule { }

This is my custom component's module file:
import { NgModule } from '@angular/core';
import { IonicModule } from 'ionic-angular';
// components
import { EaterSignUp } from './eater_signup';
// services
import { SignUpService } from '../../services/signup.service';

@NgModule({
  declarations: [
    EaterSignUp
  ],
  imports: [
    IonicModule,
  ],
  exports: [
    EaterSignUp
  ],
  entryComponents: [
    EaterSignUp
  ],
  providers: [
    SignUpService
  ]
})
export class EaterSignupModule { }

And this is the components typescript file/class file:
import { Component } from '@angular/core';
import { AlertController, App, LoadingController } from 'ionic-angular';
// interfaces
import { Credentials,
  EaterProfile,
  VendorProfile,
  VehicleDimensions
} from '../../../../interfaces/main.interfaces';
// services
import { SignUpService } from '../../services/signup.service';

@Component({
  selector: 'eater-signup',
  templateUrl: 'eater_signup.html',
})
export class EaterSignUp {

  constructor(
    public loadingCtrl: LoadingController,
    public alertCtrl: AlertController,
    public signUpService: SignUpService,
    public app: App
  ) {
    this.initialize();
   }

  public initialize(){

  }

}

Code for where I actually use the selector:
<ng-container *ngIf="viewState=='eaterSelected'">
  <eater-signup></eater-signup>
</ng-container>

My understanding of doing this sort of thing in ionic is limited (IonicPage and IonicPage Module)
I am faced with the following error: "Uncaught Error: Template parse errors:
'eater-signup' is not a known element:
1. If 'eater-signup' is an Angular component, then verify that it is part of this module....."
In normal angular I usually just declare the component, and don't even need a module for it.
Would appreciate any help with this. Thanks


text:
Q: Can one design neural networks to learn the ReLU activation function itself? I was studying neural networks and activation functions. It crossed my mind that what if ReLU non-linearity is learned by a neural network itself. If it is possible, How?

A: Yes. ReLU is a nice well-behaved function and neural networks are universal function approximaters, so they can certainly learn ReLU.
For example:
https://arxiv.org/abs/1906.09529


text:
Q: Is there a way to get the system boot time? After you reboot and the system is all loaded up, is there a place that stores the system boot time; meaning the total time it took for the system to boot back up.
I would like to compare different systems and their boot times perhaps for testing things like fastest booting OS's, optimization performance, or fastest booting drives like solid-state drives compared to other drives.

A: If you're running Windows XP, use Bootvis. you will get a detailed graph showing you exactly how long each application and device driver takes to load.

For later Windows versions use MSDN's Windows Performance Toolkit, an even better set of tools than the old Bootvis utility. At its most basic, you can use the tools to provide you with a similar graphical display of boot performance which was provided by Bootvis.

A simpler application would be Boot Timer, but it also works for Vista/7.

And then there is Passmark's AppTimer to analyze the startup behaviour of applications.

So much for software. Other than that, resort to Phoshi's hardware solution that works cross-platform :)

A: In PowerShell:
$os = Get-WmiObject -computer localhost -class Win32_OperatingSystem

$boot = $os.ConvertToDateTime($os.LastBootUpTime)

then
((Get-Date) - $boot).TotalSeconds

or in Days:Hours:Minutes:Seconds...
((Get-Date) - $boot).ToString()

A: Under Linux, use bootchart to measure the boot time. It can also be used to analyze how much time is spent by which programs as well as I/O and CPU use.
More basically, you can check /proc/uptime to see how long the kernel has been running.

A: How to find the last 2 boot time using PowerShell?
Get-EventLog -LogName System -Source Microsoft-Windows-Kernel-General | Where-Object {$_.EventID -eq 12} | Select-Object -Property TimeGenerated -First 2


text:
Q: MySQL Refactoring Lengthy Query Alright, I totally hate myself for asking this; but I'm looking for another way to do this query, something that might be faster as well as more elegant (this looks like crap).  Tell me what you think please:
  SELECT TRUNCATE(SUM(sub.Total),3) AS GrpTotal, sub.ActualDate,
         TRUNCATE(SUM(sub.BonusAmt),3) AS GrpBonusAmt, sub.UID,
         sub.CUSTID, YEAR(MIN(sub.ActualDate)) AS Year, pusers.username
  FROM ( SELECT a.UID, a.ActualDate, 'Global Report' AS Report,
                SUM(a.totalpayment) AS Total, a.CUSTID,
               ((SUM(a.totalpayment)*IFNULL((u.retention_percent/100),1))+IFNULL(u.bonus_amount,0)) AS BonusAmt
         FROM `globalreport` a
              LEFT JOIN `users` u ON u.uid = a.UID
         WHERE true AND a.CUSTID = 1020
         GROUP BY a.ActualDate, a.UID
         UNION ALL
         SELECT a.UID, a.ActualDate, 'Amex Residuals' AS Report,
                SUM(a.payment) AS Total, a.CUSTID,
                ((SUM(a.payment)*IFNULL((u.retention_percent/100),1))+IFNULL(u.bonus_amount,0)) AS BonusAmnt
         FROM `amexresiduals` a
              LEFT JOIN `users` u ON u.uid = a.UID
         WHERE true AND a.CUSTID = 1020
         GROUP BY a.ActualDate, a.UID
         UNION ALL
         SELECT a.UID, a.ActualDate, 'Compliance Fee' AS Report,
                SUM(a.profit) AS Total, a.CUSTID,
                ((SUM(a.profit)*IFNULL((u.retention_percent/100),1))+IFNULL(u.bonus_amount,0)) AS BonusAmnt
         FROM `compliancefee` a
              LEFT JOIN `users` u ON u.uid = a.UID
         WHERE true AND a.CUSTID = 1020
         GROUP BY a.ActualDate, a.UID
         UNION ALL
         SELECT a.UID, a.ActualDate, 'Checks On Demand' AS Report,
                SUM(a.myprofit) AS Total, a.CUSTID,
                ((SUM(a.myprofit)*IFNULL((u.retention_percent/100),1))+IFNULL(u.bonus_amount,0)) AS BonusAmnt
         FROM `geticheck` a
              LEFT JOIN `users` u ON u.uid = a.UID
         WHERE true AND a.CUSTID = 1020
         GROUP BY a.ActualDate, a.UID
         UNION ALL
         SELECT a.UID, a.ActualDate, 'Gift Cards on Demand' AS Report,
                SUM(a.payment) AS Total, a.CUSTID,
                ((SUM(a.payment)*IFNULL((u.retention_percent/100),1))+IFNULL(u.bonus_amount,0)) AS BonusAmnt
         FROM `gcod` a
              LEFT JOIN `users` u ON u.uid = a.UID
         WHERE true AND a.CUSTID = 1020
         GROUP BY a.ActualDate, a.UID
         UNION ALL
         SELECT a.UID, a.ActualDate, 'Global Check' AS Report,
                SUM(a.myprofit) AS Total, a.CUSTID,
                ((SUM(a.myprofit)*IFNULL((u.retention_percent/100),1))+IFNULL(u.bonus_amount,0)) AS BonusAmnt
         FROM `globalcheck` a
              LEFT JOIN `users` u ON u.uid = a.UID
         WHERE true AND a.CUSTID = 1020
         GROUP BY a.ActualDate, a.UID
         UNION ALL
         SELECT a.UID, a.ActualDate, 'Bonus True Up' AS Report,
                SUM(a.finalpayment) AS Total, a.CUSTID,
                ((SUM(a.finalpayment)*IFNULL((u.retention_percent/100),1))+IFNULL(u.bonus_amount,0)) AS BonusAmnt
         FROM `bonustrueup` a
              LEFT JOIN `users` u ON u.uid = a.UID
         WHERE true AND a.CUSTID = 1020
         GROUP BY a.ActualDate, a.UID
         UNION ALL
         SELECT a.UID, a.ActualDate, 'Bonus Take Back - Did Not Activate' AS Report,
                SUM(a.amount) AS Total, a.CUSTID,
                ((SUM(a.amount)*IFNULL((u.retention_percent/100),1))+IFNULL(u.bonus_amount,0)) AS BonusAmnt
         FROM `bonusadjnosetup` a
              LEFT JOIN `users` u ON u.uid = a.UID
         WHERE true AND a.CUSTID = 1020
         GROUP BY a.ActualDate, a.UID
         UNION ALL
         SELECT a.UID, a.ActualDate, 'Bonus Take Back - Closed Less Than 6 Months' AS Report,
                SUM(a.amount) AS Total, a.CUSTID,
                ((SUM(a.amount)*IFNULL((u.retention_percent/100),1))+IFNULL(u.bonus_amount,0)) AS BonusAmnt
         FROM `bonusadjclosed6mo` a
             LEFT JOIN `users` u ON u.uid = a.UID
         WHERE true AND a.CUSTID = 1020
         GROUP BY a.ActualDate, a.UID
         UNION ALL
         SELECT a.UID, a.ActualDate, 'Month End Fee Rejects' AS Report,
                SUM(a.amount) AS Total, a.CUSTID, SUM(a.amount) AS BonusAmnt
         FROM `merchantloss` a
             LEFT JOIN `users` u ON u.uid = a.UID
         WHERE true AND a.CUSTID = 1020
         GROUP BY a.ActualDate, a.UID
         UNION ALL
         SELECT a.UID, a.ActualDate, 'Direct ACH Debits and Credits' AS Report,
                SUM(a.amount*-1) AS Total, a.CUSTID, SUM(a.amount*-1) AS BonusAmnt
         FROM `dirachdebcred` a
             LEFT JOIN `users` u ON u.uid = a.UID
         WHERE true AND a.CUSTID = 1020
         GROUP BY a.ActualDate, a.UID
         UNION ALL
         SELECT a.UID, a.ActualDate, 'Merchant Adjustments' AS Report,
                SUM(a.amount) AS Total, a.CUSTID,
                ((SUM(a.amount)*IFNULL((u.retention_percent/100),1))+IFNULL(u.bonus_amount,0)) AS BonusAmnt
         FROM `merchantadj` a
             LEFT JOIN `users` u ON u.uid = a.UID
         WHERE true AND a.CUSTID = 1020
         GROUP BY a.ActualDate, a.UID
  ) sub
      LEFT JOIN `pending_users` pusers ON pusers.UID = sub.UID
  WHERE sub.CUSTID = 1020
       AND sub.`UID` NOT IN
                ( SELECT `UID`
                  FROM `users`
                  WHERE `is_admin` AND `company_id` = sub.`CUSTID`)
  GROUP BY sub.ActualDate, sub.UID, sub.Report
  ORDER BY sub.ActualDate ASC

Clearly, this is a lengthy query.  I'm just not sure it has to be.  Essentially, I'm gathering and summing a different column in each of the unioned tables and grouping by that amount at the very end so I can get a total sum from all tables.

A: Since you're getting results from several different tables, your query actually looks really good. I agree that the length of the SQL text is a bit daunting.
The overall approach looks like it's going to be the most efficient way to get the specified result. I'm assuming that the inner queries against the individual tables are collapsing a lot of rows.
In terms of performance, about the only thing I would change is that NOT IN predicate, since that's going to cause the subquery to be executed for each row.
You could get an equivalent result using an anti-join pattern, assuming that UID is a primary key in users table, or, that it's at least guaranteed to be NOT NULL. (I'm assuming that the subquery doesn't return NULL; if it did, the NOT IN predicate wouldn't return TRUE, and you wouldn't get any rows back at all.)
So this:
  WHERE sub.CUSTID = 1020
       AND sub.`UID` NOT IN
                ( SELECT `UID`
                  FROM `users`
                  WHERE `is_admin` AND `company_id` = sub.`CUSTID`)

can be replaced with an equivalent but (usually) more efficient:
   LEFT
   JOIN `users` n
     ON n.is_admin
    AND n.company_id = sub.`CUSTID`
    AND n.`UID` = sub.`UID`
  WHERE n.`UID` IS NULL
    AND sub.CUSTID = 1020

The anti-join pattern is looking for a matching row, and then excluding any rows that did have a match, so what we're left with is just the rows that didn't match.
Actually, there's no need check that sub.CUSTID = 1020, that can be omitted. We're already guaranteed it's going to be 1020 by each of the queries in the sub inline view.

In the SELECT list of the outer query, I think this MIN aggregate adds some confusion:
YEAR(MIN(sub.ActualDate))

It just looks unnecessary, since the query is doing a GROUP BY sub.ActualDate, and since the YEAR function is deterministic (i.e. the values returned by YEAR(foo) are going to be equal for equal values of foo. I'd replace that with just:
YEAR(sub.ActualDate)

Actually, I don't think it's necessary to perform a GROUP BY operation at all on the outer query.
The value returned for the Report column of sub are distinct to each of the UNION ALL queries.  And each of those queries has already performed a GROUP BY UID, ActualDate. So, the (UID,ActualDate,Report) tuple from sub is already guaranteed to be unique.
The only question there is whether UID is unique in the pending_users table. If it's not, then the totals the query is returning are getting doubled, tripled, etc., and just picking the username value from one matching row.  But I don't think that the query is doing that, I strongly suspect that UID is unique in pending_users.  (There aren't any columns from pending_users included in the outermost GROUP BY.)  Aside from matching multiple rows from pending_users...
The query has already guaranteed that there aren't any rows to be collapsed by that GROUP BY on the outermost query. It looks like all that GROUP BY is getting you is a sort operation.  That could be replaced with an ORDER BY.
That also means that the SUM aggregates (in the SELECT list of the outermost query) aren't necessary. For example, this expression:
TRUNCATE(SUM(sub.Total),3)

could be replaced with:
TRUNCATE(sub.Total,3)

and return an equivalent result.

In terms of performance... having suitable indexes available is important. in the EXPLAIN, we'd rather not see Using filesort for the GROUP BY operations of those inner queries. We'd much rather see Using index.
For those inner queries, ideally we'd see an indexes like this:
... ON merchantloss (CUSTID, ActualDate, UID, amount)

There's an equality predicate on CUSTID, and there's a GROUP BY operation on ActualDate,UID. Having the columns in this order (almost) guarantees that MySQL will use the index to perform the GROUP BY and avoid a Using filesort operation.  Including the other columns referenced in the query makes it a covering index, meaning the query can be satisfied entirely from the index without any need to visit the pages in the underlying table.

One final note...  it might be just a tiny bit more efficient to do that is_admin exclusion (using the anti-join pattern) on each of the individual inner queries, if that limits the number rows being returned from sub. But I suspect it won't make much difference, and it might even be slower...  I'd leave it on the outermost query, if just for the sake of avoiding repeating that multiple times.

A: UPDATE
As if my previous answer wasn't long enough ...
I'd also move the JOIN to the users table from the inner queries to the outer queries, it looks like it's identical in every case.
But, we need that for the calculation of BonusAmnt (which appears to always be based on whatever Total is; the calculation is the same for all of them except for two. So, I also moved the BonusAmnt calculation to the outer query as well, and just adding a check for which calculation to do, using a CASE expression.
I may have missed something.
But here's how I'd write the query.
I'll show it in two pieces, with the query for the sub inline view separate from the outer query.
  SELECT TRUNCATE(sub.Total,3) AS GrpTotal
       , sub.ActualDate
       , CASE
           WHEN sub.Report IN ('Month End Fee Rejects','Direct ACH Debits and Credits') THEN
             TRUNCATE(sub.Total,3)
           ELSE
             TRUNCATE(sub.Total*IFNULL((u.retention_percent/100),1)+IFNULL(u.bonus_amount,0)),3)
         END AS GrpBonusAmt
       , sub.UID
       , sub.CUSTID
       , YEAR(sub.ActualDate) AS Year
       , pusers.username
    FROM (
           -- query to produce sub goes here
         ) sub
    LEFT
    JOIN `users` u
      ON u.uid = sub.UID
    LEFT
    JOIN `pending_users` pusers
      ON pusers.UID = sub.UID
    LEFT
    JOIN `users` n
      ON n.UID = sub.CUSTID
     AND n.is_admin
   WHERE n.UID IS NULL
   ORDER BY sub.ActualDate, sub.UID, sub.Report

And here is the second part. This is the query that gets stuck into the middle of the part above, as an inline view. This is the query that that produces sub row source for the outer query:
           SELECT 'Global Report' AS Report
                , a.UID, a.ActualDate, a.CUSTID
                , SUM(a.totalpayment) AS Total
             FROM `globalreport` a
            WHERE a.CUSTID = 1020
            GROUP BY a.ActualDate, a.UID
            UNION ALL
           SELECT 'Amex Residuals'
                , a.UID, a.ActualDate, a.CUSTID
                , SUM(a.payment) AS Total
             FROM `amexresiduals` a
            WHERE a.CUSTID = 1020
            GROUP BY a.ActualDate, a.UID
            UNION ALL
           SELECT 'Compliance Fee'
                , a.UID, a.ActualDate, a.CUSTID
                , SUM(a.profit) AS Total
             FROM `compliancefee` a
            WHERE a.CUSTID = 1020
            GROUP BY a.ActualDate, a.UID
            UNION ALL
           SELECT 'Checks On Demand'
                , a.UID, a.ActualDate, a.CUSTID
                , SUM(a.myprofit) AS Total
             FROM `geticheck` a
            WHERE a.CUSTID = 1020
            GROUP BY a.ActualDate, a.UID
            UNION ALL
           SELECT 'Gift Cards on Demand'
                , a.UID, a.ActualDate, a.CUSTID
                , SUM(a.payment) AS Total
             FROM `gcod` a
            WHERE a.CUSTID = 1020
            GROUP BY a.ActualDate, a.UID
            UNION ALL
           SELECT 'Global Check' AS Report
                , a.UID, a.ActualDate, a.CUSTID
                , SUM(a.myprofit) AS Total
             FROM `globalcheck` a
            WHERE a.CUSTID = 1020
            GROUP BY a.ActualDate, a.UID
            UNION ALL
           SELECT 'Bonus True Up'
                , a.UID, a.ActualDate, a.CUSTID
                , SUM(a.finalpayment) AS Total
             FROM `bonustrueup` a
            WHERE a.CUSTID = 1020
            GROUP BY a.ActualDate, a.UID
            UNION ALL
           SELECT 'Bonus Take Back - Did Not Activate'
                , a.UID, a.ActualDate, a.CUSTID
                , SUM(a.amount) AS Total
             FROM `bonusadjnosetup` a
            WHERE a.CUSTID = 1020
            GROUP BY a.ActualDate, a.UID
            UNION ALL
           SELECT 'Bonus Take Back - Closed Less Than 6 Months'
                , a.UID, a.ActualDate, a.CUSTID
                , SUM(a.amount) AS Total
             FROM `bonusadjclosed6mo` a
            WHERE a.CUSTID = 1020
            GROUP BY a.ActualDate, a.UID
            UNION ALL
           SELECT 'Month End Fee Rejects'
                , a.UID, a.ActualDate, a.CUSTID
                , SUM(a.amount) AS Total
             FROM `merchantloss` a
            WHERE a.CUSTID = 1020
            GROUP BY a.ActualDate, a.UID
            UNION ALL
           SELECT 'Direct ACH Debits and Credits'
                , a.UID, a.ActualDate, a.CUSTID
                , SUM(a.amount*-1) AS Total
             FROM `dirachdebcred` a
            WHERE a.CUSTID = 1020
            GROUP BY a.ActualDate, a.UID
            UNION ALL
           SELECT 'Merchant Adjustments'
                , a.UID, a.ActualDate, a.CUSTID
                , SUM(a.amount) AS Total
             FROM `merchantadj` a
            WHERE a.CUSTID = 1020
            GROUP BY a.ActualDate, a.UID


text:
Q: Question about estimating number of individuals in a population that belong to 2 sets... Suppose we have a population containing $x$ number of individuals. Out of these individuals we know a number $x_{men}$ are men and $x_{women}$ are women. We also know that there are $x_{veg}$ vegetarians and $x_{non-veg}$. We also assume the following:
$$x_{men} + x_{women} = x$$
$$x_{veg} + x_{non-veg} = x$$
Can we deduce how many vegetarian men there are? If not can we at least make an estimate?


text:
Q: Hadoop Mapreduce: How to partition data from mapper to reducer I have tested map.py and reduce.py in the local environment.
The input file like:
R55726rest149624640000014962753030007006483323902288110000NJ110112hoboken   R55726rest149636308400014964192000007063481824780452130000NY130800hoboken   R23412rest149641920000014965055650007063480924780416130000NJ130800weehawken

The output of Map like:
R55726,1496246400000,1496275303000,70064833,23902288,Hoboken
R55726,1496289016000,1496293537000,70685312,24637310,Hoboken
R12345,1496357338000,1496357862000,70634437,24780843,Jersey city
R12345,1496357921000,1496361659000,70632989,24780983,Jersey city

Then I want to partition the output data of Map by the first column.
Final output will have two files:part-00000, part-00001
The run.sh:
-D stream.map.output.field.separator=, \
-D stream.num.map.output.key.fields=2 \
-D map.output.key.field.separator=, \
-D num.key.fields.for.partition=1 \
-numReduceTasks 1 \

But it dosen't work.
Chould you tell me how to modify the program? Thank you very much!

A: From the Hadoop docs :
hadoop jar hadoop-streaming-2.7.3.jar \
  -D stream.map.output.field.separator=. \
  -D stream.num.map.output.key.fields=4 \
  -D map.output.key.field.separator=. \
  -D mapreduce.partition.keypartitioner.options=-k1,2 \
  -D mapreduce.job.reduces=12 \
  -input myInputDirs \
  -output myOutputDir \
  -mapper /bin/cat \
  -reducer /bin/cat \
  -partitioner org.apache.hadoop.mapred.lib.KeyFieldBasedPartitioner

The property you are looking for is mapreduce.partition.keypartitioner.options.
You also need to specify your partitioner. In your case, one of the defaults, KeyFieldBasedPartitioner would work.


text:
Q: Help with finding Hex header information of file I'm not 100% this is meant to go in stackoverflow but I'm sure it'll be moved if necessary.
I have a hex header file I just screen grabbed and would like to know what extension the file really is. The file was originally an exe but didn't seem to work, but looking at the hex information showed that it was an mzp, I just need it to be confirmed.

Thanks.

A: It is an executable file created with Delphi. The first 3 bytes 0x4D 0x5A 0x50 are decoded as 'MZP' in ASCII. The "P" stands for Pascal.

A: This does look like an exe file.

A: MZ - First two bytes indicate dos executable. Not sure what third byte P is for. Might be actually more than one byte and part of program identifier?
http://www.fileformat.info/format/exe/corion-mz.htm


text:
Q: How to analyze observed vs expected when expected is just a proportion? I did an experiment where I had subjects with a repertoire of possible responses to a stimulus. The stimulus presented was something in their repertoire. If they responded to the stimulus with a match of the stimulus I assigned them a value of 1 for match. If they responded to the stimulus without matching I assigned them a value of 0.
I'm interested in knowing if they matched the stimulus more often than expected by chance. I'm fairly certain I have to do a chi-square test for this but I'm uncertain how to go about my expected values. In most papers the expected value is the inverse of the mean repertoire across subjects. This makes sense in my study as well. What I don't know how to do is how to present my expected value in the correct way to do a chi-square, since my observed values are multiple values in a column and my expected value is just a proportion.
For example:
Observed Matches
1
0
0
0
0
1
0
0
0
0

Where the observed proportion of matches is 0.2. The mean repertoire for example is 10, meaning the expected proportion of matches is 0.1.
How do I perform a chi-square test (if this is the correct test) with these values?

A: The test you need is a one sample z-test.
We seek to test $H_0:p=1/2 vs. H_1:p<1/2$, where $p$ is the proportion responding to the stimulus.
The test statistic is $Z = \frac{p-1/2}{\sqrt{0.5(1-0.5)/n}}$.
The distribution of $Z|H_0$ a standard normal, $N(0,1)$.
StatisticsLectures.com outlines the test further.


text: Q: Vs code pre debugging flutter I have a flutter project. I debug it in Visual Studio Code and write the code. Before Visual Studio Code can debug, it needs to decode string text to base64 and create a file. Then I want to debug the project. Is this possible in vs code?


text:
Q: How can I calculate all possible Bézier handle points in order to make the curve to a given length? Given two anchor points and a handle point of a cubic Bézier curve, how can I calculate the other handle point in order to make the curve length to a fixed value?
What kind of orbit will it be?
NOTE: Ultimately I will make a solution in C++ for my CAD software. What I need then is, given a point (mouse cursor position), calculate the "nearest" possible handle point that makes the curve to a given length. I assume the orbit should be a closed curve wrapping around the anchor. If that is the case, I would want to check the intersection of a ray (from cursor to the anchor) to the orbit. For performance. I would accept the "nearest" possible point comes from the ray.
Thanks in advance.