text:
Q: Efficient way for in between merge of array I have single channel pixel data in plain DataView format. So the size of the DataView is width*height. For rendering a bitmap from that data, I need to get 4-channel data if I'm right. My current test/naive implementation is like this.
const data = new Uint8ClampedArray(data);
const expanded = new Uint8ClampedArray(width * height * 4);
data.forEach((v, i) => {
 expanded[i * 4] = v;
 expanded[i * 4 + 1] = v;
 expanded[i * 4 + 2] = v;
 expanded[i * 4 + 3] = 255;
});

But that's obviously not performant. On 12 megapixel data, this takes something like 300ms. Is there a more efficient way to do a merge like this?
Or even better as a side question: Can I draw single channel bitmap on img tag or canvas?

A: You can boost the performance by filling your target array with 32 bit instead of 8 bit unsigned integers. In this case the 32 bit value holds the r, g, b and alpha value which you can send using a single instruction.
To better understand let's look at an example. Say we have the color #4080c4 with full alpha ff. On a little-endian processor architecture this corresponds to:
0xffc48040 == 4291067968

Alpha==0xff==255

Blue==0xc4==196

Green=0x80==128

Red==0x40==64

So the 8 bit unsigned integer values are 255, 64, 128 and 196 respectively. To make a 32 bit unsigned integer out of this 4 individual values we need to use bit-shifting.
If we look back at the hexadecimal number - 0xffc48040 - in a naive way, we can see that the ff alpha value is at the left. That means there are 24 bits before which in turn means that ff has to be shifted 24 bits to the left. If we apply the same logic to the remaining three values we end up with this:
let UI32LE = (Alpha << 24) | (Blue << 16) | (Green << 8) | Red;

The << is JavaScript's bitshift operator.
Please note that the order of the bits is important! As I mentioned, the above applies to little-endian. If it's a big-endian architecture the order is different:
let UI32BE = (Red << 24) | (Green << 16) | (Blue << 8) | Alpha;

Now if we take this technique and use it on something close to your use case we end up with this:

let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
let width = canvas.width;
let height = canvas.height;
let dummyData = [];
for (let a = 0; a < width * height; a++) {
  dummyData.push(parseInt(Math.random() * 255));
}
const data = new Uint8ClampedArray(dummyData);

let buffer = new ArrayBuffer(width * height * 4);
let dataView = new Uint32Array(buffer);
let expanded = new Uint8ClampedArray(buffer);

data.forEach((v, i) => {
  dataView[i] = (255 << 24) | (v << 16) | (v << 8) | v;
});

let imageData = context.getImageData(0, 0, width, height);
imageData.data.set(expanded);

context.putImageData(imageData, 0, 0);
<canvas id="canvas" width="200" height="100"></canvas>


text:
Q: TestFx headless MonoclePlatformFactory not found I trying to use JavaFX + Maven + TestFX (with headless)
i followed this tutorial JavaFX headless tutorial to enable the test in headless mode.
my pom
<groupId>com.bega</groupId>
<artifactId>Chronos</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>Chronos</name>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <mainClass>com.bega.chronos.MainApp</mainClass>
</properties>

<organization>
    <!-- Used as the 'Vendor' for JNLP generation -->
    <name>dazzd</name>
</organization>

<build>
    <plugins>
         <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>cobertura-maven-plugin</artifactId>
            <version>2.7</version>
            <configuration>
                 <formats>
                    <format>xml</format>
                </formats>
                <check>
                </check>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>clean</goal>
                        <goal>cobertura</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.18.1</version>
            <configuration>
                <forkCount>1</forkCount>
                <reuseForks>false</reuseForks>
                <threadCount>1</threadCount>
                <systemPropertyVariables>
                    <glass.platform>Monocle</glass.platform>
                    <monocle.platform>Headless</monocle.platform>
                    <prism.order>sw</prism.order>
                </systemPropertyVariables>
                <additionalClasspathElements>
                    <additionalClasspathElement>${java.home}/lib/ext/jfxrt.jar</additionalClasspathElement>
                </additionalClasspathElements>
            </configuration>
        </plugin>
    </plugins>
</build>
<dependencies>
    <dependency>
        <groupId>de.jensd</groupId>
        <artifactId>fontawesomefx</artifactId>
        <version>8.9</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-core</artifactId>
        <version>1.3</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.testfx</groupId>
        <artifactId>testfx-core</artifactId>
        <version>4.0.13-alpha</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.testfx</groupId>
        <artifactId>testfx-junit</artifactId>
        <version>4.0.13-alpha</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.testfx</groupId>
        <artifactId>openjfx-monocle</artifactId>
        <version>1.8.0_20</version>
        <scope>test</scope>
    </dependency>
</dependencies>

MainApp
public class MainApp extends Application {

@Override
public void start(Stage stage) throws Exception {
   Parent root = FXMLLoader.load(getClass().getResource("/fxml/Scene.fxml"));

    Scene scene = new Scene(root);
    scene.getStylesheets().add("/styles/Styles.css");

    stage.setAlwaysOnTop(true);
    stage.setTitle("Super Chrono");
    stage.setScene(scene);
    stage.show();

    stage.setOnCloseRequest((WindowEvent t) -> {
       try {
           sleep(1000);
       } catch (InterruptedException ex) {
           Logger.getLogger(MainApp.class.getName()).log(Level.SEVERE, null, ex);
       }
        Platform.exit();
        System.exit(0);
    });
}
/**
 * The main() method is ignored in correctly deployed JavaFX application.
 * main() serves only as fallback in case the application can not be
 * launched through deployment artifacts, e.g., in IDEs with limited FX
 * support. NetBeans ignores main().
 *
 * @param args the command line arguments
 */

public static void main(String[] args) {
    launch(args);
}

ChronoTest.java
public class ChronoTest extends ApplicationTest {

@BeforeClass
public static void setupHeadlessMode() {
    if(Boolean.getBoolean("headless")){
        System.setProperty("testfx.robot", "glass");
        System.setProperty("testfx.headless", "true");
        System.setProperty("prism.order", "sw");
        System.setProperty("prism.text", "t2k");
        System.setProperty("java.awt.headless", "true");
    }
    //bundle = ResourceBundle.getBundle("Bundle");
}

@Before
public void beforeEachTest() throws Exception{
    FxToolkit.setupApplication(MainApp.class);
}

@Test(expected = FxRobotException.class)
public void testAffihage(){
   verifyThat("#emma", hasText("Emmanuel"));
}

@After
public void afterEachTest() throws TimeoutException{
    FxToolkit.hideStage();
    release(new KeyCode[]{});
    release(new MouseButton[]{});
}

public <T extends Node> T find(final String query){
    return (T) lookup(query).queryAll().iterator().next();
}

}
i have also add headless=true in my profil properties (NetBeans IDE).
When i try to build it the test bug and i got this exception :
java.lang.ClassNotFoundException: com.sun.glass.ui.monocle.MonoclePlatformFactory
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at com.sun.glass.ui.PlatformFactory.getPlatformFactory(PlatformFactory.java:42)
at com.sun.glass.ui.Application.run(Application.java:146)
at com.sun.javafx.tk.quantum.QuantumToolkit.startup(QuantumToolkit.java:257)
at com.sun.javafx.application.PlatformImpl.startup(PlatformImpl.java:211)
at com.sun.javafx.application.LauncherImpl.startToolkit(LauncherImpl.java:675)
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:695)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$154(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:748)

Failed to load Glass factory class
If you have any idea ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Programmatically add binding to ItemsSource of DataGrid I want to display different tables in a DataGrid. I don't want to create a DataGrid for each table. So I have to dynamically add the ItemsSource of the DataGrid from the code.
How can I achieve this (WPF) ItemsSource="{Binding}" in the C# code.

A: Set the databinding to the property on your ViewModel that you want to bind to...
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:this ="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">
    <DataGrid ItemsSource="{Binding CurrentTable}"/>
</Window>

Set the datacontext (I prefer to do it in Xaml, but that's more than I like to do for an example)...
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainWindowViewModel();
    }
}

Create the property on you ViewModel...
public class MainWindowViewModel : INotifyPropertyChanged
{
    private DataTable currentTable;

    public DataTable CurrentTable
    {
        get
        {
            return this.currentTable;
        }
        set
        {
            this.currentTable = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("CurrentTable"));
        }
    }

    public MainWindowViewModel()
    {
        DataTable table = new DataTable();
        table.Columns.Add("Column1");
        table.Columns.Add("Column2");
        table.Rows.Add("This is column1", "this is column2");

        CurrentTable = table;
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

All you have to do now is set the CurrentTable property to whatever table you want and it will update the UI and display it.


text:
Q: mod_rewrite remove sub directory from certain URLs I have a situation where I'm trying to remove a subdirectory from certain URLS.
Here is what I'm trying to accomplish
http://www.example.com/shop/some_product should go to http://www.example.com/some_product
But
I need http://www.example.com/shop/customer/account to stay the same.
So essentially I need to rewrite anything shop/... except shop/customer/... shop/admin/...
Here is what I have tried
RewriteCond %{REQUEST_URI} !^/shop/customer
RewriteCond %{REQUEST_URI} !^/shop/admin
RewriteCond %{REQUEST_URI} !^/shop/sales
RewriteRule ^/shop/(.*) http://www.example.com/$1 [L]

Anyone have any advice here?

A: Thanks arkascha.
Turns out I had a couple problems. Here is what I ended up with:
in /shop/.htaccess
RewriteCond %{REQUEST_URI} !^/shop/(media|skin|js|customer|admin|sales|checkout)/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) /$1 [L]

I needed to not rewrite URLs matching a file or directory. Also, it seems that having /shop/ was a requirement for the RewriteCond, but would not work in the RewriteRule.


text:
Q: Simplest solar panel home installation to power electric heaters? Background: With the surging cost of electricity (I'm in Europe), I want to install solar panels to power electric heaters at home.
Research = batteries are needed: All setups I see include batteries (+charger controllers for the batteries.)
My understanding regarding batteries: The batteries serve two purposes: store energy as solar production doesn't necessarily align with the consumption AND regulate power output (constant output to prevent power cuts, minimum output so appliances can operate, maximum output so as to not damage appliances.)
My problem with batteries: They are expensive, and the moment I include them in my simulations they make the overall setup no longer cost effective.

QUESTION: Can't we just skip batteries? If all I want to power are basic electric heaters (essentially just resistors) AND I just want to power them during the day with whatever solar power is available, can't I just skip batteries altogether?

My naive thought: Basic electric heaters are just resistors, they don't contain any electronics, have no sensitive components, so my thought is that they should be able to produce heat with whatever solar power they receive, which would allow me to heat up my home as much and as cheaply as possible during the day (0 cost of batteries,) then at night I go to bed so I don't care if the installation doesn't generate any heat.

A: Yes you can just skip batteries and the alternator and a lot of stuff if all I want to power are basic electric heaters AND you just want to power them during the day with whatever solar power is available.  You don't have to take my word for it if you can get a pv panel and some nichrome wire.  You will find that you reach a limit in power and temperature when you try to heat something large that constantly loses that heat.
Heck, you can skip electricity altogether and go solar thermal.  Stirling engine if you need to pump what you heat.  Much cheaper to scale too so you can keep scaling until you have enough, if you have the space.  Do some insolation calculations to get an idea of what you have available in your area, figure out what efficiency you need to get out of your available solar field, and maybe build a scaled down version to start and see if you can get to that efficiency.

A: Storage is needed. But not necessarily batteries.
You could re-purpose an old hot water storage tank, with solar panels driving an immersion heater element.
(Bypass its own thermostat, which isn't rated to switch DC. Or use the thermostat at low voltage, to switch a DC rated contactor. But you'll need some control system to prevent boiling for safety's sake).
Add a pump to circulate warm water through room radiators.
If your storage tank has a heat exchanger loop for a central heating system, you could add solar thermal heating too, and benefit from its much higher efficiency.


text:
Q: Is there a way to gain access to the class of a method when all you have is a callable I have code that is like:
class Foo:
    def foo(self):
        pass

class Bar:
    def foo(self):
        pass

f = random.choice((Foo().foo, Bar().foo))

How do I access Bar or Foo from f?
f.__dict__ is of little to no help, but as repr(f) gives <bound method Bar.foo of <__main__.Bar object at 0x10c6eec18>>' it must be possible, but how?

A: Each bound method has the __self__ attribute which is the

instance to which this method is bound, or None

(copied from here)
More about bound methods (from Data Model):

If you access a method (a function defined in a class namespace)
  through an instance, you get a special object: a bound method (also
  called instance method) object. ... Bound methods have two special
  read-only attributes: m.__self__ is the object on which the method
  operates...

So f.__self__ will get you the class instance:
print(f.__self__) # <__main__.Foo object at 0x7f766efeee48>

And type(f.__self__) or f.__self__.__class__ will get you the type object:
print(type(f.__self__)) # <class '__main__.Foo'>

You'd only use __class__ for old-style classes.


text:
Q: How to write links in SVG to be URL-relative instead of webserver root (Filesystem) relative? When I add a link inside a SVG file, like

then this link is treated as filesystem-relative to where the SVG sits, for example (assuming a  Wordpress setup) it becomes www.example.com/wordpress/wp-content/themes/mytheme/mysvgfolder/target.htm.
When doing this in HTML (sitting in the same filesystem path as the SVG file), like my Link, then the link actually gets www.example.com/prettyurl/target.htm, no matter what the actual filesystem path is.
How do I have to enter the relative link in the SVG file to actually get (HTTP-)URL-relative links that respect my prettylink structure?
Absolute paths are no option for me, because the SVG files are meant to be used on different domains and in different filesystem paths.

A: You don't need to put the domain in you could use

This will expand to reflect the domain but won't be relative to a file location.
Alternatively use an HTML <base> tag and then all relative links will be relative to the <base> tag location. You'd need to be careful with internal links if you did that of course.


text:
Q: Обновление файлов css/js Есть молодой сайт, на котором приходится постоянно обновлять файлы. Используется фреймворк Flask. Как обеспечить обязательное обновление файлов css и js?
Подключение файла стилей:
<link href="{{url_for('static', filename='css/index.css')}}" rel="stylesheet" type="text/css"/>

Добавление версии не решает проблему. Файл стилей таким образом просто не добавляется.
<link href="{{url_for('static', filename='css/log_in.css?v=2')}}" rel="stylesheet" type="text/css"/>

Аналогично файлы js.

A: <link href="{{url_for('static', filename='css/log_in.css')}}?v=2" ...


text:
Q: SELECT который возвращает каждую n-ую запись Добрый день!
Есть селект в системе, на основе этого селекта строится график.
Данные в таблицу постапуют 2 раза в секунду. При этом соответсвенно график строит 7200 значений в час. Такая точность необходима для системы, но не для графика. На нем становиться невозвожно что-то прочитать. Для графика оптимально будет значение каждые 20 минут. Т.е как организовать селект, чтобы он брал только каждую 2400 запись?
В голову прирходят только идеи с временными таблицами, но не могу понять как реализовать код :(
Код основного селекта
 BEGIN
    select Coun_W = a.Count_W,
           DateTime=a.DateTime,
           Consumption = (a.Diff_Count_W/a.Diff_Count_AP)*1000000,
           OrderNo = b.OrderNo,
           ProductNo = b.ProductNo,
           Value = b.Value,
           Brand = b.Brand,
           BrandName = b.BrandName,
           LinkUp = b.LinkUp,
           KDF= b.KDF,
           StartDate = b.StartDate,
           CompletionDate = b.CompletionDate

      FROM ( SELECT * FROM [AcetateWeight].[dbo].[WeightCounter] where Equipment IN (@Equipment) AND Diff_Count_AP>0 and Diff_Count_AP is not null
    AND DateTime
    BETWEEN DateAdd(Minute,450,(@DateTime))  AND DateAdd(minute,1170,(@DateTime))) as a

      inner join

      (SELECT * FROM [AcetateWeight].[dbo].[AW_FilterPOActuals] WHERE /*DAY=@DateTime AND Shift=@Shift and*/ KDF=@Equipment) as b
      ON
    a.DateTime >= b.StartDate AND a.DateTime<= b.CompletionDate

   END

A: Высчитайте номер записи (или возьмите готовый, если он у вас есть), и выберите те записи, у которых номер нацело делится на 2400:
Для готового номера:
... WHERE ID % 2400 = 0

Для построения номера по DateTime
;WITH allrecords AS (
     -- тут ваш запрос
),
rowsWithNumbers AS (
    SELECT *,
    -- вместо DateTime - нужную колонку
    ROW_NUMBER() OVER (ORDER BY DateTime) as RowNumber allrecords
)
SELECT * FROM rowsWithNumbers
WHERE RowNumber % 2400 = 0

но вообще, если даты у вас  уникальные, можно было бы ограничится получением записей где минуты равны 0, 20 или 40.


text:
Q: Regular expression for replacing integers followed by underscore in a string in php I am new to regular expressions in php.
I am trying to replace values something like

101_1
  102_2
  103_3

to word "custom values" in my strings
I have tried many combinations but could not find solution. Here is the code I think should work according to documentation of regular expressions help available on internet
$result = str_replace('[1-6]*_1', "custom values", $string);

Remember these values come in between the string, nor in start neither in end of string.

A: Try something such as this:
$result = preg_replace('/\d{3}_\d/', "custom values", $string);

it captures the first three digits followed by the underscore and then another digit.

A: Your expression doesn't work because it is not capturing the 0 in [1-6].
Assuming you always have an underscore between one or more digits, use:
$result = preg_replace('/\d+_\d+/', "custom values", $string);

A: use preg_replace instead of str_replace
preg_replace('/[0-6]{1,3}_[1-3]/', 'custom values', $string);


text:
Q: Another question about amenability and Følner sequences Følner's characterization of Amenability says that a group $G$ is amenable if there exists a directed set $(I,\leq)$ and a net {$F_i:i\in I$} of finite subsets of $G$ such that for every $γ ∈ G$,
$$\lim_{i\in I}\frac{|γF_i\Delta F_i|}{|F_i|}\ \ \ \rightarrow 0\ ,$$
where $\Delta$ is the symmetric difference of two sets. It is also known that, if $G$ is countable, the word "net" can be substituted by "sequence" (that is $I=\mathbb N$ with the usual order).
Is it true that for countable (or at least finitely generated) groups we can always find a Følner sequence as above, which satisfies the following conditions:
(1) $F_{n}\subseteq F_{n+1}$, for all $n\in \mathbb N$;
(2) $\bigcup_{n\in\mathbb N}F_n=G$.
The motivation for my question comes from the paper "The Abramov-Rokhlin Entropy Addition Formula for Amenable Group Actions" by Ward and Zhang (Mh. Math, 1992). In fact, their Theorem 2.6 (that they attribute to Ornstein and Weiss) is proved for a Følner sequence as the one above but it is applied to actions of arbitrary countable Amenable groups. So... it seems that such sequences always exist.

A: Yes - see Lemma 5.1 of Gabor Pete's book on probability and groups: http://www.math.bme.hu/~gabor/PGG.html (by the way, these are excellent lecture notes)

A: Yes, it follows from the following simple lemma: if $(F_n)$ is a Følner sequence, then $(A\cup F_n)$ is also a Følner sequence for any finite set $A$.
EDIT. It is a quite common misconception to formulate the Følner condition in terms of exhausting sequences only. The bottom line is that existence of almost invariant functions or measures (be it for a group/groupoid action or the Riemannian/combinatorial Laplacian) is equivalent to existence of sets with small boundary (Følner sets). There is nothing in this equivalence which would require these sets to be nested or to exhaust the whole state space. In what concerns the lecture notes you mention you miss the connectivity condition on a Følner exhaustion which is imposed there, which completely changes the situation.
Let me give a more detailed argument showing how the lemma above implies existence of a nested exhausting sequence of Følner sets on any amenable group or graph. Actually, for the sake of simplicity let me do it just for graphs with uniformly bounded vertex degrees - which also takes care of finitely generated groups; for infinitely generated groups one has to consider symmetric differences between individual translates instead of dealing just with boundaries in the Cayley graph.
By the classical theorem of Gerl a graph $X$ is amenable if and only if there exist finite subsets $F$ with arbitrarily small ratio $|\partial F|/|F|$. I claim that one can always choose a nested sequence $\Phi_n$ which exhausts $X$ with $|\partial \Phi_n|/|\Phi_n|\to 0$. Indeed, take a sequence $F_n\subset X$ with $|\partial F_n|/|F_n|\to 0$, an exhausting nested sequence $A_n\subset X$, and a sequence $\epsilon_n\to 0$. Put $\Phi_1=F_1$, and then inductively (by using the above lemma) $\Phi_{n+1}=\Phi_n \cup A_n \cup F_N$, where $N=N(n)$ is chosen to satisfy the inequality $|\partial\Phi_{n+1}|/|\Phi_{n+1}|<\epsilon_{n+1}$.
This argument is totally trivial (and I would say redundant) from geometrical point of view.


text:
Q: MYSQL InnoDB:why performance after increasing the buffer pool size isn't even close to the MEMORY engine? I have a database containing a single table. the size of the table is 3.5 Gs.
I'm doing a read only query on the table, using three different configurations:

1- Innodb default buffer pool size.

2- Innodb buffer pool size = 6G.

3- Memory engine.

the running times of the three different configurations:

1- default buffer pool size .... 15,53 seconds.

2- buffer pool size = 6G ...... 13,60 seconds.

3- Memory engine .... 3,96 sec.

....

if increasing the buffer pool size shall make the database like "in-memory" databases.... why there is a huge gap between Memory engine and the buffer pool with huge enough space to contain the tables.

Notes:

1- I'm doing the experiment on a dedicated machine.

2- when using the buffer pool with 6Gs.... no swapping occurs, so the table fits comfortably within the memory..without swapping.

3- I was doing the query more than once to ensure the "hot data" was loaded to the main memory... and I was watching the memory consumption... it went from 500 MB to arround 4G after doing the query .... buffer pool 6G setting.

4- the table created using this command:
CREATE TABLE lineitem (
L_ORDERKEY    INTEGER NOT NULL,
L_PARTKEY     INTEGER NOT NULL,
L_SUPPKEY     INTEGER NOT NULL,
L_LINENUMBER  INTEGER NOT NULL,
L_QUANTITY    DECIMAL(15,2) NOT NULL,
L_EXTENDEDPRICE  DECIMAL(15,2) NOT NULL,
L_DISCOUNT    DECIMAL(15,2) NOT NULL,
L_TAX         DECIMAL(15,2) NOT NULL,
L_RETURNFLAG  CHAR(1) NOT NULL,
L_LINESTATUS  CHAR(1) NOT NULL,
L_SHIPDATE    DATE NOT NULL,
L_COMMITDATE  DATE NOT NULL,
L_RECEIPTDATE DATE NOT NULL,
L_SHIPINSTRUCT CHAR(25) NOT NULL,
L_SHIPMODE     CHAR(10) NOT NULL,
L_COMMENT VARCHAR(44) NOT NULL);

5- the query I'm running, (i.e), query 6 of the tpch
select
sum(l_extendedprice * l_discount) as revenue
from
  tpch2.lineitem
where
   l_shipdate >= date '1994-01-01'
   and l_shipdate < date '1994-01-01' + interval '1' year
   and l_discount between 0.06 - 0.01 and 0.06 + 0.01
   and l_quantity < 24;

A: *

*Are there no indexes?  Or does the table have INDEX(l_shipdate) and INDEX(l_discount) and INDEX(l_quantity) so that the Optimizer can pick among them?

*Please provide EXPLAIN SELECT ... for both the InnoDB and Memory versions.

*Are you running one connection doing that query repeatedly?  Or many?  Or so many that you are maxing out resources?

INDEX(l_shipdate, l_discount, l_quantity) is not beneficial since the Optimizer can't really handle more than one "range", and each part of the WHERE is a "range".
I'm surprised that the speed ratio is more than 3:1.  Memory would have to do a table scan, testing every row.  InnoDB, with the 3 indexes I suggest would probably use an index.  This depends on the distribution of the data.  Speaking of which, how many rows in that date range?  In that discount range?  In that quantity range?
Did you run each timing twice?  The first time would have I/O, but "warm up the cache"; the second would (presumably) have no I/O.


text:
Q: Resize Rotated UIView from Corners I have a UIView selectFrame with four corner handles as subviews. Each corner handle has a UIPanGestureRecognizer which calls this method:
This is my code (where self is the selectFrame UIView):
-(void)handleDrag:(UIPanGestureRecognizer *)gesture

{
    UIView *view = gesture.view;
    CGPoint translation = [gesture translationInView:view.superview];

    CGRect frame = self.bounds;

    switch (view.tag) {
        case (DRAG_HANDLE_TAG):  //upper left
            frame.size.width -= translation.x;
            frame.size.height -= translation.y;
            break;
        case (DRAG_HANDLE_TAG+1): //upper right
            frame.size.width += translation.x;
            frame.size.height -= translation.y;
            break;
        case (DRAG_HANDLE_TAG+2): //bottom left
            frame.size.width -= translation.x;
            frame.size.height += translation.y;
            break;
        case (DRAG_HANDLE_TAG+3): //bottom right
            frame.size.width += translation.x;
            frame.size.height += translation.y;
            break;
    }
    self.bounds = CGRectIntegral(frame);

    CGAffineTransform transform = self.transform;
    transform = CGAffineTransformTranslate(transform, translation.x/2, translation.y/2);
    self.transform = transform;

    [gesture setTranslation:CGPointZero inView:view.superview];

}

This code works really well without a rotation, but with the UIView rotated, it drifts.
However, if I do the whole calculation at the end of the gesture, by putting
if (gesture.state != UIGestureRecognizerStateEnded)
    return;

at the top of the method, it works well even with the rotation, so it seems that the code works, but could it be rounding errors?
This question seems to have been asked in many different guises, but I can't find, after many hours of looking, one exactly answered. There are a number of StickerView examples available that resize from the center. This question Resize UIView While It Is Rotated with Transform receives a very full answer, but it doesn't really answer the question.
Edit: There are a lot of responses suggesting trigonometry, and I have attempted this, but it seems to me that it should be possible simply using CGAffineTransforms. I have experimented with this, but with no good result.

A: I've put up a project on github to move, rotate and scale. It only uses CGAffineTransforms for the rotation. This project has drag handles at the corners of the view, and resizes from the opposite corners and a rotate handle.
It uses Erica Sadun's article Taking Charge of UIView Transforms in iOS Programming and Brad Larson's / Magnus's anchor point code.
Link to my Resizable project: https://github.com/carolight/Resizable

A: We also had a problem in accumulating different transformations. Only translation or only scaling or only rotation would work well. But, if I rotated after translation or vice versa, then either the rotation would rotate the view around parent view's 0, 0 and scaling would drift the image as mentioned in your question.
Following two things solved our problem:

*

*For each of these gestures, we set anchor point to 0.5, 0.5 for the view we are rotating, if the state is UIGestureRecognizerStateBegan.
view.layer.anchorPoint = CGPointMake(0.5, 0.5)

*When we translate or scale, we get the view's current transformation, concat it with new (scaling/translation) transformation as follows:
CGAffineTransformConcat(currentTransformation, newTransformation)
However, in case of rotation we concat with newTransformation first and currentTransformation as second parameter, as follows:
CGAffineTransformConcat(newTransformation, currentTransformation)
Please note closely that the order we pass the transformation to be concatenated is important, as mentioned in documentation of CGAffineTransformConcat
Also, read this to understand anchorPoint better, and this for why it might be related to you problem.


text:
Q: Python list in list with 2 strings I have 2 lists of strings. I would like to combine them together to create list in lists like this one below.
[['Hello','praet:sg:m1:perf'], ['world', 'subst:pl:acc:n']]
How to do it? Somehow create instance of list in list or there is some "python magic"?
Thank you

A: zip (Python Docs) is what you are looking for. You can stitch together two lists in a list comprehension:
l1 = ['Hello', 'world']
l2 = ['praet:sg:m1:perf','subst:pl:acc:n']

zipped = [list(items) for items in zip(l1,l2)]

print(zipped)

Result:
[['Hello', 'praet:sg:m1:perf'], ['world', 'subst:pl:acc:n']]

A: There are many ways to do that.
ex-1: by using '+'
list1=['Hello', 'world']
list2 = ['praet:sg:m1:perf','subst:pl:acc:n']

print([list1]+[list2])

ex-2: by using append()
res =[]
list1=['Hello', 'world']
list2 = ['praet:sg:m1:perf','subst:pl:acc:n']

res.append(list1)
res.append(list2)
print(res)

ex-3: by using zip()
list1=['Hello', 'world']
list2 = ['praet:sg:m1:perf','subst:pl:acc:n']

res = [[l1, l2] for l1,l2 in zip(list1, list2)]

print(res)

A: I hope this helps:
list1=['Hello', 'world']
list2 = ['praet:sg:m1:perf','subst:pl:acc:n']

newlist = []

for i in range(len(list1)):
   newlist.append([list1[i],list2[i]])

A: Just add the two list you have to another list:
list1 = ['Hello', 'praet:sg:m1:perf']
list2 = ['world', 'subst:pl:acc:n']

result = [list1, list2]

Another way:
result = []
list1 = ['Hello', 'praet:sg:m1:perf']
list2 = ['world', 'subst:pl:acc:n']

...

result.append(list1)
result.append(list2)

A: Use zip
list1=['Hello', 'world']
list2 = ['praet:sg:m1:perf','subst:pl:acc:n']

result = [[x, y] for x,y in zip(list1, list2)]

print(result)

Output:
[['Hello', 'praet:sg:m1:perf'], ['world', 'subst:pl:acc:n']]


text:
Q: Dialog shown in first activity, not the one that created the fragment I have a main activity and it starts a new activity. This new activity has a fragment which loads it's layout which only has a ListView (extended by my own TableListView):
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState)
        {
        View rootView = inflater.inflate(R.layout.list, container, false);
        lv = (TableListView) rootView.findViewById(R.id.list);
        return rootView;
        }

    // The Activity
@Override
protected void onCreate(Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.act_clients);
    findViewById(R.id.container).setBackgroundColor(Color.WHITE);
    list = new TableFragment();
    getFragmentManager().beginTransaction().add(R.id.container,list).commit();
    }

So far so good. But when I click an item in my TableListView I want to show a dialog box which is shown in the main activity (so it's only visible if I discard the current activity, either manually or with finish()!).
It's like the listview is created within a fragment which runs within the first activity. What could be wrong ?
Edit: It's not related to my custom ListView, still the same problem on an empty fragment.

A: I'd say your best bet would be to look into startActivityForResult() and onActivityResult() in the developer documentation.
Essentially, you'd start your new activity from your main one, and then when the new activity finishes you can send a certain amount of information back.  From there, you can determine whether you need to open an AlertDialog or not.

A: I found the answer. Dialogs originating from a fragment do not lock to the "current activity", so it's better to pass the dialog creation code to the activity that has loaded the fragment.


text:
Q: One or more screenshots are under 1280x720 pixels in resolution I am submitting my app to amazon store. My app passed all the test. But It is not submitting the app and says One or more screenshots are under 1280x720 pixels in resolution. I take the screen shots from nexus 7 device and all screenshots are of 800 × 1280.
Please help me how to take screenshots for amazon store?


text:
Q: Using grep to find and edit the correct form I have a website, built on a CMS (Ushahidi) that has built in translations. At the top right of each page is a drop down for 30+ languages. I'm trying to edit this so that only two languages remain: English and French.
In order to find which files to edit I have been using grep like so:
grep -Rl English pathtowebsite

I used the word English as a search term. This led me down a rabbit hole of files and directories that hold the language translations for each language option. I deleted all of them except English and French.
But, the form still gives options for all the languages. I am at a loss for what search term to use in order to find the form to edit.
Here is a sample of the html. How would I grep to find this form in order to remove the options for every language except English and French? The website in question is here, if it helps: http://tinyurl.com/c8djrvr
<div class="language-box"><form action="https://trashswag.com/main?l=uk_UA&l=en_GB" method="get">
<input type="hidden" name="l" value="en_GB"  />
<select id="l" name="l"  onchange="this.form.submit()" >
<option value="az_AZ">Azərbaycan dili (AZ)</option>
<option value="id_ID">Bahasa Indonesia (ID)</option>
<option value="bs_BA">Bosanski (BA)</option>
<option value="ca_ES">Català (ES)</option>
<option value="cy_GB">Cymraeg (GB)</option>
<option value="da">Dansk</option>
<option value="de_DE">Deutsch (DE)</option>
<option value="en_GB" selected="selected">English (GB)</option>
<option value="en_US">English (US)</option>
<option value="es_AR">Español (AR)</option>
<option value="es_CL">Español (CL)</option>
<option value="es_ES">Español (ES)</option>
<option value="es_PE">Español (PE)</option>
</select></form>
</div>

A: Ushahidi framework might provide you cleaner solution but purely talking about grep command you can use:
 grep -Rl 'English (.*)</option>' pathtowebsite

Update:
Actually this drop-down is being dynamically populated instead of coming directly from a file. It is coming directly from application/cache/kohana_configuration if you clear your cache directory after tweaking application/i18n you should be fine.

A: The documentation on the Ushahidi wiki tells us that the language dropdown is generated by looking at the the application/i18n directory. You should remove the corresponding folder for the languages you don't want to support from that directory.
Don't forget to clear the application cache by removing the contents of your application/cache folder after making the changes.
Wiki page:
https://wiki.ushahidi.com/display/WIKI/Localization


text:
Q: I'm unable to join chat in Safari on my iPhone when on my mobile network (O2) I'm aware that we have a nice lite version of chat for mobile clients, and I've seen reports that other people have it working quite nicely, so what am I doing wrong?

*

*I'm logged in successfully to chat.stackexchange.com (so the list of my favourite rooms is correct and populated).

*Visiting the Login Help page results in "All tests successful".

I can view the transcripts of rooms (which used to be the default view IIRC), however when I actually join a room (for example LEGO®) all that happens is I get a screen with "Loading LEGO® Just a second...".
This has always been the case for me, and happens on every room I try and join - are there any settings I can tweak here?
I'm using iOS 5.0.1 on an iPhone 4, connecting via O2 here in the UK - it seems to work OK when I turn on WiFi, but generally when I'm in range of a WiFi connection I'm happy to access, I'm also in range of a desktop or laptop computer ;)

Edit to add:
Turning on the debug console (thanks balpha, just to note in latest version it's "Settings -> Safari -> Advanced -> Debug Console) I get the following two errors:

*

*JavaScript: Error on Line 20
http://chat.stackexch...e.com/rooms/1653/lego
SyntaxError: Invalid regular expression: nothing to repeat

*JavaScript: Error
Undefined
ReferenceError: Can't find variable: StartChat

A: Since

*

*The error message says the error is happening in the page (i.e. not in an included JS file),

*we don't create regular expressions in the page,

*O2 UK, as we just learned yesterday among other things likes to put JavaScript into our pages if you download over 3G:

Another annoying feature of O2 is that they interfere with the responses from servers too. They downgrade all images and insert a javascript link into the HTML of each page.

*and you're saying it doesn't happen over WiFi
– I'm inclined to blame O2 UK for this.


text:
Q: include prevents other layout to be shown I have a layout which starts with an include to another layout and right after that there is a LinearLayout with two buttons in it.
The problem is that I don't see the layout with the two buttons after I added the include. But when I wrap the include with another layout, I do see the two buttons below the include and the problem is solved.
Can someone please tell me why I have to wrap the include?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <include
            android:id="@+id/keypad_layout"
            layout="@layout/keypad_layout" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/buttonAudio"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/button_audio_selector" />

        <Button
            android:id="@+id/buttonVideo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/button_video_selector" />
    </LinearLayout>

</LinearLayout>

A: try this
<include
            android:layout_height="wrap_content"
            android:id="@+id/keypad_layout"
            layout="@layout/keypad_layout" />

perhaps the layout_height in keypad_layout root is match_parent so override it in the include


text:
Q: Filtering a Wagtail index page by fields of the child pages (user-initiated query) / (FieldError at ... cannot resolve keyword) My Wagtail project is at heart just a very conventional listings page where users can browse items in the database and then click on any item of interest to go its detail page. But how do I allow users to filter and/or sort the listings on the main page by the contents of fields on the child pages? This most generic, ordinary task eludes me.
Let's say the database is a collection of Things. And let's say that what people find important about each Thing are (a) the year it was discovered, and (b) the country where it can be found. A user may want to browse through all the Things, but she should be able to narrow down the list to just those Things found in 2019 in Lithuania. And she should be able to sort by year or by country. Just your super-standard functionality but I can't find any guidance or figure it out myself.
Cribbing from examples of other people's work here are my models so far:
    class ThingsListingPage(Page):

        def things(self):
            ''' return all child pages, to start with '''
            things = self.get_children().specific()
               # do I need 'specific' above?
               # Is this altogether the wrong way to fetch child
               #    pages if I need to filter on their fields?
            return things

        def years(self, things): # Don't need things parameter yet
            '''Return a list of years for use in queries'''
            years = ['2020', '2019', '2018',]
            return years

        def countries(self, things):
            '''Return a list of countries for use in queries.'''
            countries = ['Angola', 'Brazil', 'Cameroon','Dubai', 'Estonia',]
            return countries

        def get_context(self, request):
            context = super(ThingsListingPage, self).get_context(request)
            things = self.things()

            # this default sort is all you get for now
            things_to_display = things.order_by('-first_published_at')

            # Filters prn
            has_filter = False
            for filter_name in ['year', 'country',]:
                filter_value = request.GET.get(filter_name)
                if filter_value:
                    if filter_value != "all":
                        kwargs = {'{0}'.format(filter_name): filter_value}
                        things_to_display = things_to_display.filter(
                            **kwargs)
                    has_filter = True

            page = request.GET.get('page') # is this for pagination?

            context['some_things'] = things_to_display
            context['has_filter'] = has_filter # tested on listings page to select header string
            context['page_check'] = page # pagination thing, I guess
            # Don't forget the data to populate filter choices on the listings page
            context['years'] = self.years(things)
            context['countries'] = self.countries(things)

            return context

    class ThingDetailPage(Page):

            year = models.CharField(
            max_length=4,
            blank=True,
            null=True,
        )

        country = models.CharField(
            max_length=50,
            blank=True,
            null=True,
        )
        CONTNT_PANELS = Page.content_panels + [
            FieldPanel('year'),
            FieldPanel('country'),
        ]
        # etc.

The template for the listings (index) page, showing only the filter controls (sorting controls are also required, and of course the listings themselves):
{% extends "base.html" %}
{% block content %}

    <form method="get" accept-charset="utf-8" class="filter_form">

          Years

Sub-categories

                  <input type="radio" name="year" value="all" id="filter_year_all"
                      {% if request.GET.year == "all" %}checked="checked" {% endif %} />All Years</input>

              {% for year in years %}

              <input type="radio" name="year" value="{{ year }}" id="filter_year_{{ year }}"
                {% if request.GET.year == year %}checked="checked" {% endif %} />{{ year }}</input>

              {% endfor %}

          Countries

Sub-categories

              <input type="radio" name="country" value="all" id="filter_country_all"
                  {% if request.GET.country == "all" %}checked="checked" {% endif %} />All Countries</input>

            {% for country in countries %}

                <input type="radio" name="country" value="{{ country }}" id="filter_country_{{ country|slugify }}"
                    {% if request.GET.country == country %}checked="checked" {% endif %} />{{ country }}</input>

            {% endfor %}

      <input type="submit" value="Apply Filters"/>
    </form>

{% endblock %}

The above Page models seem to work fine in Wagtail. I've created a ThingsListingPage page named "Things," and a set of child ThingDetailPage pages, each with 'year' and 'country' data. The pages display fine: The filters on the Things listings page display the (currently hard-coded) year and country items from the ThingsListingPage model. The listings page also lists the child pages on command. No complaints from the server.
But: Upon making my filter selections and clicking the submit / Apply filters button, I get an appropriate URL in the address bar (http://localhost:8000/things/?year=2019&country=Lithuania) but this error:
FieldError at /things/
Cannot resolve keyword 'year' into field.
(If I don't select a year filter but do filter on a country I get the same error on the 'country' keyword.)

SO:
How should I change the ThingsListingPage model so that I can filter on child page fields (fields of ThingDetailPage pages)? Or is there a completely different approach I should be taking, a better / everybody-knows-that's-how Wagtail way to do arbitrary, user-initiated filter and sort operations on a page's children's fields?
Just please note that in the real project there may be different page types for TinyThings, WildThings, and what not, so I'm looking for a solution that can be modified to work even when some children don't have the field(s) used in the filter(s).
I'd also appreciate any direction you might have on how sort operations should be done.

A: Page.get_children returns the results as basic Page instances where only the core fields such as title are available - this is because it has no way to know the expected page type of the children at the time of doing the query (see What is the difference between ChildPage.objects.child_of(self) and ParentPage.get_children()?). Adding .specific() will return the results as the more specific page types, but this won't help for filtering, since it works as a post-processing step after the main query has run (including applying any filters).
However, you can get around this by reorganising the query expression to specify the page type:
things = ThingDetailPage.objects.child_of(self)

Here, Django knows which specific page model to query on, and so all fields of ThingDetailPage are available for filtering.
This does limit you to a single page type, and there's no perfect way around that - at the database level each page type is handled by a separate table, and it's not possible to efficiently query data that's distributed over multiple tables. (Even if ThingDetailPage and TinyThingDetailPage both have a year field defined, those are distinct entities in the database, so there's not a single 'year' column that can be filtered on.) However, you may be able to restructure your models to accommodate this using multi-table inheritance. Just as Wagtail itself gives you a base Page model containing the fields common to all pages, you could define ThingDetailPage to contain the fields common to all Things (such as year) and have subtypes inheriting from that:
class TinyThingDetailPage(ThingDetailPage):
    size = models.CharField(...)

Your TinyThingDetailPages will then be included in the results of ThingDetailPage.objects.child_of(self), although they'll only be returned as instances of ThingDetailPage. Again, you can add .specific() to return them  in their most specific form, but this won't work for filtering - so you'll be able to filter on the fields common to ThingDetailPage (such as year) but not size.

A: The answer by @gasman succeeds perfectly. However, an alternative solution suggested by one of @gasman's linked posts is equally effective.
The @gasman answer above requires that child page objects be accessed through their own model (note that you need to append child_of(self) so that the query returns only those pages that belong to the current listings page:
    def things(self):
        ''' return all child pages, to start with '''
        things = ThingDetailPage.objects.child_of(self)
        return things

By querying the child page model in this way you can then access the fields of the child pages without any prefix. Thus, the get_context method in my models.py (see question) works as is. Specifically, these lines work without any changes:
     kwargs = {'{0}'.format(filter_name): filter_value}
     things_to_display = things_to_display.filter(**kwargs)

However, it seems it's just as valid to start with the listing page and retrieve its child pages, the way the query was written in my question:
    def things(self):
        ''' return all child pages, to start with '''
        things = self.get_children().specific()
        return things

But to make this work, you must then prefix your filters with the name of the child page model (with an obligatory two underscores connecting the model name with that of the field).
The filters functioned as expected and without error as soon as I added that:
    kwargs = {'{0}'.format('thingdetailpage__' + filter_name): filter_value}
    things_to_display = things_to_display.filter(**kwargs)

Based on these findings, I have some doubt about the explanation @gasman gives as to why my original code didn't work:

Adding .specific() will return the results as the more specific page
types, but this won't help for filtering, since it works as a
post-processing step after the main query has run (including applying
any filters).

Be that as it may, I'm adding this answer just to document an alternative solution, i.e., one that also seems to work. I have no reason to prefer the approach used in my question. Filters on child page fields now function.


text:
Q: Detecting duplicate entries in core data and removing them I have started to work on a core data project. The data to store in the database comes from the server and I am able to store it successfully into coredata. However, each fetch is resulting in duplicate entries. What is the best way to check whether the data exists in core data and append only if the data is not found.
Here is my implementation so far:
for (NSDictionary *dict in array) {
        DatabaseManagement *mo = [NSEntityDescription insertNewObjectForEntityForName:@"Subscription" inManagedObjectContext:context];
        [mo setValuesForKeysWithDictionary:dict];

The array contains nested dictionary with keys corresponding to my entities attribute names.
I know I can use NSPredicate to achieve this but can someone provide sample code or some resources?


text:
Q: Worklight: Issue while rendering dojo 1.9 widgets on actual device Environment:

*

*Worklight 6.0

*Dojo 1.9.1

*ADT 22.0

*API level 14

*Device - Samsung Tab 3

We have developed a mobile app using worklight 5.0 and dojo 1.8.
Now we have upgraded to worklight 6.0 and dojo 1.9. After upgrade we are seeing following issue while rendering dojo widgets.
The widgets are getting rendered fine in simulator (MBS). But on the actual device, the widgets are not getting rendered properly. The tab bar buttons are getting rendered as labels with bold underline etc.
The HTML file -

        <meta charset="UTF-8">
        <title>RQMOffline</title>
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <link rel="shortcut icon" href="images/favicon.png">
        <link rel="apple-touch-icon" href="images/apple-touch-icon.png">
        <link rel="stylesheet" href="css/MobileApp.css">
        <link rel="stylesheet" href="css/qmMobile.css"/>

Note: I have added all the android related css file under www folder.
This was working fine with dojo 1.8
Any help on this will be appreciated.

A: I fixed this issue by doing following changes -

*

*In dojox/mobile/deviceTheme.js, replaced "holodark" with "android" for all android devices.

*For bigger font size issue, added 'targetSdkVersion' attribute to  property in AndroidManifest.xml - <uses-sdk android:minSdkVersion="8"  android:targetSdkVersion="13"/>
Thanks all for your help.


text:
Q: How to display categories in magento? $category = Mage::getModel('catalog/category')->getCollection();
            $category->addAttributeToFilter("Top_Menu" , array('eq' => '146'));
            $category->addAttributeToFilter("entity_id" , array('eq' => $catId));
            $category->load();
            $category->getName();

When I use this code i get this error
Fatal error: Call to undefined method Mage_Catalog_Model_Resource_Category_Flat_Collection::getName()

A: A category collection is a collection of category objects.Therefore the category collection has no name. If you would like to get the first category from the category collection you can use the following method.
$category->getFirstItem()->getName();

However it seems like you don't need a collection for what you are trying to achieve. So I'd suggest you just use the loadByAttribute() method. See below
// Load by attribute value
$categoryWithTopMenuId146 = Mage::getModel('catalog/category')->loadByAttribute("Top_Menu","146");

// Get name
$categoryWithTopMenuId1460->getName();


text:
Q: Using R to obtain slope raster from DEM GRID raster After some extensive googling, I wasn't able to find my answer (first time I couldn't surmount the issue by looking at others questions/answers). I am new to asking questions, so forgive any missteps.
I am attempting to perform what ArcGIS or QGIS performs with the slope tool, just within R. To do so I have been importing a raster that I exported from ArcGIS in GRID format with the following characteristics:
class      : RasterLayer
dimensions : 821, 581, 477001  (nrow, ncol, ncell)
resolution : 4.996121, 4.996121  (x, y)
extent     : 2832147, 2835049, 14234048, 14238150  (xmin, xmax, ymin, ymax)
crs        : +proj=tmerc +lat_0=34.75 +lon_0=-118.583333333333 +k=0.9999 +x_0=800000.000000001 +y_0=3999999.99999999 +datum=NAD83 +units=us-ft +no_defs
source     : rr_2020_shell
names      : rr_2020_shell
values     : 5623.253, 6401.356  (min, max)

It is already projected in the correct coordinate system (EPSG: 3423) but when I go to find the slope using the following code:
RR_2020_Slope = terrain(RR_2020_St1_Raster,'slope', units = 'degrees', neighbors = 8, filename = 'RR_2020_Slope.grd', overwrite = T)

The result is a slope raster that ranges from 0 to 1.28°, which is very different from what I have calculated in ArcGIS using the slope tool. Using the same DEM raster in the same projection in ArcGIS I used the slope tool with an input of 'Degree' for the output measurement, 'Planar' for the method, and 1 for Z factor and my resulting slope raster ranges from 0.001 to 73.396°.
Overall I am wondering where my mistake in R originates from, is it an elevation resolution problem? Are there issues with my projection? Forgive me, I can't necessarily include the data as they are sensitive materials but perhaps there is a clear and obvious mistake in my approach or assumptions about the functions I have used?

A: The only red flag I see is that you say "it is already projected in the correct coordinate system". Projecting raster data degrades the quality. As cell values get smoothed, the slopes will get smaller. This may be particularly pronounced if the relief is at the scale of the cell size (e.g. sand dunes vs mountain chains). Have you compared with what you get with  the original data?
Another source of error could be that the units of the values are different from the units of the coordinate reference system. But it would appear that in your case both are in feet.
Can you also try this with terra::terrain()?


text:
Q: How to retrieve more than two values from the database I have a login table names login
I have written a stored procedure for the login.
Now what i need is while logging,the POST value of the particular emp_name should be stored in a Session.
can anyone help me with this?

A: just make a session like this (if php)
$_SESSION["emp_name"] = $_POST["emp_name"];


text:
Q: What is faster and less in memory in Java: int[] or boolean[]? In Java, what is faster and less in memory: int[n] or boolean[n] or maybe Bitset(n) ?
The question is applicable for arrays of small (n is up to 1000), medium (n is between 1000 and 100000) and huge (n is greater than 100000) sizes. Thank you.
I want to achieve flags (1/0) storage.

A: On most JVMs; an array or object has a 12-16 byte overhead.  An int use 4 bytes and a boolean uses a byte (it doesn't have to but it does with OpenJDK/HotSpot)  BitSet uses two objects and more memory for small sets, but only one bit per have. So for small collections an int[] can be smaller than a BitSet but as the size grows, BitSet will be the smallest.
If the data structure is smaller than your cache the fastest is int[] then boolean[] then BitSet This is because there is non-trival overhead in breaking int into byte or a bit.
However once your cache size becomes important, it can be that the overhead of BitSet fades compared to the overhead of using a slower cache or main memory.
In short: if in doubt use BitSet as this is clearer as to your intent and its likely to be faster.

A: Actually, it is JVM dependent. For example Sun JVM converts boolean type to int. That mean even boolean variable uses 32 bit. But jvm optimize boolean arrays, and reserve 8 bit per boolean array cell.

A: Java store boolean as int internally. So int[] and boolean[] is exactly the same.
BitSet use less memory. Faster or not depends on your usage pattern.

A: Descending order in memory usage
int[n] > Bitset(n) > boolean[n]

However, in accessing the indexes, there should not be any difference.

A: Consider to replace bit flags with enums. Then you can use e.g. EnumSet instead of Bitset.


text: Q: Is still true that every nonzero Prime Ideal is Maximal in a noncommutative PID? Basically what I said in the title: I can't find a proof that doesn't make use of commutativity. I know that Commutativity is generally taken for granted in a domain, but I wanted to know in general, since this not being true would break "PID implies Dedekind" in a noncommutative setting.


text:
Q: constant errors using insights Facebook marketing api (php) I get this error when I try to run my app locally via xampp. Just to note, I generated code using quick start from developers.facebook so there shouldnt be errors within the code itself.

Notice: Use of undefined constant STDOUT - assumed 'STDOUT' in C:\xampp\htdocs\working\vendor\facebook\php-ads-sdk\src\FacebookAds\Logger\CurlLogger.php on line 83
Warning: fwrite() expects parameter 1 to be resource, string given in C:\xampp\htdocs\working\vendor\facebook\php-ads-sdk\src\FacebookAds\Logger\CurlLogger.php on line 182
Fatal error: Uncaught exception 'FacebookAds\Http\Exception\AuthorizationException' with message '(#100) Filtering field delivery_info is invalid. Please refer to the document https://developers.facebook.com/docs/marketing-api/insights for valid filters.' in C:\xampp\htdocs\working\vendor\facebook\php-ads-sdk\src\FacebookAds\Http\Exception\RequestException.php:144 Stack trace: #0 C:\xampp\htdocs\working\vendor\facebook\php-ads-sdk\src\FacebookAds\Http\Client.php(215): FacebookAds\Http\Exception\RequestException::create(Object(FacebookAds\Http\Response)) #1 C:\xampp\htdocs\working\vendor\facebook\php-ads-sdk\src\FacebookAds\Http\Request.php(282): FacebookAds\Http\Client->sendRequest(Object(FacebookAds\Http\Request)) #2 C:\xampp\htdocs\working\vendor\facebook\php-ads-sdk\src\FacebookAds\Api.php(162): FacebookAds\Http\Request->execute() #3 C:\xampp\htdocs\working\vendor\facebook\php-ads-sdk\src\FacebookAds\Api.php(204): FacebookAds\Api->executeRequest(Object(FacebookAds\Http\Request)) #4 C:\xampp\htdocs\working\vendor\facebo in C:\xampp\htdocs\working\vendor\facebook\php-ads-sdk\src\FacebookAds\Http\Exception\RequestException.php on line 144

I'm starting to suspect that I got the wrong files from the composer. or there might be a problem with my setup. The contents of my composer.json just before I ran composer.phar was

{
   "require": {
     "facebook/php-sdk-v4" : "~5.0",
     "facebook/php-ads-sdk": "2.10.*"
   }
  }

I'm going to attach the code below just in case you guys want to look at it as well. The only thing that I modified there is adding the app_id since it was not included from the generated code.

<?php
require __DIR__ . '/vendor/autoload.php';

use FacebookAds\Object\AdAccount;
use FacebookAds\Object\AdsInsights;
use FacebookAds\Api;
use FacebookAds\Logger\CurlLogger;

$app_id = '274807576345457';
$access_token = 'EAAD575ZC4O3EBAChoTmxC0nwdbvjXLRUKGGXgmZA6HZBFjmKZB6F3olMIe2mG2dgQSb9SudtN7EeeO8gzo7zgFZB0EHZAwTrg4wsIKsJxB3bhw5fonZC3YCZA0C4InaCSOgW42i4PswQa3BZCctMZBYTh94TwGLxGg8gZAZAj4zZC5PfgXl0kw6eOuxW4g1L41NOwtRDGS7O7FsJZBWZCM0IAe00WSf';
$ad_account_id = 'act_113902719358005';
$app_secret = 'aeb42f19e0f33f0937c023fff12909c4';

$api = Api::init($app_id, $app_secret, $access_token);
$api->setLogger(new CurlLogger());

$fields = array(
  'cost_per_result',
  'cost_per_total_action',
  'cpm',
  'cpp',
  'frequency',
  'impressions',
  'impressions_auto_refresh',
  'impressions_gross',
  'reach',
  'relevance_score:score',
  'relevance_score:positive_feedback',
  'relevance_score:negative_feedback',
  'result_rate',
  'results',
  'social_impressions',
  'social_reach',
  'spend',
  'today_spend',
  'total_actions',
  'total_unique_actions',
  'actions:video_view',
  'video_10_sec_watched_actions:video_view',
  'delivery',
);
$params = array(
  'level' => 'campaign',
  'filtering' => array(array('field' => 'delivery_info','operator' => 'IN','value' => array('active','limited'))),
  'breakdowns' => array(),
  'time_range' => array('since' => '2017-09-28','until' => '2017-09-29'),
);
echo json_encode((new AdAccount($ad_account_id))->getInsights(
  $fields,
  $params
)->getResponse()->getContent(), JSON_PRETTY_PRINT);

A: if comment this part
[json_encode((new AdAccount($ad_account_id))->getInsights(
  $fields,
  $params
)->getResponse()->getContent(), JSON_PRETTY_PRINT);]

; the error stop.
if make [var_export((new AdAccount($ad_account_id));] show full array

A: I experienced the exact same error. I believe (in my case) this was because I was also using an older PHP version (5.6) resulting in some compatibility issues.
I solved this by changing the version of php-ads-sdk from 2.8 to "8.*" (or change it to any recent version according to when you are reading this solution) in composer.json.
Then call sudo composer update in your terminal


text:
Q: Add custom style property to MXML Custom Component I have a Custom Component that has a couple of Canvas with some background colors assigned to them. Now i have hard coded the colors, i want to move them to an external css file.
So i would like to have the css declaration like this :
ControlBar
{
  dividerRightColor: #ffffff;
  dividerLeftColor: #f3f3f3;
}

My question is if i can define custom style names like dividerRightColor and if so, how can i use that value inside my MXML Component? I have seen examples of using them inside Pure AS components.

A: In CSS:
.dividerRightColor {
    background-color: #ffffff;
}

.dividerLeftColor {
    background-color: #f3f3f3;
}

In MXML:
<mx:ControlBar>
    <mx:Canvas styleName="dividerLeftColor">
        …
    </mx:Canvas>

    <mx:Canvas styleName="dividerRightColor">
        …
    </mx:Canvas>
</mx:ControlBar>

A: It sounds to me like you need to create the style in the component; not just send the style values into the component as the other answer.
Read this documentation.
Basically, styles don't get defined the same way that properties get defined.  You can set any style name on the component you want.  However, the component needs to know what to do w/ the style.  To do that you need to override the styleChanged method:
override public function styleChanged(styleProp:String):void {

    super.styleChanged(styleProp);

    // Check to see if style changed.
    if (styleProp=="dividerRightColor")
    {
      // do stuff to implement the style
      dividerRight.setStyle('backgroundColor',getStyle('dividerRightColor'));
    }
}

A common approach is to set "styleChanged" properties and invalidate the display list and then make the appropriate style changes in the updateDisplayList() method.
To make the style available in code hinting, you'll need to add metadata, like this:
[Style(name="dividerRightColor")]

This will only be required if you wish to set the style as a property in MXML.


text:
Q: Magento 2 - Show product options and attributes in categories I need some help to display products custom options and attributes in category view, I can't find any guide to do this.
What I want to do is that if a simple product has custom options to display a list with those in the category view.
Also I'd like to show the products attributes there too, not all attributes but ones I've selected in the template with attribute codes.

A: As we need to override below file
From:
magento\vendor\magento\module-catalog\view\frontend\templates\product\list.phtml

To:
magento\app\design\frontend\Custom\YourTheme\Magento_Catalog\templates\product\list.phtml

Content:
 <?php foreach ($_productCollection as $_product): ?>
        <?php echo($iterator++ == 1) ? '
' : '

' ?>

            <?php
            // START DISPLAY ATTRIBUTE
            $attributeName = $_product->getResource()->getAttribute('your_attribute_name');
            if ($attributeName) {
                $labelValue = $attributeName->getFrontend()->getValue($_product);
            }
echo $labelValue;
            // END DISPLAY ATTRIBUTE
            ?>

    <?php endforeach; ?>

Please check from Main File & U can display your thing as needed & adjust as per your design.
Thanks.


text:
Q: Using ActiveRecord classes with legacy tables I have many legacy databases from which I need to pull raw data. Each of the tables in the database have arbitrary names, and an arbitrary collection of fields. I have been getting access to these fields with the following class:
class Frt < ActiveRecord::Base
  establish_connection :legacy
  set_primary_key "point"
end

When I reach the point in my code where I know the table name, I can call:
Frt.set_table_name "table"
t = Frt.find_by_sql("blah")
something = t.field_name + t.other_field_name
etc...

The problem is that I've realized that this locks the accessible field names to whatever table I select first. If I try to change the table with another call to the `set_table_name' method, it changes the attribute for the class, but any new instances will still have the same set of fields as the first one. So far, in my app, I've not needing anything else, but I'm expanding the program in a way in which I know it will bite me in the butt down the road.
I've tried `Frt.send :set_table_name "new_table"', hoping that it would cause ActiveRecord to do it's magic again. It doesn't.
Can anyone suggest how I might be able to keep the convenience of ActiveRecord, but get it to dynamically remap its fields for whatever table I need loaded?

A: I've never used it, but Magic Model Generator claims to create models for tables automatically.

A: Sorry to answer my own post, but I guess I didn't explain it very well. In case someone else comes along after this, what I needed to do was issue a call to the "Frt.reset_column_information" method. I was revisiting this issue, and just dumped all the methods on the ActiveRecord class, and found that one lurking in the list.

A: A better way to solve this would be to create a model for each legacy table you need to interact with - no dynamic table name remapping required, and it works right out of the box.


text:
Q: QGIS:When exporting a print layout as a .svg, the entire map gets exported I have a problem, I'm using QGis 3.2.3, when I make a print layout an put a map on it

, if I use some projections (in this case albert projection focused on canada), then export it as a .svg, the entire map gets exported  resulting in a very heavy vector file that is hardly usable. However if I export it as a picture, it works  and only shows what is inside the frame, furthermore I don't encounter this problem if use some other projection, like platte carree.
What am I doing wrong? Is this a glitch?


text:
Q: Loop through rows to populate Email body My current working Macro is:
Sub emailGenerator()

'Disable Screen Updating
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False

ThisWorkbook.Sheets("Email").Activate
Worksheets("Email").Visible = False
'ThisWorkbook.Sheets("P6").Activate

ActiveWorkbook.Save

Worksheets("Email").Visible = True
ThisWorkbook.Sheets("Email").Activate

Dim TempFilePath As String
Dim nameOfProject As String
Dim firstName As String

nameOfProject = Cells(3, 7)
firstName = Cells(4, 7)

'Create a new Microsoft Outlook session
Set appOutlook = CreateObject("outlook.application")
'create a new message
Set Message = appOutlook.CreateItem(olMailItem)

With Message
    .Subject = nameOfProject & " Programme Analytical Tool"

    .HTMLBody = "" _
    & "
" _
    & "Hi " & firstName & ",

Please find attached the analytical tool for " & nameOfProject & ". Commentary below:" _
    & "

" & " - " & Cells(7, 2) _
    & "
" & " - " & Cells(9, 2) _
    & "
" & " - " & Cells(11, 2) _
    & "
" & " - " & Cells(13, 2) _
    & "
" & " - " & Cells(15, 2) _
    & "
" & " - " & Cells(17, 2) _
    & "
" & " - " & Cells(19, 2) _
    & "
" & " - " & Cells(21, 2) _
    & "
" & " - " & Cells(23, 2) _
    & "
" & " - " & Cells(25, 2) _
    & "
" & " - " & Cells(27, 2) _
    & "
" & " - " & Cells(29, 2) _
    & "
" & " - " & Cells(31, 2) _
    & "

"

    'first we create the image as a JPG file
    'Call createJpg("GRAPHS", "B2:AA90", "OFGraph")
    'we attached the embedded image with a Position at 0 (makes the attachment hidden)
    TempFilePath = Environ$("temp") & "\"
    '.attachments.Add TempFilePath & "OFGraph.jpg", olByValue, 0
    .attachments.Add ActiveWorkbook.FullName
    '.attachments.Add "\\MSQFDC02\DFSRoot$\NW\NW08Groups\LNW North ASM Team\Incident Management Specialist\OUTSTANDING FAULT SUMMARIES\UNVERIFIED & OUTSTANDING FAULT SUMMARYs\DELIVERY UNITs\Closing of Faults Form.docx"

    'Then we add an html  link to this image
    'Note than you can customize width and height - not mandatory

    '.HTMLBody = .HTMLBody _
        '& "
"
'        & "
"

    .To = firstName
    .CC = ""

    .Display
End With

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True

End Sub

I want to make those lines that are under the .HTMLBody more dynamic so I can add in more lines in the Excel sheet without having to re-visit the macro and tell it to read this specific line.
"        & "" & " - " & Cells(x, 2) _"
Here's my attempt to make it dynamic and adding a loop, but not sure where it went wrong and it's highlighted as red.

This is how the sheet looks like:


text:
Q: Reopen same socket for reuse C++ I am having an application which listens on a particular RPC Port number say 10001 for connection with another device(hardware) using socket programming.
Meanwhile the hardware device will be trying to establish connection to my IP and same port number 10001.
So that way my application and the hardware are connected. Now assume i disconnect the network cable from my machine, my application would still be listening on port number 10001, however it wont receive any connection.
Now if i reconnect the network again then is it possible for me to reuse the same socket which i was using earlier for communicaiton with the hardware.
Do i sound confusing
Thanks

A: Once an established socket connection has been disconnected, you cannot reuse that socket.  You must close that socket and allocate a new socket for a new connection.
However, pulling out the network cable on the listening end should not have any effect on the existing listening socket being able to accept new connections once the cable has been put back in.  If it is not able to do that, then your OS's socket stack is likely faulty.


text:
Q: symbol's value as variable is void: php-executable I'm getting the following warning printed on the minibuffer when I try to use php-auto-yasnippets by pressing C-c C-y into Emacs
symbol's value as variable is void: php-executable

I'm using Ubuntu 14.04 with php5-cli. I did use setq in my emacs configuration file to set the variable to the proper path
(add-to-list 'load-path "~/.emacs.d/site-lisp")
(add-to-list 'load-path "~/.emacs.d/elpa/yasnippet-0.8.0")
(require 'php-auto-yasnippets)
(setq php-auto-yasnippet-php-program "~/.emacs.d/site-lisp/Create-PHP-YASnippet.php")

I know this issue has been addressed with other modules but I'm not skilled with lisp programming to fix php-auto-yasnippets module. Any help is greatly appreciated

A: It looks like the php-auto-yasnippets code has a dependency on php-mode written by the same author. You could either follow the instructions provided in the php-mode repository for installing it and then require it ahead of the php-auto-yasnippets package, like this:
(add-to-list 'load-path "~/.emacs.d/site-lisp")
(add-to-list 'load-path "~/.emacs.d/elpa/yasnippet-0.8.0")
(require 'php-mode)
(require 'php-auto-yasnippets)
(setq php-auto-yasnippet-php-program "~/.emacs.d/site-lisp/Create-PHP-YASnippet.php")

Or you might instead just try setting the php-executable variable first, but not sure this will address other as-yet-unknown dependencies:
(add-to-list 'load-path "~/.emacs.d/site-lisp")
(add-to-list 'load-path "~/.emacs.d/elpa/yasnippet-0.8.0")
(setq php-executable "/usr/bin/php")
(require 'php-auto-yasnippets)
(setq php-auto-yasnippet-php-program "~/.emacs.d/site-lisp/Create-PHP-YASnippet.php")


text:
Q: Two column layout Here is what I'm trying to do.
I have two columns. Let's call them col1 and col2. I want it so that if the height of col2 increases, the height of col1 will increase accordingly to the same height. How can I achieve this?
I know that I can do it using tables, but I'm looking for a css-based solutions.

A: There are a ton of tutorials on Google:
http://www.google.ca/search?sourceid=chrome&ie=UTF-8&q=same+height+columns
Other stuff here:
Equal height columns in jQuery

A: As CSS - Equal Height Columns? already explains the best resource probably is http://matthewjamestaylor.com/blog/perfect-multi-column-liquid-layouts
Basically you have wrappers around your columns and they become your actual backgrounds and not the columns themselves.

A: You can fake it with an image using the faux columns technique, but you can do it just with CSS - http://jsfiddle.net/spacebeers/s8uLG/3/
You set your container up with overflow set to hidden, then on each div add negative margin-bottom and equal positive padding-bottom.
#container { overflow: hidden; }
#container div { float: left; background: #ccc; width: 200px; margin-bottom: -2000px; padding-bottom: 2000px; }
#container .col2 { background: #eee; }

Content 1

Content 2

Content 2

Content 2

Content 2

EDIT: If you want a border round it then have a look at this example - http://www.ejeliot.com/samples/equal-height-columns/example-6.html


text:
Q: Fastest way to generate binomial coefficients I need to calculate combinations for a number.
What is the fastest way to calculate nCp where n>>p?
I need a fast way to generate binomial coefficients for an polynomial equation and I need to get the coefficient of all the terms and store it in an array.

(a+b)^n = a^n + nC1 a^(n-1) * b + nC2 a^(n-2) * ............
  +nC(n-1) a * b^(n-1) + b^n

What is the most efficient way to calculate nCp ??

A: If you want complete expansions for large values of n, FFT convolution might be the fastest way. In the case of a binomial expansion with equal coefficients (e.g. a series of fair coin tosses) and an even order (e.g. number of tosses) you can exploit symmetries thus:
Theory
Represent the results of two coin tosses (e.g. half the difference between the total number of heads and tails) with the expression A + A*cos(Pi*n/N). N is the number of samples in your buffer - a binomial expansion of even order O will have O+1 coefficients and require a buffer of N  >=  O/2 + 1 samples - n is the sample number being generated, and A is a scale factor that will usually be either 2 (for generating binomial coefficients) or 0.5 (for generating a binomial probability distribution).
Notice that, in frequency, this expression resembles the binomial distribution of those two coin tosses - there are three symmetrical spikes at positions corresponding to the number (heads-tails)/2. Since modelling the overall probability distribution of independent events requires convolving their distributions, we want to convolve our expression in the frequency domain, which is equivalent to multiplication in the time domain.
In other words, by raising our cosine expression for the result of two tosses to a power (e.g. to simulate 500 tosses, raise it to the power of 250 since it already represents a pair), we can arrange for the binomial distribution for a large number to appear in the frequency domain. Since this is all real and even, we can substitute the DCT-I for the DFT to improve efficiency.
Algorithm

*

*decide on a buffer size, N, that is at least O/2 + 1 and can be conveniently DCTed

*initialise it with the expression pow(A + A*cos(Pi*n/N),O/2)

*apply the forward DCT-I

*read out the coefficients from the buffer - the first number is the central peak where heads=tails, and subsequent entries correspond to symmetrical pairs successively further from the centre

Accuracy
There's a limit to how high O can be before accumulated floating-point rounding errors rob you of accurate integer values for the coefficients, but I'd guess the number is pretty high. Double-precision floating-point can represent 53-bit integers with complete accuracy, and I'm going to ignore the rounding loss involved in the use of pow() because the generating expression will take place in FP registers, giving us an extra 11 bits of mantissa to absorb the rounding error on Intel platforms. So assuming we use a 1024-point DCT-I implemented via the FFT, that means losing 10 bits' accuracy to rounding error during the transform and not much else, leaving us with ~43 bits of clean representation. I don't know what order of binomial expansion generates coefficients of that size, but I dare say it's big enough for your needs.
Asymmetrical expansions
If you want the asymmetrical expansions for unequal coefficients of a and b, you'll need to use a two-sided (complex) DFT and a complex pow() function. Generate the expression A*A*e^(-Pi*i*n/N) + A*B + B*B*e^(+Pi*i*n/N) [using the complex pow() function to raise it to the power of half the expansion order] and DFT it. What you have in the buffer is, again, the central point (but not the maximum if A and B are very different) at offset zero, and it is followed by the upper half of the distribution. The upper half of the buffer will contain the lower half of the distribution, corresponding to heads-minus-tails values that are negative.
Notice that the source data is Hermitian symmetrical (the second half of the input buffer is the complex conjugate of the first), so this algorithm is not optimal and can be performed using a complex-to-complex FFT of half the required size for optimum efficiency.
Needless to say, all the complex exponentiation will chew more CPU time and hurt accuracy compared to the purely real algorithm for symmetrical distributions above.

A: This is my version:
def binomial(n, k):
if k == 0:
    return 1
elif 2*k > n:
    return binomial(n,n-k)
else:
    e = n-k+1
    for i in range(2,k+1):
        e *= (n-k+i)
        e /= i
    return e

A: I recently wrote a piece of code that needed to call for a binary coefficient about 10 million times. So I did a combination lookup-table/calculation approach that's still not too wasteful of memory. You might find it useful (and my code is in the public domain). The code is at
http://www.etceterology.com/fast-binomial-coefficients
It's been suggested that I inline the code here. A big honking lookup table seems like a waste, so here's the final function, and a Python script that generates the table:
extern long long bctable[]; /* See below */

long long binomial(int n, int k) {
    int i;
    long long b;
    assert(n >= 0 && k >= 0);

    if (0 == k || n == k) return 1LL;
    if (k > n) return 0LL;

    if (k > (n - k)) k = n - k;
    if (1 == k) return (long long)n;

    if (n <= 54 && k <= 54) {
        return bctable[(((n - 3) * (n - 3)) >> 2) + (k - 2)];
    }
    /* Last resort: actually calculate */
    b = 1LL;
    for (i = 1; i <= k; ++i) {
        b *= (n - (k - i));
        if (b < 0) return -1LL; /* Overflow */
        b /= i;
    }
    return b;
}

#!/usr/bin/env python3

import sys

class App(object):
    def __init__(self, max):
        self.table = [[0 for k in range(max + 1)] for n in range(max + 1)]
        self.max = max

    def build(self):
        for n in range(self.max + 1):
            for k in range(self.max + 1):
                if k == 0:      b = 1
                elif  k > n:    b = 0
                elif k == n:    b = 1
                elif k == 1:    b = n
                elif k > n-k:   b = self.table[n][n-k]
                else:
                    b = self.table[n-1][k] + self.table[n-1][k-1]
                self.table[n][k] = b

    def output(self, val):
        if val > 2**63: val = -1
        text = " {0}LL,".format(val)

        if self.column + len(text) > 76:
            print("\n   ", end = "")
            self.column = 3
        print(text, end = "")
        self.column += len(text)

    def dump(self):
        count = 0
        print("long long bctable[] = {", end="");

        self.column = 999
        for n in range(self.max + 1):
            for k in range(self.max + 1):
                if n < 4 or k < 2 or k > n-k:
                    continue
                self.output(self.table[n][k])
                count += 1
        print("\n}}; /* {0} Entries */".format(count));

    def run(self):
        self.build()
        self.dump()
        return 0

def main(args):
    return App(54).run()

if __name__ == "__main__":
    sys.exit(main(sys.argv))

A: If you really only need the case where n is much larger than p, one way to go would be to use the Stirling's formula for the factorials. (if n>>1 and p is order one, Stirling approximate n! and (n-p)!, keep p! as it is etc.)

A: The fastest reasonable approximation in my own benchmarking is the approximation used by the Apache Commons Maths library: http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/special/Gamma.html#logGamma(double)
My colleagues and I tried to see if we could beat it, while using exact calculations rather than approximates.  All approaches failed miserably (many orders slower) except one, which was 2-3 times slower.  The best performing approach uses https://math.stackexchange.com/a/202559/123948, here is the code (in Scala):
var i: Int = 0
var binCoeff: Double = 1
while (i < k) {
  binCoeff *= (n - i) / (k - i).toDouble
  i += 1
}
binCoeff

The really bad approaches where various attempts at implementing Pascal's Triangle using tail recursion.

A: nCp = n! / ( p! (n-p)! ) =
      ( n * (n-1) * (n-2) * ... * (n - p) * (n - p - 1) * ... * 1 ) /
      ( p * (p-1) * ... * 1     * (n - p) * (n - p - 1) * ... * 1 )

If we prune the same terms of the numerator and the denominator, we are left with minimal multiplication required. We can write a function in C to perform 2p multiplications and 1 division to get nCp:
int binom ( int p, int n ) {
    if ( p == 0 ) return 1;
    int num = n;
    int den = p;
    while ( p > 1 ) {
        p--;
        num *= n - p;
        den *= p;
    }
    return num / den;
}

A: You cau use dynamic programming in order to generate binomial coefficients
You can create an array and than use O(N^2) loop to fill it
C[n, k] = C[n-1, k-1] + C[n-1, k];

where
C[1, 1] = C[n, n] = 1

After that in your program you can get the C(n, k) value just looking at your 2D array at [n, k] indices
UPDATE smth like that
for (int k = 1; k <= K; k++) C[0][k] = 0;
for (int n = 0; n <= N; n++) C[n][0] = 1;

for (int n = 1; n <= N; n++)
   for (int k = 1; k <= K; k++)
      C[n][k] = C[n-1][k-1] + C[n-1][k];

where the N, K - maximum values of your n, k

A: If you need to compute them for all n, Ribtoks's answer is probably the best.
For a single n, you're better off doing like this:
C[0] = 1
for (int k = 0; k < n; ++ k)
    C[k+1] = (C[k] * (n-k)) / (k+1)

The division is exact, if done after the multiplication.
And beware of overflowing with C[k] * (n-k) : use large enough integers.

A: I was looking for the same thing and couldn't find it, so wrote one myself that seems optimal for any Binomial Coeffcient for which the endresult fits into a Long.
// Calculate Binomial Coefficient
// Jeroen B.P. Vuurens
public static long binomialCoefficient(int n, int k) {
    // take the lowest possible k to reduce computing using: n over k = n over (n-k)
    k = java.lang.Math.min( k, n - k );

    // holds the high number: fi. (1000 over 990) holds 991..1000
    long highnumber[] = new long[k];
    for (int i = 0; i < k; i++)
        highnumber[i] = n - i; // the high number first order is important
    // holds the dividers: fi. (1000 over 990) holds 2..10
    int dividers[] = new int[k - 1];
    for (int i = 0; i < k - 1; i++)
        dividers[i] = k - i;

    // for every dividers there is always exists a highnumber that can be divided by
    // this, the number of highnumbers being a sequence that equals the number of
    // dividers. Thus, the only trick needed is to divide in reverse order, so
    // divide the highest divider first trying it on the highest highnumber first.
    // That way you do not need to do any tricks with primes.
    for (int divider: dividers) {
       boolean eliminated = false;
       for (int i = 0; i < k; i++) {
          if (highnumber[i] % divider == 0) {
             highnumber[i] /= divider;
             eliminated = true;
             break;
          }
       }
       if(!eliminated) throw new Error(n+","+k+" divider="+divider);
    }

    // multiply remainder of highnumbers
    long result = 1;
    for (long high : highnumber)
       result *= high;
    return result;
}

A: If I understand the notation in the question, you don't just want nCp, you actually want all of nC1, nC2, ... nC(n-1). If this is correct, we can leverage the following relationship to make this fairly trivial:

*

*for all k>0: nCk = prod_{from i=1..k}( (n-i+1)/i )

*i.e. for all k>0: nCk = nC(k-1) * (n-k+1) / k

Here's a python snippet implementing this approach:
def binomial_coef_seq(n, k):
    """Returns a list of all binomial terms from choose(n,0) up to choose(n,k)"""
    b = [1]
    for i in range(1,k+1):
        b.append(b[-1] * (n-i+1)/i)
    return b

If you need all coefficients up to some k > ceiling(n/2), you can use symmetry to reduce the number of operations you need to perform by stopping at the coefficient for ceiling(n/2) and then just backfilling as far as you need.
import numpy as np

def binomial_coef_seq2(n, k):
    """Returns a list of all binomial terms from choose(n,0) up to choose(n,k)"""

    k2 = int(np.ceiling(n/2))

    use_symmetry =  k > k2
    if use_symmetry:
        k = k2

    b = [1]
    for i in range(1, k+1):
        b.append(b[-1] * (n-i+1)/i)

    if use_symmetry:
        v = k2 - (n-k)
        b2 = b[-v:]
        b.extend(b2)
    return b

A: Time Complexity : O(denominator)
Space Complexity : O(1)
public class binomialCoeff {
    static double binomialcoeff(int numerator, int denominator)
    {
        double res = 1;
        //invalid numbers
        if (denominator>numerator || denominator<0 || numerator<0) {
            res = -1;
            return res;}
        //default values
        if(denominator==numerator || denominator==0 || numerator==0)
            return res;

        // Since C(n, k) = C(n, n-k)
        if ( denominator > (numerator - denominator) )
            denominator = numerator - denominator;

        // Calculate value of [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1]
        while (denominator>=1)
        {

        res *= numerator;
        res = res / denominator;

        denominator--;
        numerator--;
        }

        return res;
    }

    /* Driver program to test above function*/
    public static void main(String[] args)
    {
        int numerator = 120;
        int denominator = 20;
        System.out.println("Value of C("+ numerator + ", " + denominator+ ") "
                                + "is" + " "+ binomialcoeff(numerator, denominator));
    }

}


text:
Q: Least-square fit with uneven distribution of data I'd like to perform least-squares fit to data which is unevenly distributed on the x-axis.
For example, if I was to bin the data, it would be something like
x = 0~5: 10 data points
x = 5~10: 20 data points
x = 10~15: 2 data points
x = 15~20: 4 data points
I want to fit a best-fit to this to predict future values, but the model of course performs poorly for high values of x.
I can bin the data as above and then assign weights to the data based on the density (sparsity) of values in each bin. These weights can then be used to weight the contribution to the total error by each point, but I wonder: Is this the standard way of dealing with this problem, or is there another method?
Incidentally, I will be implementing this using a python library, so any advice about practical implementation is also appreciated.
Thank you for any advice!
Edit: Added a picture for illustration.
Left: Well-distributed points leading to a reasonable estimation for all x.
Right: Points distributed to lower-x values, leading to poor estimation of y at high-x values

A: Assuming that some data is redundant simply because they are similar in value (on the x-axis) then your approach is correct (if ignoring issues of outliers).  The technique you are looking for is called Kernel density estimation.  The kernel bandwidth should be chosen based on the context of the data.  If x-values within a certain distance are to be considered redundant then the bandwidth of the kernel should be wide enough to include any two values within that distance.  Then you can use the inverse of the density estimation as the weights used in the least-squared regression.
Two dimensional kernel's can be used if two points can be considered non-redundant even though they have the same x-value.  (e.g. a single point in the top left of your graph would have the same weight as the values in the top right.)

A: You can use cubic splines. One advantage of splines over standard polynomial regression is that data points influence is more local. This is due to irregularity at knots.


text:
Q: Smallest possible difference between AUC of two ranker If there are 10 positive examples, and 90 negative examples in the test set, what is the smallest possible difference in AUC, between two rankers giving different AUC?

A: If rankers aren't allowed to give ties, then the minimum positive differences in AUROC for two rankers on a population with $N$ negative and $P$ positives examples is $1/(NP)$.  The ROC space for such a population is a $(N+1)\times(P+1)$ grid of points, because the true positive rate and false positive rate have denominators $P$ and $N$ respectively.  Without ties, the ROC curves consist of axis-aligned segments joining these points, and so the area is a collection of full grid squares (there are $N\times P$ such squares).  Finding two curves that differ in exactly one square is pretty easy.
If rankers are allowed to give ties, then the minimum positive difference is $1/(2NP)$, from a simple observation related to Pick's theorem, namely that a polygon with integer coordinates has half-integer area.  Scaling our grid to integers and back, the 1/2 gets scaled by $1/(NP)$.  Then it's just up to us to find two curves realizing that.  The perfect ROC curve and one almost-perfect one works, namely having just the two nontrivial points $(FPR, TPR)=(0, 1-1/P)$ and $(1/N, 1)$.  In terms of the ranking, that's something like $(0<0<\dotsc<0<0<1=0<1<1<\dotsc<1)$.


text:
Q: How to programmatically set appointment's recipient display name in Outlook without creating a contact in address book I am trying to achieve setting programmatically the display name of an appointment's recipient in Outlook without creating a contact for him. The desired result would be the following:

which can be achieved through Outlook UI by double clicking on the respective address in Address book dialog and setting the display name in the following dialog:

Using the following code, adds the new recipient to the Outlook appointment but does not set the required display name:
var appointmentItem = outlookApplication.ActiveInspector() as AppointmentItem;
var newRecipient = appointmentItem.Recipients.Add("john_smith@example.com");
newRecipient.AddressEntry.Name = "John Smith";

Any ideas how this can be achieved?

A: Pass the name in the form "John Smith <john_smith@example.com>".