text:
Q: create interval with criterion in R              gdk   frist   pers       start     code  reg  prog       done  omreg
1           FALSE  FALSE 1941-12-23 2011-01-19 MM2001 FFG FRIST 2012-09-21 FALSE
4            TRUE  FALSE 1943-04-04 2011-09-01 MM2001 FFG FRIST 2012-01-11 FALSE
6           FALSE   TRUE 1944-01-27 2013-09-01 MM2001 FFG FRIST 2014-06-12 FALSE
10          FALSE  FALSE 1944-11-01 2010-01-19 MM2001 FFG FRIST 2010-12-17 FALSE
11          FALSE  FALSE 1945-04-21 2009-09-01 MM2001 FFG FRIST 2010-06-14 FALSE
12          FALSE   TRUE 1945-06-13 2013-01-19 MM2001 FFG FRIST 2014-01-13 FALSE

above, we have a piece of the head (both)
I have estimated that it takes 160 days for the students to read one semester. And I want to find out which students were approved for 160 days.
I used:
gdk<-(difftime(as.Date(both$done),
as.Date(both$start), units="days") < 160 & !both$omreg)

but right now I want to add a criterion for this range.
variable prog = which program students study
Here is all the programs;
FRIST LARAA NASTK NBFFK NBIBK NDATK NFYSK NMATK NMETK NMFIK NSFYY SMEKK

so if the student reads FRIST or NDATK they should be <320 days
for LARAA NASTK NBFFK NBIBK NFYSK NMATK NMETK NMFIK NSFYY SMEKK
it should still be <160
I simply want to have a similar column that gdk with true and false if students meet the criteria. But I want them to be adapted to this criterion. How do I?

A: Just put the ifelse instead of 160:
( difftime(as.Date(both$done), as.Date(both$start), units="days") <
    ifelse(both$prog %in% c("FRIST", "NDATK"), 320, 160) &
    !both$omreg)


text:
Q: What is the cause here because I have null error? LINQ LeftJoin Problems var allCustomers = customers.GroupJoin(packages,
    customers => customers.PackId,
    packages => packages.PackId,
    (customers, packages) => new { customers, packages })
    .SelectMany(y => y.packages.DefaultIfEmpty(),
    (x, y) => new { CustId = x.customers.CustomerId, PackId = y.PackId }).ToList();

I tried to DO left join operation, but without success

A: Look at the DefaultIfEmpty() call. If a Customer has no related Package, the packages collection would be empty. Calling DefaultIfEmpty() returns a default (null) package object for empty packages collections. That means, in the call to SelectMany you can get nulls for y in the last parameter of SelectMany. To overcome this, you can use Null-conditional operator  (?.):
var allCustomers = customers
    .GroupJoin(
        packages,
        customer => customer.PackId,
        packages => packages.PackId,
        (customer, packages) => new { customer, packages })
    .SelectMany(
        y => y.packages.DefaultIfEmpty(),
        (x, y) => new { CustId = x.customer.CustomerId, PackId = y?.PackId })
    .ToList();

You should also note that in this case PackId in the resulting collection is a nullable type (maybe int?) and is null for some resulting items.
Advice: The query syntax is much simpler for such cases:
var allCustomer =
    (from customer in customers
     join package in packages on customer.PackId equals package.PackId into g
     from package in g.DefaultIfEmpty()
     select new { CustId = customer.CustomerId, PackId = package?.PackId })
    .ToList();

Another note: If you write such a query against IQueryable collections coming from an ORM (Entity Framework, for example), you will not get a NullReferenceException. Because your query is translated to SQL and is run on your DBMS.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mail.app on Mac corrupting PDFs A co-worker is having an issue where PDFs sent as attachments are being corrupted.  If opened through webmail, the attachment is fine.  Any ideas here?
I've rebuilt the Mailbox (using Mail.app's built in feature), but it happened after it.

*

*Macbook Air

*2012 Model

*10.8.3

*Google Apps IMAP

*Happening to PDFs randomly and a powerpoint.

A: I had a similar issue at one point.
Try clicking the save button on the top-right corner of the email and designate where to save the files. Then open the file through finder (instead of just clicking on the pdf within the email). This worked for me.

A: Same issue. Mail.app seems to convert line breaks in a PDF from Linux to windows style. In a text (PostScript ) block it makes no difference, but it messes up the binary parts of the PDF.


text:
Q: image control - dynamic load image from the resource file I create in the code some image control and i want to set on this image control some of the picture that i saved ( load those pictures before creating the image control )
How can i do it ?

A: Specify your image in your Resource like this
<BitmapImage x:Key="SampleImageSource" UriSource="sample.png" />

and assign that to your image control like
<Image Source="{StaticResource SampleImageSource}" />

or if you are trying to do in code
img.Source = (ImageSource) Resources["SampleImageSource"];


text:
Q: Moving a physics button with fixed axis after rotation in Unity I'm trying to make a physics based button as shown below.

The red cube should travel down on the Y axis when force is applied and hit the trigger (the light grey box).
I have achieved this by making the red cube a rigidbody and freezing rotation and position (except on Y axis). The red cube is attached to the trigger via a sprint joint.
This works pretty well, until I try to rotate the whole container for the button, and then the button depresses on the world Y axis (red arrow below) instead of it's local Y axis (green arrow below).

How can I fix this? Thanks!

A: Figured it out, this code will restrict movement to the local y axis only and remove the freeze position flags on the rigidbody component
void Update()
{
    transform.localPosition = new Vector3(0, transform.localPosition.y, 0);
}


text:
Q: Unique with sort ignores 2nd condition I am using the following formula to create a unique list with 2 conditions, the formula works fine:
=UNIQUE(FILTER('Credit Pulls'!$E$2:$E$150000,('Credit Pulls'!$D$2:$D$150000=Summary!M17)*('Credit Pulls'!$AI$2:$AI$150000 >0)))
However, I also ant to sort the list, but when I add the sort part to the formula it ignores my second criteria
=SORT(UNIQUE(FILTER('Credit Pulls'!$E$2:$E$150000,('Credit Pulls'!$D$2:$D$150000=Summary!M17)*('Credit Pulls'!$AI$2:$AI$150000 >0))))
Can someone tell me what I am doing wrong?
Column AI has a 0 or 1, I do not want to include any results that have a 0

A: This requires troubleshooting to discover where the error ariss --
a) Create the unique(filter(..)) list in a column within excel, then apply (to that spill # range) the sort function - do the two columns have different lengths? If not - there is no issue (it would seem)
b) Are there any cells within the filter range, or filter criteria range that dependent (or link to) the results of the unique(sort()) output (if so , do you have iterative calculation on?)
c) Scale down by using, say,the first 10-20 rows, and see if you encounter same issue (I doubt you will)
d) Then extend range to 75k rows (half of desired) - do you still encounter issue? if so, cut back the range to 37.5k rows? if no issue then try half way between 37.5 and 75 - effectively honing in where exactly the problem arises.
e) Do you have any blank cells, or #value! values in any of the cells (target filter range, the set of two conditions?
f) If you swap around the two conditions within the filter - i.e. (D:D * AI:AI) -> (AI:AI * D:D), what do you find (does it now 'ignore' the 'new' 2nd condition (D:D) or does it figure out what you've done and now ignore the new first? (AI:AI) ☺
g) Do all above but chanage the order in which you sort - you could sort i) before filter ii) after filter but before unique - do you still encounter issues under a-f) above?
As noted - I was unable to replicate your error myself with pseudo/scaled down example - per screenshot - so I gather there must be something you're overlooking that you would probably uncover once you started attempting above troubleshooting suggestions.

A: After going through some of the testing that was recommended I discovered it was a something so easy to fix, I was typing in the criteria I needed and it did not work. It was more of a user error than the formula. I learned a lot from this experience, thank you for all that helped.


text:
Q: PhantomJS Local ISO Date off I have some tests for an Angular 2 app that pass in when run in Firefox but fail in PhantomJS. In the test I'm checking that a date is set properly. I feed in a local iso date string in the form "2017-07-20T14:20". The date portion is set properly but the time is off. I'm running the test in Mountain Time zone (-6:00 UTC) so the time is coming through as 08:20. Is there a shim or set up config I may be missing.
Here is some code:
In my customDate class file
public startTime: string;

public setDate(date: string) {
    let date:Date = new Date(date);
    this.startTime = date.getHours() + ':';
    if (date.getMinutes() < 10) {
        this.startTime += date.getMinutes() + '0';
    } else {
        this.startTime += date.getMinues();
    }
 }

In my test file
it('should pass') {
    let testDate = new customDate();
    testDate.setDate('2017-07-20T14:20');
    expect(testDate.startTime).toBe('14:00'); <-- this is failing it's comeing through as ('8:00')
}

A: When researching a similar problem with older versions of Chrome and Safari parsing a local date time string as UTC we found this solutions: Javascript: parse a string to Date as LOCAL time zone . It turns out that PhantomJS uses ES5 and thus the date time strings are parsed as UTC not local. The solution in the link explains whats happening and how to work around it.


text:
Q: jQueryJavaScript error - missing ; before statement I was using this statement in my code to cache the jquery selector and this was causing an error in the console. The error was "Missing ; before statement"
var $medium-image-holder = $('#image_'+itemID_value);

where itemID_value is a numeric value. This statement is inside a for loop
Out of curiosity and after trying various tricks to overcome this thing, I replaced the hyphen with underscore in the variable name.
var $medium_image_holder = $('#image_'+itemID_value);

Surprisingly this worked.
I want to know whether using hyphens in JavaScript variable names is not permitted. At least, I didn't know about this. Would be very helpful if someone clarifies.

A: Indeed, hyphens are not allowed in variable names.

A: MDC Guidelines for variable names state;

A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).

A: Your statement $medium-image-holder is interpreted as $medium - image - holder ($medium minus image minus holder).
After interpreting this statement as an algebraic expression, you try to set the outcome of it to a value with another statement (=$('#image_'+itemID_value)), which is not allowed. That is where your error message comes from.

A: java script does not allow hyphen in variable name declaration variable name can only include alphabets numbers or underscore moreover variable name should only start with alphabet variable names cannot start with numbers
cheers


text:
Q: Drag and Drop: Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob' I am creating a speed reader which first takes in a PDF and converts it to text. I have a drag and drop area set up and a button that goes into the user's files to select.
The file select works and I am able to read in the file but when I try to use the drag and drop it doesn't work and I get an error. Any help would be greatly appreciated!
Here's what I have (I am still fairly new to JS):

        <form class="my-form">

Upload multiple files with the file dialog or by dragging and dropping images onto the dashed region

            <input type="file" id="fileElem" name="fileElem" multiple accept=".pdf" onchange="handleFiles(this.files)" />

            <progress id="progress-bar" max=100 value=0></progress>

Select some files

        </form>

<button class="button" id="submit" onclick="convert()">Process PDF</button>

...


text:
Q: Why do spectrum analyzers generate X-Rays Most, if not all, old HP spectrum analyzers say

X-Rays generated in this intsr are sufficiently screened

Why do they generate x-rays at all. The HP 8565E I am looking at can only measure up to 50 GHz so I have trouble seeing why it would have such high frequencies in it.

A: The warning relates to the display, not the instrument itself.
The HP 8565E uses a CRT monitor as its display. CRTs are electron beam devices, and can emit some X-rays if improperly adjusted and/or inadequately shielded. The notice is reassuring you that the hardware limits on brightness, and the leaded glass built into the screen, are sufficient to protect you from exposure.
This sort of notice is normal for devices containing CRTs; You'll probably find similar notices buried in the manuals of old televisions and computer monitors.


text:
Q: FullCalender check if selection days has an event? I am using the Full Calender js plugin, so far so good. but i want to check if a selection between the start and end has events?
I just need a true or false returned. Basically i want to stop users from creating events if an even already exists on the date selection.
var calendar = $('#calendar').fullCalendar({

    selectable: true,
    selectHelper: true,
    firstDay: 5,
    weekNumbers: false,
    select: function (start, end, allDay, event) {
        var TitleSet = false;
        StartDate = start;
        EndDate = end;
        if (event) {}
        if (TitleSet) {
            calendar.fullCalendar('renderEvent', {
                title: title,
                start: start,
                end: end,
                allDay: allDay
            },
            true // make the event "stick"
            );
        }
        calendar.fullCalendar('unselect');

    },
    editable: true,
    events: EventsArr,
    eventRender: function (event, element) {
        element.qtip({
            content: event.description
        });
    }
});

A: I tried this methode and it looks fine
    // check if this day has an event before
    function IsDateHasEvent(date) {
        var allEvents = [];
        allEvents = $('#calendar').fullCalendar('clientEvents');
        var event = $.grep(allEvents, function (v) {
            return v.start === date;
        });
        return event.length > 0;
    }

then you can call it from dayclick event
    dayClick: function (date, allDay, jsEvent, view) {

        if (!IsDateHasEvent(date)) {
            selectedDate = date;
            $("#divAddNewAppointment").dialog("open");
        }
        else {
            $('<%= "#" + lblMessage.ClientID%>').html(" your error msg");
            $("#divMessage").dialog("open");
        }
    }

A: You will need to create a method to get the array of events already loaded in calendar, after that use that array to get all days that have events and if user clicks on one of that dates don´t let create another event. This is something that only you can make and figure out, you will need to make an algorithm for yourself...
Check this clientEvents


text:
Q: Updating value in columns based on a column from another table I am using pandasql to update or replace values in columns using an ID from another table.
I have two tables one that I am trying to update or replace the values
Table A
id  start_destination  end_destination
=======================================
1        3431              3010
2        3521              3431
3        3010              3521

Table B
destination_id     destination_name
=======================================
      3010              NameA
      3431              NameB
      3521              NameC

I am trying to write an SQL query to create the following output
id  start_destination  end_destination
=======================================
1        NameB              NameA
2        NameC              NameB
3        NameA              NameC

I tried
update TableA
set start_destination = TableB.destination_name
from TableB
where TableB.destination_id = TableA.start_destination

But I was getting an error
(sqlite3.OperationalError) near "from": syntax error

In the real dataset, there are more than 10 columns in Table A, which I need to keep all.
Also, if there is a destination_id that cannot be matched with either start or end_destination, it should be null.

A: You may try joining table B to table A, twice:
SELECT
    a.id,
    b1.destination_name AS start_destination,
    b2.destination_name AS end_destination
FROM TableA a
LEFF JOIN TableB b1
    ON b1.destination_id = a.start_destination
LEFT JOIN TableB b2
    ON b2.destination_id = a.end_destination
ORDER BY
    a.id;


text:
Q: Is there any way to trace or listen that user clicks on any link from a browser, or any chat messenger app or even SMS? I am trying to trace link click anywhere & in any app in android device.
For Example, if user clicks links inside WhatsApp - before link redirects to browser, i want to trace it inside my application that link is clicked.
Is there any way to achieve this??
I tried Safe Browsing, but its not fulfilling my requirement.
Your suggestions can help me a lot.
Please Let me know if any have solutions for this.

A: Within your App yes it is possible to trace user's click events i.e. You can collect analytics data But the same is not possible for whole device i.e. you can not get trace/click events/analytics data of other apps or entire device.
It is against the security policy and Google will not allow it.
Hope it will help you.


text:
Q: Component in AEM console not activated I have created a servlet class which will get called while making a ajax call.When seeing it from AEM console system/console/components ,its status is in Factory mode but it should have the status Active also.How to make the Component Active ? Can anyone help ?

A: It looks like you have attribute configurationFactory = true in your @Component annotation. It makes this class to behave as service factory and I believe put it here unintentionally, right? If you remove it - you will see Active.
Otherwise, If you need your servlet to be service factory, for some reason, you need to create named configuration for this factory.


text:
Q: Save result of multiplication to existing array Consider the following code:
a = numpy.array([1,2,3,4])
b = numpy.array([5,6,7,8])
# here a new array (b*2) will be created and name 'a' will be assigned to it
a = b * 2

So, can numpy write the result of b*2 directly to memory already allocated for a, without allocating a new array?

A: Yes this is possible - you need to use np.multiply with its out parameter:
np.multiply(b, 2, out=a)

The array a is now filled with the result of b * 2 (and no new memory was allocated to hold the output of the function).
All of NumPy's ufuncs have the out parameter which is especially handy when working with large arrays; it helps to keep memory consumption to a minimum by allowing arrays to be reused. The only caveat is that the array has to the correct size/shape to hold the output of the function.


text:
Q: Missing something in the linux terminal after launching matlab from the command line I'm having a weird behaviour when launching matlab from the command line in linux.
I've a bash script in linux that execute a function in matlab from the command line and does other operations with custom functions written in C++ as follows:
#!/bin/bash
# prepare input data just to be sure it has not been written by other test!
matlab2011a -nodesktop -nosplash -r "prepare_data_matlab( 'A' ); quit"
# launch C++ program
...
# prepare more data
matlab2011a -nodesktop -nosplash -r "prepare_data_matlab( 'B' ); quit"

When the script is finished I can not see what I'm writing in the terminal, although the commands have effects. I need to reset the terminal.
The fact is that everything works fine if I only launch matlab with the prepare_data_matlab( 'A' ) but the problem comes when I execute the function with option prepare_data_matlab( 'B' ).
I have commented line by line and found that the problem is with option B that call the function
dlmwrite(file_name, B, ' ');

which is not used in prepare_data_matlab( 'A' ).
So, how should I execute the matlab from the command line to avoid this behaviour? Is there a known bug with the dlmwrite() function?
I'm using Ubuntu 12.04 64 bits, GNU bash, versión 4.2.24(1)-release (x86_64-pc-linux-gnu) and matlab2011a.
EDITED: The output generated for prepare_data_matlab( 'A' ) is

The output generated for prepare_data_matlab( 'B' ) is

EDITED: file_name is created as strcat(path_to_data,f); where path_to_data = /tmp/ and f = data_out.txt. Matrix B is not displayed before or after.
The only output to the terminal before or after the MATLAB script is generated from the bash script as follow:
echo "#### SELECT DATA FROM WORKSPACE ####"
matlab2011a -nodesktop -nosplash -r "prepare_data_matlab( 'B' ); quit";
echo "#### Process Data as input in a C++ programs ####"

The MATLAB function select data from the workscape and save it to disk as follows:
function [ ] = prepare_data_matlab( type )
if strcmp(type,'A')
    % load data from workscape
    load ('workspace_with_my_arrays.mat', 'A');
    % save data as a standalone variable
    save('/tmp/A.mat', 'A');
elseif strcmp(type,'B')
    % load data from workscape
    load ('workspace_with_my_arrays.mat', 'B');
    path_to_data = '/tmp/';
    f            = 'data_out.txt';
    file_name    = strcat(path_to_data,f);
    % save data as a txt file
    dlmwrite(file_name, B, ' ');
end
end

EDITED: whos -file workspace_with_my_arrays.mat
Name                             Size                     Bytes  Class     Attributes

A                             610x340x103            170897600  double
B                             610x340x103            170897600  double
P                             610x340                  1659200  double
t1                            38855x100                 31084000  double
t2                            3921x2x100                6273600  double

There are more arrays in the workspace but those are which I load.
The prepare_data_matlab function is the same as posted above but with an argument error checking as follow:
%% Load data from file
% Data is saved in a MATLAB variable or in TXT
if nargin ~= 1
    error('Use: prepare_data_matlab( [ A | B ] )')
end

and the following command:
cd /data/matlab;

which is executed after the arguments error check in both cases (option Aand option B), that is, before the if statement.

A: The problem is not with dlmwrite. This seems to be a bug in some versions of MATLAB, as reported in this link.
The proposed solution (if you have a buggy version of MATLAB) is to use nohup:
nohup matlab -nodesktop -nosplash -r ...........

UPDATE:
Per @Amro 's suggestion, @pQB reported the problem to MathWorks Support. Their response was:

The problem is a known issue in versions prior to R2012a. Run MATLAB under a different shell. For example, neither tcsh or zsh have this issue.

OLD answer:
The problem is not with dlmwrite, but with the content of your matrix. Furthermore, unless file_name points to stdout (e.g., file_name='/dev/stdout';), the dlmwrite function will not write anything to screen and will not mess your terminal. Either file_name points to stdout or you are displaying the matrix B right before (or after) the dlmwrite call.
In any case, the problem is with the contents of your matrix B (see the strange characters in your output). You need to fix the problem with your matrix B. Perhaps the method you are using to read its input data is faulty.

A: If you want to ignore output from MATLAB (like the banner printed at the beginning), launch the process and redirect both the standard input and error to /dev/null device:
#!/bin/sh

echo '### running MATLAB ###'
matlab -nodesktop -nosplash -r "..." > /dev/null 2>&1
echo '### done ###'

./other_script.sh

matlab -nodesktop -nosplash -r "..." > /dev/null 2>&1

Note that you should be careful since MATLAB process returns immediately possibly before it has finished running, which could cause problems if your next program depends on files produced by MATLAB. See here for a possible solution.


text:
Q: Embed Jquery into html or seperate file? Is it better to put J Query directly into html or in a separate file and which one is more conventional?

A: I would say it's better to keep your jQuery in a separate file. It makes your HTML code more organised.


text:
Q: Most efficient way to insert an already sorted set into REDIS I have an already sorted set in memory of size (N) and want to dump it into redis, can it be done in O(N) if inserted head or tail first? or it doesn't matter, and the insertion will be O(log(N!)) ~ O(N log(N))
For further details, redis sorted sets are implemented using a hashmap and a skiplist (for the ordering).
EDIT: this question remains unanswered since quite a bit, or at least the answer is a bit ambiguous for me: Redis: Is ZADD better than O(logN) when the inserted element is at the beginning or end?

A: Here are the results from my "empirical" approach which suggest there may be a slight benefit to having order :)
(.venv)foo@bar:~/so_bounty$ python main.py
ascending order
5.57414388657
descending order
5.72963309288
random order
6.75937390327
0 score
5.79048109055

A: After having doubts on the methodology employed in another empirical approach, I have conducted my own insertion benchmark (all sets are initialized before timing insertion, for random insertion testing, the list of tuples is shuffled before we start timing) with the following results:
for an ordered set with 2k, 20k and 200k members:

*

*head first: 196.29s | 1146.43s | 9897.29s

*tail first: 170.14s | 993.43s | 9722.14s

*rand insert: 146.00s | 1014.57s | 9968.57s

All with enough variability (standard devs at 7.8 | 54.5 | 324.5 respectively)  so the difference are not significant enough for conclusions. Seems it doesn't matter... :(


text:
Q: storyboard dynamic auto layout issue I have this situation :

When I tap on "add" button I reduce the pink view's(first view) height and I execute this code:
@IBOutlet weak var viewPink: UIView!

    @IBAction func add(_ sender: AnyObject) {

        viewPink.frame = CGRect(x: viewPink.frame.origin.x, y: viewPink.frame.origin.y, width: viewPink.frame.size.width, height: viewPink.frame.size.height - 50)

        }

but I want that the last view remains to the same distance from the pink view , essentially you have to climb on why the pink view reduces its height , instead the second view remains where it was before.
Can you help me about it?
P.S I set the vertical spacing constraint between the two views but It doesn't work

A: You should add an Height constraint on your pink view, create an IBOutlet to this constraint in your ViewController, and set the "constant" property to change the height.
Example:
heightConstraint.constant = 150
This will change the height with Autolayout, you shouldn't change the height by setting a new frame because it doesn't use Autolayout.


text:
Q: Document a constant using ngDoc How would one go about documenting a constant using ngDoc?  I don't see any angular specific documentation for documenting values registered with .constant, and the jsDoc syntax for constants doesn't seem to generate any actual docs when it's run through ngDoc.
Ex:

/**
* @constant
* @name WHITE
*
* @description
* The color white!
**/
module.constant( 'WHITE', '#fff' );

A: ngDocs currently doesn't provide a way to document constants. As you can see in its templating source code. There isnt relevant html_usage_* method.
I document constants like this, it shows a APP_CONFIG as a module then.
/**
 * @ngdoc object
 * @name APP_CONFIG
 * @description
 *   constant...
 * @example
 * APP_CONFIG is injectable as constant (as a service even to .config())
 * <pre>
 * (...)    .config(function ($APP_CONFIG) {
 * </pre>
 */

A: It should be @const
/** @const */ var MY_BEER = 'stout';

/**
 * My namespace's favorite kind of beer.
 * @const {string}
 */
mynamespace.MY_BEER = 'stout';

/** @const */ MyClass.MY_BEER = 'stout';

/**
 * Initializes the request.
 * @const
 */
mynamespace.Request.prototype.initialize = function() {
  // This method cannot be overridden in a subclass.
};

See the constant part http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#Constants and the comments part http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml?showone=Comments#Comments for more informations


text:
Q: Modify data frame with respect to another data frame in R I have two data frames:
> test
     par1  par2  par3 progress
1    TRUE  TRUE FALSE        0
2    TRUE FALSE  TRUE        0
3    TRUE  TRUE  TRUE        0
4    TRUE  TRUE  TRUE        0
5    TRUE FALSE FALSE        0
6   FALSE FALSE  TRUE        0
7    TRUE FALSE  TRUE        0
8    TRUE  TRUE  TRUE        0
9    TRUE FALSE  TRUE        0
10   TRUE FALSE  TRUE        0
...

> rules
    par1  par2  par3 progress
1   TRUE  TRUE  TRUE      0.1
2   TRUE  TRUE FALSE      0.3
3   TRUE FALSE  TRUE     -0.2
4   TRUE FALSE FALSE      0.7
...

I'd like to modify test$progress <- test$progress + rules$progress according to values of par1, par2 and par3 i.e. in case of test[1, ] its progress should be increased by 0.3, in case of test[2, ] its progress should be decreased by 0.2 and so on. After appropriate changes of test$progress its par1, par2 and par3 values will be recalculated and the process will be repeated many times.
Data frame test has around 4k rows and data frame rules has all combinations of TRUE/FALSE for its parameters.
I know how to do this in a loop, but I know it is not the best way to do it. What is a better way?

A: Then you can merge the two tables on the first three columns:
df <- merge(test, rules, all.x = TRUE, by = c("par1", "par2", "par3"))
df[,5][is.na(df[,5])] <- 0
df$progress = df$progress.x + df$progress.y
df <- df[c(1:3,6)]

df
    par1  par2  par3 progress
1  FALSE FALSE  TRUE      0.0
2   TRUE FALSE FALSE      0.7
3   TRUE FALSE  TRUE     -0.2
4   TRUE FALSE  TRUE     -0.2
5   TRUE FALSE  TRUE     -0.2
6   TRUE FALSE  TRUE     -0.2
7   TRUE  TRUE FALSE      0.3
8   TRUE  TRUE  TRUE      0.1
9   TRUE  TRUE  TRUE      0.1
10  TRUE  TRUE  TRUE      0.1

Pay attention at the new ordering.
Or with dplyr
left_join(test, rules, by = c("par1", "par2", "par3")) %>%
replace(is.na(.), 0) %>% mutate(progress = progress.x + progress.y) %>% select(-c(4:5))
    par1  par2  par3 progress
1   TRUE  TRUE FALSE      0.3
2   TRUE FALSE  TRUE     -0.2
3   TRUE  TRUE  TRUE      0.1
4   TRUE  TRUE  TRUE      0.1
5   TRUE FALSE FALSE      0.7
6  FALSE FALSE  TRUE      0.0
7   TRUE FALSE  TRUE     -0.2
8   TRUE  TRUE  TRUE      0.1
9   TRUE FALSE  TRUE     -0.2
10  TRUE FALSE  TRUE     -0.2


text:
Q: How to filter request based on client in C# (Identity Server 4) I made this method because the actual project was working with tokens in Header, and for my project I have to read the body (my token is in body). What I did was first checking if the token is under Authorization, if not check the body... But I´ve become the feedback that the best way to solve that is based on my Client, because im the only one reading the token from Body..
private string GetTokenFromHeader()
  {
     string value = _contextAccessor.HttpContext.Request.Headers["Authorization"];
     if (value.IsNull()) //if null, check body.
        return GoogleGetTokenFromBody(_contextAccessor);
     return value.Substring(IdentityServerAuthenticationDefaults.AuthenticationScheme.Length + 1).Trim();
  }

I have no clue how to filter a request by client name, has someone an idea or suggestion?


text:
Q: How to load an *.obj file in python and apply a texture to it The title is my question: How can I load an *.obj 3d model in Python and apply a texture to it. I managed to load a 3d model, view it and apply textures to simple blocks and walls, but it seems impossible to apply a texture to a 3d model. How can I do that? Is there a script to load a 3d model with a texture in Python.
I'm using PyOpenGL as platform and I'm not allowed to use pygame from my teacher.

A: you might want to check out ASSIMP, it has python bindings:  http://assimp.sourceforge.net
also, if you feel like writing your own .obj loader (it is a pretty simple format) check out this tutorial:
http://en.wikibooks.org/wiki/OpenGL_Programming/Modern_OpenGL_Tutorial_Load_OBJ


text:
Q: Проблема с функцией(C++, структуры)
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string.h>
using namespace std;
struct aeroflot
{
    char* fname;
    int fnumber;
    char* ptype;

};
void input(aeroflot obj)
{
    char* buffer = new char[255];
    cout << "название пункта назначения рейса: " << endl;
    cin >> buffer;
    obj.fname = new char[strlen(buffer) + 1];
    strcpy(obj.fname, buffer);
    obj.fname[strlen(buffer)] = '\0';
    cout << "номер рейса (число): " << endl;
    cin >> obj.fnumber;
    cout << "тип самолета: " << endl;
    cin >> buffer;
    obj.ptype = new char[strlen(buffer) + 1];
    strcpy(obj.ptype, buffer);
    obj.ptype[strlen(buffer)] = '\0';
{
 aeroflot plane = {};
 input(plane);
 system("pause");
}

Если вытащить из под функции все работает, в функции же (Вызвано исключение по адресу 0x00254B31 в lab4.exe: 0xC0000005: нарушение прав доступа при чтении по адресу 0x00000000.) Однако, эта же версия с указателем работает(картинка1), помогите разобраться, пожалуйста =3

A: Дело в том, что вы передаёте вашу структуру в функцию по значению. То есть, в функцию приходит копия структуры, она там как-то заполняется, а оригинал структуры остаётся незаполненным.
Из-за этого все проблемы.
Передавайте, например, указатель или ссылку на структуру, будет всё работать.
P. S.: Остаток кода не смотрел.


text:
Q: Showing that 2 elements of a vectorspace are equal I don't know how to solve the following problem. Suppose that dim(V) = n and W = $\mathbb{R}$. The vectorspace V* = Hom(V, $\mathbb{R}$) is called the dual space of V. An element $\phi$ $\in$ V* is called a (linear) functional. Now, suppose that v, w $\in$ V such that $\phi$(v) = $\phi$(w) for all $\phi$ $\in$ V*. Can we conclude that v = w?
Thanks for your help.


text:
Q: Convert codes to faster codes using Groupby I need to return value in this format:
Find the news using their category and choose from each category 6 news
 Category :
          news
          news
          news
          news
          news
          news
 Category :
          news
          news
          news
          news
          news
          news
 Category :
          news
          news
          news
          news
          news
          news

I've written this code but it's very slow.
private async Task<List<NewsDto>> GetCatNews()
{
    List<NewsDto> news = new List<NewsDto>();
    var FindAllCategory = this.CategoryService.Entities.ToList();
    foreach (var item in FindAllCategory)
    {
        var model = new NewsDto();
        var TakNews = Entities.Where(x => x.CategoryId == item.Id).Take(6)
            .OrderBy(x => x.CreateDate).ToList();
        if (TakNews.Count >= 6)
        {
            news.Add(new NewsDto
            {
                CatId = item.Id,
                CatName = item.Name,
                NewsContents = await AddNewsContents(TakNews)
            });
        }
    }
    return news;
}

public async Task<List<NewsContent>> AddNewsContents(List<Post> TakNews)
{
    List<NewsContent> newsContents = new List<NewsContent>();
    foreach (var addNews in TakNews)
    {
        newsContents.Add(new NewsContent
        {
            Description = addNews.Description,
            Id = addNews.Id,
            ImagePath = rootSiteData.GetNewPath() + '/' + addNews.ImagePath,
            Title = addNews.Title
        });
    }
    return newsContents;
}

I need to write faster code for up performance in project .
How can I solve this problem?
Sample Data :
i except return this value
iexcept return this value
"data": [
{
  "catId": 1,
  "catName": "سیاسی",
  "newsContents": [
    {
      "id": 3048,
      "imagePath": "https://localhost:44372/Uplaod/NewsPictureFolder/NewsMainPicture/509246904089447.jpg",
      "title": "نفت در برابر غذا! / حقایق تلخ اینستکس چیست؟ ا",
      "description": "اروپایی‌ها بعد از ۹ ماه تعلل و مذاکره و ۴ ماه پس از اعلام تصمیم‌شان برای مقابله با تحریم‌های ثانویه امریکا یک ساز و کار با ظرفیت محدود آن هم نه برای تبادل پول بلکه برای تامین غذا و دارو ایجاد کرده اند.\n"
    },
    {
      "id": 3049,
      "imagePath": "https://localhost:44372/Uplaod/NewsPictureFolder/NewsMainPicture/349512794187136.jpg",
      "title": "پاسخ ایران به ادعای آمریکا در رابطه با بروز تنش در منطقه",
      "description": "نمایندگی ایران در سازمان ملل، ادعاها اخیر آمریکا از جمله دستور تخلیه کارمندان غیرضروری این کشور در عراق را آخرین پرده از جنگ تبلیغاتی آمریکا علیه ایران با استفاده از \"گزارش‌های اطلاعاتی تقلبی\"دانست که به منظور بهانه شروع یک درگیری احتمالی بیان می‌شود.\n"
    },
    {
      "id": 3050,
      "imagePath": "https://localhost:44372/Uplaod/NewsPictureFolder/NewsMainPicture/946066292956619.jpg",
      "title": "به زودی احکام افزایش دستمزد کارمندان ابلاغ می‌شود",
      "description": "تسنیم نوشت: نماینده همدان در مجلس از نشست مشترک دولت، مجلس و دیوان محاسبات برای تعیین تکلیف حقوق و دستمزد کارمندان خبر داد.\n\n"
    },
    {
      "id": 3051,
      "imagePath": "https://localhost:44372/Uplaod/NewsPictureFolder/NewsMainPicture/322083917213095.jpg",
      "title": "عصبانیت شدید ترامپ از سیاست های بولتون و ترامپ در قبال ایران",
      "description": "روزنامه واشنگتن پست به نقل از چند مقام آمریکایی گزارش داد دونالد ترامپ از مشاوران ارشدی که به نظر وی ایالات متحده را به سوی تقابل با ایران می برند ناراضی و ناامید شده و او به دنبال گفت وگو با ایران است."
    },
    {
      "id": 3052,
      "imagePath": "https://localhost:44372/Uplaod/NewsPictureFolder/NewsMainPicture/322083917213095.jpg.jpg",
      "title": "اقدامات ایران غرب را پشیمان خواهد کرد",
      "description": "عضو شورای مرکزی حزب موتلفه اسلامی گفت: آمریکایی‌ها در برجام بد عهدی کردند و از آن خارج شدند، لذا مذاکره با آمریکا تعطیل است."
    },
    {
      "id": 3053,
      "imagePath": "https://localhost:44372/Uplaod/NewsPictureFolder/NewsMainPicture/215729472154856.jpg",
      "title": "ایران در برابر آمریکا باید سیاست تهاجمی به کار گیرد",
      "description": "نایب رییس جبهه پیروان خط امام و رهبری گفت: باید در سالگرد خروج آمریکا از برجام سیاست تهاجمی به کار گیریم و خیلی پذیرفته نیست که در برابر آمریکایی‌ها منفعل باشیم.\n"
    }
  ]
},
{
  "catId": 14,
  "catName": "ورزشی",
  "newsContents": [
    {
      "id": 3042,
      "imagePath": "https://localhost:44372/Uplaod/NewsPictureFolder/NewsMainPicture/226736856824855.jpeg",
      "title": "همه احتمالات درباره قفس توری " استقلال " ؛ وضعیت رحمتی و حسینی چگونه خواهد بود ؟",
      "description": "استقلال در ادوار مختلف دروازه‌بان‌های خوبی داشته و در خیلی سال‌ها کیفیت خوب هر دو دروازه‌بان از نظر فنی به نفع تیم بوده، اما مشکلات زیادی هم درست کرده است.\n\n"
    },
    {
      "id": 3043,
      "imagePath": "https://localhost:44372/Uplaod/NewsPictureFolder/NewsMainPicture/21463635040650.jpg",
      "title": "پرسپولیس ستاره استقلال را به صورت رسمی جذب کرد",
      "description": "به گزارش گروه ورزشی خبرگزاری برنا؛ با نظر مثبت برانکو، ساسان زمانه، دروازه بان تیم امید استقلال به صورت رسمی به تیم فوتبال پرسپولیس پیوست.\n\n"
    },
    {
      "id": 3044,
      "imagePath": "https://localhost:44372/Uplaod/NewsPictureFolder/NewsMainPicture/836138365621559.jpg",
      "title": "یک میلیارد به من بدهید استقلال را قهرمان کنم",
      "description": "گلر سابق استقلال نسبت به شرایط کنونی این تیم ناراضی است و از بازیکنان گلایه دارد.\n\n"
    },
    {
      "id": 3045,
      "imagePath": "https://localhost:44372/Uplaod/NewsPictureFolder/NewsMainPicture/622410699584925.jpg",
      "title": "مهره ثابت برانکو رفتنی شد",
      "description": " فصل نقل‌وانتقالات از همین حالا برای باشگاه پرسپولیس آغاز شده است."
    },
    {
      "id": 3046,
      "imagePath": "https://localhost:44372/Uplaod/NewsPictureFolder/NewsMainPicture/130684227374618.jpg",
      "title": "سکوی قهرمانی پرسپولیس در حال آماده‌سازی",
      "description": "به گزارش شریان نیوز،پرسپولیس در آستانه قهرمانی لیگ برتر قرار دارد.\n\n"
    },
    {
      "id": 3047,
      "imagePath": "https://localhost:44372/Uplaod/NewsPictureFolder/NewsMainPicture/149180200034218.jpg",
      "title": "سلطانی‌فر: زیر سؤال بردن همه چیز با یک شکست، عین بی‌انصافی و بی‌عدالتی است",
      "description": "مسعود سلطانی‌فر، وزیر ورزش و جوانان گفت: اینکه هر کسی شکست بخورد و بخواهد همه چیز را زیر سؤال ببرد، عین بی‌انصافی و بی‌عدالتی است.\n"
    }
  ]
},
{
  "catId": 1011,
  "catName": "فناوری",
  "newsContents": [
    {
      "id": 3054,
      "imagePath": "https://localhost:44372/Uplaod/NewsPictureFolder/NewsMainPicture/458855903672103.jpg",
      "title": "دستیابی به فرمولاسیون بزاق زالو برای ترمیم زخم",
      "description": "محققان کشور درصدد هستند تا فرمولاسیون سرم و کرمی که از بزاق زالوی ایرانی به دست آورده اند را برای ترمیم زخم به کار ببرند.\n\n"
    },
    {
      "id": 3055,
      "imagePath": "https://localhost:44372/Uplaod/NewsPictureFolder/NewsMainPicture/5412820294475.jpg",
      "title": "آزمایش موفقیت آمیز سپر دفاعی ایرانی برای خنثی کردن «استاکس‌نت»",
      "description": "وزیر ارتباطات و فناوری اطلاعات از موفقیت‌آمیز بودن آزمایش سپر دفاعی (فایروال) برای سیستم‌های اتوماسیون صنعتی که از سوی دانشمندان جوان ایران ساخته شده، خبر داد.\n\n"
    },
    {
      "id": 3056,
      "imagePath": "https://localhost:44372/Uplaod/NewsPictureFolder/NewsMainPicture/135842434489640.jpg",
      "title": "شرکت های فناوری در برابر محتوای خشونت آمیز اینترنت متعهد شدند",
      "description": "طرح «کریستی چرچ» در اجلاسی با حضور رهبران ۹ کشور و نمایندگان شرکت های فناوری امضا شد. در این سند قانونی شرکت‌های فناوری از جمله فیس بوک، توئیتر، گوگل به اقدامات خاص متعهد شدند.\n\n"
    },
    {
      "id": 3057,
      "imagePath": "https://localhost:44372/Uplaod/NewsPictureFolder/NewsMainPicture/364654025412296.jpg",
      "title": "عملکرد مناطق ویژه علم و فناوری بازنگری می شود",
      "description": "دبیرکل شورای عالی علوم تحقیقات و فناوری با بیان اینکه عملکرد مناطق ویژه علم و فناوری خوب نبوده گفت: عملکرد این مناطق مورد بازنگری قرار می گیرد.\n\n"
    },
    {
      "id": 3058,
      "imagePath": "https://localhost:44372/Uplaod/NewsPictureFolder/NewsMainPicture/157874084121194.jpg",
      "title": "تاکسی هوایی آلمانی برای نخستین بار آزمایش شد",
      "description": "نخستین آزمایش تاکسی هوایی متعلق به شرکت آلمانی لیلیوم انجام شد. این تاکسی هوایی الکتریکی ۳۶ موتور دارد و به طور عمودی از زمین بلند می شود و فرود می آید."
    },
    {
      "id": 3059,
      "imagePath": "https://localhost:44372/Uplaod/NewsPictureFolder/NewsMainPicture/236575355911763.jpg",
      "title": "مایکروسافت مجبور به وصله کردن ویندوزهای از رده خارج شد",
      "description": "اگر چه مایکروسافت سالهاست دیگر از ویندوز ایکس پی پشتیبانی نمی‌کند، اما خطرات روزافزون بدافزار واناکرای این شرکت را مجبور به پشتیبانی مجدد از ویندوزهای قدیمی کرده است."
    }
  ]
}

A: I'm suspicious of what the "Entities" property in these classes returns. They could easily be returning materialized lists of all entities which effectively do a "SELECT *" from the database.
Start by simplifying the problem. Remove all unknowns, abstractions, and especially that async because from what I can read of this code it isn't leveraging async. Async is something that should be catered for after a sync solution is proven, it's not a silver bullet or a performance fix.
To fetch the oldest 6 news articles by category:
using (var context = new NewsDbContext())
{
    var categoriesWithNews = context.News.GroupBy(x => x.Category)
        .Select(x => new
        {
            Category = x.Key,
            News = x.OrderBy(n => n.CreatedDate).Take(6).ToList()
        }).ToList();
}

If you want the newest 6 news articles, then replace the OrderBy with OrderByDescending.
Depending on the number of categories this could still materialize a significant amount of data. Provided this is still reasonable, we can optimize this to select just the data we need rather than the entire entities:
var baseImagePath = rootSiteData.GetNewPath() + '/';
using (var context = new NewsDbContext())
{
    var data = context.News.GroupBy(x => x.Category)
        .Select(x => new
        {
            data = new
            {
                CatId = x.Key.Id,
                catName = x.Key.Name,
                newsContents = x.OrderBy(n => n.CreatedDate)
                .Select(n => new
                {
                    id = n.Id,
                    imagePath = baseImagePath + n.ImagePath,
                    title = n.Title,
                    description = n.Description
                 }).Take(6).ToList()
        }).ToList();

    // Serialize data.
}

The above example uses anonymous types which should be sufficient if you just want to serialize the results. Alternatively you could use Select to populate your view models if that is what you want to return. (NewsContent, etc.)
The one last detail from your example was whether you want to exclude any category that doesn't have at least 6 news items under it. If this is a requirement, then add a Where clause before the final ToList():
    var data = context.News.GroupBy(x => x.Category)
        .Select(x => new
        {
            data = new
            {
                CatId = x.Key.Id,
                catName = x.Key.Name,
                newsContents = x.OrderBy(n => n.CreatedDate)
                .Select(n => new
                {
                    id = n.Id,
                    imagePath = baseImagePath + n.ImagePath,
                    title = n.Title,
                    description = n.Description
                 }).Take(6).ToList()
        })Where(x => x.newsContents.Count() == 6)
        .ToList();


text:
Q: How to change OData API paths to lowercase format? I added OData to my .NET Web API. I only use it for querying data (HttpMethod GET).
When I run my application, and I look at Swagger I see the following:

As you can see, the OData endpoints use uppercase name for the resource set which I something I really dislike. It's important to note that the endpoints work fine even in lowercase.
How can I make it so that the OData endpoints use lowercase by default to create consistency in my swagger documentation?
Thanks in advance

A: Use:
services.AddRouting(options => options.LowercaseUrls = true);

In your startup.cs


text: Q: Android Video and image Concat I have a problem, I am developing a video recording application in Android, at the end of the recording I want to include my logo image as last frame in the video, I would like to know how to do this is in Android Java, is there any sample code available for this


text:
Q: Isomorphism in a commutative diagram, variation of snake lemma Suppose I have the following commutative diagram of groups, where the hooked arrows represent injections and the double-headed arrows represent surjections. In particular, we have exactness at $B$ and $D$. I want to show that $E$ is isomorphic to $F$. Is this true? I would love a result similar to the Snake Lemma, although in this case, our rows are shifted over by one.

A: If you take $C=0$, the square is guaranteed to commute. Moreover you must have $E=B$, and if you take $B=A$, with the arrow $A\to B$ being the identity, then $E$ is equal to a subgroup of $D$ and $F$ to the quotient $\frac{D}{E}$. There is no reason that these should be isomorphic, for example it always fails if $D=\mathbb{Z}$.


text:
Q: PHP & MySQL rating script page problem? I found this script on about.com which I'm trying to learn from on how to create a rating system but the script for some reason wont count a vote when the link is clicked and will send me to a page that says not found. The page should just reload to itself and count the vote>
I was wondering how can I fix this problem? And what part of the code do I need to change and where?
Below is how the page looks like that I'm sent too.
Not Found

The requested URL /New was not found on this server.

Here is the script below.
<?php
// Connects to your Database
mysql_connect("localhost", "root", "", "sitename") or die(mysql_error());
mysql_select_db("sitename") or die(mysql_error());

//We only run this code if the user has just clicked a voting link
if ( $mode=="vote")
{

//If the user has already voted on the particular thing, we do not allow them to vote again $cookie = "Mysite$id";
if(isset($_COOKIE[$cookie]))
{
echo "Sorry You have already ranked that site
";
}

//Otherwise, we set a cooking telling us they have now voted
else
{
$month = 2592000 + time();
setcookie(Mysite.$id, Voted, $month);

//Then we update the voting information by adding 1 to the total votes and adding their vote (1,2,3,etc) to the total rating
mysql_query ("UPDATE vote SET total = total+$voted, votes = votes+1 WHERE id = $id");
echo "Your vote has been cast
";
}
}

//Puts SQL Data into an array
$data = mysql_query("SELECT * FROM vote") or die(mysql_error());

//Now we loop through all the data
while($ratings = mysql_fetch_array( $data ))
{

//This outputs the sites name
echo "Name: " .$ratings['name']."
";

//This calculates the sites ranking and then outputs it - rounded to 1 decimal
if($ratings['total'] > 0 && $ratings['votes'] > 0) {
    $current = $ratings['total'] / $ratings['votes'];
}
else{
     $current = 0;
}
echo "Current Rating: " . round($current, 1) . "
";

//This creates 5 links to vote a 1, 2, 3, 4, or 5 rating for each particular item
echo "Rank Me: ";
echo "Vote 1 | ";
echo "Vote 2 | ";
echo "Vote 3 | ";
echo "Vote 4 | ";
echo "Vote 5
";
}
?>

A: What's the value of $_SERVER['PHP_SELF'] ? Does it contain a space? You need to put quotes around the href value, and encode all HTML entities (such as &), so the last lines become like this:
echo "Vote";

A: from the php documentation:
The filename of the currently executing script, relative to the document root. For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/test.php/foo.bar would
just erase that thing and write the path to the script by yourself.


text:
Q: Plot x against y Statsmodels mixed-model result I want to plot my Statsmodels mixed-model result with X against Y, and would like some verification that I've understood it correctly. I am mostly uncertain how I should treat the fixed parameters (other_fixed_effects in the code segment), and if they should be included.
Fixed parameters:
Intercept            330.777402
Score                 39.101520
Group Var              8.264719
Group x Score Cov      0.248543
Score Var              0.007475
dtype: float64

My code:
# Load data from fitted model
parameters = final_volume_fit.params
r_effects = final_volume_fit.random_effects

# Fig size
fig = plt.figure(figsize = (16, 9))

# Fixed effects
fixed_intercept = parameters[0]
fixed_score = parameters[1]
fixed_grp_var = parameters[2]
fixed_grpxscore_var = parameters[3]
fixed_score_var = parameters[4]

# Color counter
ctr = 0

# Group represent the different stocks, j=(AAPL,...,VIAC)
for group in r_effects:

    # Random effects, intercept and slope
    group_intercept = r_effects[group][0]
    group_slope = r_effects[group][1]

    # Random and fixed effects added togheter
    # (Fixed intercept + Intercept(j))
    y_group_intercept = fixed_intercept+group_intercept

    # (Fixed slope + slope(j))
    y_group_slope = fixed_score+group_slope

    # Observed traded volume for the timeperiod
    z = corrected_data_transformed.loc[corrected_data_transformed['Stock'] == group]
    stock_dates = list(z['Date'])
    stock_volume = list(z['Transformed_Volume'])

    stock_line = []
    # Stock dates represents the timeperiod, i=(1,...,15), that observations was carried out during.
    for i in stock_dates:

        # Data point for regressionline
        data_point = y_group_intercept + y_group_slope*i

        #Should these fixed effects (other_fixed_effects) also be added to the estimation of data_point?
        other_fixed_effects = fixed_grp_var*i + fixed_grpxscore_var*i + fixed_score_var*i

        observation_ij = data_point + other_fixed_effects

        # Add estimation to regressionline
        stock_line.append(observation_ij)

    # Seaborn plot ax
    ax = sns.lineplot(x = stock_line, y = stock_volume ,
                      color = colors[ctr], label = group)

    # Increase color counter
    ctr += 1

# Plot settings
ax.set(xlabel='Regressionline', ylabel='Volume')
ax.legend(bbox_to_anchor=(0, 1), loc=2, borderaxespad=0.1)
ax.figsize = (16, 9)
ax.set_title('Regression-line for each observation X against registered volume during timeperiod Y', weight='bold').set_fontsize('16')

picture = plt.savefig('yijplot2.png', bbox_inches='tight')
plt.show()

Below is my plot:

A: Any parameter whose name ends in "Var" or "Cov" is describing the variance structure, not the mean structure.  These terms should not be added to this type of plot in the way that you have done (they are already accounted for in the internal calculation of the BLUPs for the random effects).
Originally I though you were planning to plot the fitted y against x=score.  In that case the plot should contain a line for each stock, not a non-linear path.  You are plotting the fitted values on the horizontal axis (which is unusual), and I'm not clear about what you are putting on the vertical axis.


text:
Q: Registering NLog ILogger with Simple Injector Is there any way I can get the context so I can retrieve the loggerName and use LogManager.GetLogger(loggerName) instead of LogManager.GetCurrentClassLogger()?
I noticed container.RegisterConditional() has access to the context.
Also, I want to avoid solutions like SimpleLogging.NLog for now.
Finally, I am willing to accept this is not the right approach. BTW, AOP is an option that I've already explored (Is it a good practice to have logger as a singleton?).
Note: I am aware that GetCurrentClassLogger() gets the same information I'd retrieve with .NET reflection.
using NLog;
using SimpleInjector;

namespace DependencyInjection
{
    class Program
    {
        private static Container _container;
        static void Main(string[] args)
        {
            Bootstrap();
            _container.GetInstance<Greeter>().Greet();
        }

        private static void Bootstrap()
        {
            _container = new Container();

            _container.Register<ILogger>(() => LogManager.GetCurrentClassLogger(), Lifestyle.Transient);
            _container.Register<Greeter>();

            _container.Verify();
        }

        public class Greeter
        {
            private ILogger _logger;

            public Greeter(ILogger logger)
            {
                _logger = logger;
            }

            public void Greet()
            {
                _logger.Log(LogLevel.Info, "Hello world!");
            }
        }
    }
}

A: You need to define a proxy logger which routes the message to the correct Nlog Logger. This proxy is pretty simple:
public class NLogProxy<T> : ILogger
{
    private static readonly NLog.ILogger logger =
                 LogManager.GetLogger(typeof (T).FullName);

    void ILogger.Log(string message)
    {
        logger.Log(LogLevel.Info, message);
    }
}

You can register this as

container.RegisterConditional(typeof(ILogger),
     context => typeof(NLogProxy<>).MakeGenericType(context.Consumer.ImplementationType),
     Lifestyle.Singleton, context => true);

Everywhere you need logging you only will have to inject ILogger.
As for AOP. I'm unsure what you mean by this comment

A wrapper that has to be maintained (NLog.ILogger contract is huge).

Logging is a cross cutting concern and using a decorator is a great way to apply cross cutting concerns. With a decorator it won't be possible to log every (private) function call entrance and exit but why would you want that? As you can read here you probably don't need that. The simple fact that a service is called (with the data passed to this service) and possible exceptions are logged with the complete stacktrace will be more than sufficient in most cases.
So consider this:

public interface ISomeService
{
    void DoSomething(string someParameter);
}

public class SomeServiceDecorator : ISomeService
{
    private readonly ISomeService decoratee;
    private readonly ILogger logger;

    public SomeServiceDecorator(ISomeService decoratee, ILogger logger)
    {
        this.decoratee = decoratee;
        this.logger = logger;
    }

    public void DoSomething(string someParameter)
    {
        try
        {
            this.logger.Log(string.Format("Do something called with {0}", someParameter));
            this.decoratee.DoSomething(someParameter);
        }
        catch (Exception e)
        {
            this.logger.Log(e.ToString());
            throw;
        }
    }
}

This decorator will log all function calls with the information passed to the service and will also log any exception.
But this approach would increase the number of classes by 2, so not very DRY. This problem is caused because this design is at least suboptimal. Using a design around a single open generic abstraction will totally solve this problem. You can read about this design here and here.
In this case you would have a single `LoggingDecorator' as

public class LoggingCommandHandlerDecorator<T> : ICommandHandler<T>
{
    private readonly ICommandHandler<T> decoratee;
    private readonly ILogger logger;

    public LoggingCommandHandlerDecorator(ICommandHandler<T> decoratee, ILogger logger)
    {
        this.decoratee = decoratee;
        this.logger = logger;
    }

    public void Handle(T command)
    {
        // serialize command to json and log
        this.logger.Log(serializedcommandData);
        this.decoratee.Handle(command);
    }
}

And this single decorator will log all your commands.
That's my vision of AOP....


text:
Q: How to remotely access a local parse server (parse port and server url) I made an app for my friends and I as well as a parse server. I know how to setup locally, but how do I allow us to connect remotely. I know how to setup port forwarding, but I'm not sure which port parse uses, and how to enter the serverURL in the app.

A: The port can be determined by the PORT environment variable.
If you will have a look on the index.js file of the parse server you will see the following line:
var port = process.env.PORT || 1337;

In this line parse server will try to get the port from the PORT env. variable and if not the default port will be 1337 so if you didn't specify and value under the PORT env. variable the port will be 1337
another important thing to notice is the mouthPath parameter so inside your parse server index.js you will see the following line:
var mountPath = process.env.PARSE_MOUNT || '/parse';

this line will try to get the mouthPath from the PARSE_MOUNT env. variable and it will is not exist the default will be /parse
so in your case after you deploy parse server successfully you should access it via the following URL:
http://{host}:{port}/{mouth_path}
and if you use only default values the URL will be:
http://{HOST}:1337/parse


text:
Q: Elastic Beanstalk Deploy ERROR: AttributeError :: 'NoneType' object has no attribute 'split' When I try to deploy to my Elastic Beanstalk environment I am getting this python error. Everything was working fine a few days ago.
$ eb deploy
ERROR: AttributeError :: 'NoneType' object has no attribute 'split'

I've thus far attempted to update everything to no effect by issuing the following commands:
sudo pip install --upgrade setuptools

and
sudo pip install --upgrade awscli

Here are the resulting versions I'm working with:
$ eb --version
EB CLI 3.10.0 (Python 2.7.1)

$ aws --version
aws-cli/1.11.56 Python/2.7.13rc1 Darwin/16.4.0 botocore/1.5.19

Everything looks fine under eb status
$ eb status
Environment details for: ***
  Application name: ***
  Region: us-west-2
  Deployed Version: ***
  Environment ID: ***
  Platform: 64bit Amazon Linux 2016.09 v3.3.1 running Node.js
  Tier: WebServer-Standard
  CNAME: ***.us-west-2.elasticbeanstalk.com
  Updated: 2017-03-02 14:48:29.099000+00:00
  Status: Ready
  Health: Green

This issue appears to only effect this elastic beanstalk project. I am able to deploy to another project on the same AWS account.

A: I had the same issue. Turns out that when you enable CodeCommit the CLI looks for a remote called "codecommit-origin" and if you don't have a git remote with that specific name it will throw that error.
Posting this for anyone else who stumbles upon the same issue.

A: I fixed this with eb codesource local && eb deploy, so it forgets about CodeCommit.

A: To fix this error I needed to add the following lines to my .elasticbeanstalk/config.yml
branch-defaults:
 master:
   environment: prod-api
   group_suffix: null
 staging:
   environment: staging-api
   group_suffix: null

You'll need to change the branch names and environments to what is applicable to your case (in our case we have a master branch deploying to an eb environment named prod-api).


text:
Q: Akka.NET: Restrict child actor creation in akka.net cluster to a single machine We have a particular scenario in our application - All the child actors in this application deals with huge volume of data (Around 50 - 200 MB).
Due to this, we have decided to create the child actors in the same machine (worker process) in which parent actor was created.

Currently, this is achieved by the use of Roles. We also use .NET memory cache to transfer the data (Several MBs) between child actors.

Question : Is it ok to turn off clustering in the child actors to achieve the result we are expecting?
Edit: To be more specific, I have explained the our application setup in detail, below.

*

*The whole process happens inside a Akka.NET cluster of around 5 machines

*Worker processes (which contains both parent and child actors) are deployed in each of those machines

*Both parent and child actors are cluster enabled, in this setup

When we found out the network overhead caused by distributing the child actors across machines, we decided to restrict child actor creation to the corresponding machines which received the primary request, and distribute only the parent actor across machines.
While approaching an Akka.NET expert with this problem, we were advised to use "Roles" in order to restrict the child actor creation to a single machine in a cluster system. (E.g., Worker1Child, Worker2Child instead of "Child" role)
Question (Contd.) : I just want to know, if simply by disabling cluster option in child actors will achieve the same result; and is it a best practice to do so?
Please advise.

A: Sounds to me like you've been using a clustered pool router to remotely deploy worker actors across the cluster - you didn't explicitly mention this in your description, but that's what it sounds like.
It also sounds like, what you're really trying to do here is take advantage of local affinity: have child worker actors for the same entities all work together inside the same process.
Here's what I would recommend:

*

*Have all worker actors created as children of parents, locally, inside the same process, but either using something like the child-per-entity pattern or a LOCAL pool router.

*Distribute work between the worker nodes using a clustered group router, using roles etc.

*Any of the work in that high volume workload should all flow directly from parent to children, without needing to round-trip back and forth between the rest of the cluster.

Given the information that you've provided here, this is as close to a "general" answer as I can provide - hope you find it helpful!


text:
Q: Essential Business System licensing grace period After our initial installation and configuring we are ready to migrate users over to our EBS domain.  We have installed enough device CALs to cover the organization however they must be assigned to the device manually before users can log into their computers.
Is there a way to reset the 30 compliance grace period so we can join all the computers at once then go aback and assign the CALs?  If not can we configure EBS to assign one of the available Device CALs to new computers as they joint the domain?

A: slmgr -rearm does not reset client licensing.
You can reset the grace period for activation for the servers, but once the initial 30 days are up the CAL enforcement is enabled and cannot be prolonged.
In regards to your question about assigning CALs automatically to devices. I am not sure if it could be done automatically, but you can use the script mentioned in the Blog Post link below. However I think that it is for bulk assigning CALs to users and not devices. But it could put you on the correct path.
Link to Blog Post


text:
Q: Read/Write Excel with java based API - vogella I'm trying to modify existing excel file with the JAVA Excel API vogella, but can't handle it. I found a way to recreate the excel file, but this is not what I want. Could someone to give an advice, hint or share a short example.
I'm sharing what I'm trying to do:
    /**
     * Reading external file.
     *
     * @return Record[];
     * @throws IOException;
     * @throws BiffException.
     */
    public Record[] read() throws IOException {
        File inputWorkbook = new File(inputFile);
        Workbook w;
        Record[] records = null;
        int rowsCount = 0;
        try {
            w = Workbook.getWorkbook(inputWorkbook);
            Sheet sheet = w.getSheet(0);

            int columnsCount = sheet.getColumns();
            rowsCount = sheet.getRows();
            records = new Record[rowsCount];

            for (int rowIndex = 0; rowIndex < rowsCount; rowIndex++) {
                Record record = new Record(columnsCount);
                for (int columnIndex = 0; columnIndex < columnsCount; columnIndex++) {
                    Cell cell = sheet.getCell(columnIndex, rowIndex);
                    String value = cell.getContents();
                    record.setRecordData(columnIndex, value);
                }
                records[rowIndex] = record;
            }
        } catch (BiffException e) {
            errorMessage = 1;
        }

        return records;
    }

   /**
    * Writing to existing excel file.
    *
    * @param records;
    * @throws IOException;
    * @throws WriteException;
    * @throws BiffException.
    */
    public void write(Record[] records) throws IOException, WriteException, BiffException {
        File file = new File(inputFile);
        WorkbookSettings wbSettings = new WorkbookSettings();

        wbSettings.setLocale(new Locale("en", "EN"));

        Workbook workbook = Workbook.getWorkbook(file, wbSettings);
        WritableWorkbook writableworkbook = Workbook.createWorkbook(file, workbook, wbSettings);
        WritableSheet excelSheet = writableworkbook.getSheet(0);

        createLabel(excelSheet);
        createContent(excelSheet, records);

        writableworkbook.write();
        writableworkbook.close();
    }

A: The code you're providing is written specifically to overwrite what already exists.. This line:
 for (int rowIndex = 0; rowIndex < rowsCount; rowIndex++)

will always start at row 0 and so overwrite everything that's there.
Also, earlier, you're calling:
rowsCount = sheet.getRows();

Which will tell you how many rows are already populated.  If you start populating after the last populated row, you'll keep everything that's already there.


text:
Q: Can I wake up iPhone by double tapping the screen? Can I wake up an iPhone/iPad by double tapping the screen without hacking/installing Cydia?

A: You can't do this natively as part of the built-in functions of iOS.  There are a few apps that allows knocking, one is called MacID.  I've used it for a few years and the developer is very responsive to support issues.


text:
Q: VB.Net using & _ to carry to next line Error Error 1   Operator '&' is not defined for types 'String' and 'System.Windows.Forms.TextBox'.
What is wrong with this????!??
       SQL = "UPDATE ATG_PP_QTE_HEAD SET " & _
            "PART = '" & txtPart.Text & "', " & _
            "LOCATION = '" & txtLoc.Text & "', " & _
            "DESCRIPTION = '" & txtDescription.Text & "', " & _
            "CUSTOMER = '" & txtCustID.Text & "', " & _
            "CONTACT_NAME = '" & txtContactName.Text & "', " & _
            "CONTACT_PHONE = '" & txtPhone.Text & "', " & _
            "CONTACT_EMAIL = '" & txtEmail.Text & "', " & _
            "LEAD_TIME = '" & txtLead.Text & "', " & _
            "SETUP = " & txtSetup.Text & ", " & _
            "WEIGHTPP = " & txtPCWT.Text & ", " & _
            "NOTES = '" & txtNotes.Text & "', " & _
            "LAST_MODIFIED = '" & DateTime.Now & "', " & _
            "LABOR_RATE = " & txtLabor.Text & ", " & _
            "OVERHEAD = " & txtOH.Text & ", " & _
            "GA = " & txtGA.Text & ", " & _
            "SORT_CODE = '" & txtSortCode.Text & "', " & _
            "REFERENCE = '" & txtReference.Text & "', " & _
            "PL = '" & txtPL.Text & "', " & _
            "CUST_DRAW_NO = '" & txtCustDraw.Text & "', " & _
            "COMMISSION = " & txtCommission.Text & ", " & _
            "PCWT = " & txtPCWT & _
            "WHERE QUOTE_ID = " & txtQuoteID.Text

A:
What is wrong with this????!??

Quite a bit, actually.  But let's start with the error itself...
On this line:
"PCWT = " & txtPCWT & _

You're trying to concatenate a TextBox to a String.  As the error states, you can't do that.  Perhaps you meant to use the .Text property:
"PCWT = " & txtPCWT.Text & _

Now, what else is wrong?
First, your code is highly vulnerable to SQL injection attacks.  You're going to want to use parameterized queries instead of executing user input as code.
Second, using parameterized queries will make the code a lot easier to read and support, which will make errors like this much easier to find.
Third, on this line there's a significant potential for bugs:
"LAST_MODIFIED = '" & DateTime.Now & "', " & _

Using parameterized queries will remove the culture-dependent string representations from the query and use the actual DateTime data in the query.  And you should also get into the habit of using DateTime.UtcNow instead, as having a consistent non-timezone-dependent value is going to make things a lot easier when you have to deal with multiple time zones.


text:
Q: How can I execute same code for a condition in try block without repeating code in except clause I am checking consecutive indices of a list and I want to execute same piece of code in case if the consecutive elements are not equal or if the list index is out of range.
Here's what I'm trying
for n in range(len(myList))
    try:
         if myList[n]==myList[n+1]:
             #some code
         else:
             #if they are not equal then do something
             #same code should execute if exception raised: index error  --> how do i do this?

Is there a way to do this elegantly without having to repeat the same code in the except block somehow?

A: A simple way of doing this is to just modify the if statement to check that the candidate element isn't the last one, avoiding the need for a exception clause, and keeping the code short.
    for n, i in enumerate(myList):
       if n+1 != len(myList) and i == myList[n+1]:
           #some code
       else:
           #if they are not equal then do something
           #This block will also be exicuted when last element is reached

A: for n in range(1, len(myList))
    if myList[n]==myList[n-1]:
         #some code
    else:
         #foo_bar()
#foo_bar()

A: Check out this(As Tom Ron suggested):
def foobar():
    #the code you want to execute in both case
for n in range(len(myList)):
    try:
        if myList[n]==myList[n+1]:
            #some code
        else:
            foobar()
    except IndexError:
        foobar()

A: The other answers are good for the specific case where you can avoid raising the exception in the first place. The more general case where the exception cannot be avoided can be handled a lambda function as follows:
def test(expression, exception_list, on_exception):
    try:
        return expression()
    except exception_list:
        return on_exception

if test(lambda: some_function(data), SomeException, None) is None:
    report_error('Something happened')

The key point here is that making it a lambda defers evaluation of the expression that might raise an exception until inside the try/except block of the test() function where it can be caught. test() returns either the result of the evaluation, or, if an exception in exception_list is raised, the on_exception value.
This comes from an idea in the rejected PEP 463. lambda to the Rescue presents the same idea.
(I offered the same answer in response to this question, but I'm repeating it here because this isn't exactly a duplicate question.)


text:
Q: Moving a field inside an array I have an array containing a subdocument. I need to take the fields inside this subdocument to outside the subdocument. The document is something like this.
field1: "abc"
field2: "dsf"
field3: {

    allowed-type: [
               field4: "32"
}

I need to take field 4 outside of the array allowed-type and put it under field3. I have tried the following
db.collection.find({}).forEach( function (doc) {
    doc.field3.field4 = 'doc.field3.allowed-type.field4';
db.collection.save(doc);  });

The problem is that the array allowed-type contains a hyphen so I can't refer to it without using double quotes. But when i use double quotes field4 will be assigned 'doc.field3.allowed-type.field4' as a string rather than taking the value from doc.field3.allowed-type.field4.

A: Aggregation is your solution. You will first have to unwind your document, this will basically flatten the document and take "32" out of the array. You will then need to take the returned result and project the "field4" value to a new field, which is a document under "field3". pretty() is only to present the result in a readable format.
db.fields.aggregate(
   {$unwind:"$field3.allowed-type.field4"},
   {$project:
       {field1:1,
        field2:1,
        field3:
           {field4: "$field3.allowed-type.field4"
}} }).pretty();


text:
Q: Trigger event after seconds rather than minutes I am creating a Google Script that includes this code:
ScriptApp.newTrigger("fetchTweets")
         .timeBased()
         .everyMinutes(1)
         .create();

How can I change this to trigger the event every ten seconds instead of once every minute?

A: A solution similar to this should work for you, it's working correctly in my test area:
function callSixTimes() {
  fetchTweets();
  for(var i = 1; i <= 5; i++)
  {
    Utilities.sleep(10000);
    fetchTweets()
  }
}

function generateTriggers() {

  var everyMinute = ScriptApp.newTrigger("callSixTimes")
      .timeBased()
      .everyMinutes(1)
      .create();
}

According to this post in google groups, this appears to be the recommended way to achieve this level of granularity.  Please note that even after the trigger is deleted, the function with settimeout in it may continue to fire until it finishes looping.


text:
Q: Need to Bulk Copy records from csv file to table I need to bulk copy the below records from .csv file to 3 different tables based on first field . I need to use Bulk Insert in SQL server for doing it. Also I am not sure of final record as the count of records will change (header and trailer will be same). Please assist. I have tried with Bulk Insert but it fails as the header and trailer have different columns

01,EMP,5,06-16-2018 --header
02,06-16-2018,06-16-2018,100,SMF,Debit,KK
02,06-16-2018,06-16-2018,100,LKX,Encash,SS
03,2,200 -- trailer
If 01 then copy to header table, If 02 then copy to emp table
If 03 then trailer table

A: What if you try the approach from the Importing a txt file into SQL Server with a where clause?
It says that you should create a temporary table and after bulk insert into this table you would be able to make some conditional inserts in your real tables. This approach implies that the structure of your 01, 02 and 03 records should be more or less the same, though.


text:
Q: sp_MSForEachDB Invalid Use of Side-Effecting Operator Within Function Is there anyway to put the below code into a Table-Valued (inline or multi-statement) or even a View.  I'm able to use it in a stored procedure but do to the inability to do joins to the results of stored procedures I'd rather put it in a Table-Valued function or View.
Below is the SQL that gives me the results I'm looking for
DECLARE @ColumnInformation TABLE
(
    DatabaseName NVARCHAR(255),
    TableSchema NVARCHAR(255),
    TableName NVARCHAR(255),
    ColumnName NVARCHAR(255),
    TableType NVARCHAR(255),
    FullyQualifiedTableName NVARCHAR(255),
    FullyQualifiedColumnName NVARCHAR(255)
)
INSERT INTO @ColumnInformation
EXECUTE master.sys.sp_MSForEachDB  '
IF ''?'' NOT IN (''master'', ''tempdb'', ''msdb'', ''model'', ''ReportServer'', ''ReportServerTempDB'' )
BEGIN
    USE [?];
    PRINT ''?''
    SELECT
         T.TABLE_CATALOG AS DatabaseName
        ,T.TABLE_SCHEMA as TableSchema
        ,T.TABLE_NAME AS TableName
        ,C.COLUMN_NAME AS ColumnName
        ,T.TABLE_TYPE AS TableType
        ,''['' + T.TABLE_CATALOG + ''].['' + T.TABLE_SCHEMA + ''].['' + T.TABLE_NAME + '']'' AS FullyQualifiedTableName
        ,''['' + T.TABLE_CATALOG + ''].['' + T.TABLE_SCHEMA + ''].['' + T.TABLE_NAME + ''].['' + C.COLUMN_NAME + '']'' FullyQualifiedColumnName
    FROM INFORMATION_SCHEMA.TABLES as t inner join
        INFORMATION_SCHEMA.COLUMNS as c on c.table_name = t.table_name
END
'

SELECT *
FROM @ColumnInformation
ORDER BY DatabaseName, TableSchema, TableName, ColumnName

however when I try to put it in a table valued function I'm getting the error
Msg 443, Level 16, State 14, Procedure fGetAllColumnInformation, Line 17
Invalid use of a side-effecting operator 'INSERT EXEC' within a function.

I believe that sp_MSForEachDb is generating dynamic SQL but not real sure. I vaguely remember hearing that dynamic SQL can not be used in table-valued functions.  If this is the case is there anyway of bypassing that restriction so that I can use the above code in a table-valued function or view.
If the answer to the above is no...is there any way of rewriting the statement so that it does not use dynamic SQL?
I'm basically trying to union the results of all of the INFORMATION_SCHEMA.COLUMNS from every database on a SQL Server.

A: You can't do this dynamically (as in without hard-coding all the database names in advance) without dynamic SQL, and you can't use dynamic SQL in a function. You shouldn't be using sp_MSForEachDB in any case or, IMHO, using INFORMATION_SCHEMA.
Write a stored procedure that returns the result set. If you absolutely need to join the output to other stuff (why not code that into the stored procedure?), then insert the output into a #temp table.
Try this:
CREATE PROCEDURE dbo.AllMyColumnsEverywhereForReals
AS
BEGIN
  SET NOCOUNT ON;

  DECLARE @sql NVARCHAR(MAX) = N'';

  SELECT @sql += '
  UNION ALL SELECT
      [database]  = N''' + d.name + ''' COLLATE SQL_Latin1_General_CP1_CI_AI,
      [schema]    = s.name COLLATE SQL_Latin1_General_CP1_CI_AI,
      [object]    = o.name COLLATE SQL_Latin1_General_CP1_CI_AI,
      [column]    = c.name COLLATE SQL_Latin1_General_CP1_CI_AI,
      [qualified] = QUOTENAME(''' + d.name + ''')
        + ''.'' + QUOTENAME(s.name)
        + ''.'' + QUOTENAME(c.name) COLLATE SQL_Latin1_General_CP1_CI_AS,
      [type] = CASE o.type WHEN ''U'' THEN ''Table'' ELSE ''View'' END
    FROM ' + QUOTENAME(d.name) + '.sys.columns AS c
      INNER JOIN ' + QUOTENAME(d.name) + '.sys.objects AS o
      ON c.[object_id] = o.[object_id]
      INNER JOIN ' + QUOTENAME(d.name) + '.sys.schemas AS s
      ON o.[schema_id] = s.[schema_id]
      WHERE o.type IN (''U'', ''V'')'
  FROM sys.databases AS d WHERE [state] = 0 AND name NOT IN
    (N'master',N'tempdb',N'msdb',N'model',N'ReportServer',N'ReportServerTempDB');

  SET @sql = STUFF(@sql, 1, 13, '');

  EXEC sp_executesql @sql;
END
GO

Usage:
CREATE TABLE #x
(
  db     SYSNAME,
  sch    SYSNAME,
  obj    SYSNAME,
  col    SYSNAME,
  qual   NVARCHAR(390),
  [type] CHAR(5)
);

INSERT #x EXEC dbo.AllMyColumnsEverywhereForReals;

SELECT cols FROM #x AS x -- INNER JOIN something else ON x.whatever...


text:
Q: Copying byte array to various fields in class/struct in C# In the example C# code below, I have a byte array which has been read from a socket. I want to parse the data into the various fields of 'exampleClass' (first 8 bytes into the 64-bit variable 'field1', next 4 bytes into 32-bit variable 'field2', etc.)
using System;
namespace CsByteCopy
{
  class Program
  {
    class ExampleClass
    {
      public UInt64 field1;
      public UInt32 field2;
      public UInt16 field3;
      public byte[] field4 = new byte[18];
    }

    static void Main(string[] args)
    {
      byte[] exampleData =
      {
        // These 8 bytes should go in 'field1'
        0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,
        // These 4 bytes should go in 'field2'
        0x08,0x09,0x0A,0x0B,
        // These 2 bytes should go in 'field3'
        0x0C,0x0D,
        // These 18 * 1 bytes should go in 'field4'
        0x0E,0x0F,0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F,
      };

      ExampleClass exampleClass = new ExampleClass();
      // Perform copy
    }
  }
}

It's been a long time since I last used C, but if I recall correctly, I might have been able to get away with a single memcpy() call to populate all the fields in the class. What's the most efficient way of populating the fields of 'exampleClass' in C#?

A: I think you want this:
Here by changing the buffer in field4 you also change the other 3 which are specific types.
[StructLayout(LayoutKind.Explicit, Size=8)]
struct UValue
{
   [FieldOffset(0)]
   public fixed byte field4[18]; // 18 bytes long

   [FieldOffset(0)]
   public uint64 field1;

   [FieldOffset(8)]
   public Uint32 field2

   [FieldOffset(12)]
   public Uint16 field3

}

You might want this:
Here by changing the buffer in fieldload you change the others as above but there is also another byte buffer at the end.
[StructLayout(LayoutKind.Explicit, Size=8)]
struct UValue
{
   [FieldOffset(0)]
   public fixed byte fieldload[38]; // modify this to modify others

   [FieldOffset(0)]
   public uint64 field1;

   [FieldOffset(8)]
   public Uint32 field2

   [FieldOffset(12)]
   public Uint16 field3

   [FieldOffset(14)]
   public fixed byte field4[18]; // 18 bytes long
}

A: Another option, if you can use a struct, is to Marshal the byte array directly into the structure.
struct ExampleStruct
{
    public UInt64 field1;
    public UInt32 field2;
    public UInt16 field3;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 18)]
    public byte[] field4;
}

And to get a struct for that:
var handle = GCHandle.Alloc(exampleData, GCHandleType.Pinned);
var structure = Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof (ExampleStruct));
handle.Free();

And structure will contain your data.

A: You have a lot of options, the one that turns out the best usually depends on what your program needs/can handle and exactly how much speed you want.  There are a lot of articles that explain the different ways you can populate a class or a struct with data.
Binary Serialization is one way.  That requires you write a custom serializer, which is fairly easy.  An MSDN article regarding that shows it's not too difficult.
You can write a private constructor that takes in the byte array and uses a BinaryReader or the BitConverter class to read from the byte array (you'd have to wrap it in a MemoryStream for BinaryReader) or to simply convert sections of the byte array to the values you need (BitConverter).  In the case of BitConverter you would also need to use Buffer.BlockCopy to copy the remaining data of the byte array to the byte array field in your class
A third way, also generally the fastest way, is to convert your class to a struct and use unsafe code to cast the byte array as that struct.  Something like this:
unsafe struct ExampleClass
{
   public ulong field1;
   public uint field2
   public ushort field3
   public fixed byte field4[18];

   public static ExampleClass ReadStruct(byte[] data)
   {
       fixed (byte* pb = &data[0])
       {
           return *(ExampleClass*)pb;
       }
   }
}

Of course, the above code is only valid if you can use unsafe code.  Furthermore, converting the class to a struct may also not be what you're looking for. In most cases, structs are passed by value to functions, so that calling methods copies the entire struct (in this case 32 bytes) instead of passing a reference (4 or 8 bytes, depending on CPU architecture) and can reduce the efficiency of your program. There are exceptions to structs being passed by value, and you can use your favorite search engine for that.
If you can't use unsafe code, there is also Marshal.PtrToStructure which will do the same as the above code, but about 10 times slower.  You would also need to use the MarshalAs attribute to specify the size of the array, instead of using the fixed keyword (which is unsafe).   At that point, you might as well use the BinaryReader/BitConverter, as it will be faster than the marshal class.

A: Forget the efficiency thing and make your code maintainable and readable first.  If necessary, profile and improve.
Whats wrong with using the BitConverter class.
field1 = BitConverter.ToInt64(exampleData, 0)
field2 = BitConverter.ToInt32(exampleData, 8)
field3 = BitConverter.ToInt16(exampleData, 12)
Array.Copy(exampleData, 14, field4, 0, 18)

A: And now for something completely different ...
This does not really answer the OP's question; instead it is something I cooked up to provide a way of mapping a C# struct on top of a byte array, and allow the individual fields in the underlying byte array to be both read and written. It uses unsafe code, and gets a pointer to the byte array and then casts it to a pointer to the struct that maps the fields.
This may not be all that efficient, but has the advantage of providing a symbolic mapping of the fields without the use of "magic numbers" for the lengths and offsets of the fields. But note that this will not work for data interchange with a system that uses big endian instead of little endian data representation.
The field access methods are implemented as extension methods. See TestMethod() for an example of how to use them.
This was inspired by the answer by Christopher Currens - if you find this useful please give him an upvote.
using System;
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
   [StructLayout(LayoutKind.Sequential, Pack = 1)]
   unsafe struct ExampleStruct
   {
      internal const int CField4Length = 18;

      public UInt64 Field1;
      public UInt32 Field2;
      public UInt16 Field3;
      public fixed byte Field4[CField4Length];
   }

   static unsafe class ExampleStructExtensionMethods
   {
      public static UInt64 GetField1(this byte[] byteArray)
      {
         fixed (byte* byteArrayPointer = &byteArray[0])
         {
            return (*(ExampleStruct*)byteArrayPointer).Field1;
         }
      }

      public static UInt32 GetField2(this byte[] byteArray)
      {
         fixed (byte* byteArrayPointer = &byteArray[0])
         {
            return (*(ExampleStruct*)byteArrayPointer).Field2;
         }
      }

      public static UInt16 GetField3(this byte[] byteArray)
      {
         fixed (byte* byteArrayPointer = &byteArray[0])
         {
            return (*(ExampleStruct*)byteArrayPointer).Field3;
         }
      }

      public static byte[] GetField4(this byte[] byteArray)
      {
         fixed (byte* byteArrayPointer = &byteArray[0])
         {
            byte[] field4 = new byte[ExampleStruct.CField4Length];
            for (int i = 0; i < ExampleStruct.CField4Length; i++)
               field4[i] = (*(ExampleStruct*)byteArrayPointer).Field4[i];

            return field4;
         }
      }

      public static void SetField1(this byte[] byteArray, UInt64 field1)
      {
         fixed (byte* byteArrayPointer = &byteArray[0])
         {
            (*(ExampleStruct*)byteArrayPointer).Field1 = field1;
         }
      }

      public static void SetField2(this byte[] byteArray, UInt32 field2)
      {
         fixed (byte* byteArrayPointer = &byteArray[0])
         {
            (*(ExampleStruct*)byteArrayPointer).Field2 = field2;
         }
      }

      public static void SetField3(this byte[] byteArray, UInt16 field3)
      {
         fixed (byte* byteArrayPointer = &byteArray[0])
         {
            (*(ExampleStruct*)byteArrayPointer).Field3 = field3;
         }
      }

      public static void SetField4(this byte[] byteArray, byte[] field4)
      {
         if (field4.Length != ExampleStruct.CField4Length)
            throw new ArgumentException("Byte array must have length 18", "field4");

         fixed (byte* byteArrayPointer = &byteArray[0])
         {
            for (int i = 0; i < ExampleStruct.CField4Length; i++)
               (*(ExampleStruct*)byteArrayPointer).Field4[i] = field4[i];
         }
      }
   }

   class TestProgram
   {
      byte[] exampleData =
      {
        // These 8 bytes should go in 'field1'
        0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,
        // These 4 bytes should go in 'field2'
        0x08,0x09,0x0A,0x0B,
        // These 2 bytes should go in 'field3'
        0x0C,0x0D,
        // These 18 * 1 bytes should go in 'field4'
        0x0E,0x0F,0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F,
      };

      public void TestMethod()
      {
         UInt64 field1 = exampleData.GetField1();
         UInt32 field2 = exampleData.GetField2();
         UInt16 field3 = exampleData.GetField3();
         byte[] field4 = exampleData.GetField4();

         exampleData.SetField1(++field1);
         exampleData.SetField2(++field2);
         exampleData.SetField3(++field3);
         exampleData.SetField4(new byte[ExampleStruct.CField4Length]
           { 0x42,0x42,0x42,0x42,0x42,0x42,0x42,0x42,0x42,0x42,0x42,0x42,0x42,0x42,0x42,0x42,0x42,0x42 });
      }
   }
}

A: To use classes instead of struct, you can use something like the following.  I used various elements of the above answers and put it together for a high performance class.  If you don't like all the manual coding of the Serialize/Deserialize methods, you could quite easily write a code generator that would iterate through all the fields/properties and emit the appropriate methods. Here is the code:
public interface ISerializableClass
{
    int SerializableClassSize { get; }
    StreamInflateTest Deserialize(byte[] buffer, int startOffset);
    byte[] Serialize(byte[] buffer, int startOffset);
}

public class   StreamInflateTest : ISerializableClass
{
    private const int _classSize = 10;
    public float Float32Value { get; set; }
    public Int32 Int32Value { get; set; }
    public byte Byte8Value { get; set; }
    public bool IsOk0 { get; set; }
    public bool IsOk1 { get; set; }
    public bool IsOk2 { get; set; }
    public bool IsOk3 { get; set; }
    public bool IsOk4 { get; set; }

    public StreamInflateTest()
    {
    }

    public int SerializableClassSize { get { return _classSize; } }
    public StreamInflateTest(byte[] buffer, int startOffset)
    {
        Deserialize(buffer, startOffset);
    }

    public unsafe StreamInflateTest Deserialize(byte[] buffer, int startOffset)
    {
        fixed (byte* pb = &buffer[startOffset])
        {
            Float32Value = *(float*)pb;
            Int32Value = *(int*)(pb + 4);
            Byte8Value = pb[8];
            BitField8 bitfld = new BitField8(pb[9]);
            IsOk0 = bitfld.Bit0;
            IsOk1 = bitfld.Bit1;
            IsOk2 = bitfld.Bit2;
            IsOk3 = bitfld.Bit3;
            IsOk4 = bitfld.Bit4;
        }

        return this;
    }
    public unsafe byte[] Serialize(byte[] buffer, int startOffset)
    {
        fixed (byte* pb = &buffer[startOffset])
        {
            *(float*)pb = Float32Value;
            *(int*)(pb + 4) = Int32Value;
            pb[8] = Byte8Value;
            BitField8 bitfld = new BitField8(0)
            {
                Bit0 = IsOk0,
                Bit1 = IsOk1,
                Bit2 = IsOk2,
                Bit3 = IsOk3,
                Bit4 = IsOk4
            };
            pb[9] = bitfld.Value;
        }

        return buffer;
    }
}

public struct BitField8
{
    public byte Value;

    public BitField8(byte value)
    {
        Value = value;
    }

    public bool Bit0
    {
        get { return (Value & 0x01) != 0; }
        set
        {
            if (value)
                Value |= 0x01;
            else
                Value = (byte)(Value & 0xFE);  // clear the bit
        }
    }
    public bool Bit1
    {
        get { return (Value & 0x02) != 0; }
        set
        {
            if (value)
                Value |= 0x02;
            else
                Value = (byte)(Value & 0xFD);  // clear the bit
        }
    }
    public bool Bit2
    {
        get { return (Value & 0x04) != 0; }
        set
        {
            if (value)
                Value |= 0x04;
            else
                Value = (byte)(Value & 0xFB);  // clear the bit
        }
    }
    public bool Bit3
    {
        get { return (Value & 0x08) != 0; }
        set
        {
            if (value)
                Value |= 0x08;
            else
                Value = (byte)(Value & 0xF7);  // clear the bit
        }
    }
    public bool Bit4
    {
        get { return (Value & 0x10) != 0; }
        set
        {
            if (value)
                Value |= 0x10;
            else
                Value = (byte)(Value & 0xEF);  // clear the bit
        }
    }
    public bool Bit5
    {
        get { return (Value & 0x20) != 0; }
        set
        {
            if (value)
                Value |= 0x20;
            else
                Value = (byte)(Value & 0xDF);  // clear the bit
        }
    }
    public bool Bit6
    {
        get { return (Value & 0x40) != 0; }
        set
        {
            if (value)
                Value |= 0x40;
            else
                Value = (byte)(Value & 0xBF);  // clear the bit
        }
    }
    public bool Bit7
    {
        get { return (Value & 0x80) != 0; }
        set
        {
            if (value)
                Value |= 0x80;
            else
                Value = (byte)(Value & 0x7F);  // clear the bit
        }
    }

    public bool Set(bool value, int bitNo)
    {
        if (bitNo > 7 || bitNo < 0)
            throw new ArgumentOutOfRangeException();

        if (value)
            Value |= (byte)(0x01 << bitNo);
        else
            Value = (byte)(Value & ~(0x01 << bitNo));  // clear the bit

        return value;
    }
    public bool Get(int bitNo)
    {
        if (bitNo > 7 || bitNo < 0)
            throw new ArgumentOutOfRangeException();

        return ((Value >> bitNo) & 0x01) != 0;
    }
    public bool this[int bitNo]
    {
        get { return Get(bitNo); }
        set { Set(value, bitNo); }
    }
}

A: This can be used to marshal a byte array and rotate the byte order. Handy for network messages passed up from C. Wrap your structs in a class to pass them by ref.
using System;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Net;

namespace ConsoleApp1
{
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    struct MarshalMe
    {
        private UInt16 _param1;
        private UInt32 _param2;
        private UInt16 _param3;
        private UInt16 _param4;
        public ushort Param1 { get => _param1;  }
        public uint Param2 { get => _param2;  }
        public ushort Param3 { get => _param3; }
        public ushort Param4 { get => _param4; }
    }

    class Program
    {

        static void Main(string[] args)
        {

            byte[] bytes = new byte[] {0x00, 0x03, 0x00, 0x00,  0x00, 0x04, 0x00, 0x05, 0x00, 0x00 };

            var metoo = rotateStruct<MarshalMe>(stamp<MarshalMe>(bytes));

            Console.WriteLine("{0}-{1}-{2}", metoo.Param1, metoo.Param2, metoo.Param3);

            Console.ReadKey();
        }

        private static T stamp<T>(byte[] bytes)
        {
            var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
            var structure = Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
            handle.Free();

            return (T)structure;
        }

        private static T rotateStruct<T>(object value)
        {
            FieldInfo[] myFieldInfo;
            Type myType = typeof(T);
            // Get the type and fields of FieldInfoClass.
            myFieldInfo = myType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

            foreach (var s in myFieldInfo)
            {
                if (s.FieldType.Name == "UInt16"){
                    UInt16 u16 = (ushort)s.GetValue(value);
                    u16 = (ushort)IPAddress.HostToNetworkOrder((short)u16);
                    s.SetValue(value,u16 );
                }
                else if(s.FieldType.Name == "UInt32")
                {
                    UInt32 u32 = (uint)s.GetValue(value);
                    u32 = (uint)IPAddress.HostToNetworkOrder((int)u32);
                    s.SetValue(value, (object)u32);
                }
                else if (s.FieldType.Name == "UInt64")
                {
                    UInt64 u64 = (ushort)s.GetValue(value);
                    u64 = (ulong)IPAddress.HostToNetworkOrder((long)u64);
                    s.SetValue(value, u64);
                }

            }

            return (T)value;
        }

    }
}


text:
Q: Python3 allow for custom key size using AES256 I am using AES256 in a python project, and the encryption key is entered by the user. I have no way to require the user's key to be a specific length in bytes. I am using the PyCryptodome library for AES256 and when I try to use the keys given for encryption like this:
cipher = AES.new(key, AES.MODE_EAX)
nonce = cipher.nonce
bal_encrypted, tag = cipher.encrypt_and_digest(data.encode("utf8"))

I get this error:
ValueError: Incorrect AES key length (26 bytes)

I know that AES usually required specific key lengths, but I have seen online tools that allow for AES encryption with custom key size, such as https://encode-decode.com/aes256-encrypt-online/, and I am wondering if there is a way I can implement something similar in Python3.