text:
Q: How to log or replay lines or instructions executed immediately before a crash Often I have to debug crashing C++ programs on Windows where I can reproduce the crash, but it is hard to determine what sequence of instructions in the code caused the crash (e.g. another thread overwriting memory of the crashing thread). Even a call stack does not help in that case. Usually I resort to narrowing down the crash cause by commenting out sections of the source code, but this is very tedious.
Does anyone know a tool for Windows that can report or replay the last few source code lines or machine code instructions executed in all threads immediately before a crash? I.e. something like the reverse debugging capability of gdb or something like Mutek's BugTrapper (which no longer is available). I am looking for a released and stable tool (I am aware of SoftwareVerify's 'Bug Validator' and Hexray's IDA Pro 6.3 Trace Replayer, both of which still are in closed beta programs).
What I already tried were the WinDbg trace commands wt and ta @$ra, but both commands have the disadvantage that they stop automatically after a few seconds. I require trace commands that run until the crash happens, and that trace all threads of the running program.
NOTE: I am not looking for a debug tool designed to fix a particular problem, like gflags, pageheap, Memory Validator, Purify, etc. I am looking for released and stable tool to trace or replay at the instruction level.

A: In case you face with another thread overwriting memory of the crashing thread it is useful to use gflags (GFlags and PageHeap ). Instead of telling you a few lines that has been executed before a crash it will tell you exactly the place where your algorithm has overwriten a correctly allocated block of memory.
You first activate this type of check:
gflags /p /enable your_app.exe /full or
gflags /p /enable your_app.exe /full /backwards
Check that you have activated correctly
gflags /p
run you application and collect dump files
and then disable checking with gflags:
gflags /p /disable your_app.exe

Update 1
It does not immediately detect problems like *p = 0; where p is an invalid pointer
At least some problems are detected.
For example:
#include <stdio.h>
int main(int argc, char *argv[])
{
  int *p = new int;
  printf("1) p=%p\n",p);
  *p = 1;
  delete p;
  printf("2) p=%p\n",p);
  *p = 2;
  printf("Done\n");
  return 0;
}

When I run with gflags enabled I get a dump file and the problem is correctly identified:
STACK_TEXT:
0018ff44 00401215 00000001 03e5dfb8 03dfdf48 mem_alloc_3!main+0x5b [c:\src\tests\test.cpp\mem_alloc\mem_alloc\mem_alloc.3.cpp @ 11]
0018ff88 75f8339a 7efde000 0018ffd4 77bb9ef2 mem_alloc_3!__tmainCRTStartup+0x10f [f:\dd\vctools\crt_bld\self_x86\crt\src\crtexe.c @ 586]
0018ff94 77bb9ef2 7efde000 2558d82c 00000000 kernel32!BaseThreadInitThunk+0xe
0018ffd4 77bb9ec5 004013bc 7efde000 00000000 ntdll!__RtlUserThreadStart+0x70
0018ffec 00000000 004013bc 7efde000 00000000 ntdll!_RtlUserThreadStart+0x1b

STACK_COMMAND:  ~0s; .ecxr ; kb

FAULTING_SOURCE_CODE:
     7:   printf("1) p=%p\n",p);
     8:   *p = 1;
     9:   delete p;
    10:   printf("2) p=%p\n",p);
>   11:   *p = 2;
    12:   printf("Done\n");
    13:   return 0;
    14:
    15: }

Update 2
Another example from @fmunkert:
#include <stdio.h>

int main()
{

        int *p = new int;
        printf("1) p=%p\n",p);
        *p = 1;
        p++;
        printf("2) p=%p\n",p);
        *p =  2;   // <==== Illegal memory access
        printf("Done\n");
        return 0;

}

gflags /p /enable mem_alloc.3.exe  /full /unaligned
STACK_TEXT:
0018ff44 00401205 00000001 0505ffbe 04ffdf44 mem_alloc_3!main+0x52 [c:\src\tests\test.cpp\mem_alloc\mem_alloc\mem_alloc.3.cpp @ 12]
0018ff88 75f8339a 7efde000 0018ffd4 77bb9ef2 mem_alloc_3!__tmainCRTStartup+0x10f [f:\dd\vctools\crt_bld\self_x86\crt\src\crtexe.c @ 586]
0018ff94 77bb9ef2 7efde000 2577c47c 00000000 kernel32!BaseThreadInitThunk+0xe
0018ffd4 77bb9ec5 004013ac 7efde000 00000000 ntdll!__RtlUserThreadStart+0x70
0018ffec 00000000 004013ac 7efde000 00000000 ntdll!_RtlUserThreadStart+0x1b

STACK_COMMAND:  ~0s; .ecxr ; kb

FAULTING_SOURCE_CODE:
     8:         printf("1) p=%p\n",p);
     9:         *p = 1;
    10:         p++;
    11:         printf("2) p=%p\n",p);
>   12:         *p =  2;   // <==== Illegal memory access
    13:         printf("Done\n");
    14:         return 0;
    15:
    16: }

Unfortunatelly The /unaligned option might result in the fact that a program will not work properly (How to use Pageheap.exe):

Some programs make assumptions about 8-byte alignment and they stop
  working correctly with the /unaligned parameter. Microsoft Internet
  Explorer is one such program.

A: I found a solution: "replay debugging" using VMware Workstation and Visual Studio 2010. Setting it up takes a lot of time, but you are rewarded with a Visual Studio C++ debugger that can debug backwards in time. Here is a video that demonstrates how replay debugging works: http://blogs.vmware.com/workstation/2010/01/replay-debugging-try-it-today.html.
A drawback of the solution is that VMware seemingly has discontinued replay debugging in the latest VMware versions. Furthermore, only certain processor types seem to support replaying. I have not found any comprehensive list of supported processors; I tested the replay features on three of my PCs: replaying did not work on a Core i7 200; replaying worked on a Core2 6700 and on a Core2 Q9650.
I really hope that VMware reconsiders and introduces replay debugging again in future VMware Workstation versions, because this really adds a new dimension to debugging.
For those of you who are interested, here is a description how you can set up an environment for replay debugging:
In the description below, "local debugging" means that Visual Studio and VMware are installed on the same PC. "Remote debugging" means that Visual Studio and VMware are installed on different PCs.

*

*Install Visual Studio 2010 with SP1 on the host system.

*Make sure Visual Studio has been configured to use Microsoft's symbol servers. (Under "Tools | Options | Debugging | Symbols").

*On the host system, install "Debugging Tools for Windows".

*Install VMware Workstation 7.1. (Version 8.0 no longer contains the replay debugging feature). This will also install a plug-in into Visual Studio.

*Install a virtual machine (VM) on VMware with Windows XP SP3.

*If the application under test is a debug build, install the Visual Studio debug DLLs on the VM. (See http://msdn.microsoft.com/en-us/library/dd293568.aspx for instructions how to do that, but use a "Debug" configuration instead of "Release").

*Copy "gflags.exe" from the host's "Debugging Tools for Windows" directory to the VM, run gflags.exe on the VM, select "Disable paging of kernel stacks" under the "System Registry tab" and press OK. Reboot the VM.

*Copy all EXE and DLL files of the application under test to the VM and make sure that you can start the application and reproduce the problem.

*Shutdown the VM and create a snapshot (via context menu item "Take Snapshot" in VMware Workstation).

*(Only for remote debugging:) Start the following command on the Visual Studio PC and enter an arbitrary passcode:
C:\Program Files\VMware\VMware Workstation\Visual Studio Integrated Debugger\dclProxy.exe hostname
Replace hostname by the name of the PC.

*(Only for remote debugging:) Create a recording manually for the VM. I.e. log in to the VM's operating system, start the recording (via context menu "Record"), run the application under test and perform the actions necessary to reproduce the problem. Then stop and save the recording.

*Start Visual Studio and go to "VMware | Options | Replay Debugging in VM | General", and set the following values:

*

*"Local or Remote" must be set to "Local" for local debugging or to "Remote" for remote debugging.

*"Virtual Machine" must be set to the path to the VM's .vmx file .

*"Remote Machione Passcode" must be set to be passcode you used above (only for remote debugging).

*"Recording to Replay" must be set to a recording name that you previously created with VMware.

*"Host Executable Search Path" must be set to a directory in which you save DLLs which are required by the application under test and which are needed by Visual Studio to display correct stack traces.

Press "Apply".

*Go to "VMware | Options | Replay Debugging in VM | Pre-Record Event", and set the following values:

*

*"Base Snapshot for Recording": name of snapshot created previously.

Press "OK".

*(For local debugging:) In Visual Studio, select "VMware | Create Recording for Replay"; this restarts the VM. Login to the VM, run the application under test and perform the actions necessary to reproduce the problem. Then stop and save the recording.

*Select "VMware | Start Replay Debugging". VMware now automatically restarts the VM and the application under test and replays the recorded actions. Wait until the application crashes; the Visual Studio debugger then automatically becomes active.

*In the Visual Studio debugger, set a breakpoint to a location where you think the application has been before the crash. Then, select "VMware | Reverse Continue". The debugger now runs backwards to the breakpoint. This operation can take some time because the VM will be restarted and replayed until your breakpoint is reached. (You can speed up this operation by adding a snapshot a few seconds before the crash happens when you record the scenario. You can add additional snapshots during replay debugging.)

*Once VMware has replayed the VM to your breakpoint, you can use "Step Over" and "Step Into" to step forward from your breakpoint, i.e. you replay the recorded history of events, until you reach a point where you can identify the reason why your application crashed.
Further information: http://www.replaydebugging.com/

A: I would attach WinDbg when the program is running and do a minidump when it debugbreaks on a crash or exception:
.dump /ma c:\mem.dmp // c:\mem.dmp could be any other location you desire

I would enable gflags for your app, either from the command line of within WinDbg:
!gflag +ust

remember to remove this flag after!!
Then you could run an automated exepction analysis:
!analyze -v

this may tell you what it thinks caused the crash, you can dump the call stacks of all threads:
~* kb

and if see anything suspicuous you can switch thread and inspect further:
~x s

You can inspect the exception context record:
.ecxr

there is a good link on how to recover the call stack from a catch block:http://blogs.msdn.com/b/slavao/archive/2005/01/30/363428.aspx and also this: http://blogs.msdn.com/b/jmstall/archive/2005/01/18/355697.aspx
the main thing here is that with windbg attached you should be able to inspect the state of all the threads and the call stacks, you can also open the minidump in visual studio: http://msdn.microsoft.com/en-us/library/windows/desktop/ee416349%28v=vs.85%29.aspx#Analysis_of_a_minidump if you prefer visual studio for navigating, you can open the same dump in windbg to use its tools for analysis and visual studio for navigating the code. Hope this helps.

A: How about using BMC's AppSight?
We used it at a previous company (sorry, it took me a while to remember the name), it was used to research crashes etc.  ISTR you ran it and then ran your software and it recorded everything that was happening in a log file which you can view later.
It definitely works on Windows as that is what I used it on.
It might well be what you are looking for?

A: Doesn't gdb offer this functionality out of the box?
It has been a while since I used it but I recall it could run a program until it crashed and then replay the steps for you in the debugger.
Also, it would be straightforward to setup your own logging application which could output any amount of data you chose and could be activated by a command line param to the exe?
You could set it up now to tackle a crash you are having or just to cover the basics and then extend it as you fixed bugs or added new functionality.  The advantage would be that you would be able to capture exactly the data that you find useful and could even specify levels of logging to avoid being swamped with noise?

A: Not entirely sure if this is what you want, but 'u' will disassemble the last instructions from the current IP register on the current thread. This will show you the last instructions that were run, and you can normally figure out what values were for different registers by backing your way through the code it disassembles. It's a slow and tough process most of the time, but it gives you with almost 100% accuracy (barring some strange hardware problems, or really odd code problems) what just happened. I've used this method in the past to figure out why certain things were nulled out when I didn't have the source code.
If you check the windbg help file you'll find more information on it.


text:
Q: Yodlee API Account/Summary/all returning body with empty errors array Thanks for looking at this question,
Hitting up https://rest.developer.yodlee.com/services/srest/restserver/v1.0/account/summary/all
with the cobSessionToken and the userSessionToken returns a body response with an empty error array. ie
$response  = array("body"=>array("error"=>array(0=>"")));

The account is still in testing mode, I was wondering if this API resource worked while in sandbox mode?
I am trying to obtain the list of account that the user has added.
Thanks in advance.
EDIT
when trying to force the JSON response, you need to be quite fussy about the headers...
In PHP:
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "Content-Type: application/json",
        "Accept: application/json"
    ));

works, whereas:
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "Content-Type : application/json",
        "Accept : application/json"
    ));

does not.

A: This API do work in sandbox mode, for testing purpose you can append the cobSessionToken & userSessionToken in the URL itself. i.e. like

https://rest.developer.yodlee.com/services/srest/restserver/v1.0/account/summary/all?cobSessionToken
  ="Value"&userSessionToken="value".

Note that this API is using GET method while rest of the APIs are using POST method of HTTP.
While, if you are using Site Based aggregation then you should use getAllSiteAccounts
API.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unit Testing (C#) I am unit testing some CRUD operations. My questions are:
1) If I need to test the Add, Get, and Delete methods. The persistence layer is a database. Since I need to have a test object to Get and Delete, should I combine all 3 of these into one [TestMethod], or separate these into 3 methods and re-add the object before the Get and Delete tests?

A: Ideally you should have individual tests for each case.
You should use some sort of mocking - either via a framework or by setting up the database yourself - to set the initial conditions for each test.
So to test add you would start with a blank database and then add some new data, try to add the same data again (it should fail), add incomplete data etc.
Then to test get and delete you would start with a pre-populated database and perform the various tests you need.

A: I'd generally make a separate test. If I'm testing a "get" type method, the test setup would insert the object (generally by way of some mock framework) I expect to get as necessary, it just wouldn't be asserted against in the same way the actual get would.
This does mean that if the add implementation breaks, both the tests for the get and the add will fail in one way or another, assuming proper coverage. But that's kind of what you want anyhow, right?

A: If you are writing you own ORM to handle CRUD, I suggest you separate each action in a different test. Don't create big tests, that has many points of failure and many reasons to change, because it will turn your test project hard to maintain. Test each feature separately.
Now, if you are using some third part ORM to deal with CRUD, you should not test the tool at all, unless you don't trust it. But, in this case, you should find a better alternative. :)
You can do some Acceptance Tests to check if everything is working and, at this time, you will really reach the database.

A: Whatever makes testing easier for you :) as long as you get a return stating which method passed/failed then it should be good.

A: Hello :) I'd separate and test individually, and set up cleanly before and clear up after each.


text:
Q: .Net Razor Pages Error: No suitable constructor was found for entity type 'Endpoint' I am building a simple razor pages project with the below model and a corresponding page.
I have this class and an equivalent table in SQL server, which is supposed to display the contents of the "Classes" table on the page:
    public class ClassModel : PageModel
    {

        [BindProperty]
        public string ClassName { get; set; }
        [BindProperty]
        public int ClassSize { get; set; }
        [BindProperty]
        public string ClassPreference { get; set; }
        [BindProperty]
        public string ClassPhoneNumber { get; set; }

        private readonly DataContext _context;

        public ClassModel(DataContext context)
        {
            _context = context;
        }

        public List<ClassModel> Classes{ get; set; }

        public async Task OnGetAsync()
        {
            try
            {
                Classes = await _context.Classes.ToListAsync();
            }
            catch(Exception e)
            {
                Console.WriteLine("There was an error.\n " + e);
            }

        }

When I run the debugger and open the corresponding page, I get this error:

System.InvalidOperationException: No suitable constructor was found for entity type 'Endpoint'. The following constructors had parameters that could not be bound to properties of the entity type: cannot bind 'requestDelegate', 'metadata', 'displayName' in 'Endpoint(RequestDelegate requestDelegate, EndpointMetadataCollection metadata, string displayName)'.

I can't figure out where this is occurring, because nowhere in my code do I have an "Endpoint" class with any of those parameters.
Full error:
 System.InvalidOperationException: No suitable constructor was found for entity type 'Endpoint'. The following constructors had parameters that could not be bound to properties of the entity type: cannot bind 'requestDelegate', 'metadata', 'displayName' in 'Endpoint(RequestDelegate requestDelegate, EndpointMetadataCollection metadata, string displayName)'.
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.ConstructorBindingConvention.ProcessModelFinalizing(IConventionModelBuilder modelBuilder, IConventionContext`1 context)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnModelFinalizing(IConventionModelBuilder modelBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnModelFinalizing(IConventionModelBuilder modelBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.Model.FinalizeModel()
   at Microsoft.EntityFrameworkCore.ModelBuilder.FinalizeModel()
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, ModelDependencies modelDependencies)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder, ModelDependencies modelDependencies)
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
   at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.<>c.<TryAddCoreServices>b__7_3(IServiceProvider p)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.get_Model()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityType()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.CheckState()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityQueryable()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.System.Collections.Generic.IAsyncEnumerable<TEntity>.GetAsyncEnumerator(CancellationToken cancellationToken)
   at System.Runtime.CompilerServices.ConfiguredCancelableAsyncEnumerable`1.GetAsyncEnumerator()
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
   at ASPDotNetRazorApp.Models.PartyModel.OnGetAsync() in C:\(Path to my project):line 48

A: I figured this out. I needed to separate the model logic from the pagemodel logic. Now I have a model class for the model properties, and a pagemodel class for the OnGet function.


text:
Q: One-liner to count number of occurrences of String in a String[] in Java? I have an array of String:
String[] myArray = {"A", "B", "B", "C"};

Is there a quick way to count the number of occurrences of a string in that array? Yes, I know I can iterate and do the count myself:
int count = 0;
String whatToFind = "B";
for (String s : myArray) {
    if (s.equals(whatToFind)) {
        ++count;
    }
}

But I was wondering if there was a utility function for this. I couldn't find anything in Arrays or ArrayUtils. Is it possible to do this with a one-liner?

A: You can use the frequency method:
List<String> list = Arrays.asList(myArray);
int count = Collections.frequency(list, "B");

or in one line:
int count = Collections.frequency(Arrays.asList(myArray), "B");

With Java 8 you can also write:
long count = Arrays.stream(myArray).filter(s -> "B".equals(s)).count();

Or with a method reference:
long count = Arrays.stream(myArray).filter("B"::equals).count();

A: You can also try using Guava which is full of useful utilities. Using below code, you can count the frequency via Multiset:
public static void main(final String[] args) {
        String[] myArray = {"A", "B", "B", "C"};
        Multiset<String> wordsMultiset = HashMultiset.create();
        wordsMultiset.addAll(new ArrayList<String>(Arrays.asList(myArray)));
        int counts=wordsMultiset.count("B");
        System.out.println(counts);
    }

Although I know that you are looking for a single liner, but Guava is full of many more utils which are not possible with routine java utils.


text:
Q: C program for assigning elements of a matrix without letters I'm having trouble outputting an invalid statement if the user inputs a letter instead of a number into a 2D array.
I tried using the isalpha function to check if the input is a number or a letter, but it gives me a segmentation fault. Not sure what's wrong any tips?
the following code is just the part that assigns the elements of the matrix.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define MAX 10

void display(int matrix[][MAX], int size);

int main() {
    int n, degree;
    int matrix[MAX][MAX];

    printf("Enter the size of the matrix: ");  // assigning size of the matrix
    scanf("%d", &n);

    if (n <= 1 || n >= 11) {  // can't be bigger than a 10x10 matrix
        printf("Invalid input.");
        return 0;
    }

    for (int i = 0; i < n; ++i) {  // assigning the elements of matrix
        printf("Enter the row %d of the matrix: ", i);
        for (int j = 0; j < n; ++j) {
           scanf("%d", &matrix[i][j]);

           if (!isalpha(matrix[i][j])) { // portion I'm having trouble with
               continue;
           } else {
               printf("Invalid input.");
               return 0;
           }
        }
    }
    ...

A: As the value of n will be number, we can solve it using string instead of int.
char num[10];
int n;
scanf("%s", num);
if(num[0] < '0' || num[0] > '9' || strlen(num) > 2){
    printf("invalid\n");
}
if(strlen(num) == 1) n = num[0] - '0';
if(strlen(num) == 2 && num[0] != 1 && num[1] != 0) printf("invalid\n");
else n = 10;

Also we can use strtol() function to convert the input string to number and then check for validity.You can check the following code for it. I have skipped the string input part. Also you have to add #include<stdlib.h> at the start for the strtol() function to work.
char *check;
long val = strtol (num, &check, 10);
if ((next == num) || (*check != '\0')) {
        printf ("invalid\n");
}
if(val > 10 || val < 0) printf("invalid\n");
n = (int)val; //typecasting as strtol return long

A: You must check the return value of scanf(): It will tell you if the input was correctly converted according to the format string. scanf() returns the number of successful conversions, which should be 1 in your case.  If the user types a letter, scanf() will return 0 and the target value will be left uninitialized.  Detecting this situation and either aborting or restarting input is the callers responsibility.
Here is a modified version of your code that illustrates both possibilities:
#include <stdio.h>

#define MAX 10

void display(int matrix[][MAX], int size);

int main(void) {
    int n, degree;
    int matrix[MAX][MAX];

    printf("Enter the size of the matrix: ");  // assigning size of the matrix
    if (scanf("%d", &n) != 1 || n < 2 || n > 10) {
        // can't be bigger than a 10x10 matrix nor smaller than 2x2
        // aborting on invalid input
        printf("Invalid input.");
        return 1;
    }

    for (int i = 0; i < n; i++) {  // assigning the elements of matrix
        printf("Enter the row %d of the matrix: ", i);
        for (int j = 0; j < n; j++) {
            if (scanf("%d", &matrix[i][j]) != 1) {
                // restarting on invalid input
                int c;
                while ((c = getchar()) != '\n') {
                    if (c == EOF) {
                        printf("unexpected end of file\n");
                        return 1;
                     }
                }
                printf("invalid input, try again.\n");
                j--;
            }
        }
    }
    ...

A: The isdigit() library function of stdlib in c can be used to check if the condition can be checked.

A: Try this:
if (isalpha (matrix[i][j])) {
    printf ("Invalid input.");
    return 0;
}

A: So if anyone in the future wants to know what I did. here is the code I used to fix the if statement. I am not expecting to put any elements greater than 10000 so if a letter or punctuation is inputted the number generated will be larger than this number. Hence the if (matrix[i][j] > 10000). May not be the fanciest way to do this, but it works and it's simple.
for (int i = 0; i < n; ++i) {  // assigning the elements of matrix

    printf("Enter the row %d of the matrix: ", i);

    for (int j = 0; j < n; ++j) {

    scanf("%d", &matrix[i][j]);

    if (matrix[i][j] > 10000) { // portion "fixed"

       printf("Invlaid input");

       return 0;

       }

    }

}

I used a print statement to check the outputs of several letter and character inputs. The lowest out put is around and above 30000. So 10000 I think is a safe condition.


text:
Q: Using jQuery to close lightbox div from a button I have the below code is there a function that would enable me to closing a lightbox div .productInformation within my confirm function?
jQuery Code:
$('body').on("click", "#product_delete_product", function (e) {
    e.preventDefault();
    var box = $("#product_delete_product");
    var id = box.data("id");
    var name = box.data("name");

    var url = box.data("url");
    var data_array = {
        id: id,
    };

    if (confirm("Delete " + name + "?")) {
        ajaxCall(url, data_array, null, 'product_delete');
    }

});

A: If by closing you mean setting display:none, you can use
box.hide()

A: I forgot to mention that I was using colorbox I solved my issue buy adding the following:

            $(this).colorbox.close();


text:
Q: How to be int array in python? import array as arr
a = arr.array('i', [22, 44, 66, 88])
result = []
for i in range(0, len(a)):
     result = (a[i]**2)/10
     print (result)

The output is 48.4 193.6 435.6 and 774.4
How to be output is 48 193 435 and 774 ?
Sorry for my english

A: You need to precede int() to your variable result, if you want the variable to be saved as a float, but printed as an int:
import array as arr
a = arr.array('i', [22, 44, 66, 88])
result = []
for i in range(0, len(a)):
     result = (a[i]**2)/10
     print(int(result))

Otherwise, if you wish to save the variable as an integer:
import array as arr
a = arr.array('i', [22, 44, 66, 88])
result = []
for i in range(0, len(a)):
     result = int((a[i]**2)/10)
     print(result)

Finally, if you wish to add each integer to your list result:
import array as arr
a = arr.array('i', [22, 44, 66, 88])
result = []
for i in range(0, len(a)):
     result.append(int((a[i]**2)/10))
print(result)

Output:
[48, 193, 435, 774]


text:
Q: Why does AND, OR work as expected but an error is shown with XOR? (define-syntax e.g.
  (syntax-rules (===>)
    ((e.g. proposition)
     (unless proposition
       (error "invalid proposition: "'proposition)))
    ((e.g. proposition ===> value)
     (let ((result proposition))
       (unless (equal? proposition value)
         (error "invalid proposition: "'proposition
                ", expected "value", got "result))))))

(define my-eval
  (let ((ns (make-base-namespace)))
    (lambda (expr) (eval expr ns))))

(e.g. (my-eval '(and #t #t)) ===> #t)
(e.g. (my-eval '(and #t #f)) ===> #f)
(e.g. (my-eval '(or #t #f)) ===> #t)
(e.g. (my-eval '(or #f #f)) ===> #f)
(e.g. (my-eval '(xor #t #t)) ===> #f)
(e.g. (my-eval '(xor #t #f)) ===> #t)

It works correctly for AND,OR but for XOR:
XOR: undefined;
cannot reference an identifier before its definition.
even tough in the REPL seems to work correctly:

(xor #t #f)
t

A: You need to require racket/bool, which provides xor, into the namespace used by my-eval. One way to do that is to run (my-eval '(require racket/bool)) before your xor tests.

A:
The question is who has time to read whole documents like that?

You don't have to read it all in one sitting, but that is where the information is, and Racket has a lot of great documentation.
eval can be a bit slippery in Racket; you need to finish setting up the namespace where the eval expression is evaluated. One way to do this is to use parameterize to create an empty namespace. This needs to happen inside the lambda expression, i.e., the environment in which eval is evaluated, and you need to be sure that both racket/base and racket/bool are required:
#lang racket

(define-syntax e.g.
  (syntax-rules (===>)
    ((e.g. proposition)
     (unless proposition
       (error "invalid proposition: " 'proposition)))
    ((e.g. proposition ===> value)
     (let ((result proposition))
       (unless (equal? proposition value)
         (error "invalid proposition: " 'proposition
                ", expected " value ", got " result))))))

(define my-eval
  (lambda (expr)
    (parameterize ([current-namespace (make-base-empty-namespace)])
      (namespace-require 'racket/base)
      (namespace-require 'racket/bool)
      (eval expr))))

(e.g. (my-eval '(and #t #t)) ===> #t)
(e.g. (my-eval '(and #t #f)) ===> #f)
(e.g. (my-eval '(or #t #f)) ===> #t)
(e.g. (my-eval '(or #f #f)) ===> #f)
(e.g. (my-eval '(xor #t #t)) ===> #f)
(e.g. (my-eval '(xor #t #f)) ===> #t)


text:
Q: Can't activate WPS-Office in Ubutu I bought a subscription from wps office to enable the premium features and it worked well on windows. Now I switched to Ubuntu and installed wps but there's no field to enter the product key to activate it. There is no option to upgrade.
I have Ubuntu 22.04.1 LTS (the latest LTS).
I downloaded wps from the wps-homepage Deb-Package and installed it with the command "sudo dpkg -i wps-office_11.1.0.11664.XA_amd64.deb"
Can anyone help, please?


text:
Q: Makefile always execute default command irrespctive of CFLAGS I am currently building msp430 gcc based c plus plus program using minGW and conemu console.
    SUPPORT_FILE_DIRECTORY = "/c/ti/msp430_gcc/include"
SOURCES=blink.cpp
OBJECTS=$(SOURCES:.cpp=.o)
DEVICE  = msp430g2553
CC      = msp430-elf-gcc
GDB     = msp430-elf-gdb

CFLAGS = -I $(SUPPORT_FILE_DIRECTORY) -mmcu=$(DEVICE) -O2 -g
LFLAGS = -L $(SUPPORT_FILE_DIRECTORY)

all: ${OBJECTS}
        $(CC) $(SOURCES) $(CFLAGS) $(LFLAGS) -o $(DEVICE).out

clean:
        rm $(OBJECTS)

if I run make with just print I always get following output
$ make --just-print
g++    -c -o blink.o blink.cpp
msp430-elf-gcc blink.cpp -I "/c/ti/msp430_gcc/include" -mmcu=msp430g2553 -O2 -g -L "/c/ti/msp430_gcc/include" -o msp430g2553.out

And actual make fail with following error
g++    -c -o blink.o blink.cpp
    blink.cpp:21:20: fatal error: msp430.h: No such file or directory
     #include <msp430.h>
                        ^
    compilation terminated.
    mingw32-make: *** [<builtin>: blink.o] Error 1

Additional observation made is if object file is already present then this error do not occurs.


text:
Q: Item between 'minor' and 'major' I am looking for a word, or multiple words, which would fit between the terms 'minor' and 'major'. For example: 'Major arterial road' and 'minor arterial road' describe two types of roads with particular traffic flows (and design requirements), but what if there is a scenario which does not fit any of the two precisely, but sits somewhere in between?
The reason I am asking is that I am attempting to devise a naming convention for drawing layers in CAD. Usually a 'minor' and a 'major' layer suffice. An example would be lines depicting concrete, where the 'major' lines are the outlines and edges and the 'minor' lines interior corners and hidden lines. Now I have come across a few scenarios where I need another option in between.
Please note that I am not asking for help with creating a naming convention. I am looking for a word in the English Language that is between 'minor' and 'major'.

A: Intermediate would work, as it means that it comes between two extremes.
Medium, mid, middle, and median could also work, and are pleasing because they begin with an M so fit with major and minor.

A: To me, arterial roads means roads within a city that are quite long and used for travel between suburbs or areas some distance apart. I find it hard to imagine why you could need an extra classification of those.
This may be wrong for your purposes, but perhaps your first classification could be between longer 'arterial roads', which pass by or through a number of suburbs or areas, and 'local or suburban streets' which are much shorter. You might then classify both into major or minor depending on the amount of traffic, etc.
Just a thought. I hope it helps.

A: How about 'median' for your in-between layers?
https://www.google.com.sg/search?q=definition+median&ie=UTF-8&oe=UTF-8&hl=en-sg&client=safari
Or you could use 'interstitial' which means 'occupying the space between'.
https://www.google.com.sg/search?q=interstitial&ie=UTF-8&oe=UTF-8&hl=en-sg&client=safari

A: How about "Moderate"? Its context is broad yet implicates neither extreme, though could be interpreted as an indication toward the upper-end of the scale between Minor and Major.
Personally, I would vote "Intermediate" as it suggests that multiple instances of the term could apply, e.g. a minor layer, a major layer and many intermediate layers.


text:
Q: UINavigation Bar changing tint after using UIImagePickerController I have a app that can attach a photo to an NSAttributedString in a textView. The UI design has a blue-grey navigation bar with white text.
However, after I use the UIImagePicker, the tint of the NavigationController changes to black text.
- (void)showImagePickerForSourceType:(UIImagePickerControllerSourceType)sourceType
{
    _imagePickerController = [[UIImagePickerController alloc] init];
    _imagePickerController.modalPresentationStyle = UIModalPresentationCurrentContext;
    _imagePickerController.sourceType = sourceType;
    _imagePickerController.delegate = self;

    if (sourceType == UIImagePickerControllerSourceTypeCamera)
    {
        _imagePickerController.showsCameraControls = YES;

    }

    [self presentViewController:_imagePickerController animated:YES completion:nil];
}

I'd post an image of the view before launching the UIImagePicker but I don't have enough reputation points (and I don't really know how to get them either).
And I'd post the image after launching the image picker and picking one and returning from the UIImagePicker, but again, not enough reputation points.
Anyone have any ideas if this is 'normal' or a bug ion iOS?  Any suggestions on a workaround?
P.S.  If you want to see the images, I can email them to you.  Any advice is appreciated.

A: This indeed seems to be a bug, and has been present since iOS 7 beta 6 (or earlier).
There is another SO post about this with some solutions: UIImagePickerController breaks status bar appearance

A: This problem can be avoided by changing picker's modal presentation class to be different than full screen (e.g. UIModalPresentationPageSheet)
Code:
imagePickerController.modalPresentationStyle = UIModalPresentationPageSheet;


text:
Q: Second Callout fails in plot (code and datasets) I have two large datasets to plot histograms and their PDFs. The code used is the following:
<< eNpop.dat;
Arand = Map[Sort, eNpop, {2}];
AArand = Cases[Arand, {_, _, _, _, _}, 2];
A1rand = N @ Flatten[Map[(#[[1]]) &, AArand]];
<< eFPSpop.dat;
Afps = Map[Sort, eFPSpop, {2}];
AAfps = Cases[Afps, {_, _, _, _, _}, 2];
A1fps = N @ Flatten[Map[(#[[1]]) &, AAfps]];
eϕ1rand =
 FindDistribution[A1rand, TargetFunctions -> "Continuous",
  PerformanceGoal -> "Quality"];
A1fps = N @ Flatten[Map[(#[[1]]) &, AAfps]];
eϕ1fps =
 FindDistribution[A1fps, TargetFunctions -> "Continuous",
  PerformanceGoal -> "Quality"];

Show[Legended[
  Histogram[
   <|"RAND" -> A1rand, "FPS" -> A1fps|>
   , {10}, "PDF",
   PlotRange -> {{0, 350}, All}, PlotTheme -> "Scientific",
   ChartStyle -> 96,
   ChartBaseStyle -> Directive[EdgeForm[None], Opacity[0.25]],
   FrameLabel -> {"Time", "Probability"}], Placed[
   SwatchLegend[96, {"No stigmergy", "FPS"}], {0.9, 0.8}]],
 Plot[{Callout[PDF[eϕ1rand, x],
    "FrechetDistribution (α=0.9, β=65.3, μ=-6.7)", \
{150, 0.0075}, 40, CalloutMarker -> "CirclePoint"],
   PDF[eϕ1fps, x]
   }, {x, 0, 350}, PlotStyle -> Thick, PlotRange -> All],
 ImageSize -> 600]

The datasets eNpop.datand eFPSpop.dat can be downloaded from
(the two data sets)
The code above it works fine with the one Calloutbut it does not work if I try to put a second Calloutfor the second PDF function.
How could I set the two Calloutsin the same plot?
Besides, I want to include this figure in a publication. How could I improve it?. I have been testing Histogram options with no clear better results.

A: As stated in the comments to your previous question on this topic, you need to upgrade from v11.0.0 to v11.0.1
$Version

(*  "11.0.1 for Mac OS X x86 (64-bit) (September 21, 2016)"  *)

<< /Users/roberthanlon/Downloads/datasets/eNpop.dat;

<< /Users/roberthanlon/Downloads/datasets/eFPSpop.dat;

Arand = Map[Sort, eNpop, {2}];
AArand = Cases[Arand, {_, _, _, _, _}, 2];
A1rand = N@Flatten[Map[(#[[1]]) &, AArand]];
Afps = Map[Sort, eFPSpop, {2}];
AAfps = Cases[Afps, {_, _, _, _, _}, 2];
A1fps = N@Flatten[Map[(#[[1]]) &, AAfps]];
eϕ1rand =
  FindDistribution[A1rand, TargetFunctions -> "Continuous",
   PerformanceGoal -> "Quality"];
A1fps = N@Flatten[Map[(#[[1]]) &, AAfps]];
eϕ1fps =
  FindDistribution[A1fps, TargetFunctions -> "Continuous",
   PerformanceGoal -> "Quality"];

Note that your Callout had the wrong parameters for the FrechetDistribution
Show[
 Legended[
  Histogram[<|"RAND" -> A1rand, "FPS" -> A1fps|>, {10}, "PDF",
   PlotRange -> {{0, 350}, All},
   PlotTheme -> "Scientific",
   ChartStyle -> 96,
   ChartBaseStyle -> Directive[EdgeForm[None], Opacity[0.25]],
   FrameLabel -> {"Time", "Probability"}],
  Placed[LineLegend[96, {"No stigmergy", "FPS"}], {0.9, 0.85}]],
 Plot[{
   Callout[PDF[eϕ1rand, x],
    StringForm["FrechetDistribution (α=`1`, β=`2`, μ=`3`)",
     Sequence @@ (NumberForm[#, {3, 1}] & /@ eϕ1rand)],
    {150, 0.007}, 50,
    CalloutMarker -> "CirclePoint"],
   Callout[PDF[eϕ1fps, x], StringReplace[ToString[eϕ1fps],
     {"{Cauchy" -> "\n{Cauchy", "Inverse" -> "\nInverse"}],
    {190, 0.01}, 65,
    CalloutMarker -> "CirclePoint"]},
  {x, 0, 350},
  PlotStyle -> Thick,
  PlotRange -> All],
 ImageSize -> 600]


text:
Q: How to receive mouse press event on clicking QTableWidget? I'm having a table with 100 datas. I need to receive mouse press event while clicking on the table.
Here is the code:
ui->tableWidget->viewport()->installEventFilter(this);

bool Dbtable::eventFilter(QObject *obj, QEvent *event)
{
    if(event->type() == QEvent::MouseButtonPress)
    {
        debugLog("# TABLE WIDGET IS PRESSED");
        return ;
    }
}

Now the table is not visible.
Could any one help me in solving this?

A: have you tried returning  QWidget::eventFilter()


text:
Q: How do I distribute tasks to multiple celery workers in parallel?
It seems every celery questions are like 5 years to 10 years old and
utilizing old celery versions and design patterns

Using celery version 5.0.5
I have a celery task that queries the database and then performs some computations/calculations on each row of the rows returned by query
Issue is this task is taking several minutes to complete because of the thousands of rows returned from query so i am trying to distribute to multiple celery workers in parallel
@celery.task()
def send_sms(to, body):
    from twilio.rest import Client

    account_sid = os.environ["ACCOUNT_SID"]
    auth_token = os.environ["AUTH_TOKEN"]
    from_ = os.environ["NUMBER"]

    client = Client(
        account_sid,
        auth_token,
    )

    message = client.messages.create(
        to=to,
        from_=from_,
        body=body,
    )

@celery.task()
def notify_users():
    session = create_session()
    query = session.query(Rentals).filter(Rentals.enabled == True)
    today = datetime.now()
    for q in query:
        if q.returned_date is not None:
            if (today - q.returned_date).total_seconds() < q.rental_period:
                continue

        user = session.query(Users).filter(User.id == q.user_id).one()

        to = send_notification_get_to.get(q.notification_method)(user)
        body = f"sending email to {user.email}"

        send_sms.delay(to, body)

What will be the best way to distribute these tasks to multiple workers as opposed to letting one worker run it for several minutes which gets slower exponentially as the number of rows returned increase from a few thousands to tens of thousands

A: I had the same use case earlier, what I did was
I paginated the query (broke the records into smaller chunks) and each page was processed by a celery worker
You can also try using different worker pools like gevent, eventlet pools for better performance.
the code would look like this.
@celery.task()
def send_sms(to, body):
    from twilio.rest import Client

    account_sid = os.environ["ACCOUNT_SID"]
    auth_token = os.environ["AUTH_TOKEN"]
    from_ = os.environ["NUMBER"]

    client = Client(
        account_sid,
        auth_token,
    )

    message = client.messages.create(
        to=to,
        from_=from_,
        body=body,
    )

@celery.task()
def notify_range_of_users(num_chunks, skip):
    session = create_session()
    today = datetime.now()

    query = session.query(Rentals).filter(Rentals.enabled == True)

    paginated_query = query.limit(num_chunks).offset(skip * num_chunks)
    for q in paginated_query:

        if q.returned_date is not None:
            if (today - q.returned_date).total_seconds() < q.rental_period:
                continue

        user = session.query(Users).filter(User.id == q.user_id).one()

        to = send_notification_get_to.get(q.notification_method)(user)
        body = f"sending email to {user.email}"

        send_sms.delay(to, body)

@celery.task()
def notify_users():
    session = create_session()
    today = datetime.now()

    query = session.query(Rentals).filter(Rentals.enabled == True)
    total_rentals = query.count()
    # each chunk will contain, 100 rows/objects
    num_chunks = 100

    # find total number of chunks
    quo, remainder = divmod(total_rentals, num_chunks)
    # each job will contain a certain number of chunks
    jobs = quo

    if remainder:
        jobs = jobs + 1

    skip = 0
    for i in range(jobs):
        notify_range_of_users.delay(num_chunks, skip)

        # increment skip to go the next page
        skip = skip + 1


text:
Q: when opening my site opens a popup with two options accept cookies or if cookies are disabled then not use our site without allow cookies hi I want to add a method in my site js or html, when opening my site opens a popup with two options accept cookies or if cookies are disabled then not use our site without allow cookies.

A: you can set up web server to answer only when browser has sent "has accept cookie" Otherwise just show popup page. So user can see site only if accept cookie and it has enabled.

A: If you want to create your own popup, you can start by learning how to create modals in JS (example: https://www.w3schools.com/howto/howto_css_modals.asp) as well as Cookies in JS (example https://www.w3schools.com/js/js_cookies.asp).
But, if you want avoid "reinventing the wheel",  there's a few turn-key solutions I found online:
Cookie Bar: https://cookie-bar.eu/
GDPR Cookie Consent Prompt: https://www.jqueryscript.net/other/GDPR-Cookie-Consent-Popup-Plugin.html


text:
Q: Time series prediction: need help using series with different periods of days There's this event that my organization runs, and we have the ticket sales historic data from 2016, 2017, 2018. This data contains the quantity of tickets selled by day, considering all the sales period.
To the 2019 edition of this event, I was asked to make a prediction of the quantity of tickets selled by day, considering all the sales period, sort of to guide us through this period, meaning we would have the information if we are above or below the expected sales average.
The problem is that the historic data has a different size of sales period in days:
In 2016, the total sales period was 46 days.
In 2017, 77 days.
In 2018, 113 days.
In 2019 we are planning 85 days. So how do I  ajust those historical data, in a logic/statistical way, so I could use them as inputs to a statistical predictive model (such as ARIMA model)?
Also, I'm planning to do this on Python, so if you have any suggestions about that, I would love to hear them too!
Thank you!

A: Based on what I understand after reading your question, I would approach this problem in the following way.

*

*For each day, find how far out the event is from that day. The max
value for this number is 46 in 2016, 77 in 2017 etc. Scale this value
by the max day.

*Use the above variable, along with day of the month, day of the week
etc as extraneous variable

*Additionally, use lag information from ticket sales. You can try one
day lag, one week lag etc.

*You would be able to generate all this data from the sale start until
end.

*Use the generated variables as predictor for each day and use ticket
sales as target variable and generate a machine learning model
instead of forecasting.

*Use the machine learning model along with generated variables to predict future sales.


text:
Q: grep all Gentoo Stage3 links to the terminal I want to display all links from https://www.gentoo.org/downloads/mirrors/ to the terminal.
Firstly, the script would wget the web page to a file called index.html, then a grep or sed command would simply display all the https://, http:// and ftp:// to the terminal.
Can someone help me with this command? I know it's simple, but I'm not really familiar with neither of these commands.
What i tried:
grep "" index.html
Output:
              ftp://mirrors.tera-byte.com/pub/gentoo
              http://gentoo.mirrors.tera-byte.com/
              rsync://mirrors.tera-byte.com/gentoo

How can I remove the empty spaces, tags and all unnecessary text after the link?

A: If you just want the domain link to remain, you can try this grep
grep -Eo '[h|f]t*ps?://.[^<|>|"]*' index.html

This will display only http,https and ftp matches
If the need is to match within  blocks, this sed will work
sed -En '// {s|.*([h|f]t*ps?://.[^<|>|"]*).*|\1|p}' index.html

A: You can use grep with this pattern:
grep -Po "(?<=)(https?|ftp)(.*)(?=<\/code>)" index.html
Top 3 lines of output:
ftp://mirrors.tera-byte.com/pub/gentoo
http://gentoo.mirrors.tera-byte.com/
ftp://mirror.csclub.uwaterloo.ca/gentoo-distfiles/


text:
Q: how can I do Apache kafka to spark streaming and get msg in rdd PySpark I am trying to streaming from Kafka to spark.

*

*Installed both kafka and spark

*Started zookeeper with default

*properties config Started kafka server with default properties
config

*Started kafka producer Started kafka consumer Sent message
from producer to consumer.
Works fine.
but I don't know How to send spark rdd.
I trying to solve this from 3 days but didn't get any output.
because I am new in spark kafka.
I want send producer msg to spark rdd.
I have setup spark-2.0.1-bin-hadoop2.7 and kafka_2.11-0.10.0.1.
Please help me to solve my problem.


text:
Q: Automatically update GitHub wiki based on repository markdown files I'm fairly new to GitHub and I've been trying to get the GitHub Wiki associated with a project to get the content from the main repository with no success.
Online there are guides on how to do this on Microsoft Azure here, but for some reason, I cannot find anything similar for GitHub. I am not sure where to ask this question so I came to the trusted StackOverflow community.
Basically I have a repository where we are uploading a series of markdown documents (see giovannellilab/protocols) and I would like the content of the wiki for the same project to be updated with pages coming from the repository. Each markdown file in the repository becomes its own wiki page. Ideally, the wiki will get automatically updated every time we push something new to the repo or we merge a new pull request.
So far I have not found an easy to implement a solution.
I've also tried to use a GitHub Action found in the marketplace, SwiftDocOrg with no success. I'm new to GitHub-actions and even follwing the guide I could not make this work.
Here the content of my .yml page:
- name: Publish to GitHub Wiki
  uses: SwiftDocOrg/github-wiki-publish-action@1.0.0
  with:
    # A path to the directory of files to publish
    path: giovannellilab/protocols

The action is failing each time (obviously something is wrong/missing, but I cannot figure out what).
Any suggestions on how to make it work in GitHub?
Any other place where I can host documentation pulling directly from a GitHub repository?
Any other better way to implement this?
Thank you very much,
Don


text:
Q: Should I hardcode data or use props in React? I am new to React and was wondering if we have to use hardcode data like this:
import React from "react";
    import "../src/App.css";

    const header = props => {
      return (

Content Manager

      );
    };

    export default header;

    import React, { Component } from "react";
    import Header from "../src/header";

    class App extends Component {
      render() {
        return (

        );
      }
    }

    export default App;

As you can see the code above, I just put "Content Manager" inside h1 as a usual content just like we do in HTML. Or do I need to use props instead of hardcoding:
import React from "react";
import "../src/App.css";

const header = props => {
  return (

{props.title}

  );
};

export default header;

import React, { Component } from "react";
import Header from "../src/header";

class App extends Component {
  render() {
    return (

    );
  }
}

export default App;

Guys if something is not clear please let me know

A: Basically If you want to reuse a component you should be using props.
Example:
When you need same header component for 3 places saying "Welcome","Hello" and "Hi" and have hard coded you will result in writing 3 header components with your heading as "Welcome","Hello" and "Hi".
something like this:

    const HiHeader = props => {
      return (

Hi

      );
    };

    export default HiHeader;

       const HelloHeader = props => {
      return (

Hello

      );
    };

    export default HelloHeader;

       const WelcomeHeader = props => {
      return (

Welcome

      );
    };

    export default WelcomeHeader;

and you use them as

<HiHeader/>
<HelloHeader/>
<WelcomeHeader/>

in case, if you use props you can write a single header and pass different props.
example :

const header = props => {
  return (

{props.title}

  );
};

export default header;

import Header  from './header.js'

A: If your header component going to be reused to display different headers pass in the text as a prop. Else, if you are dead sure that this is gonna be used only once, hard coding is fine.
Cheers,

A: Never hardcoding, it's the evil!


text:
Q: WTForms BooleanField treats JSON false value as true I'm using wtforms to handle data from my post requests.  One certain post requests sends a variety of data including a boolean value.
My form looks like this:
class EditFileForm(Form):
    title = StringField('title')
    shared = BooleanField('shared')
    fileID = IntegerField('fileID')
    userID = IntegerField('userID')

I can see that when I receive the request the data looks like this:
data = MultiDict(mapping=request.json)
print(data)
>>MultiDict([(u'shared', False), (u'title', u'File5'), (u'userID', 1), (u'fileID', 16)])

You can see the boolean field is "false", and printing the raw data shows that too  However, when I print the actual form field I get true.
print(form.shared.raw_data)
[False]
print(form.shared.data)
True

I read that WTForms might not know how to handle false boolean values.  What is the proper way of doing this?  Using an IntegerField instead?
I have another form with a booleanfield that is handling false boolean values from my postgres database just fine.

A: WTForms is not really meant to work with JSON data.  In this case, BooleanField checks that the value it received is in field.false_values, which defaults to ('false', '').  The False object is not in there, so it's considered true.
You can pass a different set of false_values to the field.
BooleanField(false_values={False, 'false', ''})

Or patch it for all instances by placing this somewhere before the field is used for the first time.
BooleanField.false_values = {False, 'false', ''}

You may better off using a serialization library such as Marshmallow to handle JSON data.


text:
Q: How do I get technical information on my video card? (Model, RAM, Mhz, etc) I'd like to get as much technical information about my MacOSX's video card as possible... technical details, even serial number if the card has a unique identifier.
I intend to use this information do research what GPU specific commands I can run on a given laptop.

A: Select Graphics/Displays from the output of system_profiler.
In a mac terminal, type:
system_profiler SPDisplaysDataType
The output will show something like this with your card name and details:
system_profiler SPDisplaysDataType

Graphics/Displays:

AMD FirePro D500:

  Chipset Model: AMD FirePro D500
  Type: GPU
  Bus: PCIe
  Slot: Slot-2
  PCIe Lane Width: x16
  VRAM (Total): 3072 MB
  Vendor: ATI (0x1002)
  Device ID: 0x679e
  Revision ID: 0x0000
  ROM Revision: 113-C3861J-687
  gMux Version: 4.0.11 [3.2.8]
  EFI Driver Version: 01.00.687
  Displays:
    CS230:
      Resolution: 1920 x 1080
      Pixel Depth: 32-Bit Color (ARGB8888)
      Display Serial Number: 27673034
      Main Display: Yes
      Mirror: Off
      Online: Yes
      Rotation: Supported
    CS230:
      Resolution: 1920 x 1080 @ 60Hz (1080p)
      Pixel Depth: 32-Bit Color (ARGB8888)
      Display Serial Number: 27712034
      Mirror: Off
      Online: Yes
      Rotation: Supported
      Television: Yes

AMD FirePro D500:

A: Click on the Apple icon in the upper left hand corner of your menu bar and select About This Mac from the menu.
In the dialog that appears click on the More Info... button to bring up the detailed about dialog.

Click on the System Report... button and you'll get a split-window dialog that has hardware components down the left side and details on the right.

Click on Graphics/Displays on the left. Pick a graphics card from the right side and you'll see all the details the system provides about it.

You can also get to the System Report by running Applications -> Utilities -> System Information.

A: There is a small amount of information in System Information/System Profiler -> Graphics and Displays
If you want more, you will have to take apart your Mac and actually look at the graphics card.


text:
Q: How to solve elasticsearch No alive nodes found in your cluster? When I research some text my service response No alive nodes found in your cluster. Also service show "Type: Elasticsearch\Common\Exceptions\NoNodesAvailableException"
my elasticsearch.yml file is below:

# ---------------------------------- Cluster -----------------------------------
#
# Use a descriptive name for your cluster:
#
#cluster.name: my-application
#
# ------------------------------------ Node ------------------------------------
#
# Use a descriptive name for the node:
#
#node.name: node-1
#
# Add custom attributes to the node:
#
#node.attr.rack: r1
#
# ----------------------------------- Paths ------------------------------------
#
# Path to directory where to store the data (separate multiple locations by comma):
#
path.data: /var/lib/elasticsearch
#
# Path to log files:
#
path.logs: /var/log/elasticsearch
#
# ----------------------------------- Memory -----------------------------------
#
# Lock the memory on startup:
#
#bootstrap.memory_lock: true
#
# Make sure that the heap size is set to about half the memory available
# on the system and that the owner of the process is allowed to use this
# limit.
#
# Elasticsearch performs poorly when the system is swapping the memory.
#
# ---------------------------------- Network -----------------------------------
#
# By default Elasticsearch is only accessible on localhost. Set a different
# address here to expose this node on the network:
#
#network.host: 192.168.0.1
#
# By default Elasticsearch listens for HTTP traffic on the first free port it
# finds starting at 9200. Set a specific HTTP port here:
#
#http.port: 9200
#
# For more information, consult the network module documentation.
#
# --------------------------------- Discovery ----------------------------------
#
# Pass an initial list of hosts to perform discovery when this node is started:
# The default list of hosts is ["127.0.0.1", "[::1]"]
#
#discovery.seed_hosts: ["host1", "host2"]
#
# Bootstrap the cluster using an initial set of master-eligible nodes:
#
#cluster.initial_master_nodes: ["node-1", "node-2"]
#
# For more information, consult the discovery and cluster formation module documentation.
#
# ---------------------------------- Various -----------------------------------
#
# Require explicit names when deleting indices:
#
#action.destructive_requires_name: true
#

How can I solve this problem? I use php and client builder. Actually it was worked before but my when disc is full I got an error.(Watermark) So, I decrease disc size but now. Cluster not found.


text:
Q: Test if PowerShell script being called with Invoke-Expression? Is there a way to tell if a script is being called using Invoke-Expression rather than called directly? I want to do something different, e.g. pause for input, if the script is being called directly but skip that if it is being called from another location.

A: In short, I would say no.
Instead you should structure the code in such a way that you could inform the code either that it should or should not prompt, like with a -Prompt parameter or something.
I can't really give more specific advice without seeing the code or knowing what it is you're trying to do.

A: Using Invoke-Expression the one way I've found is to use Get-PSCallStack.
So for instance, if I have a script called foo1.ps1 into which I put :
$CallStack = Get-PSCallStack | select -ExpandProperty Command
$CallStack[($CallStack.count-2)]

then create a second script called foo2.ps1 which just contains :
Invoke-Expression .\foo1.ps1

If I run foo1.ps1 directly at a PS prompt it returns foo1.ps1, if I run foo2.ps1 it returns that script name instead.
Another method I found is using $MyInvocation, but that doesn't seem to work with Invoke-Expression. If you simply call the script with "& .\foo1.ps1" or even just ".\foo1.ps1" it works. With that method if you put the following in foo1.ps1 :
if ($MyInvocation.ScriptName -eq "") {Write-Host "Run directly"}
else {Write-Host "Called from " $MyInvocation.ScriptName }

It will display either that you've called it directly or return the path to the script (eg foo2.ps1) which called it.


text:
Q: How to delete elements from a list using a list of indexes? If I have the following list of elements:
list = ['one', 'two', 'three', 'four']

and I have another list that contains the indexes I need to delete from the list above:
to_delete = [0,2]

How can I delete those elements from list using to_delete? Using a for loop doesn't work since, obviously, when you delete one element from a list the index of each remaining element changes.
What can I do?

A: You can use enumerate together with a conditional list comprehension to generate a new list containing every element of my_list that is not in the index location from to_delete.
my_list = ['one', 'two', 'three', 'four']
to_delete = [0,2]

new_list = [val for n, val in enumerate(my_list) if n not in to_delete]

>>> new_list
['two', 'four']

A: Use list comprehension filtering :
 [ my_list[i] for i in range(len(my_list)) if i not in to_delete ]


text:
Q: Validation loss much lower than training loss. Is my model overfitting or underfitting? I am using a convolutional neural network to train a large set of spectral data, which has 653 classes. I am storing the loss values and the accuracy values per epoch in a list. the optimiser i am using is Adams with a learning rate=0.01. The loss function i am using is a weighted cross entropy loss function, and the test set was made using a leave one out scheme from the training data.
I am normalising the losses by dividing them by number of samples in training and number of samples in validation, respectively.

The other outputs i am printing every 5th epoch is as shown below:-

What do you think might be happening here? Overfitting? Underfitting?
Any and every help is appreciated.


text:
Q: Avoid printing specific field with jax ws logger? For trace reasons I need to display the response of a soap webservice, and I do that this way:
jaxWsProxyFactoryBean.getOutInterceptors().add( new LoggingOutInterceptor());

it works but, incidentally, the webservice answers with a base64 representation of a pdf file.
Something like this:
<response>
    <name>aName</name>
    <description>decription</description>
    <file>...
       loooooooooooong
     ...
    </file>
</response>

I want to print only the name and description tags, while for the file tag a simple "obfuscated as too big" string will do.
Is it possible?


text:
Q: How to convert python arrays to MATLAB readable arrays? I have a function in MATLAB which takes four inputs
function f = calculate_mat(F,M,a,b).

Here F and M are multi dimensional arrays and 'a' and 'b' are constant terms.
Now I have to call this function in python script where I give all the above input values.
import matlab.engine
import numpy as np

# c, a, b are constants
c = 100
a = 30
b = 0.2
freal = np.arange(0,30000,10) # real frequency range
fimag = np.arange(0,200,1) # imaginary frequency range
F = np.zeros((3000,200))
M = np.zeros((3000,200))
for i in range(len(freal)):
    for j in range(len(fimag)):
        F = freal[i] + fimag[j]
        omega = 2 * np.pi * F[i][j]
        kx = omega / c # wave number
        M[i][j] = np.abs(kx)

eng = matlab.engine.start_matlab()
fst = eng.calculate_mat(F, M, a,b)

But the python script throws an error : "TypeError: unsupported Python data type: numpy.ndarray"
I have understood that this is because Matlab cannot read in numpy array format.
How to convert numpy array into matlab- readable arrays? Any examples would be helpful.

A: You can't call a matlab function with numpy arrays. You have to convert the numpy arrays to matlab matrices:
fst = eng.calculate_mat(matlab.double(F.tolist(), is_complex=True), matlab.double(M.tolist(), is_complex=True), a, b)


text:
Q: How to use Nokogiri to change the HTML meta data? I am currently on a task to add a company name at the end of the meta-description in all .asp files. With a bit of knowledge about Nokogiri and Ruby, I think I should be able to automate this "Human-intensive" task. I can easily scrape through the asps and got a list of description to change. However, how can I change the value and write it back to the file?
I am trying to do this with Nokogiri but it seems like Nokogiri was designed to scrap data and write xml but not quite htmls. (The asps are fairly simple, just including some duplicated codes and no logic at all... so can be treated as html/text). Does Nokogiri provide this feature? If not, what else can I do? Thanks!

A: Nokogiri is excellent for this:
require 'nokogiri'

doc = Nokogiri::HTML.parse(<<EOT)

    <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
    <meta name="description" content="Free Web tutorials">

EOT

meta = doc.at('meta[@name]')
meta['content'] = 'foo'

puts doc.to_html
# >> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
# >>
# >>
# >>     <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
# >>     <meta name="description" content="foo">
# >>
# >>
# >>

If you want to append something to the description's content:
meta['content'] = meta['content'] + ' by foobar'

Which results in:
# >> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
# >>
# >>
# >>     <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
# >>     <meta name="description" content="Free Web tutorials by foobar">
# >>
# >>
# >>

HTML that you don't control can change in wild and wonderful ways if the creators change to different HTML generators. That can break your application unless you use something robust, and regular expressions for HTML are not robust enough.
It's easy to write a pattern to match
<meta name="description" content="Free Web tutorials">

It's not so easy to write one that matches that one day, and then
<meta
name="description"

content="Free Web tutorials"
>

the next.
It's easy to imagine seeing various HTML output styles because the site's content people used different tools, along with some automation. A parser can handle it nicely.

A: Open the file use a regex or String to identify the replacement and gsub it appropriately then write back to the File.
There are lots of solutions on SO for this Heres just one and a brief example
File.write("hello.txt",File.open("hello.txt",&:read).gsub("install","upgrade"))

this will replace every instance of the word "install" in "hello.txt" with "upgrade"


text:
Q: FoxPro string returned from procedure is truncated I am VERY new to FoxPro so please pardon what is most likely a very silly question. I am trying to wrap my brain around several FoxPro 9 programs that were written by a non-programmer and, having never looked at FoxPro code before in my life, am finding it quite a chore to understand some of it's idiosyncrasies.
I have a pretty simple SQL statement that is returning information from the Project file(being used as a table). I have three simple functions that handle giving me some useful information about the objects (files) that are included in the project.
Here is the entire main program that gets run. It's nothing but a single SQL statement that uses three simple functions:
SELECT ShortName(Name) AS SName, LongName(Name) AS LName, Type, GetType(Type) AS TypeName ;
FROM <my project file here> ;
ORDER BY Type, SName

The SQL statement runs fine and my three functions get called and all three return the data I expect with the exception of the GetType function. The ShortName function returns just the file name, the LongName function returns the entire path and file name and the GetType function is supposed to return a more human readable string that tells me what the file type is. Such as "Table", "Program", etc . . .
HERE IS THE PROBLEM:
The GetType function is being run and the return value is being set but the value being returned is being truncated to 6 characters.

I have verified that the return value of the function is the full string of text that I expect just before the function exits. However; when the data is displayed in the viewer the value is truncated.
Why is this data being truncated? The two other functions work nearly the same way (at least from my completely "un-knowledgeable" view point) and they are not being truncated.
Here is the code from the GetType function
PARAMETERS pType

retVal = ""

DO CASE
    CASE LEFT(ALLTRIM(pType),1) = 'B'
        retVal  = "Lable"
    CASE LEFT(ALLTRIM(pType),1) = 'D'
        retVal  = "Table"
    CASE LEFT(ALLTRIM(pType),1) = 'd'
        retVal  = "XBase Table"
    CASE LEFT(ALLTRIM(pType),1) = 'F'
        retVal  = "Format"
    CASE LEFT(ALLTRIM(pType),1) = 'H'
        retVal  = "Header"
    CASE LEFT(ALLTRIM(pType),1) = 'I'
        retVal  = "Index"
    CASE LEFT(ALLTRIM(pType),1) = 'L'
        retVal  = "Library"
    CASE LEFT(ALLTRIM(pType),1) = 'M'
        retVal  = "Menu"
    CASE LEFT(ALLTRIM(pType),1) = 'P'
        retVal  = "Program"
    CASE LEFT(ALLTRIM(pType),1) = 'Q'
        retVal  = "Query"
    CASE LEFT(ALLTRIM(pType),1) = 'R'
        retVal  = "Report Form"
    CASE LEFT(ALLTRIM(pType),1) = 's'
        retVal  = "Screen Table"
    CASE LEFT(ALLTRIM(pType),1) = 'S'
        retVal  = "Screen Program"
    CASE LEFT(ALLTRIM(pType),1) = 'T'
        retVal  = "Configuration File"
    CASE LEFT(ALLTRIM(pType),1) = 'x'
        retVal  = "File"
    CASE LEFT(ALLTRIM(pType),1) = 'X'
        retVal  = "File"
    CASE LEFT(ALLTRIM(pType),1) = 'Z'
        retVal  = "Application"
ENDCASE

RETURN retVal

A: Actually, shorter, have your Function GetType(), always return the "PADR( retVal, 15 )" (or whatever length).
Reason being.  When VFP runs a query, it actually runs it TWICE.  First time checks to make sure its valid, and looks at function calls to ensure a given type for the result.  If your query on the first record returns a shorter string length value, so too is the final cursor that column width.
By enforcing a full - constant length from your function you will guarantee it won't be truncated, nor missed in any other SQL call elsewhere.

A: Replace your SQL SELECT with:
SELECT ShortName(Name) AS SName, LongName(Name) AS LName, Type, PADR(GetType(Type), 10) AS TypeName ;
FROM <my project file here> ;
ORDER BY Type, SName

This will pad right the resulting text with the appropriate number so spaces until the result is 10 characters. Adjust the value as you need.
This happens becuase SQL SELECT determines column widths based on the first record returned.

A: You are getting a truncated return because the first item found in the SELECT is what determines the length.  Pad you answer with '00000000000000' or something to correct this.  Have you ever heard of ProMatrix?  Super powerful VFP overlay builder.  I have used it for several years and really helped me with the learning curve. HTH


text:
Q: Formatting JSON in post I need to send the id and quantity as an integer. I define it as an integer, but for some reason when I try and post it, it posts the id as a string.
I'm missing something easy here, just no idea what.. How can I send both id and quantity as an integer? My code is below:
  var id = parseInt(identifier, 20);
  var quantity = parseInt(amount, 10);
  var updates = {};
  updates[id] = quantity;
  $.post('/cart/update.js', {updates: {updates}});

The JSON in the post should look like this:
$.post('/cart/update.js', {updates: {40076307207: 1}});

Thanks

A: $.post doesn't send JSON, it uses application/x-www-form-urlencoded format. This format does not distinguish data types, everything is sent as a string. If a parameter is supposed to be an integer, you need to convert it in the server code.
Also, in JSON, object keys are always strings.
In order to get the structure you want, it should be:
$.post('/cart/update.js', {updates: updates});

You're adding an extra level of nesting, because {updates} is the ES6 shorthand for {updates: updates}, so you're sending {updates: {updates: updates}}.


text:
Q: C# Generics Inheritance Problem I'd like to add different types of objects derived from one class with generics into a List of base type. I get this compile error
Error   2   Argument 1: cannot convert from 'ConsoleApplication1.Stable' to 'ConsoleApplication1.ShelterBase<ConsoleApplication1.AnimalBase>'   C:\Users\ysn\Desktop\ConsoleApplication1\ConsoleApplication1\Program.cs 43  26  ConsoleApplication1

I can't see the problem could you provide me an alternative way of doing this kind of thing?
abstract class AnimalBase { public int SomeCommonProperty;}

abstract class ShelterBase<T> where T : AnimalBase
{
    public abstract List<T> GetAnimals();
    public abstract void FeedAnimals(List<T> animals);
}

class Horse : AnimalBase { }

class Stable : ShelterBase<Horse>
{
    public override List<Horse> GetAnimals()
    {
        return new List<Horse>();
    }

    public override void FeedAnimals(List<Horse> animals)
    {
        // feed them
    }
}

class Duck : AnimalBase { }

class HenHouse : ShelterBase<Duck>
{
    public override List<Duck> GetAnimals()
    {
        return new List<Duck>();
    }

    public override void FeedAnimals(List<Duck> animals)
    {
        // feed them
    }
}

class Program
{
    static void Main(string[] args)
    {
        List<ShelterBase<AnimalBase>> shelters = new List<ShelterBase<AnimalBase>>();

        ///////////////////////////// following two lines do not compile
        shelters.Add(new Stable());
        shelters.Add(new HenHouse());
        /////////////////////////////

        foreach (var shelter in shelters)
        {
            var animals = shelter.GetAnimals();
            // do sth with 'animals' collection
        }
    }
}

A: You can do this using covariance and contravariance, but your ShelterBase class needs to derive from an interface, since only interfaces can be co- or contravariant.  You list will need to be a List<IShelterBase<T>> and it should work.
See here for more info

A: To solve this particular problem you don't actually need covariance. When you consume animal lists, you still get AnimalBase through IShelterBase<out T> interface. Might as well expose a list of AnimalBase through the base class.
A better and cleaner design would be to make GetAnimals return a list of AnimalBase, and to create an overload in each shelter class to return a list of that particular animal.
abstract class ShelterBase<T> where T : AnimalBase
{
    public List<AnimalBase> GetAnimals(){return new List<AnimalBase>();}
}

class Stable : ShelterBase<Horse>
{
    public List<Horse> GetHorses(){return new List<Horse>();}
}

Another problem with this design is exposing a collection through the most derived type - i.e. List, as opposed to IEnumerable or IList. Seeing as you went into trouble of creating a class abstracting a collection of animals, you should really protect the inner collection by disallowing direct insert/delete ability. Once you do that, things become a bit easier. E.g. here is how I would solve this problem.
abstract class ShelterBase<T> where T : AnimalBase
{
    protected List<T> _Animals;
    public AnimalBase() {
       _Animals = CreateAnimalCollection();
    }

    protected abstract List<T> CreateAnimalCollection();
    public IEnumerable<AnimalBase> GetAnimals(){return _Animals.Cast<AnimalBase>();}

    //Add remove operations go here
    public void Add(T animal){_Animals.Add(animal);}
    public void Remove(T animal){_Animals.Remove(animal);}

}

class Stable : ShelterBase<Horse>
{
    protected override List<Horse> CreateAnimalCollection(){return new List<Horse>();}

    public IEnumerable<Horse> GetHorses(){return _Animals;}
}

You will notice that the internal collection of animals is never exposed as mutable list. This is good, as it allows you tighter control over its contents. The Add and Remove methods in the base shelter are a bit contrived in this example as they don't add anything extra over direct collection access, but you can add logic there - e.g. checking for maximum shelter size when adding or checking the animal age before removing it.

A: You can use contravariance, but only if you change your abstract class to an interface and the return type of GetAnimals to an IEnumerable<T>, because List<T> doesn't support this feature.
Code that works:
abstract class AnimalBase { public int SomeCommonProperty;}

interface IShelterBase<out T> where T : AnimalBase
{
    IEnumerable<T> GetAnimals();
}

class Horse : AnimalBase { }

class Stable : IShelterBase<Horse>
{
    public IEnumerable<Horse> GetAnimals()
    {
        return new List<Horse>();
    }
}

class Duck : AnimalBase { }

class HenHouse : IShelterBase<Duck>
{
    public IEnumerable<Duck> GetAnimals()
    {
        return new List<Duck>();
    }
}

void Main()
{
    List<IShelterBase<AnimalBase>> shelters = new List<IShelterBase<AnimalBase>>();

    shelters.Add(new Stable());
    shelters.Add(new HenHouse());

    foreach (var shelter in shelters)
    {
        var animals = shelter.GetAnimals();
        // do something with 'animals' collection
    }
}

A: An article on co and contra-variance in generics:
http://msdn.microsoft.com/en-us/library/dd799517.aspx

A: I just got a similar problem.
All my entities derive from a base class and I created a method to return a concatenated list of ids. So created the method with generics and got some convert errors. Managed to cast the generic T to Object and Object to BaseClass and put some sort of validation just in case.
//Needs it generic to use in a lot of derived classes
private String ConcatIds<T>(List<T> listObj)
{
    String ids = String.Empty;

    foreach (T obj in listObj)
    {
        BaseEntity be = CastBack(obj);

        if (ids.Count() > 0)
            ids = ids + String.Format(", {0}", be.Id);
        else
            ids = be.Id.ToString();
    }

    return ids;
}

//I'll probably move it to the Base Class itself
private BaseEntity CastBack<T>(T genericObj)
{
    Type type = typeof(T);

    if (type.BaseType == typeof(BaseEntity))
    {
        Object _obj = (Object)genericObj;
        return (BaseEntity)_obj;
    }
    else
    {
        throw new InvalidOperationException(String.Format("Cannot convert {0} to BaseEntity", type.ToString()));
    }
}

usage:
public class BaseEntity
{
   public Int32 Id {get; set;}
}

public class AnyDerivedClass : BaseEntity
{
  // Lorem Ipsum
}

private void DoAnything(List<AnyDerivedClass> myList)
{
    String ids = this.ConcatIds<AnyDerivedClass>(myList);
}

Edit: After a while I needed to create more hierarchy level and sometimes cast back to parent or to grand parent. So I let my CastBack method more generic.
private B CastBack<T,B>(T genericObj)
{
    Type type = typeof(T);

    if (type.BaseType == typeof(B))
    {
        Object _obj = (Object)genericObj;
        return (B)_obj;
    }
    else
    {
        throw new InvalidOperationException(String.Format("Cannot cast back {0}", type.ToString()));
    }
}


text:
Q: Automorphisms proof Disclaimer: I am new to the subject of Isomorphisms of Groups, so I may need some guidance here.
This is what I am working on:

Show that if $k$ and $n$ are relatively prime positive integers, then the function $f(x) = kx$ is an automorphism of $(\mathbb{Z_n},+)$.

I know that an isomorphism of a group with itself is called an automorphism. My textbook does not provide any examples of groups that are automorphic and that is the problem here. So for this problem, what are the conditions that I am suppose to know in order to carry out this problem? Any insights are greatly appreciated.

A: Hint: Prove that $f$ is an injective homomorphism.
(Make sure you understand why this suffices.)


text:
Q: Backing up a disk image with Time Machine I'm storing backup of my Gmail account in a disk image, to cut on number of files on the main HFS+ volume. This makes Time Machine ignore the existence of this volume, just because it's in a disk image.
Is it possible to get Time Machine to treat the disk image as a regular disk, and get Time Machine to back it up as if it were a "physical" volume?
This is on Mountain Lion 10.8.2, on late 2009 white unibody Macbook.

A: To back up a disk image, you back up the .dmgfile itself, instead of the virtual disk the system shows you.
However, unless the disk image is a sparse bundle image. Time machine will have to backup the entire disk every time the disk changes.


text:
Q: Is there a way to fade in background colors using javascript? I have a div with onClick (colorRefresh) and the script works fine but I would like to know if I could fade it in.
 function colorRefresh()
{ body[0].style.backgroundImage = `linear-gradient(to right, rgb(${colorOne[0]},${colorOne[1]},${colorOne[2]}),rgb(${colorTwo[0]},${colorTwo[1]},${colorTwo[2]})).fadeIn()`;
}

I tried to use fadeIn() but nothing happens. How do I go about doing this?


text:
Q: php json_decode returns null every time I am using json_decode on file_get_contents("php://input") but I get null every time.
I output file_get_contents("php://input") and got output in this format a=1&b=2.
How can I convert this to an array?

A: Why json_decode?! Use parse_str


text:
Q: How to avoid the change of timestamp of files when moving then from directory When I move files from one directory to another, the timestamp of the files changes. For example, if the file was created with  a date 2013-01-01, when I move it to a different directory, the final file will have the date of the move, not of the creation.
How to fix this?

A: *

*cp -r -p SOURCE DESTINATION

*cp -r --preserve=mode,ownership,timestamps SOURCE DESTINATION
These two commands do the same thing.  The Second allows you to chose what remains the same.  I am not aware of a way of specifically doing this with mv, but I believe this is mvs default behavior.
Alternatively, you could try copying hard-links, which is much more similar to mv, as suggested here:

*

*cp -p -r -l source/date target/
I believe the problem you are experiencing is due to an ntfs/fat partition?  If this is true, try setting up a rule in /etc/fstab that uses your uid.


text:
Q: Solve pde problem For each of the following PDE. (a) solve the characteristic equation (b) define a transformation of the PDE. And obtain the transformed equation. (c) find the general solution of the transformed equation.
$$xu_x-yu_y+u =x $$
Let $r=r(r,s) ,s=s (r,s) $
Char. eq. :
$$\frac{dy}{dx}= \frac {-y}{x} $$
$$\frac{dy}{y}= \frac {-dx}{x} $$
$$lny =-lnx + c$$
$$s=c =lnx+lny=lnxy $$
let r=x
$$u_x=u_r +\frac {u_s}{x}$$
$$u_y=0 +\frac {u_s}{y}$$
Substitute in eq.$(r=x,s=lnxy)$
$$ru_r+u_s -u_s+u =r $$
$$ru_r+u=r $$
First one homogeneous  eq
$$u_r+\frac {u}{r}=0$$
$$M= exp ( \int (1/r))=r$$
$$ru_r+u=0$$
$$u = \frac {F (s)}{r}=\frac{F (lnxy) }{x}$$
How to find nonhomogenes  for this problem?
Thanks

A: $$ru_r+u=r$$
You want the solution for this equation ?
$$r\frac {du}{dr}+u=r$$
$$(ru)'=r$$
Just integrate
$$ru=\int rdr=\frac {r^2}2+K(s)$$
$$u=\frac 1r( \frac {r^2}2+K(s))$$
$$\boxed{u(r,s)=\frac {K(s)}r+ \frac {r}2}$$

A: $$x u_x-y u_y=x-u$$
$$\frac{dx}{x}=\frac{dy}{-y}=\frac{du}{x-u}$$
A first family of characteristic curves comes from $\quad \frac{dx}{x}=\frac{dy}{-y}$
$$xy=c_1$$
A second family of characteristic curves comes from $\frac{dx}{x}=\frac{du}{x-u}=\frac{-dx+2du}{-x+2(x-u)}=\frac{d(-x+2u)}{-(-x+2u)}$
$$x(-x+2u)=c_2$$
General solution of the PDE :
$$x(-x+2u)=\Phi(xy)$$
$$u(x,y)=\frac12\left(x+\frac{1}{x}\Phi(xy) \right)$$
$\Phi$ is an arbitrary function, to be determined according to the boundary conditions.


text:
Q: REST - Typed resources vs HYDRA classes From Fielding's article (https://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven):

A REST API should never have "typed" resources that are significant to the client. Specification authors may use resource types for describing server implementation behind the interface, but those types must be irrelevant and invisible to the client. The only types that are significant to a client are the current representation's media type and standardized relation names. [ditto]

In HYDRA, classes can be documented in the API documentation like this:
supportedClass:
  '@id': 'schema:Event'
    supportedProperty:
      - property:
          '@id': eventName

Isn't it considered a typed resource? There is even a @type field in JSON-LD. I understand the importance of standardized relation names, as they give clients the semantics, the format and constraints necessary to do useful stuff with the resource or property, however by limiting the range of possible relations in the API documentation, we are really declaring types (classes).
Without classes, clients won't know what relations will be present, and coding a client so it knows most relation types (e.g. from schema.org) isn't practical.
What is the exact meaning of this constraint, and how could it be useful in practice? Does HYDRA not respect this?

I'm asking this out of theoretical interest. In practice, I don't care if my HTTP API satisfies all constraints if it is usable.

A: I think I get the difference between 'typed resources' (as Fielding calls them), and types or classes defined in media-types like JSON-LD/HYDRA. I'm answering my own question, but please extend/correct it if necessary.

TL;DR my understanding is that this constraint refers to types as predefined representations (or structures) of the resource, and advocates documenting possible relations and media-type processing rules instead of this structure. These relations can still be grouped under 'types', but the representation will not be rigid.

Properties usually have predefined names and understood in the context of its enclosing type. This means that the server/client should agree on this naming convention in order to process these types, and a field named the same in one type as in a different type may have a fully different semantics. It yields a rigid structure for resources.
On the other hand, hypermedia types like JSON-LD do not use properties in a common way. They instead use some embedded information (@context) to define the semantics of the properties, which can be other entities, value objects, references, etc...
By processing a resource with a given hypermedia type, the properties are translated to some well-defined relations, usually defined in a vocabulary. This means that the same relation can be reused for multiple types, e.g. a name field in a Person and Book could refer to the https://schema.org/name relation between them and value objects (e.g. simple string names).
This decouples the client from the server by allowing them to use a common vocabulary for relation types, and by defining processing rules for a media type, so it is advisable to preprocess the resource before using it directly in its serialized format (as you might not know how it is returned).
For example:
{
  "@context": "http://schema.org/",
  "@type": "Person",
  "@id": "http://srv.org/users/1",
  "name": "Jane Doe",
  "telephone": "(425) 123-4567",
  "url": "http://www.janedoe.com"
}

is the same resource as
{
  "@context": {
    "a": "http://schema.org/name",
    "b": "http://schema.org/telephone",
    "c": {
      "@id": "http://schema.org/url",
      "@type": "@id"
    }
  },
  "@type": "http://schema.org/Person",
  "@id": "http://srv.org/users/1",
  "a": "Jane Doe",
  "b": "(425) 123-4567",
  "c": "http://www.janedoe.com"
}

or even as
[
  {
    "@id": "http://srv.org/users/1",
    "@type": [
      "http://schema.org/Person"
    ],
    "http://schema.org/name": [
      {
        "@value": "Jane Doe"
      }
    ],
    "http://schema.org/telephone": [
      {
        "@value": "(425) 123-4567"
      }
    ],
    "http://schema.org/url": [
      {
        "@id": "http://www.janedoe.com"
      }
    ]
  }
]


text:
Q: Rails API : how to allow one single url to call my API? My environment is a Rails 7 API + React frontend.
The issue is that we need to call the API from the frontend only and prevent others urls to make any requests. I tried to configure this with the gem rack-cors and its file config/initializers/cors.rb as this (allowing only localhost:3001) :
Rails.application.config.middleware.insert_before 0, Rack::Cors do
    allow do
      origins 'http://localhost:3001'

      resource '*',
               headers: :any,
               methods: %i[get post put patch delete options head],
               expose: %w[Authorization Uid]
    end
  end

The problem is that a POST request made with POSTMAN is not blocked.
What did I miss ?
Thanks.
Julien


text:
Q: I want to drop only one table when ever sailsjs lift I want to migrate only one table to drop whenever sails lift I wanted to delete that table. How it is possible to do? Or is there any way to delete table after sails lift?
I already tried to add migrate : 'drop'    in that particular model but it won't work.
I am currently using sails 1.0 version

A: I found a way.
Sails Bootstrap
This runs before sails lifted
I drop the table here.

config/bootstrap.js

module.exports.bootstrap = async function() {
    await Users.destroy({});
};

A: Manually Delete
if you want to delete collection manually, you can use this command in shell.
db.collection.drop()
check this link for more detail click here
Delete via Sails.js
to use low-level native code for mongodb
// Get access to the native MongoDB client via the default Sails datastore.
var db = sails.getDatastore().manager;

db.collection('users').drop()

find link here link

A: In sails.js structure there is one file called bootstrap which located in config folder.
bootstrap file execute before sails server is lift.
so whatever you wan't to do before server lifting you can write code in this bootstrap file.
module.exports.bootstrap = function(callback) {
     Users.destroy({},(error,response)=>
     {
        if(error) { console.log("error while deleting table"); }
        else { callback(); }
     });
};


text:
Q: How to get localStorage working in vue testing I am trying to test vue components.
I have a vue single file component which uses vuex. My states are stored in store.js which makes use of localStorage. However, when I run npm test I get error that reads:

WEBPACK  Compiled successfully in 9416ms
MOCHA  Testing...
RUNTIME EXCEPTION  Exception occurred while loading your tests
ReferenceError: localStorage is not defined

Tools I am using for testing:
@vue/test-utils, expect, jsdom, jsdom-global, mocha, mocha-webpack

How I run the tests:

"test": "mocha-webpack --webpack-config node_modules/laravel-mix/setup/webpack.config.js --require tests/JavaScript/setup.js tests/JavaScript/**/*.spec.js"

A sample test, order.spec.js:
require('../../resources/assets/js/store/store');
require('../../resources/assets/js/app');
import { mount } from '@vue/test-utils';
import Order from '../../resources/assets/js/views/order/List.vue';
import expect from 'expect';

describe('Order', ()=>{
    it('has alert hidden by default', () => {
        let wrapper = mount(Order);
        expect(wrapper.vm.alert).toBe(false);
    })
})

In setup.js file I am loading jsdom like this:
require('jsdom-global')();

How do I fix this?

A: jsdom-global is using an old version of jsdom. jsdom has supported localStorage since 11.12.0.
To use jsdom 11.12+ with localStorage support, you can add jsdom window properties to the global scope yourself in a test setup file that runs before your tests:
/* setup.js */

const { JSDOM } = require('jsdom');

const jsdom = new JSDOM('<!doctype html>');
const { window } = jsdom;

function copyProps(src, target) {
  Object.defineProperties(target, {
    ...Object.getOwnPropertyDescriptors(src),
    ...Object.getOwnPropertyDescriptors(target),
  });
}

global.window = window;
global.document = window.document;
global.navigator = {
  userAgent: 'node.js',
};
global.requestAnimationFrame = function (callback) {
  return setTimeout(callback, 0);
};
global.cancelAnimationFrame = function (id) {
  clearTimeout(id);
};
copyProps(window, global);


text:
Q: data Table on JSF + PrimeFaces I need some help because I need to create dynamically tables in my page and for this I use
ui:repeat tag.
Here is my code in the jsf file:
<ui:define name="contenido">
    <p:fieldset legend="Cronograma">
        <ui:repeat value="#{cronogramaBean.cronogramaBB.listaParciales}" var="parciales">
            <br/>
            <p:dataTable id="tablaPacial"
                         value="#{**here I want to use the same item in the list that I use in the Ui:repeat**}"
                         var="parcial"
                         emptyMessage="No existen registros"
                         rows="10"
                         rowIndexVar="rowIndex"
                         sortBy="#{parcial.ordinal}"  sortOrder="ascending"
                         style="overflow: auto">
                <f:facet name="header">
                    <p:outputLabel value="#{parcial.ciclo.nombre}"/>
                </f:facet>
                <p:column headerText="Nº"
                          style="text-align: center; width: 20px">
                    <h:outputText value="#{rowIndex+1}"/>
                </p:column>
                <p:column headerText="Nombre"
                          style="width: 100px">
                    <h:outputText value="#{parcial.nombre}"/>
                </p:column>
            </p:dataTable>
        </ui:repeat>
    </p:fieldset>
</ui:define>

the ui:repat tag need's a in the value a list and a var to iterate the list, inside the ui:repeat I want to create the tables with the same list.
Is this posible?
How I can do that?

A: To answer your question, yes you can use the same value for ui:repeat and p:dataTable but it will do a behavior that you don't want. All tables will have exactly the same data.
To achieve what you want, you need to change #{cronogramaBean.cronogramaBB.listaParciales} for a List of List example :
public List<List<Partial>> getListaParciales()
{

}

And modify your view like this :
<ui:define name="contenido">
    <ui:repeat value="#{cronogramaBean.cronogramaBB.listaParciales}" var="parciales">
        <p:fieldset legend="Cronograma">
            <p:dataTable id="tablaPacial"
                    value="#{parciales}"
                    var="parcial"
                    emptyMessage="No existen registros"
                    rows="10"
                    rowIndexVar="rowIndex"
                    sortBy="#{parcial.ordinal}"  sortOrder="ascending"
                    style="overflow: auto">
                <f:facet name="header">
                    <p:outputLabel value="#{parcial.ciclo.nombre}"/>
                </f:facet>
                <p:column headerText="Nº"
                        style="text-align: center; width: 20px">
                    <h:outputText value="#{rowIndex+1}"/>
                </p:column>
                <p:column headerText="Nombre"
                        style="width: 100px">
                    <h:outputText value="#{parcial.nombre}"/>
                </p:column>
            </p:dataTable>
        </p:fieldset>
    </ui:repeat>
</ui:define>


text:
Q: sed: bad option in substitution expression : bad option in substitution expression I have a string like this
string="10.212.1.1/29"

and when I use sed command like this I am getting error of  bad option which is most probably due to /29 / is this . How I can fix this as I want to replace this part
my command is like this
sed -i "s/variable \"vpc\".*/variable \"vpc\" { default = \"$string\" }/g"  var.tf

A: use a different sed separator:
sed -i "s#variable \"vpc\".*#variable \"vpc\" { default = \"$string\" }#g"  var.tf