text:
Q: Почему функция генерации случайных строк в цикле не срабатывает? Функция генерации рандомных строк в цикле генерирует только одну строку и заполняет массив. При этом если смотреть через отладку, то все нормально.
static string GetRandomString(int Length)
{
    string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    Random rnd = new Random();
    StringBuilder sb = new StringBuilder(Length - 1);
    int Position = 0;

    for (int i = 0; i < Length; i++)
    {
        Position = rnd.Next(0, Alphabet.Length - 1);
        sb.Append(Alphabet[Position]);
    }
    return sb.ToString();
}

    string[] s = new string[10];
    for (int i = 0; i < 10; i++)
    {
        s[i] = GetRandomString(6);
    }

A: Смотрите. Вычисление случайных чисел происходит так. У генератора есть текущее число (seed), которое инициализируется при создании Random. При вычислении следующего числа seed преобразуется по какому-то закону, и из нового значения seed строится выдаваемое наружу случайное число.
При этом, понятно, если начальные значения seed одинаковые, то и вся последовательность случайных чисел тоже будет одинаковой.
Судя по всему, вы пользуетесь .NET Framework, а в нём конструктор new Random() инициализирует генератор случайных чисел текущим временем.
А поскольку ваш цикл выполняется очень быстро, то текущее время не успевает «тикнуть», так что у всех ваших вызовов начальные значения seed одинаковы. Поэтому и последовательности тоже одинаковы.
Из документации:

Инциализация нескольких генераторов случайных чисел в цикле или подряд создаёт генераторы, которые скорее всего произведут одинаковые последовательности случайных чисел. В большинстве случаев это не то, на что вы рассчитываете [...].
Чтобы одновременно и улучшить производительность, и избежать создания генераторов, генерирующих одну и ту же последовательность чисел, мы рекомендуем создать один объект Random, и генерироваить с его помощью много случайных чисел, вместо того, чтобы создавать много генераторов, и генерировать каждым из них понемногу.

В .NET Core описанного эффекта нет: Random() берёт случайный seed, не привязанный ко времени, поэтому данная проблема не возникла бы.

Что делать? Используйте общий экземпляр Random. Например, так:
static Random rnd = new Random(); // общий экземпляр
static string GetRandomString(int Length)
{
    string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    StringBuilder sb = new StringBuilder(Length - 1);
    int Position = 0;

    for (int i = 0; i < Length; i++)
    {
        Position = rnd.Next(0, Alphabet.Length - 1);
        sb.Append(Alphabet[Position]);
    }
    return sb.ToString();
}

Или переходите на .NET Core.

A: Псевдослучайный генератор выдает одинаковые последовательности, при создании в сходных условиях, цикл очень быстро проходит - условия не успевают измениться. Можно объявлять так:
Random rnd = new Random(unchecked((int)(DateTime.Now.Ticks)));

Или создайте экземпляр Random вне функции и передавайте его параметром.
Должно помочь.


text:
Q: Using Stack for variable allocation mips I am trying to convert c functions into mips assembly code as a practice.
I was trying to allocate the space on stack for local variables & function arguments. But I get alignment errors at run time. I know that the memory should be aligned with appropriate data structure (i.e. if we want to store a word to memory, the word address should be a multiple of 4 is my understanding and similar for half words).
My problem is I am unable to figure it out how to handle this issue during a run time growing stack?
my c code is
int main(void){
int i, j;
i = 0;
j = 300;
foo(1, i, j);
return 0;
}
int foo(char a, int b, int c){
int x, y, z;
x = a+b;
y = c-a;
z = x+y;
return z;
}

My assembly code is
    .text
init:   li $sp, 0x1002FFFF  #initialize sp here
main:
    addi $sp, $sp, -4   #allocate two 16 bit ints on stack (i,j local vars)
    sh $zero, 1($sp)    #i = 0 (i is always sp + 1)
    li $t0, 300     #move 300 to reg to init j (j is always sp + 3)
    sh $t0, 3($sp)      #j = 300

    li $a0, 1       #load agruments of func foo in the arg regs
    lh $a1, 1($sp)      #load value of i
    lh $a2, 3($sp)      #load value of j
    jal foo         #call function
    move $a0, $v0       #move return value in a0 for disp
    li $v0, 1
    syscall
exit:
    li $v0, 10
    syscall

foo:    #There are alignment errors in ths code
    #storing the values of args & local var is done in this code
    #this is of no use in this currently but will help
    #in case if recurssion or other function calls are done in this fn
    addi $sp, $sp, -15  #15B allocated on stack for (RA + ARG + Local Vars
    sw $ra, ($sp)       #store return address starting from addr sp to sp+3 4B
    sb $a0, 4($sp)      #store 1st arg (char a)
    sh $a1, 5($sp)      #store 2nd arg (int b)
    sh $a2, 7($sp)      #store 3rd arg (int c)
    add $t0, $a0, $a1   #Write function body starts (value of x computed)
    sh $t0, 9($sp)      #store value of x
    sub $t1, $a2, $a0   #calc Y = c - a
    sh $t1, 11($sp)     #store value of Y
    add $t0, $t0, $t1   #Calc Z = X + Y
    sh $t0, 13($sp)     #store value of Z
    move $v0, $t0       #store return value in v0 (Z val)
    lw $ra, ($sp)       #pop return address from the stack
    addi $sp, $sp, 15   #Deallocate args from the stack
    jr $ra          #jump to return address

A: Take a look at the MIPS calling convention here.
In particular, functions with four or fewer arguments pass the arguments in registers $a0,...,$a3. The stack pointer must always be four byte aligned, even when saving a value smaller than four bytes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I add a template into the header panel? Magento-2.1.7 Porto Template I created the modified default.xml and created headerContent.phtml to add new content to the header panel to be position on the opposite side of the login and welcome msg.  However, after uploading, modifying and clearing all caches, my new content isn't showing up on the page at all.

Vendor/Theme_name/Magento_Theme/layout/default.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="header.panel">
            <block class="Magento\Framework\View\Element\Template" name="header.content" template="Magento_Theme::headerContent.phtml" before="header.links" />
        </referenceContainer>
    </body>
</page>

Vendor/Theme_name/Magento_Theme/templates/headerContent.phtml

Hello World!

What am i doing wrong? did i use the wrong location or a typo somewhere?

A: You have missed out html in the template path.
So change
template="Magento_Theme::headerContent.phtml"

To
template="Magento_Theme::html/headerContent.phtml"


text:
Q: highlight event that spans weekend on mouseover I have set up my fullcalendar to display a mixture of 1 day events (shown in one color) and week-long events(shown in diff color). I wanted to improve the visibility of events as it can get confusing with lots of overlapping events, so i set it up so that an event is highlighted with yellow border on mouseover.
This all works ok, except when i have an event that spans over a weekend - ie. starts on wednesday, ends on following wednesday - on mouseover the event is only highlighted for the current week - the portion of the event that falls after the weekend, is not highlighted,
any help would be greatly appreciated !

A: Ok,
I got this working.
fullcalendar.js generates a unique id for each event -> event._id (_fc1, _fc2...etc)
Each event is represented by an anchor tag (). An event that spans over a weekend is represented by 2 anchor tags. The unique id for each event is not outputted in the html by fullcalendar.js so it is impossible to see which anchors are associated with which events.
I made a small change to fullcalendar.js which adds the unique id of each event to the anchor being generated (as an additional css class name)
This means that all anchor tags associated with an event can be selected in the mouseover event using the JQuery class selector.
 eventMouseover: function (event, jsEvent, view) {
        $("." + event._id).each(function (index) {
            $(this).css('border-color', 'yellow');
        });
    },

works for me !

A: There could be a better way, but I found a way that does not touch the source:

*

*Add a unique css class for each event.

*When rendering, even if the event stretches across weekends, the class is applied to all segments.

*When user clicks an event:

$("." + calEvent.className).addClass('red');

Side note: When you drag an event, the other segments, belonging to the same event, are hidden, so fullCalendar is aware of the other segments, but I have not found a way to access them through the API.


text:
Q: Detect Keyboard Input with ES3? Alright, I have perhaps a bit of a toughie for my...second ever StackOverflow question. Below is a hefty bit of background on my issue. Here is the TLDR: can I, using native Javascript, ActiveX objects, and through that PowerShell, capture keyboard input without popping up a window or using HTML?
BACKGROUND - I'm working in a specific game engine. Said game engine uses ES3, with apparently a few features of ES5 tacked on such as array.indexOf(), for plugin development. It's really not pretty, but recently some folks and I discovered we can still create ActiveXObjects, run powershell through that, and so forth. Through this, we're managing all kinds of things - the next step is, hopefully, to capture keyboard input.
Natively, the engine - SRPG Studio - can only detect a limited number of inputs, assigned starting at -1 for nothing, -2 for mouse, and 0 through 11 for Left, Up, Right, Down, and various other keys that are assignable in a config file once you export a game or demo. You cannot, natively, detect other keys - they use a hidden "root" command, root.isInputState(), which returns true or false if the value is from 0 to 11, and always returns true if it's higher, or always false if it's lower. I cannot see the code of the function itself, but I have tested various numbers, to the point of crashing the Test Play feature by inputting a number that is too large for it to parse - 30501850151. At random keypresses.
That was all background, and I apologize for how much there is. The question is as follows:
Can I detect and capture keyboard input using ActiveX or Powershell, using a method that will not require jQuery, NodeJs, or in fact any such additional modifications, as well as not using HTML, as the engine reads it as bad syntax? It would aid us in creating a communications interface for a recently developed PvP plugin.
Thank you for your time.


text:
Q: Kafka Producer, multi DC failover support I have two distinct kafka clusters located in different data centers - DC1 and DC2. How to organize kafka producer failover between two DCs? If primary kafka cluster (DC1) becomes unavailable, I want producer to switch to failover kafka cluster (DC2) and continue publishing to it? Producer also should be able to switch back to primary cluster, once it is available. Any good patterns, existing libs, approaches, code examples?

A: Each partition of the Kafka topic your producer is publishing to has a separate leader, often spread across multiple brokers in the cluster, so the producer is connected to many "primary" brokers simultaneously. Should any one of them fail another In Sync Replica (ISR) will be  elected as leader and automatically take over. You do not need to do anything in your client app for it to reconnect to the new leader(s), retry any failed requests, and continue.
If this is for Multi-Data Center (MDC) failover then things get much more complicated depending on if the client apps die as well or if they keep running and need just their cluster connections to failover. Offsets are not preserved across multiple Kafka clusters so while producers are simpler, consumers need to call GetOffsetsForTimes() upon failover.
For a great write up of the the MDC failover modes and best practices see the MDC Whitepaper here: https://www.confluent.io/white-paper/disaster-recovery-for-multi-datacenter-apache-kafka-deployments/
Since you asked only about producers, your app can detect if the primary cluster is down (say for a certain number of retries) and then instead of attempting to reconnect, it can instead connect to another brokerlist from the secondary cluster. Alternatively you can redirect the dns name of the brokerlist hosts to point to the secondary cluster.


text:
Q: Merging imported class with namespace in TypeScript Valid:
class InputField {

}

namespace InputField {
  export enum Types {
    text = "text",
    number = "number"
  }
}

export { InputField };

Invalid:
import InputField from "@Controls/InputFields/InputField.vue";
// TS2440: Import declaration conflicts with local declaration of 'InputField'

namespace InputField {
  export enum Types {
    text = "text",
    number = "number"
  }
}

export { InputField };

How can I merge imported InputField class with namespaceInputField (and reexport it)?
How I'll use the result
import { Vue, Component, Prop } from "vue-property-decorator"
import { InputField } from "@Components/..."

@Component({
  //              Usage as namespace    ↓↓↓
  template: `<InputField type="InputField.Types.number" />`,
  components: {
    InputField // Usage as Vue component
  }
})
export default class Application extends Vue {
  // Provide access from template
  private InputField: typeof InputField = InputField;
}

Why I need this
declare module "*.vue" {
  import Vue from "vue";
  export default Vue;
}

Because of this, TypeScript does not see the public fields of imported classes in .vue files

A: You can circumvent this *.vue as VueContructor<Vue> issue by proxiing it via a *.ts file:
import DefaultImportClass, {componentOptions} from "@/source/index.vue"
import {Component} from "vue-property-decorator"

@Component<exportClassName>(componentOptions)
class exportCalssName extends DefaultImportClass {}
namespace exportClassName {}

export {exportClassName}

BUT
You can use static to achive the same result as done via namespace:
enum Types {
  Text: "text",
  Number: "number"
}

@Component
export class InputFieldTypes extends Vue {
  static Types = Types
}

A: Limitation
@Component({
  template: `<input type="HTML_Type" />`
})
export default class InputField extends Vue {

  //              Vue will not see this !! ↓↓
  @Prop({ default: InputField.Properties.Types.text, type: String })
  private readonly HTML_Type!: string;
}

namespace InputField {
  export enum Types {
    text = "text",
    number = "number"
  }
}

It could be solved by static fields.


text:
Q: mysql group by with latest record per day Table Name : Log
id      |   userid  |       loginDate       |   type    |
---------------------------------------------------------
1       |   1       |   2017-07-01 00:05:50 |   1       |
2       |   1       |   2017-07-01 06:06:50 |   2       |
3       |   2       |   2017-07-01 06:34:50 |   3       |
4       |   3       |   2017-07-01 06:56:76 |   1       |
5       |   2       |   2017-07-01 15:46:52 |   2       |
---------------------------------------------------------

I have a table like this. so i need to filter last login type count per day
i tried the following query
SELECT
  DATE(logindateindividual) AS loginlocaldate,
  typeofattendanceforday    AS typeofattendance,
  count(*)                  AS count
FROM (SELECT
        DATE(logindate) AS logindateindividual,
        type            AS typeofattendanceforday,
        count(*)        AS count
      FROM log
      WHERE logindate BETWEEN '2017-07-01 00:00:00' AND '2017-07-31 23:59:59'
      GROUP BY CAST(logindate AS DATE), type, userid) AS data
GROUP BY data.logindateindividual;

but it is not giving the latest type.
If a user had more than one login then it is counting the
Result i am getting for above query is
loginlocaldate   |   typeofattendance   |   count   |
-----------------------------------------------------
   2017-07-01    |    1                 |    5      |
-----------------------------------------------------

My Expectation is
loginlocaldate   |   typeofattendance   |   count   |
-----------------------------------------------------
   2017-07-01    |    1                 |    1      |
-----------------------------------------------------
   2017-07-01    |    2                 |    2      |
-----------------------------------------------------


text:
Q: Preview document history I seemingly open 5 documents for every one document I close in preview (I do a lot of reading with preview).
Is there a way to have preview reopen all of the documents I had opened last time it was closed (for example, when I want to restart my computer to grab an update), regardless of the number of opened documents? Sometimes the history just isn't enough for me or the history doesn't reflect what I presently have open.
If not, can you suggest an alternative?

A: Acrobat Reader has an option to open PDFs from the last session. You may give that a test drive since it's free. Launch Acrobat Reader and go to the file menu. 2nd option down reads "Reopen PDFs from last session". This may do what you want.


text:
Q: Aggregating according to factor levels in R (create new columns?) I have an array of dates and an array of categories. I want to aggregate the array of categories by dates, counting the occurrences. If I just do:
array <- aggregate(array$category,by=list(array$date),FUN="length")

I will get the occurrences of all the categories. I want the occurrences per factor of the category.
I have several data, each with its own category. It varies from 5 to 9 categories, and in each date, you can have different categories.
An example data is:
category dateop
   3 05/07/2012
   3 05/07/2012
   4 05/07/2012
   4 05/07/2012
   4 05/07/2012
   4 05/07/2012
   5 05/07/2012
   5 05/07/2012
   5 05/07/2012
   3 05/07/2012
   3 05/07/2012
   3 05/07/2012
   3 03/07/2012
   1 04/07/2012
   5 05/07/2012
   5 05/07/2012
   5 05/07/2012
   5 05/07/2012
   5 05/07/2012
   3 05/07/2012

I guess that I have to create new arrays that will keep the occurrences of each category. I have written a function that does a for loop over each level and creates a new array, but I was wondering if there was a faster (and with less code) way to do this.
Thank you!

A: Here are two possible simple solutions (I'll call your data set df, though it's not any better name than array)
library(data.table)
setDT(df)[, .(occurrences  = .N), .(date, category)]

#          date category occurrences
# 1: 05/07/2012        3           6
# 2: 05/07/2012        4           4
# 3: 05/07/2012        5           8
# 4: 03/07/2012        3           1
# 5: 04/07/2012        1           1

Or
library(dplyr)
df %>%
  group_by(date, category) %>%
  summarise(occurrences = n())

# Source: local data table [5 x 3]
# Groups: date
#
#         date category occurrences
# 1 05/07/2012        3           6
# 2 05/07/2012        4           4
# 3 05/07/2012        5           8
# 4 03/07/2012        3           1
# 5 04/07/2012        1           1

Or with base R
df$occurrences <- 1
aggregate(occurrences ~ date + category, df, sum)
#         date category occurrences
# 1 04/07/2012        1           1
# 2 03/07/2012        3           1
# 3 05/07/2012        3           6
# 4 05/07/2012        4           4
# 5 05/07/2012        5           8

And @akruns uber vectorized solution
subset(as.data.frame(table(df[2:1])), !!Freq)


text:
Q: tsql order by with distinct for xml path I have a query that I use later to do a dynamic pivot. I'd like to order this query before doing the distinct. How could I achieve this? Whenever I order this it breaks the distinct completely.
    DECLARE @cols NVARCHAR(max);
SET @cols = STUFF
(
    (SELECT distinct ',' + c.[PivotColumnTitle]
        FROM [myTable] c
        WHERE c.Id = @idInput
        AND c.IsPivotVisible = 1
              --order by c.PivotColumnOrder
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)')
    ,1,1,''
)

A: Try this:
DECLARE @cols NVARCHAR(max);

SET @cols = STUFF
(
    (
        SELECT ',' + c.[PivotColumnTitle]
        FROM [myTable] c
        WHERE c.Id = @idInput
            AND c.IsPivotVisible = 1
        GROUP BY c.[PivotColumnTitle]
        order by MAX(c.PivotColumnOrder)
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)')
    ,1,1,''
)


text:
Q: Rails cache and user specific content Lets say I have a next view:
<% cache ['v1', post] do %>

        <%= render post.author %>
        <%= post.body %>

<% end %>

This will work fine, but how do I implement a caching in case I need to show Delete, Edit links for the Admin user - something like:
<% cache ['v1', post] do %>

        <%= render post.author %>
        <%= post.body %>

    <% if @admin? %>
        <%# Content specific for Admin %>
    <% end %>
<% end %>

The only idea I have is to add a parameter to the Caching Key - Simple User or Admin - then they will have a different caches. Is it a right way to go?

A: Add current_user to the cache call:
<% cache ['v1', current_user, post] do %>

        <%= render post.author %>
        <%= post.body %>

    <% if @admin? %>
        <%# Content specific for Admin %>
    <% end %>
<% end %>

A: There are several possibilities. You can decide to skip the cache if the user is admin, or to append another parameter to the cache path.
This is the second solution.
<% cache ['v1', post, "admin:#{admin?}"] do %>

    <%= render post.author %>
    <%= post.body %>

  <% if @admin? %>
    <%# Content specific for Admin %>
  <% end %>
<% end %>

The first one may be very helpful if you have different level of admin, or to ensure that admin always access the most fresh content.
Another possibility is to not render the link directly in the cached helper, but just leave a placeholder. Then, using an async call in AJAX, append the links or (generally speaking) all the admin features.


text:
Q: Proper way to regularly write to file which can be cleared by another process? I have a Python script that must write a new line (containing a number) to a file each second.
I have another program that will regularly need to archive that file, so it will probably move the file to another location (Python can for example re-create the file if it doesn't exist anymore), but any other solution is possible (the file can be copied, left in place and emptied f.e.).
What would be the proper way to ensure that everything happens atomically, i.e. that no data is lost?

A: You can try opening file with "w+" option , it will append data if file exist or create new one if file is not there.


text:
Q: Using a single button to show and hide text I don't know if this will be a duplicate, but I've tried multiple scripts (not just in jQuery, but also in Javascript) to try to get the job done. Here's the HTML:

  I will disappear!

<button id="togglebutton">
  Go!
</button>

And jQuery:
$('#togglebutton').click(function() {
    $('text').toggle('slow');
});

Click me to try the Fiddle
I hope you may be able to  find a solution. Thanks :D

A: use #test instead of test to select an id attribute in jquery

 $('#togglebutton').click(function() {
     $('#text').toggle('slow');
    });

  I will disappear!

<button id="togglebutton">
  Go!
</button>

A: Because you're selecting an ID, $('text') should be $('#text')

$('#togglebutton').click(function() {
  $('#text').toggle('slow');
});

  I will disappear!

<button id="togglebutton">
  Go!
</button>

A: You're missing the # sign for the text attribute.
$('#togglebutton').click(function() {
    $('#text').toggle('slow');
});


text:
Q: How to assign the root DNS as a folder I am wanting to change the root address of my domain to 31.xx.xxx.xx/folder/. How can I go about doing this?
I know that within the "zone file" I can edit the "A(host)" to the ip 31.xx.xxx.xx and that will work but I can not assign it as a folder!

A: What you're asking is impossible. DNS only maps domain names to IP addresses, like to allow a browser to find the web server (or to allow email software to find the target SMTP server, and so on). Next, the browser will tell the server for which domain it wants the web site; see What exactly happens when you browse a website in your browser?
Likewise, you cannot map some specific URL to another server, or map a domain to a specific port.
If your web server needs to handle requests for multiple domains, you need something called "virtual hosting", to map domains to folders. If you only have one domain, you somehow need to tell your web server to set the root of the website to the specific folder.


text:
Q: How to remove an element from style sheet in document header i have the following style sheet in my header tag that gets added in by a npm plugin i have to show and hide columns from
showhidecolumns
everything works fine except the bellow style sheet gets added to the header tag of my page which is fine but when i navigate away from that page and return  to the page again it still remembers the styles that was applied to it.
<style type="text/css">#elements-table-1 td:nth-child(1),#elements-table-1 th:nth-child(1),#elements-table-1 td:nth-child(2),#elements-table-1 th:nth-child(2){display:none}</style>

is there a way that i can remove the #elements-table-1 tag from the style sheet so that the style sheet is empty?


text:
Q: Can't access struct outside of function, out of scope EDITED  to write the whole code.
What I'm trying to solve is that once I get the data from Firebase, it displays the same data over and over (the amount of the array, in this case 0, 1, 2). The data is being retrieved correctly.

It seems to not be populating the array correctly when I update it on the local variable so I can use it when displaying the posts in the table view. This is the code:
import UIKit
import Firebase
import FirebaseAuth
import Foundation

class StylerSalonHomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var tableView:UITableView!
    var posts = [Post]()

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView = UITableView(frame: view.bounds, style: .plain)

        let cellNib = UINib(nibName: "PostTableViewCell", bundle: nil)
        tableView.register(cellNib, forCellReuseIdentifier: "postCell")

        view.addSubview(tableView)

        var layoutGuide:UILayoutGuide

        if #available(iOS 11.0, *){
            layoutGuide = view.safeAreaLayoutGuide
        }

        layoutGuide = view.safeAreaLayoutGuide

        tableView.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true
        tableView.topAnchor.constraint(equalTo: layoutGuide.topAnchor).isActive = true
        tableView.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor).isActive = true

        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableFooterView = UIView()

        observe()

        tableView.reloadData()

    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return posts.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell
        cell.set(post: posts[indexPath.row])
        return cell
    }

    internal func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
             return 180
     }

    @IBAction func handleLogout(_ target: UIBarButtonItem) {
        try! Auth.auth().signOut()
        self.dismiss(animated: false, completion: nil)
    }

    func observe() {
        let postsRef = Database.database().reference(withPath: "post")

                postsRef.observe(.value, with: { snapshot in
                    var tempPosts = [Post]()

                    for child in snapshot.children {
                        if let childSnapshot = child as? DataSnapshot,
                            let data = childSnapshot.value as? [String:Any],
                            let first_name = data["Author"] as? String,
                            let postTitle = data["title"] as? String,
                            let postDescription = data["description"] as? String,
                            let postUrl = data["postUrl"] as? String,
                            let postAddress = data["Address"] as? String,
                            let url = URL(string:postUrl)
                        {
                            let post = Post(author: first_name, postTitle: postTitle, postDescription: postDescription, postUrl: url, postAddress: postAddress)
                            tempPosts.append(post)

                        }
                    }

                    self.posts = tempPosts

                    // HERE IT WORKS
                    print(self.posts[0].postTitle , " 0")
                    print(self.posts[1].postTitle , " 1")

                    self.tableView.reloadData()
                })
        // HERE IT DOESN'T WORK
        print(self.posts[0].postTitle , " 0")
    }

    func getDateFromTimeStamp(timestamp : Double) -> String {
        let date = Date(timeIntervalSince1970: timestamp)
        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = TimeZone(abbreviation: "GMT") //Set timezone that you want
        dateFormatter.locale = NSLocale.current
        dateFormatter.dateFormat = "HH:mm" //Specify your format that you want
        let strDate = dateFormatter.string(from: date)

        return strDate
    }

}

The function that I have to access my data and store it into the var posts = [Post]() is observe() but if you notice the comments there, I can't call the array outside of that function, could that be the problem? When I do, it says: Thread 1: Fatal error: Index out of range
I believe that the error is accessing the data outside of postsRef.observe(.value, with: { snapshot in

A: Without seeing all your code I can't be totally sure, but I think this is a timing issue.
Until you run observe() you won't have any observer on the database, and then it won't populate any data in the updatePosts.posts array until (1) there is a database change that triggers a snapshot and (2) the closure completes processing the snapshot.
Where  are you calling observe()? Is it before viewDidLoad runs and tries to print out the array contents?  And are you confident that a snapshot will be received and processed by the time viewDidLoad runs?  Otherwise in viewDidLoad you are trying to index items in the posts array that don't yet exist, which is why you are getting index out of range errors.
What are you trying to achieve in viewDidLoad that means you need to access the posts array as there might be another approach that avoids this issue?


text:
Q: Zend framework deployment on the shared hosting I want to deploy my project made in zend framework to my shared hosting.
My project has such structure:
application
docs
library
Obsolete
public
scripts
tests
This is what I have done:

*

*I copied Zend folder (all library files) into library folder

*I copied all the structure above into public_html/projects/project
(so if I type www.mydomain.com/projects/project/public I run the project

*I tried to click on some link so that it redirected me to www.mydomain.com/projects/project/public/someController/someAction
Unfortunately all i see is a white, empty page.
Locally (using Zend server CE) it worked perfectly
Here it looks like Zend doesn't recognize that it should do anything with this url and redirecto to appropriate action.
What have I missed?
Greetings!

A: The reason you see empty page instead of errors is that error_reporting is probably off by default on your production server.
You may change the settings concerting displaying errors and exceptions in application.ini.
The other cases the errors are not displayed is something goes wrong in the view (eg. view helpers), which must return string, not the exception.
Things to check:

*

*paths

*include_path

*permissions to write for files/dirs which do require this

*PHP version

*.htaccess setup

A: stating the obvious here but I'd check your apache error log.

A: You should check if the server is running php as a module or CGI, in the later case it will not read the SetEnv of .htaccess and you will have to set to development mode in index.php by hand, or specify your config in php.ini


text: Q: What is the real difference between GWT app and Vaadin pure-client app? Are there any additional binding or server-client communication techniques or any other advantage rather than using client widgets like VButton/VTextEdit e.t.c?


text:
Q: Play 2.0 Framework - find all that haven't expired I'm trying to figure out how I can go about finding members of a list - but only ones that haven't past their expired date - which is one of the properties of the model.
Right now I have:
public static Result getAllNotifications() {
 List<Notification> notifications = Notification.getAllNotifications();

 for (Notification i: notifications) {
     List<Attachments> attachments = Attachments.findAllById(i.id);
     i.attached = attachments;
 }

    return ok(toJson(notifications));
}

Somewhere in there I need to check the expiration date of an individual notification and not return it if today is past that date.
Right now that model for a notificatin looks like this:
public class Notification extends Model {

/**
 *
 */
private static final long serialVersionUID = 1L;

@Id
@NonEmpty
public Long id;

@Constraints.Required
public String title;

@Formats.DateTime(pattern = "dd/MM/yyyy")
public Date created = new Date();

@Constraints.Required
@Column(columnDefinition="TEXT")
public String text;

@Formats.DateTime(pattern = "dd/MM/yyyy")
public Date updated = new Date();

public Boolean status;

public Date expires;

public String author;

public List<Attachments> attached;

public Notification() {
}

public Notification(Long id, String title, String text) {
    this.created = new Date();
    this.title = title;
    this.text = text;
    this.id = id;
}

public static Model.Finder<String, Notification> find = new Model.Finder<String,     Notification>(String.class, Notification.class);

This is my first ever Stackoverflow post so go easy on me! And thank you, in advance, for the help!

A: Hm, you're looking for all rows which expires date is bigger than current one OR it's null (not set), right?
In such case you can just use simple DB comparission (iterating whole resultset is definitely WRONG idea!)

*

*gt stands for Greater Than

*lt for Lower Than
in your model add finders:
// If expires date is grater than current one, the Notification IS expired
public static List<Notification> findAllExpired() {
    return find.where().gt("expires", new Date()).findList();
}

// If expires date is lower than current one OR isn't set at all,
// the Notification is valid.
public static List<Notification> findAllNotExpired() {
    return find.where().or(
              Expr.lt("expires", new Date()),
              Expr.isNull("expires")
           ).findList();
}

So you'll get the list not expired (or not expired) notifications in your controller:
List<Notification> notExpiredList = Notification.findAllNotExpired();

// check in terminal
for (Notification notification : notExpiredList) {
    Logger.info("This Notification IS NOT expired: " + notification.title);
}

List<Notification> expiredList = Notification.findAllExpired();

// check in terminal
for (Notification notification : expiredList) {
    Logger.warn("This Notification IS expired: " + notification.title);
}

A: You could use an iterator and remove all notifications that are expired.
something like this:
    public static Result getAllNotifications() {
      List<Notification> notifications = Notification.getAllNotifications();

      Iterator<Notification> iterator = notifications.iterator();

      while (iterator.hasNext()) {
        Notification next = iterator.next();
        if (new Date().after(next.expires)) {
            iterator.remove();
        }
      }

      for (Notification i: notifications) {
        List<Attachments> attachments = Attachments.findAllById(i.id);
        i.attached = attachments;
      }

      return ok(toJson(notifications));
  }

if the List is immutable you could return a filtered copy of it.


text:
Q: DFP returning empty vast files (ads) I am using DFP to serve ads, and fiddler to monitor the requests.
After 3 GET requests to the dfp server, in a short period of time (say 30 seconds), every subsequent request will a list of empty ads.
Does DFP have some sort of spam protection? if so, is there a way around it? debugging an ad implementation is quite slow when you're ad payloads are empty!

A: There is definitely some rate limiting going on within DFP... I have run into this many times! I think it may be per ad unit from what I can tell... and it doesn't last very long....
As for debugging have your tried the DFP google console? That makes debugging a lot easier... and I am pretty sure it will give you the diagnostics you need to debug without the rate limit being an issue.

A: Have you looked into adding a "corrolator" value in the parameters?
Just &c=rand(10000,99999).


text:
Q: Android Application Stops When Animation Added i am  beginner in android and coding small game  Intro screen. My problem is that when  i add some basic animation to intro screen there is no output and application stops with popup like this  ,
and when i comment animation method it shows simple xml  based layouts please help me where is problem  here is my java file
public class MainActivity extends Activity
{
TextView  logo ;
TextView bottom  ;
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    animate();
}
public void animate()
{
    logo=  (TextView) findViewById(R.id.toplogo);
    bottom =(TextView) findViewById(R.id.footer);
    Animation fade1= AnimationUtils.loadAnimation(this, R.anim.fade_in);
    logo.setAnimation(fade1);

    Animation fade2=  AnimationUtils.loadAnimation(this, R.anim.fade_in2);
    bottom.setAnimation(fade2);

    fade2.setAnimationListener(new AnimationListener(){

        @Override
        public void onAnimationEnd(Animation animation)
        {
           startActivity(new  Intent(MainActivity.this, Menu.class));
           MainActivity.this.finish();
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onAnimationStart(Animation animation) {
            // TODO Auto-generated method stub
    }}
    );

 }
public void onpause()
{
    super.onPause();
    logo.clearAnimation();
    bottom.clearAnimation();
}
public void onResume()
{
    super.onResume();
    animate();
}

}
activity_main.xml file

<LinearLayout       xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@android:color/black"
>

<TextView
    android:id="@+id/toplogo"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello_world"
    android:textColor="@color/logoname"
    android:gravity="top|center"
    android:textSize="@dimen/logosize" />

<TableLayout
    android:id="@+id/TableLayout01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:stretchColumns="*" >

    <TableRow
        android:id="@+id/tableRow1"
         android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical|center_horizontal"
             android:minHeight="150px"
            >
        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_gravity="center_vertical|center_horizontal"
            android:src="@drawable/splash1"
              />

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical|center_horizontal"
            android:src="@drawable/splash2"
              />

    </TableRow>

    <TableRow
        android:id="@+id/tableRow2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="150px"

        >
         <ImageView
            android:id="@+id/imageView3"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_gravity="center_vertical|center_horizontal"
            android:src="@drawable/splash3" />

        <ImageView
            android:id="@+id/imageView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical|center_horizontal"
            android:src="@drawable/splash4" />
    </TableRow>

</TableLayout>

<TextView
    android:id="@+id/footer"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/logoname"
    android:textSize="@dimen/logosize"
    android:text="Done That "
    android:gravity="bottom|center"
    android:minHeight="120px"
     >
  </TextView>

   </LinearLayout>

animation files
   fade_in2.xml
   <?xml version="1.0" encoding="utf-8"?>
  <set  xmlns:android="http://schemas.android.com/apk/res/android"
 android:shareInterpolator="false">
  <alpha
    android:fromAlpha="0.0"
    android:toAlpha="1.0"
    android:duration="2500"
    android:startOffset="2500">
 </alpha>

 </set >

and same way fade_in.xml etc.  please  help me with the problem whats wrong with the logic/code  that its not working with animation ..
EDIT   Error log ..
i am not sure if i copied requred one or not please see this one ( i did select error in drop down from logcat tab)
04-06 20:18:25.996: E/AndroidRuntime(812): FATAL EXCEPTION: main
04-06 20:18:25.996: E/AndroidRuntime(812): android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.simplegame/android.view.Menu}; have you declared this activity in your AndroidManifest.xml?
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1618)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.app.Instrumentation.execStartActivity(Instrumentation.java:1417)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.app.Activity.startActivityForResult(Activity.java:3370)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.app.Activity.startActivityForResult(Activity.java:3331)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.app.Activity.startActivity(Activity.java:3566)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.app.Activity.startActivity(Activity.java:3534)
04-06 20:18:25.996: E/AndroidRuntime(812):  at com.example.simplegame.MainActivity$1.onAnimationEnd(MainActivity.java:41)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.view.animation.AnimationSet.getTransformation(AnimationSet.java:400)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.view.animation.Animation.getTransformation(Animation.java:940)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.view.View.drawAnimation(View.java:13205)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.view.View.draw(View.java:13344)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.view.ViewGroup.drawChild(ViewGroup.java:2928)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2797)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.view.View.draw(View.java:13715)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.view.View.draw(View.java:13596)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.view.ViewGroup.drawChild(ViewGroup.java:2928)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2797)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.view.View.draw(View.java:13715)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.widget.FrameLayout.draw(FrameLayout.java:467)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.view.View.draw(View.java:13596)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.view.ViewGroup.drawChild(ViewGroup.java:2928)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2797)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.view.View.draw(View.java:13594)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.view.ViewGroup.drawChild(ViewGroup.java:2928)
04-06 20:18:25.996: E/AndroidRuntime(812):  at an  droid.view.ViewGroup.dispatchDraw(ViewGroup.java:2797)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.view.View.draw(View.java:13715)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.widget.FrameLayout.draw(FrameLayout.java:467)
04-06 20:18:25.996: E/AndroidRuntime(812):  at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:2211)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.view.ViewRootImpl.drawSoftware(ViewRootImpl.java:2281)
04-06 20:18:25.996: E/AndroidRuntime(812):  at  android.view.ViewRootImpl.draw(ViewRootImpl.java:2177)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2045)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1854)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.view.Choreographer.doCallbacks(Choreographer.java:562)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.view.Choreographer.doFrame(Choreographer.java:532)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.os.Handler.handleCallback(Handler.java:725)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.os.Handler.dispatchMessage(Handler.java:92)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.os.Looper.loop(Looper.java:137)
04-06 20:18:25.996: E/AndroidRuntime(812):  at android.app.ActivityThread.main(ActivityThread.java:5041)
04-06 20:18:25.996: E/AndroidRuntime(812):  at java.lang.reflect.Method.invokeNative(Native Method)
04-06 20:18:25.996: E/AndroidRuntime(812):  at java.lang.reflect.Method.invoke(Method.java:511)
04-06 20:18:25.996: E/AndroidRuntime(812):  at  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-06 20:18:25.996: E/AndroidRuntime(812):  at     com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-06 20:18:25.996: E/AndroidRuntime(812):  at dalvik.system.NativeStart.main(Native       Method)

EDIT  FOR  Manifest.xml
 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.example.simplegame"
 android:versionCode="1"
 android:versionName="1.0" >

 <uses-sdk
 android:minSdkVersion="8"
 android:targetSdkVersion="17" />

 <application
 android:allowBackup="true"
 android:icon="@drawable/ic_launcher"
 android:label="@string/app_name"
 android:theme="@style/AppTheme" >
 <activity
  android:name="com.example.simplegame.MainActivity"
  android:label="@string/app_name" >
  <intent-filter>
  <action android:name="android.intent.action.MAIN" />
  <category android:name="android.intent.category.LAUNCHER" />
  </intent-filter>
  </activity>
  <activity android:name="Menu"></activity>
   </application>

  </manifest>

A: The problem is that you didn't declare the Activity in your Manifest
04-06 20:18:25.996: E/AndroidRuntime(812): android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.simplegame/android.view.Menu}; have you declared this activity in your AndroidManifest.xml?

UPDATED
add this to your manifest. and replace package name with your package name which is like com.etc.xxx
    <activity
        android:name="*package name*.Menu"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MENU" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

A: You did not create the activity in the AndroidManifest.xml.
This link should help you: Best way to add Activity to an Android project in Eclipse?
Remember Google is your friend, make an effort to learn things on your own, it will benefit you in the long run.

A:  <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.example.simplegame"
 android:versionCode="1"
 android:versionName="1.0" >

 <uses-sdk
  android:minSdkVersion="8"
  android:targetSdkVersion="17" />

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

   <activity
       android:name="com.example.simplegame.INTRO"
       android:label="@string/app_name" >
       <intent-filter>
         <action android:name="android.intent.action.MAIN" />
         <category android:name="android.intent.category.LAUNCHER" />
       </intent-filter>
   </activity>
   <activity
       android:name= "com.example.simplegame.Menu" <!-- java file-->
       android:label="@string/app_name">
       <intent-filter>
         <action android:name="thePackageOfTheLayoutsXmlFiles.MENU"/> <!-- layout -->
         <category androi:name = "android.intent.category.DEFAULT"/>
      </intent-filter>
   </activity>
 </application>
 </manifest>

in the manifest file you forgot to refernce the layout to the java file..
also, when you want to add a new activity to your app, you need to create a new xml file
for the layout.. and new java class, this class should extends the Activity
and then add to this class the onCreate() method..


text:
Q: Radiant CMS database mailer extension I am trying to use the Database mailer extension for my Radiant CMS application.
I have followed the exact same steps mentioned here.
http://blog.aissac.ro/radiant/database-mailer-extension/
When I try to run the rake task to migrate I get this error. I am fighting with this for a while now. Where and what am I missing?
Radiant version - 0.9
Database - mysql 5.0.75
Rails version - 2.3.5
This is my error log.
http://gist.github.com/524155

A: Someone made a fork of this extension and fixed this. I built on their work to fix a few additional bugs: https://github.com/mstalker/radiant-database-mailer-extension


text:
Q: Hiding an NSArray - how do I do it? I've got an NSArray setup in my code to display two PNG's alternately flashing, I'm trying to setup a piece of code that sets it to a hidden status, moves it off screen, anything to get it out of sight of the user.
The code for my array is
NSArray *imageArray = [[NSArray alloc] initWithObjects:
 [UIImage imageNamed:@"CONNECTED dark yellow FF CC 00.png"],
 [UIImage imageNamed:@"CONNECTEDR dark yellow FF CC 00.png"], nil];

UIImageView *animation = [[UIImageView alloc] initWithFrame: CGRectMake(20, 10, 300, 80)];
animation.animationImages = imageArray;
animation.animationDuration = .8;
animation.contentMode = UIViewContentModeBottomLeft;
[self.view addSubview:animation];
[animation startAnimating];
[animation release];
[view release];

However if I try using a setHidden or .hidden:YES it doesn't seem to hide and cries out that animation is not declared. Can anyone suggest the answer to this? Sure its staring me slap bang in the face but after a few hours of trying? I've admitted defeat for now.

A: hidden is not animate-able, as there is no animation possible between YES and NO. There is no way to express "A bit YES and a bit NO" in boolean logic.
Try using alpha instead
[aView setAlpha:1.0] // fully opaque
[aView setAlpha:0.0] // fully transparent

A: You have to keep a reference to the animation view (add a member/property to your view controller and add a code like _animationView = animation right before releasing it; and then use the _animationView instead of animation when trying to hide it).
Or you might set a tag to this view and find it by tag later...
I hope that I've understood your problem right - let me know otherwise.
EDIT (after your first response):
In MyViewController.h file:
class MyViewController : UIViewController {
    UIImageView *_animationView;
}

In MyViewController.m file:
NSArray *imageArray = [[NSArray alloc] initWithObjects:
 [UIImage imageNamed:@"CONNECTED dark yellow FF CC 00.png"],
 [UIImage imageNamed:@"CONNECTEDR dark yellow FF CC 00.png"], nil];

UIImageView *animation = [[UIImageView alloc] initWithFrame: CGRectMake(20, 10, 300, 80)];
animation.animationImages = imageArray;
animation.animationDuration = .8;
animation.contentMode = UIViewContentModeBottomLeft;
[self.view addSubview:animation];
[animation startAnimating];

// Add the next line
_animationView = animation;

[animation release];
[view release];

// Use this method to hide the animation view...
- (void)hideAnimationView {
    _animationView.hidden = YES;
    [_animationView stopAnimating];
}

EDIT 2:
Changed the declaration line in .h file (UIImageView *_animationView;)

A: Have you tried setting the alpha property on your animation UIImageView to zero? If you modify this property inside an animation block, it will do an animated fade out.


text:
Q: Strange Django/Apache 500 error when loading dynamically generated images (sometimes) I have a really strange Http500 error when loading dynamically generated images.  And for some reason it only happens sometimes.
The apache error log doesn't show any errors.
The django development server used to serve them fine in development.
Example from the logs:
174.255.117.79 - - [04/Feb/2013:12:00:46 -0600] "GET /images/gender/ HTTP/1.1" 500 531 "http://okstereotype.me/results/" "Mozilla/5.0 (Linux; U; Android 4.0.4; en-us; XT862 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30"
174.255.117.79 - - [04/Feb/2013:12:00:46 -0600] "GET /images/bodytype/ HTTP/1.1" 500 531 "http://okstereotype.me/results/" "Mozilla/5.0 (Linux; U; Android 4.0.4; en-us; XT862 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30"
174.255.117.79 - - [04/Feb/2013:12:00:46 -0600] "GET /images/religion/ HTTP/1.1" 200 30722 "http://okstereotype.me/results/" "Mozilla/5.0 (Linux; U; Android 4.0.4; en-us; XT862 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30"
174.255.117.79 - - [04/Feb/2013:12:00:46 -0600] "GET /images/smoking/ HTTP/1.1" 200 58577 "http://okstereotype.me/results/" "Mozilla/5.0 (Linux; U; Android 4.0.4; en-us; XT862 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30"
174.255.117.79 - - [04/Feb/2013:12:00:47 -0600] "GET /images/ethnicities/ HTTP/1.1" 500 531 "http://okstereotype.me/results/" "Mozilla/5.0 (Linux; U; Android 4.0.4; en-us; XT862 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30"
~

And sometimes they load:
192.168.1.4 - - [04/Feb/2013:12:11:20 -0600] "GET /images/gender/ HTTP/1.1" 500 531 "http://okstereotype.me/results/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:18.0) Gecko/20100101 Firefox/18.0"
192.168.1.4 - - [04/Feb/2013:12:11:20 -0600] "GET /images/religion/ HTTP/1.1" 200 41967 "http://okstereotype.me/results/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:18.0) Gecko/20100101 Firefox/18.0"
192.168.1.4 - - [04/Feb/2013:12:11:20 -0600] "GET /images/ethnicities/ HTTP/1.1" 200 44148 "http://okstereotype.me/results/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:18.0) Gecko/20100101 Firefox/18.0"
192.168.1.4 - - [04/Feb/2013:12:11:20 -0600] "GET /images/bodytype/ HTTP/1.1" 200 44471 "http://okstereotype.me/results/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:18.0) Gecko/20100101 Firefox/18.0"
192.168.1.4 - - [04/Feb/2013:12:11:20 -0600] "GET /images/smoking/ HTTP/1.1" 200 59910 "http://okstereotype.me/results/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:18.0) Gecko/20100101 Firefox/18.0"

The images are generated with a view:
(r'^images/(\w+)/$', mysite.views.show_pic)

And the view uses the PIL library to draw and save the image like so:
response = HttpResponse(mimetype="image/png")
img.save(response, "PNG")

All my static css is served correctly though.
Any ideas?

A: A good way to analyze the error would be making a copy of settings.py calling it "settings_test.py" for example. Then, set this copy to DEBUG=True and from a shell run - you can use some other port different than 80 or 443:
python manage.py runserver 0.0.0.0:5678 --settings relative.path.to.settings_test

or:
python django-admin.py runserver 0.0.0.0:5678 --settings relative.path.to.settings_test

Then, test it through this port (for instance: www.mydomain.com:5678/) and you will see a traceback if something happens. Even if it is a secondary GET/POST method that doesn't interfere with the mainpage's loading, you should see a traceback in the Shell like this.
Use Ctrl+C to interrupt the execution of runserver when you are done.


text:
Q: Find the place of max in array recursively c++ I have used this function to find the maximum element
It works for some cases but it got wrong place in other cases and this is the case i call function with.
int maxElement=maxi(names,noOfTeams,0,1,sum,0)

this is the function :
  int maxi(string names[],int sizee,int prev,int next,int scores[],int maxx)
{
    if (sizee ==1)return 0;
    if (scores[maxx]<scores[next]) maxx=next;
    if ((next+1)==sizee)return maxx;
    else return maxi(names,sizee,prev+1,next+1,scores,maxx);

}

A: Below could be a better approach:
Go through each element of the array, till there are elements left in the array which will be the base case.
Then in each function call check whether element at current index is greater than the element found at maxIndex if so update the max index and check for next array element by calling function again and so on.
Please find code below for both finding max element and max index recursively:
#include <iostream>

using namespace std;

int findMax(int arr[], int size,int index, int max);
int findMaxIndex(int arr[], int size,int index, int maxIndex);

int main()
{
    int arr[] = {5,2,8,1,4};
    int len = sizeof(arr) / sizeof(int);

    cout << "Max is: " << findMax(arr, len, 0, arr[0]) << endl;
    cout << "Max Index is: " << findMaxIndex(arr, len, 0, 0) << endl;

    return 0;
}

int findMax(int arr[], int size, int index, int max)
{
    if (index == size)
        return max;

    if (arr[index] > max)
        max = arr[index];

    return findMax(arr, size, index + 1, max);
}

int findMaxIndex(int arr[], int size, int index, int maxIndex)
{
    if (index == size)
        return maxIndex;

    if (arr[index] > arr[maxIndex])
        maxIndex = index;

    return findMaxIndex(arr, size, index + 1, maxIndex);
}

A: You have couple of errors in your function.

*

*The line
else if (scores[prev]<scores[next])maxx=next;

needs to be
else if (scores[maxx]<scores[next])maxx=next;
//              ^^^^

*You are missing a return in the recursive call. Instead of
else maxi(names,sizee,prev+1,next+1,scores,maxx);

it needs to be
else
   return maxi(names,sizee,prev+1,next+1,scores,maxx);

Also, the function can be simplified.

*

*The argument name is not used at all. It can be removed.

*The argument prev can be removed too.

*Couple of the checks you have can be combined into one.

*You don't need a chain of if-else-else statements.

Here's a simplified version.
int maxi(int sizee, int next, int scores[], int maxx)
{
   if ( sizee == next )
      return maxx;

   if (scores[maxx] < scores[next])
      maxx=next;

   return maxi(sizee, next+1, scores, maxx);
}

More importantly, it will be better to have an overload of the function:
int maxi(int sizee, int scores[]);

That should be the user facing function. The implementation of the user facing function can use the recursive function as an implementation detail.
int maxi(int sizee, int scores[])
{
   return maxi(sizee, 0, scores, 0);
}

See it working at http://ideone.com/chvtPA.

A: You need to compare scores[maxx] with scores[next], aslo you dont need prev
Change your function to
int maxi(string names[],int sizee,int next,int scores[],int maxx)
{
    if (sizee ==1)
        return 0;
    if (scores[maxx]<scores[next])
        maxx=next;
    if ((next+1)==sizee)
        return maxx;
    return maxi(names,sizee,next+1,scores,maxx);
    //You need to return, else the function will be called but that
    // value wont be returned.
}


text:
Q: Volume Integral of this set I'm not sure about this exercise. Be:
$$E=\left\{(x,y,z) \in \mathbb{R^3} : x\geq 0, y\geq 0, 0\leq z\leq \frac{1}{\sqrt{x^2+y^2}}-1\right\}$$
Find:
$$\int_{E} z\, \max\{x,y\}\: dx \, dy \, dz$$
My idea is that since $x,y\geq 0$, one of the two variables will be greater than the other in a section of the quadrant divided by the bisector and vice versa. For example, let's suppose that $x\geq y$, the  section of the volume would be something like:
$$\left\{(x,y,z)\in \mathbb{R^3}  : 0\leq x\leq \infty, 0\leq y\leq x,0\leq z\leq \frac{1}{\sqrt{x^2+y^2}}-1\right\}$$
The volume of this would be:
$$\int_0^\infty\int_0^x\int_0^{\frac{1}{\sqrt{x^2+y^2}}-1} zx\: dz\, dy\, dx$$
Then the volume of $E$ would be this volume plus the volume of the case where $y\geq x$, does this look correct to you?

A: Partial answer:
The upper limit of integration for the $x$ variable doesn't actually go to infinity. Note that the bounds for $z$ imply an additional constraint on the range of $x$ and $y$:
$$\begin{align}
0\le z\le\frac{1}{\sqrt{x^2+y^2}}-1
&\implies0\le\frac{1}{\sqrt{x^2+y^2}}-1\\
&\implies1\le\frac{1}{\sqrt{x^2+y^2}}\\
&\implies\sqrt{x^2+y^2}\le1\\
&\implies x^2+y^2\le1\\
&\implies0\le x\le1\land0\le y\le\sqrt{1-x^2}.\\
\end{align}$$
With the correct integration bounds for your triple integral, and strategically splitting up the integration intervals to eliminate the max functions, we find:
$$\begin{align}
I
&=\iiint_{E}\mathrm{d}^{3}v\,\left[z\max{\left(x,y\right)}\right]\\
&=\int_{0}^{1}\mathrm{d}x\int_{0}^{\sqrt{1-x^{2}}}\mathrm{d}y\int_{0}^{\frac{1}{\sqrt{x^2+y^2}}-1}\mathrm{d}z\,z\max{\left(x,y\right)}\\
&=\int_{0}^{\frac{1}{\sqrt{2}}}\mathrm{d}x\int_{0}^{\sqrt{1-x^{2}}}\mathrm{d}y\int_{0}^{\frac{1}{\sqrt{x^2+y^2}}-1}\mathrm{d}z\,z\max{\left(x,y\right)}\\
&~~~~~+\int_{\frac{1}{\sqrt{2}}}^{1}\mathrm{d}x\int_{0}^{\sqrt{1-x^{2}}}\mathrm{d}y\int_{0}^{\frac{1}{\sqrt{x^2+y^2}}-1}\mathrm{d}z\,z\max{\left(x,y\right)}\\
&=\int_{0}^{\frac{1}{\sqrt{2}}}\mathrm{d}x\int_{0}^{x}\mathrm{d}y\int_{0}^{\frac{1}{\sqrt{x^2+y^2}}-1}\mathrm{d}z\,z\max{\left(x,y\right)}\\
&~~~~~+\int_{0}^{\frac{1}{\sqrt{2}}}\mathrm{d}x\int_{x}^{\sqrt{1-x^{2}}}\mathrm{d}y\int_{0}^{\frac{1}{\sqrt{x^2+y^2}}-1}\mathrm{d}z\,z\max{\left(x,y\right)}\\
&~~~~~+\int_{\frac{1}{\sqrt{2}}}^{1}\mathrm{d}x\int_{0}^{\sqrt{1-x^{2}}}\mathrm{d}y\int_{0}^{\frac{1}{\sqrt{x^2+y^2}}-1}\mathrm{d}z\,z\max{\left(x,y\right)}\\
&=\int_{0}^{\frac{1}{\sqrt{2}}}\mathrm{d}x\int_{0}^{x}\mathrm{d}y\int_{0}^{\frac{1}{\sqrt{x^2+y^2}}-1}\mathrm{d}z\,xz\\
&~~~~~+\int_{0}^{\frac{1}{\sqrt{2}}}\mathrm{d}x\int_{x}^{\sqrt{1-x^{2}}}\mathrm{d}y\int_{0}^{\frac{1}{\sqrt{x^2+y^2}}-1}\mathrm{d}z\,yz\\
&~~~~~+\int_{\frac{1}{\sqrt{2}}}^{1}\mathrm{d}x\int_{0}^{\sqrt{1-x^{2}}}\mathrm{d}y\int_{0}^{\frac{1}{\sqrt{x^2+y^2}}-1}\mathrm{d}z\,xz.\\
\end{align}$$
Presumably you can take the helm from there?


text:
Q: Domains and tunneling connections with firefox I want to know when i use SSH and firefox if someone else can see the domains or any sites i log into (i like using ftp://user:pass@site.com). I like to know  the information so i can decide if going to a private (work) site from an untrusted site is a good idea or not.
At the very least i want to know if anyone at all can see me visit http://SiteWithBetaPhpAndAnUnsecureDB.com/Debug.php

A: What you want is to configure ssh to run as a SOCKS5 proxy and not just to do simple tunneling (-L) through it. The difference is in the DNS lookup. With the tunnel, the DNS lookup is done on the browser end, which may be insecure. With the SOCKS5 proxy, DNS lookup can be done on the secure remote end.
ssh -D 1080 user@remoteserver

Then in the firefox configuration, set network.proxy.socks_remote_dns = true in about:config. This forces the DNS to be handled on the remoteserver. This will even allow you to access non-public servers using their private names.
As Goyuix said, bonus points for using certificate based authentication and blocking everything else.

A: Generally, SSH will provide you with pretty good privacy - though there are a few pitfalls to be aware of:
First, depending on where you terminate (e.g. the server side) the SSH connection, anything on the other side of it could be watching your traffic.
Second, while the majority of your traffic will be routed over SSH, it is possible (and probable) that DNS lookups could happen outside of the SSH tunnel. That wouldn't give away the full URL granted, but if you are concerned about someone plunking around the server in general this isn't the best idea.
Best plan: Terminate the SSH connection on the network edge where your private server sits. Ideally the database/web server should not be internet facing and requires that you poke a hole through your firewall using SSH to even connect to the server(s).
Bonus points: Using ssh certificates with your connection to further reduce the chance of issues.

A: This is really two questions:
1- When I use SSH and Firefox to connect to that site, can people see it?
Unless you have turned off your DNS lookup, the hostmaster of your DNS server will see your query. Also, anyone who can packet trace your DNS traffic (exposure varies), can figure this out.
Also, the URL you provided was clear text (unencrypted). Anyone that could normally sniff your packets will be able to see.
2- The other question is basically: is it safe for me do work on a public site w/o turning on encryption for all services? The answer is no. You should not have any work sites that allow authentication or general access over unencrypted connections.


text:
Q: pdfkit js read from file I am working on a nodejs service where I need to read a PDF document from a file.
At a high level, here is the workflow. First time a user requests a PDF, I generate it (using pdfkitjs) and save it to the server. Then, when the user request the same document again, I need to read it from the server and send it back.
Is there a way that I can use PDFDocument from pdfkitjs to read the contents from the file and create a corresponding PDFDocument? Almost all searches come up with how to pipe the PDF to a stream, but now how to read from a stream.

A: If "the stream" is your server response then you shouldn't have to do much more than add the appropriate headers to the response first.


text:
Q: How to link source from outside of maven project? In Maven, is it possible to link additional dependent java src from outside the project folders, so that when we build our main package, maven may include such classes into final jar?
just as we can link any source folder to our project in Eclipse and eclipse treats it as regular project source?

A:
In Maven, is it possible to link additional dependent java src from outside the project folders

Technically, it's possible to add source folders to a build and this is usually done using the build-helper-maven-plugin. However, I would recommend against doing so for directories outside a given module, a maven module should be self contained.


text:
Q: How to view the size of an InnoDB table in MySQL? When I say view the size, I'm looking to compare relative sizes of different InnoDB tables on disk.

A: If you have phpMyAdmin you can easily see it there.


text:
Q: Box In new page I am trying to get a PayPal link/button to open on another page instead of opening on the same page. It is an old site so I was looking for the best way to update it. The link is as follows. Thanks in advance!
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top"><input name="cmd" type="hidden" value="_s-xclick" />
<input name="hosted_button_id" type="hidden" value="XXXXX" />
<input alt="PayPal - The safer, easier way to pay online!" name="submit" src="https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif" type="image" />
<img src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" alt="" width="1" height="1" border="0" /></form>

A: With that old style button code, you can accomplish what you want by changing target="_top" to target="paypal" (or _blank)

However, the best solution would be to change to using a smart button, which uses an in-context approval flow rather than a separate browser tab. You can create one for your account via https://www.paypal.com/buttons , first option
(There's also a code demo here, and full documentation here)

A: Simply change your target to target="_blank" rel="noopener noreferrer". The target _blank opens a new tab for you without closing the original. noopener and noreferrer is a good security measure.


text:
Q: LINQ to SQL Classes Is it better to have one fat data context class with all the tables in it or break them into smaller classes and potentially having "single table" classes?
From organizational standpoint I feel like I shouldn't split relations over several data contexts (I don't even think it's doable). But on the other hand I think that creating a whole new instance of that fat class just to query a single, unrelated table is an overkill.
What do you think?

A: It's not expensive to construct a data context regardless of how many tables it manages, so that shouldn't be a criterion when deciding whether to have one or more separate data context implementations. A new data context is "empty" until you actually start using it, and table instances are created as needed.
What makes a data context instance expensive is when you use the same instance over and over again for tracking changes to different objects - for example, using a cached instance of a data context in an ASP.NET application for all database operations (now that's a no-no).
As long as you use the data context as intended, in a unit-of-work pattern, it doesn't matter how many tables it can manage at the class definition level, as you only instantiate the ones you need within the current unit of work.
To me, the data context logically represents the target database, so it should represent all the entities that are mapped within that database, whether there are 10 or 100 - splitting it up really offers no benefit other than less lines of code in a given class, but if that's something you care about then by all means, have different classes.

A: Depends on the number of tables you've got. If its say less than, say, 20, i personally wouldn't split it up.
If you wanted, you could split by task, or by relationships, or by purpose.
Up to you, i'd say, really. The thing i'd be keeping foremost in my mind is 'which is the most maintainable way to do this?' when deciding whether to split them up.


text:
Q: Ubuntu Usb persistence problem with Ubuntu Software Good morning everyone,
I would like to know if you could help, the problem is the following :
Yesterday i tried to install "Atom" and "Gimp" from Ubuntu Software, both downloaded correctly, but when i lunch the programs they do not respond, i mean they do not open at all, it seems that they are only loading for few second but that's it.
I'm currently running Ubuntu 18.04 with Usb  persistence.
Any help would be appreciated,
Thanks anyway.

A: I can verify that gimp can be installed and that it works in a persistent live Ubuntu 18.04 LTS [family flavour, Lubuntu].

My test system was installed into an old hard disk drive, that I have connected via a USB3 to SATA adapter. I used mkusb to create the persistent live system.
I have run gimp also in standard Ubuntu 18.04 LTS and it works also in a USB pendrive, if there is enough free space in the casper-rw file or partition. You must activate the repository 'universe' for the gimp package to be found and installed,
sudo add-apt-repository universe

Edit: Before giving up your current persistent live system, try to reboot.

*

*If no luck, maybe it would be best to create a fresh persistent live system with mkusb, or

*if your USB drive is big and fast enough to create an installed system in it, installed like into an internal drive but into a USB drive. Such a system can be portable enough (but not as portable as a persistent live system), and it is more flexible and stable, when we talk about installing program packages.


text:
Q: What is the function of buffer size and hop size in aubio library for python? I'm working with the aubio library for sound analysis. Basically to detect onset of beats. aubio.onset() takes 4 arguments, 2 of which are buffer size and hop size. I'm trying to figure how changing these 2 values affects my onset detection.
-B, --bufsize win  The size of the buffer to analyze, that is the length
  of the window used for spectral and temporal computations. Defaults to 512.

-H, --hopsize hop  The number of samples between two consecutive analysis.
  Defaults to 256.

The 2 definitions that I found after doing some online search (https://aubio.org/manual/latest/cli.html#aubioonset) are mentioned above.
From my understanding increasing buffer will require more processing time and increase latency. However is there anything else that buffer size will affect.
Also I did not get what the hop size is, in the above definition what do they mean when they say no of audio samples between 2 consecutive analysis. What is the analysis they are performing and what do they do with the audio samples. How will changing the hop size affect my onset detection


text:
Q: `testImplementation` does not seem to resolve the dependencies correctly for tests I am working in some Unit Tests (not instrumented) in Android Studio. All my test dependencies have been declared in my 'build.gradle' like this:
testImplementation 'junit:junit:4.12'
testImplementation "org.mockito:mockito-core:$mockitoVersion"
testImplementation "org.powermock:powermock-module-junit4:$powerMockVersion"
testImplementation "org.powermock:powermock-api-mockito2:$powerMockVersion"
testImplementation 'org.json:json:20140107'
testImplementation 'org.robolectric:robolectric:3.4.2'

However, when I load a test file, all the dependencies are marked as "Cannot resolve symbol XXX". If I change it from testImplementation to androidTestImplementation, all dependencies are detected correctly. However these are not instrumented tests, but independent unit tests, so when I execute the tests with androidTestImplementation it returns a error: package org.junit does not exist, preventing me from running the unit tests.
Things that I have checked so far (from many stackoverflow answers):

*

*Ensure my tests are in the test folder, and not in androidTest

*Delete .idea and .gradle folder

*Remove dependencies, sync gradle, re declare dependencies, re sync.

*Invalidate caches and restart (several times).

*Try with Android Studio 4.0 (currently 3.6)

*Re import project from scratch.

Also it is important to note (or maybe not) that the project is a library and not an application.
As a workaround, I have declared the dependencies as implementation so I can continue running tests locally, but of course this is bothering and dangerous as I do not want to end up shipping my AAR with testing dependencies by mistake.

A: A late answer, but maybe it will help people who come across this question and struggle with the same issue.
What worked for me was to set the sourceSets in build.gradle (in the android brackets) to the correct directory, at first I had a different configuration but the one below worked for me and let me import JUnit to my test class
sourceSets {
    test.java.srcDirs += 'src/test/java'
}


text:
Q: Visual studio 2012 overwrites properties in my .csproj project file I am using Visual Studio 2012. I have many projects each containing at least one .csproj file. The .csproj files contain this section:
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <IntermediateOutputPath>Assembly\Release\</IntermediateOutputPath>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
    <IntermediateOutputPath>Assembly\Debug\</IntermediateOutputPath>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
    <IntermediateOutputPath>Assembly\x86\Debug\</IntermediateOutputPath>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
    <IntermediateOutputPath>Assembly\x86\Release\</IntermediateOutputPath>
  </PropertyGroup>

For some reason, whenever I open the project in Visual Studio, saving it changes the .csproj file to look like this:
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <IntermediateOutputPath>C:\Users\user\AppData\Local\Temp\vs9475.tmp\Release\</IntermediateOutputPath>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
    <IntermediateOutputPath>C:\Users\user\AppData\Local\Temp\vs9475.tmp\Debug\</IntermediateOutputPath>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
    <IntermediateOutputPath>C:\Users\user\AppData\Local\Temp\vs9475.tmp\x86\Debug\</IntermediateOutputPath>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
    <IntermediateOutputPath>C:\Users\user\AppData\Local\Temp\vs9475.tmp\x86\Release\</IntermediateOutputPath>
  </PropertyGroup>

I have tried several things including adding a BaseIntermediateOutputPath element as well as creating separate conditional IntermediateOutputPath elements. The problem is that this messes with our version control and also generates errors when someone other than myself loads it (because of the local path). Can anyone tell me how to stop visual studio from changing the file every time we load it? This happens to everyone who opens it in Visual Studio 2012. It worked in 2010 but we are transitioning and need to fix this. It is a 2012 project.


text:
Q: how to insert data into array object in c# I'm working with Json As i converted that json into classes and my class structure is like below
Class Demo
{
    public A a { get; set; }
    public B b { get; set; }
    public C[] c { get; set; }
}

class A
{
public string x{ get; set; }
}
class B
{
public string y{ get; set; }
}
class C
{
public string z{ get; set; }
public D d{ get; set; }
}
class D
{
public string p{ get; set; }

}

to assign values to the parameter i'm using below code.
 Demo demo = new Demo {

                        a = new A{
                            x = "test data",

                        },
                        b = new B{
                            y = "test data",

                        }

for the same class A and B i'm able to assign value but Class C is an array how can i assign parameter value to the class C

A: Two ways,
 Demo demo = new Demo
        {
            a = new A
            {
                x = "test data",
            },
            b = new B
            {
                y = "test data",
            },
            c = new C[]
            {
                new C
                {
                    z = "hello",
                    d = new D
                    {
                        p = "This is D's property"
                    }
                },
                new C
                {
                    z = "Hi",
                    d = new D
                    {
                        p = "Another D's property"
                    }

                },

            }
        };

Or add to list and convert to the array. I would recommend the first one.
 Demo demo = new Demo
        {
            a = new A
            {
                x = "test data",
            },
            b = new B
            {
                y = "test data",
            },
            c = new List<C>
            {
                new C
                {
                    z = "hello"
                }
            }.ToArray()
        };

Here is the full sample program,
class Program
{
    static void Main(string[] args)
    {
        Demo demo = new Demo
        {
            a = new A
            {
                x = "test data",
            },
            b = new B
            {
                y = "test data",
            },
            c = new C[]
           {
                new C
                {
                    z = "hello",
                    d = new D
                    {
                        p = "This is D's property"
                    }
                },
                new C
                {
                    z = "Hi",
                    d = new D
                    {
                        p = "Another D's property"
                    }

                },

           }
        };

        Console.WriteLine(demo.a.x);
        Console.WriteLine(demo.b.y);

        foreach (var c in demo.c)
        {
            Console.WriteLine(c.z);
            Console.WriteLine(c.d.p);
        }

        Console.ReadKey();
    }
}

public class Demo
{
    public A a { get; set; }
    public B b { get; set; }
    public C[] c { get; set; }

    public D d { get; set; }
}

public class A
{
    public string x { get; set; }
}

public class B
{
    public string y { get; set; }
}

public class C
{
    public string z { get; set; }
    public D d { get; set; }
}

public class D
{
    public string p { get; set; }

}

and the output,

A: Create new empty array where each item would be of type C:
c = new C[0]

Create new array with two new items of type C, where each item has property values set:
c = new C[] { new C { z = "1"}, new C { z = "2"}}

However, if you don't know the number of items beforehand, you may be better of using generic enumerables, such as:
// Create new empty list
var myList = new List<C>();

// Add a new object to the list
myList.Add(new C());


text:
Q: How to customize zbar sdk's UIImagePickerView? Iam working on barcode reder app which reads barcode and display it's data using zbar Sdk.
Now client wants to customize the square bracket which appears when camera auto focus the barcode,
  my question is that is it possible to customize it,
Thanks

A: It is possible to customize it, but it's not very documented. Afaik you only have APIs for setting its color and so on. If you want to do further customization, you'll need to re-implement that part yourself.
The code for the built-in tracking can be found here: http://zbar.hg.sourceforge.net/hgweb/zbar/zbar/file/443c9f0e3c8f/iphone

A: This will disable the autofocus property in zbar sdk
reader.tracksSymbols=FALSE;


text:
Q: Android - NullpointerException when I launch my application with turned-on GPS This is my code. An error occurred when I launch the application with turned-on GPS. It also means that with turned-off GPS, the application works perfectly.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View v = inflater.inflate(R.layout.fragment_map, null, false);

        map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map))
                .getMap();
        map.setMyLocationEnabled(true);

        LocationManager lm=(LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
        Criteria c = new Criteria();
        String provider = lm.getBestProvider(c, false);

        final TextView switchStatus = (TextView) v.findViewById(R.id.switchStatus);
        Switch mySwitch = (Switch) v.findViewById(R.id.gpsSwitch);

        boolean statusOfGPS = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (statusOfGPS){
            mySwitch.setChecked(true);
            switchStatus.setText("GPS Switch is currently ON");
        }
        else{
            mySwitch.setChecked(false);
            switchStatus.setText("GPS Switch is currently OFF");
        }

        mySwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {

         @Override
         public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
          if(isChecked){
           switchStatus.setText("GPS Switch is currently ON");
           Intent viewIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
           startActivity(viewIntent);
          }else{
           switchStatus.setText("GPS Switch is currently OFF");
          }
         }
        });

        //check the current state before we display the screen
        if(mySwitch.isChecked()){
         switchStatus.setText("GPS Switch is currently ON");
        }
        else {
         switchStatus.setText("GPS Switch is currently OFF");
        }

        Location l = lm.getLastKnownLocation(provider);

        if(l!=null)
        {
            onLocationChanged(l);
        }

        lm.requestLocationUpdates(provider, 20000, 0, this);

        return v;
}

    @Override
    public void onLocationChanged(Location location) {
        TextView ln=(TextView)getView().findViewById(R.id.lng);
        TextView lt=(TextView)getView().findViewById(R.id.lat);

        // Getting latitude of the current location
        double latitude = location.getLatitude();

        // Getting longitude of the current location
        double longitude = location.getLongitude();

        // Creating a LatLng object for the current location
        LatLng latLng = new LatLng(latitude, longitude);

        Marker myLoc = map.addMarker(new MarkerOptions()
        .position(latLng)
        .title("MyLocation")
        .snippet("I am at ")
        .icon(BitmapDescriptorFactory
            .fromResource(R.drawable.ic_launcher)));

        // Showing the current location in Google Map
        map.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        // Zoom in the Google Map
        map.animateCamera(CameraUpdateFactory.zoomTo(15));

        ln.setText("long: "+longitude);
        lt.setText("lat: "+latitude);
    }

    @Override
    public void onProviderDisabled(String provider) {
        if (provider.equals("gps")){
            TextView ln=(TextView) getView().findViewById(R.id.lng);
            ln.setText("GPS is OFF");
        }

    }

    @Override
    public void onProviderEnabled(String provider) {
        if (provider.equals("gps")){
            TextView ln=(TextView) getView().findViewById(R.id.lng);
            ln.setText("GPS is ON... wait for updates");
        }

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

Here is an Error Log, but I don't know which part of my code gives me an error.
    06-22 13:18:21.639: E/AndroidRuntime(26702): FATAL EXCEPTION: main
    06-22 13:18:21.639: E/AndroidRuntime(26702): java.lang.NullPointerException
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at com.gpsocial.fragments.MapFragment.onLocationChanged(MapFragment.java:103)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at com.gpsocial.fragments.MapFragment.onCreateView(MapFragment.java:93)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:461)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.support.v4.view.ViewPager.populate(ViewPager.java:1064)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.support.v4.view.ViewPager.populate(ViewPager.java:911)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1432)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.view.View.measure(View.java:16848)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5245)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.view.View.measure(View.java:16848)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5245)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:302)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.view.View.measure(View.java:16848)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5245)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2586)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.view.View.measure(View.java:16848)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2191)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1354)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1537)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1251)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6379)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:791)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.view.Choreographer.doCallbacks(Choreographer.java:591)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.view.Choreographer.doFrame(Choreographer.java:561)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:777)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.os.Handler.handleCallback(Handler.java:730)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.os.Handler.dispatchMessage(Handler.java:92)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.os.Looper.loop(Looper.java:137)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at android.app.ActivityThread.main(ActivityThread.java:5493)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at java.lang.reflect.Method.invokeNative(Native Method)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at java.lang.reflect.Method.invoke(Method.java:525)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
    06-22 13:18:21.639: E/AndroidRuntime(26702):    at dalvik.system.NativeStart.main(Native Method)

Can anyone help with this? That would be really appreciated.

A: You cannot use getView() from onCreateView(). It returns null, precisely because you haven't actually finished executing onCreateView() yet.
The best option would probably be to delay this call until later in the lifecycle. For example, using onStart() would be a good chice.
Another possible workaround would be to assign the view you're returning to a memeber variable, for example:
private View mMainView;

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    View v = inflater.inflate(R.layout.fragment_map, null, false);
    mMainView = v;
    ...
}

And then use mMainView in onLocationChanged().


text:
Q: How to add fields to "New Event" under "Activity" tab in Lightning? I am trying to add custom fields to the "New Event" layout under "Activities" on Opportunity:

However, it appears this component is a static, non-customizable component because when I click on it in Builder, I only see this:

One forum post suggested that one cannot customize this component and therefore cannot add custom fields.
Another post suggests it is possible by editing the Global Action Layout, but this only changed the Global Action for Classic UI.
How can I make available a custom "New Event" layout in Lightning Experience under the "New Event" tab?

A: For your two queries:-

*

*one cannot customize this component and therefore cannot add custom fields:-

There is the option to add fields to event layout.

*it is possible by editing the Global Action Layout, but this only changed the Global Action for Classic UI.

Editing Global action will reflect wherever it is used.

When you want to add a custom field in the new event tab inside activities on lightning record detail page layout, First check the button, link and action section under object manager of an object if there is any new event quick action or not. If there is not, then the new event action is a global action.
In order to add an extra field on global action layout, you can go to setup and type global action and select and open the new event action and edit the page layout. Add the desired field to the new event global action layout.

Note:- Any change in Global action will reflect everywhere it is being
  used. If it affects your org, My suggestion would be to go and create
  one object-specific quick action of type create a record and select
  target object as the event. Add the desired field on the layout of the
  action.
Using Global action on the layout and having record types for the event
  and task in your org needs one extra activity. You need to associate a
  record type for global action in order to show those actions under the
  activity tab on the record page in lightning. If you do not, even
  after adding the global action in salesforce mobile and lightning
  action section on the page layout, the action will not appear in
  activities tab.

One good solution if you want to use the related list to create New event and the task is:-

*

*add related list single on the layout by editing the page using edit page option appears after clicking the setup icon

*select the object Open activities and save it. Do not forget to activate it.
Once done, In your related list, You can see the open activities related list as you were seeing it in Classic. Even You can add this one inside Activity publisher tab on the lightning record detail page. The field displayed here are controlled by normal page layout for task and event. Refer How can I customize my tasks and events page layouts? for more information to edit the page layout of an event and task.

The advantage of using related list is the button here will give you
  an option to select the record type which will never possible through
  an action. Action always needs to associate with a record type, hence lose the ability.

This image tells you about related list single:-

This image tells how you can edit the event layout when using related list single:-

A: First, you have to create the field under Activity in the Object Manager and assign it to the event layout. Next, in Setup, type Global Actions in the Quick Find box. There, you will see the New Event action. Click Layout next to the New Event action. There, you can add custom fields.

A: You can't edit the Activity Publisher component, but you can change the set of tabs that appear therein. They're Quick Actions.
You can control which Quick Actions appear in the Activity Publisher by editing the "Salesforce Mobile and Lightning Experience Actions" section of the page layout assigned for the relevant record type/profile combination. It's not editable from Lightning App Builder.
Note that the Mobile and Lightning Experience Actions section is "digested" by the Lightning Experience to generate both the Activity Publisher tabs and actions that appear in the button bar on the record page. Actions that publish Activities (Events and Calls) will automatically be routed to the Activity Publisher, and will appear in the same order they're shown in the Mobile and Lightning Experience Actions section.
You can create new Quick Actions, and edit existing ones, in Object Manager under Buttons, Links, and Actions for an object. Edit the Quick Action Layout to add or remove fields from display, or add Predefined Field Values to prepopulate fields whether or not they're shown on the layout.