text:
Q: Addition of two subspaces Suppose that we have a vector space $V$ and the subspaces $U=\{(x,x,y,y)\in F^4:x,y\in F\}$ and $W=\{(x,x,x,y)\in F^4:x,y\in F\}$. Then how comes
$$U+W=\{(x,x,y,z)\in F^4:x,y,z\in F\}?$$

A: Let $\vec u \in U $ and $ \vec w \in W$. It follows that $\vec u + \vec w \in U + W$. Now, consider any element in $U$, which means that it is of the form $(a,a,b,b)$, with  $a, b \in F$. Consider some element in $W$. It will be of the form $(c,c,c,d)$, with $c,d \in F$.
Adding the two vectors yields:
$$\vec e = (a,a,b,b) + (c,c,c,d) = (a+c, a+c, b+c, b+d) \in U + W.$$
However, $$(a+c, a+c, b+c, b+d) = (a+c)\cdot (1,1,0,0) + (b+c)\cdot (0,0,1,0) + (b+d)\cdot (0,0,0,1).$$
That means that our vector $\vec e$ can be written as a linear combination of the  linearly independent vectors $(1,1,0,0), \, (0,0,1,0), \, (0,0,0,1)$. Thus, $U+W$ contains all the linear combinations of the $3$ above linearly independent vectors, which means  that every element in $U+W$ can be written as:
$$x(1,1,0,0) + y(0,0,1,0) + z(0,0,0,1) = (x,x,y,z), \quad x,y,z \in F.$$
I guess you are talking about vector spaces.


text:
Q: py2exe [ImportError: No module named sqlalchemy] I installed sqlalchemy-0.8.1 in my win7 via 'setup.py install'
and "import sqlalchemy" works well
But when I want to pack my files with py2exe, error occurs
ImportError: No module named sqlalchemy
Here is part of my setup.py
import os
import glob
from distutils.core import setup
import py2exe

includes = ['encodings', 'encodings.*', 'glob',
            'sqlite3', 'wx.lib.scrolledpanel',
            'wx.richtext', 'wx.lib.mixins.listctrl',
            'wx.lib.sized_controls', 'sqlalchemy']

excludes = ['pyreadline', 'difflib', 'doctest',
            'tarfile', 'pickletools', 'optparse',
            'pickle', 'cookielib', 'urllib',
            'Tkinter', 'email', 'tcl', 'Tkconstants' ]

py2exe_options = {
    'build': {'build_base': 'dist/'},
    'py2exe': {
        'compressed': 1,
        'dll_excludes': ['msvcp90.dll', 'w9xpopen.exe'],
        'optimize': 2,
        'includes': includes,
        'excludes': excludes,
        'dist_dir': 'dist',
        'ascii': False,
        }
    }

A: Try including sqlalchemy in packages too
py2exe_options = {
    "packages": ["sqlalchemy.databases.sqlite"]
}

obviously I'm guessing that you're interested in sqlite.

A: That usually works for me. Put the next line into your main script you tell py2exe to compile.
import sqlalchemy

Even though in general py2exe is rather greedy and includes much more than needed, sometimes it does just the opposite and skips needed packages despite the fact you list them in includes. Manually importing them usually works. Just put a comment next it to why you import packages you don't need in this module.

A: The problem here is that SQLAlchemy is installed in an egg on your system; you need it to be unzipped, or to teach py2exe to read eggs. For a detailed overview, see the py2exe wiki page ExeWithEggs.
That said, the easiest approach is to reinstall SQLAlchemy unzipped:
easy_install --always-unzip sqlalchemy

redpajama_set_name: RedPajamaStackExchange


text:
Q: Initial value problem, open rectangle I have no idea how to come up with this.
Give an example of an initial value problem for which the open rectangle

$R = [ (x,y) : 0 < x < 4, -1<y<2]$

represents the largest region in the xy-plane where the hypotheses of Existence and Uniqueness Theorem are satisfied.

A: For a general first order ODE $F(x,y) = y'$ with initial value $y(x_0)= y_0$ to be guaranteed existence or uniqueness on a rectangular region $R$, it must be continuous on that region, and for uniqueness to hold, its derivative with respect to $y$ must also be continuous.  Of course the point $(x_0, y_0)$ also needs to be contained in $R$.
To solve your problem, you must then do the following:
specify an appropriate initial value in your given $R$.  Define $F(x,y)$ such that $F(x,y)$ is continuous and has continuous derivative with respect to $y$ in the region $R$, but such that $F(x,y)$ hits 'walls' at the boundaries of $R$ where continuity fails.
Big hint:

think about the function $\frac{1}{y-a}$, which is, among other things, continuous everywhere except at $y=a$.


text:
Q: Using react-query in external package leads to "No QueryClient set" error even though QueryClientProvider is used in index.js I try to use hooks from an self developed package that uses useQuery within a create-react-app application.
This is my scenario: I am developing two npm projects: 'Core' and 'Demo'.
Core contains functions, hooks and components that I'd like to use in other applications (like Demo which is a CRA). Some hooks contain useQuery (react-query). Unfortunately, when using this hooks in other applications like Demo, I always get the error message "No QueryClient set, use QueryClientProvider to set one" even though I set a QueryClientProvider.
Is there any configuration I have to set within Core to make the desired behaviour work (e.g. that the used hook is placed within the application context)? Do I have to build the package as a specific module? Or is it possible to pass the application's QueryClient to the custom hooks of Core?
Here's some code to show my attempt:
Core/hooks/useHookWithUseQuery.js
export function useHookWithUseQuery() {
  const queryClient = useQueryClient();
  const { data } = useQuery(
    "QUERY_KEY",
    getDataFn
  );

  const invalidateData = () => {
    queryClient.invalidateQueries("QUERY_KEY");
  };

  return { data, invalidateData };
}

Demo/index.js:
ReactDOM.render(
  <React.StrictMode>
    <QueryClientProvider client={queryClient} contextSharing={false}>
      <App />
    </QueryClientProvider>
  </React.StrictMode>,
  document.getElementById("root")
);

Demo/App.js
import { useHookWithUseQuery } from "core/dist/hooks"; // also tried core/src/hooks
...

function App() {
  const { data } = useHookWithUseQuery();

  const { someFetchedText } = data;
  return (
    <div>{ someFetchedText }</div>
  );
}

And here is how I install Core into Demo

*

*in Core (build + publish locally on Verdaccio)

*

*

*rm -rf dist && NODE_ENV=production babel src --out-dir dist --copy-files

*

*

*npm publish --registry http://localhost:4873/

*in Demo

*

*

*NPM_CONFIG_REGISTRY=http://localhost:4873 npm i core

A: If anyone is still interested, I had the same issue described above.
The problem for me was that I was installing my 'Core' package from a local folder. As a consequence react-query was not correctly deduplicated.
Installing it directly from git (or from the npm registry) allowed npm to correctly dedupe it and fixed the issue for me.

A: I had the same problem and deduplicating your react-query dependency in your yarn lock or NPM package lock is the solution:
For yarn.lock you can run
npx yarn-deduplicate --strategy fewer

Or for package-lock.json:
npm dedupe

This will solve your issue like solved mine.


text:
Q: Размер типа boolean Для всех примитивных типов данных, кроме типа boolean, в Java однозначно определен размер.
Размер типа boolean, насколько я понимаю, зависит от реализации конкретной виртуальной машины.
Вопрос: почему для типа boolean однозначно не определили размер?

A: Да, вы действительно правы. Спецификация JVM - не определяет размер типа boolean:

Although the Java Virtual Machine defines a boolean type, it only provides very limited support for it. There are no Java Virtual Machine instructions solely dedicated to operations on boolean values. Instead, expressions in the Java programming language that operate on boolean values are compiled to use values of the Java Virtual Machine int data type.

В первой версии спецификации JVM созданной святым James Gosling - boolean вообще отсутствовал как тип:

Although Java defines a boolean type, the Java Virtual Machine does not have
  instructions dedicated to operations on boolean values. Instead, a Java expression
  that operates on boolean values is compiled to use the int data type to represent
  boolean variables.

Я полагаю, что это сделано как баланс между скоростью и удобством. То есть одиночный тип boolean рассматривается как int, а массив, рассматривается как массив byte, а кое где и вовсе как бит

A: Как Вы сказали, все зависит от определенной реализации JVM и почему — не знаю и ответа, когда искал, тоже не нашел. Однако, вот информация, которая все же может помочь (брал тут):
В стандартной реализации Sun JVM и Oracle HotSpot JVM тип boolean занимает 4 байта (32 бита), как и тип int. Однако, в определенных версия JVM имеются реализации, где в массиве boolean каждое значение занимает по 1-му биту.

Также есть библиотеки для уменьшения размера boolean: BitSet и OpenBitSet (от Apache). Дословная цитата с Хабра:

Спасением в таких случаях будет класс BitSet, который ведёт себя подобно массиву boolean, но упаковывает данные так, что для одного бита выделяется всего один бит памяти (с небольшими издержками для всего массива). BitSet хранит внутри себя массив типа long, а при запросе или установке значения определенного бита — высчитывает индекс нужного long и пользуясь побитовыми операциями и операциями сдвига производит вычисления над единственным битом.
  Существует еще более интересная реализация BitSet, OpenBitSet — Apache реализация, которая используется для Lucene. Она гораздо быстрее, но упускает некоторые проверки, проводимые в оригинальном BitSet. Что использовать — решать Вам.

A: А зачем? Языку не должно быть до этого дела.
Если поведение однозначно определено, всё остальное вторично.
Тип boolean прекрасно определяется множеством своих допустимых значений. Математически оно ограничивает минимальный размер значения одним битом.
Но использовать именно один бит (и ни битом более) эффективно далеко не всегда, поскольку на популярных архитектурах нельзя адресовать отдельные биты. А потому значения отдельных boolean'ов нельзя быстро сохранить в отдельные биты оперативной памяти — необходимо использовать комбинацию побитовых операций, что почти наверняка будет медленнее, чем запись целого отдельного регистра в оперативную память (размер которого может быть различным на разных платформах!).
Но при этом, к примеру, я вполне себе представляю, как на x86 компилятор может использовать в нативном коде в качестве какого-нибудь конкретного boolean-значения один бит регистра флагов, при условии, что это значение никогда не попадает в оперативную память (отдельно от других). Поэтому любые ограничения на размер более одного бита тоже могут потенциально мешать.
И эта свобода представления позволяет авторам виртуальных машин Java использовать любые реализации, которые они считают наиболее эффективными в каждом конкретном контексте. Как видно из примеров выше, любые ограничения будут только мешать.


text:
Q: Covariance and contravariance, compile time errors I've been reading up on covariance and contravariance - Wikipedia talks about the following:

Suppose you have a class representing a person. A person can see the doctor, so this class might have a method virtual void Person::see(Doctor d). Now suppose you want to make a subclass of the Person class, Child. That is, a Child is a Person. One might then like to make a subclass of Doctor, Pediatrician. If children only visit pediatricians, we would like to enforce that in the type system. However, a naive implementation fails: because a Child is a Person, Child::see(d) must take any Doctor, not just a Pediatrician.

Here is a "naive implementation":
public interface IDoctor
{
}

public interface IPerson
{
    void VisitDoctor(IDoctor doctor);
}

public class Adult : IPerson
{
    public void VisitDoctor(IDoctor doctor)
    {
        Console.WriteLine("Adult saw doctor of type: {0}", doctor.GetType().Name);
    }
}

public class Child : IPerson
{
    public void VisitDoctor(IDoctor doctor)
    {
        Console.WriteLine("Child saw doctor of type: {0}", doctor.GetType().Name);
    }
}

public class AdultDoctor : IDoctor
{
}

public class ChildDoctor : IDoctor
{
}

These tests:
[Test]
public void AdultSeesDoctor()
{
    var adult = new Adult();
    adult.VisitDoctor(new AdultDoctor());
    adult.VisitDoctor(new ChildDoctor());  // <-- Would like this to fail
}

[Test]
public void ChildSeesDoctor()
{
    var child = new Child();
    child.VisitDoctor(new AdultDoctor());  // <-- Would like this to fail
    child.VisitDoctor(new ChildDoctor());
}

Output:

Adult saw doctor of type: AdultDoctor
Adult saw doctor of type: ChildDoctor
Child saw doctor of type: AdultDoctor
Child saw doctor of type: ChildDoctor

Now, I can implement the following, which throws a runtime error if an adult tries to visit a child doctor, or if a child tries to visit an adult doctor (throws a System.InvalidCastException):
public interface IVisitDoctors<T> where T : IDoctor
{
    void VisitDoctor(T doctor);
}

public class Child : IPerson
{
    private readonly ChildDoctorVisitor _cdv = new ChildDoctorVisitor();

    public void VisitDoctor(IDoctor doctor)
    {
        _cdv.VisitDoctor((ChildDoctor)doctor);
    }
}

public class Adult : IPerson
{
    private readonly AdultDoctorVisitor _adv = new AdultDoctorVisitor();

    public void VisitDoctor(IDoctor doctor)
    {
        _adv.VisitDoctor((AdultDoctor)doctor);
    }
}

Could you force classes of Adult to only visit doctors of type AdultDoctor, such that a compile-time error is thrown if a doctor of type ChildDoctor is visited (and vice versa for classes of Child)?

A: You don't need co or contra-variance for this:
public interface IDoctor<TPatient> where T : IPerson<TPatient>
{
}

public interface IPerson<T> where T : IPerson<T>
{
    void VisitDoctor(IDoctor<T> doctor);
}

public class Adult : IPerson<Adult>
{
    void VisitDoctor(IDoctor<Adult> doctor) {  }
}

public class AdultDoctor : IDoctor<Adult>
{
}

Now the following will fail to compile:
Adult a = new Adult();
a.VisitDoctor(new ChildDoctor());

while this will:
Adult a = new Adult();
a.VisitDoctor(new AdultDoctor());

This is called the curiously recurring template pattern. In this case, it is used to get the concrete implementor type (Adult) through the interface type IPerson. This means that the type of doctor an IPerson can visit can be restricted to the same type as the implementor.
You can also see it in the Java Enum class. The compareTo method allows you to compare enums, but the recurring template is needed to ensure that you can only compare enums of the same type.
It is quite ugly however, so you may want to consider changing your design to something like:
public interface IDoctor<TPatient>
{
    void SeePatient(TPatient patient);
}

public interface IAppointments<T>
{
    void MakeAppointment(T patient, IDoctor<T> doctor);
}

So you can remove the need for IPerson to have a type parameter.

A: I understand what you would like to achieve. But if you will keep in play this interface:
public interface IPerson
{
    void VisitDoctor(IDoctor doctor);
}

then any further restriction on implementers will break the Liskov principle. And that will most likely later cause some problems to your code.
What you can do is place that restriction into your interface declaration
public interface IPerson<TDoctor>
    where TDoctor : class, IDoctor...
{
    void VisitDoctor(TDoctor doctor);
}


text:
Q: Count of Equal Adjacent Elements in 2D Array I am working on a programming assignment and stuck on one part.  The directions ask to create a count for equal adjacent elements within a 2d array.
I have tried setting up 2 for loops followed by if statements with multiple conditions using "or" to test if the elements are equal. The issue is the if statement can only be used for elements bounded within the array. The function i tried is shown below
int count(int** t, int r, int c) {

int i, j, count = 0;

for (i = 0; i < r; i++) {

for (j = 0; j < c; j++)

if (t[i][j] == t[i - 1][j - 1] || t[i][j] == t[i - 1][j] || t[i][j] ==
t[i - 1][j + 1] || t[i][j] == t[i][j - 1] || t[i][j] == t[i][j + 1] ||
t[i][j] == t[i + 1][j - 1] || t[i][j] == t[i + 1][j] || t[i][j] == t[i +
1][j + 1])

count++; }
return count;

}
I am new to programming, please help!

A: Your provided code have few issues i will explain them to you one by one ,
Passing arrays to functions
To pass multidimensional arrays to functions , I will show you 2 ways to do that
1)  Passing multidimensional arrays as single dimensional arrays
This works because we know how array is represented in the memory , and our this knowledge of representation is what makes pointers in C/C++ such a powerful tool .
Read this answer to get a better picture of representation of array in memory.
Arrays are represented linearly and contiguously in memory , thus if define array as arr[5][5] , we are telling compilers that we need a memory block having sufficient space for storing 5*5 = 25 int data types . And it's also worth to know that arrays are represented in row major form , read this to learn more about row major form.
 .
Elements(here ints) are filled in the way as described by the zig-zag line in the picture .
Thus in our example array int arr[5][5],
2nd element of the 1st row(arr[0][1]) can be accessed by *(arr+0*5+1) , as arr gives the base address of the array , similarly , 4th element of 5th row (arr[4][3]) can be accessed by *(arr+4*5+3) , here we are multiplying row index by 5 because each row have 5 elements(that is number of columns) , with this knowledge in mind we can write code to access array elements of a matrix in the following way
void display(int *arr,int r,int c)
{
    for(unsigned i=0;i<r;++i)
    {
        for(unsigned j=0;j<c;++j)
        {
            cout<<*(arr+i*c+j)<<ends;
        }
        cout<<endl;
    }
}
const unsigned ROW=3,COL=3;
int main()
{
    int arr[ROW][COL]={1,2,3,
                       4,5,6,
                       7,8,9
                    };
    display((int *)arr,ROW,COL);
}

While calling the function , casting arr to (int *) is necessary because originally arr type is int (*)[3] , that is pointer to an int array of 3 elements .
2) Passing multidimensional array as pointer to an array in the function argument .
const unsigned ROW=3,COL=3;
void display(int (*arr)[COL],int r,int c)
{
    for(unsigned i=0;i<r;++i)
    {
        for(unsigned j=0;j<c;++j)
        {
            cout<<arr[i][j]<<ends;
        }
        cout<<endl;
    }
}
int main()
{
    int arr[ROW][COL]={1,2,3,
                       4,5,6,
                       7,8,9
                    };
    display(arr,ROW,COL);
}

In this , there is no need to cast the arr
Index out of bounds
In your code you are not taking care of array index going out of bounds , if your array is int arr[5][5] and you try to access arr[-1][5] or arr[5][3] , the result will be undefined , that is anything can happen from your code just crashing to your system going up in flames(just a metaphor) .
Keeping these things in mind , a working code satisfying your needs is
int count(int *t, int r, int c)
{

    int i, j, result = 0;

    for (i = 0; i < r; i++)
    {

        for (j = 0; j < c; j++)
        {
            if(i!=r-1)
            {
                if(*(t+i*c+j)==*(t+(i+1)*c+j))
                    ++result;
                if(j!=r-1)
                {
                    if(*(t+i*c+j)==*(t+(i+1)*c+j+1))
                        ++result;
                }
                if(j!=0)
                {
                    if(*(t+i*c+j)==*(t+(i+1)*c+j-1))
                        ++result;
                }
            }
            if(j!=c-1)
            {
                if(*(t+i*c+j)==*(t+i*c+j+1))
                    ++result;
            }
        }
    }
    return result;
}
const unsigned ROW=3,COL=3;
int main()
{

    int arr[ROW][COL]={1,1,2,
                       1,2,3,
                       4,5,2
                    };
    cout<<count((int *)(arr),ROW,COL)<<endl;

}


text:
Q: aws instance is not accessing through public IP i installed nginx server in ubuntu instance. then i copy my data into /var/www/html folder. then i access site through public ip. its working fine. Then i create A record with public ip address. so i can access with domain name.
After few hours i am not accessing the site.
I checked in server nginx service is running. but i can't access the website.
ports are open in security group for that instances.
curl localhost
curl privateip
curl publicdns are working. but curl  with public ip is not working. could you please help me this issue.

A: You'll probably want to create an Elastic IP, associate with the instance, and associate your DNS record with that.  IP addresses for instances are released when the instance is stopped, unless you have an elastic ip associated, which will then persist across stops/starts.


text:
Q: json serialisation formatting I am trying to serialise a collection of objects using json.net
The object looks like this:
public class TaxBand
{
    public TaxBand(string county, decimal taxPercentage)
    {
        County = county;
        Tax = taxPercentage;
    }

    public string County { get; private set; }
    public decimal Tax { get; private set; }
}

and they are contained in a structure like this:
var data = new Dictionary<string, List<TaxBand>>();
data = PopulateDataset();
string json = JsonConvert.SerializeObject(data, Formatting.Indented);

This produces json that looks like this:
{
  "North": [
    {
      "County": "Merseyside",
      "Tax": 5.0
    },
    {
      "County": "Greater Manchester",
      "Tax": 6.0
    }
  ],
  "South": [
    {
      "County": "Greater London",
      "Tax": 5.5
    },
    {
      "County": "Surry",
      "Tax": 6.2
    }
  ]
}

is it possible to produce json that looks like this:
{
  "North":
    {
      "Merseyside": 5.0,
      "Greater Manchester" : 6.0
    },
  "South":
    {
      "Greater London": 5.5,
      "Surry": 6.2
    }
}

Am happy to consider changing the shape of any objects, or indeed use a different serialisation library

A: With the help of some Linq
var data = new Dictionary<string, List<TaxBand>>();
data = PopulateDataset();

var data2 = data.ToDictionary(kv => kv.Key,
                              kv => kv.Value.ToDictionary(t=>t.County,t=>t.Tax) );

var s = JsonConvert.SerializeObject(data2,Newtonsoft.Json.Formatting.Indented);

OUTPUT:
{
  "North": {
    "Merseyside": 5.0,
    "Greater Manchester": 6.0
  },
  "South": {
    "Greater London": 5.5,
    "Surry": 6.2
  }
}

A: This:
"Merseyside": 5.0

looks to me similar to a single entry in a Dictionary and you may get some mileage from experimenting in that fashion.
However the example JSON looks entirely reasonable. Given that you have clients consuming this I would likely not worry about the serialisation, and would certainly be wary of compromising your object model to reflect a desired serialisation (especially given that it looks legitimate and easy to parse). Note that if you change the serialsiation your clients have to be able to parse this successfully.
If you were to modify the JSON output, rather than compromise your object model, I would isolate that change - copy your TaxBand object into a TaxBandJson object or similar.


text:
Q: How can I build a charger for this RC helicopter? I have this remote controlled helicopter: http://www.clasohlson.com/se/Radiostyrd-helikopter/31-8071
Currently it is charged by connecting the remote control. However, since the RC runs on batteries, I am thinking it would be nice to charge the helicopter with a battery charger or similar.
I am a complete beginner, and am now looking for how to understand how I can solve this problem. How do I find out what I need? Can I use for example an iPhone charger or anything simliar that many homes has?

A: You need a charger which is matched to the battery in your helicopter. Typically these use a single Lithium Polymer cell with a capacity of ~100mAh. To charge this properly the charger must limit current to 0.1A and voltage to 4.2V maximum.
If a Lipo battery is charged incorrectly it may explode and burn up anything around it. This is not just theoretical. I have personally seen the results of some Lipo fires, and they were not pretty.
An iPhone 'charger' is just a 5V power supply that simulates a USB port - the actual charger circuit is built into the phone. Some devices use an external charger, but this will be matched to the battery in the device. Unless you know exactly what you are doing, you should only use a charger with the device it was designed for (and similarly, never use a charger that was not designed for that device!).
You could use an iPhone 'charger' or other USB power supply to run your own charger, eg. this one from Adafruit. Then you just need to attach the correct plug to suit your heli (perhaps removed from the transmitter).


text:
Q: Android Application onCreate is not called before Activity onCreate On Google Play I receive a NullPointerException when trying to access a static Application instance. It appears on different Android OS versions: Android 9, 8, and 6.
From code it seems that Application.onCreate() hasn't been called or is called after Activity.onCreate().
I saw similar questions but without any useful response:
Application onCreate called(not called) after Activity onCreate
Android Activity::onCreate called before Application.onCreate
As a side solution, I'm going to create a separate singleton class depending on Context and get it with the Context. But, I'm not sure how it will work with Dagger.
My questions are:

*

*Is it an Android bug?

*Am I doing something wrong?

*How have other developers solved it?

public class App extends androidx.multidex.MultiDexApplication implements Application.ActivityLifecycleCallbacks, ComponentCallbacks2 {
    private static App instance;

    public static App getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;

        // init singletone
    }

    private Singletone singletone;

    public Singletone getSingletone() {}
}

public class MainActivity extends androidx.appcompat.app.AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // On Google Play it produces NullPointerException

        Singletone singletone = App.getInstance().getSingletone();
    }
}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.package.name">
    <application
        android:name=".app.App"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme.NoActionBar"
        android:largeHeap="true"
        >

        <activity
            android:name=".activities.MainActivity"
            android:screenOrientation="portrait"
            android:launchMode="singleTask"
            android:windowSoftInputMode="adjustPan"
            android:theme="@style/AppTheme.NoActionBar.Launcher"
            >
        </activity>
    </application>
</manifest>

A: You have to move instance = this; from onCreate() to App's constructor.


text:
Q: Logstash XML parsing merging all the fields content under one field? Logstash 2.4.1
I want to parse a XML file :
   <?xml version="1.0" encoding="ISO-8859-1"?>
    <catalog>
      <cd country="USA">
        <title>Empire Burlesque</title>
        <artist>Bob Dylan</artist>
        <price>10.90</price>
      </cd>
      <cd country="UK">
        <title>Hide your heart</title>
        <artist>Bonnie Tyler</artist>
        <price>10.0</price>
      </cd>
      <cd country="USA">
        <title>Greatest Hits</title>
        <artist>Dolly Parton</artist>
        <price>9.90</price>
      </cd>
</catalog>

I want output in this format :
  "country" => "USA" ,
     "title" => [
    [0] "Empire Burlesque"
],
    "artist" => [
    [0] "Bob Dylan"
],
     "price" => [
    [0] "10.90"
],
      "country" => "UK" ,
     "title" => [
    [0] "Hide your heart"
],
    "artist" => [
    [0] "Bonnie Tyler"
],
     "price" => [
    [0] "10.0"
],
   so on .....

But what i got is like this :
 "country" => [
    [0] "USA",
    [1] "UK",
    [2] "USA"
],
     "title" => [
    [0] "Empire Burlesque",
    [1] "Hide your heart",
    [2] "Greatest Hits"
],
    "artist" => [
    [0] "Bob Dylan",
    [1] "Bonnie Tyler",
    [2] "Dolly Parton"
],
     "price" => [
    [0] "10.90",
    [1] "10.0",
    [2] "9.90"
]

My logstash configuration is like this :
input {
      file {
            path => "F:\logstash-2.4.0\logstash-2.4.0\bin\samplexml.xml"
            start_position => "beginning"
            sincedb_path => "NUL"
        codec => multiline {
               pattern => "^<\?cd.*\>"
               negate => true
               what => "previous"
        }
  }

}
filter {
    xml {
   source => "message"
   xpath =>
   [
     "/catalog/cd/@country", "country",
     "/catalog/cd/title/text()", "title",
     "/catalog/cd/artist/text()", "artist",
     "/catalog/cd/price/text()", "price"
   ]
   store_xml => false
   target => "doc"
        }
    }
output {
 stdout { codec => rubydebug }
  }

How can i achieve the my desired output from the above xml file?
Thanks

A: This is not what you asked for, but if you can consider Foopipes as an alternative to Logstash create a foopipes.yml in current directory like this:
pipelines:
  -
    when:
      - queue: started
    from:
      - readfile: ./input.xml
    do:
      - parsexml
      - select: $.catalog.cd[*]    # This is a Json path expression
      - map: ~
        country: "#{@country}"     # These are data binding expressions
        title: "#{title}"
        artist: "#{artist}"
        price: "#{price}"
    to:
      - log
    finally:
      - exit

Start with:
docker run -v %CD%:/project aretera/foopipes

(%CD% will get replaced with an absolute path to current directory on Windows)


text:
Q: Setting working directory I try to set the working directory to a specific sub-folder x1 which is in folder y. R gives me this output:
setwd("~/Desktop/Statistics/Assignments/Assignment 4")

so i know that the working directory has been set to Assignment 4.
However, when I run the command getwd(), the result shows that the working directory is "Assignment 5".
getwd()
[1] "/Users/anirudhmaru/Desktop/Statistics/Assignments/Assignment 5"

Tried this multiple times but no success. Please help.

A: In the window down next to the right corner, next to the console, search the File tab and then your directory there, then click on More -> Set as working directory
Tip: avoid spaces on my working directories, for instance, use: Assignment4 instead of Assignment 4.


text:
Q: Slicing a 3D tensor with a 1D tensor-index in PyTorch How can I slice a 3D tensor using a 1D tensor? For instance, consider the following 2 tensors: t of size [Batch, Sequence, Dim]; and idx of size [Batch]. The values of idx are restricted to be integers between 0 and Sequence-1.
I need tensor idx to select the corresponding slices in the second dimension of tensor t. For example:
t = torch.arange(24).view(2,3,4)
>>> tensor([[[ 0,  1,  2,  3],
          [ 4,  5,  6,  7],
          [ 8,  9, 10, 11]],

         [[12, 13, 14, 15],
          [16, 17, 18, 19],
          [20, 21, 22, 23]]])

idx = torch.tensor([0,2])
>>> tensor([0, 2])

Then the desired output is: tensor([[ 0,  1,  2,  3], [20, 21, 22, 23]]).
The following code solves the problem, however it's inefficient, as it involves one_hot, multiplication and sum operations.
one_hot_idx = nn.functional.one_hot(idx.long(), num_classes=t.shape[1]).unsqueeze(-1)
(t*one_hot_idx).sum(1)

A: You can do it like this:
import torch
t = torch.arange(24).view(2, 3, 4)
idx = torch.tensor([0, 2])
print(t[range(len(idx)), idx])

Output:
tensor([[ 0,  1,  2,  3],
        [20, 21, 22, 23]])


text:
Q: vlookup behavior in pandas merge I would like to have the vlookup behavior merging two dataframes.
suppose I have the below tables in excel:

using vlookup for adding "staus" column to Table2 would result like below:

which for code "124" will return the first corresponding status "a". and that is exactly what I need.
What I try to code in python to have my desired output is like below:
Table1 = pd.DataFrame({"section" : ["1","2","1","2","2","2"], "code" : [124,254,156,147,124,156], "status" : ["a","b","c", "a", "b", "c"]})

Table2 = pd.DataFrame({"code": [124,254,156,147]})

result1 = Table1.iloc[:,1:].merge(Table2, on = 'code')

result2 = Table1.iloc[:,1:].merge(Table2, on = 'code', how = 'right')

I can manage to remove the duplicates in the results, however still I have 2 rows of the code "124" with status "a" and "b".
I have also searched through the posts like this but that wouldn't be help.
any recommendation regarding the solution would be appreciated.

A: Table1 = pd.DataFrame({"section" : ["1","2","1","2","2","2"], "code" : [124,254,156,147,124,156], "status" : ["a","b","c", "a", "b", "c"]})
df1=Table1.drop_duplicates("code") #create new df without duplicates code
Table2 = pd.DataFrame({"code": [124,254,156,147]})

result2 = df1.iloc[:,1:].merge(Table2, on = 'code', how = 'right')


text:
Q: What is causing my nav ul in my header to indent when displaying inline? I've tried everything! What is causing this indentation? This is mainly a Team Treehouse lesson project, which I copied and pasted into Atom to work on. The indentation disappears just fine when previewed from the Treehouse workspace...
https://i.stack.imgur.com/Jmd9Q.png
Anyways, obviously I'm going to run into this problem at some point and I just want to understand what's going on

.name {
  font-size: 1.25em;
}

.name,
.main-nav li {
  text-align: center;
  background-color: #fff;
  padding: 6px;
  margin-top: 6px;
  margin-bottom: 6px;
}

.main-nav a {
  font-size: .95em;
  color: #3acec2;
  text-transform: uppercase;
}

.main-nav a:hover {
  color: #093a58;
}

/* ---- Layout Containers ---- */

.container {
  padding-left: 1em;
  padding-right: 1em;
}

.main-header {
  padding-top: 1.5em;
  padding-bottom: 1.5em;
  background: #3acec2;
  margin-bottom: 30px;
}

/*=================================
          Media Queries
        ==================================== */

@media (min-width: 769px) {
  .wrap {
    min-height: calc(100vh - 89px);
  }
  .container {
    width: 80%;
    max-width: 1150px;
    margin: 0 auto;
  }
  .name,
  .main-nav li {
    display: inline;
  }
<!DOCTYPE html>

  <title>Best City Guide</title>
  <link href='https://fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="normalize.css">
  <link rel="stylesheet" href="superlordstylesheet.css">

Best City Guide

ice cream

donuts

tea

coffee

Welcome!

Everything in this city is worth waiting in line for.

Cupcake ipsum dolor sit. Amet chocolate cake gummies jelly beans candy bonbon brownie candy. Gingerbread powder muffin. Icing cotton candy. Croissant icing pie ice cream brownie I love cheesecake cookie. Pastry chocolate pastry jelly croissant.

Cake sesame snaps sweet tart candy canes tiramisu I love oat cake chocolate bar. Jelly beans pastry brownie sugar plum pastry bear claw tiramisu tootsie roll. Tootsie roll wafer I love chocolate donuts.

Great food

Croissant macaroon pie brownie. /p>

 Fruitcake jelly-o croissant soufflé.

    ©2015 Residents of The Best City Ever.

A: ULs by default have a padding on the left. You can adjust this by giving it a padding of 0:

.name {
  font-size: 1.25em;
}

.main-nav {
  padding-left: 0px;
}

.name,
.main-nav li {
  text-align: center;
  background-color: #fff;
  padding: 6px;
  margin-top: 6px;
  margin-bottom: 6px;
}

.main-nav a {
  font-size: .95em;
  color: #3acec2;
  text-transform: uppercase;
}

.main-nav a:hover {
  color: #093a58;
}

/* ---- Layout Containers ---- */

.container {
  padding-left: 1em;
  padding-right: 1em;
}

.main-header {
  padding-top: 1.5em;
  padding-bottom: 1.5em;
  background: #3acec2;
  margin-bottom: 30px;
}

/*=================================
      Media Queries
    ==================================== */

@media (min-width: 769px) {
  .wrap {
    min-height: calc(100vh - 89px);
  }
  .container {
    width: 80%;
    max-width: 1150px;
    margin: 0 auto;
  }
  .name,
  .main-nav li {
    display: inline;
  }
<!DOCTYPE html>

  <title>Best City Guide</title>
  <link href='https://fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="normalize.css">
  <link rel="stylesheet" href="superlordstylesheet.css">

Best City Guide

ice cream

donuts

tea

coffee

Welcome!

Everything in this city is worth waiting in line for.

Cupcake ipsum dolor sit. Amet chocolate cake gummies jelly beans candy bonbon brownie candy. Gingerbread powder muffin. Icing cotton candy. Croissant icing pie ice cream brownie I love cheesecake cookie. Pastry chocolate pastry jelly croissant.

Cake sesame snaps sweet tart candy canes tiramisu I love oat cake chocolate bar. Jelly beans pastry brownie sugar plum pastry bear claw tiramisu tootsie roll. Tootsie roll wafer I love chocolate donuts.

Great food

Croissant macaroon pie brownie. /p>

 Fruitcake jelly-o croissant soufflé.

    ©2015 Residents of The Best City Ever.


text:
Q: Storing user input (STRING) into Array JAVA Alright so for my computer science course I have to make two separate arrays, fill them with user input from two separate methods. I'm stuck on actually making the input from my code be stored in my two arrays. I don't even know where to start with it. I've tried searching for examples, but I haven't found anything. I am also rather new to coding.
  import java.util.Scanner;
 /**
  * @author SH
  *
  */
  public class SearchSort {

Scanner console = new Scanner(System.in);

public void inputFavoriteMovies(){
    System.out.println("Enter 6 of your favorite movies");
    int x = 0;
    while(x<6){
    String movies = console.nextLine();
    x++;
    }
}
public void inputFavoriteMusic(){
    System.out.println("Enter 5 of your Favorite Songs");
    int y = 0;
    while(y<5){
        String music = console.nextLine();
        y++;
    }
}

public static void main(String[] args) {
    new SearchSort().inputFavoriteMovies();
    new SearchSort().inputFavoriteMusic();

    String[] myFavoriteMovies = new String[6];

    String[] myFavoriteMsuic = new String[5];
 }

}

A: Take a look at the changes I made below to your code and my comments related to each. If you wanted to make this quite a bit more flexible, use an ArrayList inside the methods and let the user enter as many as the want and use the .add() method of ArrayList to add each entry the user types. You'd have to come up with some sort of "sentinel" value that the user types when they are done (an empty string would work; you'd have to then check the inputValue.Length() of the string they entered and compare to 0 and exit a while loop once that length == 0). Then, you could use toArray() of ArrayList and convert it to an array that you then return to the calling code. That would give you a very dynamic arrangement and quite a bit more flexibility. You may not have learned about ArrayList yet but in all likelihood, you will fairly soon.
Hope this helps and good luck!
   import java.util.Scanner;
     /**
      * @author SH
      *
      */
      public class SearchSort {

    /*

    Since your code is essentially linear in nature (and not truly object-oriented), it's probably best to make it all static. You'll note I added the static modifier to the 2 methods you created along with the console declaration.

    */

    static Scanner console = new Scanner(System.in);

    public static void inputFavoriteMovies(String[] storage){
/*
    For both of these methods, it makes sense to pass an array into them and then use the passed array for storage. Since arrays are essentially pass by reference, when you make changes to the array in this method, the array that was passed in will be modified when you return from this code.

Using the length of the array for both the prompt and the loop control helps to reduce the "index out of bounds" errors that may otherwise occur. It would actually be a little better to code this as a for loop:

for (int x=0; x < storage.length; x++ ) {
<insert all the code>
} // end for

*/
        System.out.println("Enter " + storage.length + " of your favorite movies");
        int x = 0;
        while(x < storage.length){
        storage[x] = console.nextLine();
        x++;
        }
    }

/*
comments here are essentially identical to those above.
*/

    public static void inputFavoriteMusic(String[] storage){
        System.out.println("Enter " + storage.length + " of your Favorite Songs");
        int y = 0;
        while(y < storage.length){
            storage[y] = console.nextLine();
            y++;
        }
    }

    public static void main(String[] args) {

/*
Here in main, you basically declare an array as large as you want. Since you are now using methods that look at the length of the array, the code is slightly more abstract and gives you a tad more flexibility in design since it's not hard-coded
*/

        String[] myFavoriteMovies = new String[6];

// After declaring the array, pass it to the input method you created earlier. When that
// method returns, the array will contain the values the user entered.

        inputFavoriteMovies(myFavoriteMovies);

// same as above - declare an array, then pass it to your input method.
        String[] myFavoriteMusic = new String[5];
        inputFavoriteMusic(myFavoriteMusic);

/* now, if you want to print the results, you'd do a pair of for loops that iterate
   over each array and output the results. For a bit more elegance, you could use
   this form of the for loop:

   for (String userInput : myFavoriteMovies) {
System.out.println(userInput);
}

for (String userInput : myFavoriteMusic) {
System.out.println(userInput)
    }

  }
}

A: You'll need to create the arrays before running the input methods, instead of afterwards.  Then, as each string is input, put the string in the appropriate array.


text:
Q: Uboot custom application images load from flash I have 2 images stored in predefined addresses in flash that are loaded based on some criteria I can test for on bootup.
Can someone please suggest a method to programmatically launch either image using uboot's tools like bootm, etc? Or point to an example of this procedure.
Thanks in advance.

A: I assume whatever method you use to load the images takes an address, so just set that before running it.  bootcmd is the main entry point, boot is basically the same as run bootcmd.
setenv flashload 'fooload $imageflashaddr $loadaddr'
setenv setimageflashaddr 'if something; then setenv imageflashaddr xxx ; else setenv imageflashaddr yyy; fi'
setenv bootcmd 'run setimageflashaddr && run flashload && bootm $loadaddr'

u-boot is enormously flexible; there are many ways to do this.  This uses environment variables.  You can also do this from C code or from a script file you load at run time.

If you want to do it in C code, you can edit your board's C file (usually in board/vendor_name/board_name.c.  You can define a board_late_init() (there are other hooks, but this one is usually a good place to start).  You can use env_get() and env_set() to set your address so your bootcmd loads from different places.


text:
Q: Trying to put some javascript into an ASP.NET page I have a javascript link which I need to appear in a table on my aspx page.  Hard coding it as a literal isn't working right.  Consultation with the script's provider suggests I shouldn't hard-code it, but should embed it using ScriptManager.  How do I get the link as javascript into the appropriate place in my page (it goes in a table)?  I have this code to register the script:
string myScript = "http://forms.aweber.com/form/85/1556724385.js";

ClientScript.RegisterClientScriptBlock(this.GetType(), "MyScript", myScript);

I want this link to appear in this table cell:
<asp:TableRow ID="TableRow3" runat="server">
   <asp:TableCell ID="TableCell4" runat="server" HorizontalAlign="Center">
   </asp:TableCell>
</asp:TableRow>

Not clear on how to do this... insert into some control inside the cell, such as a Panel?  And I am unclear on how to "emit" the script.
Edited to add:
After communicating with the vendor, it is clear that trying to do what I am trying to do in an ASP.NET page will not work -- at least with the current version of the product.  So I've accepted @cccason's answer, since it comes closest to what the answer would be if the situation were otherwise.

A: RegisterClientScriptBlock method just adds specified javascript block(literal) to the page. To include any internal or external javascript file you should to use RegisterClientScriptInclude method.

A: So, I would suggest just dropping it in there instead of using RegisterClientScriptBlock if you need it anywhere EXCEPT the start of the form tag.
The RegisterClientScriptBlock method places the JavaScript directly after the opening  element in the page.
So I would do something like this:
<asp:TableRow ID="TableRow3" runat="server">
   <asp:TableCell ID="TableCell4" runat="server" HorizontalAlign="Center">
       <script type="text/javascript" src="http://forms.aweber.com/form/85/1556724385.js"></script>
   </asp:TableCell>
</asp:TableRow>

So, whats happening in the script is that it writes some DOM elements out to your page.  Since you are using webforms, this all sits inside of a  tag.  The stuff they are writing to your page is another .  So you'll end up with a form in a form.  Then, when you submit the information, it is supposed to postback to http://www.aweber.com/scripts/addlead.pl.
You should check the request that is being sent and see what its trying to do.  You can use firefoxes firebug, fiddler or chrome's tools (f12).


text:
Q: computational complexity of an expression I am wondering what is the time complexity of the following expression:

where A  and Y  are n×n  sparse matrices with nnz  non-zeros, and x  and y  are n×1  vectors.
I found (A*A*A)*x would be more efficient if we compute it as A*(A*(A*x)). So is there some memorization techniques I can use to efficiently compute this expression?


text:
Q: How to make dense matrix as input to Tfidf transformer? Basically, how to make this code running with my data?
    # build term document matrix
    V = len(word2idx)
    N = len(sentences)  #sentences=sents
    print("V:", V, "N:", N)

    # create raw counts first
    A = np.zeros((V, N))

    j = 0
    for sentence in sentences:
        for i in sentence:
            A[i,j] += 1
        j += 1
    print("finished getting raw counts")

    transformer = TfidfTransformer()
    A = transformer.fit_transform(A.T).T

The problem is those values of V or N are consec. 200k+ and 30k. There are far too beyond my memory stack and @ the line np.zeros( the memory occurs. Can I avoid this loop and produce A matrix dense as a input to the Tfidf Straightforwardly?
I've read I must use PySpark. Should I really?


text:
Q: Mongodb $addFields does not outputs the data if null i am struggling with an annoying problem. I am using aggregation in a query and i need to join some collections and the output has to be an object. This is my code...
usersModel.aggregate([
    {
        $match: { _id: ObjectId(req.params.id) }
    },
    {
        $lookup: {
            from: "agents",
            as: "agent",
            let: { "idAgent": "$agent" }, //$agent can be null
            pipeline: [
                {
                    $match: {
                        $expr: {
                            $eq: ['$_id', "$$idAgent"]
                        },
                    }
                }
            ],
        }
    },
    { $unwind: { path: '$agent', preserveNullAndEmptyArrays: true } },
    {
        $addFields: {
            agent: "$agent", //If $agent is null, it does not output the field agent...
        }
    }

])

If in the last Stage, the field $agent is null, $addFields does not output the field.
There is any other approach to do it? i need just agent field as an object after lookup. Thanks

A: Add an $ifNull condition with $addFields
{
  "$addFields": {
    "agent": { "$ifNull": ["$agent", {}] }
  }
}


text:
Q: Only first test in class failed when running multiple classes I have a really strange problem when running multiple tests in intellij. My first test in class failed because apparently jwt was not valid, but then in the second test in the same class everything is working fine with the same jwt.
If I try to run every class separately everything works fine, also if I run mvn test from the terminal, all tests will pass.
This is my configuration for the test in intellij
I also tried to set Fork mode to class, then test passed, but every test run separately, so it takes a while, and also I can't use coverage in Fork mode.
edit:
This is my code for init and first test
    @BeforeAll
    void init() throws Exception {
        token = login(new LoginRequest("user", "123"));
    }

    private String login(LoginRequest loginRequest) throws Exception {
        ResultActions resultActions = mockMvc.perform(post("/api/auth/login")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(loginRequest)))
                .andExpect(status().isOk());
        return resultActions.andReturn().getResponse().getHeader(JwtUtilities.HEADER);
    }

    @Test
    @Order(1)
    void findAllTeamsByCreator_ok() throws Exception {
        mockMvc.perform(get(PATH)
                .contentType(MediaType.APPLICATION_JSON)
                .header(JwtUtilities.HEADER, token))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/hal+json"))
                .andExpect(jsonPath("$._embedded.teamDtoList").isNotEmpty());
    }

so, I'm not setting any state in my test, and if I create test like this
@Test
@Order(1)
void test() {}

and then everything else remains the same, my tests will work. It's like something is not loaded in first test.
And it's really strange to me why mvn test works fine, but in Intellij I have bug

A: This sounds like something is "state full" in your test cases, so something in the first test is initializing something that is needed in the remaining test cases.
As you are using JUnits, you might make sure all the initialization is done in one of the "Before"-type methods that the framework supports.
It would be helpful to see the code of your first test case to determine what has "state".


text:
Q: Javascript image upload (Non framework) I'd like to upload image(s) via JavaScript (Non framework). Does anyone have a basic example of how to this?
I get this error message:

Warning: Missing boundary in multipart/form-data POST data in Unknown on line 0 Array ( )

Here is what I'm working with so far.
<form action="" method="" enctype="" id="uploadImage">
<input type="file" name="image1" id="image1" value="" >
<input type="button" id="submit_button" data-data_enctype="multipart/form-data"     data-form_name="uploadImage" data-url="/gallery/images/upload/" data-change_div="getForm"  value="Upload" onclick="image(this.id, form.id)"/>
</form>

var xmlhttp;
if (window.XMLHttpRequest)
{
    xmlhttp = new XMLHttpRequest();
}
else
{
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

var datVar = document.getElementById(id);
var url = datVar.dataset.url;
var change_div = datVar.dataset.change_div;

xmlhttp.onreadystatechange = function()
{
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
    {
        document.getElementById(change_div).innerHTML = xmlhttp.responseText;
    }
}

xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "multipart/form-data");
xmlhttp.send('NULL');

A: You need to pass the data that you want to send to the xmlhttp.send() method. Currently you are passing it 'NULL' so it complains that the data is missing.
Something like
var data = document.getElementById('#uploadImage');
gets the form.
create a FormData object (FormData is only supported in modern browsers)
var formData = new FormData(data);
and then passing formData to the send method should do.


text:
Q: On drop not working Im trying to figure out how to make use of drag n drop, just added the draggable="true" on a element
test

but cant make in drop on parent div, cant tell if its calling a error or not.

A: have you tried inserting js to accept drop? here
ondragover="allowDrop(event);"

function allowDrop(x) { x.preventDefault(); }


text:
Q: UrlEncoding issue for string with ß character I have a parameter which I must pass as part of a url.  The parameter contains this character: ß
When I encode this string, I am expecting this: %DF
but instead i'm getting: %c3%9f
Here is a line of C# which I have been using to test
  string test = HttpUtility.UrlEncode("ß");

A: This is because the default implementation of UrlEncode is based on the UTF8 character encoding.  Actually this is entirely within your control.
For example, the following code:
string sample = new string((char)0x0DF, 1);
string test = HttpUtility.UrlEncode(sample);
Console.WriteLine("UTF8 Ecoded: {0}", test);
test = HttpUtility.UrlEncode(sample, Encoding.GetEncoding(1252));
Console.WriteLine("1252 Ecoded: {0}", test);

Outputs the following:
UTF8 Ecoded: %c3%9f
1252 Ecoded: %df

Of course the danger with using another encoding on a URI is that some characters can not be represented at all...
for example, this code:
string sample = new string((char) 312, 1);
Encoding encoding = Encoding.GetEncoding(1252);
string test = HttpUtility.UrlEncode(sample);
Console.WriteLine("UTF8 Ecoded: {0}, round-trip = {1}", test, sample == HttpUtility.UrlDecode(test));
test = HttpUtility.UrlEncode(sample, encoding);
Console.WriteLine("1252 Ecoded: {0}, round-trip = {1}", test, sample == HttpUtility.UrlDecode(test, encoding));
Console.ReadLine();

Will output the following:
UTF8 Ecoded: %c4%b8, round-trip = True
1252 Ecoded: %3f, round-trip = False

You can see in the later example the encoding is "%3f" which, when unencoded is equal to a question mark "?", not the input character of 312 (0x138).
In a nutshell there is nothing wrong with encoding "ß" as "%c3%9f", to the contrary, it is the correct representation.  Yet if you must have the encoding "%DF for the remote server to correctly decode it, then use the 1252 codepage as shown.

A: The ß character is encoded as %c3%9f when using the UTF-8 encoding. This is what you should be using, if possible.
If your target webserver uses some other encoding, you need to know exactly what encoding that is. Since you want to encode that character into %df that could be Windows-1252 or Windows-1250 (or possibly others).
If you're sure this is what you want to do, you can use (assuming Windows-1252):
HttpUtility.UrlEncode("ß", Encoding.GetEncoding(1252))


text:
Q: Passing label.text through application layers I am working on a multilayer website (asp C#).  I am curious how I can access set a label text from inside the business layer.  Currently it says it can not resolve the symbol but I have it in my presentation layer.  Is there a way to pass through all the layers and set the label.Text?
Basically I want to do my validation in the Business layer not on the presentation layer but I need to be able to set the label when the validation fails.
public CommandResponse<int> AddRequest(AddRequestCommand command)
    {
        CommandResponse<int> response = new CommandResponse<int>();
        //DO domain logic
        using (var context = ContextFactory.GetContext())
        {
            var repo = RepositoryFactory.GetRequestRepository(context);
            string email = command.Request.RecipientEmail;
            Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
            Match match = regex.Match(email);
            if (!match.Success)
            {
                lblEmailmsg.Text = "Error Message"
            }

            var id = repo.Add(command.Request);

            response.Id = id;
            response.IsSuccessful = true;

            DomainEvents.Raise<RequestCreatedEvent>(new  RequestCreatedEvent(command.Request, command.Request.Token ));
        }

A: Your question is a little thin on details, but from your last sentence:

Basically I want to do my validation in the Business layer not on the
  presentation layer but I need to be able to set the label when the
  validation fails.

I think I know what you mean.
Here's how I would do this kind of thing:
Use Ajax/JSON to send the data to the server.  Process what you need including all validations there, then send JSON data back to the client (which is then available in the 'success' handler of your Ajax call) including any label text that needs to be updated.
You can then take this result and do what you need to do with JS/jQuery including updating labels and so on.  Also, Knockout.js is an excellent tool (among several) that can simplify this type of client-side data binding.

A: Presumably you're trying to do something like this:
public class SomethingInThePresentationLayer
{
    public void SomeMethod()
    {
        var businessObject = new SomethingInTheBusinessLayer();
        businessObject.Validate();
    }
}

public class SomethingInTheBusinessLayer
{
    public void Validate()
    {
        pageElement.Text = "This is the text.";
    }
}

This is incorrect, for a couple of reasons.  First, classes can't see each other's members like that.  SomethingInTheBusinessLayer would need a reference to the pageElement member in order to use it.
Second, this is mixing concerns.  pageElement is a presentation layer element.  It is wholly owned by the presentation layer and nothing in the business layer should know about it.  This is especially true is understanding it requires referencing libraries which the business layer shouldn't reference (such as System.Web).
Instead, when interacting with the business layer, you would use more portable types.  They can be custom types exposed by the business layer itself, or just the primitive types of the values you're using.  For example, you might have something like this:
public class SomethingInThePresentationLayer
{
    public void SomeMethod()
    {
        var businessObject = new SomethingInTheBusinessLayer();
        var result = businessObject.Validate();
        pageElement.Text = result;
    }
}

public class SomethingInTheBusinessLayer
{
    public string Validate()
    {
        return "This is the text";
    }
}

Now the business layer only performs the logic, it doesn't try to interact with the presentation elements.  That's a job for the presentation layer.


text:
Q: Formula keyboard ios my application is a maths application, and I would like a sort of formula keyboard to appear besides the normal ios keyboard. The ios keyboard on ipad gives numbers, but not square roots and other maths formats, so is there an already existing api i can use for this purpose? Thanks for any ideas

A: Find these superb links that will help you to create custom keyboard.
Few have many different formats of keyboard with running applications, you can simply modify them according to your need.
http://www.cocoacontrols.com/search?utf8=%E2%9C%93&q=keyboard
http://code.google.com/p/networkpx/wiki/Using_5RowQWERTY
https://github.com/vikingosegundo/KeyPad
http://iphonedevsdk.com/forum/iphone-sdk-tutorials/7350-adding-subviews-custimize-keyboard.html

A: Yes, text fields and text views provide inputView and inputAccessoryView properties you can use to customise the keyboards used for them.


text:
Q: Updates to an uncommitted Perforce changelist in a code collaborator peer review I have created a Code Collaborator peer review from an uncommitted Perforce changelist. This works fine, and the peer review is going swimmingly. A defect was found, and the changes were made. Now, I want the peer review updated with the new version of the file.
When I try to upload the new version of the file, it adds it as a new resource rather than a new version of the existing file already in the peer review. When I try to upload the entire uncommitted changelist again, it shows up as a new version of that same uncommitted changelist. In other words, I can't seem to get the existing file in the peer review to show up with my changes...everything I do adds another resource in some form or fashion.
Any ideas?

A: Heard from CodeCollaborater on this. Apparently the way to approach this is to consistently upload the entire pending changelist when you want any updates to show up in the peer review. This will still show multiple sets of the peer review files (one set for reach time the pending changelist is uploaded).
You can, however, change the view of the Review Summary screen to "compact" all those sets into one. Each reviewer wanting to see this presentation needs to select the following in the Review Materials section of the review:

View as: Overlay


text:
Q: How Use Google earth in WPF without WebBrowser & JavaScript I want to use Google Earth to Create a GIS map.
I using WPF & MultiTouch Events for Map Control and not define ManipulationDelta on WebBrowser Control. Because not use WebBrowser & JavaScript for Map Control.
How can I use Google earth in WPF without WebBrowser & JavaScript?

A: You can use the JSON GMAP API directly if you want. Have a look at this project too, may be you find it useful.


text:
Q: How can I determine if my Cocoa Desktop application is on the list of apps to be opened at login? I am developing a SandBoxed Cocoa Application. I have successfully implemented the Launch at login feature by using the Core Foundation function:
SMLoginItemSetEnabled

I have based the implementation on This tutorial
But now I need a way to determine if my app is set to be launched at login, so that I can show the button in the appropriate position upon launch. I would expect a similar Core Foundation function to find out if a bundle identifier is on the list of login items, but I didn't find it.
Another problem is that, by using this Core Foundation approach, although it is recommended by Apple, my app is still inconsistent with the "Open at Login" tick in my application dock menu.

A: You can do it using the functions in the LSSharedFileList.h header, which is in LaunchServices.framework, which is in CoreServices.framework.  As far as I can tell, Apple hasn't documented this stuff except in the header comments, but that's probably enough.  The basic outline is that you first create a LSSharedFileListRef using the function LSSharedFileListCreate for the list type kLSSharedFileListSessionLoginItems.  Then copy a snapshot of the list (which is a CFArrayRef) using LSSharedFileListCopySnapshot.  Then for any item in the array, you can get its URL using LSSharedFileListItemCopyResolvedURL.  That last function requires Mac OS X 10.10 or later, while I think the others date back to 10.5.
By the way, the docs on SMLoginItemSetEnabled say that it's for setting an embedded helper app as a login item, but it sounds like you're talking about a freestanding app.
Apple's sandbox documentation says:

With App Sandbox, you cannot create a login item using functions in the LSSharedFileList.h header file. For example, you cannot use the function LSSharedFileListInsertItemURL.

But maybe you can still use the shared file list functions on a read-only basis.


text:
Q: How to store a list of KFunction1 for kotlin? Basically I want to create a router that can be used in the following way
router.register(someInstance::getData)
router.register(someInstance::submitData)

where both getData and submitData is an instance of
getParam : KFunction1<GetParam, GetResponse>
submitData : KFunction1<SubmitParam, SubmitResponse>

where GetParam, GetResponse, SubmitParam, SubmitResponse is a class that implements respective interfaces (IParam, IResponse)
inside the register it would look like
val routeMap = mutableMapOf<String, KFunction1<IParam, IResponse>
fun register<P : IParam, R : IResponse>(func : KFunction1<P, R>) {
    routeMap["abc"] = func
}

only problem right now is that it seems that I can't access KFunction1 directly (so I cannot store them)
the idea is to basically create some sort of router that can register and call the registered functions later on. If anyone has any other idea on how to implement this, feel free to give suggestions

A: If you just want to register and call them, use the normal function types: (P) -> R, not KFunction1<P, R>.
But the real issue is that (P) -> R is not a subtype of (IParam) -> IResponse (and can't be because its invoke method doesn't accept any IParam) and so can't be stored in routeMap.
How to fix this will depend on what you want to happen when types don't match.


text:
Q: What happens if a survival curve doesn't reach 0.5? Does this mean you can't compute the median?

A: Yes, unless you use a parametric approach and are willing to extrapolate.
See SAS Lifereg.

A: The median survival time is defined to be the time at which the survival curve crosses 50% survival. If the curve doesn't cross 50% (because survival is greater than 50% at the last time point), then median survival is simply undefined. More precisely, it is greater than the last time point on your survival curve. The only way around this, as B_Miner posted,is if you fit some kind of model so are willing to extrapolate beyond the time span you have data for.

A: "The median is the data point which is greater than 50% of all data points. As soon as you have one or more data points, you always have a median. What does the phrase "doesn't reach 0.5" mean? Please clarify. "
In a survival curve situation, you have N individuals followed over time and let's say only 10% of them die in 5 years. Until 50% of them die and contribute a survival duration, you cannot measure the median survival of the whole group of N people.  If the question were, "What is the median age at death in your town?" then you could look at the people who died and calculate median age at death. This is a cross-sectional analysis of those who died. But consider instead of a cross sectional study, you do a cohort study. If the question were "What is the median age at death among people born in 1998?" then you can only provide age at death among those who died, but not among the whole cohort. We can break down the latter question into 2 different ones and they yield 2 different measures. (1) "What is the median age at death among people born in 1998 who had died by Sept 7, 2013?" You can answer this question if you have any number of observations (deaths) greater than 0.  The question in issues of median survival in a cohort study is more often this: (2) "What is the median age at death among all of the people born in 1998?" For this, you need 50% of people to have died to be able to measure the median survival. If not, the survival curve, which starts at 1 (100% alive) and ends eventually at 0 (100% died), does not cross 0.5 (the point at which 50% have died).


text:
Q: How to create a pydub AudioSegment using an numpy array? I have the following code in python
from scipy.io.wavfile import read
rate, signal = read('./data/input.wav')
# get only one channel
signal = signal[:,0]
# do a bunch of processing here

Now I want to create an pydub segment using 'signal' and 'rate'
audio_segment = pydub.AudioSegment()

So how can I create this audio segment, and after that,
how can I get back my signal as an numpy array?

A: I was able to run this code on my machine:
from scipy.io.wavfile import read
from pydub import AudioSegment

rate, signal = read("./test/data/test1.wav")
channel1 = signal[:,0]

audio_segment = pydub.AudioSegment(
    channel1.tobytes(),
    frame_rate=rate,
    sample_width=channel1.dtype.itemsize,
    channels=1
)

# test that it sounds right (requires ffplay, or pyaudio):
from pydub.playback import play
play(audio_segment)


text:
Q: get all attributes for entity from core data how does my fetchedResultsController method look like, if I want to fetch all my attributes for an entity from core data? I only know and understand how to fetch data for a tableView and I think that is where all my confusion is coming from.
Here is my Core-Data setup:

I'm trying to fill an array with all the Attributes my Setting entity has and the show those values via NSLog output in my debug console.
Here is what I changed so far:
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

        NSManagedObjectContext *context = [appDelegate managedObjectContext];

        NSManagedObject *newEntry = [NSEntityDescription insertNewObjectForEntityForName:@"Setting" inManagedObjectContext:context];
        //NSManagedObject *newSetting = [NSEntityDescription insertNewObjectForEntityForName:@"Setting" inManagedObjectContext:context];

        [newEntry setValue: @"StudiSoft" forKey:@"settingName"];

        if (_overrideSysTimeSwitch.on) {
            [newEntry setValue: @YES forKey:@"settingSysTimeOverride"];
            //editSetting.settingSysTimeOverride = @YES;
            NSLog(@"IF A");
        } else {
            //[newEntry setValue: @NO forKey:@"settingSysTimeOverride"];
            //editSetting.settingSysTimeOverride = @NO;
            NSLog(@"IF B");
        }

        if (_timeFormatSwitch.on) {
            //[newEntry setValue: @YES forKey:@"settingTimeFormat"];
            //editSetting.settingTimeFormat = @YES;
            NSLog(@"IF C");
        } else {
            //[newEntry setValue: @NO forKey:@"settingTimeFormat"];
            //editSetting.settingTimeFormat = @NO;
            NSLog(@"IF D");
        }
        [self.settingsArray addObject:@"StudiSoft"];

        NSError *error;
        [context save:&error];

I'm using this code-snipped that and I'm able to modify the core data content.
However, every time I run this code, it of course adds a new object.
I've been looking for a way to update existing Attributes in my Entity, or modify them, but I could NOT find them.
Anyhow this is a good step into the right direction.
I created a completely new project, with just one view, once I have it working on the main view I'm going to experiment with segues....
But for now, how would I update or change existing attributes?
Thanks guys!!
This is my editSave Method to store some data in core data:
- (IBAction)editSave:(UIBarButtonItem *)sender
{
    if ([_editSaveButton.title isEqualToString:@"Edit"])
    {
        [self setTitle:@"Edit Settings"];
        //self.title = @"Edit Settings";

        _overrideSysTimeSwitch.userInteractionEnabled = YES;
        _timeFormatSwitch.userInteractionEnabled = YES;

        _editSaveButton.title = @"Save";
    } else if ([_editSaveButton.title isEqualToString:@"Save"])
    {
        [self setTitle:@"Settings"];
        //self.title = @"Settings";

        _overrideSysTimeSwitch.userInteractionEnabled = NO;
        _timeFormatSwitch.userInteractionEnabled = NO;

        _editSaveButton.title = @"Edit";

        // #############################################################
        AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

        NSManagedObjectContext *context = [appDelegate managedObjectContext];

        //NSManagedObject *newEntry = [NSEntityDescription insertNewObjectForEntityForName:@"Setting" inManagedObjectContext:context];

        //[newEntry setValue: @"StudiSoft" forKey:@"settingName"];

        /*NSString *firstName = [anEmployee firstName];
        Employee *manager = anEmployee.manager;
        Setting *newSetting = [NSString @"Test"];

        [newSetting setValue:@"Stig" forKey:@"settingName"];
        [aDepartment setValue:[NSNumber numberWithInteger:100000] forKeyPath:@"manager.salary"];*/

        //editSetting.settingName = @"Test";

        if (_overrideSysTimeSwitch.on) {
            //[newEntry setValue: @YES forKey:@"settingSysTimeOverride"];

            editSetting.settingSysTimeOverride = @YES;
            NSLog(@"IF A");
        } else {
            //[newEntry setValue: @NO forKey:@"settingSysTimeOverride"];

            editSetting.settingSysTimeOverride = @NO;
            NSLog(@"IF B");
        }

        if (_timeFormatSwitch.on) {
            //[newEntry setValue: @YES forKey:@"settingTimeFormat"];

            editSetting.settingTimeFormat = @YES;
            NSLog(@"IF C");
        } else {
            //[newEntry setValue: @NO forKey:@"settingTimeFormat"];

            editSetting.settingTimeFormat = @NO;
            NSLog(@"IF D");
        }
        //[self.settingsArray addObject:@"StudiSoft"];

        NSError *error = nil;
        //if ([self.managedObjectContext hasChanges]) {
            //NSLog(@"SAVE & DISMISS conetx has changed");
            if (![context save:&error]) {                 // save failed
                NSLog(@"Save failed: %@", [error localizedDescription]);
            } else {                                                        // save succeeded
                NSLog(@"Save Succeeded");
            }
        //}

        //[self.tableView reloadData];
        // #############################################################
    }
}

Debug Output:
2014-06-10 19:09:29.881 SettingsCoreData[508:60b] Entry #5: <Setting: 0x8f983e0> (entity: Setting; id: 0x8f97030 <x-coredata://FA78AB86-3225-4B1E-97DD-3F31F5323A18/Setting/p6> ; data: {
    settingName = StudiSoft;
    settingSysTimeOverride = 0;
    settingTimeFormat = 0;
})
2014-06-10 19:09:29.883 SettingsCoreData[508:60b] Entry #6: <Setting: 0x8f98430> (entity: Setting; id: 0x8f97040 <x-coredata://FA78AB86-3225-4B1E-97DD-3F31F5323A18/Setting/p7> ; data: {
    settingName = StudiSoft;
    settingSysTimeOverride = 1;
    settingTimeFormat = 1;
})

Now I should be able to use something like this in my viewDidLoad, right?
if (editSetting.settingSysTimeOverride.boolValue == 0) {
        _overrideSysTimeSwitch.on = NO;
    } else {
        _overrideSysTimeSwitch.on = YES;
    }

But it doesn't work as I thought it will :-(

A: Next you need to call -performFetch: on the NSFetchedResultsController.  Make sure you check the response and handle the error if the response is NO.
From there your NSFetchedResultsController is populated and ready to be used.  You can then grab individual elements via -objectAtIndex: or you can grab them all with -fetchedObjects.
I would suggest just reviewing the documentation on the methods that are available as it has pretty strong and clear documentation.
Update
If you are not receiving any data then break it down.  Take the NSFetchRequest that you created and call -executeFetchRequest:error: against your NSManagedObjectContext and see if you get any data back.

*

*If you do then there is something wrong with your handling of the NSFetchedResultsController.

*If you don't then there is something wrong with your NSFetchRequest or you don't have any data in your store.

Update
Sounds like you need to read a book on how Core Data works.
A NSFetchRequest is a query against Core Data so that objects can be returned from the store.  You can pass a NSFetchRequest to a NSFetchedResultsController so that the NSFetchedResultsController can monitor the store for changes and let your view controller know when those changes occur.
A NSFetchRequest can also be executed directly against the NSManagedObjectContext and you can retrieve the results directly.  You do that by calling -executeFetchRequest:error: against your NSManagedObjectContext and getting a NSArray back.  You can then check that NSArray to see if you get any results.
If you do not understand that paragraph then you need to take a step back and read the tutorials on Core Data and/or read a book on Core Data.  I can recommend an excellent book on the subject ;-)


text:
Q: AngularJS throws error when passing a URN to an argument In my AngularJS/Ionic app I'm writing a directive with a custom argument of its element containing an JSON Schema URN. The problem is that AngularJS tries to evaluate this URN as an expression.
<myDirective myAttr="urn:jsonschema:net:example:net:myschema"></myDirective>

The error:
Error: [$parse:syntax] http://errors.angularjs.org/1.2.25/$parse/syntax?p0=%3A&p1=is%20an%20unexpected%20token&p2=4&p3=urn%3Ajsonschema%3Anet%3Aexample%3Anet%3Amyschema&p4=%3Ajsonschema%3Anet%3Aexample%3Anet%3Amyschema
    at Error (native)
    at http://localhost:8000/app/www/lib/ionic/js/ionic.bundle.min.js:37:450
    at fb.throwError (http://localhost:8000/app/www/lib/ionic/js/ionic.bundle.min.js:200:227)
    at fb.parse (http://localhost:8000/app/www/lib/ionic/js/ionic.bundle.min.js:199:82)
    at $get (http://localhost:8000/app/www/lib/ionic/js/ionic.bundle.min.js:130:31)
    at h (http://localhost:8000/app/www/lib/ionic/js/ionic.bundle.min.js:136:163)
    at k.$get.k.$watch (http://localhost:8000/app/www/lib/ionic/js/ionic.bundle.min.js:137:444)
    at linker (http://localhost:8000/app/www/js/directives.js:8:15)
    at http://localhost:8000/app/www/lib/ionic/js/ionic.bundle.min.js:95:293
    at N (http://localhost:8000/app/www/lib/ionic/js/ionic.bundle.min.js:85:372) <jsonform schema="urn:jsonschema:net:example:net:myschema"> ionic.bundle.min.js:123(anonymous function) ionic.bundle.min.js:123$get ionic.bundle.min.js:99N ionic.bundle.min.js:85g ionic.bundle.min.js:78g ionic.bundle.min.js:78N ionic.bundle.min.js:85g ionic.bundle.min.js:78N ionic.bundle.min.js:85g ionic.bundle.min.js:78(anonymous function) ionic.bundle.min.js:77d ionic.bundle.min.js:345u.directive.a.compile ionic.bundle.min.js:345N ionic.bundle.min.js:85g ionic.bundle.min.js:78N ionic.bundle.min.js:85g ionic.bundle.min.js:78N ionic.bundle.min.js:85g ionic.bundle.min.js:78(anonymous function) ionic.bundle.min.js:77d ionic.bundle.min.js:345u.directive.a.compile.b ionic.bundle.min.js:345$get.k.$broadcast ionic.bundle.min.js:145v.transitionTo.v.transition.N.then.v.transition.v.transition ionic.bundle.min.js:321l.promise.then.E ionic.bundle.min.js:131(anonymous function) ionic.bundle.min.js:132$get.k.$eval ionic.bundle.min.js:143$get.k.$digest ionic.bundle.min.js:140$get.k.$apply ionic.bundle.min.js:143h ionic.bundle.min.js:103u ionic.bundle.min.js:108w.onreadystatechange ionic.bundle.min.js:110XMLHttpRequest.send (async)b ionic.bundle.min.js:110s ionic.bundle.min.js:105$get.f ionic.bundle.min.js:102l.promise.then.E ionic.bundle.min.js:131l.promise.then.E ionic.bundle.min.js:131(anonymous function) ionic.bundle.min.js:132$get.k.$eval ionic.bundle.min.js:143$get.k.$digest ionic.bundle.min.js:140$get.k.$apply ionic.bundle.min.js:143(anonymous function) ionic.bundle.min.js:49d ionic.bundle.min.js:66c ionic.bundle.min.js:49fc ionic.bundle.min.js:49Xc ionic.bundle.min.js:48(anonymous function) ionic.bundle.min.js:245a ionic.bundle.min.js:176(anonymous function) ionic.bundle.min.js:62r ionic.bundle.min.js:38c ionic.bundle.min.js:62

How can I stop AngularJS from parsing my attribute?
Edit: Changed attribute name from schema to myAttr because schema is reserved. Results in the same error.

A: use text @ binding:
app.directive('myDirective', function () {
    return {
      restrict: 'E',
      scope: {
          myAttr: "@"
       },
       link: function (scope) {
          console.log(scope.myAttr);
        }
      };
    }
);

html:
<my-directive my-attr="urn:jsonschema:net:example:net:myschema"></my-directive>

plunker: http://plnkr.co/edit/xfh3MVWzhBrw7bpJsZ2B?p=preview


text:
Q: OutputCache is sending wrong Vary header when the call hits the cache I have an action method that I want to cache:
[OutputCache(Duration=60*5, Location=OutputCacheLocation.Any, VaryByCustom="index")]
public ActionResult Index()
{
    return View();
}

With this approach:
public override string GetVaryByCustomString(HttpContext context, string custom)
{
    context.Response.Cache.SetOmitVaryStar(true);
    context.Response.Cache.VaryByHeaders["Cookie"] = true;

    if (User.Identity.IsAuthenticated)
    {
        Debug.Print("Authenticated");
        context.Response.Cache.SetNoServerCaching();
        context.Response.Cache.SetCacheability(HttpCacheability.Private);
        return null;
    }
    else
    {
        Debug.Print("Non authenticated");
        return custom;
    }
}

The idea was to keep a cached version of the page for non-authenticated users, but avoid caching for authenticated ones.
I thought it will always return a Vary:Cookie HTTP header, but it is not.
Doing a test with Fiddler and issuing twice the same request, in the first HTTP call it goes good:
HTTP/1.1 200 OK
Cache-Control: public, max-age=300
Content-Type: text/html; charset=utf-8
Expires: Thu, 09 Feb 2012 10:53:36 GMT
Last-Modified: Thu, 09 Feb 2012 10:48:36 GMT
Vary: Cookie
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 09 Feb 2012 10:48:37 GMT
Content-Length: 441

But in the second one, it overwrites the header:
HTTP/1.1 200 OK
Cache-Control: public, max-age=297
Content-Type: text/html; charset=utf-8
Expires: Thu, 09 Feb 2012 10:53:36 GMT
Last-Modified: Thu, 09 Feb 2012 10:48:36 GMT
Vary: *
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 09 Feb 2012 10:48:39 GMT
Content-Length: 441

So, as far as I know, browsers won't cache the request even if it is public, since Vary:* means that the request has been generated with parameters that are not in the URL nor in the HTTP headers. Is there a way to fix this?
Regards.
UPDATE:
In a similar way, when I send two identical authenticated requests, the first call gets the private modifier, but not the Vary header:
HTTP/1.1 200 OK
Cache-Control: private, max-age=300
Content-Type: text/html; charset=utf-8
Expires: Thu, 09 Feb 2012 12:43:14 GMT
Last-Modified: Thu, 09 Feb 2012 12:38:14 GMT
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 09 Feb 2012 12:38:14 GMT
Content-Length: 443

But the second one gets the same response that a non-authenticated request:
HTTP/1.1 200 OK
Cache-Control: public, max-age=298
Content-Type: text/html; charset=utf-8
Expires: Thu, 09 Feb 2012 12:44:32 GMT
Last-Modified: Thu, 09 Feb 2012 12:39:32 GMT
Vary: *
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 09 Feb 2012 12:39:33 GMT
Content-Length: 443

I have uploaded a test project showing the issue so may be you want to give it a try.
Please be aware that there is an IHttpModule that sets a request as authenticated or not depending on if the request has a cookie or not, this is not a "real life" approach, it is just for testing purposes.
The project contains only a web page with a link to itself, a link that logs you in, and another link that logs you out:

*

*LogIn : Sends a cookie in a HTTP 302 redirection to the home page again.

*LogOut: Sends a expired cookie in a HTTP 302 recirection to the home page again.

The expected/ideal behaviour would be:

*

*User access Index, and get the page from the server. The page show date "A".

*User access Index again, and the browser shows the cached version.The page show date "A".

*Clean browser cache.

*User access Index again, and the browser shows the server cached version. The page show date "A".

*User clicks login, and the broswer gets a new page, that show date "B".

*User clicks logout, and the browser gets the server cached page. The page show date "A" again.

But this is the behaviour so far:

*

*User access Index, and get the page from the server. The page show date "A".

*User access Index again, and the browser shows the cached version.The page show date "A".

*Clean browser cache.

*User access Index again, and the browser shows the server cached version. The page show date "A".

*User clicks login, and the broswer gets a new page, that show date "B".

*User clicks logout, and the browser should get the server cached page, but it does not. The page show date "B" again from the browser cache. This is because the lack of the Vary header in the authenticated response.

I don't know if I get something wrong about caching, just missing some detail or the OutputCache does not work very well, but I would appreciate any guidance.
Cheers.
UPDATE 2:
My intention is to use the HTTP cache semantics to:

*

*Allow browsers and proxys to cache the "public" version of the page.

*Allow browsers to cache the "authenticated" version of the page for its user.

If I change the OutputCache declaration to do the caching only on the server and prevent the downstream and client caching:
[OutputCache(Duration=60*5, Location=OutputCacheLocation.Server, VaryByCustom="index")]

it behaves as expected, but the downstream and client cache is prevented, and that is not what I want.

A: I don't think the [OutputCache] attribute is what you want, the VaryByCustom method is basically saying that I want to cache different versions based on these parameters, it doesn't really have an option for Do Not Cache and the majority of the code in the attribute is built around server based caching.
That being said the documentation on MSDN for custom caching seems to indicate you need to return a string to vary on based on the authentication state:
public override string GetVaryByCustomString(HttpContext context, string custom)
{
    if(custom == "user") return "User:" + context.Request.User.Identity.Name;

    return base.GetVaryByCustomString(context, custom);
}

And then use the user literal in the VaryByCustom:
[OutputCache(Duration=60*5, Location=OutputCacheLocation.Any, VaryByCustom="user")]
public ActionResult Index()
{
    return View();
}

So basically this would result in a cache being built for anonymous (assuming the anonymous identity is empty string or something) and every user on the server, and a Vary: * sent to the client I believe.  Obviously not ideal what you are looking for.
If you really just want to cache the unauthenticated version using HTTP caching I would recommend not using the OutputCacheAttribute and using something more custom.
You could easily just write in your own custom attribute something like what you have for your GetVaryByCustomString implementation (this is just some pseudo code, would need more than this):
public class HttpCacheUnauthenticatedAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if(!filterContext.HttpContext.Request.IsAuthenticated) {
            //TODO: set unauthenticated caching values and vary here
        }
    }
}

And then tag your action method with it:
[HttpCacheUnauthenticated]
public ActionResult Index()
{
    return View();
}

A: Sort of wrestling with something similar myself.  Have you tried in the web.config to the setting omitVaryStar=true
https://msdn.microsoft.com/en-us/library/ms228124(v=vs.100).aspx

A: I am using a custom cache provider and in this case there is a simple solution for this.
On the BeginRequest, based on the user authentication status, we set a context information to not run cache:
HttpContext.Current.Items["NoCache"] = "1";

And then on our GetVaryBy method we return null if this information is set:
public override string GetVaryByCustomString(HttpContext context, string custom)
{
    if (HttpContext.Current.Items["NoCache"] != null)
        return null;

    // remaining code here
}

And then on the cache methods, we can test the same. For instance:
public override object Add(string key, object entry, DateTime utcExpiry)
{
    if (HttpContext.Current.Items["NoCache"] != null)
        return null;

    // remaining code here
}


text:
Q: Priority of shapes that are added to a zone from a view I'm not using Orchard terms here but I have a snippet of text that I want to wrap up in a shape. It's some social sharing urls on the blog detail page. I wanted to keep it clean so I decided to make a new shape.
I have posted the full listing of Content-BlogPost.Detail.cshtml below but the idea is that:

*

*I make a cshtml to hold the social media markup

*I prep the data in the main post detail view

*I create the shape and add it to the Meta zone (which is a local zone not like meta descriptions) using Model.Meta.Add(socialShape, "1");
The shape is added as expected but the second parameter, the priority, doesn't work. It has to be a string, passing an int breaks the page. The default priority for the other items in the Meta zone are on 5 so it should put it at the top but it always ends up at the end.
// Model.Meta.Add works but the priority seems to be ignored?
@using Orchard.ContentManagement;
@using Orchard.Utility.Extensions
@using Orchard.Blogs.Models
@functions{
    void AddSocialMediaShareLinks() {
        var socialShareUrl = new Uri(new Uri(WorkContext.CurrentSite.BaseUrl), Url.ItemDisplayUrl((IContent)Model.ContentItem)).ToString();
        var socialShareTitle = Model.ContentItem.Title;
        var socialShape = New.BlogPost_SocialMediaShareLinks(ShareUrl: socialShareUrl, ShareTitle: socialShareTitle);
        Model.Meta.Add(socialShape, "1");
    }
}
@{
    if (Model.Title != null) {
        Layout.Title = Model.Title;
    }

    BlogPart parentBlog = Model.Blog;
    IContent contentItem = Model.ContentItem;
    var contentTypeClassName = ((string)Model.ContentItem.ContentType).HtmlClassify();

    AddSocialMediaShareLinks();

    Model.Classes.Add("content-item");
    Model.Classes.Add(contentTypeClassName);

    var tag = Tag(Model, "article");
}
@tag.StartElement

    @Display(Model.Header)

        @if (Model.Meta != null) {

                @Display(Model.Meta)

        }
        @Display(Model.Content)

@T("Go back to the news")

@if (Model.Footer != null) {

        @Display(Model.Footer)

}
@tag.EndElement

After reading some articles I found old post be Bertrand post about customizing the first item template.
I thought maybe where I was adding it to the zone was too late in the process so I changed the code to the snippet below, but the Model.Meta.Add never gets hit in this scenario:
@functions{
    void AddSocialMediaShareLinks() {
        var socialShareUrl = new Uri(new Uri(WorkContext.CurrentSite.BaseUrl), Url.ItemDisplayUrl((IContent)Model.ContentItem)).ToString();
        var socialShareTitle = Model.ContentItem.Title;
        var socialShape = New.BlogPost_SocialMediaShareLinks(ShareUrl: socialShareUrl, ShareTitle: socialShareTitle);

        ShapeMetadata metadata = Model.Metadata;
        metadata.OnDisplaying(ctx => {
            Model.Meta.Add(socialShape, "1");
        });
    }
}

Can anybody tell me what I am doing wrong?

A: To enable ordering, you should add Tab property to the shape Metadata, as following:
socialShape.Metadata.Tab = "";
Model.Meta.Add(socialShape, "1");

This will disable shapes grouping within ContentZone.
I think it's a bug in Orchard, but this workaround should solve your problem.

A: Most shapes just render their children in the order they were added. The difference in Zone and ContentZone shapes is the call to Order before the children are rendered:
    [Shape]
    public void Zone(dynamic Display, dynamic Shape, TextWriter Output) {
        string id = Shape.Id;
        IEnumerable<string> classes = Shape.Classes;
        IDictionary<string, string> attributes = Shape.Attributes;
        var zoneWrapper = GetTagBuilder("div", id, classes, attributes);
        Output.Write(zoneWrapper.ToString(TagRenderMode.StartTag));
        foreach (var item in Order(Shape))
            Output.Write(Display(item));
        Output.Write(zoneWrapper.ToString(TagRenderMode.EndTag));
    }

You can get the same effect in your own shapes by also calling Order from your template or shape method code.


text:
Q: Returning a DataTable using Entity Framework By Executing Stored Procedure Stored Procedure returns dynamic table which can have dynamic columns. I want to retrieve the list of data to tempResult .
IList<SqlParameter> parameters = GetCashInItemsParameters("inv.uspMonthendProces");
string queryString = CreateStoredProcedureExecuteQuery("inv.uspMonthendProcess", parameters);
var tempResult = ExecuteStoredProcedureForDataRetrieve<dynamic>(queryString, parameters.ToArray()).ToList();

CreateStoredProcedureExecuteQuery
public static string CreateStoredProcedureExecuteQuery(string storedProcedureName, IList<SqlParameter> parameters)
{
            string result = string.Empty;
            string parameterString = string.Join(
                ",", parameters.Select(i => i.ParameterName));
            result = string.Format(
                "{0} {1}", storedProcedureName, parameterString);

            return result;
}

CreateParameter
public static SqlParameter CreateParameter(string parameterName, object value, SqlDbType dbType)
        {
            SqlParameter param = new SqlParameter(parameterName, dbType);
            param.Value = value;
            param.Value = value ?? (object)DBNull.Value;
            return param;
        }

GetCashInItemsParameters
public static IList<SqlParameter> GetCashInItemsParameters(string storedProcedureName)
        {
            IList<SqlParameter> parameters = new List<SqlParameter>();
            try
            {
                parameters.Add(CreateParameter(
                    "@Year", 2019, SqlDbType.Int));
                parameters.Add(CreateParameter(
                    "@Month", 3, SqlDbType.Int));
                parameters.Add(CreateParameter(
                    "@FromDate", "2019-03-01", SqlDbType.Date));

                parameters.Add(CreateParameter(
                    "@ToDate", "2019-03-31", SqlDbType.Date));
                parameters.Add(CreateParameter(
                    "@CashCentreId",1, SqlDbType.Int));
                parameters.Add(CreateParameter(
                    "@CustomerId", 2, SqlDbType.Int));
                parameters.Add(CreateParameter(
                    "@CurrencyId", 1, SqlDbType.Int));

            }
            catch (Exception ex)
            {
            }

            return parameters;
        }

ExecuteStoredProcedureForDataRetrieve
public IList<T> ExecuteStoredProcedureForDataRetrieve<T>(string sqlQuery, params object[] parameters) where T : class
        {
            return db.Database.SqlQuery<T>(sqlQuery, parameters).ToList();
        }

This is what i get as result
enter image description here
I tried with object , DataTable , DataSet. But it didnt work either. The project Im working on is using Repository.  So Cannot use Traditional ADO.net

A: Three things:

*

*You misspelled inv.uspMonthendProces

*You are outputting a parameter, rather than parameter.value for the results.

*The column that the parameter belongs to is not identified.
https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlparameter
SqlParameter(String, SqlDbType, Int32, String)
Initializes a new instance of the SqlParameter class that uses the parameter name, the SqlDbType, the size, and the source column name.