text:
Q: segmentation fault in file operations in c #include<stdio.h>

/* this is a lexer which recognizes constants , variables ,symbols, identifiers , functions , comments and also header files . It stores the lexemes in 3 different files . One file contains all the headers and the comments . Another file will contain all the variables , another will contain all the symbols. */

int main()
{
    int i;
    char a,b[20],c;
    FILE *fp1;

    fp1=fopen("source.txt","r"); //the source file is opened in read only mode which will passed through the lexer

    //now lets remove all the white spaces and store the rest of the words in a file

    if(fp1==NULL)
    {
        perror("failed to open source.txt");
        //return EXIT_FAILURE;
    }
    i=0;
    while(1)
    {

        a=fgetc(fp1);

        if(a !="")
        {
            b[i]=a;
        }
        else
        {

            fprintf(fp1, "%.20s\n", b);
            i=0;
            continue;
        }
        i=i+1;

        /*Switch(a)
        {
            case EOF :return eof;
            case '+':sym=sym+1;

            case '-':sym=sym+1;

            case '*':sym=sym+1;

            case '/':sym=sym+1;

            case '%':sym=sym+1;

            case '
        */
    }
return 0;
}

how does this code end up in segmentation fault?

A: And also, the string b is probably not null terminated. At some point in your code you need:
 b[i] = '\0';

A: It looks like it needs a check to be sure it is not writing beyond the end of array b.  If it reads over 20 characters, it will write past it and corrupt the stack.

A: There is no check to test the End of File.
Change
while(1)

to
while (!feof(fp1))

EDIT:
But the reason for seg-fault is the missing NULL char at the end of b. You can add the NULL char at the end of b just before writing it to the file:
b[i] = 0; // i must <=19
fprintf(fp1, "%.20s\n", b);

This way you also need to ensure that you don't stuff more than 19 char into b that way you always have space to write the NULL char.

A: Use your while like this:
...
 while((a=fgetc(fp1))!=EOF)
    {
        if(a !="")
        {
            b[i]=a;
        }
...

You will check every-time if a is different from EOF. If a equals EOF, the processing will stop.
I would consider reading a bigger buffer with fread() / fgets(), and parse the resulting string, instead of reading character by character. I think this may improve the overall performance of your parser.

A: SegFault?? usually INFINITE LOOP...

Use the following...

#include<stdio.h>

/* this is a lexer which recognizes constants , variables ,symbols, identifiers , functions , comments and also header files . It stores the lexemes in 3 different files . One file contains all the headers and the comments . Another file will contain all the variables , another will contain all the symbols. */

int main()
{
    int i;
    char a,b[20],c;
    FILE *fp1;

    fp1=fopen("source.txt","r"); //the source file is opened in read only mode which will passed through the lexer

    //now lets remove all the white spaces and store the rest of the words in a file

    if(fp1==NULL)
    {
        perror("failed to open source.txt");
        //return EXIT_FAILURE;
    }
    i=0;
    while(!feof(fp1))
    {

        a=fgetc(fp1);

        if(a !="")
        {
            b[i]=a;
        }
        else
        {

            b[i]='\0';
            fprintf(fp1, "%.20s\n", b);
            i=0;
            continue;
        }
        i=i+1;

        /*Switch(a)
        {
            case EOF :return eof;
            case '+':sym=sym+1;

            case '-':sym=sym+1;

            case '*':sym=sym+1;

            case '/':sym=sym+1;

            case '%':sym=sym+1;

            case '
        */
    }
return 0;
}

GoodLUCK!!
CVS @ 2600Hertz


text:
Q: Blaze: template inclusion with dynamic content I have something quite simple to solve, but couldn't find anything in the doc.
I want to create a reusable component with a title, and when I click on it, it open/close its content. Basically a collapsible accordion.
The only problem is content can vary.
Is something like the following code exists in Blaze ?
{{>Accordion title="a title"}}

a custom paragraph

{{/Accordion}}

{{>Accordion title="another title"}}

list 1

list 2

{{/Accordion}}

and would render into:

a title

a custom paragraph

another title

list 1

list 2

Is it possible ? Or do I have to create a separate Template for the content and call it with {{> Template.dynamic}}

A: Look for custom block helpers (other source):
<template name="header">

    {{#if ready}}
      {{> Template.contentBlock}}
    {{else}}
      {{> Template.elseBlock}}
    {{/if}}

</template>

<template name="examplePage">
  {{#header ready=Template.subscriptionsReady}}
    Example Page
  {{else}}
    Loading...
  {{/header}}
</template>

redpajama_set_name: RedPajamaStackExchange


text:
Q: When will one need to create a separate process in a Application? I was reading a article in Android developer blog Process and Threads which talks about creating new process for specific component of Application. But I failed to understand when will creating a new process in my application becomes a absolute need. Could you please help me understand following doubts I have in this regard.

*

*When as a developer I should feel I need to have a separate process for a Android component/s?

*Does introducing a new process has any side effect on application's overall performance?

Any other info is greatly appreciated.
Thanks,
SKU

A: Having a separate process can be useful if there are components of your application that do not necessarily need to both be running to be useful to the user, and the background task is critical to application "correctness" (either now or in the future). The classic example of this is an app that has a service where the service saves or uploads some  data that is critical to your application (critical meaning the only way to get the data back is to have the user re-enter it!). The service might be responsible for doing something like uploading or saving data, while the activity is just the interface for the user. So developers should decouple these two components to prevent problems that may arise from my next point..
Android was designed to run in a resource (especially memory) constrained environment, so processes deemed unimportant are killed periodically to open up memory for important ones by the "low memory killer" (LMK) (if you Google this you'll get tons of information on the topic). Things like foreground processes are understandably given a higher priority since they're currently in use, but they're sometimes killed off as well for reasons like consuming too much memory. Now, imagine you need to save off some data to a database after the user does something in the app and you use a service to do so to ensure that it is done even if the user navigates away from the app. Unless you create the service in its own process the process containing both the activity and the service is likely to be killed since the process belongs to a non-foreground activity.
However it is not always necessary to place the service in its own process, oftentimes simply giving the service its own thread will suffice; it's very application specific. I would only place a service in its own process if it took longer than maybe a few seconds (long enough for the user to navigate away from my application and for the LMK to step in) to perform some task in the background and that task related to the "correctness" of my application (I.E. saving data for later). For something like caching, stick to threads, since if the process gets prematurely killed you can just recreate that data later.
Another reason to have a separate process is if you're running a global service (a service that can be used by applications other than your own) that maybe you provide an interface with via an Activity for configuration.
As for the performance question, there will definitely be a performance hit for something like this. Interprocess communication is not cheap, so you should really only use a separate process if you fit into a specific use case, like the ones mentioned above. Also, there's a certain amount of memory overhead for maintaining a process, so that's another performance hit.

A: 1.)You need to do something on seperate process or thread when you don't want your app to behave slowly. As by introducing threads you force your app not to run on UI thread. Thus making your app responsive to other events. For Example : you can use threads when you have to fetch some data from web service so that it happens in background and doesn't effect your app.
2.)Threads should not be used..We should use AsyncTask or loaders rather in android.

A: 1.) In android 4.0 (and possibly 3.0, not sure though) The device does not let you use the HTTP Agent in the main thread, for this slows the UI..
This is when threads come in handy.
Also with the use of functions that need alot of cpu, if these are run in the UI thread, the UI will lag and not respond until the function finishes.
2.) as stated at 1, it will actually improve the visual performance of your app ;)


text:
Q: TSQL Weighted Average I am trying to create a TSQL function to calculate weighted average cost for inventory calculation. So given the following table structure
ProductId | DatePurchased | Qty | Cost
--------- | ------------- | --- | ----
1         | Jan 1         | 10  | 1.50
1         | Jan 10        | 5   | 2.00
1         | Jan 20        | 7   | 2.50

Now if on Jan 21 someone purchased 15 the weighted cost would be
((7 * 2.5) + (5 * 2.0) + (3 * 1.5)) / 15 = 2.13
Basically, that is the average cost of 7 from Jan 20, 5 from Jan 10 and 3 from Jan 1.
I am sure this can be done with some kind of recursive CTE, but by someone smarter than me.

A: A weight average is simple:
select sum(qty * cost) / sum(qty)
from t;

You are looking for something else.  Perhaps an "allocated" average:
select sum(case when cume_qty - qty < 15 then qty * cost
                else (cume_qty - 15) * cost
           end) as allocated_average
from (select t.*,
             sum(qty) over (partition by productid order by date desc) as cume_qty
      from t
     ) t
where cume_qty - qty < 15 and
      cume_qty >= 15;


text:
Q: ASP.NET: Search inside treeview nodes I have a treeview with some nodes
--Parent
  --Child-0
    --child-0.0
    --child-0.1
    --child-0.2
    --child-0.3
  --Child-1
  --Child-2

I am updating this treeview later on, how can u update/insert values into child-0.2 programmatically where i don't know how many child does Child-0 has?
Tried following code, but compiler doesn't like it
foreach (TreeNode n in Treeview1.Nodes[0].ChildNodes[0])
{
   //whats the syntax gonna be?
}

A: int childrenCount = Treeview1.Nodes[0].ChildNodes[0].ChildNodes.Count;


text:
Q: How to loop through TextBox controls? (C# WinForms) I have 49 text boxes that are on a form in a table-like format. Each row of textboxes belongs to a different category. I'm wondering how would I cycle through them all in an array?
Here's what I mean:
txtName(0).Text
txtOtherName(0).Text
txtName(1).Text
txtOtherName(1).Text
((and so on...))
Where (#) is a unique suffix of the textbox name.
I'm trying to avoid assigning them all separate variables (in each group) if possible. So I would have a total of 7 variables and 49 textboxes.
Any help is appreciated.
Thanks

A: You can traverse through each control this way
foreach (var control in this.Controls)
{
    var textBox = control as TextBox;
    if (textBox != null)
    {
          // do your stuff here
    }
}

A: This may help: root is the container or window, id is the control:
#region Find Control Recursive
public Control FindControlRecursive(Control root, string id)
{
    if (root.ID == id)
       return root;
    foreach (Control c in root.Controls)
    {
        Control t = FindControlRecursive(c, id);
        if (t != null)
           return t;
    }
    return null;
}
#endregion


text:
Q: Image- Xamarin.Form I have implemented a login page and now I want to add a header image; however, image does not show up on the view.
    public LoginView ()
    {
        InitializeComponent ();

        Title= "Login";

        Content = new StackLayout {
            Spacing = 20,
            Padding = 50,
            VerticalOptions = LayoutOptions.Center,
            Children = {
                new Image {Source="headerImage.jpg"},
                (username = new Entry { Placeholder = "Username" }),
                (password = new Entry { Placeholder = "Password", IsPassword = true }),
                (button=new Button { Text = "Login", TextColor = Color.White, BackgroundColor = Color.FromHex ("77D065")})
            }
        };

        button.Clicked += Login;
    }

A: Images need to be placed in the platform projects (iOS, Android, etc) not the shared Forms project.  See Working with Images for details.
"Images can be shared across platforms with Xamarin.Forms, they can be loaded specifically for each platform, or they can be downloaded for display."


text:
Q: how to use this WEBAPI in android apps without using any third party tool My requirement is to fetch the data from SQL Server database to mobile in Android Apps. For fetching data, I have used WEB API and developed this WEB API using VS2012.
While using Web Service, I got the data successfully from database and loaded in android apps. Now I am using WEB API instead of Web-service to fetch data from database.
How to use this WEB API in android apps without using any third party tool?

A: To use API  without third party tools you need to use SDK of web service which is provided by web service. include SDK in your project. you can also use jar file in library.
Or you can see better example from here


text:
Q: email sender backend with angularjs frontend If I was to make a page that sends emails from clients, what should i use for backend.  Of course, I mean what's the best & the easiest way?
I thought about slim php framework or similar stuff.
But can this be done easily with a node.js or any other cloud solutions?

A: My recomendation is implement the mail funcionality out from client service.
If you have an API backend consumed in your front-end, you should implement at this API.If you dont have right now a backend, create a simple nodejs backend for that functionallity, this will provide you high scalability and security for you email account.
I dont recommend you to use php for that. Ofcurse that you can do it, but if you do "magic things" do them right.

A:
thought about slim php framework

Is plain old PHP just too easy? It's between 1 and 5 lines of code without a framework depending on the security model.

can this be done easily with a node.js or any other cloud solutions?

Oh dear. You've been sitting too close to the sales people. node.js is not a "cloud solution". Yes node.js is quite capable of doing this, as is ASP, Java, Python, .NET, Perl, bash..... IMHO it's more difficult with node.js than with PHP - since you need to configure the node.js as a webserver and add libraries to support SMTP.


text:
Q: STM32G0B1CE Can the Boot Option bits be used to jump to system bootloader? I have seen that there are quite a few questions about jumping from an app to the ST system bootloader, for example this one. These use the method of setting the MSP and PC then doing the jump with a function pointer.
This seems to cause an issue with the system bootloader dual-bank management whereby the first jump fails and a second jump needs to be done.
My question is - would it be possible/better to use the user option bytes to jump to the bootloader instead?
Since the OB register is read during boot in the OBL phase, if we set both the "nBOOT1 bit" and "nBOOT_SEL bit" and clear the "nBOOT0 bit" then do a soft reset would this avoid the empty check weirdness and let us jump to the bootloader in one go?

(Just for context - this would be the first step of doing updates via CAN as the MCU in question has a CAN bootloader built in)
Thanks in advance!

A: After some time tinkering with a dev board and with some help from Tilen Majerle I found that this is indeed possible and does work well.
I added the following in my main() while(1) loop so that when the blue button is pressed, the user option bits are modified and a reset is performed.
I found that we don't have to do the soft reset ourselves as the HAL_FLASH_OB_Launch() function triggers the reset for us, after which we should boot into system memory according to the reference manual page 67.
Also I found that the flash and option bytes must be unlocked before setting the option bytes, but not locked afterwards or the reset won't occur.
Here is the code to do it:
if(HAL_GPIO_ReadPin(BUTTON_GPIO_Port, BUTTON_Pin) == GPIO_PIN_RESET)
{
   // Basic de-bounce for testing
   HAL_Delay(100);
   while(HAL_GPIO_ReadPin(BUTTON_GPIO_Port, BUTTON_Pin) == GPIO_PIN_RESET)
   {
      __NOP();
   }

   // Read, modify & write user option bits
   // nBOOT1 = 1, nBOOT_SEL = 1, nBOOT0 = 0; will select system memory as boot area
   uint32_t optBits = FLASH->OPTR;
   optBits = (optBits | FLASH_OPTR_nBOOT1 | FLASH_OPTR_nBOOT_SEL);
   optBits &= ~(FLASH_OPTR_nBOOT0);

   // Unlock flash
   HAL_FLASH_Unlock();

   // Clear OPTLOCK
   HAL_FLASH_OB_Unlock();

   // Set up struct with desired bits
   FLASH_OBProgramInitTypeDef optionBytesSetting = {0};
   optionBytesSetting.OptionType = OPTIONBYTE_USER;
   optionBytesSetting.USERConfig = optBits;
   optionBytesSetting.USERType = OB_USER_nBOOT0;

   // Write Option Bytes
   HAL_FLASHEx_OBProgram(&optionBytesSetting);

   HAL_Delay(10);

   // Soft reset
   HAL_FLASH_OB_Launch();
   NVIC_SystemReset();    // is not reached
}

I verified that the flash OPTR register is modified correctly (it goes from 0xFFFFFEAA to 0xFBFFFEAA, essentially just the nBOOT0 bit is cleared as the other two bits were already set). The MCU does reset at HAL_FLASH_OB_Launch() as expected and pausing the program reveals that after reset it is running the system bootloader based on the PC address.
I also verified it using STM32CubeProgrammer which allows me to view the PC and option bytes, plus lets me set nBOOT0 back to 1 and boot the board to my app.
As for reverting the OB settings programmatically, you could either use the Write Memory command before jumping to the app, or you could use the Go command to jump to the app then modify the option bytes first thing in your app.


text:
Q: Order by same input where in sqlite For my project I'm using sqlite normally I use mysql. In mysql I would make this query:
SELECT * FROM breeds where id in (2, 1, 4) ORDER BY FIELD(id, 2, 1, 4) ASC

I need to order by the where in ids. How can I get the same result in sqlite because FIELD is not working in sqlite?

A: You can use a case expression - basically that's what MySQL's field() function does:
select *
from breeds
where id in (2, 1, 4)
order by case id
    when 2 then 1
    when 1 then 2
    when 4 then 3
end

A: If you can create a string which is a comma separated list of the ids, like '2,1,4' then you can use the function INSTR():
SELECT * FROM breeds
WHERE id IN (2, 1, 4)
ORDER BY INSTR(',' || '2,1,4' || ',', ',' || id || ',')


text:
Q: Javascript Customize Confirm with "Yes" or "No" How do I have a Javascript confirm() box with "Yes" or "No" instead of the default "Ok" or "Cancel" ?

A: You cannot do it with standard javascript.
You have this workaround for IE only (source):
<script language=javascript>

/*@cc_on @*/
/*@if (@_win32 && @_jscript_version>=5)

function window.confirm(str)
{
    execScript('n = msgbox("'+str+'","4132")', "vbscript");
    return(n == 6);
}

@end @*/
var r = confirm("Can you do it?");
alert(r);
</script>

Or, you can use custom dialog from jquery ui

A: The javascript confirm dialog cannot be customized.
If you require dialog customization I would suggest looking at JQuery UI - Dialog

A: To put it simply i think you can't. There are a lot of answers about that on stack overflow, for example this one : custom choices in javascript confirm dialog that states it. If you want to do it, you have to use your own dialogs like those of jquery ui

A: Today, you can do it simply with javascript. There's is a simple js library called notiejs that has a confirm option.
With a simple line
notie.confirm('Title text', 'Yes button text', 'No button text', yes_callback)

you can have a custom confirm box. (Maybe the style or the interaction won't fit your use case but I'm just pointing out that it is possible).


text:
Q: Error when I compile 'hello-world' example from Contiki I have installed the Contiki OS sources, and the ARM GCC compiler by doing brew install arm-none-eabi-gcc. However, when I try to run the hello world example in Contiki's example folder using the command make TARGET=srf06-cc26xx BOARD=sensortag/cc2650 hello-world.bin CPU_FAMILY=cc26xx, I get the following error message:
  CC        ../../cpu/cc26xx-cc13xx/lib/cc26xxware/startup_files/ccfg.c
arm-none-eabi-gcc: error: unrecognized -march target: core2
arm-none-eabi-gcc: note: valid arguments are: armv4 armv4t armv5t armv5te armv5tej armv6 armv6j armv6k armv6z armv6kz armv6zk armv6t2 armv6-m armv6s-m armv7 armv7-a armv7ve armv7-r armv7-m armv7e-m armv8-a armv8.1-a armv8.2-a armv8.3-a armv8.4-a armv8.5-a armv8-m.base armv8-m.main armv8-r iwmmxt iwmmxt2
arm-none-eabi-gcc: error: missing argument to '-march='
arm-none-eabi-gcc: error: unrecognized command line option '-mssse3'
make: *** [obj_srf06-cc26xx/ccfg.o] Error 1

I triple-checked that the ARM GCC compiler is accessible from the terminal by doing arm-none-eabi-gcc --version, and I can see that it is properly installed:
arm-none-eabi-gcc (GNU Tools for Arm Embedded Processors 9-2019-q4-major) 9.2.1 20191025 (release) [ARM/arm-9-branch revision 277599]
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

So I am really not sure what might be wrong here. Can anyone help?
My operating system is macOS Mojave Version 10.14.6.
UPDATE: The makefile is given in the example folder (from contiki):
CONTIKI_PROJECT = hello-world
all: $(CONTIKI_PROJECT)

CONTIKI = ../..
include $(CONTIKI)/Makefile.include

UPDATE 2: By adding V=1 in the command, my output is:
arm-none-eabi-gcc -march=core2 -mtune=haswell -mssse3 -ftree-vectorize
 -fPIC -fPIE -fstack-protector-strong -O2 -pipe -DCONTIKI=1
-DCONTIKI_TARGET_SRF06_CC26XX=1 -DNETSTACK_CONF_WITH_IPV6=1
-DUIP_CONF_IPV6_RPL=1 -DBOARD_SENSORTAG=1 -DBACKDOOR_IOID=0x00000000
-I../../cpu/cc26xx-cc13xx/lib/cc26xxware -I../../cpu/cc26xx-cc13xx
/lib/cc26xxware/driverlib -I../../cpu/cc26xx-cc13xx/lib/cc26xxware/inc
-mcpu=cortex-m3 -mthumb -mlittle-endian -ffunction-sections -fdata-sections
 -fshort-enums -fomit-frame-pointer -fno-strict-aliasing -Wall -std=c99 -O2
  -I. -I../../platform/srf06-cc26xx/. -I../../platform/srf06-cc26xx
/sensortag/cc2650 -I../../platform/srf06-cc26xx/sensortag -I../../platform
/srf06-cc26xx/common -I../../cpu/cc26xx-cc13xx/. -I../../cpu/cc26xx-cc13xx/dev
-I../../cpu/cc26xx-cc13xx/rf-core -I../../cpu/cc26xx-cc13xx/rf-core/api -I../../cpu/cc26xx-cc13xx/lib/cc26xxware/startup_files -I../..
/cpu/cc26xx-cc13xx/../arm/common/dbg-io -I../../core/dev -I../../core/lib -I../../core/net -I../../core/net/llsec -I../../core/net/mac -I../..
/core/net/rime -I../../core/net/rpl -I../../core/sys -I../../core/cfs
-I../../core/ctk -I../../core/lib/ctk -I../../core/loader -I../../core/. -I../../core/sys -I../../core/dev -I../../core/lib -I../../core/net/ipv6 -I../../core/net/ip -I../../core/net/rpl -I../../cpu/cc26xx-cc13xx
/lib/cc26xxware/driverlib -I../../core/net -I../../core/net/mac -I../..
/core/net/mac/contikimac -I../../core/net/llsec -I../../platform/srf06-
cc26xx/ -I../.. -DCONTIKI_VERSION_STRING=\"Contiki-3.x-3345-g32b5b17\"
-include "contiki-conf.h" -c ../../cpu/cc26xx-cc13xx/lib/cc26xxware
/startup_files/ccfg.c -o obj_srf06-cc26xx/ccfg.o

UPDATE 3: If I do unset CFLAGS, I get a new error message:
/usr/local/Cellar/arm-none-eabi-gcc/9-2019-q4-major/gcc/bin/../lib/gcc/arm-none-eabi/9.2.1/../../../../arm-none-eabi/bin/ld: hello-world.elf section `.interp' will not fit in region `FLASH_CCFG'
/usr/local/Cellar/arm-none-eabi-gcc/9-2019-q4-major/gcc/bin/../lib/gcc/arm-none-eabi/9.2.1/../../../../arm-none-eabi/bin/ld: region `FLASH_CCFG' overflowed by 9120 bytes
/usr/local/Cellar/arm-none-eabi-gcc/9-2019-q4-major/gcc/bin/../lib/gcc/arm-none-eabi/9.2.1/../../../../arm-none-eabi/bin/ld: warning: cannot find entry symbol ad_strip_dylibs; defaulting to 0000000000000000
collect2: error: ld returned 1 exit status
make: *** [hello-world.elf] Error 1
rm obj_srf06-cc26xx/startup_gcc.o hello-world.co obj_srf06-cc26xx/fault-handlers.o

A: Here's a consolidation of @kfx's solution (which worked like a charm):

*

*unset CFLAGS

*unset LDFLAGS

*make clean
This is because there may be some other flags which you accidentally set previously, so you have to unset them in order for the compilation to work.


text:
Q: Merge conflict resolve Before that i've had experience that i needed to merge my feature in two branches and everything was ok, but not so long ago i had a problems with that. Previously i checkout first branch and merged there my feature branch and after i checkout my second branch and merged there my feature. Everything was ok before, but when i've done it last time first branch was merged to second and it became a problem. So i try to understand was it my mistakes as i didn't checkout and merge correct branches or i just don't understand how merging works.
For example i have 3 branches.
dev
feature-1
master

if i checkout dev and merge there feature-1 branch and after that i checkout master and merge there feature-1 branch, will full dev branch be moved to master as one branch (dev+feature-1) or only feature-1 branch will be merged in master? Hope you understand me.

A: Take a look at rebase it might simplify things for you ( git rebase doc ) .
so:

*

*rebase feature-1 on master :

git checkout feature-1
git rebase master

*then from master merge feature-1 (this will do a fast forward merge)

git checkout master
git rebase feature-1

*now repeat with dev branch

git checkout dev
git rebase master
git checkout master
git rebase dev

this is going to be much cleaner (my opinion) and maybe easier to understand


text:
Q: Delete with PQexec by given ID in C++ I am taking ID from my user and then i want to delete that ID from the database. I am using postgresql. but the query is not running. When i give hard code value like id=5 then it runs but when i give it user's value like id = DeleteId then it doesn't run. Here is the function:
void DeleteValue(PGconn *conn, int DeleteId)
      {

       PGresult *res = PQexec(conn, "DELETE FROM testData where ID =  DeleteId" );

         if (PQresultStatus(res) != PGRES_COMMAND_OK)
         {
           cout << "Delete testData record failed." << endl;
           PQclear(res);
           CloseConn(conn);
         }
          cout << "\nDelete testData record - OK\n";
          PQclear(res);
      }

A: Just solved my own problem.first concatenate it with the help of sprintf and then execute the query. Here is the solution of the problem
sprintf(sql,"DELETE FROM testData WHERE id = %d",DeleteId);
PGresult *res = PQexec(conn, sql );


text:
Q: Assigning a value to a certain number of rows within a "by" group - SAS I've spent quite a lot of time on Stack Overflow looking for answers to other questions, but I'm really stuck on this one, so I'm finally asking a question!
I have a dataset of fish in SAS, with:

*

*a unique ID for each angler

*three different variables with number of fish released in each category by that angler: over legal size, under legal size, and released dead

*a sequential number (fishno) based on the number of rows for each ID; 1 to the last row of that ID.

*Variable to be created: Disposition--could be either character variable with "legal" "under" "dead" options or even numeric values of 1-3.

It was originally set up with one row per unique ID, but I set it so that now there is one row per fish discarded (i.e. if there were 3 legal size and 2 undersize fish, I now have 5 rows).
I need to assign, by unique ID, whether each row/fish was released legal, undersize or dead. In the previous example, for a unique ID, I'd need 3 rows assigned to a Disposition of "legal" and 2 rows  assigned to a Disposition of "under".
I've tried first.var statements along with if-then-do statements; played around with macros; nothing worked quite right and I'm pretty stuck here. Is there some sort of random assignment I should try? Is there a much easier way that I'm missing?
Example of the data below...
THANK YOU!!
Data in Excel format

A: Assuming you already have the FISHNO variable, there needs to be some method for assigning each fish as legal, dead, or undersize. The following code will assign the disposition in the that order:
data have;
input ID LEGAL DEAD UNDERSIZE FISHNO;
datalines;
15 1 0 1 1
15 1 0 1 2
29 2 0 2 1
29 2 0 2 2
29 2 0 2 3
29 2 0 2 4
38 1 0 1 1
38 1 0 1 2
53 1 0 1 1
53 1 0 1 2
55 1 0 1 1
55 1 0 1 2
;
run;

data want;
set have;
if legal>0 and legal>=fishno then disposition = 'legal';
else if dead>0  and legal+dead>=fishno then disposition = 'dead';
else if undersize>0 and legal+dead+undersize>=fishno then disposition = 'under';
run;


text:
Q: Loading c++ dll in Asp.net Web App using winmd file I have a c++ dll, and an idl file that was used to generate a .winmd file.
I created a C# application that consumes the .winmd file and I can successfully create an object for a class that was defined in the dll. i.e the program compiles and runs without any issues.
However, when I try and use the same exact winmd file (which works when consumed by a C# application) for a C# Asp.net web app (i.e I add a reference to the winmd file and I see that the winmd file and dll are copied into my web apps bin folder), I get a runtime exception saying:
"Could not find Windows Runtime type [Name of class]"
When I use Fusion Logs to see what went wrong when the application was attempting to load the dll, I see this:
END   : Typename or Namespace was not found in metadata file. (Exception from HRESULT: 0x8000000F)
So my question is, what is the main difference between loading a native dll in a C# application vs an Asp.Net application?


text:
Q: Why is data being pushed into the channel but never read from the receiver goroutine? I am building a daemon and I have two services that will be sending data to and from each other. Service A is what produces the data and service B a is Data Buffer service or like a queue. So from the main.go file, service B is instantiated and started. The Start() method will perform the buffer() function as a goroutine because this function waits for data to be passed onto a channel and I don't want the main process to halt waiting for buffer to complete. Then Service A is instantiated and started. It is then also "registered" with Service B.
I created a method called RegisterWithBufferService for Service A that creates two new channels. It will store those channels as it's own attributes and also provide them to Service B.
func (s *ServiceA) RegisterWithBufferService(bufService *data.DataBuffer) error {
    newIncomingChan := make(chan *data.DataFrame, 1)
    newOutgoingChan := make(chan []byte, 1)
    s.IncomingBuffChan = newIncomingChan
    s.OutgoingDataChannels = append(s.OutgoingDataChannels, newOutgoingChan)
    bufService.DataProviders[s.ServiceName()] = data.DataProviderInfo{
        IncomingChan: newOutgoingChan, //our outGoing channel is their incoming
        OutgoingChan: newIncomingChan, // our incoming channel is their outgoing
    }
    s.DataBufferService = bufService
    bufService.NewProvider <- s.ServiceName() //The DataBuffer service listens for new services and creates a new goroutine for buffering
    s.Logger.Info().Msg("Registeration completed.")
    return nil
}

Buffer essentially listens for incoming data from Service A, decodes it using Decode() and then adds it to a slice called buf. If the slice is greater in length than bufferPeriod then it will send the first item in the slice in the Outgoing channel back to Service A.
func (b* DataBuffer) buffer(bufferPeriod int) {
    for {
        select {
        case newProvider := <- b.NewProvider:
            b.wg.Add(1)
            /*
            newProvider is a string
            DataProviders is a map the value it returns is a struct containing the Incoming and
            Outgoing channels for this service
            */
            p := b.DataProviders[newProvider]
            go func(prov string, in chan []byte, out chan *DataFrame) {
                defer b.wg.Done()
                var buf []*DataFrame
                for {
                    select {
                    case rawData := <-in:
                        tmp := Decode(rawData) //custom decoding function. Returns a *DataFrame
                        buf = append(buf, tmp)
                        if len(buf) < bufferPeriod {
                            b.Logger.Info().Msg("Sending decoded data out.")
                            out <- buf[0]
                            buf = buf[1:] //pop
                        }
                    case <- b.Quit:
                        return
                    }
                }
            }(newProvider, p.IncomingChan, p.OutgoingChan)
        }
    case <- b.Quit:
        return
    }
}

Now Service A has a method called record that will periodically push data to all the channels in it's OutgoingDataChannels attribute.
func (s *ServiceA) record() error {
    ...
    if atomic.LoadInt32(&s.Listeners) != 0 {
        s.Logger.Info().Msg("Sending raw data to data buffer")
        for _, outChan := range s.OutgoingDataChannels {
            outChan <- dataBytes // the receiver (Service B) is already listening and this doesn't hang
        }
        s.Logger.Info().Msg("Raw data sent and received") // The logger will output this so I know it's not hanging
    }
}

The problem is that Service A seems to push the data successfully using record but Service B never goes into the case rawData := <-in: case in the buffer sub-goroutine. Is this because I have nested goroutines? Incase it's not clear, when Service B is started, it calls buffer but because it would hang otherwise, I made the call to buffer a goroutine. So then when Service A calls RegisterWithBufferService, the buffer goroutine creates a goroutine to listen for new data from Service B and push it back to Service A once the buffer is filled. I hope I explained it clearly.
EDIT 1
I've made a minimal, reproducible example.
package main

import (
    "fmt"
    "sync"
    "sync/atomic"
    "time"
)

var (
    defaultBufferingPeriod int = 3
    DefaultPollingInterval int64 = 10
)

type DataObject struct{
    Data    string
}

type DataProvider interface {
    RegisterWithBufferService(*DataBuffer) error
    ServiceName() string
}

type DataProviderInfo struct{
    IncomingChan    chan *DataObject
    OutgoingChan    chan *DataObject
}

type DataBuffer struct{
    Running         int32 //used atomically
    DataProviders   map[string]DataProviderInfo
    Quit            chan struct{}
    NewProvider     chan string
    wg              sync.WaitGroup
}

func NewDataBuffer() *DataBuffer{
    var (
        wg sync.WaitGroup
    )
    return &DataBuffer{
        DataProviders: make(map[string]DataProviderInfo),
        Quit: make(chan struct{}),
        NewProvider: make(chan string),
        wg: wg,
    }
}

func (b *DataBuffer) Start() error {
    if ok := atomic.CompareAndSwapInt32(&b.Running, 0, 1); !ok {
        return fmt.Errorf("Could not start Data Buffer Service.")
    }
    go b.buffer(defaultBufferingPeriod)
    return nil
}

func (b *DataBuffer) Stop() error {
    if ok := atomic.CompareAndSwapInt32(&b.Running, 1, 0); !ok {
        return fmt.Errorf("Could not stop Data Buffer Service.")
    }
    for _, p := range b.DataProviders {
        close(p.IncomingChan)
        close(p.OutgoingChan)
    }
    close(b.Quit)
    b.wg.Wait()
    return nil
}

// buffer creates goroutines for each incoming, outgoing data pair and decodes the incoming bytes into outgoing DataFrames
func (b *DataBuffer) buffer(bufferPeriod int) {
    for {
        select {
        case newProvider := <- b.NewProvider:
            fmt.Println("Received new Data provider.")
            if _, ok := b.DataProviders[newProvider]; ok {
                b.wg.Add(1)
                p := b.DataProviders[newProvider]
                go func(prov string, in chan *DataObject, out chan *DataObject) {
                    defer b.wg.Done()
                    var (
                        buf []*DataObject
                    )
                    fmt.Printf("Waiting for data from: %s\n", prov)
                    for {
                        select {
                        case inData := <-in:
                            fmt.Printf("Received data from: %s\n", prov)
                            buf = append(buf, inData)
                            if len(buf) > bufferPeriod {
                                fmt.Printf("Queue is filled, sending data back to %s\n", prov)
                                out <- buf[0]
                                fmt.Println("Data Sent")
                                buf = buf[1:] //pop
                            }
                        case <- b.Quit:
                            return
                        }
                    }
                }(newProvider, p.IncomingChan, p.OutgoingChan)
            }
        case <- b.Quit:
            return
        }
    }
}

type ServiceA struct{
    Active                  int32 // atomic
    Stopping                int32 // atomic
    Recording               int32 // atomic
    Listeners               int32 // atomic
    name                    string
    QuitChan                chan struct{}
    IncomingBuffChan        chan *DataObject
    OutgoingBuffChans       []chan *DataObject
    DataBufferService       *DataBuffer
}

// A compile time check to ensure ServiceA fully implements the DataProvider interface
var _ DataProvider = (*ServiceA)(nil)

func NewServiceA() (*ServiceA, error) {
    var newSliceOutChans []chan *DataObject
    return &ServiceA{
        QuitChan:  make(chan struct{}),
        OutgoingBuffChans: newSliceOutChans,
        name:   "SERVICEA",
    }, nil
}

// Start starts the service. Returns an error if any issues occur
func (s *ServiceA) Start() error {
    atomic.StoreInt32(&s.Active, 1)
    return nil
}

// Stop stops the service. Returns an error if any issues occur
func (s *ServiceA) Stop() error {
    atomic.StoreInt32(&s.Stopping, 1)
    close(s.QuitChan)
    return nil
}

func (s *ServiceA) StartRecording(pol_int int64) error {
    if ok := atomic.CompareAndSwapInt32(&s.Recording, 0, 1); !ok {
        return fmt.Errorf("Could not start recording. Data recording already started")
    }
    ticker := time.NewTicker(time.Duration(pol_int) * time.Second)
    go func() {
        for {
            select {
            case <-ticker.C:
                fmt.Println("Time to record...")
                err := s.record()
                if err != nil {
                    return
                }
            case <-s.QuitChan:
                ticker.Stop()
                return
            }
        }
    }()
    return nil
}

func (s *ServiceA) record() error {
    current_time := time.Now()
    ct := fmt.Sprintf("%02d-%02d-%d", current_time.Day(), current_time.Month(), current_time.Year())
    dataObject := &DataObject{
        Data: ct,
    }
    if atomic.LoadInt32(&s.Listeners) != 0 {
        fmt.Println("Sending data to Data buffer...")
        for _, outChan := range s.OutgoingBuffChans {
            outChan <- dataObject // the receivers should already be listening
        }
        fmt.Println("Data sent.")
    }
    return nil
}

// RegisterWithBufferService satisfies the DataProvider interface. It provides the bufService with new incoming and outgoing channels along with a polling interval
func (s ServiceA) RegisterWithBufferService(bufService *DataBuffer) error {
    if _, ok := bufService.DataProviders[s.ServiceName()]; ok {
        return fmt.Errorf("%v data provider already registered with Data Buffer.", s.ServiceName())
    }
    newIncomingChan := make(chan *DataObject, 1)
    newOutgoingChan := make(chan *DataObject, 1)
    s.IncomingBuffChan = newIncomingChan
    s.OutgoingBuffChans = append(s.OutgoingBuffChans, newOutgoingChan)
    bufService.DataProviders[s.ServiceName()] = DataProviderInfo{
        IncomingChan: newOutgoingChan, //our outGoing channel is their incoming
        OutgoingChan: newIncomingChan, // our incoming channel is their outgoing
    }
    s.DataBufferService = bufService
    bufService.NewProvider <- s.ServiceName() //The DataBuffer service listens for new services and creates a new goroutine for buffering
    return nil
}

// ServiceName satisfies the DataProvider interface. It returns the name of the service.
func (s ServiceA) ServiceName() string {
    return s.name
}

func main() {
    var BufferedServices []DataProvider
    fmt.Println("Instantiating and Starting Data Buffer Service...")
    bufService := NewDataBuffer()
    err := bufService.Start()
    if err != nil {
        panic(fmt.Sprintf("%v", err))
    }
    defer bufService.Stop()
    fmt.Println("Data Buffer Service successfully started.")

    fmt.Println("Instantiating and Starting Service A...")
    serviceA, err := NewServiceA()
    if err != nil {
        panic(fmt.Sprintf("%v", err))
    }
    BufferedServices = append(BufferedServices, *serviceA)
    err = serviceA.Start()
    if err != nil {
        panic(fmt.Sprintf("%v", err))
    }
    defer serviceA.Stop()
    fmt.Println("Service A successfully started.")

    fmt.Println("Registering services with Data Buffer...")
    for _, s := range BufferedServices {
        _ = s.RegisterWithBufferService(bufService) // ignoring error msgs for base case
    }
    fmt.Println("Registration complete.")

    fmt.Println("Beginning recording...")
    _ = atomic.AddInt32(&serviceA.Listeners, 1)
    err = serviceA.StartRecording(DefaultPollingInterval)
    if err != nil {
        panic(fmt.Sprintf("%v", err))
    }
    for {
        select {
        case RTD := <-serviceA.IncomingBuffChan:
            fmt.Println(RTD)
        case <-serviceA.QuitChan:
            atomic.StoreInt32(&serviceA.Listeners, 0)
            bufService.Quit<-struct{}{}
        }
    }
}

Running on Go 1.17. When running the example, it should print the following every 10 seconds:
Time to record...
Sending data to Data buffer...
Data sent.

But then Data buffer never goes into the inData := <-in case.

A: To diagnose this I changed fmt.Println("Sending data to Data buffer...") to fmt.Println("Sending data to Data buffer...", s.OutgoingBuffChans) and the output was:
Time to record...
Sending data to Data buffer... []

So you are not actually sending the data to any channels. The reason for this is:
func (s ServiceA) RegisterWithBufferService(bufService *DataBuffer) error {

As the receiver is not a pointer when you do the s.OutgoingBuffChans = append(s.OutgoingBuffChans, newOutgoingChan) you are changing s.OutgoingBuffChans in a copy of the ServiceA which is discarded when the function exits. To fix this change:
func (s ServiceA) RegisterWithBufferService(bufService *DataBuffer) error {

to
func (s *ServiceA) RegisterWithBufferService(bufService *DataBuffer) error {

and
BufferedServices = append(BufferedServices, *serviceA)

to
BufferedServices = append(BufferedServices, serviceA)

The amended version outputs:
Time to record...
Sending data to Data buffer... [0xc0000d8060]
Data sent.
Received data from: SERVICEA
Time to record...
Sending data to Data buffer... [0xc0000d8060]
Data sent.
Received data from: SERVICEA

So this resolves the reported issue (I would not be suprised if there are other issues but hopefully this points you in the right direction). I did notice that the code you originally posted does use a pointer receiver so that might have suffered from another issue (but its difficult to comment on code fragments in a case like this).


text:
Q: "How to use argparse module and call the function from command line?" I am trying to use argparse in my code and call the function from the command prompt. But I don't know, how the argparse can be used? what should be there in my add-arguments in order to get my expected result?
I have tried to add arguments but getting the error. I am new to this. Can anyone help me and show how to format the code?
import argparse

for i in range(4):
    def func():
        global a
        a = 5
        print("today")
        print("yesterday")

    def func1():
        func()
        print(a)
        print('function 1')

parser=argparse.ArgumentParser()
parser.add_argument()
args = parser.parse_args()

my expected result is
today
yesterday
5
function 1
today
yesterday
5
function 1
today
yesterday
5
function 1
today
yesterday
5
function 1
Can anyone give me an example how to give command line values in python? and if i have some optional parameter in function how can i use argparse to make the function work from cmd?
Thanks in advance.


text:
Q: Как лучше добавлять элементы в bytearray Есть код на Си
for (int i = 0, int j = 0; i < size; i++)
{
    switch (buf[i])
    {
    case '[':
    case ']':
    case '\\':
        tbuf[j++] = '\\';
        tbuf[j++] = ~buf[i];
        break;
    default:
        tbuf[j++] = buf[i];
        break;
    }
}

Как его правильно переписать на python?
for i in buf:
    if i in b'[]\\':
        tbuf += b'\\' + bytes((~i & 0xFF, ))
    else:
        tbuf += bytes((i, ))

В данном варианте не нравится преобразование к bytes через кортеж, использование операции & 0xFF для ограничения значения переменной

A: Для добавления одного байта (как числа) к bytearray можно использовать метод append.
По поводу операции ~i & 0xFF - это инвертирование бит (замена 0 на 1 и наоборот) в пределах одного байта, это можно сделать с помощью применения к числу битового XOR со значением 0xFF, получится на одну операцию меньше.
tbuf = bytearray()

for i in buf:
    if i in b'[]\\':
        tbuf += b'\\'
        tbuf.append(i ^ 0xFF)
    else:
        tbuf.append(i)


text:
Q: Where can I find what "Fields" are in my Azure Storage Blob Container for use with Azure Search Index? I can't seem to find this information in any MSFT documentation. I'm wanting to create a new search index from an already existing Storage Blob Container, but can't seem to do so by clicking on the "Add Search" button from the storage view. So, I decided to go the other way and create the index by linking to the blob storage, but selecting "Import Data >  existing blob" gives another error when trying to validate the data:
Error detecting index schema from data source: ""
Searching on that error led me to this:
AzureSearch- Error on detecting index schema from data source
which was not helpful.

A: Sorry to hear that the Azure Portal is not working when you try to import a Blob container into Azure Search. Is it possible to try the Create Indexer REST Api or the SDK? There's a sample on how to use the SDK to create indexers. There's also a guide you can follow which walks you through all the steps the portal takes when it runs the import data step.


text:
Q: parallel execution failure in python? I have code like:
import pandas as pd
import multiprocessing as mp

a = {'a' : [1,2,3,1,2,3], 'b' : [5,6,7,4,6,5], 'c' : ['dog', 'cat', 'tree','slow','fast','hurry']}
df = pd.DataFrame(a)

def performDBSCAN(feature):
    value=scorecalculate(feature)
    print(value)
    for ele in range(4):
        value=value+1
        print('here value is ', value)
    return value

def processing(feature):
    result1=performDBSCAN(feature)
    return result1

def scorecalculate(feature):
    scorecal=0
    for val in ['a','b','c','d']:
        print('alpha is:', val )
        scorecal=scorecal+1
    return scorecal

columns = df.columns
for ele in df.columns:
    processing(ele)

The above code is executing in a serial fashion. I would like to make faster by using multiprocessing in python and wrote the following code.
import pandas as pd
import multiprocessing as mp

def performDBSCAN(feature):
    value=scorecalculate(feature)
    print(value)
    for ele in range(4):
        value=value+1
        print('here value is ', value)
    return value

def scorecalculate(feature):
    scorecal=0
    for val in ['a','b','c','d']:
        print('alpha is:', val )
        scorecal=scorecal+1
    return scorecal

def processing(feature):
    result1=performDBSCAN(feature)
    return result1

a = {'a' : [1,2,3,1,2,3], 'b' : [5,6,7,4,6,5],
'c' : ['dog','cat','tree','slow','fast','hurry']}
df = pd.DataFrame(a)
columns = df.columns
pool = mp.Pool(4)
resultpool = pool.map(processing, columns)

I want to see the output but the kernel is continuously running without any output? what could be the issue?


text:
Q: How to integrate Orbeon and another Spring Web application running in separate Tomcat server? I am new to Orbeon. My company has a requirement to integrate our Spring MVC application with Orbeon. I read many posts about deploying Orbeon and Spring app war files separately but mostly within the same Tomcat container by using crossContext config. Is there a way to have both applications running on separate tomcat servers? If so, are there examples available online?

A: Orbeon Forms 4.7 will have a built-in embedding solution, see Server-side Form Runner embedding #1808. Until that is done, there is no good solution.


text:
Q: Publishing error in American edition of The Lord of the Rings I am working on a research project about The Lord of the Rings and my English teacher mentioned some sort of publishing error when the books were being sent to the US for publishing. She has further hinted that it wasn't the copyright/lawsuit issues that it also encountered. Does anyone know anything about this?

A: It's hard to know exactly what your teacher is referring to. However, recent editions of LoTR include at the beginning a "Note on the Text" written by Douglas A. Anderson, which talks about the history of the revisions made in different editions, and in particular mentions the changes that happened when it was republished in the US.

In 1965, stemming from what then appeared to be copyright problems in the United States, an American paperback firm published an unauthorized and non-royalty-paying edition of The Lord of the Rings. [...]
Tolkien set to work on his first revision of the text so that a newly revised and authorized edition could successfully compete on the American market. This first revision of the text was published in America in paperback by Ballantine Books, under licence from Houghton Mifflin, in October 1965. In addition to revisions within the text itself, Tolkien replaced his original foreword with a new one. [...]
[...] Soon after this he sent a small number of further revisions to Ballantine for the appendicies, including the now well-known addition of 'Estella Bolger' as wife of Meriadoc in the family trees in Appendix C. Most of these revisions [...] somehow never made it into the main sequence of revision in the three-volume British hardcover edition.


text:
Q: Granting access to authzTo attribute I'm trying to grant certain accounts auth access to their authzTo attribute in order to allow proxied authorization.
I tried adding this ldif:
dn: olcDatabase={-1}frontend,cn=config
changetype: modify
add: olcAccess
olcAccess: {1}to authzTo by dn.children="ou=Special Accounts,dc=example,dc=com" auth
-

using the command ldapadd -f perm.ldif -D "cn=admin,cn=config" -W
but got this error:
modifying entry "olcDatabase={-1}frontend,cn=config"
ldap_modify: Other (e.g., implementation specific) error (80)
    additional info: <olcAccess> handler exited with 1

using verbose output and turning up the debug level haven't given me any more clues.  Can anyone see what I'm doing wrong?

A: Realized what I was doing dumb after working on some other permissions.  It should be attrs=authzTo, not just authzTo by itself.  And what I really wanted was
to dn.children="ou=Special Accounts,dc=example,dc=com" attrs=authzTo by self auth

A: EDIT: OP explicitly asked about 'auth', not 'write' access, so this answer is not very relevant.
I realize that I'm 8 years late for this question, but I think that it needs to be noted that it's a bad idea to permit write access to own authzTo attribute.

Source rules are extremely powerful. If ordinary users have access to
  write the authzTo attribute in their own entries, then they can write
  rules that would allow them to authorize as anyone else. As such, when
  using source rules, the authzTo attribute should be protected with an
  ACL that only allows privileged users to set its values.

(quote from https://www.linuxtopia.org/online_books/network_administration_guides/ldap_administration/sasl_SASL_Proxy_Authorization.html)


text:
Q: Operator targeting $\ell^2$-direct sum of Hilbert spaces continuous if all its projections are continuous? Let $(U, \|\cdot\|_U)$ be a Banach space, $(H_k, \|\cdot\|_k)_{k\in\mathbb{N}}$ be a sequence of Hilbert spaces and denote by
$$\tag{1}H:=\bigoplus_{k=1}^\infty H_k \equiv \left\{h=(h_k)\ \middle| \ h_k \in H_k, \,\forall k\in\mathbb{N} \quad \text{and} \quad \|h\|_H^2:=\sum_{k=1}^\infty\|h_k\|_k^2 < \infty \right\}$$
the $\ell^2$-direct sum of these spaces (which is known to be a Hilbert space itself).
Let further $\pi_k : H \rightarrow H_k$, $\pi_k((h_k)) := h_k$, be the projection of $H$ onto its $k^{\mathrm{th}}$-component.
Question: Is it true, then, that a (not necessarily linear) map $T : U \rightarrow H$ is $\textit{continuous}$ if its projections
$$\tag{2}T_k := \pi_k\circ T \quad \text{are continuous} \quad \text{for each } \ k\in\mathbb{N}?$$
Remark: If necessary, it may be assumed that each of the $H_k$ are finite-dimensional.
Any references, hints or proofs (or indeed counterexamples) that cover this are appreciated!
(This is not a homework question.)

A: Here is a counter example: take $U={\mathbb R}$  and $H_k={\mathbb R}$, for all $k$, so that $H=\ell ^2$.
Let $f:{\mathbb R}\to {\mathbb R}$ be the function whose graph is a triangle
with vertices $(0,0)$, $(1,1)$, and $(2,0)$, hence vanishing identically on $(-\infty ,0]\cup [2,\infty )$, and consider the map
$$
  T:U\to H=\ell ^2,
  $$
given by
$$
  T(x) = \big (f(x), f(2x), f(3x), \ldots \big ).
  $$
Then clearly $\pi _k\circ T$ is continuous for all $k$.  However
$$
  \|T(0)-T(1/n)\| =
  \|T(1/n)\| \geq  $$$$ \geq    \|\pi _n\big (T(1/n)\big ) )\| = |f(1)| = 1,
  $$
so $T(1/n)$ does not converge to $T(0)$, hence $T$ is not continuous at 0.


text:
Q: Avro format deserialization in Spark structured stream I'm using Spark Structured Streaming as described on
this page.
I get correct message from Kafka topic but value is in Avro format. Is there some way to deserialize Avro records (something like KafkaAvroDeserializer approach)?

A: Spark >= 2.4
You can use from_avro function from spark-avro library.
import org.apache.spark.sql.avro._

val schema: String = ???
df.withColumn("value", from_avro($"value", schema))

Spark < 2.4

*

*Define a function which takes Array[Byte] (serialized object):
import scala.reflect.runtime.universe.TypeTag

def decode[T : TypeTag](bytes: Array[Byte]): T = ???

which will deserialize Avro data and create object, that can be stored in a Dataset.

*Create udf based on the function.
val decodeUdf  = udf(decode _)

*Call udf on value
val df = spark
  .readStream
  .format("kafka")
  ...
  .load()

df.withColumn("value", decodeUdf($"value"))


text:
Q: Url button from web There are buttons like this:

   Upload:

   <input type="file" name="datafile" size="40">

Is it possible to have a button in which user can include (copy/paste) the url of a photo somewhere in the web?
Example: I want to have press button which will ask the user to insert a link of image from web like this and it will take the picture

A: I understand that this is a vague answer, but it's only as vague as your question.  If this is NOT what you want, please tell us what the end result should look like.

function writeImage(url){

  document.body.innerHTML = '';

  }
<input type="text" id="imgUrl" size="30" value="http://placekitten.com/g/300/200" placeholder="image url here"/><input type="button" value="Insert Image" onclick="writeImage(document.getElementById('imgUrl').value)"/>

Copy and paste this into a webpage:
    <input type="text" id="imgUrl" size="30" value="http://placekitten.com/g/300/200" placeholder="image url here"/><input type="button" value="Insert Image" onclick="writeImage(document.getElementById('imgUrl').value)"/>


text:
Q: How can I type a function argument as native function I have a helper function to use in python repl to move variables to global for easy debugging. But there is a mypy error:
class stepin(object):  # pylint: disable=R0903
    def __init__(self, func: Callable) -> None:
        self.func = func
        self.args = func.__code__.co_varnames
        if hasattr(func, "__defaults__") and func.__defaults__:
            self.defaults = dict(zip(reversed(self.args), reversed(func.__defaults__)))
        else:
            self.defaults = None

    def __call__(self, *args, **kwargs):
        result_dict = {x: None for x in self.args}
        if self.defaults:
            result_dict.update(self.defaults)
        result_dict.update(dict(zip(self.args, args)))
        result_dict.update(kwargs)
        for x in result_dict.keys():
            if result_dict[x] is None:
                raise ValueError('Missing args: ', self.func.__qualname__, x)
        globals().update(result_dict)

Now, the line
if hasattr(func, "__defaults__") and func.__defaults__:
    self.defaults = dict(zip(reversed(self.args), reversed(func.__defaults__)))

raises a mypy error that says func has no __defaults__
Now I understand that the BDFL has said he despises the "hasattr" check so it's probably not gonna be solved inside mypy; then my question is, is there a way to change the __init__ typing signature to get rid of the error?
What have I tried: Callable doesn't work, understandable: not all Callables have __defaults__.
But where is the type "function"? If I type() a function it says "function" but "function" is not in preamble or "typing". I see that some people mention "FunctionType" but it's not in "typing" either.

A: The type of a function is types.FunctionType (in the types module).
If you modify the annotation for func from Callable to types.FunctionType, mypy no longer complains about __defaults__.


text:
Q: Why does eclipse GWT designer for uibinder generate exception because of uifield I'm fairly new to GWT App development, so the learning curve hasn't really straightened out a whole lot yet; however, it seems to me the following shouldn't be causing a problem.
I'm working from example code off the net to learn more. I'm using Eclipse Kepler and GWT designer 3.1.2.
The App works, minus a small error in the styling references in the Login.ui.xml which I had fixed but reversed out trying to find how I broke this.
I'm getting the following error when I use design mode on Login.ui.xml.
Unable to create @UiField(provided=true).
You are attempting to use @UiField(provided=true) for (com.learn.client.LoginResources) res, however GWT Designer was not able to create instance of requested object. This can be caused by one of the following reasons:

Type is interface and you've not provided *.wbp-component.xml description with UiBinder.createInstance script.
GWT Designer attempted to use shortest constructor of type (such as default constructor), but it caused exception.

Show stack trace.
Hide stack trace.

Stack trace:
org.eclipse.wb.internal.core.utils.exception.DesignerException: 4508 (Unable to create @UiField(provided=true).). com.learn.client.LoginResources res
    at com.google.gdt.eclipse.designer.uibinder.parser.UiBinderParser.createProvidedField(UiBinderParser.java:291)
    at com.google.gdt.eclipse.designer.uibinder.parser.UiBinderParser$2.invoke(UiBinderParser.java:182)
    at com.sun.proxy.$Proxy670.provideField(Unknown Source)

My sources are as follows:
Login.ui.xml
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
    xmlns:gwt="urn:import:com.google.gwt.user.client.ui"
    xmlns:res="urn:with:com.learn.client.LoginResources">
    <ui:with field="res" type="com.learn.client.LoginResources" />
   <gwt:HTMLPanel>
      <div align="center">
         <gwt:VerticalPanel res:styleName="style.background">
            <gwt:Label text="Login" res:styleName="style.blackText" />
            <gwt:TextBox ui:field="loginBox" res:styleName="style.box" />
            <gwt:Label text="Password" res:styleName="style.blackText" />
            <gwt:PasswordTextBox ui:field="passwordBox"  res:styleName="style.box" />
            <gwt:HorizontalPanel verticalAlignment="middle">
               <gwt:Button ui:field="buttonSubmit" text="Submit" res:styleName="style.loginButton" />
               <gwt:CheckBox ui:field="myCheckBox" />
               <gwt:Label ui:field="myLabel" text="Remember me" res:styleName="style.blackText" />
            </gwt:HorizontalPanel>
            <gwt:Label ui:field="completionLabel1" res:styleName="style.blackText" />
            <gwt:Label ui:field="completionLabel2" res:styleName="style.blackText" />
         </gwt:VerticalPanel>
      </div>
   </gwt:HTMLPanel>
</ui:UiBinder>

Login.java
public class Login extends Composite {
       private static LoginUiBinder uiBinder = GWT.create(LoginUiBinder.class);
       private Boolean tooShort = false;

       @UiField(provided=true) TextBox loginBox;
       @UiField TextBox passwordBox;
       @UiField Label completionLabel1;
       @UiField Label completionLabel2;
       @UiField(provided=true) final LoginResources res;

       /*
       * @UiTemplate is not mandatory but allows multiple XML templates
       * to be used for the same widget.
       * Default file loaded will be <class-name>.ui.xml
       */
       @UiTemplate("Login.ui.xml")
        interface LoginUiBinder extends UiBinder<Widget, Login> {
       }

       public Login() {
           loginBox = new TextBox();
          this.res = GWT.create(LoginResources.class);
          res.style().ensureInjected();
          initWidget(uiBinder.createAndBindUi(this));
       }
        :
        :
        Handlers
        :
        :
    }

nResources.java
public interface LoginResources extends ClientBundle {
       /**
       * Sample CssResource.
       */
       public interface MyCss extends CssResource {
          String blackText();

          String redText();

          String loginButton();

          String box();

          String background();
       }

       @Source("LoginStyle.css")
       MyCss style();
}

LoginStyle.css
.blackText {
   font-family: Arial, Sans-serif;
   color: #000000;
   font-size: 11px;
   text-align: left;
}

.redText {
   font-family: Arial, Sans-serif;
   color: #ff0000;
   font-size: 11px;
   text-align: left;
}

.loginButton {
   border: 1px solid #3399DD;
   color: #FFFFFF;
   background: #555555;
   font-size: 11px;
   font-weight: bold;
   margin: 0 5px 0 0;
   padding: 4px 10px 5px;
   text-shadow: 0 -1px 0 #3399DD;
}

.box {
   border: 1px solid #AACCEE;
   display: block;
   font-size: 12px;
   margin: 0 0 5px;
   padding: 3px;
   width: 203px;
}

.background {
   background-color: #999999;
   border: 1px none transparent;
   color: #000000;
   font-size: 11px;
   margin-left: -8px;
   margin-top: 5px;
   padding: 6px;
}

A: It seems designer does not support provided fields when they need a generator.
I would include the LoginStyle.css stuff in the Login.ui.xml
Something like this:
<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'
    xmlns:g='urn:import:com.google.gwt.user.client.ui'>
    <ui:style>
          .container {
          }
        </ui:style>
    <g:FlowPanel ui:field="container" addStyleNames="{style.container}">
    </g:FlowPanel>
</ui:UiBinder>


text:
Q: variable checkout design on magento multisite with single checkout I'm running a magento multisite with a single checkout.  The sites are currently set up as stores and they're all using one secure url for checkout.
How do i get the checkout url to vary it's display of the design/format/logo ect, depending on which site the user is coming from?  Right now my checkout url retains only the default theme settings.

A: Magento always executes within a single store context and therefore one theme configuration scope. You will need to adjust the theme calculation in Mage_Core_Model_Design_Package to evaluate the store id in the quote object.
You can likely do this in an observer observing the checkout-related FullActionName controller_action_predispatch_* events in Mage_Core_Controller_Varien_Action->preDispatch() and in your observer method doing something like the following:
Mage::getSingleton('core/design_package')->setTheme('theme');

This is a rough guide. YMMV.


text:
Q: Armazenar valores de um data set em variaveis ASP.NET Estou com problemas para conseguir armazenar o retorno de um select em variaveis , estou usando um data set para criar uma tabela com o resultado do select , esse select ira me devolver alguns registros e da formar que estou fazendo so consigo pegar o primeiro valor , ja pesquisei como fazer lista e percorrer usando for each mais não estou conseguindo oir em pratica aqui vai um pedaço do codigo
DataSet dtteste = conexao.getDataSet("SELECT ID_FUNCIONARIO FROM VW_APONTAMENTO_HORAS WHERE ID_PROJETO="+idProjeto+"GROUP BY ID_FUNCIONARIO");
var count = dtteste.Tables[0].Rows.Count;
foreach(DataRow teste in dtteste.Tables[0].Rows )
{

   var retorno = dtteste.Tables[0].Rows[0].ToString();
   var retorno1 = dtteste.Tables[0].Rows[2].ToString();
   var retorno3 = dtteste.Tables[0].Rows[4].ToString();
}

Desta forma ele n apresenta nada de resultado, acho que preciso converter de SQL pra int ou algo do tipo?

A: Você está percorrendo cada linha do DataTable dentro do foreach, sendo necessário apenas informar a coluna. Você também não pode ter retorno, retorno1 e retorno2 para pegar os resultados. Imagine que você terá 50 linhas, vai declarar 50 variáveis ?
Utilize uma lista para armazenar cada valor que tiver retornado.
A utilização do DataSet / DataTable / DataRow é a seguinte:
DataSet.Tables[t] onde t é o nome ou índice da tabela.
DataSet.Tables[t].Rows[r] onde r é o índice da linha.
DataSet.Tables[t].Rows[r][c] onde c é o nome ou índice da coluna.
DataSet dtteste = conexao.getDataSet("SELECT ID_FUNCIONARIO FROM VW_APONTAMENTO_HORAS WHERE ID_PROJETO="+idProjeto+"GROUP BY ID_FUNCIONARIO");
var count = dtteste.Tables[0].Rows.Count;
List<string> retornos = new List<string>();
foreach(DataRow teste in dtteste.Tables[0].Rows )
{
   retornos.Add(teste[0].ToString());
}

Edit
Entendendo que você primeiro seleciona os funcionários, e depois em algum momento vai selecionar somente os 'apontamento_horas' para aquele funcionário, deveria ser algo desse tipo o seu Select
  SELECT
      ID_APONTAMENTO_HORAS,
      Projeto,
      Ativ,
      Local,
      [Dt Inic],
      [Dt Fim]
  FROM VW_APONTAMENTO_HORAS
  WHERE ID_PROJETO = " + idProjeto +" AND
  ID_FUNCIONARIO= "+ retornos[0] +";";

Voltemos ao seu foreach se você precisa de uma tabela para cada id_funcionário, faça assim:
DataSet dtteste = conexao.getDataSet("SELECT ID_FUNCIONARIO FROM VW_APONTAMENTO_HORAS WHERE ID_PROJETO="+idProjeto+"GROUP BY ID_FUNCIONARIO");
var count = dtteste.Tables[0].Rows.Count;
string SqlApontamentos = "";

foreach(DataRow teste in dtteste.Tables[0].Rows )
{
   SqlApontamentos += @"SELECT
      ID_APONTAMENTO_HORAS,
      Projeto,
      Ativ,
      Local,
      [Dt Inic],
      [Dt Fim]
  FROM VW_APONTAMENTO_HORAS
  WHERE ID_PROJETO = " + idProjeto +" AND
  ID_FUNCIONARIO= "+ teste[0].ToString() +"; ";

}

DataSet dsApontamentos = conexao.getDataSet(SqlApontamentos);

E então no seu DataSet você terá n tabelas onde:
dsApontamentos.Tables[0] é a primeira, dsApontamentos.Tables[1] a segunda... etc


text:
Q: How to perform a join and/or cogroup operation on two maps in scala I am looking to match keys in two maps and produce a Tuple2 of their cogroup.
so:
val m = Map("a" -> "ma", "b" -> "mb")
val n = Map("b" -> "nb", "a" -> "na" )

val join = m.join(n)
{ b -> ['mb', 'nb'], a -> ['ma', 'na']}

Note the ordering of the keys is not important, but it IS expected that the order of the values be retained according to the join order.
It is of course possible to do a 'nested loops' operation- i.e. take every key of m and do lookups against n to create the result.
m.map{ case (k,v) =>
          (k, (v,n(k)))
     }
res4: collection.immutable.Map[String,(String, String)] = Map(a -> (ma,na), b -> (mb,nb))

So we could put this into a function:
  def join[T <: Comparable[T]](a: Map[T,_], b: Map[T,_]) = {
      a.map{ case (k,v) =>
        (k, (v, b(k)))
      }
  }

Try it out:
scala> join(m,n)
res7: scala.collection.immutable.Map[String,(Any, Any)] = Map(a -> (ma,na), b -> (mb,nb))

Just wondering if there were any other approaches to this.
UPDATE  Yes this was a duplicate of "merge map".
In any case the best answer is close to the accepted one below:
 (a.toSeq++b.toSeq).groupBy(_._1).mapValues(_.map(_._2).toList)

A: You can do it like this
(m.toSeq ++ n.toSeq).groupBy(_._1).mapValues(_.map(_._2))

In this case m & n do not have to have same key sets


text:
Q: Invariant linear combination of Wigner matrices under point group My goal is to expand a function of $L^2(SO(3))$ first in terms of Wigner matrices as
$$f(\alpha, \beta, \gamma) = \sum f^l_{mn} D^l_{mn}(\alpha, \beta, \gamma)$$
where $\alpha$, $\beta$ and $\gamma$ are Euler angles.
Then I want to use the fact that $f$ is invariant under rotations that transform the tetrahedron into itself, i.e. the tetrahedral group $T$. That means
$$ f(R) = f(R \cdot t) \quad \forall t \in T$$
One could insert this into the expansion from above, take advantage of the group property of the Wigner matrices and compute all terms. The problem is, that no matter which coordinate system I chose, evaluating $D(t)$ for all elements in $T$ isn't possible in a closed form. Therefor I can't find restrictions wrt to the moments $f^l_{mn}$ that result from the symmetry of $f$ (except for very basic ones).
My question is: Is there is a more systematic approach, maybe using projection operators, to find non-vanishing, linearly independent combinations of $D^l_{mn}$ that result from the imposed 'intrinsic' symmetry group (in this case $T$)?
Is the projection operator as defined by
$$P_{ij}^{l} = \frac{1}{|G|}\sum_{g \in T}D_{ij}^{l}(g)^* \hat{g}$$
applicable here? Naively, I'd think it acts on the space of Wigner matrices, such that $\hat{g}$ would also need to be represented by a corresponding $D^l_{mn}(\Omega)$. Then applying the operator to a basis function $D^j_{mk}$ I'd get a triple product of Wigner matrices.


text:
Q: Difference between Conv and FC layers? What is the difference between conv layers and FC layers?
Why cannot I use conv layers instead of FC layers?

A: A convolutional layer applies the same (usually small) filter repeatedly at different positions in the layer below it. E.g. if the input layer has dimensions 512 x 512, you could have a conv layer that applies the same 8 x 8 filter (specified by 64 filter coefficients), at each point in (e.g.) a 128 x 128 grid overlaid on the input layer. On the other hand, each node in a fully connected layer would learn 512 x 512 weights, one for each of the nodes in the input layer.
Conv layers therefore are well suited to detect local features that may appear anywhere in the input (e.g. edges in a visual image). The idea is that you don't have to train every node separately to detect the same feature, but rather you learn one filter that is shared among all the nodes.
(Note that each conv layer usually learns a set of several filters, each of which gets applied repeatedly across the input. E.g. if the conv layer learns 16 different features, it is said to have a 'depth' of 16.)
FC layers are used to detect specific global configurations of the features detected by the lower layers in the net. They usually sit at the top of the network hierarchy, at a point when the input has been reduced (by the previous, usually convolutional layers) to a compact representation of features. Each node in the FC layer learns its own set of weights on all of the nodes in the layer below it.
So you can (roughly) think of conv layers as breaking the input (e.g. an image) up into common features, and the FC layers as piecing those features together into e.g. objects that you want the network to recognize.

A: You can use conv layers for instead of FC. However, due to the nature of conv layers where weights are shared, there will be much less parameters. It may cause that your network may not be capable enough to learn the stuff. But it all depends on your network.

A: Convolutional and fully connected layers are the building blocks of most neural networks. They are the units (layers) that most NNs are constructed from.
Convolutional and fully connected layers are multiplication parameters that connect one layer of neural network to subsequent layers, thereby making each layer's weights as a linear combination of its previous layer (nonlinear after applying Relu or Tanh). They differ however in the way that they connect two layers of a neural network.
As the name suggests, fully connected layers connect each neuron of the output layer to each and every neuron of the input layer. They can serve in order to express any general pattern in the input layer. This enables fully connected layers best to be capable of recognizing global patterns in a NN layer. Therefore, they are well suited for being applied to wrap up all the patterns recognized with all previous layers (as the final layer of NNs). Also, the size of the layers at the final layers of NN is often relatively small, which means that the high number of parameters within a fully connected layer is less of an issue when it comes to learning. However, the abundance of the number of the weights (that should be learned independently in learning the NN), as well as potential problems such as over-fitting can hinder them from being the ubiquitous solution in NN architectures.
On the other hand, in convolutional connects each neuron of the output layer merely to a handful of the neurons (locally) in the previous layer via a universal "filter" that makes the number of the parameters to be learned really less than a fully-connected layer. Additionally, the uniqueness of the filter applied to the whole neuron layer allows for the convolutional layer to recognize recurrence of the same pattern in different input layers (coincidence of letters in text processing and corners in image recognition). Accordingly, They can more easily be stacked in order to construct deep neural networks with affordable learning processes due to the low number of parameters to learn.


text:
Q: Adding AddToCart link to facebook shopping page I have a Magento v1.9.2.3 webshop and I'm also adding my products to my Facebook shopping page.
I thought I could use the form action url from my webshop as the payment url in FB shopping: my-webshop/checkout/cart/add/uenc/aHR0cHM6Ly93d3cuc2NyYXB3ZWJzaG9wLm5sL3N0ZXJyZW5iZWVsZC1rbmlwdmVsbGVuLmh0bWw_X19fU0lEPVU,/product/5130/form_key/bO1glkQ2GyvpRd7m/
But after reading I (and trying) I understand the form_key is changed after every cache clear/refresh (which we do very regularly).
So I need a more flexible solution.
How can I solve this? I can't imagine I'm the first to try this. Should I create a new php page that will do this or ... ?
Thanks for any advice.
EDIT
I created a new php page in the root of my webshop and added these lines:
 $product = Mage::getModel('catalog/product')->load(5130);
 echo Mage::helper('checkout/cart')->getAddUrl($product, array('qty'=>1, 'form_key'=>Mage::getSingleton('core/session')->getFormKey()));

The resulting url is my-webshop/checkout/cart/add/uenc/aHR0cHM6Ly93d3cuc2NyYXB3ZWJzaG9wLm5sL0FkZFRvQ2FydC5waHA,/product/5130/form_key/lPCvzei32zLtxqxp/qty/1/ but according to the form url it should be my-webshop/checkout/cart/add/uenc/aHR0cHM6Ly93d3cuc2NyYXB3ZWJzaG9wLm5sL3NhbGUvc3RlcnJlbmJlZWxkLWtuaXB2ZWxsZW4uaHRtbD9fX19TSUQ9VQ,,/product/5130/form_key/kqe8DtKacPrJzjgN/
Notice the difference of the form_key ?!?!?
The resulting URL is not working, but the form url is. So this is not a working solution.
Found something else and added these lines of code:
try {
    $cart = Mage::getSingleton('checkout/cart');
    $cart->init();
    $product = Mage::getModel('catalog/product')->load(5130);

    $parameter = array('product' => '5130',
                'qty' => '1',
                'form_key' => Mage::getSingleton('core/session')->getFormKey()
        );

    $request = new Varien_Object();
    $request->setData($parameter);
    $cart->addProduct($product, $request);
    $cart->save();
    Mage::getSingleton('customer/session')->setCartWasUpdated(true);
    echo 'product added<br>';
} catch (Exception $e) {
  print_r($e->getMessage());
}

product added was printed but when I go to my cart it is still empty.
So this is not working either.
I would really much appreciate if someone would help me out.

A: I did see the controller suggestion before, but I find it a bit complicated for my skills ;)
I found this answer: https://stackoverflow.com/questions/47281786/add-product-to-cart-outside-of-magento-external-script
Which I merged with what I already had. And the trick seems to be to call $session = Mage::getSingleton("customer/session"); then you get the correct form-key.
Here's my complete script, which seems to work:
/* Configuration */
define('WEBSTORE_NAME','default');

$productId = !isset($_GET['id']) ? '' : $_GET['id'];
if(empty($productId)) {
    // "no product-id found";
    redirect("my-webshop", 301);
}

// https://stackoverflow.com/questions/47281786/add-product-to-cart-outside-of-magento-external-script
require_once 'app/Mage.php';
umask(0);
Mage::app(WEBSTORE_NAME);
umask(0);
Mage::app()->loadArea('frontend');

Mage::getSingleton("core/session", array("name" => "frontend"));
$session = Mage::getSingleton("customer/session");

$product = Mage::getModel('catalog/product')->load($productId);
$url = Mage::helper('checkout/cart')->getAddUrl($product, array('qty'=>1, 'form_key'=>Mage::getSingleton('core/session')->getFormKey()));

redirect($url);

// https://stackoverflow.com/questions/768431/how-to-make-a-redirect-in-php
function redirect($url, $statusCode = 303)
{
   header('Location: ' . $url, true, $statusCode);
   die();
}

And I call it as this: my-webshop/AddToCart.php?id=5130

A: I know this might be a little late, but you should be able to do this.

yourdomain.com/checkout/cart/add?product=sku&qty=1


text:
Q: How do I fix this strange error when trying to integrate admobs into my app? I am trying to integrate admob into my app but I keep getting this strange error that says

Duplicate class com.google.android.gms.common.api.internal.zza found
  in modules jetified-play-services-base-11.6.2-runtime.jar

(com.google.android"attached is my build.gradle file.
(com.google.android.gms:play-services-base:11.6.2"

A: The error usually appears when one of the modules that you include in your project has inside another library that you are including in your main project as well. My recommendation is to first update the version of the libraries that are highlighted. Then try to remove this and check if everything works:
implementation 'com.google.android.gms:play-services-ads:18.3.0'
Or if you have access to the gradle file of the module remove 'play-services-ads' there


text:
Q: How to use Numbers and whitespace in xmlID xmlIDREF JAXB I have the following classes:
   @XmlRootElement
   @XmlAccessorType(XmlAccessType.FIELD)
   public class Employee {

   @XmlAttribute
   @XmlID
   private String id;

   public String getId() {
      return id;
   }

   public void setId(String id) {
      this.id = id;
   }

   public String getName() {
      return name;
   }

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

   public Employee getManager() {
      return manager;
   }

   public void setManager(Employee manager) {
     this.manager = manager;
   }

   public List<Employee> getReports() {
      return reports;
   }

   public void setReports(List<Employee> reports) {
     this.reports = reports;
   }

  @XmlAttribute
  private String name;

  @XmlIDREF
  private Employee manager;

  @XmlElement(name="report")
  @XmlIDREF
  private List<Employee> reports;

  public Employee() {
      reports = new ArrayList<Employee>();
  }
}

The Company class:
  @XmlRootElement
  @XmlAccessorType(XmlAccessType.FIELD)
  public class Company {

  @XmlElement(name="employee")
  private List<Employee> employees;

  public Company() {
      employees = new ArrayList<Employee>();
  }

  public List<Employee> getEmployees(){
      return employees;
  }
}

My main contains the following:
    Employee employee1 = new Employee();
    employee1.setId("1");
    employee1.setName("Jane Doe");
    company.getEmployees().add(employee1);

    Employee employee2 = new Employee();
    employee2.setId("2");
    employee2.setName("John Smith");
    employee2.setManager(employee1);
    employee1.getReports().add(employee2);
    company.getEmployees().add(employee2);

    Employee employee3 = new Employee();
    employee3.setId("3");
    employee3.setName("Anne Jones");
    employee3.setManager(employee1);
    employee1.getReports().add(employee3);
    company.getEmployees().add(employee3);

If I marshall this it runs fine. But if I create the following schema and then add the schema in the main then I get the following errors:
Schema:
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">

    <xs:element name="company" type="company"/>

    <xs:complexType name="company">
    <xs:sequence>
    <xs:element name="employee" type="employee" minOccurs="0"  maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="employee">
    <xs:sequence>
      <xs:element name="manager" type="xs:IDREF" minOccurs="0"/>
      <xs:element name="report" type="xs:IDREF" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
    <xs:attribute name="id" type="xs:ID"/>
    <xs:attribute name="name" type="xs:string"/>
  </xs:complexType>
</xs:schema>

Error Received:
Exception in thread "main" javax.xml.bind.MarshalException
 - with linked exception:
[org.xml.sax.SAXParseException: cvc-datatype-valid.1.2.1: '1' is not a valid value for 'NCName'.]
I am aware this is because NCName cannot start with a number and have whitespaces. But in my case the id is a number.
I want to know:
1) Why does this only happen when I include the schema?
2) What is the workaround, and is the only way to use moxy

A: 1) Setting an XML Schema using marshaller.setSchema(schema); turns on validation against that XML Schema, and you know that an all-digit ID value is invalid.
2) You can use an Adapter.
Add an annotation in Employee.java:
@XmlAttribute
@XmlID
@XmlJavaTypeAdapter(Adapter.class)
private String id;

And you'll need this simple class:
public class Adapter extends XmlAdapter<String, String> {
  @Override
  public String marshal(String s) throws Exception {
    return "_" + s;
  }
  @Override
  public String unmarshal(String v) throws Exception {
    return v.substring(1);
  }
}

The resulting XML will be correct according to XML Schema:
<company>
  <employee id="_1" name="Jane Doe">
    <report>_2</report>
    <report>_3</report>
  </employee>
  <employee id="_2" name="John Smith">
    <manager>_1</manager>
  </employee>
  <employee id="_3" name="Anne Jones">
    <manager>_1</manager>
  </employee>
</company>


text:
Q: How to copy Stream until you find a certain Element using the streamAPI? i have a list of strings {"a","b","c","d",...}. i want to reduce them up to a certain element. for example this listto elements up to "c". this means that I want to keep all the elements that come before it. is there a way with only using streams to achieve it?
i tried .filter() but that didnt work out

A: You looking for takeWhile() method
String[] chars = {"a","b","c","d","e"};

List<String> justUntilC = Arrays.stream(chars)
        .takeWhile(c -> !c.equals("c"))
        .collect(Collectors.toList());


text:
Q: SelectInput within RenderDataTable Shiny I have created a DataTable in shiny within which the user has the option to select whether an ID should be considered as Dependent, Independent or None. I have attached a reproducible example for convenience. If you run the App, by default, all Id's are classified as Independent. What i am next trying to do next but currently unsuccessful is that the selection corresponding to ID 3 should be by default Dependent. I am using a selectInput for each of the rows in the dataTable. Can someone help me understand how can i make one particular ID as dependent and rest as independent by Default. When the user then runs the App he can changes the selection under ID's according to his need using the selectInputs.
library(shiny)
library(DT)

ui = fluidPage(
  DT::dataTableOutput('x1'),
)

server = function(input, output, session) {

# Helper function for making checkbox
  shinyInput = function(FUN, len, id,...) {
    inputs = character(len)
    for (i in seq_len(len)) {
      inputs[i] = as.character(FUN(paste0(id, i), label = NULL, ...))
    }
    inputs
}

# helper function for reading selections
  shinyValue = function(id, len) {
    unlist(lapply(seq_len(len), function(i) {
      value = input[[paste0(id, i)]]
      if (is.null(value)){
        NA
      } else {
        value
      }
    }))
}

n = 5

df = data.frame(ID = seq_len(n),
      selection = shinyInput(selectInput, n, 'cb_', choices=c("Independent","Dependent","None")),
      month = month.abb[1:n],
      stringsAsFactors = FALSE)

output$x1 = DT::renderDataTable({
      df},
      escape = FALSE, selection = 'none',
      options = list(
        dom = 't', paging = FALSE, ordering = FALSE,
        preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
        drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')
      ),rownames=FALSE)

}

shinyApp(ui = ui,server = server)

A: From ?selectInput

selected   The initially selected value (or multiple values if multiple = TRUE). If not specified then defaults to the first value for single-select lists and no values for multiple select lists.

So by default selectInput will choose the first value as the default value, so we need to change the default value when i=3 i.e ID=3
# Helper function for making checkbox
shinyInput = function(FUN, len, id,...) {
  #browser()
  inputs = character(len)
  for (i in seq_len(len)) {
    if(i!=3){
      inputs[i] = as.character(FUN(paste0(id, i), label = NULL, ...))
    } else {
      inputs[i] = as.character(FUN(paste0(id, i), label = NULL, selected = "Dependent",...))
    }
  }
  inputs
}


text:
Q: Why doesn't mouseenter execute every time? I have a slick slider and on hover of the slider I want it to go to the second slide. I've managed to do this with mouseenter and mouseleave, however if you hover on/off the slider quickly the function doesn't work.
I'm presuming this is because it doesn't have enough time to complete each function but I'm not sure how to get around this. Any advice would be appreciated.
jsFiddle
JS:
$('.slider').on('mouseenter', function (e) {
    $(this).slick('slickGoTo', 1);
});
$('.slider').on('mouseleave', function (e) {
    $(this).slick('slickGoTo', 0);
});

A: In the function that you provided:
$(document).ready(function(){
  $('.slider').slick({
    dots: true,
    speed: 1000,
    infinite: true,
    autoplay: false,
  });
});

I see that you have set the speed very high. If you put speed to 10 etc. than it should work better.


text:
Q: Initialize a class variables address to NULL in C++? Lets assume that i have a class as shown below:
  class CBase
  {
      public:
         CBase(void){};
         ~CBase(void){};
         Sigintgen m_oSignals;// This is another class variable which i have not defined here.
   };

The code begins as shown below:
       main()
       {
           CBasec *ptr = new CBasec();
           I would want the following to happen as shown below:
           &(ptr->m_oSignals) should be equal to NULL. Can anyone please suggest me how to get this?
            &(ptr->m_oSignals) = NULL; //This was tried but compilation errors.
       }

Advanced thanks for the support.

A: You can't. An object always exists once declared.
Instead you could dynamically allocate the Sigintgen when needed, and have CBase store a pointer (which can start as nullptr).
Or use std::optional.


text:
Q: CSS right align centered in
How would I align the 3 input fields so that the right edges are all vertical?
I would still like the text+Input to be in the middle of the column but aligned vertically...
Currently using Bootstrap 3.3.7
HTML:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

            Net. Config

                <form class="form-inline">
                    IP Address:
                    <input type="text" class="form-control txbIPsubmit" id="SYST_IPAD" placeholder="0.0.0.0">
                </form>
                <form class="form-inline">
                    NetMask :
                    <input type="text" class="form-control txbIPsubmit" id="SYST_NETM" placeholder="0.0.0.0">
                </form>
                <form class="form-inline">
                    Gateway :
                    <input type="text" class="form-control txbIPsubmit" id="SYST_GWAD" placeholder="0.0.0.0">
                </form>

                    <input type="checkbox" class="form-check-input" id="SYST_DHCP">
                    DHCP

                <form class="form-inline">
                    <button type="button" class="btn btn-light" id="btnNetConfig">Apply</button>
                </form>

A: There are many things wrong (or at least, out of the standard and good practices) in that code.
First: you don't need to use one form tag for every field but only one wrapping the whole table
Second: it's not recommended to use table for this kind of content. There are many other ways to do this. Such as flexbox (Basic concepts of flexbox)
Tables are only recommended for when the information you have to display is an actual table. (a set of information in rows and columns)
Third: th tags are supposed to be used inside thead tags (h is for header, they are supposed to be the top cell for every column showing the title for the content in that column)
If you still want to use tables for this you should make a td for the label of the field and one for the input in every row, and you can use colspan and rowspan to make cells occupy the space of more than one cell (horizontally or vertically respectively) try this code:

        net. config
        IP Address
        <input type="text" id="SYST_IPAD" placeholder="0.0.0.0">

        Netmask
        <input type="text" id="SYST_NETM" placeholder="0.0.0.0">

        Gateway
        <input type="text" id="SYST_GWAD" placeholder="0.0.0.0">

A: You can solve your problem and improve usability/accessibility in one shot. We can use a flexbox display on the forms to fix your alignment issues. I added s to the text and set them flex-grow: 1. This tells the s to take up maximum horizontal space. Another advantage is that it creates a second child element within each parent flex container to manipulate.

form {
  display: flex;
}

label {
  flex-grow: 1;
  text-align: right;
  padding-right: 10px;
}
<form>
  String<input type="text" id="t1">
</form>

<form>
  Long string<input type="text" id="t2">
</form>

<form>
  The longest string<input type="text" id="t3">
</form>

http://jsfiddle.net/cyhgk9j2/1/

A: As you are using bootstrap you can use col-md-4 and col-md-8 so that elements will be aligned vertically. And for text+Input to be in the middle you can use text-align: center;
I have made an example here. fiddle


text:
Q: How to avoid multiple OR statement bash I have GUI check list for parameters to use grep search. When you check the list - this parameter should show up in grep control option.
For example:
w=TRUE or FALSE
s=TRUE or FALSE
N=TRUE or FALSE
L=TRUE or FALSE

And I would like to use all combination of check list selection something like:
if [ "$w" == TRUE ]; then

grep -w searsch_pattern INFILE

elif [ "$w" == TRUE ] && [ "$s" == TRUE ];then

grep -w -s searsch_pattern INFILE

....

fi

My question is if possible to avoid write all combination elif statement and found some more elegant solution.
PS: I want to use more then four output control parameters in grep search.
Thank you for any help.

A: Generally, no, unless the effects of each flag are independent. You could try building up the arguments to grep in an array. For example:
grep_options=()
if [ $w == TRUE ]; then
    grep_options+=( -w  )
fi

if [[ $s == TRUE ]]; then
    grep_options+=(-s)
fi

# etc.

grep "${grep_options[@]}" search_pattern INFILE

A: For single options as in your example, you can try :
w=TRUE
s=TRUE
N=FALSE
L=TRUE

for opt in w s N L; do
  [[ ${!opt} == "TRUE" ]] && options+=" -${opt}"
done

grep "${options}" searchpattern INFILE


text:
Q: Spring Tool Suite 3.7: Where is the option for Creating a Spring MVC project I am starting to learn Spring. I downloaded STS 3.7 and tried to find out a Spring MVC tutorial on the web. However, most of the tutorials i found are for STS version lower than 3.7 and they all start with Create new project -> Spring Template -> MVC.
However, When i check my New Project options (in my STST 3.7), i only see two Spring options -  "Spring Project" and "Spring Starter Project".
1. Under Spring Project, i can see one of the templates(closest match to a web project) named as: Simple Spring web maven, and i tried creating the project using that template, but it did not create the same folder structure as was shown in tutorials. For instance, it did not create a WEB-INF folder and hence no servlet-context.xml
2. Under Spring Starter Project, i could see a lot of options, one of them was Web and one was WS, but none of them could produce similar folder structure as shown in tutorials like the one here: http://www.codejava.net/frameworks/spring/spring-mvc-beginner-tutorial-with-spring-tool-suite-ide so again no servlet-context.xml
Could someone kindly explain what am i missing here. Should i downgrade to a lower version of STS so it matches tutorials and i can see the same options as shown in tutorial? Please help

A: Try with File>New Project>Spring>Spring Project and then you can select a template from the template´s section.

A: You should create a new Project with Spring Legacy
click next to Choose Spring MVC as the Template
The below resource may be helpful
http://www.journaldev.com/2433/spring-mvc-tutorial


text:
Q: Is there a way to set the parent mbo modified when childMbo was modified in Automation Script (Python)?
Automation Script Object launch point is set to parentMbo. Trigger is upon save, currently happening is when i make changes in childMbo then save() the parentMbo, it will not setValue in 'Description' attribute. I need to change parentMbo first before the changes take effect. Here's my sample code:

triggerInvoke = False

childMbo = mbo.getMboSet("RELATEDTICKET")
if childMbo is not None:
    triggerInvoke = True

if triggerInvoke == True:
    mbo.setValue("DESCRIPTION", "Invoke")

A: I've had similar requirements on the WO/Tasks hierarchy. Here's an example that should work for you:
Suppose you have an object launch point on the child object, on the before save event. This code should flag the owner mbo as modified and its save method should be called.
if mbo.getOwner() is not None and mbo.isModified():
    mbo.getOwner().modify()

You could obtain the same result with an attribute launch point on the child object.
This is useful if you want to trigger a save process on the parent object depending on children data.


text:
Q: Unable to change Identity Specification to Yes in Sql Server table This may be a dumb question, but why can't I change the Identity Specification or (Is Identity) from 'No' to 'Yes'?

A: Remove Default Value or Binding.

A: Check your column data type.
If it is varchar then you can't change identity column.
To change identity column, it should have int data type.

A: You can disable the Option "prevent saving changes that require table re-creation"
but this is strongly unrecommended by msdn.
to do so go to:
Tools -> Options -> Designers
There uncheck: "prevent saving changes that require table re-creation"

A: You cannot change the IDENTITY property of a column on an existing table. What you can do is add a new column with the IDENTITY property, delete the old column, and rename the new column with the old columns name.
Of course, what happens then (for some people) is that they don't like the fact that the new column appears "at the end" of the list of columns (even though you shouldn't care about the positions of columns - you should always be using their names). In that case, you need to do the same trick, but at a higher level - create a new table (with the column definition altered), copy data from the old table to the new, drop the old table, and rename the new one.
I thought SSMS still tried to pretend that it was possible, by doing the second trick behind the scenes.

A: Also check to make sure that there isn't a default value or binding on the column.

A: Following on from Damien_The_Unbeliever's comment above, you can edit the column order in Visual Studio's design interface.
I've managed to do this successfully. To confirm, the steps are:

*

*Add a new column with the IDENTITY property

*delete the old column,

*Rename the new column with the old columns name.

*(Optional) Re-order columns to have the IDENTITY column from Visual Studio.

A: The solution that worked for me was to change the Data Type to int from its default nchar. Additionally, I had to refresh my database server connection to get it working.

A:
As you can see the yes value for the identity specification is disabled so the other answers above is not applicable for me but following Joy's answer, I saw that I really had a Default Value or Binding. I just omitted the default value and everything i neede was enabled.

A: Took me a while to find the solution to this, at first I was trying to find a way to change a value from here (it's yes cause I was able to change it using the next way)

But then by right-clicking -> properties -> Table designer -> Choose Identity column

Doing this made the "Identity Specifiacation" to "Yes"

A: I think Firstly you have to check the (isIdentity) checkbox after that you can able to check the Identity Specification Checkbox