text:
Q: Receive/install application updates from code I would like to control android app updates (app is published on Google Play). In my situation, automatic updates are turned off in Play Store, and user needs to search for updates (and install if available) manually - by click on button, menu item or else. Is there a way to implement this? (e.g. send request to Google Play or something like that)
Thanks in advance.
Michael.

A: I'm not sure Google support this, but since you know the application package, you can use a unoficial library to get information about your application (so the current version on the Play Store)
Here is the link to a library : http://code.google.com/p/android-market-api/
It seems to be a little old and I don't know if it's currently maintenaid
The best way is to implement a little WebService (or a simple page on a server) on your own and check against it
You can check it at the application startup and display a Dialog for instance


text:
Q: Generate a multi-select option on a form using a junction table -> web2py I have two tables with a many-to-many relationship between them. One table holds types of properties, the other holds regions.
For the sake of simplicity let's say it goes something like this:
_property_
id
name
description

_region_
id
name

_property-region_
id
property.id
region.id

I want to build a form to create new properties, and I want this form to contain a multi-select option allowing the user to specify which region/s the property is available in.
I understand that I can create a multi-select form using list:reference without actually creating a junction table, but I would be interested in learning how to do this without de-normalising the database.

A: its not denoramalising?
each region can have many properties and relation is held by region...
on the query level you just ask for regions which hold the id of the property... (either way you have to query db for that even if you have junction/through table)
If you have specific info about relation, you have to process that logic yourself. Aint that hard,
create two forms validate property info and the record will be in database thus you posess the id. Then just add that id as one part of relation and all the selected items as other.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Changing value of a variable according to a condition inside a target in Makefile In a makefile which I have ,I want to assign value to a variable based on a condition.
I have:
CMAKE=cmake ../

I tried doing:
if test condition;
then $(eval CMAKE := $(cmake -DCMAKE_BUILD_TYPE=Release ../));\
fi;

But this does not work.Is there any other way to do this?
P.S The error which is getting reported is :
Syntax error: ";" unexpected

When I removed ";" ,it showed another error :
Syntax error: "fi" unexpected

A: This kind of "back and forth" between the shell and make is not possible.  It's important to understand the relationship between them: make does not implement a shell parser: it just runs the shell for that.  All make gets back from the shell is a single exit code that determines whether the command succeeded or not.
Make runs a recipe by first expanding all the variables and functions in the recipe, then passing the resulting command to the shell to be invoked.
Thus it should be clear why your example doesn't work.
Before we can give you good advice we'd need higher-level information about exactly what you're trying to do and why.  One way to do what you want is to use $(shell ...) to compute the conditional, all outside of any rule:
ifeq ($(shell test condition && echo true),true)
  CMAKE := cmake -DCMAKE_BUILD_TYPE=Release ../
endif

However, this looks pretty strange to me.  If you described what you really want to do we can probably give you better help.
ETA:
Based on your description below, the best option is target-specific variables:
CMAKE_BUILD_FLAG = -DCMAKE_BUILD_TYPE=$(CMAKE_BUILD_TYPE)

debug:   CMAKE_BUILD_TYPE = Debug
release: CMAKE_BUILD_TYPE = Release

setup:   CMAKE_BUILD_FLAG =

debug release setup: all

all:
        cmake $(CMAKE_BUILD_FLAG) ../


text:
Q: Parallel downloading and get individual download progress via AsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) I am working on parallel downloading of files using
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)

I want the individual progress of the every Task I add.
ArrayList<AsyncTask> mListAsync = new ArrayList<>();
final DownloadTask downloadTask = new DownloadTask(mContext, name);
downloadTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,mVideoUrl.trim());
mListAsync.add(downloadTask );

Above is the sample code I use to download file and I do maintain an arraylist to get how many tasks has been added in que.
Is there any way that I can get the individual AsyncTask progress update added in Thread Pool.

A: Assuming your DownloadTask class uses the https://developer.android.com/reference/android/os/AsyncTask.html#publishProgress(Progress...) method, you can get the current progress in a callback from https://developer.android.com/reference/android/os/AsyncTask.html#onProgressUpdate(Progress...)
EDIT:
Some sample code with a callback:
public class SampleTask extends AsyncTask<Void, Integer, String> {

    private final int id;
    private final ProgressCallback callback;

    public SampleTask(int uniqueId, ProgressCallback callback){
        this.id = uniqueId;
        this.callback = callback;
    }

    @Override
    protected String doInBackground(Void... voids) {
        // do work and call publish progress in here
        for(int i = 0; i <= 100; i++) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e){
                e.printStackTrace();
            }
            publishProgress(i);
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        //handle progress updates from in here
        callback.onProgress(id, values[0]);
    }
}

public interface ProgressCallback{
    void onProgress(int uniqueId, int progress);
}


text:
Q: Django request.FILES gets name, filename but not file (blob) I'm trying to send an audiofile via a POST request to the server (aws, ec2) and I'm using Django, but my request.FILES doesn't receive the blob file, but it DOES receive the key and the filename.
Everything worked fine when I ran this on localhost.
How can I get the file?
I'm enabling my website on chrome://flags/#unsafely-treat-insecure-origin-as-secure, so that I can access the microphone.
Using RecorderJs to generate a Blob object containing the recorded audio in WAV format.
Main.js
rec.exportWAV(function(blob){
...
var fd = new FormData();
fd.append('text', speech);
fd.append('audio', blob, 'test.wav');
$.ajax({
 type: 'POST',
 enctype: 'multipart/form-data',
 url: url,
 data: fd,
 processData: false,
 contentType: false,
 success: function(response) {
  console.log(response);
 }
})
...

speech is String,
blob in console is Blob {size: 221228, type: "audio/wav"}, so it does exist.
Views.py:
@csrf_exempt
def get_blob(request):
    thislist = []
    for key in request.POST:
       thislist.append(request.POST.get(key))
    for key in request.FILES:
       thislist.append(request.FILES.get(key).name)

    json_stuff = json.dumps({"check": thislist})
    return HttpResponse(json_stuff, content_type="application/json")

I've tried with and without enctype, doesn't make a difference.
I've tried setting contentType to multipart/form-data, doesn't make a difference.
The formdata seems to be sent correctly, because I can get the speech correctly (request.POST).
And I can get the key from request.FILES ('audio'), and get the filename ('test.wav').
If I try request.FILES['audio'].read(), it says MultiValueDictError.
If I try request.FILES.get('audio').read() it says AttributeError, 'NoneType' object has no attribute 'read'.
When I print request.POST I do get the dictionary with 'text': whatever text I've spoken.
When I print request.FILES I get an empty dictionary even though I can get the key and filename through
for key in request.FILES: and request.FILES['audio'].filename.
Does anyone know what's going on and/or can help me with the problem?

A: You may use read() method for it:
@csrf_exempt ## it doesn't work for post requests in later Django versions, so you need to disable it in another way or add a token to all post requests
 def get_blob(request):
    thislist = []
    for key in request.POST:
       thislist.append(request.POST.get(key))
    for key in request.FILES:
       thislist.append(request.FILES.get(key).name)
    # I am not sure that "name" exists in the request — you may use any filename, although the following works with multipart requests.
    with open(request.FILES["name"],"wb+") as f:
       f.write(request.FILES['file'].read())
    json_stuff = json.dumps({"check": thislist})
    return HttpResponse(json_stuff, content_type="application/json")

By the way,
@csrf_exempt — doesn't work for post requests in later Django versions, as a token is checked before your view is even called. So, you may need to disable CSRF middleware or just add a correct 'X-CSRFToken' token to all requests.


text:
Q: How to create Bridged connection for Qemu/KVM with Wifi? I want to create a bridged connection in qemu/kvm.
What I want to do is connect the wifi to a bridge (as a slave), then use this bridge to provide network access to the VM.
Using nmtui, I deleted my wifi connection, then created a new bridge and added the wifi to it as a slave. Doesn't work. On the other hand, If I add a wired connection as a slave to the bridge, the bridge gets an IPv4 address, and the VM gets an IP in the same network.
I also tried configuring the slave wifi as "access point" (instead of client), which didn't help.
Now I'm pretty sure someone will say that the bridge requires promiscuous mode and you can't connect a wifi to a wired connection, which is what you have on the VM side, and it requires support from the wifi drivers and bla bla bla.
It can work, somehow. I can easily get a bridged network in VirtualBox.


text:
Q: Call Method From Class or Instantiate Class of an Installed Eclipse Plugin Is it possible to call a method from a class or instantiate a class which is inside of an installed Eclipse plugin? For instance, my Eclipse plugin includes a class MyClass. This class should be used by programmers which have installed my Eclipse plugin. They should be able to instantiate this class and call methods on it. Is this somehow possible?
There is an old page which explains it related to another product (Eclipse BIRT), but the code sample from this page does not seem to work for me:
#import org.eclipse.core.runtime.Bundle;
#import org.eclipse.core.runtime.Platform;
#import org.eclipse.myCorp.security.Validate;

Bundle mybundle = Platform.getBundle("org.eclipse.myCorp.security");
java.lang.Class validateClass = mybundle.loadClass("org.eclipse.myCorp.security.Validate");
Validate validateInstance = validateClass.newInstance();
String password = validateInstance.getPass(loginID);

And it is also always a problem to import Eclipse packages like org.eclipse.core.runtime, because they usually have multiple dependencies.
So is there a way to do that somehow or is that impossible?


text:
Q: get all form details in vb.net i want list all forms in current project. example
listbox1.items.add(form1.name & form1.text)
i want  load all form details in current project.
the following code give for only open forms.
  For linti As Integer = Application.OpenForms.Count - 1 To 0 Step -1
      Application.OpenForms.Item(linti).Text
      Application.OpenForms.Item(linti).name
  Next

i want all form and its text. what i do sir please help me

A: Using a bit of Linq you could try
Dim list = AppDomain.CurrentDomain.GetAssemblies().ToList(). _
                    SelectMany(Function(s) s.GetTypes()). _
                    Where(Function(p) (p.BaseType Is [GetType]().BaseType AndAlso _
                                       p.Assembly Is [GetType]().Assembly))
For Each type As Type In list
    Dim typeName As String = type.Name
Next


text:
Q: Error occured The data source does not support server-side data paging wd vb.net ,sqlclient i want to enable paging on grid view but i found error above describe.
listviewaspxvb code is below.
      Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Response.Write("value loop " & gvwExample.PageIndex & "
")

    Dim cmd As SqlCommand = New SqlCommand("SELECT  UserName,pass_word,ApplicantName,FatherName FROM userinfo", New SqlConnection(" Server=vu-it-wqs-pc\sqlexpress;Database=Test;Uid=sa;Pwd=123;"))
    Try
        Dim adp As New SqlDataAdapter(cmd)
        cmd.Connection.Open()
        Dim ds As New DataSet()
        adp.Fill(ds)

        gvwExample.DataSource = cmd.ExecuteReader()

        gvwExample.DataBind()
        adp.Dispose()
        ds.Dispose()

        cmd.Connection.Dispose()

    Catch ex As Exception
        lblStatus.Text = ex.Message

    End Try
End Sub
Protected Sub OnPaging(ByVal sender As Object, ByVal e As GridViewPageEventArgs) Handles gvwExample.PageIndexChanging
    Try
        gvwExample.PageIndex = e.NewPageIndex
        gvwExample.AllowPaging = True

        gvwExample.DataBind()
    Catch ex As Exception
        lblStatus.Text = ex.Message
    End Try
End Sub

listviewaspx code is below
     <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="listview.aspx.vb" Inherits="WebAppFramework20.listview" %>

<!DOCTYPE html>

    <title></title>

    <form id="form1" runat="server">

                    aaaa

                    aaaab

                    aaaac

        <asp:GridView ID="gvwExample" runat="server"   CssClass="basix"
             CellPadding="4" EnableModelValidation="True" ForeColor="Black"
             GridLines="Horizontal" AutoGenerateColumns="False" BackColor="White"
             BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" Width="666px"
             PageSize="5" AllowPaging="True"  OnPageIndexChanging = "OnPaging"
           >

<Columns >

    <asp:BoundField DataField="UserName" HeaderText="First Name" />
    <asp:BoundField DataField="pass_word" HeaderText="Last Name" />
    <asp:BoundField DataField="ApplicantName" HeaderText="Date Hired" />
        <asp:BoundField DataField="FatherName" HeaderText="First Name" />
        <asp:HyperLinkField HeaderText="View Details..." Text="View Details..." DataNavigateUrlFields="UserName"
                DataNavigateUrlFormatString="DBform.aspx?ID={0}" />
         </Columns>

                <FooterStyle BackColor="#CCCC99" ForeColor="Black" />
                <HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
                <PagerSettings FirstPageText="First" LastPageText="Last" Mode="NumericFirstLast" />
                <PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
                <SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />

                </asp:GridView>
                  <asp:Label ID="lblStatus" runat="server" Text="" Width="300px" style="margin-left: 20px"></asp:Label>

        </form>

if i disable paging like allowpaging="false" then only gridview working well
tell me what i am doing wrong

A: Have you tried using the DataSet variable ds as your data source?
 Dim ds As New DataSet()
 adp.Fill(ds)

 gvwExample.DataSource = ds
 gvwExample.DataBind()


text:
Q: Mysql Query to calculate the distinct count of pickup numbers by plant I am trying to get the distinct count of pickup numbers by plant and pickupmonth year
Input
pickdate    picknumber  Plant
1/3/2022    L009803 Seattle
1/3/2022    L009803 Seattle
1/3/2022    L009803 Seattle
1/20/2022   L19033  Irving
1/21/2022   KL89231 Mini chih
1/23/2022   MY12341 kettle
1/23/2022   MY12341 kettle
1/25/2022   FD1211  Seattle
1/26/2022   HJ12W1  Irving
2/11/2022   K231245 Irving
2/11/2022   K231245 Irving
2/15/2022   N12ER1  Mini chih
2/21/2022   JS1234  Irving
2/25/2022   MK12E1  Kettle

I am looking to get to the below table to get the distinct count of pickup numbers by plant and timeperiod
Time period     Seattle Irving  Mini chih   Kettle
Jan-22              2     2        1           1
Feb-22              0     2        1           1

Please find the DDL for the input table..
create table input
(pickdate date,
picknumber varchar(40),
plant varchar(20))

insert into input values
('1/3/2022','L009803','Seattle'),
('1/3/2022','L009803','Seattle'),
('1/3/2022','L009803','Seattle'),
('1/20/2022','L19033','Irving'),
('1/21/2022','KL89231','Mini chih'),
('1/23/2022','MY12341','kettle'),
('1/23/2022','MY12341','kettle'),
('1/25/2022','FD1211','Seattle'),
('1/26/2022','HJ12W1','Irving'),
('2/11/2022','K231245','Irving'),
('2/11/2022','K231245','Irving'),
('2/15/2022','N12ER1','Mini chih'),
('2/21/2022','JS1234','Irving'),
('2/25/2022','MK12E1','Kettle')

A: With conditional aggregation:
SELECT DATE_FORMAT(pickdate, '%b-%y') Time_period,
       COUNT(DISTINCT CASE WHEN plant = 'Seattle' THEN picknumber END) Seattle,
       COUNT(DISTINCT CASE WHEN plant = 'Irving' THEN picknumber END) Irving,
       COUNT(DISTINCT CASE WHEN plant = 'Mini chih' THEN picknumber END) Mini_chih,
       COUNT(DISTINCT CASE WHEN plant = 'kettle' THEN picknumber END) kettle
FROM input
GROUP BY Time_period
ORDER BY STR_TO_DATE(CONCAT('01-', Time_period), '%d-%b-%y');

Or:
SELECT DATE_FORMAT(pickdate, '%Y-%m') Time_period,
       COUNT(DISTINCT CASE WHEN plant = 'Seattle' THEN picknumber END) Seattle,
       COUNT(DISTINCT CASE WHEN plant = 'Irving' THEN picknumber END) Irving,
       COUNT(DISTINCT CASE WHEN plant = 'Mini chih' THEN picknumber END) Mini_chih,
       COUNT(DISTINCT CASE WHEN plant = 'kettle' THEN picknumber END) kettle
FROM input
GROUP BY Time_period
ORDER BY Time_period;

See the demo.


text:
Q: Из XML выбрать нужные данные с приоритетом Есть упрощенный вариант xml:
<items>
    <item>
        <eissn>12-12</eissn>
    </item>
    <item>
        <eissn>11-13</eissn>
        <issn>11-12</issn>
    </item>
    <item>
    </item>
</items>

Мне нужно извлечь все issn и eissn, но если ни того, ни другого нет, этой строки вообще не должно быть. А если есть и issn, и eissn, то в приоритете должен быть issn. Ожидаемый вариант:
#1105: Статья в журнале
#963: 12-12
*****
#1105: Статья в журнале
#963: 11-12
*****
#1105: Статья в журнале
*****

С этой функцией я получаю issn и eissn:
def get_issn_eissn(item) -> str:
    return item.find("issn") or item.find("eissn")

from bs4 import BeautifulSoup
root = BeautifulSoup(text, 'html.parser')
for item in root.select('item'):
     issn_eissn = get_issn_eissn(item)
        issn_eissn = '#963: ' + str(issn_eissn)
        issn_eissn = re.sub(r'\<.*?\>', '', issn_eissn)
        print(issn_eissn)

Подскажите пожалуйста, как можно выставить приоритет и если ничего нет, получить:
#1105: Статья в журнале
*****

Заранее благодарна за ответ

A: Решение "в лоб":
def get_issn(item):
    x = item.find('issn') or item.find('eissn')
    return '#1105: Статья в журнале' + (f'\n#963: {x.text}' if x else '') + '\n*****'

In [17]: for item in root.select('item'):
    ...:     print(get_issn(item))
    ...:
#1105: Статья в журнале
#963: 12-12
*****
#1105: Статья в журнале
#963: 11-12
*****
#1105: Статья в журнале
*****


text:
Q: Why doesn't my C code snippet work? Simplistic version does. Passing args without VA_ARGS for unsigned long long Basically I'm writing a printf function for an dedicated system so I want to pass an optional number of arguments without using VA_ARGS macros. I knocked up a simple example and this block of code works:
#include <stdio.h>

void func(int i, ...);
int main(int argc, char *argv);

int main(int argc, char *argv) {

    unsigned long long f = 6799000015ULL;
    unsigned long long *g;

    //g points to f
    g = &f;

    printf("natural: %llu in hex: %llX address: %x\n", *g, *g, g);

    //put pointer onto stack
    func(6, g, g);

    return 0;
}

void func(int i, ...) {

    unsigned long long *f;

    //pop value off
    f = *(&i + 1);

    printf("address: %x natural: %llu in hex: %llX\n", f, *f, *f);

}

However the larger example I'm trying to transfer this to doesn't work.
(in the main function):
unsigned long long f = 6799000015ULL;
unsigned long long *g;

g = &f;

kprintf("ull test: 1=%U 2=%X 3=%x 4= 5=\n", g, g, g);

(my dodgy printf function that I'm having trouble with. It maybe worth pointing out
this code DOES work with ints, char strings or anyother % flags which are passed by
value and not pointer. The only difference between what did work and the unsigned
long longs is one is bigger, so I pass by value instead to ensure I don't increment
the &format+ args part wrongly. Does that make sense?)
void kprintf(char *format, ...)
{
 char buffer[KPRINTF_BUFFER_SIZE];

 int bpos = 0; /* position to write to in buffer */
 int fpos = 0; /* position of char to print in format string */
 char ch; /* current character being processed*/

 /*
  * We have a variable number of paramters so we
  * have to increment from the position of the format
  * argument.
 */
 int arg_offset = 1;

 /*
  * Think this through Phill. &format = address of format on stack.
  * &(format + 1) = address of argument after format on stack.
  * void *p = &(format + arg_offset);
  * kprintf("xxx %i %s", 32, "hello");
  * memory would look like = [ 3, 32, 5, "xxx", 32, "hello" ]
  * get to 32 via p = &(format + 1); (int)p (because the int is copied, not a pointer)
  * get to hello via p = &(format + 2); (char*)p;
  */

 void *arg;
 unsigned long long *llu;
 arg = (void*) (&format + arg_offset);
 llu = (unsigned long long*) *(&format + arg_offset);

 while (1)
 {
  ch = format[fpos++];

  if (ch == '\0')
   break;

  if (ch != '%')
   buffer[bpos++] = ch;
  else
  {
   ch = format[fpos++];
   if (ch == 's')
    bpos += strcpy(&buffer[bpos], KPRINTF_BUFFER_SIZE - bpos, (char*)arg);
   else if (ch == '%')
    buffer[bpos++] = '%';
   else if (ch == 'i')
    bpos += int_to_str(&buffer[bpos], KPRINTF_BUFFER_SIZE - bpos, *((int*)arg));
   else if (ch == 'x')
    bpos += int_to_hex_str(&buffer[bpos], KPRINTF_BUFFER_SIZE - bpos, *((int*)arg));
   else if (ch == 'o')
    bpos += int_to_oct_str(&buffer[bpos], KPRINTF_BUFFER_SIZE - bpos, *((int*)arg));
   else if (ch == 'X') {
    //arg is expected to be a pointer we need to further dereference.
    bpos += unsigned_long_long_to_hex(&buffer[bpos], KPRINTF_BUFFER_SIZE - bpos, *llu);
   } else if (ch == 'U') {
    bpos += unsigned_long_long_to_str(&buffer[bpos], KPRINTF_BUFFER_SIZE - bpos, *llu);
   } else
   {
    puts("invalid char ");
    putch(ch);
    puts(" passed to kprintf\n");
   }

   arg_offset++;
   arg = (void *)(&format + arg_offset);
   llu = (unsigned long long*) *(&format + arg_offset);
  }
 }

 buffer[bpos] = '\0';
 puts(buffer);
}

(and the unsigned long long functions it goes on to call):
int unsigned_long_long_to_hex(char *buffer, int max_size, unsigned long long number)
{
 return ull_number_to_str(buffer, max_size, number, BASE_HEX);
}

int unsigned_long_long_to_str(char *buffer, int max_size, unsigned long long number) {
 return ull_number_to_str(buffer, max_size, number, BASE_DECIMAL);
}

int ull_number_to_str(char *buffer, int max_size, unsigned long long number, int base) {

 int bufpos = 0;

 unsigned int lo_byte = (unsigned int) number;
 unsigned int hi_byte = (unsigned int) (number >> 32);

 bufpos = number_to_str(buffer, max_size, lo_byte, base);
 bufpos += number_to_str(buffer + bufpos, max_size, hi_byte, base);

 return bufpos;

}

#define NUMERIC_BUFF_SIZE (11 * (ADDRESS_SIZE / 32))

int number_to_str(char *buffer, int max_size, int number, int base)
{
 char *char_map = "0123456789ABCDEF";

 int remain = 0;
 char buff_stack[NUMERIC_BUFF_SIZE];
 int stk_pnt = 0;
 int bpos = 0;

 /* with this method of parsing, the digits come out backwards */
 do
 {
  if (stk_pnt > NUMERIC_BUFF_SIZE)
  {
   puts("Number has too many digits to be printed. Increasse NUMBERIC_BUFF_SIZE\n");
   return 0;
  }

  remain = number % base;
  number = number / base;
  buff_stack[stk_pnt++] = char_map[remain];
 } while (number > 0);

 /* before writing...ensure we have enough room */
 if (stk_pnt > max_size)
 {
  //error. do something?
  puts("number_to_str passed number with too many digits to go into buffer\n");
  //printf("error. stk_pnt > max_size (%d > %d)\n", stk_pnt, max_size);
  return 0;
 }

 /* reorder */
 while (stk_pnt > 0)
  buffer[bpos++] = buff_stack[--stk_pnt];

 return bpos;
}

Sorry guys, I can't see what I've done wrong. I appreciate this is a "wall of code" type scenario but hopefully someone can see what I've done wrong. I appreciate you probably dislike not using VA_ARGS but I don't understand why this technique shouldn't just work? And also, I'm linking with -nostdlib too. If someone can help I'd really appreciate it. Also, this isn't meant to be production quality code so if I lack some C fundamentals feel free to be constructive about it :-)

A: It's a bad idea to code this way.  Use stdarg.h.
On the off chance (I presume this based on the name kprintf) that you're working on a hobby kernel or embedded project and looking to avoid using standard libraries, I recommend at least writing your own (architecture and compiler specific) set of stdarg macros that conform to the well-known interfaces and code against that.  That way your code doesn't look like such a WTF by dereferencing past the address of the last argument.
You can make a va_list type that stores the last-known address, and your va_arg macro could appropriately align the sizeof of the type it's passed and advance the pointer accordingly.  For most conventions I have worked on for x86, every type is promoted to 32 bits...

A: You have to read on the calling conventions for your platform, i.e. how on your target processor/OS function arguments are passed, and how registers are saved. Not all parameters are passed on stack. Depending on number of parameters and their types, many complex situations can arise.

A: I should add: if you want to manipulate the stack by hand as you are doing above, you need to do it in assembler, not in C. The C language follows a defined standard, and what you are doing above it not legal code (i.e., its meaning is not well-defined). As such, the compiler is allowed to do anything it wants with it, such as optimize it in weird ways unsuitable to your needs.


text:
Q: My android studio 4.3 app is crashing right away and I get exception The IDE switches to Debug window and it lists an exception. I cannot figure out how to copy or save the entire window to show you. The final list entry is "stat: 130. forwardingOs (libcore.io)". Is there a way to copy the entire message list so I can present it to you? I am guessing that this exception is related to the new android studio 4.3 I downloaded. I placed a break in onCreate of my class but it never reaches it. My manifest is below and I assume the exception is UI related.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.curco.rsproject"
android:versionCode="1"
android:versionName="1.0" >

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-sdk
    android:minSdkVersion="17"
    android:targetSdkVersion="17" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher" android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <activity
            android:name=".MainActivity" android:label="@string/app_name"
            android:screenOrientation="landscape">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity
            android:name=".MyPrefs"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Holo.Light.Dialog.NoActionBar">
        <intent-filter>
            <action android:name=".MyPrefs" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

</application>

</manifest>


text:
Q: 90s or 80s Sci-Fi movie about a female cyborg / robot Please help identify an old movie I watched as a kid.
Plot (vaguely remembered): a group of people are trying to escape a facility (probably underground) and are pursued by a hard-to-kill / indestructible robot / cyborg. There are two main characters (male and female) who developed a romantic relationship.
They escape the facility in the end and find themselves in a desert. The female is a cyborg and is injured. She dies in the male's arms with a sort of a remote control with a cord out of her body. There is a teary goodbye and he shuts her down.
She might have given a birth or something.
I have recently watched and eliminated: Cyborg, Cyborg 2, Cyborg 3, Cyborg Cop 1, 2 and 3, Lunar Cop (quite close, but not it), Cyber Tracker 1 and 2

A: I think you may be looking for Cyborg 2: Glass Shadow.

In the year 2074 the PinWheel corporation creates an 'almost-human' cyborg Casella Reese, aka Cash, designed specifically to charm/seduce her way into a rival manufacturer's headquarters and then self-detonate. Things go awry, when she starts to have feelings for a human Colton Ricks, aka Colt 45, who works for PinWheel as a martial arts instructor. He falls for Cash as well, and with the help of Mercy, they escape. PinWheel Corp. sends Danny Bench, a 'Cyborg Tracker' after both Colt and Cash. Violence ensues.

It was following by a sequel, Cyborg 3: the Recycler

Prepare yourself for the all too deadly future. Cash, the heroine of Cyborg 2, is living safe in the free zone. But not for long. Biomechanical problems are taking down her systems and a visit to a doctor in Silica confirms her worst fears. She is more then a marvel of cyborg technology. She is the first of her kind to become a creator-she is pregnant.

What does not match, as you might guess from that she shows up in the sequel, is that Cash does not die after exiting the facility, although in Cyborg 3, the scene where Evans shows Cash is pregnant does have him holding what looks like a remote control, plugged into her.

Trailer / "Best Parts"

Found by searching for science fiction film facility escape desert cyborg, which turned up 80's (?) sci-fi movie identification, cyborg, desert, isolation, which has an answer referencing Cyborg 3, which led to me looking up what the prequel was.

A: This sounds like it could be Nemesis
In the movie, the main character Alex Raine is a cyborg former cop, in the first movie, his ex-lover, Jared is an android. With respect to her death, "It turns out that Jared was fatally wounded in her escape from LA, requiring her memory core to be salvaged from her body." I seem to remember lots of industrial settings and desert.

A: This sounds like Cherry 2000 (1987)... I vaguely remember this.

In 2017, a successful businessman travels to the ends of the earth to find that the perfect woman is always under his nose. He hires a sexy renegade tracker to find an exact duplicate of his android wife.

A: It sounds like this is Screamers.

A: American Cyborg: Steel Warrior(1993)

After World War III people are sterile and ruled by the artificial intelligences they created in this violent world. The only woman who was able to give life to a fetus has to take it through the dangerous city of Charleston, South Carolina to the port where a ship is on its way to Europe. She is followed by an android assassin through all the dangers, and only one man tries to help her survive and protect her from the killing machine.


text:
Q: If $f$ is convex in $\mathbb{R}$ and $x_0 \in \mathbb{R}$ prove $f(x)\geq f'(x_0)(x-x_0)+f(x_0) \, \forall x \in \mathbb{R}$. Proof by MVT. $f$ is convex in $\mathbb{R}$ then $f'$ is strictly increasing in $\mathbb{R}$
If $x<x_0$
$f$ continuous in $[x,x_0]$ and differentiable in $(x,x_0)$, from the Mean Value Theorem
\begin{align*}
  \exists &\xi \in (x,x_0):f'(\xi)=\frac{f(x_0)-f(x)}{x_0-x}=\frac{f(x)-f(x_0)}{x-x_0}  \\
 x_0>\xi \Rightarrow   f'(x_0)&>f'(\xi) \\ \Rightarrow  f'(x_0)&>\frac{f(x)-f(x_0)}{x-x_0} \\
  \Rightarrow  f'(x_0)(x-x_0)&<f(x)-f(x_0) \\ \Rightarrow  f(x)&>f'(x_0)(x-x_0)+f(x_0)
\end{align*}
If $x>x_0$
$f$ continuous in  $[x_0,x]$ and differentiable in $(x_0,x)$, from the Mean Value Theorem
\begin{align*}
  \exists & \xi \in (x_0,x):f'(\xi)=\frac{f(x)-f(x_0)}{x-x_0}  \\
 x_0<\xi \Rightarrow   f'(x_0)&<f'(\xi) \\  \Rightarrow f'(x_0)&<\frac{f(x)-f(x_0)}{x-x_0} \\
  \Rightarrow f'(x_0)(x-x_0)&<f(x)-f(x_0) \\ \Rightarrow  f(x)&>f'(x_0)(x-x_0)+f(x_0)
\end{align*}
Edit:
If $x=x_0$ then $f(x_0)\geq f(x_0) $ which holds as an equality.
In the end $f(x)\geq f'(x_0)(x-x_0)+f(x_0) \, \forall x \in \mathbb{R}$


text:
Q: Удаление ячейки из таблицы при нажатие на кнопку UITableView У меня такой вопрос:
Есть ViewController на котором расположена таблица. Она заполняется из CoreData с этим все в порядке. Мне нужно реализовать удаление ячейки при нажатие на кнопку в правом углу ячейки.
Знаю как реализовать удаление при свайпе, но это не то. Нужно именно при нажатие. Искал подобную проблему, но что-то не нашел, извеняюсь если повтор.
Как это можно сделать?

A: func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCell(withIdentifier: "your_cell", for: indexPath) as! YurCell
  cell.delete_button.addTarget(self, action: #selector(delete), for: .touchUpInside)
  return cell
}

@objc func delete(_ sender: UIButton) {
   //ваш код для удаления
}


text:
Q: C Programming - Anomaly behaviour of while loop for float condition I wrote the following code:
#include <stdio.h>

int main ()
{
  float x = 1.1;
  printf("%s\n", "Hello!");
  while (x == 1.1)
  {
    printf("%s\n", "Hey there!");
    printf("%f\n", x);
    x = x - 0.1;
  }
  printf("%s\n", "Bye!");
  return 0;
}

However the output was (which I assume was not expected):
aps120797@XENON-PC:/mnt/d/Codes/LetUsC$ gcc C04Ag.c
aps120797@XENON-PC:/mnt/d/Codes/LetUsC$ ./a.out
Hello!
Bye!

To check if it accepts float condition or not, I wrote this code:
#include <stdio.h>

int main ()
{
  float x = 1.1;
  printf("%s\n", "Hello!");
  while (x >= 1.0)
  {
    printf("%s\n", "Hey there!");
    printf("%f\n", x);
    x = x - 0.1;
  }
  printf("%s\n", "Bye!");
  return 0;
}

And I got the output as I expected.
aps120797@XENON-PC:/mnt/d/Codes/LetUsC$ gcc C04Ag.c
aps120797@XENON-PC:/mnt/d/Codes/LetUsC$ ./a.out
Hello!
Hey there!
1.100000
Hey there!
1.000000
Bye!

So, my question is, what am I doing wrong in the first code?
UPDTATE: Just figured out how to correct this error.
Appended the while condition like this: while (x == 1.1f)

A: 1.1 is not a float value, it's a double value.
When you write float x = 1.1; the compiler inserts an implicit cast: float x = (float)1.1;.
When you write x == 1.1 the compiler inserts another implicit cast: (double)x == 1.1.
So effectively you are testing whether 1.1 is still the same value after casting it to float and back to double - i.e. whether (double)(float)1.1 == 1.1 is true.
(double)(float)1.1 == 1.1 is not true, due to floating-point rounding error. At least on my platform:

*

*1.1 is actually 1.100000000000000088817841970012523233890533447265625

*(double)(float)1.1 is actually 1.10000002384185791015625
and as you can see these two numbers are not the same.


text:
Q: AWS Amplify Auth.sendCustomChallengeAnswer issue I'm using a Custom-Challenge Authentication with AWS Amplify, Cognito, and React Native, implementing a Passwordless authentication process. The App was working ok, but for some reason after added a couple of new libraries just the authentication part stopped to work.
When I try to run this part:
 import {Auth} from 'aws-amplify';
 const user = await Auth.signIn(username); // This part its OK
 const signedUser = await Auth.sendCustomChallengeAnswer(user, confirmationCode); // This one breaks

The message I receive is this:
TypeError: (0, _getRandomBase.default) is not a function
A bit of more information about the project:

*

*"aws-amplify": "3.0.21",

*"aws-amplify-react-native": "4.2.2",

*"amazon-cognito-identity-js": "4.3.3",

*"@react-native-community/netinfo": "5.9.5",

My index.js file:
import Amplify from 'aws-amplify';
Amplify.configure({
  Auth: {...},
  API: {...},
  PushNotification: {...},
})

In Cognito I setup all the necessary Triggers like:

*

*CreateAuthChallenge, => This one is reached

*DefineAuthChallenge, => This one as well

*VerifyAuthChallenge, => This one is never reached!!!

A: In the end, I'm not sure what was the problem here, but after updating AWS Amplify to the latest version together with the rest of the libraries started to work.

A: I had the same error, and resolved it by updating the amazon-cognito-identity-js dependency.


text:
Q: ArgumentError: First argument in form cannot contain nil or be empty. Rails CRUD app, I'm debugging an issue with what should be a fairly simple CRUD application for a course I'm taking. It's turning out to be more difficult than I imagined. I'm attempting to set it in the app so I can go into the question and either choose to edit or delete it. The delete works more or less just fine. But I get the following errors when I click the 'edit' button:
ActiveRecord::RecordNotFound in QuestionsController#edit - Couldn't find Question with 'id'=1 citing the edit method in my Questions controller.
Here's the error:
Extracted source (around line #13):

11

12

13   <%= form_for @question do |f| %>
14

15       <%= f.label :title %>
16       <%= f.text_field :title, class: 'form-control', placeholder:        "Enter question title" %>

My controller:
 class QuestionsController < ApplicationController
  def index
    @questions = Question.all
  end

  def new
    @question = Question.new
  end

  def create
    @question = Question.new(params.require(:question).permit(:title, :body, :resolved))
      if @question.save
        flash[:notice] = "Question was saved."
        redirect_to @question
    else
       flash[:error] = "There was an error in saving your question. Please ask again."
        render :new
     end
  end

  def show
    @question = Question.find(params[:id])
  end

  def new
    @question = Question.new
  end

  def edit
    @question = Question.find(params[:id])
  end

  def update
    @question = Question.find(params[:id])
    if @question.update_attributes(params.require(:post).permit(:title, :body))
      flash[:notice] = "Post was updated."
      redirect_to @question
    else
      flash[:error] = "There was an error saving the post. Please try again."
      render :edit
    end
  end

   def create
    if      @question.update_attributes(params.require(:question).permit(:title, :body, :resolved))
      flash[:notice] = "Question was updated."
      render :edit
      redirect_to @question
    else
      flash[:error] = "There was an error saving your question. Please try again."
      render :new
    end
  end

  def delete
    @question = Question.find(params[:id])
    @question = Question.destroy
    redirect_to @question
  end
end

```
The view it's supposed to affect:

<%= @question.title %>

<%= @question.body %>

<%= link_to "Edit", edit_question_path(@question), class: 'btn btn-success' %>

<%= link_to "Delete", @question.delete, class: 'btn btn-danger' %>

And my routes file:
    Rails.application.routes.draw do
  resources :posts
  resources :advertisements
  resources :questions
  resources :answers

  get 'about' => 'welcome#about'

  root to: 'welcome#index'
end

Any help you could give me would be much appreciated. I'm still kind of learning all of this.
You can view the repository for this project at https://github.com/InsomniaNoir/bloccit

A: You have <%= link_to "Delete", @question.delete, class: 'btn btn-danger' %> on your show view. So every time you get your show view it executes @question.delete and it deletes that @question. If you don't believe me visit a question then refresh the page you will see that your @question has been deleted. Replace that code with <%= link_to "Delete", @question, method: :delete, class: 'btn btn-danger' %>. I saw that in your git repository you commented out the edit action don't forget to uncomment it.


text:
Q: How do I search over multiple models in a CMS using Sphinx? I'm attempting to using Sphinx in my CMS as a sitewide search.  Since each model in the CMS has different fulltext fields, I've created an index per model.  However, according to Sphinx's forum, searching over multiple indexes with different schema is not supported.
How are you CMS guys using Sphinx for your general site search?  Performing a call to Sphinx per model and keeping track of pagination offsets?  Creating one huge index with an index field per model/field?  Is there some other solution I'm not thinking of?

A: You probably solved this long time ago, but well...
You cannot cover multiple indexes with different Schema in one single call to ->Query(), but you can execute multiple queries with AddQuery() and RunQueries()
So, instead of calling
->Query( 'keywords' , ( 'schemaA', 'schemaB', 'schemaC' ) )

You do:
->AddQuery('keywords' , ( 'schemaA') );
->AddQuery('keywords' , ( 'schemaB') );
->AddQuery('keywords' , ( 'schemaC') );
->RunQueries();

You will get an array of results, one for each query. Then in your search results page you could display the results separated by 'type' (or schema) like:
___ RESULTS PAGE _______
Searching for "blue"...
--- we found 23 results in cars ----

*

*car 1

*car 2

*car 3

*..

--- we found 2 results in houses ----

*

*house 1

*house 2

*house 3

*..

_ (end) RESULTS PAGE _____


text:
Q: Best .php CMS for handling ad-hoc product quotes I am developing a new e-commerce enabled site for a company that sells two types of products which I will call: (1) widget items, which are minimally customizable, and (2) cars, which are highly customizable (so complex that CMS's I have reviewed, including Magento, OpenCart, etc. can't handle them with default functionality).  I have already written the scripts to handle type (2) customisations, which I will need to integrate into whichever CMS I choose.
For type (2) products, customers will create their customized product, and then request a quote.  My client will then input a price online, and then the client can add the quote/price combination to his/her cart if s/he chooses.  The quote number plus a small description of the unique product/project would be added to the cart, instead of static product attributes as with type (1).
My question is whether there is a cart (or cart + extensions) out there that can handle both type (1) and type (2) products.  That is, one that can have both static price and quoted price items put in the same cart.  If there is not, which .php CMS would you recommend I develop this functionality in?
I have explored Magento, Drupal + Unbercart, CMS MS w/ its products + modules, OpenCart, and even wordPress.  I'm leaning towards Drupal + Ubercart for its sheer flexibility/extensibility, but have reservations about its reputation for slow performance.  My client doesn't host on a dedicated server, so performance is an issue.

A: I would recommend testing ZOO 2.x for Joomla. It's an extremly flexible CCK which you can use to build customizable items. You will have to get into ZOO, but the apps which are shipping with ZOO are a good start. Only thing is that ZOO is not a eCommerce Extension, so you will have to add a cart feature and payment prozessors if you need them.


text:
Q: gnomes and lights vs. sieve of Eratosthenes I was riddled a riddle the other day - a series of gnomes flips a series of light switches. The first gnome flips every switch, the second gnome flips every second switch, the third gnome flips every third switch, etc.
This is similar to the sieve of Eratosthenes where instead of flipping a switch, the lights are removed .  The first method leaves lights on for the squares, while the second leaves the primes extant (until the nth gnome) - is there thus some connection between squares and primes?

A: There is a simple criterion for prime numbers using perfect squares.
Let $N>2$ be a positive integer and $n$ be the smallest positive integer with $n^2>N$. Then , $N$ is a prime number, if and only if it has no divisor $d$ with $1<d\le n$.


text:
Q: Failed to find the sum of the even elements of the array, and a strange error message Our professor asked us to make 4 functions.
One to print the array, find the max value, min value,
and the sum of the even elements of an array.
My code was working, until I coded the evenSum function.
And this error message appeared:

error: no match for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream'} and 'void')

Here's my code:
#include <iostream>
using namespace std;

//print array
void print(int ar[4])
{
    for(int i=0; i<4; i++)
    cout<<ar[i]<<'\t';
    cout<<endl;
}

// return the max value
int maxValue(int ar[4])
{
    cout<<"Array max value: ";
    int max= ar[0];
    for(int i=1; i<4; i++)
    if(ar[i]>max)
    max= ar[i];
    return max;
}

// return the min value
int minValue(int ar[4])
{
    cout<<endl;
    cout<<"Array min value: ";
    int min= ar[0];
    for(int i=1; i<4; i++)
    if(ar[i]<min)
    min= ar[i];
    return min;
}
// the sum of the even elements
void evenSum(int ar[4])
{
    cout<<endl<<"The sum of even elements: ";
    int sum=0;
    for(int i=0; i<4; i++)
    if(i%2==0)
    sum+= ar[i];
    cout<<sum;
}

int main()
{
    int ar[4]={1,2,3,4};

    print(ar);
    cout<< maxValue(ar);
    cout<< minValue(ar);
    cout<< evenSum(ar);

}

I expected the code to give me the sum of the even elements,
and I don't quite understand the error message or how to fix it.

A: void : is a lonely type, with no associated values to hang with him, except for a few cases, most commonly as a return type
of void function.
you put him with << and ostream,
although he love to stand a lone.


text:
Q: What are multi-level wild cards? Confusion in syntax I am reading multi-level wild cards from AngelikaLangerGenericsFaq. I am pretty confused
about the syntax. The document says

The type Collection<Pair<String,?>> is a concrete instantiation of the
    generic Collection interface.  It is a heterogenous collection of
    pairs of different types.  It can contain elements of type
    Pair<String,Long> , Pair<String,Date> , Pair<String,Object> ,
    Pair<String,String> , and so on and so forth. In other words,
    Collection<Pair<String,?>> contains a mix of pairs of different types
    of the form Pair<String,?> .
The type  Collection<? extends Pair<String,?>> is a wildcard
    parameterized type; it does NOT stand for a concrete parameterized
    type.  It stands for a representative from the family of collections
    that are instantiations of the Collection interface, where the type
    argument is of the form Pair<String,?> .  Compatible instantiations
    are Collection<Pair<String,Long>> , Collection<Pair<String,String>> ,
    Collection<Pair<String,Object>> , or Collection<Pair<String,?>> . In
    other words, we do not know which instantiation of Collection it
    stands for.
As a rule of thumb, you have to read multi-level wildcards top-down.

I am confused about the following points.

*

*Can someone elaborate on these three quotes with example. I am totally lost into the syntax

*Document says, para-1 is the concrete instantiation of a generic type and other is not the concrete instantiation? How is that?

*What does it mean to read the wild-cards top down?

*What is the advantage of multi-level wild cards?

Can someone elaborate these points. Thanks.

A:
Can someone elaborate on these three quotes with example. I am totally lost into the syntax

Well, it wouldn't make sense to write those 3 quotes again here, as I can't give a better explanation than that. Instead, I will try to answer your other questions below, then possibly you will understand the answer to this one too. If not, you can ask your query again and I'll try to elaborate a little further.

Document says, para-1 is the concrete instantiation of a generic type and other is not the concrete instantiation? How is that?

A concrete instantiation is the one in which all the type arguments are concrete types, and are known at compile time. For e.g., List<String> is a concrete instantiation, because String is a concrete type. Its type is known at compile time. Whereas, List<? extends Number> is not a concrete type, because ? extends Number can be any type that extends Number. So, its type is unknown at compile time. Similarly, Map<String, Integer> is a concrete instantiation of generic type Map<K, V>.
In the case of multi-level type parameters, List<List<? extends Number>>, the outer List is a concrete instantiation of List<E>, because the type of elements is known to be a List at compile time, although the inner List is a wildcard instantiation, as the type of elements stored can be Integer, Double, any subclass of Number. But that paragraph is talking about the outer type only. And the outer type can only contain List type.
That's why the first paragraph said, it's a heterogenous collection of Pair, because the actual type parameter of Pair can be anything, but that is certain to be Pair and nothing else.

What does it mean to read the wild-cards top down?

Talking in layman's term, it means from left-to-right. While determining the type of the parameterized type, you first see the outermost type parameter. Then if that type parameter is itself a parameterized type, then you move onto the type parameters of that parameterized type. So, we read the type parameters, from left-to-right.

What is the advantage of multi-level wild cards?

Suppose you want to create a List of List of Fruits. Now your inner List can contain any kind of of fruits. An apple is also a fruit, and a banana is also a fruit. So, you have to make sure that you get all of them. Now, since generic types are invariant, in the sense, List<Apple> is not the same as List<Fruit>, you can't add a List<Apple> if your type of list is List<List<Fruit>>. For that you would need to use wildcards like this - List<List<? extends Fruit>>, which can now take List<Apple>, List<Banana>, list of any fruit.

A: Generic types with wildcards are really "existential" types. If you're familiar at all with logic, you can read G< ? extends T > as ∃S extends T:G< S >.
Angela's explanation about reading types "top down" really means that the imaginary existential quantifier implied by a type that contains a ? in it is always as close as possible to the ?.  For example, you should mentally rewrite G< H< ? extends T > > to G<∃S extends T:H< S > >. Since there's no quantifier on the outside, it's called concrete.


text:
Q: Bind multiple keys to a Table using template I want to bind multiple keys from a JSON to a sap.ui.table.Column.
I am using a JSON-View. This is how it looks like:
{
  "Type": "sap.ui.core.mvc.JSONView",
  "content": [
    {
      "Type": "sap.ui.table.Table",
      "id": "backendConnectorsOverviewTable",
      "columns": [
        {
          "Type": "sap.ui.table.Column",
          "label": "Label",
          "template": {
            "Type": "sap.ui.commons.TextView",
            "text": "{text} {headerText}"
          }
        }
      ]
    }
  ]
}

And this is how my Data-JSON looks like:
{
  forms: [
    {
      text: "First Text"
    },
    {
      text: "Second Text"
    },
    {
      headerText: "Header Text"
    }
  ]
}

The Question is, is it possible to bind the Table-Column to multiple keys, like in my case text and headerText?
I had no success with multiple changes like:
"template": {
    "Type": "sap.ui.commons.TextView",
    "text": "{text} {headerText}"
  }

OR:

"template": {
    "Type": "sap.ui.commons.TextView",
    "text": "{/text} {/headerText}"
  }

A: Yes it is possible. Try this:
"template": {
    "Type": "sap.ui.commons.TextView",
    "text": "{ parts: [ { path: '/text' }, { path: '/headerText' } ] }"
}


text:
Q: How can I remove an element added by jquery? I want list items moved to a div when clicked and vice versa. But it seems, only elements loaded from the source can be moved.
How can I do that?
Thanks.

Item A

    Item 1
    Item 1
    Item 1
    Item 1
    Item 1
    Item 1
    Item 1

http://jsfiddle.net/wGz8s/112/

A: Try to use event delegation here since the elements that you are adding at the runtime would not be available during event binding,
$(document).on("click",".selected-item", function() {
   var text =  "
"+$(this).text()+"
";
   $(".green #selectable").prepend( text );
   $(this).remove();
});

and
$(document).on("click",".content-item", function() {
  var text =  ""+$(this).text()+"";
  $(".red").append( text );
  $(this).remove();
});

And in the place of the document in my code use a static closest dom element of the selector which is being passed inside .on()

A: You should use jQuery's event delegation.
The problem is: your jsFiddle is using jQuery 1.4 (very old version), and it doesn't have the .on event.
I've updated it to the version 1.11, and it works like a charm:
$(".abc").on("click", "span", function(e) {
    var text =  "
"+$(e.target).text()+"
";
    $(".choices #selectable").prepend( text );
    $(e.target).remove();
});

$(".choices").on("click", "li", function(e) {
    var text =  ""+$(e.target).text()+"";
    $(".abc").append( text );
    $(e.target).remove();
});

http://jsfiddle.net/wGz8s/113/


text:
Q: How to transform disjunction of Future to Future of disjunction I have the result of a method:
val res: Future[Int] Xor Future[String] = getResult(x)
and would like to transform it and use it as Future[Int Xor String]
I could not extrapolate my use case from the herding cats blog and am not sure whether a monad transformer would be the right tool here, perhaps rather some form of traverse?
Xor from cats stands in for any disjunction. Scalaz \/ or stdlib Either would be fine as well (though I would prefer a biased disjunction).
Thank you

A: Scalaz has Functor.counzip, but there is no counzip in scalaz.syntax.functor so we need to call it on Functor[Future] directly :
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scalaz.std.scalaFuture._
import scalaz.{\/, Functor}

val disj: Future[Int] \/ Future[String] = \/.right(Future.successful("foo"))
Functor[Future].counzip(disj)
// Future[Int \/ String] : Success(\/-(foo))

Scalaz also has a Cozip type class which gives you the inverse : F[A \/ B] => F[A] \/ F[B].

A: Just as sequence allows you to turn a F[G[A]] into a G[F[A]] when F has a Traverse instance and G is applicative, bisequence lets you turn a F[G[A], G[B]] into a G[F[A, B]] if F has a Bitraverse instance (and G is applicative).
Cats has provided a Bitraverse implementation for at least a couple of versions (I'm using 0.6.0-M2 here), so you can just write this:
import cats.data.Xor, cats.std.future._, cats.syntax.bitraverse._
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

def flip[A, B](x: Xor[Future[A], Future[B]]): Future[Xor[A, B]] = x.bisequence

Bitraverse is a little like Scalaz's Zip or Cozip (mentioned in the other answer), but it's more generic in that instances can be defined for any type constructor with two type arguments (assuming it has the appropriate semantics), not just tuples or disjunction.


text:
Q: Parallel sort two arrays Suppose I have two arrays:
char **words = (char**) malloc(MAX * sizeof(char*));
int *count = malloc(MAX * sizeof(int));

The first one stores the words in a given list:
words[0] = "myword0" / words[1] = "myword1" / words[2] = "myword3" ...

and the second one stores the number of occurences of each word in the list:
count[0] = 4 //means that "myword0" appears 4 times in the list

I want to print the most frequent word and its number of occurrences. If there are words that appear the same number of times, print the first one in alphabetical order.
To do that, I thought about alphabetically sorting words:
int sortWordsAlph(const void* a, const void* b)
{
    char **x = (char**)a;
    char **y = (char**)b;

    return (strcmp(*x,*y));
}

and in int main():
qsort(words, MAX, sizeof(char*), sortWordsAlph);

Now, the problem is with count. It should still point to the occurrences of each word, thus meaning I have to sort it too. How can I do this?
Maybe I should use a swapping algorithm instead of qsort?

A: If you want to use qsort(), you should use an array of structs that contain both the word and the count. You can then pass your array to qsort() with a custom comparison function:
struct wc_s {
  char *word;
  int count;
};

int cmp_words (const void *p1, const void *p2)
{
   const struct wc_s *s1 = p1;
   const struct wc_s *s2 = p2;
   return strcmp (s1->word, s2->word);
}

int cmp_counts (const void *p1, const void *p2)
{
   const struct wc_s *s1 = p1;
   const struct wc_s *s2 = p2;
   return s2->count - s1->count;
}

...
struct wc_s *wc_list = malloc (MAX * sizeof *wc_list);
...
qsort (wc_list, MAX, sizeof *wc_list, cmp_counts);

If qsort() was guaranteed to perform a stable sort (i.e. two elements that compare the same retain their original order), you could solve your problem by first sorting by word, and then sorting by count. Unfortunately, the resulting order of two equal elements is unspecified.
What you could do is sort the array by count, and then go through the array to find sub-arrays with the same counts, and sort those individually:
int start = 0;
int length;
while (start < MAX) {
  for (length = 1; start+length < MAX; length++) {
    if (wc_list[start].count != wc_list[start+length].count)
      break;
  }
  qsort (wc_list+start, length, sizeof *wc_list, cmp_words);
  start += length;
}


text:
Q: Checking item Id with selected Id This is in my Controller and i am trying to populate the dropdown list with items. I am already populating based on active items but i also want to add the item that was previously selected even if it is now inactive. I wanted to check in the Where clause to get active items but i also want to add an 'or' to get the id of the party type that was selected previously to the party type Id in the list.
viewModel.AvailablePartyTypes =
            _partyTypeRepository.FindAll().OrderBy(o => o.Description).Where(a => a.IsActive).ToSelectList(
                "PartyTypeId", "Description", viewModel.PartyTypeId.ToString());

This is what i am trying to get:
Where(a=>a.IsActive || selected.PartyTypeId == PartyTypeId)

A: Maybe I am overlooking something but isn't it as simple as:
Where(a=>a.IsActive || selected.PartyTypeId == a.PartyTypeId)

edit:
If it gets complex refactor it to a method call like:
Where(a=> UseItem(a))

private static bool UseItem(object a)
    {
        bool result = a.IsActive;
        //etc
        return result;
    }

A: not really sure why my answer was deleted. Even though others have helped but the way i got my answer and formed wasn't really generated from the person who helped. I had it already posted in my original post to the question.


text:
Q: forEach iterator tag I have a for each loop that it works fine in the following way:
<c:forEach begin="0" end="10" varStatus="status">'+
      <div id="text<c:out value="${status.index}"/>">

</c:forEach>'+

I have the following code in the Action class. I just want to pass the listSize in the place of end="10" in the above loop.
Vector<String> l1 = new Vector<String>();
Vector<String> v1 = new Vector<String>();
l1.add("listSize");
v1.add(String.valueOf(list.length));
for (int i=0;i<list.length;i++){
    if (notEmpty(list[i].getText())){
    l1.add("text"+i);
    v1.add(list[i].getText());
         }
}response.getWriter().print(JSONUtils.toJSON(new Collection[]{l1}, new Collection[]{v1}));

does any one has idea?

A: use <c:set> to set a variable (from within JSP/JSTL) or add the variable to requestScope first (in Java part of JSP), and then refer to the variable via requestScope.variable.
then use end="${variable}" in the <c:forEach> tag.
Regards.

A: You need to set "listSize" attribute to the request, which will contain a size of the list.
All answers are here: Pass variables from servlet to jsp


text:
Q: .net Runtime - Silverlight Runtime =? I've googled around a bit, and I haven't been able to find a good listing of what classes from the .net CLR are not included in the 'CoreCLR' aka Silverlight.
What is Silverlight missing from the Windows .net Framework?
Also, is there anything that the Silverlight runtime has that the .net Framework doesn't?

A: Silverlight Runtime (Silverlight CLR) is essentially a mini-mini CLR :).
Microsoft did the work of removing many dependencies to .NET Framework assemblies not part of the Silverlight release

Silverlight CLR is a subset of the
  .NET Framework that contains
  components and libraries, including
  data integration, extensible Windows
  controls, networking, base class
  libraries, garbage collection, and the
  common language runtime (CLR).
Some parts of the .NET Framework for
  Silverlight are deployed with your
  application. These "Silverlight
  Libraries" are assemblies not included
  in the Silverlight runtime and are
  instead shipped in the Silverlight
  SDK. When Silverlight Libraries are
  used in your application, they are
  packaged up with your application and
  downloaded to the browser. These
  include new UI controls, XLINQ,
  Syndication (RSS/Atom), XML
  serialization, and the dynamic
  language runtime (DLR).

To read about a detailed comparison, see this link http://codebetter.com/blogs/patricksmacchia/archive/2008/10/01/comparing-silverlight-and-the-net-framework.aspx

A: You can see the online Silverlight 2 Documention which includes API documentation.
Or go to the Silverlight 2 Getting Started Page and either download the addins for Visual Studio 2008 if you have it (it works with the free Visual Web Developer Express if you don't have Visual Studio 2008) or download the Silverlight 2 SDK which is listed lower on the Getting Started page.
Once you have the Silverlight 2 SDK installed, you can launch Start -> All Programs -> Microsoft Silverlight 2 -> Welcome, which has links to the installed documentation as well as other resources.


text:
Q: Golang crypto/hmac global hash object I try to use global hmac hash for generating signature. Code works well, but generated signature doesn't satisfy 3rd party integration checker. If hmac hash will be created for each 'signature generation' process it will works fine.
Works fine - signature is accepted by 3rd party:
func tokenSignatureFunc(key string) tokenSignType {
    signToken := func(token string) []byte {
        h := hmac.New(sha256.New, []byte(key))
        h.Write([]byte(token))
        signature := h.Sum(nil)
        base64Signature := make([]byte, base64.StdEncoding.EncodedLen(len(signature)))
        base64.StdEncoding.Encode(base64Signature, signature)
        return base64Signature
    }
    return signToken
}

Doesn't work - signature is not accepted by 3rd party:
func tokenSignatureFunc(key string) tokenSignType {
    h := hmac.New(sha256.New, []byte(key))
    signToken := func(token string) []byte {
        h.Write([]byte(token))
        signature := h.Sum(nil)
        base64Signature := make([]byte, base64.StdEncoding.EncodedLen(len(signature)))
        base64.StdEncoding.Encode(base64Signature, signature)
        return base64Signature
    }
    return signToken
}

A: Try this, it may be failing due to base64 padding. Use RawStdEncoding instead
func HMAC256(payload string, secret string) string {
   sig := hmac.New(sha256.New,[]byte(secret))
   sig.Write([]byte(payload))
   return b64Encode(string(sig.Sum(nil)[:]))
}

func b64Encode(text string) string {
   return base64.RawStdEncoding.EncodeToString([]byte(text))
 }


text:
Q: How to get data stored in ListArray I want to store my API result in a Array List, need to store, ID and ImageURL.
I am able to store the data using my class ImgModel. But I can't figureout how to access it later on.
public class ImgModel{

private String url, id;

    public ImgModel(String id, String url) {
        this.id = id;
        this.url = url;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getId() {
        return id;
    }

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

}

in MainActivity I call the API
public class MainActivity ....{
...
List<ImgModel> photosList = new ArrayList<ImgModel>();
....

//>>in the result API... after parse the json

String id   = imgOgj.getString("id");
String url  = imgOgj.getString("url");

ImgModelp p = new ImgModel(id, url);
photosList.add(p); //THIS WORKS

}

This Part I don't know how to implement - pls help
Now in the ImagePreview Activity I want to access these images and Id to display in Image view.
    public class ImagePreviewActivity ....{

    //List<ImgModel> mProcessedImg= new ArrayList<ImgModel>(); //If I do this, that means I am creating a new list, and not accessing the store data right ?
    ProcessedImg mProcessedImg;
    ImageView mImageView;

onCreate{

    ....
    mProcessedImg.size(); //Get the size .i.e how make images url

    mImageView.setImage(mProcessedImg.getUrl(0);//sample how can I get the url of position 0 ?

    }

    }

A: The photosList variable that you have declared in MainActivity is a local variable, which means that its scope is limited to only the code block in which it has been declared. This is the reason that you cannot access the data you have stored in that variable elsewhere in your code.
In order to use and access that same variable again outside of the code block in which it was declared you could instead use an instance variable of the MainActivity class, by amending your class declaration as follows:
public class MainActivity extends Activity {
   List<ImgModel> mPhotosList;
   ...
   // Override the OnCreate method of Activity
   @Override
   public void onCreate(Bundle savedInstanceState) {
       // Create the mPhotosList instance variable
       mPhotosList = new ArrayList<ImgModel>;
       ...
   }

   // other methods where you call the API and store the data in mPhotosList
   ...

}

These pages may help to explain the differences between the types of variables that you can use in Java:
what is the difference between local and instance variables in Java
http://www.cs.umd.edu/~clin/MoreJava/Objects/local.html
In terms of the next part of your problem, to access the mPhotosList member variable from another Activity, the following post may help:
Passing a Bundle on startActivity()?

A: If you neeed to share a list between lots of activities,putting it into MyApp's instance maybe a solution.

A: Create constructor inside ImagePreviewActivity.class which allows one List parameter.
    public class ImagePreviewActivity ....{

    List<ImgModel> imgList;

    ImageView mImageView;

    public ImagePreviewActivity(List<ImgModel> imageList){
     this.imgList = imageList;
    }

onCreate{

    mImageView.setImage(imageList.get(0).getUrl();

    }

    }

Creating a object of ImagePreviewActivity.class
public class MainActivity ....{
...
List<ImgModel> photosList = new ArrayList<ImgModel>();
....

String id   = imgOgj.getString("id");
String url  = imgOgj.getString("url");

ImgModelp p = new ImgModel(id, url);
photosList.add(p);
//Craeate Object of ImagePreviewActivity
ImagePreviewActivity ipa = new ImagePreviewActivity(photosList);

}


text:
Q: how to send the location information collected to server using http request/response in windows phone 7 or 8 Application which we are currently developing collects location information using Geolocator. I want to send this collected info to the server. Could anyone plz suggest some APIs or methods to do the same.
Thanks in advance

A: You could write a web service to do it, or use Azure mobile services to write to an Azure database, or even use background file transfer to transfer the location in a file to your server


text:
Q: an array of people using structs in c? I need to create an array of persons whilst using a struct something like this :-
typedef struct Person

{
     int age;      //needs to be randomly generated
     int height;   //needs to be randomly generated
     int weight;   //needs to be randomly generated
} Person;

but im not sure how to do this with an array like :-
Person[0]
Person[1]
Person[2]
Any tips will be great!!

A: typedef struct Person
{
     int age;      //needs to be randomly generated
     int height;   //needs to be randomly generated
     int weight;   //needs to be randomly generated
} Person;

// Create an array of 5 Persons
Person persons[5];

// Set the data of the first person.
person[0].age = 25;
person[0].height = 175; // in cm
person[0].weight = 68; // in kg


text:
Q: Adding description from another table I am using EF Code First (but all the tables already exist, we're using Reverse POCO Generator). I have 3 related tables - Sales Channels (SChannels), ScsgLink and SpGroup table (that has GroupNo and Descrip columns). I have the following code right now to get the Sales Channel by Id
public override SChannels GetById(object id)
{
   var sChannel = _siriusContext.SChannels.Include("ScsgLink")
                                .Where(x => x.ChannelId == (Int32)id)
                                .First();
   return sChannel;
}

I've added GroupDescription property to the ScsgLink class, e.g.
public partial class ScsgLink
{
    [NotMapped]
    public String GroupDescription { get; set; }
}

The rest of the code for that class is auto-generated by Reverse POCO generator.
So, my problem right now is to somehow adding the description from the SpGroup table when I retrieve the Sales Channel by Id in the code I shown.
Just to clarify, this is the SChannels class:

 // Reverse navigation
        public virtual ICollection<Max4Sale> Max4Sale { get; set; } // max4sale.FK_Max4Sale_SChannels_ChannelID
        public virtual ICollection<ScsgLink> ScsgLink { get; set; } // SCSGLink.FK_SCSGLink_SChannels

And this is what I have in the link table class:

 // Foreign keys
        public virtual SChannels SChannels { get; set; } // FK_SCSGLink_SChannels
        public virtual SpGroup SpGroup { get; set; } // FK_SCSGLink_sp_group

So, I need to bring descrip column from the SpGroup when I retrieve SChannels row by Id with the related rows from the Link table. And here I'm not sure of the syntax.


text:
Q: Meteor, Mongo DB data insert error I learning meteor 1.4 with this TUTORIAL
trying to insert data through CMD with this command
db.tasks.insert({ itemOne: { text:'hello', value:0}}, itemTwo: {text:'hi', value:0}});

but get this error:
E QUERY    [thread1] SyntaxError: missing ) after argument list @(shell):1:61

A: db.tasks.insert({ itemOne: { text:'hello', value:0}, itemTwo: { text:'hi', value:0}});

Now it should work, this inser a record like this:
{
  itemOne: { text:'hello', value:0},
  itemTwo: { text:'hi', value:0}
}


text:
Q: What does "InitGoogleLogging" do? I've been modifying an example C++ program from the Caffe deep learning library and I noticed this code on line 234 that doesn't appear to be referenced again.
::google::InitGoogleLogging(argv[0]);

The argument provided is a prototxt file which defines the parameters of the deep learning model I'm calling. The thing that is confusing me is where the results from this line go? I know they end up being used in the program because if I make a mistake in the prototxt file then the program will crash. However I'm struggling to see how the data is passed to the class performing the classification tasks.

A: First of all, argv[0] is not the first argument you pass to your executable, but rather the executable name. So you are passing to ::google::InitGoogleLogging the executable name and not the prototxt file.
'glog' module (google logging) is using this name to decorate the log entries it outputs.
Second, caffe is using google logging (aka 'glog') as its logging module, and hence this module must be initialized once when running caffe. This is why you have this
::google::InitGoogleLogging(argv[0]);

in your code.


text:
Q: PostgreSQL - pgAdmin - path to database I am new to PostgreSQL and I can not found info about this. I am using pgAdmin III and my databse files are kept in instalation directory of PostgreSQL. So far so good. But now, I need to create huge DB, that is out of my HDD capacity. So I create RAID and want to move this single DB to this location. How can I specify path for single database to be somewhere else?
I dont want other on the same disk, since I have them on fast SSDs. The big one will be only for some data mining and I will remove it afterwards.

A: Have a look a tablespaces. You can keep the main and small parts of the database in the SSD drives and migrate the bigger tables to the tablespaces in your other drive.
http://www.postgresql.org/docs/9.4/static/manage-ag-tablespaces.html
In alternative the whole database can be put into the tablespace by setting the default tablespace parameter.


text:
Q: Client side templating with unknown variables Our company has an intranet consisting of several e-mail templates filled with variables (like [[NAME]], [[PROJECT]] and so on). I was thinking of implementing some sort of client side templating to make it easier to replace these variables with actual values.
The problem is that among all the client side template solutions I've located so far, all of them seem to assume that the JS code knows all the template variables that exist in the markup, and none of them seem to be able to fetch a list of variables defined in the markup.
Does anyone know of any solutions/plugin which makes this possible?
Thanks in advance!

A: Can't you just use some simple regex?
 var variables = mycontent.match(/\[\[(.*?)\]\]/g);

I set up a demo here, so you can see it in action.

A: If set of templates are already cached on client and available to customer on demand and each template will have it own set of information to be replaced in (either hardcoded or define on runtime). Then we can go for some generic solution
Pseudo code
- Decide which Template now need to render
- Send a Ajax command of array of variables in to be replace in the template
  [{var_name:"%project_name%",var_value:"Project" },{var_name:"%superviser%",var_value:"Its me :)" }]

- Write a generic code that loop through json array and replace the var_name with the template source
  Check this - http://api.prototypejs.org/language/template/


text:
Q: List is working but post is not working in nested serializer in Django Rest Framework This is my code:
Models.py
class Kitchen(models.Model):
kitchen_name = models.CharField(max_length = 100)
state = models.CharField(max_length = 40, )
city = models.CharField(max_length = 40)

def __str__(self):
    return self.kitchen_name

class AssignAudit(models.Model):
kitchen = models.ForeignKey(Kitchen, on_delete = models.SET_NULL, null = True)
assigned_date = models.DateTimeField(default = timezone.now)
assigned_by = models.ForeignKey(User, on_delete = models.SET_NULL, null =  True, related_name = 'assigned_audits')

class KitchenAudit(models.Model):
assign_audit = models.ForeignKey(AssignAudit, on_delete = models.SET_NULL, null = True)
question = models.ForeignKey(Question, on_delete = models.SET_NULL, null = True)
total_images = models.IntegerField(null = True, blank = True)
marks_scored = models.IntegerField(null=True,blank=True)
comment = models.CharField(max_length = 300, null = True, blank = True)

Serializers.py
class KitchenSerializer(serializers.ModelSerializer):
class Meta:
    model = Kitchen
    fields = '__all__'

class AssignAuditSerializer(serializers.ModelSerializer):
kitchen = KitchenSerializer()
class Meta:
    model = AssignAudit
    fields = '__all__'

def create(self, validated_data):
    assign_audit = AssignAudit.objects.create(**validated_data)
    questions = Question.objects.all()
    for question in questions:
        kitchen_audit = KitchenAudit.objects.create(question=question,assign_audit=assign_audit)
        for images in range(question.no_of_images):
            KitchenAuditImage.objects.create(kitchen_audit=kitchen_audit)
    return assign_audit

Views.py
class AssignAuditSerializerListCreate(ListCreateAPIView):
serializer_class = AssignAuditSerializer
queryset = AssignAudit.objects.all()

    def list(self, request, *args, **kwargs):
    queryset = self.filter_queryset(self.get_queryset())
    page = self.paginate_queryset(queryset)
    if page is not None:
        serializer = self.get_serializer(page, many=True)
        return self.get_paginated_response(serializer.data)
    serializer = self.get_serializer(queryset, many=True)
    return Response({'audit_assign':serializer.data})

I want to combine both of my table above to display it in one API using django-rest-framework. GET method is working fine but when i am doing POST method, it's saying i have to provide kitchen value.
{
    "kitchen": [
        "This field is required."
    ]
}

A: One of the possible solution is to make kitchen as read-only.
kitchen = KitchenSerializer(read_only=True)

A: You have set read_only = True that's why it is ignoring kitchen while posting, put or patch. It is clearly read_only so you cannot post to it.
As an alternative, you can override get_serializer_class() function in view to make this happen.


text:
Q: Does the naive definition of "commutative category" have any interesting consequences? By a commutative monoid, let us mean a monoid $A$ in which $a,b \in A$ implies $ab=ba$. Its not at all obvious how to generalize this to the case of an arbitrary category; we cannot just assume that all morphisms $f$ and $g$ satisfy $fg=gf$, since the domain/codomain conditions won't be met. We can however assume that for all objects $X$ and all endomorphisms $f,g \in \mathrm{End}(X),$ $fg=gf.$ Lets call this the naive definition of "commutative category."
Does it have any interesting consequences?

A: I don't think that this is a useful definition. You don't consider the morphisms which are no endomorphisms.
Commutative monoids are precisely the monoid objects in the category of monoids (Eckmann-Hilton argument). If $M$ is a commutative monoid, the multiplication map is a homomorphism $M \times M \to M$.
Since categories are many-objects-monoids, we could expect that (small) "commutative categories" are the monoid objects in the category of (small) categories, i.e. the strict monoidal categories. This has the correct decategorification: A monoidal category with one object (even not assumed to be symmetric) is the same as a commutative monoid.
I have to admit that this isn't a satisfactory answer, because we would rather expect that "commutative" is a property, not an extra structure.
Edit: There is a good reason why there is no natural definition of a commutative category: If $O$ is a set, the category of $O$-graphs has as objects pairs $(M,M \rightrightarrows O)$, consisting of a set $M$ and a pair of parallel morphisms $s,t : M \to O$. This category is monoidal with unit $(O,O = O)$ and tensor product $(M,s,t) \otimes (M',s',t') = (M \times_{t,s'} M', s \circ \mathrm{pr}_1,t \circ \mathrm{pr}_2)$. Then a category with object set $U$ is the same as a monoid object in this monoidal category (this is easy to see, for a reference see II.7 in Mac Lane's CWM). In order to define commutative monoids, we need a symmetric monoidal category. However, the category of $O$-graphs is not symmetric monoidal. Only the full subcategory consisting of those $O$-graphs with $s=t$ is symmetric monoidal. The commutative monoid objects therein correspond to those categories which are disjoint unions of commutative monoids.

A: I have arrived here from Google in the search of a reference on such categories, so would be very happy if someone turns up some "interesting consequences".
The property that such a "commutative category" might have that I want to take advantage of is that you can actually compute them from a finite presentation.  In fact I require a slightly stronger condition, that the endomorphism monoids are abelian groups.  When I say 'presentation' I have in mind a simplicial set, and I am interested in the fundamental category.  Now categories are too hard to work with for the application I have in mind and I don't want to invert any more edges than I have to.  Imposing the commutativity and invertibility relations on endomorphisms gives a category which is much richer than the first homology, but still possible to actually work with.
I agree with the other contributors here that the condition may be a little artificial from a category theory perspective, but it still may have some practical use.
EDIT:  I have since found a little on this topic under the subject of graph congruences.  A graph congruence is essentially an equivalence relation on the set of paths in a directed graph, which respects endpoints and composition of paths.  i.e. the set of equivalence classes of paths forms a category.
I'm not really familiar enough with the terms used in the papers I've found (languages, varieties etc.) to say anything about them, but see:
Arkadev Chattopadhyay and Denis Therien
Locally Commutative Categories
and its references.


text:
Q: When should I implement Spring Security ACL in my application? Spring Security ACL looks very powerful, and easy to implement when you can stick to their database implementation. However it appears to become much more complicated when you have to implement your own Acl and AclService (see for example this (old) very basic tutorial of only ~26 pages) and it seems difficult to find references and examples for it (that tutorial was from 2008).
In our application for example, users have roles and belong to departments. Most of the time, they are allowed to perform some operations on objects that belong to their department based on their roles. In all cases, department + role is sufficient to decide whether a user should be granted a specific operation on a specific object.
Users, roles and departments are managed by an external application from which we retrieve them when the user connects (we are using REST services but it could as well be an LDAP server).
We would like to rely on @PreAuthorize('hasPermission(…)') for implementing domain object security. 2 solutions are thus in sight:

*

*Implement a custom PermissionEvaluator that does the whole checks; or

*Implement ACL with a custom AclService that builds the object structure necessary for ACL's to work properly.

It seems that implementing the whole AclService would be more difficult and more complex than implementing a PermissionEvaluator, but ACL's seem to be more standard.
Based on which criteria should you implement one or the other?

A: The PermissionEvaluator is responsible for expression evaluation to determine whether a user has a permission for a given domain object. On the other hand the AclService provides an interface for retrieval of Acl instances. In the spirit of Separation of concerns each component addresses a separate concern.
If any PermissionEvaluator implementation needs to perform evaluation based on Acl instances, it should delegate to AclService to retrieve them. Actually AclPermissionEvaluator does exactly that.
I would suggest you to go this way. Separate evaluation from ACL retrieval. If the concept of Spring AclService and Acl is too complicated or complex for your use case, you can introduce your own service to retrieve custom ACL. Then implement PermissionEvaluator that will delegate to your ACL service.
Actually, I had to do something similar because I needed to store ACLs in NoSQL database and what Spring provides did not work for me.
I would say that it is all about the effort needed to adjust Spring ACL to meet your requirements and the effort to implement a custom solution. If your requirements can be satisfied with the default Spring ACL implementation, go for it. It will definitely save you time to implement your custom solution. However, if it is not possible to adapt Spring ACL to your requirements or it would be too difficult, then it can be easier to implement your custom solution.


text:
Q: Clarification on Github Merged pull requests I've just merged a PR from within github. The total number of commits in the branch is 1339. We have a hook into slack and the message we received says that only 1000 commits were merged.
Is this a rounding issue? or is this an actual issue and 300+ commits weren't merged. I cant see how there would be an upper limit on commits when merging.
Can someone shed some light please?


text:
Q: Use the quantifiers to give the logical form of the following statement. Also negate it and prove it True or False. For almost all great enough natural numbers $n$ we have:
$$\frac{n-2}{n^2-4n+2}<0.07$$
I am not sure the "for almost all" here. Does it mean there exists great enough n for which the statement is not satisfied:
$$\exists N\in \mathbb{N}: \exists n≥N:\frac{n-2}{n^2-4n+2}≥0.07$$
Or just simply there exists some great enough n for which the statement is satisfied:
$$\exists N\in \mathbb{N}: \exists n≥N:\frac{n-2}{n^2-4n+2}<0.07$$
Or something else?

A: What's meant is
$$\exists N\in \mathbb{N}: \forall n\ge N:\frac{n-2}{n^2-4n+2}<0.07$$
so that the statement holds for all $n$, except at most finitely many (the ones that are $<N$ for which we have no info)
The negation is
$$\forall N\in \mathbb{N}: \exists n\ge N:\frac{n-2}{n^2-4n+2}\ge 0.07$$
which implies there are infinitely many $n$ for which the inequality would fail.
But the first one is true of course and follows from the well-known fact that $$\lim_{n \to \infty} \frac{n-2}{n^2 + 4n +2} = \lim_{n \to \infty}\frac{\frac{1}{n} - \frac{2}{n^2}}{1 + \frac4n + \frac{2}{n^2}} = \frac{0+0}{1+0+0} = 0$$ using that $\frac1n \to 0$ and continuity of arithmetic operations.


text:
Q: what is the scope of $_ in a foreach-object loop in Powershell Here's a simplified version of the script I'm trying to write:
$i = 0
Get-ChildItem -Filter *.bat|
ForEach-Object {
    Write-Host $_.Name
    switch ($i) {
        0 { Write-Host $_.Name}
        1 { Write-Host $_.Name }
        2 { Write-Host $_.Name }
        Default {Write-Host "nothing here"}
    }
}

So the first Write-Host command works as expected, but once I get inside the switch statement Write-Host prints out nothing, which is mystifying to me. I assume the problem has something to do with the scope of $_ but I don't know. I'm a total Powershell amateur. Isn't the switch statement inside the foreach loop so the scope shouldn't be an issue?
If I do this then everything works like I expected, the filenames get printed from inside and outside the switch statement:
$i = 0
Get-ChildItem -Filter *.bat |
ForEach-Object {
    Write-Host $_.Name
    $temp = $_.Name
    switch ($i) {
        0 { Write-Host $temp }
        1 { Write-Host $temp }
        2 { Write-Host $temp }
        Default {Write-Host "nothing here"}
    }
}

Can someone explain what is going on here?

A: As written here:
about_Switch
The thing is that The $_ automatic variable contains the value of the expression passed to the switch statement.
That means that it does not contain the same value as it had before you entered into the switch statement.
Move over, if you would like to read more about $_ you can also refer to this article:
What Does $_ Mean in PowerShell
Good luck :)

A: $_ is getting a different value inside your switch statement - it's actually getting the value of $i and it therefore is an Int32 and doesn't have a Name property. When you assign to $temp and use that inside the switch it works because you assign the (string) value you want to a new variable.
If you were to use $_ again after the switch you would be able to access all the properties as before.
By using the code below, you're able to see what type $_ is taking as it is used in the different scopes/pipelines
Get-ChildItem -Filter *.bat |
ForEach-Object {
    Write-Host $_.gettype()
    switch ($i) {
        Default {
          Write-Host $_.gettype()
        }
    }
}


text:
Q: Windows phone handle screen manipulation Im using the toolkit GestureService.GestureListener, the implementation is going very well.
The main page contains a LongListSelector, and on the top (not visible to the user) I have my sliding menu that I slide using the GestureService.
when I try to scroll in the LongListSelector the menu on the top comes down, which is not good.
if im scrolling on the list don't slide the menu, other than that, slide the menu !
how to handle such an event.
thanks
Edit
 <Grid x:Name="LayoutRoot">
    <toolkit:GestureService.GestureListener>
        <toolkit:GestureListener DragDelta="GestureListener_DragDelta"
                                 DragCompleted="GestureListener_DragCompleted" />
    </toolkit:GestureService.GestureListener>

    <phone:Panorama Foreground="Black">

        <phone:PanoramaItem>
                <Phone:LongListSelector x:Name="MyList"
                            ItemTemplate="{StaticResource MyListTemplate}"/>
        </phone:PanoramaItem>

        <phone:PanoramaItem>

        </phone:PanoramaItem>
   </phone:Panorama >
 </Grid>

And this is my C# Code
    private void CloseSettings()
    {
        var trans = _feContainer.GetVerticalOffset().Transform;
        trans.Animate(trans.Y, 0, TranslateTransform.YProperty, 500, 0, new CubicEase //trans.Y, 0, TranslateTransform.YProperty, 120, 0, new CubicEase
        {
            EasingMode = EasingMode.EaseOut
        });

        _isSettingsOpen = false;
    }

    private void OpenSettings()
    {
        var trans = _feContainer.GetVerticalOffset().Transform;
        trans.Animate(trans.Y, 400, TranslateTransform.YProperty, 200, 0, new CubicEase
        {
            EasingMode = EasingMode.EaseInOut
        });

        _isSettingsOpen = true;
    }

    private void ResetLayoutRoot()
    {
        if (!_isSettingsOpen)
            _feContainer.SetVerticalOffset(0.0);
        else
            _feContainer.SetVerticalOffset(120.0);
    }

    private void GestureListener_DragDelta(object sender, DragDeltaGestureEventArgs e)
    {
        if (e.Direction == System.Windows.Controls.Orientation.Vertical && e.VerticalChange > 0 && !_isSettingsOpen)
        {
            double offset = _feContainer.GetVerticalOffset().Value + e.VerticalChange;
            if (offset > _dragDistanceToOpen)
                this.OpenSettings();
            else
                _feContainer.SetVerticalOffset(offset);
        }

        if (e.Direction == System.Windows.Controls.Orientation.Vertical && e.VerticalChange < 0 && _isSettingsOpen)
        {
            double offsetContainer = _feContainer.GetVerticalOffset().Value + e.VerticalChange;
            if (offsetContainer < _dragDistanceToClose)
                this.CloseSettings();
            else
                _feContainer.SetVerticalOffset(offsetContainer);
        }
    }
    private void GestureListener_DragCompleted(object sender, DragCompletedGestureEventArgs e)
    {
        if (e.Direction == System.Windows.Controls.Orientation.Vertical && e.VerticalChange > 0 && !_isSettingsOpen)
        {
            if (e.VerticalChange < _dragDistanceToOpen)
                this.ResetLayoutRoot();
            else
                this.OpenSettings();
        }

        if (e.Direction == System.Windows.Controls.Orientation.Vertical && e.HorizontalChange < 0               && _isSettingsOpen)
        {
            if (e.VerticalChange > _dragDistanceNegative)
                this.ResetLayoutRoot();
            else
                this.CloseSettings();
        }
    }

Variables declared in the class, its working really good, but as i said before, when I scroll in my longListSelector, the menu slides down, i dont want that !

A: This only happens when the parent is not receiving the invokation call . What I suggest you to do is to add IsHitTestVisible =False to your Menu and see whether it works or not


text:
Q: Вывести количество курсов на экран Angular Js Делаю небольшое англуляр прилождение ,которое отображает количество курсов в таблице, по чекбоксу пользователь выбирает прошел ли он тот или иной курс. Я хочу вывести статистику по количество пройденных курсов, но не могу сообразить как.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <title>Document</title>

                    Планировщик курсов.

Пользователь: {{data.user}}. Количество курсов - {{data.courses.length}}

Пройдено {{}}

                <input class="form-control" ng-model="courseName" />

                    <button class="btn btn-default" ng-click="addNewCourse()">Добавить</button>

                        Курс

                        Пройден

                        {{course.name}}
                        <input type="checkbox" ng-model="course.passed"/>

                                {{showText(course.passed)}}

Хочу вывести все вот сюда
Пройдено {{}}
 Спасибо!

A: Например, используя фильтр так:

Пройдено {{(data.courses | filter: {passed: true}).length}}

Также Вам стоит изучить встроенные возможности шаблонизатора Ангуляр, поскольку логика отображения данных должна быть в шаблоне, а не в контроллере.
Например это:

заменить на:
 убрав функцию из контроллера.
Или {{showText(course.passed)}}
 заменив на {{course.passed ? "Да": "Нет"}}


text:
Q: drag and drop animate shadow back to original position if not dropped to target I have made the functionality of drag and drop using ondraglistener. Its working fine But my problem is the shadow which is made does not go back to original image if the view is not dropped at the target. how to animate going of shadow from the position to original position.any help

A: We have to write our own logic to move it to back, this is what we do.
Add a OnDragListener  to your root view,
in onDrag(View view, DragEvent event) of the dragged View wait for ACTION_DRAG_ENDED.
create a image copy of your shadow.
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
shadowBuilder.onDrawShadow(canvas);

Create as ImageView with this bitmap and add to the root view of your view hierarchy.
Then you create Animator to move this back to the original position and remove the ImageView.
ObjectAnimator defaultChangeIn = ObjectAnimator.ofPropertyValuesHolder((Object)mImageView,
                pvhLeft, pvhTop, pvhRight, pvhBottom);