text:
Q: Free unmanaged memory allocation from managed code A .NET application calls C dll. The C code allocates memory for a char array and returns this array as result. The .NET applications gets this result as a string.
The C code:
extern "C" __declspec(dllexport) char* __cdecl Run()
{
    char* result = (char*)malloc(100 * sizeof(char));
    // fill the array with data
    return result;
}

The C# code:
[DllImport("Unmanaged.dll")]
private static extern string Run();

...
string result = Run();
// do something useful with the result and than leave it out of scope

Some tests of it show that the garbage collector does not free the memory allocated by the C code.
Any help will be appreciated. :)

A: Managed string is not the same as char*. What happens undercover is that the marshaling code in the interop layer makes a copy of the unmanaged string in order to convert it to a managed string, but it can't free that memory as it does not know how it was allocated.
However, you could try allocating and returning a BSTR instead of a char*. The interop layer deals way better with automation datatypes than classic unmanaged data types.
The reason why that matters is the way char* and BSTRs are allocated in the memory.
The char* buffers are allocated on the heap of the C++ runtime using private allocation/deallocation routines that the CLR knows nothing about, so there's no way it can delete that memory. And to make things even worse, the buffer that char* points can be allocated by an internal heap implementation of the dll code, or it might even point to a member variable in a private class.
The BSTRs on the other hand are allocated using the WIndows API SysAllocString and are freed by SyFreeStirng and since the CLR interop layer knows about these Windows APIs, it knows how to free a BSTR it got from unmanaged code.

A: The P/Invoke marshaller will assume that memory for the return type was allocated with CoTaskMemAlloc() and will call CoTaskMemFree() to release it.  If this was not done, the program will fail with an exception on Vista and Win7 but silently leak memory on XP.  Using SysAllocString() can be made to work but you have to annotate the return type in the [DllImport] attribute.  Not doing so will still cause a leak, without a diagnostic on Win7.  A BSTR is not a pointer to a memory block allocated by CoTaskMemAlloc, there are 4 bytes in front of the pointed-to address that store the string size.
Either of the following combinations will work properly:
extern "C" __declspec(dllexport)
BSTR __stdcall ReturnsAString() {
  return SysAllocString(L"Hello world");
}

[DllImport(@"c:\projects\cpptemp1\debug\cpptemp1.dll")]
[return: MarshalAs(UnmanagedType.BStr)]   // NOTE: required!
private static extern string ReturnsAString();

Or:
extern "C" __declspec(dllexport)
const wchar_t* __stdcall ReturnsAString() {
  const wchar_t* str = L"Hello world";
  wchar_t* retval = (wchar_t*)CoTaskMemAlloc((wcslen(str)+1) * sizeof(wchar_t));
  wcscpy(retval, str);
  return retval;
}

[DllImport(@"c:\projects\cpptemp1\debug\cpptemp1.dll", CharSet=CharSet.Auto)]
private static extern string ReturnsAString();

You should consider allowing the client code to pass a buffer so there are no memory management issues.  That ought to look similar to this:
extern "C" __declspec(dllexport)
void __stdcall ReturnsAString(wchar_t* buffer, size_t buflen) {
  wcscpy_s(buffer, buflen, L"Hello world");
}

[DllImport(@"c:\projects\cpptemp1\debug\cpptemp1.dll", CharSet=CharSet.Auto)]
private static extern void ReturnsAString(StringBuilder buffer, int buflen);
...
    StringBuilder sb = new StringBuilder(256);
    ReturnsAString(sb, sb.Capacity);
    string s = sb.ToString();

A: You cannot free unmanaged memory from managed code. You need to write a routine in C that calls free on the pointer returned by the Run function and P/Invoke it from .NET.
Another option is to allocate unmanaged memory in .NET, pass the pointer to the C function which will fill it with data and finally free this pointer:
IntPtr ptr = Marshal.AllocHGlobal(100 * sizeof(char));
SomeUnmanagedFunc(ptr);
Marshal.FreeHGlobal(ptr);

A: Another way to do it would be to pass a managed string (a StringBuilder instance) through P/Invoke (as a parameter to your Run function).
That way no allocations are made on the unmanaged side.
In other words, you would have something like:
extern "C" __declspec(dllexport) void __cdecl Run(char* data)
{
    // fill the array with data
    // no return value (void)
}

and call it like this:
[DllImport("Unmanaged.dll", CharSet = CharSet.Ansi)]
static extern void Run(StringBuilder result);

StringBuilder result = new StringBuilder(100);
Run(result);

A: I was reading some questions about PInvoke and i stoped here. I don't know if the problem is still relevant to you but i decided to post my answer to future readers.
It's about your last comment to Darin Dimitrov's answer. When the size of allocated memory is not known, the tipical solution is to call the unmanaged function with a null pointer and receive the size in an out parameter. Then, we alloc the needed space and call again the unmanaged function.
Exemple below:
//MANAGED SIDE
IntPtr ptr = IntPtr.Zero;
int size = 0;
myFunc(ptr, out size);
ptr = Marshal.AllocHGlobal(size);
myFunc(ptr, out size);
//Do your work..
Marshal.FreeHGlobal(ptr);

//UNMANEGED SIDE
int myFunc(void* dest, size_t& size){
   if(dest==NULL)
       //calculate de size..
       size = 'resul'
       return 0;
    }
    // create the array and copy all elements
    memcopy(dest, ... , size);
    //free all allocated space in unmanaged and return success
    return 0;
}

A: public class Memory
{
    [DllImport("kernel32.dll")]
    private static extern bool SetProcessWorkingSetSize(IntPtr proc, int min, int max);

    //[DllImport("kernel64.dll")]
    //private static extern bool SetProcessWorkingSetSize(IntPtr proc, int min, int max);

    public String Errores = "";
    public void Limpiar()
    {
        try
        {
            Process Mem;
            Mem = Process.GetCurrentProcess();
            SetProcessWorkingSetSize(Mem.Handle, -1, -1);
            Mem = null;
        }
        catch (Exception ex)
        {
            Errores = ex.ToString() + " " + ex.StackTrace.ToString();
        }

    }
}
public class LimpiadodeMemoria
{

    private Boolean Monitorear;
    private Boolean Salida;
    private String ElMensajeBitacoras;
    private String Error;

    public delegate void Errores(string Elerror);
    public event Errores OnErrores;

    public delegate void Bitacora(string LaBitacora);
    public event Bitacora OnBitacora;

    public void Iniciar()
    {
        Monitorear = true;
        Salida = false;
        ElMensajeBitacoras = "LimpiadodeMemoria - " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + " Iniciada";
        OnBitacora(ElMensajeBitacoras);
        while (Monitorear == true)
        {
            Salida = false;
            Memory _Memori = new Memory();
            _Memori.Limpiar();
            Error = _Memori.Errores;
            _Memori = null;
            if (Error != "")
            {
                OnErrores(Error);
            }
            Salida = true;
            System.Threading.Thread.Sleep(1000);
        }
    }

    public void Detener()
    {
        Monitorear = false;
        while (Salida == false)
        {
            System.Threading.Thread.Sleep(100);
        }
        ElMensajeBitacoras = "LimpiadodeMemoria - " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + " Detenida";
        OnBitacora(ElMensajeBitacoras);
    }

}

A: .NET memory MUST be allocated within the CLR to be cleared by the GC. You need to add a function to free the block within the C DLL.
Remember to free the memory within the same instance of the C DLL which created the memory. You cant mix and match.


text:
Q: Equality between two different forms of the zeta function of a variety over a finite field Let $X$ be a smooth projective variety over a finite field $k$. We can define the zeta function by $$Z_X(T)=\exp\left(\sum N_m \frac{T^m}{m} \right) $$ where $N_m$ is the number of $K$-points, where $K$ is the unique extension of $k$ of degree $m$.
With some work, you can show the equality of formal power series:
$$Z_X(T)=\prod_{x \text{ closed point of }X}\frac{1}{1-T^{\deg(x)}}$$
From this, you can show that $$Z_X(T)=\sum_{\text{effective divisors } D}T^{\deg(x)} $$which seems to me to be a simple argument invovling writing out $$\prod_{x \text{ closed point of }X}\frac{1}{1-T^{\deg(x)}} = \prod_{x \text{ closed point of }X}(1+T^{\deg(x)}+T^{2\deg(x)}+\cdots) $$
and doing some combinatorics.
However, this is where I became confused. It occurred to me that I don't know how to make sense of an infinite product of formal power series because there is no topological structure. (We can induce one, but would it be helpful?) Certainly, we can choose to only look at products where finitely factors many are not 1, but I would consider this some kind of restricted product, as opposed to a full product. If $X$ has only finitely many closed points then there is no problem here, but of course even something as simple as $\text{Spec}k[x]$ has infinitely many closed points.
Is there a way to make sense of an infinite product of formal power series?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to emit an event from Vue.js Functional component? As the title of the question, this context is not available in the functional component. So if I have to emit an event, how can I do that?
For example in below code snippet:
<template functional>

        <some-child @change="$emit('change')"></some-child>

</template>

My functional component doesn't have this context and hence $emit is not available. How can I bubble-up this event?

A: Child Component
<template functional>
  <button @click="listeners['custom-event']('message from child')">
    Button from child
  </button>
</template>

Parent Component
<template>

    <child-component @custom-event="call_a_method" />

</template>

See it in action on codesandbox

Do you want to emit the event from the vue instance?

export default {
  functional: true,
  render(createElement, { listeners }) {
    return createElement(
      "button",
      {
        on: {
          click: event => {
            const emit_event = listeners.event_from_child;
            emit_event("Hello World!Is this the message we excpected? :/");
          }
        }
      },
      "Pass event to parent"
    );
  }
};

See it also a sandbox example here

A: If you want to pass event listener conditionally you can do it inside functional component template like this:

v-on="listeners.change ? { change: listeners.change } : null"

The issue of conditionally attaching listeners is discussed here

A: This is explained in the docs Passing Attributes and Events to Child Elements/Components:

If you are using template-based functional components, you will also have to manually add attributes and listeners. Since we have access to the individual context contents, we can use data.attrs to pass along any HTML attributes and listeners (the alias for data.on) to pass along any event listeners.

At the most basic level, you can delegate all listeners like this:
<some-child v-on="listeners"></some-child>

If you only want to bind the change listener, you can do:
<some-child @change="listeners.change"></some-child>

but this will fail if listeners.change is undefined/null (not provided to the functional component).
If you need to handle the situation where there is no change listener, then you can do this:
<some-child @change="listeners.change && listeners.change($event)"></some-child>

otherwise you would have to settle by writing the render function by hand, since I don't think it is possible to conditionally assign the change listener to <some-child> in the template of a functional component. (Or maybe you can? I'm not sure.)

A: a component with jsx:
export default {
  name: "MyText",
  functional: true,// functional component
  props: {
    value: {
      type: [String, Number],
      default: ""
    }
  },
  render(h, context) {
    const { props } = context;

    // with jsx

    // return (
    //   <button
    //     onClick={() => {
    //       console.log(context.listeners);
    //       context.listeners.input(Math.random().toString(36));
    //       context.listeners["my-change"](Math.random().toString(36));
    //       context.data.on.change(Math.random().toString(36));
    //     }}
    //   >
    //     {props.value}
    //   </button>
    // );

    // or use h function
    return h(
      "h1",
      {
        on: {
         // emit some event when click h1
          click: () => {
            // has value prop has has input event auto
            // event name come  what event u listen in parent component
            console.log(context.listeners);
            context.listeners.input(Math.random().toString(36));
            context.listeners["my-change"](Math.random().toString(36));
            context.data.on.change(Math.random().toString(36));
          }
        }
      },
      props.value
    );
  }
};

conext.listeners is just an alias for context.data.on.
in parent componet, you should listen my-change and change, or has error.

event name inside component comes what event u listen in parent component

<MyText
  v-model="value"
  @change="change"
  @my-change="myChange"
  @u-change="uChange"
/>

vue 2.6.11 works well.
see the codesandbox online

A: Parent:
<Child @onFunction="handleFunction">

and this is the child component:
Child
<template functional>

        <some-child @change="execute"></some-child>

</template>

methods:
  execute(){
   @emit("onFunction")
  }


text:
Q: Can anyone mimic, spoof or fake Internet Explorer for this website?
Possible Duplicate:
website just allow Internet Explorer

Sorry guys, I don't want to ask a question twice(website-just-allow-internet-explorer), but I did my best without any success;
The problem as I mentioned on the other post is that my university website just allow access through Internet Explorer; which means that nobody with any other browser(like: chrome, firefox, ...) can access it;(by access I mean inserting the right credentials and entering the system)
So as one of the guys answered, I used User Agent Switcher extension for Google chrome; 3 of them; but none of them worked;(for popular sites like yahoo or facebook yes but my university website sill can recognize the real browser and denies access)
So how can I access it through Google Chrome?

guys this is not a joke or a game, I really need to know how I can do this; tnx in advance;

This the website of my university: Educational Management System

for testing:
1.don't change the value of the first combobox;
2.enter random numbers for next two text fields;
3.correct captcha for the third text field;
if the website still detects Google Chrome it will show this message:

if you became successful (of course your credentials are still wrong but you passed the recognition) you will see something like this:

A: Have you tried an IE Tab for Chrome?
https://chrome.google.com/webstore/detail/ie-tab/hehijbfgiekmjfkfjpbkbammjbdenadd


text:
Q: o2 mobile broadband won't connect with a Huawei E173 It's connected and configured via the wizard but Enable Mobile Broadband is unchecked by default and nothing happens when I click it.
When I click on the o2 mobile broadband connection itself it briefly (around half a second) connects (the icon changes) then disconnects and I get the notification disconnected from network.  The usb modem is HUAWEI E173.
I understand there have been some issues in this regard with 11.10 and just wondered if anyone else had gotten one working?

A: You need to change some settings in network manager (edit connections):

*

*APN: m-bb.o2.co.uk

*phone number: *99#

*username: o2bb

*password:password

Once you've connected, go to mobilebroadbandaccess.o2.co.uk to register. I found I was disconnected fairly soon after my initial connection, but after reconnecting (either reboot or remove and reinsert the mobile broadband dongle) it seems to work fine.


text:
Q: TableView column that is not bound to a certain bean property TableView<A>

I use a custom CellValueFactory and CellFactory to fill a TableView's cell with another mini table, that displays different properties of A.
Therefore I came up with the following solution:
TableColumn<A, A> c1;

c1.setCellValueFactory(c -> new ReadOnlyObjectWrapper<>(c.getValue()));

CellFactory implements Callback<TableColumn<A, A>, TableCell<A, A>> {
@Override
    public TableCell<A, A> call(final TableColumn<A, A> param) {
    return new TableCell<A, A>() {

        @Override
        protected void updateItem(final A item, final boolean empty) {

        super.updateItem(item, empty);
        if (empty || this.getTableRow() == null) {
            setText(null);
            setStyle("");
            setGraphic(null);
        } else {
            TableView nestedTable = buildTable();
            setGraphic(nestedTable);
        }
        }
    };
    }
}

This solution is not optimal, as it will not update cells when items are refreshed.
How else would I implement a column, that is not bound to a single bean property? Should I introduce another property that does already contain the nested table? I think rather not, since rendering the table content is task for the mentioned factory classes.

A: I solved this by introducing an intermediate bean, that holds all the properties that are needed to build the cell content.
TableColumn<A, CellBean> c1;

c1.setCellValueFactory(c -> c.cellBeanProperty()));

CellFactory implements Callback<TableColumn<A, CellBean>, TableCell<A, CellBean>> {
@Override
    public TableCell<A, CellBean> call(final TableColumn<A, CellBean> param) {
    return new TableCell<A, CellBean>() {

        @Override
        protected void updateItem(final CellBean item, final boolean empty) {

        super.updateItem(item, empty);
        if (empty || this.getTableRow() == null) {
            setText(null);
            setStyle("");
            setGraphic(null);
        } else {
            TableView nestedTable = buildTable(item);
            setGraphic(nestedTable);
        }
        }
    };
    }
}


text:
Q: Fastest way to find files modified in last 'x' minutes I have a requirement to find files modified in last 10 minutes in a directory. The directory keeps getting updated and it will have around 50k-60k files every time. I'm using the below code to get the files:
import java.io.File
import java.time.Instant

val dir = new File("/path/to/dir")
val files = dir.listFiles.toList.filter(f => f.getName.matches("some filter"))
files.filter(f => f.isFile && f.exists &&
    Instant.ofEpochMilli(f.lastModified).plus(10, MINUTES).isAfter(Instant.now))
    .toList.sortBy(_.lastModified)

This takes around 20-30 minutes to run. But I want to get the results in less than 10 minutes.
I even tried running this in our hadoop cluster using spark. This is the spark code:
val sparkConfig = new SparkConf()
    .setAppName("findRecentFiles")
    .set("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
    .set("spark.shuffle.compress", "true")
    .set("spark.rdd.compress", "true")
val sc = new SparkContext(sparkConfig)
val rdd = sc.parallelize(files)
rdd.filter(f => f.isFile && f.exists &&
    Instant.ofEpochMilli(f.lastModified).plus(10, MINUTES).isAfter(Instant.now))
    .collect.toList.sortBy(_.lastModified)

Still it takes the same time. And one thing I noticed is that filtering based on the file name is fast. But adding the lastModified filter makes it slow. Is there any better way so that I can get the results faster?
UPDATE
I updated the spark configs and now I'm able to get the results in less than 10 minutes. Earlier, I was running the jar like this:
spark-submit myJar.jar

I changed it to this:
spark-submit --deploy-mode client --queue SomeNonDefaultQueue --executor-memory 16g --num-executors 10 --executor-cores 1 --master yarn myJar.jar

Also removed set("spark.rdd.compress", "true") from code as it increases the CPU time, as explained here - https://spark.apache.org/docs/2.3.0/configuration.html#compression-and-serialization

A: The problem is the stat() check to get last modified comes after a linear search through the directory to look-up the name.  If you can change the directory format, add subdirectories (calculated by file name) and try to group the number of entries in each subdirectory to ~1000.
Otherwise, create a map of name:lastModified and use the WatchService to update the map whenever an event is fired.


text:
Q: Java. How to use "while" that program at the end asked : Do you want to search again? I want to ask you how to make It when proccess and do this again. I mean when program did his work It must to ask: Do you want search for other word, Yes or No? If Yes program will start again, if no exit.
I think about:
 int searchAgain = 0;
            System.out.println("Do you want search for other word?");
            System.out.println("1=Yes 2=No");
            searchAgain = input.nextInt();}
        else {
            System.out.println("Error...");
            }
                if (searchAgain == 1) {
                    System.out.println("Write your word: ");
                    .....//I dont know what here

                }
                    else{
                        System.out.println("Program closed.");
                    }

This is my current code:
    package lt.kvk.i3_2.kalasnikovas_stanislovas;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class Miestai {

        public static void main(String args[]) throws Exception {
            String kitasStilius = "";
            while (!"Ne".equalsIgnoreCase(kitasStilius )) {
            Scanner input = new Scanner(System.in);
            System.out.println("Pasirinkite muzikos stiliu is saraso:");
            System.out.println();

            try {

                FileReader fr = new FileReader("src/lt/kvk/i3_2/kalasnikovas_stanislovas/Stiliai.txt");
                BufferedReader br = new BufferedReader(fr);
                String stiliuSarasas;
                while((stiliuSarasas = br.readLine()) != null) {
                    System.out.println(stiliuSarasas);
                }
                fr.close();
                String stilius = input.nextLine();
                BufferedReader bf = new BufferedReader(new FileReader("src/lt/kvk/i3_2/kalasnikovas_stanislovas/Miestai.txt"));
                int counter = 0;
                String line;

                System.out.println("Ieskoma informacija apie " + stilius);
                ArrayList<String> miestuSarasas = new ArrayList<String>();
                String miestas = null;

                while (( line = bf.readLine()) != null){
                    if (line.trim().length() == 0) miestas = null;
                       else if (miestas == null) miestas = line;
                       int indexfound = line.indexOf(stilius);
                       if (indexfound > -1) {
                       counter++;
                       miestuSarasas.add(miestas);
                       }
                }
                if (counter > 0) {
                    System.out.println(stilius + " turi " + counter + " remejus: " + miestuSarasas);
                    System.out.println("Ar norite ieskoti informacijos apie kita stiliu?");
                    System.out.println("Iveskite: Taip arba Ne");
                    kitasStilius = input.next();

                    }
                else {
                    System.out.println("Klaida, nerastas muzikos stilius");
                    break;
                    }
                        if ("Taip".equalsIgnoreCase(kitasStilius)) {
                        }
                        else if ("Ne".equalsIgnoreCase(kitasStilius)) {
                            System.out.println("Darbas baigtas.");

                        }
                            else{
                                System.out.println("Neteisingai pasirinkta.");
                                break;
                            }
                        bf.close();
                        }

            catch (IOException e) {
                System.out.println("Error:" + e.toString());
            }
        }
        }
        private void searchWord(String textToSearch ){
            //your logic here which performs the search and prints the result
         }
     }

Program counting words (entered by keyboard) from file.txt and elect who repeated this word for ex.: if I enter word: One It shows:
Word One repeated 3 times by John, Elisa, Albert

file.txt looks like:
John //first line - name
One
Three
Four

Peter //first line - name
Two
Three

Elisa //first line - name
One
Three

Albert //first line - name
One
Three
Four

Nicole //first line - name
Two
Four

Thank you for answers.

A: Wrap your code(slightly modified) in a while loop with condition on searchAgain as:
EDIT: Updating to accept the option as String:
 public class Testing {

   public static void main(String args[]) throws Exception {
       Scanner input = new Scanner(System.in);
        System.out.println("Select word from list:");
        System.out.println();

        String searchAgain = "";
        while(!"No".equalsIgnoreCase(searchAgain )){
           System.out.println("Do you want search for other word?");
           System.out.println("Enter: Yes or No");
           searchAgain = input.next();
           if ("Yes".equalsIgnoreCase(searchAgain)) {
              System.out.println("Write your word: ");
              String textToSearch = input.next();
              searchWord(textToSearch );
           } else if ("No".equalsIgnoreCase(searchAgain)) {
                 System.out.println("Program closed.");
           } else{
                 System.out.println("Invalid Input.");
           }
        }
     }

     private void searchWord(String textToSearch ){
        //your logic here which performs the search and prints the result
     }
 }


text:
Q: Examples of finite groups with "good" bijection(s) between conjugacy classes and irreducible representations? For symmetric group conjugacy classes and irreducible representation both are parametrized by Young diagramms, so there is a kind of "good" bijection between the two sets. For general finite groups see MO discussion.
Question: What are the finite groups where some "good" bijection(s)  between conjugacy classes and irreducible representations are known ?
"Good" bijection is an informal "definition", nevertheless I hope example of S_n and other examples listed below, may convince that the question makes sense.
I think that it is far too optimistic to have one unique bijection for general group,
but it seems to me that for certain classes of groups there can be some set of "good" bijections. Let me briefly discuss below some properties which "good" bijection may satisfy, and may be discuss details in the next question.

Some examples:
1) symmetric group S_n
2) Z/2Z is naturally isomprhic to its dual, as well as $Z/2Z \oplus Z/2Z$ see e.g. MO "fantastic properties of Z/2Z"
3) Generally for abelian finite groups:  among all set-theoretic bijections  $G \to \hat G$, some are distinguished that they are group isomorphisms.  So we have non unique, but
a class of "good" bijections.
4) For GL(2,F_q) Paul Garret writes: "conjugacy classes match in an ad hoc fashion with specic representations".  (See here  table at page 11).
5) G. Kuperberg describes relation of the McKay correspondence and that kind of bijection for A_5 (or its central extension), see here.
6) If I understand correctly  here at MO  D. Jordan mentions that bijection exists
for Coxeter groups.  (I would be thankful for detailed reference).
7) Dihedral groups $D_{2n}$ - see answer by Glasby below
8) Finite Heisenberg group with $p^{2n+1}$ elements, also known as extraspecial group - see answer by Glasby below
9) Quternionic group $Q_{8}$ - this actually can be seen as a particular example of the item above. Or note that it is $Z/2Z$ central extension of $Z/2Z \oplus Z/2Z$,
and $ Z/2Z \oplus Z/2Z$ has natural bijection
as mentioned in item 2 above, and it is easy to extend it to $Q_8$.

10)
It seems that for Drinfeld double of a finite group (and probably more generally for "modular categories") there is known some analog of natural bijection.
There is such remark at page 5 of
Drinfeld Doubles for Finite Subgroups
of SU(2) and SU(3) Lie Groups.
R. COQUEREAUX, Jean-Bernard ZUBER:

In other words, there is not only an equal number of classes and
  irreps in a double, there is also a canonical bijection between them.

There can be several properties which "good" bijection may satisfy, at least for some "good" groups
1) Respect the action of $Out(G)$. Actually the two sets are not isomorphic in general
as  $Out(G)$-sets (see MO21606), however there are many cases where they are isomorphic see G. Robinson's MO-answer.
2) Reality/Rationality constraints. Again in general there is no correspondence see MO, but there are some cases where corresponding properties of classes and irreps agree - see  J. Schmidt's answer on that question.
Two properties below are even more problematic
3) It might be that product on conjugacy classes have something to do with tensor product of representations (at least for abelian groups we may require these two fully agree).
4)   If to think about kind of "orbit method" ideology, and think that conjugacy class is in some sense perversed coadjoint orbit, we may hope that structure of conjugacy representation,
should somehow respect the "good" bijection. For example for $S_n$ we proved that
irrep corresponding to Young diagram "d" lives inside the conjugacy subrepresentation
realized as functions on the conjugacy class parametrized exactly by "d".
(See MO153561, MO153991 for some discussion of conjugacy (adjoint) representation).
5) For algebraic groups over finite fields conjugacy classes and irreps
sometimes naturally divided into families (e.g. conjugacy classes are often
parametrized by equations $ F_{t_i}(x_k)  = 0 $ - changing "t"
we get different conjugacy classes in the same "family").
So we may hope that good bijection respects the families.
(It is works fine for Heisenberg group, but for UT(4,p) I have met some problems).

A: I think it is one of the wunderful beauties of the representation theory of finite groups of Lie type $G(\mathbb{F_{p^n}})$ such as  $GL_2(\mathbb{F_p})$ mentioned above, that irreducible representations are in some canonical (but not perfect) correspondence to conjugacy classes in the  group with the dual root system $G^\vee$ ($\sim$ Langlands dual, this is usually isomorphic or a central extension, but $B_n,C_n$ are interchanged).
In these cases, what you are asking is an essential part of Langlands philosophy for a finite field. Most of what I shall write below I think attributes to Lusztig - it workes very roughly as follows:

*

*We all known Jordan decomposition: A matrix $x$ can be decomposed into a unipotent and semisimple matrix $x_sx_u$. Since unipotent matrices are an additive group and the diagonal matrices a multiplicative group, over the field $\mathbb{F_{p^n}}$ the elements $x_s$ have order $p^k$ and the elements $x_u$ have order prime to $p$.

*...Analogously hold (more complicated!): Every character  $\chi$ of $G(\mathbb{F_{p^n}})$ can be decomposed in a unipotent and a semisimple character $\chi_u, \chi_s$ (such that the dimensions multiply to $\dim(\chi)$), which are described as follows:

*The semisimple characters  can be characterized by having a dimension prime to $p$. They are in a quite transparent way in bijection to semisimple classes $[s]$ (i.e. of order prime to $p$) in the dual group $G^\vee(\mathbb{F_{p^n}})$....basically by looking what they do on the torus.

*The unipotent characters are much more complicated to deal with. In fact I do not even know (which doesnt mean there isn't) a definition independent of the theory of flag varienty cohmology and Deligne-Lusztig characters; typically on distinguishes between cuspidal unipotent representations and between unipotent representations induced from cuspidals of smaller parabolics.

*...Nevertheless: $\chi_u$ is a unipotent character of the centralizer of $[s]$, so it is a representation of an algebraic subgroup of the dual $G^\vee(\mathbb{F_{p^n}})$. It was a difficult conjecture (I think proven?) that these are now again in bijection to special unipotent classes in again the dual (of the dual).
Example:
For $G=PSL_2$ the dual is $G^\vee=SL_2$. The unipotent representations can be constructed from the set of Deligne-Lusztig characters and one fixed Irreps of the Weyl group. This is moreover true for $PSL_n$, so we have $n!$ unipotent representations. The two extremal cases are $\chi_u$ the trivial representation and $\chi_u$ the Steinberg representation of dimension $p$ (resp. $p^{n(n-1)/2}$). In the more general case we recover the picture known from $\mathbb{S}_n$:
Unipotent $SL_n$-Irreps $\chi_u$ biject from $\mathbb{S}_n$-Irreps biject to $n$-partitions biject to $\mathbb{S}_n$ conjugacy classes, but also to Jordan blocks of unipotent matrices (with eigenvalue $1$) in $SL_n$.

A: This is an interesting question, even though it is not well defined. Call a group "good" if it has a "good" bijection between its conjugacy classes and its irreducible complex representations. I agree with Alexander that the definition of a "good" bijection/group should be guided by classes of examples, but I prefer
that a class of bijections/groups should be infinite.
There are families of good metacyclic groups. For example, if $n=2m+1$ is an odd integer, then the dihedral groups $D_{2n}=\langle a,b\mid a^2=b^n=1,\; a^{-1}ba=b^{-1}\rangle$ of order $2n$ are good. The conjugacy classes $\{b^j,b^{-j}\}$, $1\leq j\leq m$, $\{1\}$, and
$\{a,ab,ab^2,\dots,ab^{n-1}\}$ correspond bijectively (I believe this is "good") to the irreducible representations
$\rho_j$, $1\leq j\leq m$, $\sigma_0$, and $\sigma_1$, respectively where $\rho_j(a)=\begin{pmatrix}0&1\\1&0\end{pmatrix}$, $\rho_j(b)=\begin{pmatrix}\zeta_n^j&0\\0&\zeta_n^{-j}\end{pmatrix}$,
$\sigma_k(a)=\begin{pmatrix}(-1)^k\end{pmatrix}$, $\sigma_k(b)=\begin{pmatrix}1\end{pmatrix}$ and $\zeta_n=e^{2\pi i/n}$.
If an infinite family $G_1, G_2,\dots$ of groups is good, then you know a vast amount about each $G_n$ and can likely produce is a formula writing $|G_n|$ as a sum of the squares of the degrees of the irreducible representations. For $D_{2n}$ this is $2n=4m+2=m\times 2^2+2\times 1^2$. If $G_n$ is an extraspecial group of (odd) order $p^{1+2n}$ and exponent $p$, then the formula is $p^{1+2n}=(p-1)\times(p^n)^2+p^{2n}\times 1^2$. Perhaps the existence of such a formula should be part of the elusive definition of "good".
Addition: Yes Alexander, you are correct, the extraspecial groups $G_n$ of order $p^{1+2n}$ and odd exponent $p$ are "good". To describe a "good" bijection I need some notation. Let $f_n\colon V\times V\to\mathbb{F}_p$ be a nondegenerate symplectic form on $V=\mathbb{F}_p^{2n}$. Multiplication in $G_n=V\times \mathbb{F}_p$ is given by $(v_1,\lambda_1)(v_2,\lambda_2)=(v_1+v_2,\lambda_1+\lambda_2+{\frac12}f_n(v_1,v_2))$, or by the matrices you indicate. The conjugacy classes are as follows: the $p$ one-element (central) classes $Z_\lambda:=\{(0,\lambda)\}$, $\lambda\in\mathbb{F}_p$, and the $p^{2n}-1$ classes $C_v:=\{(v,\lambda)\mid \lambda\in\mathbb{F}_p\}$ where $0\neq v\in V$. The irreducible representations are also easy. The trivial degree-1 representation corresponds to class $Z_0$ containing the identity element. The $p^{2n}-1$ nontrivial degree-1 representations correspond to the $p$-element classes $C_v$. The remaining $p-1$ irreducibles of degree $p^n$ correspond to the $p-1$ central conjugacy classes $Z_\lambda$, with $0\neq\lambda\in\mathbb{F}_p$. Fix a maximal totally isotropic subspace $W$ of $V$. By Witt's theorem $|W|=p^n$. Then $A:=W\times\mathbb{F}_p$ is a maximal abelian subgroup of $G_n$ of index $p^n$. Let $\sigma_\lambda$ be the 1-dimensional representation of $A$, with kernel $W$, mapping $(0,1)$ to $e^{2\pi i\lambda/p}$. The induced representations $\rho_\lambda={\rm Ind}_A^{G_n}(\sigma_\lambda)$ are irreducible of degree $p^n$. (A direct calculation shows $\langle\rho_\lambda,\rho_\lambda\rangle=1$.
Choosing a different $f_n$, or a different maximal totally isotropic subspace $W'$, gives equivalent representations $\rho'_\lambda$. The $W$s are permuted by ${\rm Aut}(G_n)$.) This is a "good" bijection, as identifying $V$ with its dual seems allowed.


text:
Q: Using concatenation operator in knockout data binding I am trying to add a string to the id attribute of an element using '+' operator. But the id could not be generated. Below is the code snippet:

Above html is in a html file which is rendered using ko.renderTemplate method.

A: another solution I found, is using String.concat

tested working in KnockoutJS 3.4.2


text:
Q: Subversion E000037: Can't get exclusive lock on file 'db/txn-current-lock': No locks available When I try to commit a change to a Subversion repository, and I get error messages of the form
svn: E000037: Commit failed (details follow):
svn: E000037: Can't get exclusive lock on file '/path/to/repo/db/txn-current-lock': No locks available
svn: E000037: Your commit message was left in a temporary file:
svn: E000037:    '/path/to/workdir/svn-commit.tmp'

What might be the cause?

A: The Subversion code ends up trying to obtain a lock on the txn-current-lock file via a call to apr_file_lock().  You should be able to reproduce the error with the following test:
#include <apr_general.h>
#include <apr_file_io.h>
#include <apr_pools.h>
#include <stdio.h>

int main(int argc, const char * const *argv, const char * const *env) {
    apr_file_t *f;
    apr_pool_t *pool;
    apr_status_t err;
    char errbuf[200];

    if (argc <= 1) {
        fprintf(stderr, "Error: Need to specify path to file to lock\n");
        return 1;
    }

    apr_app_initialize(&argc, &argv, &env);

    if (0 != (err = apr_pool_create(&pool, NULL))) {
        fprintf(stderr, "Failed to create APR pool\n");
        return 1;
    }

    if (0 != (err = apr_file_open(&f, argv[1], APR_FOPEN_CREATE | APR_FOPEN_WRITE, APR_UREAD | APR_UWRITE, pool))) {
        apr_strerror(err, errbuf, sizeof(errbuf));
        fprintf(stderr, "Open failed: %s\n", errbuf);
        return 1;
    }

    if (0 != (err = apr_file_lock(f, APR_FLOCK_EXCLUSIVE | APR_FLOCK_NONBLOCK))) {
        apr_strerror(err, errbuf, sizeof(errbuf));
        fprintf(stderr, "Lock failed: %s\n", errbuf);
        return 1;
    }

    if (0 != (err = apr_file_unlock(f))) {
        apr_strerror(err, errbuf, sizeof(errbuf));
        fprintf(stderr, "Unlock failed: %s\n", errbuf);
        return 1;
    }

    apr_pool_destroy(pool);
    apr_terminate();
    printf("OK\n");
    return 0;
}

Ensure that your apr-devel RPM package or libapr1-dev Debian package or equivalent is installed, then build and run the test using
cc -o locktest locktest.c $(apr-1-config --includes --cflags --link-ld --libs)
./locktest /path/to/repo/db/txn-current-lock

… ideally running as the webserver user, if using a Subversion server.

One surprising possible reason for failing to obtain a lock is if the repository resides on a filesystem mounted using NFS, and the NFS client is unable to write to /var/lib/nfs — perhaps due to the /var partition being full.


text:
Q: Writing functions for a command line in C. Errors I'm writing a program in C that calls functions from the command line and it is coming up with errors all in the first line of code (the for statement) and I'm not sure why or what they are. It says "syntax error found, expecting ;" "syntax error found, expecting )" "undeclared indentifier i" and "illegal statement termination."
int main(int argc, char *argv[])
{
  for(int i = 0; i < argc; i++ )
  {
    if(0 == stricmp("ParameterA", argv[i]))
    {
      exec1 = TRUE;
    }
    else if(0 == stricmp("ParameterB", argv[i]))
    {
      exec2 = FALSE;
    }
    else if(0 == stricmp("ParameterC", argv[i]))
    {
      exec2 = TRUE;
    }
    else
    {
      fprintf(stderr, "Unknown parameter: %s", argv[i]);
    }
  }
}

A: In C variable should be declared before any executable code.
you can change the code to
int main(int argc, char *argv[])
{
    int i = 0;
    for(i = 0; i < argc; i++ )
    ...

A: In C you can't declare int i inside a FOR loop
declare int i before the loop


text:
Q: How can I pass function's return value as parameter? I have lots of functions similar to FunctionOne. Difference in these is five = this.methodTwo(two, three, four, five). I don't want to repeat code. For doing that, how can I pass function's return value as parameter?
class MyClass {
    FunctionOne(one, two, three, four, five) {
        //some code here
        one = "my one";
        two = "my two";
        five = this.FunctionTwo(two, three, four, five); //How can I pass this as parameter
        one[five] = "something";
        return one;
    }
    FunctionThree(one, two, three, four, five) {
        //some code here
        one = "my one";
        two = "my two";
        five = this.FunctionFour(two, three, four, five); //Everything in FunctionThree is same as FunctionOne except this statement
        one[five] = "something";
        return one;
    }

    FunctionTwo(two, three, four, five) {
        //some code
        return five;
    }
}

A: One way to approach this would be to take the function as another parameter.
Similar to your FunctionOne, FunctionTwo etc. you could have FunctionX which does the common work and calls the passed function which, as a parameter, can be varied by the caller.
That would look something like this:
// added 'fn', the function to call, as the sixth parameter
FunctionX(one, two, three, four, five, fn) {
    //some code here
    one = "my one";
    two = "my two";
    five = fn(two, three, four, five);
    one[five] = "something";
    return one;
}

Now you can call this elsewhere like:
let x = FunctionX(h, i, j, k, l, FunctionOne);

A: So,

*

*By doing this:
five = this.FunctionTwo(two, three, four, five)

you calling function 'FunctionTwo' with params (two, three, four, five) and assigning result of function 'FunctionTwo' to variable 'five'

*

*By doing this:
five = this.FunctionTwo

you are assigning function 'FunctionTwo' instance to variable 'five', but NOT calling it yet.
Basically later in the code you can do something like that:
five(two, three, four)

*

*Not really clear what you want, but you can pass 'this' in to the 'FunctionTwo' and assign result to current object.

Ignore if nothing helps to you :)


text:
Q: How to uninstall OCaml in mac? I have the ocaml functionality in my mac (I'm using Sierra).I did not use opam or macport to install them.So how do I uninstall OCaml from my system?
I've been searching on Google but I can barely found one that discuss about how to do it in mac.I hope someone can explain this clearly..Thank you very much!!


text:
Q: MS OneNote Link To Paragraph links to page, not paragraph If I Copy Link to Paragraph and then paste that into my browser, it just loads the Page containing the paragraph rather than actually going to that paragraph.
Repro steps:

*

*Within OneNote for Windows Desktop

*Copy Link to Paragraph

*Paste into web browser

*Load the page

*Expected: Loads that page in OneNote for the web and jumps to that paragraph

*Actual: Just loads the page.

Is this just a known bug?

OneNote Windows 10 Desktop version , version 2210


text:
Q: Voting-system wont pass on vote to database I'm having difficulties on debugging why this voting-script I'm trying to adapt wont update the vote count and register the user's IP-address in the database. As of now neither of the two things seem to be working.
The script consists of:
Index.php:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>

<?php
error_reporting(E_ALL);
      ini_set('display_errors', '1');
include('config.php');
$sql=mysql_query("SELECT * FROM messages");
while($row=mysql_fetch_array($sql))
{
$message=$row['msg'];
$mes_id=$row['mes_id'];
$totalvotes=$row['totalvotes'];
?>

    <a href="" class="vote" id="<?php echo $mes_id; ?>" name="up">

    <?php echo $totalvotes ?>

    <a href="" class="vote" id="<?php echo $mes_id; ?>" name="down">

        <?php echo $message ?>

<?php } ?>

And up.php and down.php  that is similar except from the add/subtract part in the sql command.
<?php
error_reporting(E_ALL);
            ini_set('display_errors', '1');

include("config.php");

$ip=$_SERVER['REMOTE_ADDR'];

$id=$_POST['id'];
$id = mysql_escape_String($id);

$ip_sql=mysql_query("SELECT ip_add FROM voting_ip WHERE mes_id_fk='$id' AND ip_add='$ip'");
$count=mysql_num_rows($ip_sql);

if($count==0)
{
$sql = "UPDATE messages SET totalvotes=sum(totalvotes+1) WHERE mes_id='$id'";
mysql_query($sql);

$sql_in = "INSERT INTO voting_ip (mes_id_fk,ip_add) VALUES ('$id','$ip')";
mysql_query($sql_in);

}
else
{
}

?>

Online link here: http://itu.dk/people/mbaj/dwdeksamen/voting/voting/
Thanks in advance.


text:
Q: java.lang.IllegalStateException: Failed to introspect AuthenticatedPrincipalOAuth2AuthorizedClientRepository Class While adding Oauth2 configurations to my project, I got this error:
java.lang.IllegalStateException: Failed to introspect Class [org.springframework.security.oauth2.client.web.AuthenticatedPrincipalOAuth2AuthorizedClientRepository] from ClassLoader [jdk.internal.loader.ClassLoader$AppClassLoader@73d16e93]

For reference: Blog Link
I have these dependencies in my maven project.
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.7.0</version>
</parent>

...
    <!-- Spring Boot Web starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Security Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <!-- Oauth2 client -->
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-oauth2-client</artifactId>
    </dependency>
    <!-- WebClient -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>

Please tell me what am I doing wrong here? I think the problem is related to dependencies.


text:
Q: upload picture fail to system I created a form to upload picture to my system but picture uploading fails.
I tried whether my web service was connected using getCurrentTime() in my system and it is successfully connected.
My friend told me that it should be a server problem but my friend and I really have no idea on how to check whether our server was successfully connected to our system.
Can anyone help me on this problem?
Thank in advance.
my code
 protected void btnSave_Click(object sender, EventArgs e)
    {
        string fileName = string.Empty;
        if (File2.PostedFile != null)
        {
            fileName = System.IO.Path.GetFileName(File2.PostedFile.FileName);
        }
        if (fileName != string.Empty)
        {
            if (!this.CheckFileFormat(fileName))
            {
                WindowJS.WindowAlert("Image format is incorrect !");
                return;
            }
            string server = ImageURL;
            string unique = Guid.NewGuid().ToString();
            string filePath = server.TrimEnd('\\').TrimEnd('/') + ImageURLRelative + unique + "." + fileName.Split('.')[1].ToString();
           // string LocalfilePath = Server.MapPath("..") + unique + "." + fileName.Split('.')[1].ToString();
            string uploadFileName = unique + "." + fileName.Split('.')[1].ToString();
            try
            {
                HttpPostedFile mFile = File2.PostedFile;

                int fileSize = mFile.ContentLength;
                int done = 0;

                byte[] mFileByte = new Byte[fileSize];
                mFile.InputStream.Read(mFileByte, 0, fileSize);

                string WebServiceUrl = string.Empty;

                try
                {
                    Rewards.high5.RedemptionUpload high5UploadService = new Rewards.high5.RedemptionUpload();

                    if (Brand == "high5")
                    {
                        done = high5UploadService.UploadImage(uploadFileName, mFileByte);

                        if (done == 1)
                        {

                        }
                        else
                        {
                            WindowJS.WindowAlert("Error: Upload image fail.");
                            return;
                        }
                    }
                    //else if (Brand == "TLC")
                    //{
                    //    done = TLCUploadService.UploadImage(uploadFileName, mFileByte);
                    //}

                }
                catch (Exception ex)
                {
                    WindowJS.WindowAlert("Error: Upload image fail.");
                    return;
                }
            }
            catch (Exception ex)
            { WindowJS.WindowAlert(ex.Message.ToString()); }
            try
            {
                File2.PostedFile.SaveAs(filePath);
                ImgUrl.ImageUrl = ImageURLRelative + unique + "." + fileName.Split('.')[1].ToString();
            }
            catch (Exception ex)
            {
                WindowJS.WindowAlert(ex.Message.ToString());
            }
            ViewState["IMG"] = ImageURLRelative + unique + "." + fileName.Split('.')[1].ToString();
        }
        if (txtName.Text.Trim() == string.Empty)
        {
            WindowJS.WindowAlert("Please input the Name !");
            return;
        }
        try
        {
            Convert.ToDecimal(txtPoint.Text.Trim());
        }
        catch
        {
            WindowJS.WindowAlert("Please input the Points correctly");
            return;
        }
        if (ViewState["Type"].ToString() == "E")
        {
            int rows = EditRedemption();
            if (rows == 0)
            {
                WindowJS.WindowAlert("Failed to modify");
            }
            else
            {
                WindowJS.WindowAlert("Modified successfully");
                LoadInfo("V");

            }

            return;
        }
        else if (ViewState["Type"].ToString() == "A")
        {
            AB5VIP.BLL.Redemption red = new AB5VIP.BLL.Redemption();
            if (red.Exists_RedName(txtName.Text.Trim()))
            {
                WindowJS.WindowAlert("This Redemption already existed !");
                return;
            }
            int rows = AddRedemption();
            WindowJS.WindowAlert(rows == 0 ? "Failed to save" : "save successfully");
        }
        else if (ViewState["Type"].ToString() == "V")
        {
            AB5VIP.BLL.Redemption redlang = new AB5VIP.BLL.Redemption();

            int rows = redlang.UpdateRedemptionLang(Convert.ToInt32(ViewState["ID"].ToString()), ddlLang.SelectedItem.Value, txtName.Text, txtTitle.Text.ToString(), txtDesc.Text, Session["ABP_LoginName"].ToString(), System.DateTime.Now);
            WindowJS.WindowAlert(rows == 0 ? "Failed to save" : "save successfully");
        }
        lblCode.Text = string.Empty;
    }

A: Your application need writing permission on the folder where you're going to save the pictures. Depending wich version of IIS you're running, permissions most be granted to ASPNET user (IIS 6) or the account used for application pool (IIS 7).
http://blogs.msdn.com/b/david.wang/archive/2005/08/20/why-can-i-upload-a-file-without-iis-write-permission.aspx
Best regards.


text:
Q: recover git repository from a force push I'm having a problem with my git repository. Basically what I did was to run a force push into master (I don't remember the reasons behind that). That caused the branch to diverge, in fact if I pull from development:
~/workspace/my-project(master*) » git pull origin development
From https://github.com/xxxx/xxxxx
 * branch            development -> FETCH_HEAD
Updating 77239c7..958a5ff
Fast-forward
 .eslintrc.js                                                         |   17 -
 .gitignore                                                           |    4 +-
// other files differences...

But then when I try to commit:
~/workspace/my-project(master) » git commit -a
On branch master
Your branch and 'origin/master' have diverged,
and have 430 and 20 different commits each, respectively.
  (use "git pull" to merge the remote branch into yours)

nothing to commit, working tree clean

if I try to pull from master into master I get this error:
~/workspace/my-project(master) » git pull origin master
From https://github.com/xxxx/xxxxx
 * branch            master     -> FETCH_HEAD
fatal: refusing to merge unrelated histories

I have the hash of the forced push commit, what should I do to be able to merge development into master?


text:
Q: Angular 2 http does not catch connection refused error I want to catch all http errors to inform the user of an occurred problem.
So, I created a method that does a http get with a catch.
get(path: string): Promise<any> {
  let headers = new Headers();
  return this.http.get(path, { headers: headers })
    .toPromise()
    .then(response => { ... })
    .catch((response: Response) => { this.errorHandler(response); });
}

When the path parameter is '/fault-url' the catch is handled as expected.
But when the path is 'http://localhost:5000/fault-url' the error is not catched by the catch method.
I've added logging to all different places, but it seams the get method just aborts.
The console log shows following errors

OPTIONS http://localhost:5000/fault-url net::ERR_CONNECTION_REFUSED
EXCEPTION: Response with status: 0 for URL: null
Uncaught Response {_body: ProgressEvent, status: 0, ok: false, statusText: "", headers: Headers…}

Does http realy abort or am i doing something wrong?

A: After upgrading to Angular 2.3.0 the problem is solved.


text:
Q: Is there a way to convince Rust that a particular associated type is the same as a concrete type? Given the following traits and implementations:
trait Wrapper<Type> {
    type Inner : Wrapped<Type>;
    fn bind<B, F>(self, f: F) -> <B as Wrapped<Type>>::Outer
        where B: Wrapped<Type>, F: Fn(Self::Inner) -> <B as Wrapped<Type>>::Outer;
}

trait Wrapped<Type> {
    type Outer : Wrapper<Type>;
}

struct Opt;

impl<T> Wrapped<Opt> for T {
    type Outer = Option<T>;
}

impl<T> Wrapper<Opt> for Option<T> {
    type Inner = T;
    fn bind<B, F>(self, f: F) -> <B as Wrapped<Opt>>::Outer
        where B: Wrapped<Opt>, F: Fn(Self::Inner) -> <B as Wrapped<Opt>>::Outer {
        match self {
            Some(a) => f(a),
            None => None,  // *** fails to compile
        }
    }
}

It's obvious to a human that the type <B as Wrapped<Opt>>::Outer must always be Option<B>, but rustc can't seem to figure this out:
src/main.rs:47:21: 47:25 error: mismatched types:
 expected `<B as Wrapped<Opt>>::Outer`,
    found `core::option::Option<_>`
(expected associated type,
    found enum `core::option::Option`) [E0308]
src/main.rs:47             None => None,
                                   ^~~~

Is there any way to convince it that this is safe?  I'd even settle for an unsafe solution, but mem::transmute is also not allowed since it can't prove that the types are the same size and aligned (even though there's only one real type involved and not even any newtype wrappers that could mess up alignment).

A: This is most likely a bug (either this one or that one, I'm not sure). Until it's fixed, I can only think of doing some custom unsafe trickery. Here's a transmute function that does the size equality checks at runtime.
unsafe fn runtime_transmute<T, U>(t: T) -> U {
    assert_eq!(std::mem::size_of::<T>(), std::mem::size_of::<U>());
    std::ptr::read(&t as *const _ as *const _)
}

now you can replace your None value with
unsafe { runtime_transmute(None::<T>) }


text:
Q: Escaping symbols from the json data The problem is that I want to pass data to the vue component, I prepare a json data and use pass it as property.
<gallery-modal-edit
    :gallery='{!! json_encode($gallery) !!}'></gallery-modal-edit>

But vue writes in the console 'invalid expression:'. So I think it is connected with the wrong symbols, which are stayed in json data. So what should I do with it? Is it normal to use extra param on the json_encode function on the php, or there is a simply way to find the solution for this problem?
The strings which cause problem look like this:
"some text" <script>
alert('xss test');</script>
updated
Simple example of php array:
$gallery = ['text' => '"some text" <script>alert('xss test');</script>'];

A: You're using v-bind via the shorthand of :. It expects an expression. You are trying to pass a string. What Vue sees is like
:gallery="this is a string"

which is invalid syntax because Vue tries to interpret this is a string as an expression. You could quote it:
:gallery="'this is a string'"

and it would be valid, but it makes more sense to just do
gallery="this is a string"

A: Well, according to laravel-news, the best way to solve this problem is to use double encoding:
class AppServiceProvider extends ServiceProvider
{

  public function boot()
  {
    Blade::doubleEncode();
  }
}


text:
Q: Abort connection in case of Unauthorized JWT sent in http request to Web API .net Core 2 I am writing a .net Core 2.0 Web API controller that performs file upload using a multipart type http request and is based in the streaming technique described here.
At this point I have to say that I if you want you can skip the next two paragraphs that describe the reason that led me to the need for a solution to the problem that is described after the two paragraphs.
I initially thought of authenticating the user by sending authentication data in the first section of the multipart request and validating the user as soon as the user data are read, by contacting the database and performing the proper request. However, I thought that since this is a streaming request, any delay in authenticating the user using the database, would delay reading the stream with the file. This would cause the TCP receive buffer to fill with data (possibly also increase its size) and would defeat the purpose of streaming the file (instead of buffering), since memory consumption for this connection would increase.
In order to get rid of this issue I thought of using a 2 step authentication using JWTs. The Web API user will first perform a request and ask for a JWT. Then it would use this JWT in the upload request. As I understand it, JWT authentication should be much faster than a database request since it is performed by validating the JWT using the key stored in the server, so the previous issue should not exist.
I implemented the JWT authentication for the upload request following this very good description from Auth0 and it worked just fine. More specifically the controller has an [Authorize] attribute that forces Web API to to authenticate the user by validating the JWT before the controller is executed.
The problem I am facing is that with the above proposed solution when an unauthorized user tries to upload a file the Controller action is never called. The Authentication engine returns an Unathorized (401) response to the user and lets the user continue sending file data. The last part is my problem. I would like unauthorized users, which are probably attackers, to receive the 401 response and then have their connection terminated.
So, what I want is to keep the authentication/authorization part as it already works and also terminate the user connection after sending the 401 response. I know (and have also tested it) that from inside a controller action method an http connection can be terminated by calling
HttpContext.Abort();

I suspect that by using a filter, I could do what I want but I am not very familiar with filters so that is why I am asking.

A: We can achieve that by using an IAuthorizationFilter.
Inside it, we gonna set an special ActionResult called AbortUnauthorizedConnectionResult and in that we set the Status Code to 401 and Content-Length to 0 and by calling Response.Body.Flush() we make sure it's sent to client before we call Abort().
Here we have an AuthorizationFilter called AbortUnauthorizedConnections:
class AbortUnauthorizedConnections : Attribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        if (context.HttpContext.User?.Identity == null || !context.HttpContext.User.Identity.IsAuthenticated)
        {
            // by setting this we make sure the pipe-line will get short-circuited.
            context.Result = new AbortUnauthorizedConnectionResult();
        }
    }
}

And because we have inherited from Attribute we can use it on the upload action like this:
[Authorize]
[AbortUnauthorizedConnections]
public async Task<IActionResult> UploadFile()
{
    // we do whatever we want.
}

Here is the code for AbortUnauthorizedConnectionResult:
class AbortUnauthorizedConnectionResult : StatusCodeResult
{
    public AbortUnauthorizedConnectionResult() : base(401)
    {
    }

    public override async Task ExecuteResultAsync(ActionContext context)
    {
        await base.ExecuteResultAsync(context);
        context.HttpContext.Response.Headers.Add("Content-Length", "0");
        context.HttpContext.Response.Body.Flush();
        context.HttpContext.Abort();
    }
}

Now if an unauthorized user try to access this controller will get 401 and it's connection gets aborted.

A: This is the solution I actually implemented due to its simplicity, following @Tratcher's advice:
First, I deleted the [Authorize] attribute from my Controller Action method. Then I wrote the beginning of my Controller Action method as follows:
    public async Task<string> UploadFile()
    {
        if (!(await HttpContext.AuthenticateAsync()).Succeeded)
        {
            HttpContext.Response.StatusCode = 401; //Unauthorized
            HttpContext.Response.Headers.Add("Content-Length", "0");
            HttpContext.Response.Body.Flush();
            HttpContext.Abort();
            return null;
        }

        ...
    }


text:
Q: Comments on SQL equality check "length(col) = length (?) and col = ?" A previous developer has all of their Select * from TABLE where COLUMN = value; with an additional check so that the where clause is length(COLUMN) = length(value) and COLUMN = value when performing equality checks on String-type columns.
The reasoning (as I understand) is that performing the length check can be faster and therefore improve the performance of these types of queries. My feelings are

*

*if concerned, why not use an index on the DB? (I haven't checked, but these may already be there)

*is it likely to improve the query at all, and if at all would it be specific to a certain engine or DB version?

*can it in fact be worse?

*if this is that much better, wouldn't the DB engine be likely to perform its own check under the covers? (eg statement compilation and optimisations)

*under what conditions would anyone actually notice the change?

*does it result in some either (positive or negative) DB type side effect?

I believe it was initially targeting MySQL 5.1 and we're now on MySQL 5.7, but my request for comments is not specific to these. My Google-foo returned nothing on the topic, but it smells like premature optimisation.
Note also that these are only used for direct equality, typically on unique fields, often on small tables and also often for enumeration of lookup type tables.

A: As mentioned in a comment, this handles spaces at the end of a string.
As you can see in this db<>fiddle:
select ('abc' = 'abc '), length('abc'), length('abc ')

MySQL does not (in the versions you mention) support check constraints.  So there is no simple way to prevent spaces from the end of strings.
In general, such spaces would be examples of bad data.  My guess is that the developer encountered this problem once upon a time and inserted these checks as defensive programming.
I think I would instead recommend using BINARY to get an exact match:
('abc' = binary 'abc ')

I'm not sure if this would have some unexpected consequences.


text:
Q: PYTHON get the last item of a list even if empty My Python script opens 2 threading.Threads() with the following functions :

*

*Stuff() : function appending stuff to a list (global var) if stuff happens in a big loop.

*Monitor() : function displaying the last item added to the list every second with additional info.

The purpose of these 2 threads is that Stuff() contains a loop optimized to be very fast (~ 200 ms / iteration) so printing from inside would be pointless. Monitor()takes care of the output instead.
At the beginning, I set list = [], then start the threads. Inside Monitor() I get the last item of the list with list[-1] but if no stuff happend before, the list is still empty and the Monitor() raises an IndexError: list index out of range.
Is there a simple way (no try or if not list) to display None instead of an error if the list is empty ?

A: Here's a way, although it looks odd:
(list or [None])[-1]

A: I find this more readable than @Alex's answer
lst = [1, 3, 2]
print None if not lst else lst[-1]

Edit: Though must admit, it is the first time I encountered that usage. Always thought those expressions returned bool type :)

A: You can use it also like this:
[1, 2, 3, 4][-1:] -> [4]
[][-1:]           -> []
[][-1:] or None   -> None


text:
Q: Where / how to determine whether chat message was sent or received (android) Android chat app. I'm using a temporary ArrayList on the client to make sure displaying the chat bubbles work as expected. Where and how do I determine if a message was sent or received?
ChatConversationFragment:
messageArrayList.add(new ChatConversationMessage("Hello"));
messageArrayList.add(new ChatConversationMessage("Yeah"));
messageArrayList.add(new ChatConversationMessage("Yeah", R.drawable.redhead_1));
//this last one is received because it has two inputs

ChatConversationMesssage:
/**
 * The reason we have TWO of these methods with the same name is because sent
 * messages don't have an image. We need to have a separate method for that.
 **/
public ChatConversationMessage(String sentTextMessage) {
    mSentTextMessage = sentTextMessage;
}

public ChatConversationMessage(String receivedTextMessage, int imageResourceId) {
    mReceivedTextMessage = receivedTextMessage;
    mImageResourceId = imageResourceId;
}

ConversationMessageAdapter:
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View listItemView = convertView;
    Holder holder;
    ChatConversationMessage currentMessage = getItem(position);

    if(listItemView == null) {
        holder = new Holder();

        if(currentMessage){
        listItemView = LayoutInflater.from(getContext()).inflate(
            R.layout.chat_conversation_txt_sent, parent, false);
        }
    }

    TextView sentText = listItemView.findViewById(R.id.textview_chat_message_sent);
    sentText.setText(currentMessage.getSentTextMessage());

    TextView receivedText = listItemView.findViewById(R.id.textview_chat_message_received);
    receivedText.setText(currentMessage.getReceivedTextMessage());

    return listItemView;
}

So I was trying to put it in an if-statement in this last class (the adapter). But I don't know what method to make and where to place it so I can return a Boolean or something to make it display different chat bubbles based on if the message was sent or received.

A: I found a solution for those interested:
The getView method was the only one that needed changing.
I needed to use the "setText" method within the if-statements so that the correct layout was inflated for each instance.
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View listItemView = null;
    ChatConversationMessage currentMessage = getItem(position);

    if (currentMessage.getSentTextMessage() != null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                R.layout.chat_conversation_txt_sent, parent, false);
                TextView sentText = listItemView.findViewById(R.id.textview_chat_message_sent);
                sentText.setText(currentMessage.getSentTextMessage());
        }

    if (currentMessage.getReceivedTextMessage() !=null) {
        listItemView = LayoutInflater.from(getContext()).inflate(
                R.layout.chat_conversation_txt_received, parent, false);
                TextView receivedText = listItemView.findViewById(R.id.textview_chat_message_received);
                receivedText.setText(currentMessage.getReceivedTextMessage());
    }

    return listItemView;
}

I don't know if it's the best way, but it works and I think it's concise and easy to read.


text:
Q: urllib: html to csv error I tried to grab tabular data and save as csv file as follows:
import urllib, pandas as pd
url = 'https://finance.yahoo.com/quote/BTC-JPY/history?period1=1314403200&period2=1314489600&interval=1d&filter=history&frequency=1d'

fo = 'test.txt'

response = urllib.request.urlopen(url)
html =  response.read()
data = pd.read_html(html)
data.to_csv(fo, index = False, header=False, sep=',', mode='w')

but got following error:
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U95') dtype('<U95') dtype('<U95')

without pandas
lines = html.splitlines()
for l in lines:
    fo.write(str(l) + '\n')

it writes bytes, unreadable format .
i just need tabular data
Date    Open    High    Low Close*  Adj Close** Volume
Aug 28, 2011    700.99  700.99  700.99  700.99  700.99  -
Aug 27, 2011    700.99  700.99  700.99  700.99  700.99  700

A: Below code will produce what u are looking for :
import urllib
import urllib.request
import html5lib
import pandas as pd
from bs4 import BeautifulSoup
url = 'https://finance.yahoo.com/quote/BTC-JPY/history?period1=1314403200&period2=1314489600&interval=1d&filter=history&frequency=1d'

fo = 'test.txt'
pd.set_option('display.max_colwidth', -1)
response = urllib.request.urlopen(url)
html =  response.read()
soup = BeautifulSoup(html)
table = soup.find("table")
headings = [th.get_text() for th in table.find("tr").find_all("th")]
file = open(fo,"w")
file.write(",".join(headings) + "\n")
for row in table.find_all("tr")[1:]:
    data = [td.get_text() for td in row.find_all("td")]
    if len(data)==len(headings):
        file.write(",".join(data) + "\n")
file.close()

Output:
Date,Open,High,Low,Close*,Adj Close**,Volume
Aug 28, 2011,700.99,700.99,700.99,700.99,700.99,-
Aug 27, 2011,700.99,700.99,700.99,700.99,700.99,700


text:
Q: How to initialize nested structs I have this code in one file:
struct ReadyQueue {
    struct PCB *pcb;
    struct ReadyQueue *next;
};

extern struct CPU new_cpu;

typedef struct ReadyQueue *node;

node* head;

node createNode() {
    node temp;
    temp = (node)malloc(sizeof(struct ReadyQueue));

    if (temp == NULL) {
        printf("Error creating node");
        exit(0);
    }

    temp->next = NULL;
    free(temp);

    return temp;
}

node* head;

void addToReady(FILE *p) {

    node temp;
    temp = createNode();

    temp->pcb->PC = p;  // error here

    if (temp == NULL) {
        printf("Error");
    }

}

Which creates a linked list of nodes. In my addToReady function, I am having trouble setting the PCB value which has another struct declared in another file:
struct PCB {
  FILE *PC;
};

I am having the error in temp->pcb->PC=p and its giving me a Segmentation Fault 11 error.


text:
Q: Como preencher todo um vetor com malloc(sizeof(int)) com algum valor Estou com um problema, não tenho ideia de como preencher este vetor com algum valor, por exemplo, eu quero preencher ele todo com -1 (iniciar ele todo com -1).
O problema aqui é que eu não sei exatamente qual o tamanho do meu vetor.
    typedef struct argumentosThread {
        int dim, queens, posicoes, total;
        int *posicCertas;
        int head;
    }ArgumentosThread;

La no meio do codigo eu inicializo ele, eu coloquei o sizeof(int) porque eu não sei qual vai ser o tamanho do vetor, ele pode ser bem pequeno ou então MUITO grande.
    argumentos->posicCertas = malloc(sizeof(int));

A: No momento em que alocar esse vetor usando malloc, armazene também seu tamanho na estrutura...
E faça um laço for para preencher conforme deseje.
argumentos->posicCertas = (int*)malloc(sizeof(int)*n_pos);
argumentos->n_pos = n_pos;

Depois só fazer um for preenchendo o vetor.
É interessante também fazer um casting do retorno do malloc.


text:
Q: mathastext package: \ell undefined control sequence I'm using the mathastext package in order to get a sans math font throughout the document.
Unfortunately then the \ell command is undefined. Is there any way, to get this back, e.g. with unicode usage, but how?
MWE:
\documentclass{scrartcl}

\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage[T1]{fontenc}
\usepackage{amsmath}
\usepackage{amssymb}

\renewcommand\familydefault\sfdefault
\usepackage[symbolgreek,defaultmathsizes]{mathastext}
\renewcommand\familydefault\rmdefault

\begin{document}
$\ell$
\end{document}

A: This restores an \ell whether it fits well with your font choice I leave for you to judge:-)
\documentclass{scrartcl}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage[T1]{fontenc}

\usepackage{amsmath}
\usepackage{amssymb}

\renewcommand\familydefault\sfdefault
\let\xell\ell
\usepackage[symbolgreek,defaultmathsizes]{mathastext}
\let\ell\xell
\renewcommand\familydefault\rmdefault

\begin{document}
$\ell$
\end{document}


text:
Q: Plotly parallel category linked brushing(cross filter) with Dash in Python I want to create a parallel category in plotly that have linked brushing as the documentation from plotly.
https://plotly.com/python/parallel-categories-diagram/#parallel-categories-linked-brushing
However, inside, it only show how to do it without plotly-dash.
How to combine go.Pract and dash? Can someone help me with this?

A: Let myself answer this question, hopefully can save someone's developing time.
There are two key point to take away before jumping to the code:

*

*A dash callback is required to pass the selected index between two graphs. Reference to plotly docs.

*go.Parcat dose not support selectedData for the callback, instead, you need to use clickData. This is a bit tricky.

Here is my approach.
import plotly.graph_objects as go
import pandas as pd
import numpy as np
import dash
from dash import dcc
from dash import html
from dash.dependencies import Input, Output

cars_df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/imports-85.csv')

# Build figure as FigureWidget
def get_parcat_fig(selected_index, cars_df):  # create function to update fig object
    # Build parcats dimensions
    categorical_dimensions = ['body-style', 'drive-wheels', 'fuel-type']
    dimensions = [dict(values=cars_df[label], label=label) for label in categorical_dimensions]

    color = np.zeros(len(cars_df), dtype='uint8')
    colorscale = [[0, 'gray'], [1, 'firebrick']]
    color[selected_index] = 1

    fig = go.FigureWidget(
        data=[go.Scatter(x=cars_df.horsepower, y=cars_df['highway-mpg'],
                         marker={'color': 'gray'}, mode='markers', selected={'marker': {'color': 'firebrick'}},
                         unselected={'marker': {'opacity': 0.3}}, selectedpoints=selected_index),
              go.Parcats(
                  domain={'y': [0, 0.4]}, dimensions=dimensions,
                  line={'colorscale': colorscale, 'cmin': 0,
                        'cmax': 1, 'color': color, 'shape': 'hspline'})
              ])

    fig.update_layout(
        height=800, xaxis={'title': 'Horsepower'},
        yaxis={'title': 'MPG', 'domain': [0.6, 1]},
        dragmode='lasso', hovermode='closest')
    return fig

app = dash.Dash(__name__)
app.layout = html.Div([
    dcc.Graph(
        id='parallel_category'
    )
])

@app.callback(
    Output("parallel_category", "figure"),
    Input("parallel_category", "selectedData"),
    Input("parallel_category", "clickData")
)
def get_fig_callback(selected_data, click_data):
    ctx = dash.callback_context
    if (ctx.triggered[0]['prop_id'] == "parallel_category.selectedData") \
            or (ctx.triggered[0]['prop_id'] == "parallel_category.clickData"):
        selected_data = [point['pointNumber'] for point in ctx.triggered[0]['value']['points']]
    else:
        selected_data = []
    return get_parcat_fig(selected_data, cars_df)

if __name__ == '__main__':
    app.run_server(debug=True)

A: import plotly.graph_objects as go
import pandas as pd
import numpy as np
import dash
from dash import dcc
from dash import html
from dash.dependencies import Input, Output

cars_df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/imports-85.csv')

# Build figure as FigureWidget
def get_parcat_fig(selected_index, cars_df):  # create function to update fig object
    # Build parcats dimensions
    categorical_dimensions = ['body-style', 'drive-wheels', 'fuel-type']
    dimensions = [dict(values=cars_df[label], label=label) for label in categorical_dimensions]

    color = np.zeros(len(cars_df), dtype='uint8')
    colorscale = [[0, 'gray'], [1, 'firebrick']]
    color[selected_index] = 1

    fig = go.FigureWidget(
        data=[go.Scatter(x=cars_df.horsepower, y=cars_df['highway-mpg'],
                         marker={'color': 'gray'}, mode='markers', selected={'marker': {'color': 'firebrick'}},
                         unselected={'marker': {'opacity': 0.3}}, selectedpoints=selected_index),
              go.Parcats(
                  domain={'y': [0, 0.4]}, dimensions=dimensions,
                  line={'colorscale': colorscale, 'cmin': 0,
                        'cmax': 1, 'color': color, 'shape': 'hspline'})
              ])

    fig.update_layout(
        height=800, xaxis={'title': 'Horsepower'},
        yaxis={'title': 'MPG', 'domain': [0.6, 1]},
        dragmode='lasso', hovermode='closest')
    return fig

app = dash.Dash(__name__)
app.layout = html.Div([
    dcc.Graph(
        id='parallel_category'
    )
])

@app.callback(
    Output("parallel_category", "figure"),
    Input("parallel_category", "selectedData"),
    Input("parallel_category", "clickData")
)
def get_fig_callback(selected_data, click_data):
    ctx = dash.callback_context
    if (ctx.triggered[0]['prop_id'] == "parallel_category.selectedData") \
            or (ctx.triggered[0]['prop_id'] == "parallel_category.clickData"):
        selected_data = [point['pointNumber'] for point in ctx.triggered[0]['value']['points']]
    else:
        selected_data = []
    return get_parcat_fig(selected_data, cars_df)

if __name__ == '__main__':
    app.run_server(debug=True)


text:
Q: Python:- Split email from list of emails (comma, space separated) My input is
email_list =

"mail1@mail.com,mail2@mail.com, mail3@mail.com mail4@mail.com
mail5@mail.com"

Excepted output is
['mail1@mail.com', 'mail2@mail.com', 'mail3@mail.com', 'mail4@mail.com', 'mail5@mail.com']

I tried this method, but it will split only (,) separated. please let me know.
output = email_list.split(',')

Thanks in advance...

A: You can use regular expression :
>>> import re
>>> email_list = "mail1@mail.com,mail2@mail.com, mail3@mail.com mail4@mail.com"
>>> re.split(r'[, ]*',email_list)
['mail1@mail.com', 'mail2@mail.com', 'mail3@mail.com', 'mail4@mail.com']

re.split split your string based on r'[, ]*' that split with any combine of comma (,) and space ().

A: Strangely - no one appears to have pointed possibly the most obvious and easiest...
>>> email_list = "mail1@mail.com,mail2@mail.com, mail3@mail.com mail4@mail.com"
>>> email_list.replace(',', ' ').split()
['mail1@mail.com', 'mail2@mail.com', 'mail3@mail.com', 'mail4@mail.com']

A: Without regex,
>>> email_list = "mail1@mail.com,mail2@mail.com, mail3@mail.com mail4@mail.com"
>>> [i for x in email_list.split(',') if x for i in x.split(' ') if i]
['mail1@mail.com', 'mail2@mail.com', 'mail3@mail.com', 'mail4@mail.com']

A: Also without regex :)
import re
email_list = "mail1@mail.com,mail2@mail.com, mail3@mail.com mail4@mail.com"
print filter(lambda x:x, sum([x.split(",") for x in email_list.split(" ")], []))

A: Try
email_list.replace(" ","")

Before you use
output = email_list.split(',')


text:
Q: Creating a recovery disk of Windows 10 I've recently purchased Dell laptop and it has Windows 10 pre-installed on it. I plan to install Ubuntu GNOME 16.04.2 LTS on it. But before doing so, I want to make recovery disk of Windows 10 so that in case if I lose my Windows 10 installation while installing Ubuntu, I can get recover it.
I found following options from Settings / Control Panel of Windows 10:

*

*Control Panel > Recovery > create a recovery drive

*Control Panel > Backup & Restore (Windows 7)

Which has two options create a system image and create a system repair disk. What's the difference between them?
Now I have three options:

*

*Create a recovery drive

*Create a system image

*Create a system repair disk

Here 1st option only allows me to create use a USB drive whereas I want to use a DVD. Which option should I use?

A: Well, the names are kinda self explanatory, but this what they do:

*

*Create a system image: A system image is a complete copy of your computer in its current state. This includes all of your files, and installed programs. If you ever restore from a system image in the future, it'll be exactly like it was when you created the image.
Note that this can be stored anywhere, but you cannot boot from it, ie, you need a working Windows installation to restore your PC to an earlier state using an image. Alternatively, if your computer came with a recovery partition, you can boot into it, and then restore your PC using an image.

*Create a system repair disk: A system repair disk will try to, well, repair your OS (ie, system files used by Windows) in case it is not working properly. It will NOT, however, do anything to repair/restore your personal data, or changes that you've made to the OS, such as installing software. Also note that it cannot be used to re-install Windows.

*Create a recovery drive: This will allow you to completely reset your Windows installation in case something goes wrong with your installation, but will not recover any of your personal files. If your computer came with a recovery partition, this may not be required.
In your case, since you may completely remove the Windows OS while installing Ubuntu, you should create a recovery drive. While you can also use create a system image or a system restore point and then restore your PC to it via the recovery partition, some PCs come without a recovery partition, and chances are that while installing a new OS, this partition may get corrupt too.
The reason you cannot use a DVD drive to create a recovery drive is that these are usually too large to fit on DVD drives. Flash drives aren't too expensive nowadays, and you can use a 8GB+ one perfectly, especially since your OS is a new install and doesn't have too many files/extra software.
Pro tip: Take note of your Windows 10 serial key too, and save it somewhere. In case you lose your Windows 10 installation, you can create a installation drive on another PC, and then use it to install Windows on your computer with the serial key.


text:
Q: Android app says the file does not exist but it does. I need to install it Here is my code:
        String dir = getFilesDir().getAbsolutePath();
        File myFile = new File(dir+"/file.apk");

        if (myFile.exists())
        {
            textView.setText("File exists.");
        }
        else
        {
            textView.setText("File does not exist.");
        }

myFile.exists() is false. I do not know why. The file exists and it is located in the directory.
When I solve the problem, I'll try this:
            Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
            intent.setData(Uri.fromFile(myFile));
            intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);

Can somebody help? Why it does not see the file?
UPDATE:
It's really strange. If I use code:
            if (myFile.exists())
            {
                textView.setText("it exists");
            }
            else
            {
                textView.setText(myFile.getAbsolutePath());
            }

, it goes to 'else' and shows the path to the file which 'does not exist'.

A: Thanks to greenapps:
"Please click in Astro app left to the word Primary on the up arrow to see the real path. /Primary/ does not exist on an Android device. It's an Astro invention. And Astro shows external memory with Primary. And take a better file explorer like ES File Explorer to inform you about real paths"
I used direct path I found using Astro (modified string dir to '/sdcard/data/data/...").

A: Try using this code:
    String dir = getFilesDir().getAbsolutePath();
    boolean fileExists = (new File(dir + "/file.apk")).isFile();

    if (fileExists)
    {
        // your file exists
    }
    else
    {
        // your file does not exist
    }

A: If you construct the file with the 2-arg constructor, you can avoid adding a system-dependent path separator character. Like this:
    File myFile = new File(dir, "file.apk");


text:
Q: jQuery set UI Slider when page loads using URL query string I've searched through many promising answers under various SO questions, trying each one - to no avail. I've reduced my webpage to focus on just the two issues I've not been able to figure out:

*

*When the page loads the first time, I want to parse a URL query parameter (if it exists), and use the results to set the initial state of jQuery UI sliders that the user will see. This will let people pass around the URL strings with this query parameter to others, who can then launch a browser window with the URL and see exactly the same settings (i.e. the slider handle positions) as the originator. If the query parameter does not exist in the URL, the page should load with default settings - just using the code. So, how can I get a query string from the full URL and parse it before the default HTML shows with sliders set to their fixed initial defaults?

*The issue that has so many answers that I've tried is how to programmatically set jQuery UI Sliders. I've tried to run code in different places in the code (see the alert() and following 2 lines) - but no matter where I put the code, it either does not run at all (no alert), or if it does run, but the slider handles never change from their default.
The libraries I'm using are jQuery-1.12.4, jQueryUI-1.12.1, and jQuery-3.1.1
<!DOCTYPE html>

    <meta charset="utf-8" />
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

                Climate:
                Hot to Cold

A: Here is what I would advise:

$(function() {
  var climateSteps = [
    "Hot",
    "Humid",
    "Dry",
    "Wet"
  ];

  function getUrlParameter(sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
      sURLVariables = sPageURL.split('&'),
      sParameterName,
      i;

    for (i = 0; i < sURLVariables.length; i++) {
      sParameterName = sURLVariables[i].split('=');

      if (sParameterName[0] === sParam) {
        return sParameterName[1] === undefined ? true : sParameterName[1];
      }
    }
  };

  function parseValue(s) {
    var head = s[0];
    var min = parseInt(s[1]);
    var max = parseInt(s[2]);
    var value = [head, min, max];
    return value;
  }

  $("#climate-slider .slider").slider({
    range: true,
    min: 0,
    max: 3,
    values: [0, 3],
    slide: function(event, ui) {
      climateRange = "C" + ui.values[0].toString() + ui.values[1].toString();
      if (ui.values[0] == ui.values[1]) {
        /* if user selected a single value (not a range), adjust text to fit */
        $(this).parent().children(".slider-range").text(climateSteps[ui.values[0]]);
      } else {
        $(this).parent().children(".slider-range").text(climateSteps[ui.values[0]] + " to " + climateSteps[ui.values[1]]);
      }
    }
  });

  var urlValue = getUrlParameter("sliders");
  var slideValues = parseValue(urlValue);
  if (slideValues[0] === "C") {
    $("#climate-slider .slider").slider("values", [slideValues[1], slideValues[2]]);
  }
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

      Climate:
      Hot to Cold

This is example cannot be tested since the URL of this page is not correct. I wrote this example to handle the test URL you provided:
www.example.com/?sliders=C12

We will get the parameter value from sliders and then parse it into "C" , 1 and 2. I store these in an array.
We can then set the values of the slider to these, by passing in an array [1, 2]. See more: http://api.jqueryui.com/slider/#method-values
You could do this in the parsing too:
function parseValue(s) {
  var head = s[0];
  var min = parseInt(s[1]);
  var max = parseInt(s[2]);
  var value = [head, [min, max]];
  return value;
}

Then used like so:
$("#climate-slider .slider").slider("values", sliderValues[1]);

Hope that helps.


text:
Q: Sunspot solr search with negative value I have a Wallet model with two fields user_id of type integer and balance of type floating point and have configured solr search on Wallets.
There are chances of wallet balance being negative value.
Below are the code blocks :
Wallet.rb
searchable do
  text :balance

  text :user do
    user.name
  end
end

WalletsController.rb
def index
  @search = Wallet.search {
    fulltext params[:search]
    paginate :page => params[:page], :per_page => 10
  }
end

Wallets/index.html.erb
<%= form_tag wallets_path, :method => :get do %>
  <%= text_field_tag :search, params[:search] %>
  <%= submit_tag "Search" %>
<% end %>

With this above implementation the search is returning incorrect records on searching for Wallets having negative balance.

Ex:
    search : 30
    results : 30, -30
search : -30
    results : -100, 500 (Wallets without balance = 30/-30 are returned)

Can someone provide an efficient logic to get this working?

A: Either solr configuration has to be changed to not consider "-" as special character or the search term needs to be changed and passed on to Sunspot.


text:
Q: Two list of figures I'm trying to get two separate lists of figures. Ones are the figures containing some plots created using tikzpicture like:
\begin{figure}
  \begin{tikzpicture}
    \begin{axis}
    ...
    \end{axis}
  \end{tikzpicture}
\end{figure}

and the others are simple images. At result I need to have List of Figures and a List of Plots. How can I achieve it? Please give an example if possible.

A: The package newfloat offers you a simple interface:
\usepackage{newfloat}

\DeclareFloatingEnvironment[
  fileext=lop,
  listname={List of Plots},
  name=Plot,
  placement=tp,
  %within=section,% activate it if you want
  %chapterlistsgaps=on,% meaningful only if chapters exist
]{plot}

Full example:
\documentclass{article}

\usepackage{newfloat}
\usepackage{pgfplots}

\DeclareFloatingEnvironment[
  fileext=lop,
  listname={List of Plots},
  name=Plot,
  placement=tp,
  %within=section,% activate it if you want
  %chapterlistsgaps=on,% only meaningful when chapters exist
]{plot}

\pgfplotsset{compat=1.13}

\begin{document}

\listoffigures

\listofplots

\section{Test}

\begin{figure}[htp]
\centering

\fbox{\rule{0pt}{3cm}\rule{3cm}{0pt}}

\caption{A figure}

\end{figure}

\begin{plot}[htp]
\centering

\begin{tikzpicture}
\begin{axis}[
    extra x ticks={-2,2},
    extra y ticks={-2,2},
    extra tick style={grid=major}]
    \addplot {x};
    \draw (axis cs:0,0) circle[radius=2];
\end{axis}
\end{tikzpicture}

\caption{A plot}

\end{plot}

\end{document}


text:
Q: How to fix symbol index entry? All my entries in the symbol index involving $\|\cdot\|$ get rejected. For instance
{\index{symbol}{normx@{$\|\cdot\|_X$}}}.
How can I fix this?

A: The symbol | is special within the \index command as it deals with special page ranges. You need to hide this from TeX using something like
\newcommand{\norm}{\|}

Also note that \index takes only one argument which is the index entry. If you want to also print this entry in text, you need to use the following format:
...blah blah symbol\index{symbol} blah blah...

virtually duplicating the typeset component and index entry. Here's your MWE with a the above modifications:

\documentclass{article}
\usepackage{makeidx}% http://ctan.org/pkg/makeidx
\newcommand{\norm}{\|}
\makeindex
\begin{document}
See $\|\cdot\|_X$\index{normx@$\norm\cdot\norm_X$} and the norm\index{norm}.

\printindex
\end{document}

Consider reading through Leslie Lamport's MakeIndex : An Index Processor For LaTeX.

A: Special characters for MakeIndex should be quoted: so to index |x| you have to write
\index{"|x"|}

The " character before a special character makes it lose its meaning. However \" is not treated in a particular way (it's an accent command), so your entry should be
\index{"\"|x"\"|}

or \index{normx@"\"|x"\"|} if you want a string for specifying the alphabetic order.
If you use more entries with | than entries such as \index{abc|see def} you can create a personal MakeIndex style containing just one line
encap '*'

Call this file mystyle.ist and call MakeIndex as
makeindex -s mystyle.ist filename

This will disable the special feature of | (whose role is taken by *) and so you can type \index{normx@$\|x\|$} without other precautions.


text:
Q: Querying an integer field by just checking the last x digits I have an integer field in the format YYYYMMDD, and I want to return all records made on a certain day of the month. Is there a way to perform this arithmetic within a NSPredicate so it is translated into SQL (for optimised lookups)?
Basically I need to perform the operation: (identifier - floor(identifier / 100) * 100) == day, or identifier % 100 == day (whichever ends up being a faster comparison), but this doesn't seem to work within an NSPredicate. You can't seem to perform mathematical operations in the predicate.
Alternatively, is there some way to cast a field as a string within the query? So I can use ENDSWITH?
It's an sqlite store so I think some of the predicate comparison functions (blocks mainly) can't be used, as they're restricted to in-memory stores.
Any info on how to perform this efficiently would be greatly appreciated.

A: You are in a difficult place because you really should treat that as a date object with a zero time reference, etc.
In a second option if it was just a string then life would be pretty easy too.
Having it as an integer makes your predicate rough.
Just shooting from the hip but have you tried treating it as a string?  SQLite doesn't really care although Core Data might complain about it.
Is this an existing app or do you have the opportunity to change the data model?

A: I would try the ENDSWITH syntax.
SQLite tends to transform between numeric and string types fairly transparently.