text:
Q: Join a table with 2 other tables which may or maynot have related rows I have 3 tables ie:

*

*products ( id, title)

*Stock_in ( product_id, qty, date)

*stock_out (product_id, qty, date)
I want to use joins to fetch a list of stock movement of each product.
I tried joining all 3 tables using basic joins,  but the problem with my query is that it returns rows for the products which have both in and out movements.
This is the best I could do, all other queries I tried were worst
SELECT  c.title, si.qty, so.qty, si.date  , so.date
   FROM `products` c, stock_in si , stock_out so
   where (c.id LIKE si.code OR c.id LIKE so.code)
   group by c.code_id

The expected result is to show rows for each product with a stock movement for each date either the in and out in the same row or 2 different rows.
Maybe join all 3 tables is a wrong approach, and I should run 2 queries each for stock in data and stock out data and then later in backend merge the rows? Will that be optimized?

A: You have not got a aggregation function, so you should not use group by but distinct. Also, you should use explicit join syntax based on left join if the rows between the table could not match.
    SELECT distinct c.title
        , si.qty
        , so.qty
        , si.date
        , so.date
    FROM `products` c
    LEFT JOIN stock_in si  ON  c.id =  si.code
    LEFT JOIN stock_out so OON c.id = so.code


text:
Q: Retry parallel API call if fail I've used the below code from this post - What is the best way to cal API calls in parallel in .net Core, C#?
It works fine, but when I'm processing a large list, some of the calls fail.
My question is, how can I implement Retry logic into this?
 foreach (var post in list)
        {
            async Task<string> func()
            {
                var response = await client.GetAsync("posts/" + post);
                return await response.Content.ReadAsStringAsync();
            }

            tasks.Add(func());
        }

        await Task.WhenAll(tasks);

        var postResponses = new List<string>();

        foreach (var t in tasks) {
            var postResponse = await t; //t.Result would be okay too.
            postResponses.Add(postResponse);
            Console.WriteLine(postResponse);
        }

This is my attempt to use Polly. It doesn't work as it still fails on around the same amount of requests as before.
What am I doing wrong?
var policy = Policy
              .Handle<HttpRequestException>()
              .RetryAsync(3);

foreach (var mediaItem in uploadedMedia)
{
    var mediaRequest = new HttpRequestMessage { *** }
    async Task<string> func()
    {
        var response = await client.SendAsync(mediaRequest);
        return await response.Content.ReadAsStringAsync();
    }
    tasks.Add(policy.ExecuteAsync(() => func()));
}
await Task.WhenAll(tasks);

redpajama_set_name: RedPajamaStackExchange


text:
Q: AsEnumerable Dynamic Fields in Where & Select I want to use the distinct clause for multiple levels. Firstly i tried with DataTable but did't got success so i converted DataTable to AsEnumerable.
My problem here is that the Fields which i have specified/hard coded will be coming dynamic, same for both Where & Select.
How to add dynamic Fields in Where & Select?
DataTable data3 = new DataTable();
var listData = data3.AsEnumerable()
               .Where(m => !String.IsNullOrEmpty(m.Field<string>("clientname"))
               && !String.IsNullOrEmpty(m.Field<string>("project"))
               && !String.IsNullOrEmpty(m.Field<string>("postedstate"))
               && !String.IsNullOrEmpty(m.Field<string>("postedcity"))
               && !String.IsNullOrEmpty(m.Field<string>("siteadd")))
               .Select(row => new
                {
                   clientname = row.Field<string>("clientname"),
                   project = row.Field<string>("project"),
                   postedstate = row.Field<string>("postedstate"),
                   postedcity = row.Field<string>("postedcity"),
                   siteadd = row.Field<string>("siteadd")
                }).Distinct();

A: You could do something similar to this:
string clientName = "my client";
string project = null;

DataTable data3 = new DataTable();
var listData = data3.AsEnumerable().Where(m =>
    (String.IsNullOrEmpty(clientName) || m.Field<string>("clientname") == clientName)
    && (String.IsNullOrEmpty(project) || m.Field<string>("project") == project)
).Select(row => new Project()
{
    clientname = row.Field<string>("clientname"),
    project = row.Field<string>("project"),
    postedstate = row.Field<string>("postedstate"),
    postedcity = row.Field<string>("postedcity"),
    siteadd = row.Field<string>("siteadd")
}).Distinct();

This way you will have no need to have an anonymous type returned and get rid of the problem.


text:
Q: Request pipe keeps a wrong header I've built a small app which downloads from a url and upload to another. Here is my code:
request(downloadRequest).pipe(request(uploadRequest));

So it is very simple but my first request needs authorization so it contains an Authorization header (Bearer) and the second one does not. However, this header remains still during the pipe and blocks the request (Authorization header not allowed).
I've tried the following code:
request(downloadRequest)
              .on('response', function(resp) {
                delete resp.headers['Authorization'];
              })

But it did not work. Do you have any idea?


text:
Q: Метод `All()` для пустой коллекции возвращает `true`: баг или фича? У меня есть класс Item
public class Item
{
    public int ParentId {get;set;}
    public int TypeId {get;set;}
    public int? AttachedFileId {get;set;}
}

Мне необходимо для каждого родителя получить признак наличия того или иного типа. Наличием считается что отсутствуют item без прикрепленного файла, написал следующий запрос:
var items = _context.Set<Items>()
    .GroupBy(x=>x.ParentId)
    .Select(x=>new
    {
        ParentId = x.Key,
        Type1 = x.Where(x=>x.TypeId==1).Any() && x.Where(x=>x.TypeId==1).All(x=>x.AttachedFileId!=null)
        //И так для каждого типа
    })

Запрос возвращает данные так как мне необходимо, но мне кажется что условие
x.Where(x=>x.TypeId==1).Any() && x.Where(x=>x.TypeId==1).All(x=>x.AttachedFileId!=null) можно переписать
Также меня смущает, что метод All для пустой коллекции возвращает true
Пример на fiddle

A: С точки зрения математики всё верно: метод All — это аналог квантора всеобщности, а для пустых множеств он всегда верен, независимо от условия.
Этот метод реализован так (за вычетом проверок):
public static bool All<TSource>(this IEnumerable<TSource> source,
                                Func<TSource, bool> predicate) {
    foreach (TSource element in source)
        if (!predicate(element))
            return false;
    return true;
}

Упростить ваше выражение что-то не очень получается. Разве что нагромоздить переменные для одного прохода, но с грубым нарушением идеи функциональщины:
bool any = false;
bool result = x.Where(x => any = x.TypeId == 1).All(x => x.AttachedFileId != null) && any;


text:
Q: Complex Solr sorting expression in 4.0 alpha I want to perform complex sorting expression for which I have upgraded to solr-aplha 4.0:
apache-solr-4.0.0-BETA/select?q=*:*&sort=map(sum(SCORE,11),77,77,sum(SCORE,33),sum(SCORE,44)) desc

But when I try to run this, it's not working.
How can I do such complex queries of Solr?

A: I have done this using max and sub functions like:
max(sub(SCORE,11),0)


text:
Q: How to check game board status in my tkinter game? I am currently making a 2 player tic-tac-toe game with tkinter, however as of now I don't know how I could check if the board had a winning situation or when to tell the victor they have won.
from tkinter import *

root = Tk()
twod = [[0 for x in range(3)] for y in range(3)]  # 0 will be blank 1 will be circle 2 will be x
rows = 0
columns = 0
types = "X"

for x in twod:
    for y in x:
        butt = Button(text=' ', width=20, height=10)
        twod[columns][rows]= butt
        butt.config(text=' ', width=20, height=10, command=lambda butt=butt : click(butt))

        butt.grid(row=rows, column=columns)
        columns += 1
    rows += 1
    columns = 0
root.mainloop()

I have deleted a few functions in there as those aren't the problem, the main problem is the control flow.
My first step is to try and check across however I have no idea where I should place it in my code.
So, to summarize my problem, there is a mainloop function in Tkinter that should be looping through the entire code. However, everything I type in there i.e. print statements, only gets executed once.

A: As @martineau suggested, you can check the board after the button click. You can use binary patterns to check for a winner.
Try this code. It fills the board with random values then checks for a win when you click a button.
from tkinter import *
import random

root = Tk()
twod = [[0 for x in range(3)] for y in range(3)]  # 0 will be blank 1 will be circle 2 will be x
rows = 0
columns = 0
types = "X"

btnlst = []

def CheckWin():
  wins = [0b111000000,0b000111000,0b000000111,0b100010001,0b001010100,0b100100100,0b010010010,0b001001001]  # all possible win patterns
  for p in ['X','O']:  # check each player
     m = int("".join(['1' if b['text'] == p else '0' for b in btnlst]),2) # merge button values into single binary value
     for w in wins: # check each pattern
        if w & m == w:  # if pattern matches  (binary and)
           print(p, 'wins')
           return
  print('No Winner')

def click(evt):
  CheckWin()

for x in twod:
    for y in x:
        butt = Button(text=' ', width=20, height=10)
        twod[columns][rows]= butt
        butt.config(text=random.choice(['X','O']), width=20, height=10, command=lambda butt=butt : click(butt))

        butt.grid(row=rows, column=columns)
        btnlst.append( butt)
        columns += 1
    rows += 1
    columns = 0
root.mainloop()


text:
Q: API Keys for REST So I'm developing a RESTful API, but I can't for the life of me understand how API keys work. I'm using PHP, which has an HMAC function, which I've read is a good way to sign requests, but what I don't understand is as follows.
I'm not suppose to send the API key to the client, but the client with HMAC is suppose to take the message, which is usually an array of elements involved in the request and the API key. How is the user/client expected to make a signature including the API key if the user isn't supposed to have the API key?

A: Have a look at how this is handled by companies who use APIs extensively. A good example is Google or Dropbox.
You will see that there is at some point some information you have to

*

*either get from some place (in the case of Google - the API Console) and use as part of the authentication (this is typically the key you are mentioning); this is usually used for application-to-application communication

*or use a user-based authentication protocol like oAuth.

In your case the way to go is oAuth, where users do not store anything themselves (there is a cookie stored for them but they are not aware of that). You can then use third-party systems (Google, Twitter, LinkedIn, ...) to handle the authentication on your behalf.

A: The API Key is usually used to identify the environment/privilages for a particular user in a multi tenant environment.
say, you have an application where you have three customers A,B and C. all the three customers have completely different settings/ use different features etc.
Now say, if you want to create a new user under customer C, the unique API key for customer C will be used to identify the settings/resources/environment/privilages for the users under C.

A: So unless I'm mistaken, I was misunderstanding the inherent concept of API keys, in that, I should be able to give the API key to a user who has authenticated their username and password and work with the key from there. I assume this isn't even the safest or best way, but after implementing HTTPS as mentioned by Parth Shah, I think most of my problems will be avoided and I can begin implementing the start of a basic authentication procedure for my API calls in which I will not be receiving the username and password.


text:
Q: Call to a member function connection() on null I am trying to create a new virtual development environment for one of my projects on Github. I have installed MariaDB, PHP 7, made a local clone of the repository, and restored its .env-file. It should be working.
Unfortunately, when I type php artisan and composer update, I receive the following error:

PHP Fatal error:  Uncaught Error: Call to a member function connection() on null in src/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:1058
  Stack trace:
  #0 src/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(1024): Illuminate\Database\Eloquent\Model::resolveConnection(NULL)
  #1 src/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(859): Illuminate\Database\Eloquent\Model->getConnection()
  #2 src/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(818): Illuminate\Database\Eloquent\Model->newBaseQueryBuilder()
  #3 src/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(802): Illuminate\Database\Eloquent\Model->newQueryWithoutScopes()
  #4 src/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(1374): Illuminate\Database\Eloquen in src/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php on line 1058

I do not know if this is relevant to the error at hand, but note the misspelling of Eloquent on stack trace #4.
You can find my composer.json file over here:
https://github.com/galadhremmin/Parf-Edhellen/blob/master/src/composer.json
PHP version: 7.1.2 on Debian 9.
Any ideas what might be wrong?
Edit This affects the artisan and composer components which won't even run.

A: I have found the root of the issue by using debug_print_backtrace. It is an excellent method which prints a full back-trace.
The issue in this case was the fact that I had attached a logging service to the exception handler. The logger would reach out to a database in order to record the error that occurred, and it did not support the CLI environment.


text:
Q: jquery datetimepicker format not working I am using bootstrap datetime picker,when I try to set format to "YYYY-MM-DD HH:MM" its not setting.When I enter date its changing to "YYYY/MM/DD HH:MM" but I need in the format "YYYY-MM-DD HH:MM".The below is my code:

$('#startDate').datetimepicker({
  dateFormat: 'YYYY-MM-DD hh:mm'
 });
<link rel="stylesheet" href="/css/jquery.datetimepicker.css"></link>
<script src="/js/jquery.js"></script>
<script src="/js/jquery.datetimepicker.full.min.js"></script>

<input name="startDate" type="text" id="startDate"/>

A: Here Working Example !!!
Html:-
<input name="startDate" type="text" id="startDate"/>

Javascript:-
$(document).ready(function(){
$('#startDate').datetimepicker({
        format: 'Y-m-d H:i'

    });
  });

Hope Its Work !!!

A: Try:
$('#startDate').datetimepicker({
    format: 'Y-m-d H:i'
});

http://jsfiddle.net/jn3j9ur3/


text:
Q: SQL authentication not authenticating in MS SQL Server 2008 When I try to connect to the SQL Server running on localhost using Windows Authentication in SQL Server Management Studio, I am able to connect but when I try to connect using SQL authentication, it says Login failed even though I know the user with the password exist on the DB. Here is the error log -
            ===================================

            Cannot connect to localhost.

            ===================================

            Login failed for user 'admin'. (.Net SqlClient Data Provider)

            ------------------------------
            For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&EvtSrc=MSSQLServer&EvtID=18456&LinkId=20476

            ------------------------------
            Server Name: localhost
            Error Number: 18456
            Severity: 14
            State: 1
            Line Number: 65536

            ------------------------------
            Program Location:

               at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
               at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
               at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
               at System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
               at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject)
               at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart)
               at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
               at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
               at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
               at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup)
               at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
               at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
               at System.Data.SqlClient.SqlConnection.Open()
               at Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.ObjectExplorer.ValidateConnection(UIConnectionInfo ci, IServerType server)
               at Microsoft.SqlServer.Management.UI.ConnectionDlg.Connector.ConnectionThreadUser()

A: Make sure that the login is created and enabled at the server level and that the login is assigned to the user in the database. Also make sure that mixed mode authentication is enabled.

A: Do not use localhost, use the name of the server. What about the firewall?


text:
Q: How do i get aproximation of a function? I have the following function :
f (t) = 0.05sin(1000t)+0.5cos(pit)-0.4*(10*t)
t are points distributed equidistantly between [0,1] for which i calculate values of f .
The following pairs (ti,f(ti)) are inputs for aproximation of function f with Lagrange and Least Squares.
This is what i tried, but doesn't seem to work, because i'm not sure if i'm doing f right
%Main function
t=linspace(0,1);
f = 0.05*sin(1000*t)+0.5*cos(pi*t)-0.4*sin(10*t);
lagrange(t,f); % returns coeficients of Lagrange polynomial of rank 1
least_squares(t,f) % returns coeficients of polynomial of rank n using least squares method

This is the lagrange function:
%Lagrange
function[L] = lagrange(x,y)
n = length(x);
lj= zeros(1,n)
Lj= zeros(n);
L=zeros(1,n);
jr=1:n;
for j=jr
    mr=jr(jr~=j);%m-range 1<=m<=n, m~=j
    lj=poly(x(mr));
    mult=1/polyval(lj,x(j));
    Lj(j,:)=mult*lj;
end
L=y*Lj;
X=-10:.1:10;
plot(x,y,'-*','linewidth',1,'markersize',5)
end

And the least_squares function:
function [yR] =least_squares(x,y)
stem(x,y);
a=[];
for i=1:length(x)
    a=[a;x(i) 1];
end
c=a/y';
yR=c(1)*x+c(2);
plot(x,yR,"-*");
end


text:
Q: wp enqueue style and style sheet depth How could I add a style sheet at the bottom of the <head> tag, so if there´s a need to override some other styles added before, it will override.
I heard something about wp_enqueue_style, and it seems there´s a depth parameter.
Is that what I need? To make my style sheet be the last one at the <head> tag?
If yes, what should I put in the parameter depth?
Thanks.

A: From the source, reformatted for better readability:
function wp_enqueue_style(
    $handle, // unique name
    $src = false, // URL
    $deps = array(), // array of dependencies, other styleheets unique names.
    $ver = false, // version
    $media = 'all' // media
)

So, $deps is an array of unique stylesheet handles. If you list the stylesheets here you want to wait for, WordPress will create the proper order automatically for you.
Example:
$template_dir_uri = get_template_directory_uri();
wp_register_style( 'style_1', "$template_dir_uri/style1.css" );
wp_register_style( 'style_2', "$template_dir_uri/style2.css" );
wp_register_style( 'style_3', "$template_dir_uri/style3.css", array ( 'style_1', 'style_2' )  );
wp_register_style( 'style_4', "$template_dir_uri/style4.css", array ( 'style_3', 'default_theme_css_handle' ) );

wp_enqueue_style( 'style_4' );

Now the <link> elements for the stylesheets will be printed in the correct order 1, 2, 3, 4.

A: You can add a priority number to the wp_enqueue_scripts action. So you could could give the action hooked to the enqueue of yourstyle sheet a priority of 999. Like so:
function high_priority_style() {
  Wp_enqueue_style('important', get_template_directory_uri() . '/css/important.css');
}
add_action('wp_enqueue_scripts', 'high_priority_style', '999');

A simpler way to do is enqueue all of your stylesheets, including style.css in the same function, hooked to wp_enqueue_scripts and they will be added in the order that they appear in the function, like this:
  function styles() {
  wp_enqueue_style('low-priority', get_template_directory_uri() . '/css/low-priority.css');
  wp_enqueue_style('theme', get_template_directory_uri() . '/style.css');
  wp_enqueue_style('important', get_template_directory_uri() . '/css/important.css');
}
add_action('wp_enqueue_scripts', 'styles');

I included a lower priority stylesheet in this example, that would be something like the CSS for a framework or grid system.
Make sure to remove any hard coded links to any stylesheets in header.php when adding styles this way (ie the right way.)


text:
Q: How does Pinterest remember what pin I was looking at after installed the app on iOS? I'll probably get hammered for making a question without code in it, but I didn't know how else to find an answer for it, and it is a programming question after all.
From what I've been researching, in order to communicate from a website to an app, you need URL-Schemes. But that doesn't work before the app is installed.
I found other questions about using cookies, but for that you need to actually open safari from the app, and again, you have to have the app installed in order to do that (plus, it seems as Apple is rejecting apps with this method).
But I noticed that Pinterest does it somehow.
Let's say I'm on Safari looking at something on Pinterest. I get a message saying "Open in Pinterest App".
I tap on that and I'm taken to the app store app where I can download Pinterest.
After installing Pinterest and opening the app, I'm taking automatically to the same pin that I was looking at on Safari.
EDIT 1:
These guys claim to do something similar.
https://blog.branch.io/introducing-the-first-universal-app-open-banner-that-deep-links-past-install/
Any thoughts?

A: I think it passes an info added on the URL scheme regarding that pin. The URL scheme will take you to the app store if the app is not installed and when you open the app, the app will parse the url scheme if there's data included on it like the pin id and will now redirect you to that pin.


text:
Q: Navigation Draw Submenu Array Error I'm trying to add an item from array to navigation draw submenu. But i could not it. My code ise here
> private void addItemsRunTime(NavigationView navigationView) {

    //adding items run time
    final Menu menu = navigationView.getMenu();
    for (int i = 1; i <= 3; i++) {
        menu.add("Runtime item "+ i);
    }

    //stringArray[0]="Selam";
    //stringArray[1]="Merhaba";
    //stringArray[2]="Merhaba";
    //stringArray[3]="Merhaba";

    // adding a section and items into it
    final SubMenu subMenu = menu.addSubMenu("SubMenu Title");
    for (int i = 0; i <= sayaca; i++) {
        subMenu.add("SubMenu Item " + i);
    }

    // refreshing navigation drawer adapter
    for (int i = 0, count = mNavigationView.getChildCount(); i < count; i++) {
        final View child = mNavigationView.getChildAt(i);
        if (child != null && child instanceof ListView) {
            final ListView menuView = (ListView) child;
            final HeaderViewListAdapter adapter = (HeaderViewListAdapter) menuView.getAdapter();
            final BaseAdapter wrapped = (BaseAdapter) adapter.getWrappedAdapter();
            wrapped.notifyDataSetChanged();
        }
    }
}

when i change my code like this "for (int i = 0; i <= myArray.length; i++)" it gives me and error.and my application is closed. Message is here.

Array is working other function. But in this now working.
thanks for your help.

A: it throws exception to your myarray.length  try to saving it in a variable then use the variable.

A: You are doing wrong thing , you must loopthrough from 0 to n-1 values and then your error will be solved because last element of array is always at (n-1)th location , so just make change like ,
for (int i = 0; i <= myArray.length-1; i++)


text:
Q: Is there a simple way to generate default forms (New, Edit, Display) for new custom Content Types I have created a number of custom content types representing different types of tasks a user will complete.
EDIT: The custom content types inherit from the built in Task content type, in case that makes any difference.
Each of them have at least one column that is unique to each Content Type, and the unique columns are Site Columns which have been added to the content types. Below is a simplified example using imaginary Content Types
Review Task
  - Title
  - Due date
  - Period Start Date (Unique to this CT)
  - Period End Date (Unique to this CT)

Payment Task
  - Title
  - Due date
  - Amount to pay (Unique to this CT)
  - Account Number (Unique to this CT)

They will all be stored in the same List, which has "Allow management of content types" selected, and each of the content types has ben added to the List, and appears on the Ribbon under "New Item".
The default forms for this list are used for every content type, and so of course do not display the correct fields based on which type of item the user creates in the list (Via the new item dropdown)
I am looking for the easiest and best way to automatically generate the forms a user could use for:

*

*New item

*Edit item

*Display item

If these can't be generated automatically from within SharePoint Online, then what is the easiest way to build these forms without a third party, paid product?
I know how to add a new form to the List within SharePoint designer, and how to then have that form show for the respective content type, but I was hoping there's a way to get SharePoint to generate the initial forms automatically.


text:
Q: Pyside2 QTextBrowser overwriteMode does not replace old text I'm using the PySide2 package and found that the overwriteMode won't work in my code. Here is what I wrote:
self.ui.textBrowser.setOverwriteMode(True)
self.ui.textBrowser.insertPlainText('test1\ntest2\ntest3')
self.ui.textBrowser.moveCursor(QTextCursor.Start)
self.ui.textBrowser.insertPlainText('hhh')

Complete source code
I used Qt-Creator to design my GUI and my settings for the QTextBrowser looks like that:
QTextBrowser settings
I got the following output:
Output
As you can see, the first line should be 'hhht1' but it gives 'hhhtest1'.
I'm testing this with PySide2 version 5.11.2 on a Windows 10.
I am new to Qt and can anyone please help me out? What am I missing? Thank you!

A: According to the documentation of the overwriteMode property:

This property holds whether text entered by the user will overwrite existing text
As with many text editors, the text editor widget can be configured to insert or overwrite existing text with new text entered by the user.

So apparently the overwriteMode affects only text entered by the user.
You probably need to do something like:
text = 'test1\ntest2\ntest3'
self.ui.textBrowser.setPlainText(text)
inserted_text = 'hhh'
text = inserted_text + text[len(inserted_text):]
self.ui.textBrowser.setPlainText(text)


text:
Q: How to query usagestatsmanager for daily, weekly or monthly usage in android? I am working one of android application in which I want to track all installed applications usage with daily, weekly, monthly and overall summary reporting options. For this I use usagestatsmanager but the result i get its not correct in daily or monthly usage. So any one plz help me out that how to query usagestatsmanager for daily, weekly or monthly usage ? The query which i use are given below :-
public List<UsageStats> stats;

for daily usage
//Calendar for query
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_WEEK, -1);

//List<UsageStats> Query UsageStatsManager for List<UsageStats>
stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, cal.getTimeInMillis(), System.currentTimeMillis());

for weekly usage
//Calendar for query
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -5);

//List<UsageStats> Query UsageStatsManager for List<UsageStats>
stats=mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_WEEKLY, cal.getTimeInMillis(), System.currentTimeMillis());

for monthly usage
//Calendar for query
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -5);

//List<UsageStats> Query UsageStatsManager for List<UsageStats>
stats=mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_MONTHLY,
cal.getTimeInMillis(), System.currentTimeMillis());


text:
Q: Facing glitch while clearing menu from Bottom Navigation View Android I have inflated .xml menu file to bottom navigation view in activity. After click instance I'm clearing old menu and passing new menu.xml file to inflate.
It is working fine but forclearing menu I am using
BottomNavigationView bottomNavigationView = findViewById(R.id.bottomView);
bottomNavigationView.getMenu().clear();

While clearing menu it is giving some glitch somewhat like flip animation before adding new menu. Can we disable menu clearing animation somehow?

A: You can try -
bottomNavigationView.setVisibility(View.GONE);


text:
Q: Liferay 6.0.5 - Including common javascript at the end of all portlets, before scripts? I'd like to load all my javascript at the bottom of each page, but in liferay, I'm limited to <header-portlet-javascript>, which places the javascript in the header.
If I include the JS manually at the bottom of each relevant JSP, I wind up duplicating a number of <script> includes.
What's the best way to achieve what I need? I have a number of portlets that all require the same set of javascript libraries, some of which are large, and I'm targetting mobile devices, so every byte counts.

A: You get access to how the whole page of HTML is generated in your theme, in templates/portal-normal.vm. Change this to adjust to your requirements.


text:
Q: How to group some records by name and pivot some values I am working on a SQL Query to group the results of a View by Id to have only one Row per Id
with a maximum of three pivoted results and keeping some columns static : TestCaseId, TestName, Test Case Num, Owner
Actually this is the Query i Created to get the Desired output but is now working as expected because the MAX is always retriving the max value so  i am getting only one row but the pivoted values are repeated to the right.

SELECT DISTINCT  TBL1.[TestName], TBL1.[Test Case Num], TBL1.[Owner], MAX(TBL1.[Browser]) as 'Column1', MAX(TBL1.[Run Date]) as 'Column2', MAX(TBL1.[Status]) as 'Column3', MAX(TBL1.[Duration]) as 'Column4', MAX(TBL1.[ErrorMsg]) as 'Column5', MAX(TBL2.[Browser]) as 'Column6', MAX(TBL2.[Run Date]) as 'Column7', MAX(TBL2.[Status]) as 'Column8', MAX(TBL2.[Duration]) as 'Column9', MAX(TBL2.[ErrorMsg]) as 'Column10', MAX(TBL3.[Browser]) as 'Column11' , MAX(TBL3.[Run Date]) as 'Column12', MAX(TBL3.[Status]) as 'Column13', MAX(TBL3.[Duration]) as 'Column14', MAX(TBL3.[ErrorMsg]) as 'Column15'
FROM (SELECT DISTINCT T1.[TestCaseId], T1.[TestName], T1.[Test Case Num], T1.[Owner], T1.[Browser], T1.[Run Date], T1.[Status], T1.[Duration], T1.[ErrorMsg]
FROM [TestRunner].[dbo].RunsRawResults T1) TBL1
cross apply (SELECT DISTINCT T2.[TestCaseId], T2.[Browser], T2.[Run Date], T2.[Status], T2.[Duration], T2.[ErrorMsg]
            FROM [TestRunner].[dbo].RunsRawResults T2
            WHERE T2.[TestCaseId] = TBL1.[TestCaseId] AND T2.[Run Date]  TBL1.[Run Date]) TBL2
cross apply (SELECT DISTINCT T3.[TestCaseId], T3.[Browser], T3.[Run Date], T3.[Status], T3.[Duration], T3.[ErrorMsg]
            FROM [TestRunner].[dbo].RunsRawResults T3
            WHERE T3.[TestCaseId] = TBL2.[TestCaseId] AND T3.[Run Date]  TBL2.[Run Date] AND  T3.[Run Date]  TBL1.[Run Date]) TBL3
            GROUP BY TBL1.[TestCaseId], TBL1.[TestName], TBL1.[Test Case Num], TBL1.[Owner]

Input -
Raw Data (Comes from the RunRawResults View)

Desired and Pivoted Output

A: Using a common table expression (cte) and row_number() we can simplify the identification and order of multiple run dates. This also lets us skip using distinct and group by.
Switching to outer apply lets us include results where there are less than 3 runs per TestCaseId.
;with cte as (
  select *
    , rn = row_number() over (
        partition by TestCaseId
        order by [Run Date]
        )
  from TestRunner.dbo.RunsRawResults
)
select
    tbl1.TestName
  , tbl1.[Test Case Num]
  , tbl1.Owner
  , tbl1.Browser
  , [Run Date]_tbl1 = tbl1.[Run Date]
  , Status_tbl1     = tbl1.Status
  , Duration_tbl1   = tbl1.Duration
  , ErrorMsg_tbl1   = tbl1.ErrorMsg
  , Browser_tbl2    = tbl2.Browser
  , [Run Date]_tbl2 = tbl2.[Run Date]
  , Status_tbl2     = tbl2.Status
  , Duration_tbl2   = tbl2.Duration
  , ErrorMsg_tbl2   = tbl2.ErrorMsg
  , Browser_tbl3    = tbl3.Browser
  , [Run Date]_tbl3 = tbl3.[Run Date]
  , Status_tbl3     = tbl3.Status
  , Duration_tbl3   = tbl3.Duration
  , ErrorMsg_tbl3   = tbl3.ErrorMsg
from cte as tbl1
  outer apply (
    select
        i.[Run Date]
      , i.Status
      , i.Duration
      , i.ErrorMsg
    from cte as i
    where i.TestCaseId = tbl1.TestCaseId
      and i.rn = 2
   ) as tbl2
  outer apply (
    select
        i.[Run Date]
      , i.Status
      , i.Duration
      , i.ErrorMsg
    from cte as i
    where i.TestCaseId = tbl1.TestCaseId
      and i.rn = 3
   ) as tbl3
where tbl1.rn = 1


text:
Q: Texmaker define xelatex - asymptote - xelatex command With texmaker there is a possibility to compile a document with pdflatex-asymptote-pdflatex

My aim is to define a similaire command but with xelatex engine, usually
 I use xelatex
xelatex -synctex=1 -interaction=nonstopmode %.tex

I have asymptote in C:/texlive/2017/bin/win32/asy.exe
Minimal Example
\documentclass[12pt]{article}
\usepackage{fontspec}
\usepackage[inline]{asymptote}
\setmainfont{Amiri}

\begin{document}

\centering

\begin{asy}
draw ((0,0) -- (100,100));
\end{asy}

\end{document}

A: Yes, you can define Quickbuild to do the sequence you prefer. Once you opened the preferences you go to Quick Build. There you chose "User defined" and click on the Wizard.

Now you simply add the steps you'd like texmaker to perform in the sequence you prefer.
I hope that helped. :)


text:
Q: How the stdin, stdout, stderr are closed In most modern programming languages, programmers don't need to close the stdin,stdout,stderr. Does it mean that the operating system will handle the close of the stdin, stdout, stderr in general?
Or for instance in java, the jvm will close the stdin, stdout, stderr when the running Java program exit?
There might be exceptions like some old programmers mentioned, so hereby I narrow down the language spectrum to Java, C, C++ only

A: Almost all programs run under a C run-time, so upon normal termination the rules of the C exit() function should apply. Per 7.22.4.4  The exit function of the C Standard:

Description
The exit function causes normal program termination to occur.  No
  functions registered by  the at_quick_exit function  are  called.  If  a  program  calls  the exit function more than once, or calls
  the quick_exit function in addition to the exit function, the
  behavior is undefined.
First, all functions registered by the atexit function are called,
  in the reverse order of their  registration, except  that  a  function
  is  called  after  any  previously  registered functions that had
  already been called at the time it was registered.  If, during the
  call to any such function, a call to the longjmp function is made
  that would terminate the call to the registered function, the behavior
  is undefined.
Next,  all  open  streams  with  unwritten  buffered  data  are
  flushed,  all  open  streams  are closed, and all files created by the
  tmpfile function are removed.
Finally, control  is  returned  to  the  host  environment.   If the
  value  of status is  zero  or EXIT_SUCCESS, an
  implementation-defined form of the status
  successful termination is returned.  If the value of status is EXIT_FAILURE, an implementation-defined form of  the  status
  unsuccessful  termination is  returned.   Otherwise  the  status  returned  is implementation-defined.

For any process that's not running under a standards-compliant C runtime, what happens upon process termination would be implementation-defined.

A: Your question is highly system specific. First of all, these terms have multiple meanings. Let's take the specific examples of eunuchs-variants.  There, each process is a copy of parent process. It is normal for shells to set up file numbers 0, 1, and 2 set up for the child process when it runs.
These "files" are referred to as stdin, stdout, and stderr.
C programers have two layers of libraries. In eunuchs variants, you can access the system services like read or write that operate on a file idea. In addition, the standard C library has function layered upon these (e.g. fread and fwrite) that do buffer. It also defines symbols stdin, stout, and stderr which that reference structures the serve as arguments for the f_____ file function. Somewhere, embedded in these structures is the file number.
So, just in eunuchs-land, your question has two answers depending if you are referring to stdio et al. as file numbers or as symbols created by the c library?
If you are referring to the library symbols, the library has to be set up to handle program exit to flush the buffer.
If you are referring to the file numbers, that has to be handled by the operating system.


text:
Q: iOS App change universal to iPhone only We have a app that was submitted as a universal app with support for all devices iPad and iPhone but we no longer want it to show in the store as a iPad app we want it to just be a iPhone only app.
This app was built with Appcelerator so i have changed the app tiapp.xml details to only support iPhone no longer universal, but it will not submitted to the store.
I can't upload the existing app because the family group in the bundle Id. it won't accept removing the iPad.
How can we remove the app from being listed as a iPad app really important as the app was not built with iPad in mind it would be fine if it was just a scaled up version of the app.
Any help please?

A:
Developers who wish to issue updates, but remove device support, have
  three choices:
Fix their app so that it can work on the devices they originally set
  out to support. Target a newer version of iOS that requires a newer
  device. Remove their app from the store, and upload the new app with a
  different bundle ID.


text:
Q: Installing a vim color scheme After some research, I've discovered that in order to properly install you need to create a .vim directory inside of the path represented by the $VIMRUNTIME variable from this StackOverflow post. When I go into that directory to create said directory, I get denied permission to do so. When I try chmod the directory, nothing happens still. What is the proper way to do this?

A: Unfortunately you're misinterpreting the post you linked to. You would create a .vim directory in your home directory, which is what the ~ (tilde) means.
Then within that directory you should create a colors directory, and put your colorscheme files there.
At that point, a :colorscheme command should find the file automatically.

A: TL;DR: use $HOME/.vim to store your vim related files.
Long version: read http://vimdoc.sourceforge.net/htmldoc/usr_05.html

A: You would typically only put the syntax files under $VIMRUNTIME if you are an administrator and want them available to all users.
For your own use, put it/them under .vim/colors from your home directory.


text:
Q: Windows 7 installation asks for DVD drivers I have installed Windows XP on my machine (Company CQ5020NL). Before I was able to do that, I set the SATA controller to IDE in the bios.
Now I want to install Windows 7 upgrade. The DVD boots into the installation setup, but when I click "Install now" and am asked to load "A required CD/DVD drive device".
When I click "Browse" I can browse the installation dvd and the drive I want to install to.
I have tried all the SATA options in the bios already.
I have no idea what to do... can anybody help me out?

A: If this is an upgrade dvd, and since you are booting off it, are you sure it isn't just asking you for the original Operating System disk (ie XP), to prove that you are indeed upgrading a machine and not installing on a new System?

A: Usual causes are: Most likely to least likely

*

*Source file used to burn the disc was corrupt

*A corrupt burn of the disc

*Damaged disc from supplier
Solutions:
Download the file again and burn another one.
Re burn the disc with the same source file, maybe on different media and burner.
Purchase a new disc.
.
Some have reported installing the image to a USB flash drive using this tool and install by booting from the flash drive solved the issue also.


text:
Q: error while creating shared object (so ) in gcc While trying to create a shared object in gcc i got this error
NMateLib.o: In function `set_interface_attribs':
NMateLib.c:(.text+0xbac): undefined reference to `__stack_chk_fail_local'
NMateLib.o: In function `set_blocking':
NMateLib.c:(.text+0xc45): undefined reference to `__stack_chk_fail_local'
ld: NMateLib.so: hidden symbol `__stack_chk_fail_local' isn't defined
ld: final link failed: Bad value

What wil be the problem?


text:
Q: Trouble drawing a sine curve in TikZ I'm trying to draw a sine function going out from a particular point. When I use {sin(x r)} it gives kinked lines. When I use this code I get a lot of errors that say "Package pgf Error No shape named (0 is known.
Package TikZ Error Giving up on this path. Did you forget a semicolon?.
Here is my code:
\foreach \x in {0, ..., 16}
 \draw ((0.05+\x), (3.1+{sin(((pi*\x)/4) r)})) to [out=90*\x, in=(90*(1+\x))] ((0.5+(\x+1)*.25), ({sin((pi*(\x+1)/4) r)}+3.1));

Any advice is greatly appreciated.


text:
Q: Регулярное выражение для одиночных кавычек Задача: нужно найти строки, которые заключены в одинарные ' кавычки, причём, если перед такой кавычкой стоит слэш \, такую кавычку следует пропустить.
Пример:
'abc \' def'

Я уже прочитал ответ на аналогичный случай и попытался переделать данное выражение под свой. Но, как в ответе, так и в моём адаптированном регулярном выражении имеется баг. Если строка содержит два подряд идущих символа " в оригинальном выражении, или ' в моём, она разбирается некорректно:
''value = 'abc \' def'

Результатом разбора такой строчки должны быть строки '' и 'abc \' def'.
Есть ли вообще возможность сделать это используя только регулярные выражения?

A: С использованием негативных просмотров назад составил следующее выражение:
(?<!\\)'(?<txt>.*?)(?<!\\)'

где (?<!\\)' обозначает кавычку и не предшествующий ей слеш. Далее собственно именованная маска для текста, и опять кавычка с негативным просмотром назад.


text:
Q: careers doesn't allow images in markdown or preview broken I wanted to add a "Programmer Bookshelf" section to my CV but neither
[![alt desc][1][2]]

  [1]: image url
  [2]: amazon link

 or

Work when saved, despite working in the live preview
Update:
I currently have the following in my Background section:

but on http://careers.stackoverflow.com/sam-hasler it's rendered as:

Background

A: Works OK for me, confirmed on careers (although here is the same, because careers and SO have the same code paths). I think your syntax is slightly wrong, though.

[![THE GOGLES!][1]][2]

[1]: https://www.google.com/intl/en_ALL/images/logo.gif
[2]: http://google.com


text:
Q: relation between QEventloop and QAbstractEventDispatcher What is the relation between QEventloop and QAbstractEventDispatcher ?

Event loop is a loop that runs the event dispatcher until the loop is broken.

But in Documentation of QEventLoop there is no single method that takes an QAbstractEventDispatcher  as argument.

A: Why should there be a method in QEventLoop that takes a Subclass of QAbstractEventDispatcher?
In every application, or more precise in every thread there is only one QAbstractEventDispatcher subclass instance which is only processing incomint system/Qt events and dispatches them to the Q(Core)Application. The QAbstractEventDispatcher is only a helper, it isn't listening to events, it has to be triggered, for example by a QEventLoop. The Eventloop is basically a infinite loop which uses the thread global event dispatcher to dispatch events if need be.
I hope that clears it up a little.


text:
Q: Properties of stalks, only using the categorical definition I am taking some time to reflect on the slogan "the universal property encapsulates all you need to know"; any reference or comment on this is very welcome.
Let $x$ be a point of a topological space $X$. Let $\mathcal F$ be a presheaf (or a sheaf if need be) on $X$.
Assuming that

*

*$\mathcal F$ takes values in a category where elements make sense

*the stalk $\mathcal F_x$ is by definition the colimit on the filtered/directed category indexed by open neighbourhoods $U$ of $x$,

can we easily infer from the universal property that

*

*any element of $\mathcal F_x$ comes from one of the $\mathcal F(U)$

*two "functions" have the same stalk at $x$ if and only if their restrictions to a common open set $U$ coincide

without knowing the usual construction?
I was only able to find on page 5 of Sheaf theory, Tennison that the converse is true (a cocone with those properties will be a universal cocone) in the category of sets..
Thank you.

A: This is more to be seen as a hint: For a sheaf of sets the answer to your first question is particularly easy: assume there is a element in $f \in \mathcal{F}_x$ that doesnt come from some $\mathcal{F}(U)$ and now take $ \mathcal{F}_x \cup \{1\}$ where $1$ should be seen as an arbitrary element that wasn't already in $\mathcal{F}_x$ now proof that $ \mathcal{F}_x \cup \{1\}$ still commutes with all maps but there are at least two maps from $ \mathcal{F}_x \to \mathcal{F}_x \cup \{1\}$ .
For the 2. question the if direction is easy, for only if assume there is no such open set then all the maps $\mathcal{F}(U)\to \mathcal{F}_x$ are not injective (for $U$ small enough) and you can construct "another" stalk $\mathcal{F}'_x$ which has one element more. Suppose $f,g$ are the elements in question. We know that they get maped to the same element in $\mathcal{F}_x$ under the maps $\varphi_U$ (here I assume that $U\subset V\cap W$ where $V,W$ are the sets where $f,g$ come from). Now define the maps $\varphi'_U :\mathcal{F}(U)\to \mathcal{F}_x\cup \{*\} $ by
$$ \varphi'_U(x)= \begin{cases}  * \qquad \text{ if } x \in res_{U',U}^{-1}(g_{\vert U'}) \text{ for some } U'\subset U\\
\varphi_U(x)\qquad \text{else } \\\end{cases}. $$
Now a map $\alpha: \mathcal{F}_x\to \mathcal{F}_x\cup \{*\}$ with the property $\alpha\circ \varphi_U=\varphi'_U$ cant exist because $f,g$ get send to the same element by $\varphi_U$ and therefore by $\alpha\circ \varphi_U$ but to different elements by $\varphi_U'$.


text:
Q: Purchase issue with Revenue Cat (SwiftUI) "The receipt is not valid" I have been trying to test In App purchases (Auto Renewable Subscriptions) to be specific and I always see "The receipt is not valid"
In this regard, as soon as the purchase completes I would like to write true to a bool value called premium
I have first tried to check whether the user is already subscribed at app launch and do the same logic if the user is subscribed (unlock premium)
Here is my code for the same
application didFinishlaunchingWithOptions
  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {

      // Init other stuff
       Purchases.configure(withAPIKey: Config.REVENUE_CAT_API_KEY)
       checkAllPurchases()
}

checkAllPurchases()
 func checkAllPurchases(){
        Purchases.shared.purchaserInfo { (purchaseInfo, err) in
            print("Purchase info :", purchaseInfo?.entitlements.all)
            if(err != nil){
                if purchaseInfo?.entitlements["allaccess"]?.isActive == true {
                    UserDefaults.standard.setValue(true, forKey: "premium")
                }
            }
            else{
                self.purchaseError = err?.localizedDescription ?? ""
                //print(err?.localizedDescription)
            }
        }
    }

purchase()
This gets called when the buy button is clicked
func purchase (productId : String?){
        guard productId != nil else {
            return
        }
        var skProduct : SKProduct?

        Purchases.shared.products([productId!]) { (skProducts) in
            if !skProducts.isEmpty{
                skProduct = skProducts[0]

                print("SKProduct:", skProducts[0].productIdentifier)
            Purchases.shared.purchaseProduct(skProduct!) { (transaction, purchaseInfo, error, userCancelled) in
                // If successfull purchase

                if (error == nil && !userCancelled){
                    UserDefaults.standard.setValue(true, forKey: "premium")
                }
                else if (error != nil && !userCancelled){
                    self.purchaseError = error?.localizedDescription ?? ""
                    if let err = error as NSError? {
                        print("Error: \(err.userInfo)")
                        print("Message: \(err.localizedDescription)")
                        print("Underlying Error: \(String(describing: err.userInfo[NSUnderlyingErrorKey]))")
                    }
                }
            }
            }
        }
    }

There is an open issue Here but seems like it is only the case with StoreKit file and not the physical sandbox testing
I have this issue for both the cases and now I don't know how to test my in app purchases

A: Usually the 'receipt is not valid' error indicates an error with some iOS / Xcode configuration. I would confirm:

*

*You've followed the StoreKit test guide (valid for simulator and device): https://docs.revenuecat.com/docs/apple-app-store#ios-14-only-testing-on-the-simulator

*You're using the latest RevenueCat Purchases SDK

*You've re-uploaded the StoreKit certificate after making any changes to products or code-signing

*You've confirmed the Bundle ID and shared secret are set correctly for your app

*All of your products in the StoreKit file are listed in the RevenueCat dashboard

Additionally, if you're using any other third-party purchasing SDK's they could be interfering with the validation process.


text:
Q: Python - Implementing Custom exceptions I have a project that I need to run and have no idea how to implement custom exceptions. It mostly does complicated scientific functions, to be vague.
Mostly it will be raising exceptions if something is not set.  I've been given this as a starting example from runnables.
    # Define a class inherit from an exception type
class CustomError(Exception):
    def __init__(self, arg):
        # Set some exception infomation
        self.msg = arg

try:
    # Raise an exception with argument
    raise CustomError('This is a CustomError')
except CustomError, arg:

# Catch the custom exception
print 'Error: ', arg.msg

I have no idea how this is meant to work or how I am meant to implement my code.  It's not very explicit.
To give an idea of a basic exception that needs created.
In a function:
if self.humidities is None:
        print "ERROR: Humidities have not been set..."
        return

Apparently this needs to raise/throw an exception instead.

A: A ValueError looks suitable for your humidities example.
if self.humidities is None:
    raise ValueError('Humidities value required')

If you want to be specific:
class HumiditiesError(Exception):
    pass

def set_humidities(humidities):
    if humidities is None:
        raise HumiditiesError('Value required')

try:
    set_humidities(None)
except HumiditiesError as e:
    print 'Humidities error:', e.message

This defines a subclass of Exception named HumiditiesError. The default behavior seems sufficient for your example, so the body of the class is empty (pass) as no additional nor modified functionality is required.
N.B. Python 2 assumed. In Python 3 you would access elements of the e.args tuple.


text:
Q: Measuring forecast accuracy We're forecasting sales data for one of our clients on a weekly basis. Sales is forecasted for each organizational unit.
The sales data is forecasted via different algorithms and/or algorithm parameters.
So, for every organizational unit, about 10 different forecasts are generated. Now I want to find the best forecast/algorithm to be chosen as the weekly forecast based on the accuracy of each algorithm of the past 9 weeks.
So for each algorithm there is data like:
Org Unit     Algorithm      Date          Actual       Forecast
-----------------------------------------------------------------
OU1          A1             2013-07-25    100          110
OU1          A1             2013-07-24    100          120
OU1          A1             2013-07-23    130          130
OU1          A1             2013-07-22    140          170
OU1          A1             2013-07-21    110          130
OU1          A1             ...           ...          ...
OU1          A2             2013-07-25    100          102
OU1          A2             2013-07-24    100          108
OU1          A2             2013-07-23    130          120
OU1          A2             2013-07-22    140          122
OU1          A2             2013-07-21    110          130
OU1          A2             ...           ...          ...

Based on the sample data shown above I need to decide whether to choose A1 or A2. What would you suggest?
Standard deviation on the mean absolute error plus average of MAE?
Theil's U?
P.S. It does not matter whether the forecast is below or above the actual, only the absolute deviation needs to be considered.

A: While there are many possible model selection criteria one could use here, perhaps the most basic and widely used error statistic is the root mean square error (RMSE),
\begin{equation}
RMSE=\sqrt{\frac{\sum_{i=1}^n{(y_i-\hat{y}_i)^2}}{n}}.
\end{equation}
It is very reasonable to choose a model such to minimize this criterion, given no other information on the algorithms used to generate the predictions.
Now, in the case that you are 'fitting' your algorithm; i.e. you are estimating parameters for use in the predictions, you may want to do something like cross-validation where you test the algorithm by predicting data you leave out in the fitting process. See here. And in the case of parametric statistical models, information criteria are widely used; see here and here. These statistics balance the goodness-of-fit of the model and the complexity of the algorithm used to make the predictions.


text:
Q: angular2-meteor with PrimeNG I am working on a project with Angular-Meteor and it is working great. As my starting point I made use of https://github.com/Urigo/angular2-meteor-base. Now I would like to install PrimeNG as my UI. The documentation on http://www.primefaces.org/primeng/#/setup says I need a module manager like webpack or system.js to bind the dependencies. None of them exists on the angular-meteor-base project. I don't even understand how that works, because even on the Angular2 page, the boilerplate example contains a module loader. How does the module management works on Angular-Meteor base example, and how can I add PrimeNG.
Thank you

A: Remember that Meteor already includes its own package / plugin / module manager (do not confuse them with Angular "modules").
In particular, it works well with npm now, so a simple import {myModule} from "primeng/primeng"; statement should work. Of course, make sure you have installed primeng through npm (command npm install primeng --save), as mentioned in the setup page you link to.
Meteor will then automatically include the required scripts into your app bundle.
Then you are left with including the appropriate CSS and related images / fonts. I think webpack automatically handles the links within CSS to images and fonts (do not know for SystemJS), but it is not the case with Meteor.
A simple workaround is to copy them into your public folder, with the appropriate subfolder(s) structure (like public/images/ or public/fonts/, depending on how these assets are placed relatively with the original CSS files).
As for the CSS files themselves, just include them anywhere in your client folder, and Meteor will bundle them.


text:
Q: List with function, how to understand how new list created How does this code work?. It creates a new list that doesn't affect the original list in the code?
def changeit(lst):
    lst[0] = "Michigan"
    lst[1] = "Wolverines"
    return lst

mylst = ['106', 'students', 'are', 'awesome']
newlst = changeit(list(mylst))
print(mylst)
print(newlst)

A: Wrapping mylst in another list() function creates a new object rather than applying the operations to the original list object.
Note this would not work, for example, if the list contained sub-lists - operations done on the sub-lists would also affect the sub-lists in the original list.
deepcopy could be used for lists with sub-lists.

A: It happens when the list([iterable]) constructor is called here:
newlst = changeit(list(mylst))

It constucts a new list object in memory. If you remove it, then you will have the output:
>>> newlst = changeit(mylst)
>>> print(mylst)
>>> print(newlst)

['Michigan', 'Wolverines', 'are', 'awesome']
['Michigan', 'Wolverines', 'are', 'awesome']

A: *

*I will give you one hint.

*As you can see in case when you just simply assign it to another variable they both are pointing to same object in this case mylst and a are pointing to same object so modifying either one will change other.

*In case of b when you use list function it creates new object of mylst. You can varify this by comparing id of mylst,a and b
mylst = ['106', 'students', 'are', 'awesome']
a = mylst # reference of mylst
b = list(mylst) # copy of mylst

print(id(mylst) == id(a))
print(id(mylst) == id(b))

output:
True
False


text:
Q: Best practice to work with the same web service from different subdomains I have web application with multiple client UI's (Desktop browser application, mobile, tablet, reporting etc.). All of them are html-css-javascript applications, that retrieve data via REST web services.
Most of the web services are used across applications, and only few of them are dedicated to one application.
I want to make the applications separated by subdomains:
webservices.mydomain.com
www.mydomain.com
mobile.mydoaim.com
reporting.mydomain.com

What is the best practice for doing that and maintain ajax calls, despite the different url "locations"?

A: Your AJAX calls can be to the server hosting the page and internally that server can make a b2b call to the actual REST service (mobile.mydomain.com, reporting.mydomain.com etc). You don't have to call the cross domain URL from the UI. Just proxy it through the server hosting the page.


text:
Q: DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'Disp_id' public partial class dispmgmt : System.Web.UI.Page
{
    String strConnString = ConfigurationManager.ConnectionStrings["CallcenterConnectionString"].ConnectionString;
    SqlConnection con = new SqlConnection();
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button2_Click1(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            gvbind();
        }

            GridView1.Visible = true;
            this.BindData();

        String strConnString = ConfigurationManager.ConnectionStrings["CallcenterConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(strConnString);
        con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = " Select DISTINCT CallType, Format, Disposition, SUbDisposition  from CallCenter..Loy_DispMstr where CallType=@CallType and Format=@Format and Disposition = @Disposition and  SubDisposition =@Disposition";
        SqlDataAdapter da = new SqlDataAdapter();
        DataTable dt = new DataTable();
        cmd.Parameters.AddWithValue("@CallType", ddlCalltype.SelectedValue);
        cmd.Parameters.AddWithValue("@Format", ddlFormat.SelectedValue);
        cmd.Parameters.AddWithValue("@Disposition ", ddlDisp.SelectedValue);
        cmd.Parameters.AddWithValue("@SubDisposition", ddlSubdisp.SelectedValue);
        cmd.Connection = con;
        cmd.ExecuteNonQuery();
        da.SelectCommand = cmd;
        da.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();

    }

    protected void ddlCalltype_SelectedIndexChanged(object sender, EventArgs e)
    {

        if (ddlCalltype.SelectedIndex != 0)
        {

            String strConnString = ConfigurationManager.ConnectionStrings["CallcenterConnectionString"].ConnectionString;

            SqlConnection con = new SqlConnection(strConnString);
            SqlCommand cmd = new SqlCommand();
            SqlDataAdapter sda = new SqlDataAdapter();
            DataSet dsFormat = new DataSet();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "Select Formatid,Formatdetail,dispformat  From loy_Formatdetail with (nolock) Where isactive='1' and memberstatus = 'Member' order by FormatDetail";
            cmd.Connection = con;
            sda.SelectCommand = cmd;
            sda.Fill(dsFormat);

                ddlFormat.DataValueField = "DISPFORMAT";
                ddlFormat.DataTextField = "FORMATDETAIL";
                ddlFormat.DataSource = dsFormat.Tables[0];
                ddlFormat.DataBind();
                ddlFormat.Items.Insert(0, "<----Select---->");

        }
        else
        {
            ddlFormat.Items.Clear();

        }

    }
    protected void ddlFormat_SelectedIndexChanged(object sender, EventArgs e)
    {

        if (ddlFormat.SelectedIndex != 0)
        {

            String strConnString = ConfigurationManager.ConnectionStrings["CallcenterConnectionString"].ConnectionString;

            SqlConnection con1 = new SqlConnection(strConnString);

            con1.Open();
            SqlCommand cmd = new SqlCommand();
            SqlDataAdapter sda = new SqlDataAdapter();
            DataSet dsDisp = new DataSet();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "Select DISTINCT Disposition from CallCenter..Loy_DispMstr where CallType=@CallType and SUBFormat=@Format";
            cmd.Parameters.AddWithValue("@CallType", ddlCalltype.SelectedValue);
            cmd.Parameters.AddWithValue("@Format", ddlFormat.SelectedItem.Text);
            cmd.Connection = con1;
            cmd.ExecuteNonQuery();

            sda.SelectCommand = cmd;
            sda.Fill(dsDisp);

            ddlDisp.DataTextField = "Disposition";
            ddlDisp.DataValueField = "Disposition";

            ddlDisp.DataSource = dsDisp.Tables[0];
            ddlDisp.DataBind();

            ddlDisp.Items.Insert(0, "<----Select---->");
            ddlDisp.Focus();
        }
    }

    protected void ddlDisp_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlDisp.SelectedIndex != 0)
        {
            String strConnString = ConfigurationManager.ConnectionStrings["CallcenterConnectionString"].ConnectionString;

            SqlConnection con = new SqlConnection(strConnString);
            SqlCommand cmd=new SqlCommand();
            SqlDataAdapter sda = new SqlDataAdapter();
            DataSet dsSubDisp = new DataSet();

            using (cmd = new SqlCommand("Select distinct CallType,Disposition,SubDisposition,Format from  Loy_DispMstr where CallType=@CallType and SUBFormat=@Format and Disposition = @disposition", con))
            {
                cmd.Parameters.AddWithValue("@CallType",ddlCalltype.SelectedValue);
                cmd.Parameters.AddWithValue("@Format", ddlFormat.SelectedValue);
                cmd.Parameters.AddWithValue("@disposition", ddlDisp.SelectedValue);
                con.Open();
                cmd.ExecuteNonQuery();

            }
            sda.SelectCommand = cmd;
            sda.Fill(dsSubDisp);
               {

                    ddlSubdisp.DataTextField = "SubDisposition";
                    ddlSubdisp.DataValueField = "SubDisposition";
                    ddlSubdisp.DataSource = dsSubDisp.Tables[0];
                    ddlSubdisp.DataBind();

                    ddlSubdisp.Items.Insert(0, "<----Select---->");
                    ddlSubdisp.SelectedIndex = 0;
                    ddlSubdisp.Focus();

               //     ddlDisp.Items.Insert(1, "ADD NEW VALUE");
                //    ddlDisp.SelectedIndex = 1;
                //    ddlDisp.Focus();

                }
            }
         /*   if (ddlDisp.SelectedItem.Text == "ADD NEW VALUE" )
                   {
                        TextBox1.Visible = true;
                        TextBox2.Visible = true;
                   }*/
        }

    protected void ddlSubdisp_SelectedIndexChanged(object sender, EventArgs e)
    {
        String strConnString = ConfigurationManager.ConnectionStrings["CallcenterConnectionString"].ConnectionString;

        SqlConnection con = new SqlConnection(strConnString);

        SqlDataAdapter sda = new SqlDataAdapter();
        DataSet dsOut = new DataSet();

        SqlCommand cmd = new SqlCommand("select PID,Memberstatus,calltype,format,disposition,subdisposition, man_data,creation_date,createdby,updation_date,updatedby from Loy_SubPlaceholder");
            cmd.Connection = con;
            sda.SelectCommand = cmd;
            sda.Fill(dsOut);
            ddlDisp.DataSource = dsOut.Tables[0];
            ddlDisp.DataValueField = "subdisposition";
            ddlDisp.DataTextField = "subdisposition";
            ddlDisp.DataBind();
            con.Open();

            cmd.ExecuteNonQuery();

    }
   private void BindData()
    {
        String strConnString = ConfigurationManager.ConnectionStrings["CallcenterConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(strConnString);
        con.Open();

        string query = " Select DISTINCT Disp_id ,CallType, Format, Disposition, SUbDisposition  from CallCenter..Loy_DispMstr where CallType=@CallType and Format=@Format and Disposition = @Disposition and  SubDisposition =@Disposition";
        SqlDataAdapter da = new SqlDataAdapter();
        DataTable dt = new DataTable();
        SqlCommand cmd = new SqlCommand(query);
        cmd.CommandType = CommandType.Text;

        cmd.Parameters.AddWithValue("@CallType", ddlCalltype.SelectedValue);
        cmd.Parameters.AddWithValue("@Format", ddlFormat.SelectedValue);
        cmd.Parameters.AddWithValue("@Disposition ", ddlDisp.SelectedValue);
        cmd.Parameters.AddWithValue("@SubDisposition", ddlSubdisp.SelectedValue);
        cmd.Connection = con;
        cmd.ExecuteNonQuery();
        da.SelectCommand = cmd;
        da.Fill(dt);
        GridView1.DataSource = dt;

        GridView1.DataSource = GetData(cmd);
        GridView1.DataBind();
    }

    private DataTable GetData(SqlCommand cmd)
    {
        string strConnString = ConfigurationManager.ConnectionStrings["CallcenterConnectionString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(strConnString))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    Session["dstablegvassign"] = dt;
                    return dt;
                }
            }
        }
    }
    protected void gvbind()
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from  dbo.Loy_DispMstr", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        con.Close();
        if (ds.Tables[0].Rows.Count > 0)
        {
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
        else
        {
            ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
            GridView1.DataSource = ds;
            GridView1.DataBind();
            int columncount = GridView1.Rows[0].Cells.Count;
            GridView1.Rows[0].Cells.Clear();
            GridView1.Rows[0].Cells.Add(new TableCell());
            GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
            GridView1.Rows[0].Cells[0].Text = "No Records Found";
        }

    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
        Label lbldeleteid = (Label)row.FindControl("lblID");
        con.Open();
        SqlCommand cmd = new SqlCommand("delete FROM dbo.Loy_DispMstr where Disp_id='" + Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString()) + "'", con);
        cmd.ExecuteNonQuery();
        con.Close();
        gvbind();

    }

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        gvbind();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int Disp_id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
        GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
        Label lblID = (Label)row.FindControl("lblID");
        //TextBox txtname=(TextBox)gr.cell[].control[];
        TextBox textCallType = (TextBox)row.Cells[0].Controls[0];
        TextBox textFormat = (TextBox)row.Cells[1].Controls[0];
        TextBox textDisposition = (TextBox)row.Cells[2].Controls[0];
        TextBox textSUBDisposition = (TextBox)row.Cells[3].Controls[0];
        //TextBox textadd = (TextBox)row.FindControl("txtadd");
        //TextBox textc = (TextBox)row.FindControl("txtc");
        GridView1.EditIndex = -1;
        con.Open();
        //SqlCommand cmd = new SqlCommand("SELECT * FROM detail", conn);
        SqlCommand cmd = new SqlCommand("update detail set CallType='" + textCallType.Text + "',Format='" + textFormat.Text + "',Disposition='" + textDisposition.Text + "',SUBDisposition='" + textSUBDisposition.Text + "'where id='" + Disp_id + "'", con);
        cmd.ExecuteNonQuery();
        con.Close();
        gvbind();
        //GridView1.DataBind();
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        gvbind();
    }

   protected void Button4_Click(object sender, EventArgs e)
   {
       string disp = TextBox1.Text.Trim();
       if (!string.IsNullOrEmpty(disp))
       {
           ddlDisp.Items.Add(new ListItem(disp, disp));
       }
   }

A: You probably are using Disp_id somewhere in the GridView, like <%# Eval("Disp_id") %> or DataKeyNames="Disp_id". This does mean that Disp_id must be present in every database result set that is bound to the GridView.
And it's at least missing in the query inside Button2_Click1


text:
Q: execute C++ from String variable it is possible in C++ to execute the C++ code from string variable.
Like in Javascript:
var theInstructions = "alert('Hello World'); var x = 100";

var F=new Function (theInstructions);

return(F());

I want something very similar like Javascript in C++. How to do that ?

A: Directly, no. But you can:

*

*write that string to a file.

*invoke the compiler and compile that file.

*execute the resulting binary.

A: C++ is a compiled language. You compile C++ source into machine code, the executable. That is loaded and executed. The compiler knows about C++ (and has all the library headers available). The executable doesn't, and that is why it cannot turn a string into executable code. You can, indeed, execute the contents of a string if it happens to contain machine code instructions, but that is generally a very bad idea...
That doesn't mean that it wouldn't be possible to do this kind of run-time compilation. Very little (if, indeed, anything) is impossible in C++. But what you'd be doing would be implementing a C++ compiler object... look at other compiler projects before deciding you really want this.
Interpreted languages can do this with ease - they merely have to pass the string to the interpreter that is already running the program. They pay for this kind of flexibility in other regards.

A: No, C++ is a static typed, compiled to native binary language.
Although you could use LLVM JIT compilation, compile and link without interrupting the runtime. Should be doable, but it is just not in the domain of C++.
If you want a scripting engine under C++, you could use for example JS - it is by far the fastest dynamic solution out there. Lua, Python, Ruby are OK as well, but typically slower, which may not be a terrible thing considering you are just using it for scripting.
For example, in Qt you can do something like:
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QScriptEngine engine;
    QScriptValue value = engine.evaluate("var a = 20; var b = 30; a + b");

    cout << value.toNumber();

    return a.exec();
}

And you will get 50 ;)

A: You will need to invoke a compiler to compile the code. In addition, you will need to generate some code to wrap the string in a function declaration. Finally, you'll then somehow need to load the compiled code.
If I were doing this (which I would not) I would:

*

*Concatenate a standard wrapper function header around the code

*Invoke a compiler via the command line (system()) to build a shared
library (.dll on windows or .so on linux)

*Load the shared library and map the function

*Invoke the function

This is really not the way you want to write C code in most cases.

A: You can use Cling as C++ interpreter.
I created small CMake project for easier Cling integration: C++ as compile-time scripting language (https://github.com/derofim/cling-cmake)

A: Short answer is no. Hackers would have a field day. You can however use the Windows IActiveScriptSite interface to utilize Java/VB script. Google IActiveScriptSite, there are numerous examples on the web. Or you can do what I am currently doing, roll your own script engine.


text:
Q: How do you use an interface as data type for a property (from the value stack) in a Struts 2 action? I have never used Struts before, so am not sure what I'm trying to do is possible.
I have an Action class, which has a MyType property:
public class Action /* extends ... */ {
  private MyType myType;
  // getters and setters and other members omitted

  public String doStuff() {
    myType.foo(); // NPE
    // ...
  }
}

I refactored the code (to implement the decorator pattern, blissfully unaware of Struts and its inner workings) and made MyType an interface, with MyTypeImpl providing its implementation.
Now, when the action gets called, myType is null, when in the past, it held an instance of MyType (now MyTypeImpl).
So, my question is basically: can I make Struts play nicely with that set-up, i.e. make it use MyTypeImpl for the property of MyType in the Action class, without having to change the actual web page? (In other words, how do I make this work while keeping the number of changes required to a minimum?)
Seeing how we have struts2-spring-plugin on the classpath, I assume Spring is injecting the value for myType at the end of the day, which makes me hopeful that it can somehow be configured? Update 3: After looking furhter into this, I don't think it has anything to do with Spring. Struts creates the properties automatically via value stuck from user input. These properties don't seem to be wired by Spring. (If they were, they'd be prototypes, but I don't see how their fields would be populated.) MyType is not a service bean!
Update: Here is an extract from Spring's config - it doesn't seem relevant as it doesn't mention MyType:
<bean id="Action" class="com.example.Action" scope="prototype">
    <property name="fooService" ref="fooService"/>
    <property name="barService" ref="barService"/>
</bean>

The snippet from the Struts config file that's relevant:
  <constant name="struts.objectFactory" value="org.apache.struts2.spring.StrutsSpringObjectFactory" />
  <constant name="struts.objectFactory.spring.autoWire" value="name" />
  <!-- ... -->

  <action name="doStuff" class="Action" method="doStuff">
  <!-- several interceptors called, among them -->
  <interceptor-ref name="store"><!-- ... --><interceptor-ref/>
  <interceptor-ref name="paramsPrepareParamsStack">
  <!-- according to http://struts.apache.org/docs/interceptors.html this calls
       ParametersInterceptor which is probably involved in the instantiation of it all… -->
  <!— several results defined —>
</action>

Can anyone with Struts experience say if what I am trying to do (have Struts use the implementation instead of the interface when injecting the object) is generally possible (e.g. by using annotations on MyType myType)? If the only way round this is to change Spring's autowiring type, is it possible to restrict that by package/class?
Update 2:
Spring might actually have very little to do with it all. In the website's source code, there is a form that has fields similar to these:
<input type="text" name="myType.foo" />
<input type="text" name="myType.bar" />

I haven't got the JSP in front of me, but I'm assuming it will actually use struts jsp tag library, e.g.
<s:textfield name="myType.foo" label="Random string" />

I have seen that if I used implements ModelDriven, I could specify
@Override
public MyType getModel() {
  return new MyTypeImpl();
}

However, that would "flatten" the properties from MyTypeImpl on the ValueStack, and if I understand correctly, I'd have to change the form elements' names accordingly, e.g. from myType.foo to simply foo for it to work. I can't do that; I need a solution that doesn't require me changing the forms/JSP.
Is there a way for the "normal"/regular (i.e. non-ModelDriven) approach to also define what object gets instantiated for MyType by Struts2?

A: Struts delegates autowiring of action bean to Spring. (Without entering in Struts internals and saying many words). Everything else is managed by Spring. Struts only calls Spring with certain parameters used by configuration.
If you ever used Spring, then you should know how autowiring works. I.e. you need to have configured a bean being autowired. By placing annotation @Autowired or use @javax.inject.Inject that Spring supports too.
public class Action /* extends ... */ {

  @Autowired
  private MyType myType;
  // getters and setters and other members omitted

  public String doStuff() {
    myType.foo(); // NPE
    // ...
  }
}

Then configure the bean (in Spring) of type MyType. That's it. In case if you have multiple implementation of the same type add the name to the component or the qualifier that allows to resolve ambiguity.


text:
Q: Checking the type of a SQL column in C# I have searched around here and found some threads relating to this problem but they didn't helped me. I need to check the type of a SQL column in a certain datatable and compare it. So let's say I have a column called "CustomerName" and this is a varchar in SQL. Then I want to compare it with a string or something else which is "varchar" and check if this matches. For example it should fail when my column has the type numeric and the string the value "varchar". I think the case with the string is a bad idea (for example when I've got varchar(50) and compare it to "varchar"). Is there a way to do that?

A:     SqlDataReader read = command.ExecuteReader();
    while (read.Read())
    {
        for (int i = 0; i < read.FieldCount; i++)
        {
            Type dataType = read.GetFieldType(i);
            if (dataType == typeof(int))
            {
                // Do for integers (INT, SMALLINT, BIGINT)
            }
            else if (dataType == typeof(double))
            {
                // Do for doubles (DOUBLE, DECIMAL)
            }
            else if (dataType == typeof(string))
            {
                // Do for Strings (VARCHAR, NVARCHAR)
            }
            else if (dataType == typeof(DateTime))
            {
                // Do for DateTime (DATETIME)
            }
            else if (dataType == typeof(byte[]))
            {
                // Do for Binary (BINARY, VARBINARY, NVARBINARY, IMAGE)
            }
        }
    }

A: You may try like this:
System.Type myType = reader.GetFieldType(value);
switch (myType.GetTypeCode(myType))
{
    case TypeCode.String:
        break;
    // and so on ........
}


text:
Q: Convergence with respect to a specific norm implied by convergence in measure Let $\mathcal{M} $ be the class of measurable functions on $[a,b]$ which are finite almost everywhere(a.e).
For $f \in \mathcal{M}$ define $\rho(f)= \int_a^b \frac{\lvert f \rvert}{\lvert f \rvert +1}dx .$
Show that
$ \quad \forall \epsilon >0 \quad \lim_{n \rightarrow \infty} m(\{x \in [a,b] : |f_n(x)- f(x)| \geq \epsilon  \})=0$ $\quad \Rightarrow \quad   \rho(f_n-f) \rightarrow 0 $ as $n \rightarrow \infty$ a.e (pointwisely)
Actually the converse is also true, but I could manage to show that. But the above direction is more difficult. I tried to use the fact that Convergence in measure means there exist a subsequence which is convergent. But I could not go anywhere from this fact.
How do I start to prove the above statement and can you give me a path  to handle the rest?

A: Consider the set $E = E_n= \{ x : |f_n(x) - f(x)| \ge \epsilon \}$. Then $\rho(f_n - f) \le \int_{E} 1dm + \int_{E^C} |f_n - f| dm$.


text:
Q: Vectorizing Indexing in R I am trying to index in a large data frame. The sdata frame has 3 million observations and 26 variables (at bottom).
setsize <- 6
eccent <- 150
ctrX <- 400
ctrY <- 300

xyrotate <- function(x,y,ctrX,ctrY,angle){
  distX <- x - ctrX;
  distY <- y - ctrY;
  radians <- angle * (pi/180);
  rotX <- ctrX + (distX*cos(radians)) - (distY*sin(radians));
  rotY <- ctrY + (distX*sin(radians)) + (distY*cos(radians));
  coordinates <- list("X" = rotX,"Y" = rotY)
  return(coordinates)
}

loc <- data.frame(x = numeric(setsize),
              y = numeric(setsize))
loc$x[1] <- ctrX
loc$y[1] <- ctrY - eccent
for(i in 2:setsize){
  coord <- xyrotate(loc$x[1], loc$y[1],ctrX,ctrY,(i-1)*(360/setsize))
  loc$x[i] <- coord$X
  loc$y[i] <- coord$Y
}
gazedist <- matrix(nrow=nrow(sdata), ncol = setsize)
for(d in 1:setsize){
  x <- sdata$RIGHT_GAZE_X-loc$x[d]
  y <- sdata$RIGHT_GAZE_Y-loc$y[d]
  gazedist[,d] <- sqrt(x^2+y^2)
}
sdata$gdist_T <- 0
sdata$gdist_T <- gazedist[ ,sdata$t_targLoc]

The last line here causes R to crash.  Is there some way to plug in the values of sdata$t_targLoc[i] into the d value of gazedistance[i,d]. The for loop equivalent would be:
for(i in 1:length(gazedist)){
   sdata$gdist_T[i] <- gazedist[i,sdata$t_targLoc[i]]
}

But that will be slow in R...
sdata structure
structure(list(RIGHT_GAZE_X = c(409.5, 409.6, 409.5, 409.4, 409.3,
409.2, 409.1, 409, 408.9, 408.8), RIGHT_GAZE_Y = c(291.9, 291.5,
290.9, 290.3, 290.3, 290.3, 289.8, 289.2, 288.7, 288.8), RECORDING_SESSION_LABEL = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "ET101", class = "factor"),
    t_block = c(3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), t_trialNum = c(129L,
    129L, 129L, 129L, 129L, 129L, 129L, 129L, 129L, 129L), t_subjNum = c(101L,
    101L, 101L, 101L, 101L, 101L, 101L, 101L, 101L, 101L), t_colCond = structure(c(1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "green", class = "factor"),
    t_targLoc = c(3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), t_targID = structure(c(1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "L", class = "factor"),
    t_targShape = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L), .Label = "diamond", class = "factor"), t_singLoc = c(5L,
    5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L), t_singPres = structure(c(1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "P", class = "factor"),
    t_singDist = c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), t_singAngle = c(120L,
    120L, 120L, 120L, 120L, 120L, 120L, 120L, 120L, 120L), t_targAngle = c(120L,
    120L, 120L, 120L, 120L, 120L, 120L, 120L, 120L, 120L), t_RESP = structure(c(1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "L", class = "factor"),
    t_ACC = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), t_RT = c(686.1062,
    686.1062, 686.1062, 686.1062, 686.1062, 686.1062, 686.1062,
    686.1062, 686.1062, 686.1062), TRIAL_START_TIME = c(1031031L,
    1031031L, 1031031L, 1031031L, 1031031L, 1031031L, 1031031L,
    1031031L, 1031031L, 1031031L), TIMESTAMP = c(1031030, 1031032,
    1031034, 1031036, 1031038, 1031040, 1031042, 1031044, 1031046,
    1031048), IP_START_TIME = c(1031031L, 1031031L, 1031031L,
    1031031L, 1031031L, 1031031L, 1031031L, 1031031L, 1031031L,
    1031031L), currtime = c(0, 2, 4, 6, 8, 10, 12, 14, 16, 18
    ), currsamp = c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), gdist_T = c(0,
    0, 0, 0, 0, 0, 0, 0, 0, 0), gdist_S = c(0, 0, 0, 0, 0, 0,
    0, 0, 0, 0), gdist_NS = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)), .Names = c("RIGHT_GAZE_X",
"RIGHT_GAZE_Y", "RECORDING_SESSION_LABEL", "t_block", "t_trialNum",
"t_subjNum", "t_colCond", "t_targLoc", "t_targID", "t_targShape",
"t_singLoc", "t_singPres", "t_singDist", "t_singAngle", "t_targAngle",
"t_RESP", "t_ACC", "t_RT", "TRIAL_START_TIME", "TIMESTAMP", "IP_START_TIME",
"currtime", "currsamp", "gdist_T", "gdist_S", "gdist_NS"), row.names = 53170:53179, class = "data.frame")

A: It seems like you want to grab the ith row and the sdist$$t_targLoc[i] column of gazedist. There is a built-in for that. Use:
sdata$gdist_T <- gazedist[cbind(1:nrow(gazedist),sdata$t_targLoc)]

Here's an example:
m <- matrix(1:25,nc=5)
m
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    6   11   16   21
# [2,]    2    7   12   17   22
# [3,]    3    8   13   18   23
# [4,]    4    9   14   19   24
# [5,]    5   10   15   20   25
v <- c(1,3,5,2,4)
m[cbind(1:5,v)]
# [1]  1 12 23  9 20

BTW, your first for loop can be replaced by:
loc <- as.data.frame(xyrotate(ctrX,ctrY-eccent, ctrX,ctrY,(1:(setsize-1))*360/setsize))
loc <- rbind(c(X=ctrX,Y=ctrY-eccent),lloc)

Your second for loop can be replaced by, e.g.,
f <- function(x,y) {
  x <- sdata$RIGHT_GAZE_X-x
  y <- sdata$RIGHT_GAZE_Y-y
  sqrt(x^2+y^2)
}
ggazedist <- mapply(f, loc$x, loc$y)
identical(gazedist,ggazedist)
# [1] TRUE

A: Yeah, I think this works. Essentially you want to get a vector out of a matrix, where the row indices are 1:nrow(sdat) and the column indices are sdata$t_targLoc. This isn't built-in (that I know of), but we can convert the matrix to a vector and grab the right values.
gazedist_vals = as.vector(gazedist)
rows = 1:nrow(sdat)
cols = sdat$t_targLoc
indices = (cols - 1) * nrow(gazedist) + rows
sdata$gdist_T = gazedist_vals[indices]

I think that will do what you want.
Your data excerpt doesn't illustrate this very well since t_targLoc is always 3. Here's a little illustration:
x = matrix(c(5,2,65,8,4,2), nrow = 2)
x
#      [,1] [,2] [,3]
# [1,]    5   65    4
# [2,]    2    8    2
as.vector(x)
# [1]  5  2 65  8  4  2
rows = c(1, 1, 2)
cols = c(3,2,1)
inds = (cols - 1) * nrow(x) + rows
as.vector(x)[inds]
# [1]  4 65  2

One comment: your question is thorough, but minimal examples are often preferable. You gave us 26 columns of data, of which only one a few were needed. You gave us functions and code to calculate distances, when you could have just given a distance matrix (and then only one data column would be necessary). A small example like my x matrix and rows and cols vectors might have been all you needed to show the problem.

A: You can, but I doubt you'll save much time unless you figure out a way to completely vectorize. In other words, you would have to avoid using functionals like apply or sapply, which are all based on for loops in C and hence not that much faster than normal for loops, if at all.
someFunction <- function(x) ifelse(x %in% seq(0, 50000, 100), 1, 0)

# Here you have "vectorized" the indexing
system.time(sapply(1:nrow(diamonds), someFunction))
# 2.6 elapsed secs

## vs here where you're just using a for loop

system.time(
for(i in 1:nrow(diamonds)) {
  k[i] <- someFunction(i)
}
)
# 2.7 elapsed secs


text:
Q: Which vuetify file do I download to include in my project I want to add vuetify to my project, but it can only be added by downloading files.
I have downloaded vuetify.min.css and vuetify.min.js
What other files do I need to download?

A: If you are using the Vue CLI then you can just add it like so:
vue add vuetify
The doc: https://vuetifyjs.com/en/getting-started/installation/#vue-cli-install
It also contains other installation methods if that one doesn't suit you, if you want to install it manually I think there are only these two (as seen in the code working with the CDNs), but maybe you'll want to use de Material Design Icons then you need to download that as well.