text:
Q: JSON Object. Array and variable have same names. How to parse it? I have below JSON format. Need to parse it. Using below code to parse it. But as you can see in my json there are one variable name hits and one array is dere named Hits. so cod read first "hits" and gives error it is not a json array.
Please suggest how to parse it.
JSONObject rootObject = new JSONObject(fullline);
        JSONArray rows = rootObject.getJSONArray("hits");

        for (int i = 0; i < rows.length(); i++) {
            JSONObject row = rows.getJSONObject(i);
            JSONArray elements = row.getJSONArray("_source");

            for (int j = 0; j < elements.length(); j++) {
            JSONObject element = elements.getJSONObject(j);
            JSONObject publisher = element.getJSONObject("publisher");
            JSONObject language = element.getJSONObject("language");

            JSONObject title = element.getJSONObject("title");

            System.out.println("publisher: " + publisher.toString());
            System.out.println("title: " + title.toString());
            }
        }

JSON is:
{
    "hits": {
        "hits": [
            {
                "_score": 1.4500864,
                "_type": "journal",
                "_id": "8f5e8900ffc7431f856ba063a8f1c64c",
                "_source": {
                    "index": {
                        "publisher": [
                            "Asian Network for Scientific Information"
                        ],
                        "schema_subject": [
                            "LCC:Agriculture",
                            "DOAJ:Agriculture and Food Sciences",
                            "LCC:Plant culture",
                            "DOAJ:Plant Sciences"
                        ],
                        "language": [
                            "English"
                        ],
                        "classification": [
                            "Plant culture",
                            "Agriculture and Food Sciences",
                            "Agriculture",
                            "Plant Sciences"
                        ],
                        "title": [
                            "Asian Journal of Crop Science"
                        ],
                        "country": "Pakistan",
                        "issn": [
                            "2077-2041",
                            "1994-7879"
                        ],
                        "homepage_url": "http://scialert.net/jindex.php?issn=1994-7879",
                        "schema_code": [
                            "LCC:SB1-1110",
                            "LCC:S"
                        ],
                        "subject": [
                            "Agriculture and Food Sciences",
                            "genetics",
                            "plant physiology",
                            "Plant culture",
                            "production",
                            "Plant Sciences",
                            "breeding",
                            "Agriculture"
                        ]
                    },
                    "last_updated": "2014-03-09T13:31:38Z",
                    "admin": {
                        "owner": "16823974",
                        "in_doaj": true
                    },
                    "created_date": "2009-04-30T13:50:33Z",
                    "id": "8f5e8900ffc7431f856ba063a8f1c64c",
                    "bibjson": {
                        "publisher": "Asian Network for Scientific Information",
                        "author_pays": "Y",
                        "language": [
                            "English"
                        ],
                        "title": "Asian Journal of Crop Science",
                        "author_pays_url": "http://scialert.net/guide.php?issn=1994-7879",
                        "country": "PK",
                        "oa_start": {
                            "volume": "1",
                            "number": "1",
                            "year": "2009"
                        },
                        "keywords": [
                            "plant physiology",
                            "production",
                            "genetics",
                            "breeding"
                        ],
                        "link": [
                            {
                                "url": "http://scialert.net/jindex.php?issn=1994-7879",
                                "type": "homepage"
                            }
                        ],
                        "provider": "Asian Network for Scientific Information",
                        "active": true,
                        "oa_end": {},
                        "identifier": [
                            {
                                "type": "pissn",
                                "id": "1994-7879"
                            },
                            {
                                "type": "eissn",
                                "id": "2077-2041"
                            }
                        ],
                        "subject": [
                            {
                                "scheme": "LCC",
                                "term": "Plant culture",
                                "code": "SB1-1110"
                            },
                            {
                                "scheme": "LCC",
                                "term": "Agriculture",
                                "code": "S"
                            },
                            {
                                "term": "Plant Sciences",
                                "scheme": "DOAJ"
                            },
                            {
                                "term": "Agriculture and Food Sciences",
                                "scheme": "DOAJ"
                            }
                        ]
                    }
                },
                "_index": "doaj"
            },
            {
                "_score": 1.4500864,
                "_type": "journal",
                "_id": "90287ce3214140948d1fc371793da58c",
                "_source": {
                    "index": {
                        "publisher": [
                            "Bentham open"
                        ],
                        "schema_subject": [
                            "LCC:Medicine",
                            "DOAJ:Health Sciences",
                            "LCC:Internal medicine",
                            "DOAJ:Medicine (General)",
                            "DOAJ:Neurology",
                            "LCC:Neurology. Diseases of the nervous system",
                            "LCC:Neurosciences. Biological psychiatry. Neuropsychiatry"
                        ],
                        "language": [
                            "English"
                        ],
                        "classification": [
                            "Internal medicine",
                            "Medicine (General)",
                            "Health Sciences",
                            "Neurosciences. Biological psychiatry. Neuropsychiatry",
                            "Neurology",
                            "Neurology. Diseases of the nervous system",
                            "Medicine"
                        ],
                        "title": [
                            "Open Neurology Journal"
                        ],
                        "country": "United States",
                        "issn": [
                            "1874-205X"
                        ],
                        "homepage_url": "http://www.benthamscience.com/open/toneuj/index.htm",
                        "schema_code": [
                            "LCC:RC321-571",
                            "LCC:R",
                            "LCC:RC31-1245",
                            "LCC:RC346-429"
                        ],
                        "subject": [
                            "Internal medicine",
                            "Medicine (General)",
                            "Health Sciences",
                            "Neurosciences. Biological psychiatry. Neuropsychiatry",
                            "Neurology",
                            "Neurology. Diseases of the nervous system",
                            "Medicine",
                            "neurological disorders"
                        ]
                    },
                    "last_updated": "2014-03-09T13:31:38Z",
                    "admin": {
                        "owner": "18740707",
                        "in_doaj": true
                    },
                    "created_date": "2008-05-16T17:41:22Z",
                    "id": "90287ce3214140948d1fc371793da58c",
                    "bibjson": {
                        "publisher": "Bentham open",
                        "author_pays": "Y",
                        "language": [
                            "English"
                        ],
                        "title": "Open Neurology Journal",
                        "author_pays_url": "http://www.benthamscience.com/open/toneuj/MSandI.htm",
                        "country": "US",
                        "oa_start": {
                            "volume": "1",
                            "year": "2007"
                        },
                        "keywords": [
                            "neurological disorders"
                        ],
                        "link": [
                            {
                                "url": "http://www.benthamscience.com/open/toneuj/index.htm",
                                "type": "homepage"
                            }
                        ],
                        "provider": "Bentham open",
                        "active": true,
                        "oa_end": {},
                        "identifier": [
                            {
                                "type": "pissn",
                                "id": "1874-205X"
                            }
                        ],
                        "subject": [
                            {
                                "scheme": "LCC",
                                "term": "Neurology. Diseases of the nervous system",
                                "code": "RC346-429"
                            },
                            {
                                "scheme": "LCC",
                                "term": "Neurosciences. Biological psychiatry. Neuropsychiatry",
                                "code": "RC321-571"
                            },
                            {
                                "scheme": "LCC",
                                "term": "Internal medicine",
                                "code": "RC31-1245"
                            },
                            {
                                "scheme": "LCC",
                                "term": "Medicine",
                                "code": "R"
                            },
                            {
                                "term": "Neurology",
                                "scheme": "DOAJ"
                            },
                            {
                                "term": "Medicine (General)",
                                "scheme": "DOAJ"
                            },
                            {
                                "term": "Health Sciences",
                                "scheme": "DOAJ"
                            }
                        ]
                    }
                },
                "_index": "doaj"
            }
        ],
        "total": 9744,
        "max_score": 1.4500864
    },
    "_shards": {
        "successful": 5,
        "failed": 0,
        "total": 5
    },
    "took": 3,
    "timed_out": false
}


text:
Q: RestEasy Service Returning Different response for Browser Request and Java Client Request I have written a resteasy-spring service :
    @Controller
    @RequestMapping("/abr/asd")
    @Path("/ab/ac")
    public class JobSchedulerService {

        private static final Logger LOGGER = Logger.getLogger(JobSchedulerService.class);

        @GET
        @Path("/abc/{param}")
        public String scheduleJobs(@PathParam("param") String name) {
            return "Success";
        }
    }

When i try calling this service from Browser, the response is proper :
http://localhost:8080/ControlAppWeb/rest/ab/ac/abc/name

*

*Success
But when i try calling it from a Rest Client API, it returns a web page which is actually the welcome page for the web application where i have incoroporated the rest service :
         try {
         URL url = new URL("http://localhost:8080/WebApp/rest/ab/ac/abc/name");
         HttpURLConnection conn = (HttpURLConnection) url.openConnection();

         conn.setRequestMethod("GET");
         conn.setRequestProperty("Accept", "application/json");

         if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
         throw new RuntimeException("Failed! " + conn.getResponseCode());
         }
         BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
         String output;

         System.out.println("Output from Server is: ");
         while ((output = br.readLine()) != null) {
         System.out.println(output);
         }
         conn.disconnect();
         } catch (MalformedURLException e) {
         e.printStackTrace();
         } catch (IOException e) {
         e.printStackTrace();
         }

Kindly help, as to where am i going wrong in invoking from Java API
Further: i tries removing the controller and request mapping annotation from the Service, still the browser call worked and java rest client didn't. Weird thing is that even if my modify the url to anything random (in the java client) excluding the intial part (http://localhost:8080/ControlAppWeb), the output remains the same and never is an error thrown...

A: The problem in this case seemed to be arising due to a 'filter' configured in the web.xml of the control application. Due to which all the requests to /* were getting redirected to the welcome page. Removing the filter configuration from the web.xml file resolved the problem and the response for the Java Rest API was 'Success' same as for the call from the Browser. Though i am still unclear on why the filter did not affect the request from browser but did so for the request from Java Client.
Anyways hope this helps others who might be struggling with a similar problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Allure2 How to integrate it with Jira Xray I am trying to integrate Allure2 reports with Jira plugin called Xray. So far i managed to generate those reports on local machine and on Jenkins server in pipeline job with Allure plugin.
Also i see that there is an actual Allure plugin called xray-plugin on Allure Framework GitHub, however instructions how to use this plugin are not clear enough for me (for example, where one should put those Jira env variables?).
Can someone here explain in more clear manner how to integrate Allure2 with x-ray?


text:
Q: PHP Mailer fails on MS Exchange I am trying to send an email via PHP mailer and am failing miserably. The error message I am getting is as follows:
2014-08-12 12:21:40 SMTP ERROR: Failed to connect to server: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. (10060) 2014-08-12 12:21:40    SMTP connect() failed. Mailer Error: SMTP connect() failed.

My code is as follows. I do not know where I am going wrong with this. I am pretty sure all information is correct, with the exception of the port. Given this is using microsoft exchange I am using port 587 -is this where I am going wrong?
<?php
include("phpmailer/class.phpmailer.php");

$mail             = new PHPMailer();
$body             = "HellooooO";

$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPSecure = "tls";
$mail->SMTPDebug  = 1;                     // enables SMTP debug information (for testing)
                                           // 1 = errors and messages
                                           // 2 = messages only
$mail->SMTPAuth   = true;
$mail->Host       = "My server name";
$mail->Port       = 587;
$mail->Username   = "My MS exchange email address";
$mail->Password   = "Password";

$mail->SetFrom('My MS exchange email address', 'First Last');

$mail->Subject    = "PHPMailer Test Subject via smtp, basic with authentication";

$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

$mail->MsgHTML($body);

$address = "test email address";
$mail->AddAddress($address, "John Doe");

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
} else {
  echo "Message sent!";
}

?>

-----------EDIT-------------------
Following Synchro's remark that I am not using the latest version of PHP Mailer, I have amended the code as follows. I am still not able to send emails and the error message is the same... How do I check whether the TLS port is open and working as expected?
<?php
require 'phpmailer/PHPMailerAutoload.php';

$mail = new PHPMailer;
$mail ->SMTPDebug = 1;

$mail->isSMTP();
$mail->Host = 'My Server';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = 'My email address';
$mail->Password = 'My Password';
$mail->SMTPSecure = 'tls';

$mail->From = 'My email address';
$mail->FromName = 'Mailer';
$mail->addAddress('My Test Email address', 'Joe User');

$mail->WordWrap = 50;
$mail->isHTML(true);
$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

Regards and thank you,
G.

A: Not sure if this has been cured, however this is typical firewall behavior.  You could use something like Wireshark to see if the server is recieving the request.


text:
Q: How to persist Identity Server consent in a database? I'm attempting to develop a .NET Core Identity Server but I can't seem to figure out where to hook in to persist consents in a database.  My understanding is that when the use consents to the scopes of an application and checks the Remember Consent checkbox that in only stored in memory by default and if the Identity Server were to restart, the user would have to consent again.  Is there a way to persist consent in something like a database so it can be remembered beyond a service restart?

A: you can use something like Entity framework to persist data in the database,
here is the docs for how to configure EF with Identity Server.


text:
Q: LongListSelector Scrolling In my app i load items from server in LongListSelector. On my search page i have an app bar too. I need to decrease its opacity so that it shows the items that hide behind the app bar. When i make my AppBar transparent, the long list selector items remain hidden behind the app bar.
I need exactly the same look and feel that is shown in foursquare in below screenshot.
Any help?

A: Putting your Root Grid or your LongListSelector Marging work?
Margin="0,0,0,75"

Like:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="0,0,0,75" />

Greetings!
UPDATE
I was searching now a little bit on google and I found this article. I recommend to read it.
In this article I saw that the LongListSelector has a ListFooterTemplate, so you can set a footer and it will work.
<DataTemplate x:Key="citiesListFooter">
    <Border Background="White" Opacity="0.2" Height="70">
        <TextBlock Text="Cities Footer" VerticalAlignment="Center" HorizontalAlignment="Center" Foreground="Black"/>
    </Border>
</DataTemplate>

put it in your MainPage.Resource and after in your LongListSelector put this line of code:
ListFooterTemplate="{StaticResource citiesListFooter}" Margin="1,0,-1,0"/>

This example is from the link I give you above. Hope helps.
greetings!


text:
Q: Error php: Cannot modify header information - headers already sent by tengo un formulario que envía un email al correo electrónico.Tengo la pagina web subida a hostinger y de un dia a otro sin tocar nada me da este fallo:
Creo que el error esta en el header,al intentar redirigir la pagina al index.
Gracias!

Cannot modify header information - headers already sent by

<?php

$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$portal = $_POST['portal'];
$piso = $_POST['piso'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$incidencia = $_POST['incidencia'];
$message = $_POST['message'];
$archivo = $_FILES['adjunto'];

require("archivosformulario/class.phpmailer.php");
//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
// use
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMTP over IPv6
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "correopersonal";
//Password to use for SMTP authentication
$mail->Password = "contraseña";
//Set who the message is to be sent from
$mail->setFrom($email, $first_name);
//Set an alternative reply-to address
$mail->addReplyTo($email, $first_name);
//Set who the message is to be sent to
$mail->addAddress('correo', 'minombre');
//Set the subject line
$mail->Subject = 'INCIDENCIA NUEVA: ' . $incidencia;
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML(file_get_contents('contents.html'), __DIR__);

//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
     $mail->Body     =
    "Esto es un correo generado desde la web, si quiere mas informacion contacte con:  \nAddAttachment($archivo['tmp_name'], $archivo['name']);

//send the message, check for errors
if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
     header('Location: index.html');
} else {
    echo "Message sent!";
       header('Location: index.html');
    //Section 2: IMAP
    //Uncomment these to save your message in the 'Sent Mail' folder.
    //if (save_mail($mail)) {
      //  echo "Message saved!";
    //}

}
//Section 2: IMAP
//IMAP commands requires the PHP IMAP Extension, found at: https://php.net/manual/en/imap.setup.php
//Function to call which uses the PHP imap_*() functions to save messages: https://php.net/manual/en/book.imap.php
//You can use imap_getmailboxes($imapStream, '/imap/ssl') to get a list of available folders or labels, this can
//be useful if you are trying to get this working on a non-Gmail IMAP server.
function save_mail($mail)
{
    //You can change 'Sent Mail' to any other folder or tag
    $path = "{imap.gmail.com:993/imap/ssl}[Gmail]/Sent Mail";
    //Tell your server to open an IMAP connection using the same username and password as you used for SMTP
    $imapStream = imap_open($path, $mail->Username, $mail->Password);
    $result = imap_append($imapStream, $path, $mail->getSentMIMEMessage());
    imap_close($imapStream);
    return $result;
}

A: Estás usando echo antes de redirigir:
if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
    header('Location: index.html');
} else {
    echo "Message sent!";
    header('Location: index.html');
}

El echo de por sí imprime el contenido y por tanto envía los header correspondientes (por ejemplo que el content-type es text/plain). Enviados esos headers, no puedes añadir headers nuevos sobre la marcha.
En vez de usar header para redirigir puedes usar lo que dice @sakulino, imprimir una etiqueta script que redirija desde el browser.

A: Donde usas la función header verifica si la puedes lanzar con éste método headers_sent().

headers_sent() retornará FALSE si no se han enviado encabezados HTTP
  o de lo contrario TRUE.

    <?php // Si no se han enviado encabezados, enviar
    if (!headers_sent()) {
        header('Location: http://www.example.com/');
        exit;
    }else{//si se han enviado haremos redirect desde javascript
        echo '';
        echo '';
        echo '<meta http-equiv="refresh" content="0;url='.$filename.'" />';
        echo '';
    }

?>

Documentación.


text:
Q: react sometimes not rendering dom when scrolling I have a react app that can add object from list A to list B
however, the object in list A can be too many, therefor, I shrink the container and add overflow=true css style so that the container can be scrolled

However, sometimes, the DOM is not rendering
like this:

but if I click or interact with the DOM object (the object is an accordion in this case), it will re-appear

how to fix this annoying bug?
I am using the latest chrome browser, with semantic ui as css framework


text:
Q: selenium fails some times to start firefox I am using:

*

*FireFox 53.0 (64-bit)

*selenium 3.4.1

*geckodriver-v0.16.1-linux64 (at ~/.local/bin/ which is in my $PATH)

in a python shell:
from selenium import webdriver
driver = webdriver.Firefox()

that fails occasionally, it works some times, other times it fails.
here is the bug trace:
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    driver = webdriver.Firefox()
  File "..../lib/python3.5/site-packages/selenium/webdriver/firefox/webdriver.py",
  line 152, in __init__
    keep_alive=True)
  File "..../lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py",
  line 98, in __init__
    self.start_session(desired_capabilities, browser_profile)
  File "..../lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py",
  line 188, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "..../lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py",
  line 250, in execute
    response = self.command_executor.execute(driver_command, params)
  File "..../lib/python3.5/site-packages/selenium/webdriver/remote/
  remote_connection.py", line 464, in execute
    return self._request(command_info[0], url, body=data)
  File "..../lib/python3.5/site-packages/selenium/webdriver/remote/
  remote_connection.py", line 488, in _request
    resp = self._conn.getresponse()
  File "..../.pyenv/versions/3.5.2/lib/python3.5/http/client.py",
  line 1197, in getresponse
    response.begin()
  File "..../.pyenv/versions/3.5.2/lib/python3.5/http/client.py",
  line 297, in begin
    version, status, reason = self._read_status()
  File "..../.pyenv/versions/3.5.2/lib/python3.5/http/client.py",
  line 266, in _read_status
    raise RemoteDisconnected("Remote end closed connection without"
http.client.RemoteDisconnected: Remote end closed connection without response


text:
Q: How to go and watch complete game replays? I'm looking to see some full game replays in League of Legends (that are not my friends' game)
Those "Featured games" in the starter slider are always in progress, and what I'm looking for is to get in a random game that is still on the character select screen. (or at least still in the 3 minutes buffer)
Is there any way to do this?

A: No.  There are three types of games you can spectate:

*

*The featured games on the main page

*A game that someone in your friend's list is participating in

*A custom game that has spectator slots open

A: http://www.leaguereplays.com/ is a third party application which allows you to record your own games and watch em aswell as ones recorded by other people by manually downloading them
that's the closest thing i can think of to what you're looking for

A: Download LOL Recorder from this site http://www.leaguereplays.com/ as mentioned in previous answers.  For the best results though you should go into the options (the cog wheel in the corner of the main page on LOL Recorder) and turn on:

*

*Record While Spectating
and

*Record All Matches in Specmode

What this will do is allow you to record while just purely spectating as you asked, but will also give you the recording in the mode in which you spectate (i.e. Specmode), if the Record in Specmode box is not checked, you will only see health bars of friendly and enemy champions within a certain proximity of yourself, before they disappear, you can't see the total gold of both teams, and the UI just doesn't look as nice.
If you are unaware of what specmode is I will elaborate.  Specmode includes:

*

*A very nice UI that allows you to see BOTH teams all the time (not just your own)

*Allows easy view of how long wards will last

*The UI also has a nice centerpiece that allows you to see the gold currently owned by each champion (even enemies) and how much they have acquired throughout the entire game, as well as all items owned by all champions.

*Rewind and fast forward mode

*A camera that if left untouched will follow the action and jump around the map to different champions without you touching a button (called directed camera)

*Total gold obtained by each time for easy telling which team has the gold lead

*An easy counter for how many towers each team has taken down

*Colorblind mode for anyone that is colorblind, allowing the purple team to become the red team

*More I'm sure that I just can't think of

Record in specmode will also allow all the games you play yourself to be recorded in this fashion, for very improved reviewing of your own games.  I hope I've provided sufficient information on this subject and that you enjoy LOL Recorder and Specmode recordings.

A: http://www.leaguereplays.com/ is safe riot even wrote an article about how well it worked

A: Look up the persons ign on most 3rd party sites will have a button you can click to watch that persons game.
A few sites you can try for this are:
lolnexus.com
na.op.gg


text:
Q: identity involving arithmetic function I have a question concerning the identity below.  I am having difficulty proving it without the use of induction.  In particular, I am not sure how to deal with the floor of n on the index of summations on the right hand side.  If someone can explain it to me or give me suggestions, it would be greatly appreciated.  Thank you in advance.
$\sum_{j=1}^{n}\tau(j)=2\sum_{j=1}^{\lfloor{\sqrt n}\rfloor}\lfloor\frac{n}{j}\rfloor-\lfloor{\sqrt n\rfloor}^{2}$


text:
Q: Showing dynamic items list using two tables in codeigniter php I have two tables one having advert info which includes id for images table associated with the advert. I am showing the advert information in one single page, how do I send both arrays to the view page. If I write the select for both tables, I get multiple lines since I have multiple images for an advert.
My model functions
    public function get_adverts()
    {
        //$this->db->select();
        //$this->db->from('adverts');
        $db_query='select adverts.id,adverts.address,adverts.title,adverts.item_condition, adverts.add_type, adverts.price, adverts.negotiable, adverts.product_description, countries.country_name,states.state_name, cities.city_name, product_pictures.picture_file_name
FROM adverts,countries,cities,states, product_pictures
WHERE adverts.country_id=countries.id and adverts.city_id=states.id and adverts.area=cities.id and adverts.id= product_pictures.add_id';

        $query = $this->db->query($db_query);
        return $query->result();
    }

    public function get_pictures()
    {
        //$this->db->select();
        //$this->db->from('adverts');
        $db_query='select product_pictures.picture_file_name
FROM adverts,product_pictures
WHERE adverts.id=product_pictures.add_id';

        $query = $this->db->query($db_query);
        return $query->result();
    }

and my control
public function get_products()
{
    // gets all dvertes in the system
    $this->load->model('Product_model');
    $data['products']=$this->Product_model->get_adverts();   // get database query output to the array
    $data['images']=$this->Product_model->get_pictures();
    $array_info2 = array(
        "title" => "Not Found"
    );
    $this->load->view('include/header', $array_info2);
    $this->load->view('include/navbar_logged_in');
    $this->load->view('Site/view_adverts',$data);
    $this->load->view('include/footer');
}

This lists all images under one advert, my view portion given below:

<?php foreach($products as $product):?>

                <?php foreach($images as $image):?>

                    <img class="image img-thumbnail"  src="<?php echo base_url('/uploads/advert_images/thumbs/'.$image->picture_file_name);?>" >

                <?php endforeach;?>

                                <?php echo $product->id." ".$product->title;?>

  Electronics

26th December

<?php echo $product->product_description;?>

<?php endforeach;?>


text:
Q: Why does this code return segmentation fault error? I'm writing this code to optimize the time of the problem and it is a dp      problem
Given string S is: 574674546476
for index 1:
Number of even numbers from 5 to end of the string is 7 so the result of index 1 is 7.
for index 2:
Number of even numbers from 7 to end of the string is 7 so the result of index 2 is 7.
for index 3:
Number of even numbers from 4 to end of the string is 7 so the result of index 3 is 7.
for index 3:
Number of even numbers from 6 to end of the string is 6 so the result of index 4 is 6.
...
This is the code which I've tried but it shows segmentation fault in this code
#include <bits/stdc++.h>
using namespace std;
int main()
{
    char str[10005];
    int i;
    cin >> str;
    int n = strlen(str);
    int arr[10005];
    for (i = 0; i < n; i++) {
        arr[i + 1] = str[i] - 48;
    }

    int tab[n + 1];

    if (arr[n] % 2 == 0) {
        tab[n] = 1;
    }
    else {
        tab[n] = 0;
    }

    for (i = n - 1; i >= 1; i++) {
        if (arr[i] % 2 == 0) {
            tab[i] = tab[i + 1] + 1;
        }
        else {
            tab[i] = tab[i + 1];
        }
    }
    for (i = 1; i <= n; i++) {
        cout << tab[i] << " ";
    }
}

I expect output should be

7 7 7 6 5 5 4 4 3 2 1 1

But when I'm giving input 574674546476 and I want to solve using dp I write the code, it shows segmentation fault.

A:       for(i=n-1;i>=1;i++){

should be
      for(i=n-1;i>=1;i--){

That explains the crash but you also have the two common errors we see when people submit competitive code
This is not a standard C++ header file
#include<bits/stdc++.h>

In this code you should be using
#include <iostream>

And this is not legal C++
int tab[n+1];

since in C++ array sizes must be compile time constants, but here n is a variable. You should use
#include <vector>

and
vector<int> tab(n+1);

instead.


text:
Q: Creating and adding items to list JAVA Im trying to create and add strings to a list
package the.arraylist.pkgclass;

import java.util.ArrayList;

/**
 A class to implement a Polynomial as a list of terms, where each term has
 an integer coefficient and a nonnegative integer exponent

 @author your name
 */
public
        class Polynomial
{
// instance variable declarations go here
Term theTerm ; //initializes a term

/**
 Creates a new Polynomial object with no terms
 */
public
        Polynomial ()
{
  // TO DO: Write constructor body here

    ArrayList<Term> list1 = new ArrayList<> ();
}

/**
 Inserts a new term into its proper place in a Polynomial

 @param coeff the coefficient of the new term
 @param expo  the exponent of the new term
 */
public
        void insert ( int coeff , int expo )
{
  // TO DO: write method body here.
}

I don't feel I've initiated the list correctly because I can't call on the list in the insert class.
The strings will consist of polynomials which are already strings.

A: You should keep your list as an attribute of your Polynomial class so you can add items to it later on.
public class Polynomial {

private List<Term> list;

public Polynomial() {
  this.list = new ArrayList<> ();
}

public void insert ( int coeff , int expo ) {
  this.list.add(...);
}


text:
Q: Overlay android side-menu on "Unity as a plugin" rendering screen I am writing a requirement of Unity3D viewer for Android. I need to separate UI, Data and Unity3D View. for example, from model-tree, using ViewAPI, control the unity3d viewer.  Is it possible to implement as following image?
Swipe from left overlays Model-tree menu


text:
Q: Phone Number formatting using Regex
Possible Duplicate:
A comprehensive regex for phone number validation

I have an unformatted phone number (guaranteed to be 10 digits) and an unformatted extension (could be null, blank or any number of numbers). I need to put them together into a "friendly" string. I thought I'd concatenate them, then format the concatenation using a Regex.Replace. Here's the unit test I'm using to try various regexes before I plug one in:
    [Test, Ignore("Sandbox, does not test production code")]
    public void TestPhoneRegex()
    {
        string number = "1234567890";
        string extension = "";

        var formattedContactNumber =
            Regex.Replace("{0} x{1}".FormatWith(number, extension),
                          @"^(\d{3})[ -]?(\d{3})[ -]?(\d{4})( x\d+)?",
                          @"$1-$2-$3$4");

        Debug.WriteLine("{0} x{1}".FormatWith(number, extension));
        Debug.WriteLine(formattedContactNumber);

        Assert.AreEqual("123-456-7890", formattedContactNumber);
    }

The expected formatted string is the formatted phone number, without the "x" and extension. However, the last capture group is matching the "x" with or without a number behind it, so instead of "123-456-7890" I get "123-456-7890 x". This is the last bit of development that needs to be tied down before a release. Help?

A: x isn't matched by your regex, so it isn't replaced put of the string. Try this regex instead:
@"^(\d{3})[ -]?(\d{3})[ -]?(\d{4}) x(\d*)

In the new regex x isn't optional - it will always be there according to your code (If you do want it to be optional you can use ?x?(\d*)). Also, we're using \d*, so make sure the last group will always match, even when it's empty.

A: This is maybe not a direct answer to your question, but possibly helpful... We use this pattern:
public const string NorthAmericanPhonePattern = @"^(\+?(?<NatCode>1)\s*[-\/\.]?)?(\((?<AreaCode>\d{3})\)|(?<AreaCode>\d{3}))\s*[-\/\.]?\s*(?<Number1>\d{3})\s*[-\/\.]?\s*(?<Number2>\d{4})\s*(([xX]|[eE][xX][tT])\.?\s*(?<Ext>\d+))*$";

And then reformat with:
private static string PhoneNumberMatchEvaluator(Match match)
{
    // Format to north american style phone numbers "0 (000) 000-0000"
    //                                          OR  "(000) 000-0000"
    Debug.Assert(match.Success);
    if (match.Groups["NatCode"].Success)
    {
        return match.Result("${NatCode} (${AreaCode}) ${Number1}-${Number2}");
    }
    else
    {
        return match.Result("(${AreaCode}) ${Number1}-${Number2}");
    }
}

private static string FormatPhoneNumber(string phoneNumber)
{
    var regex = new Regex(NorthAmericanPhonePattern, RegexOptions.IgnoreCase);
    return regex.Replace(phoneNumber, new MatchEvaluator(PhoneNumberMatchEvaluator));
}

Note: In our case we have included the national code if they did, you could easily take that out. We have also not included the extension in there - as we shift it out and put into a different field if we find it.

A: I love regular expressions, don't get me wrong, but this does not seem like a useful area to apply them. All you are doing is adding dashes to a string of 10 numbers then adding an optional "x" followed by an extension. Simpler is better.
public static String beautifyPhoneNumber(String number, String extension)
{
    String beautifulNumber = number.Substring(0, 3) + "-" +
                             number.Substring(3, 3) + "-" +
                             number.Substring(6, 4);
    if (!String.IsNullOrEmpty(extension))
    {
        beautifulNumber += " x" + extension;
    }
    return beautifulNumber;
}


text:
Q: Matisses Linq IConvertible Exception Matisse C# Hey Guys having a problem retrieiving a record from a matisse object database, and its getting to me now... basically tried everything and even using a count message box shows that the linq query is retrieving 1 object however im getting a IConvertible error when it should be working, basically im trying to edit the exisitng record, however its telling me it needs to be IConvertible however this would work when using SQL and it also works for others using Matisse.
db.Open();

        Zoo.Data.Zoo editanimals = new Zoo.Data.Zoo(db);

        var animalidvar = animalid.Text;
        {
          Reptiles_Amphibians f = (from  Reptiles_Amphibians a in editanimals.Reptiles_Amphibianss where a.Animal_ID == animalidvar select a).FirstOrDefault<Reptiles_Amphibians>();

            f.Animal_ID = animalid.Text;
            f.Species = species.Text;
            f.Classification = classif.Text;
            f.Given_Name = givenname.Text;
            f.Photograph = photograph.Text;
            f.Date_Of_Birth = Convert.ToDateTime(dob.Text);
            f.Age = Convert.ToInt32(age.Text);
            f.Location_Code = location.Text;
            f.Born_Captivity_Wild = borncw.Text;
            f.Special_Notes = specnote.Text;
            f.Date_Joined = Convert.ToDateTime(datejoined.Text);
            f.Animal_Dimensions_Upon_Join = duj.Text;
            f.Average_Animal_Dimension = ad.Text;
            f.Average_Life_Span = averagelife.Text;
            f.Dietary_Requirements = diet.Text;
            f.Natural_Habitat_Description = nathab.Text;
            f.Average_Number_Of_Offspring = Convert.ToInt32(averageOffspringTxt.Text);
            f.Reproduction_Type = reproductionTxt.Text;
            f.Average_Clutch_Size = clutchSizeTxt.Text;
            f.Status = statusCombo.Text;
            db.Commit();

        }
        db.Close();
    }

A: Persisten classes (like Reptiles_Amphibians) must be contained in the assembly.
MtDatabase _db = new MtDatabase("localhost", "AnimalDB", new MtPackageObjectFactory("AssemblyName.AnimalsNamespace,AssemblyName", "DataBaseNamespace"));

And before linq query
_db.SqlCurrentNamespace = "DataBaseNamespace";s


text:
Q: Use own IComparer with Linq OrderBy I have a generic
List<MyClass>

where MyClass has a property InvoiceNumber which contains values such as:
200906/1
200906/2
..
200906/10
200906/11
200906/12
My list is bound to a
BindingList<T>

which supports sorting with linq:
protected override void ApplySortCore(
           PropertyDescriptor property, ListSortDirection direction)
{

    _sortProperty = property;
    _sortDirection = direction;

    var items = this.Items;

    switch (direction)
    {
        case ListSortDirection.Ascending:
            items = items.OrderByDescending(x => property.GetValue(x)).ToList();
            break;
        case ListSortDirection.Descending:
            items = items.OrderByDescending(x => property.GetValue(x)).ToList();
            break;
    }

    this.Items = items;

}

However the default comparer sorts (as supposed) like this:
200906/1
200906/10
200906/11
200906/12
200906/2
which is nasty in this case.
Now I want to use my own IComparer<T> with this. It looks like this:
public class MyComparer : IComparer<Object>
{

    public int Compare(Object stringA, Object stringB)
    {
        String[] valueA = stringA.ToString().Split('/');
        String[] valueB = stringB.ToString().Split('/');

        if(valueA .Length != 2 || valueB .Length != 2)
             return String.Compare(stringA.ToString(), stringB.ToString());

        if (valueA[0] == valueB[0])
        {
          return String.Compare(valueA[1], valueB[1]);
        }
        else
        {
          return String.Compare(valueA[0], valueB[0]);
        }

    }

}

and changed the ApplySortCore code to use this IComparer:
case ListSortDirection.Ascending:
    MyComparer comparer = new MyComparer();
    items = items.OrderByDescending(
              x => property.GetValue(x), comparer).ToList();
    break;

When I debug my code, I see that MyComparer.Compare(object, object) is called multiple times and returns the right values (-1, 0, 1) for a compare method.
But my list is still sorted the "wrong" way. Am I missing something? I have no clue.

A: Can't we do like this:
public class MyComparer : IComparer<string>
{

    public int Compare(string stringA, string stringB)
    {
        string small = stringA;
        string big = stringB;
        if (stringA.Length > stringB.Length)
        {
            small = stringB;
            big = stringA;
        }
        else if (stringA.Length < stringB.Length)
        {
            small = stringA;
            big = stringB;
        }
        for (int j = 0; j < small.Length; j++)
        {
            if (Convert.ToInt32(small[j]) > Convert.ToInt32(big[j])) return -1;
            if (Convert.ToInt32(small[j]) < Convert.ToInt32(big[j])) return 1;
        }

        //big is indeed bigger
        if (big.Length > small.Length) return 1;

        //finally they are smae
        return 0;
    }
}

Usage:
string[] inputStrings = {"_abc*&","#almnp","abc" };
//string[] inputStrings = { "#", "_", "_a", "@", "_" };
MyComparer computer = new MyComparer();
var kola = inputStrings.OrderBy(x => x, new MyComparer()).ToArray();

This is same as :
    Array.Sort(inputStrings, StringComparer.Ordinal);

A: You can use The Alphanum Algorithm:
  (...)
    items.OrderBy(x => property.GetValue(x), new AlphanumComparator())
  (...)

AlphanumComparator
/*
 * The Alphanum Algorithm is an improved sorting algorithm for strings
 * containing numbers.  Instead of sorting numbers in ASCII order like
 * a standard sort, this algorithm sorts numbers in numeric order.
 *
 * The Alphanum Algorithm is discussed at http://www.DaveKoelle.com
 *
 * Based on the Java implementation of Dave Koelle's Alphanum algorithm.
 * Contributed by Jonathan Ruckwood <jonathan.ruckwood@gmail.com>
 *
 * Adapted by Dominik Hurnaus <dominik.hurnaus@gmail.com> to
 *   - correctly sort words where one word starts with another word
 *   - have slightly better performance
 *
 * Released under the MIT License - https://opensource.org/licenses/MIT
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
 * USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */
using System;
using System.Collections;
using System.Text;

/*
 * Please compare against the latest Java version at http://www.DaveKoelle.com
 * to see the most recent modifications
 */
namespace AlphanumComparator
{
    public class AlphanumComparator : IComparer
    {
        private enum ChunkType {Alphanumeric, Numeric};
        private bool InChunk(char ch, char otherCh)
        {
            ChunkType type = ChunkType.Alphanumeric;

            if (char.IsDigit(otherCh))
            {
                type = ChunkType.Numeric;
            }

            if ((type == ChunkType.Alphanumeric && char.IsDigit(ch))
                || (type == ChunkType.Numeric && !char.IsDigit(ch)))
            {
                return false;
            }

            return true;
        }

        public int Compare(object x, object y)
        {
            String s1 = x as string;
            String s2 = y as string;
            if (s1 == null || s2 == null)
            {
                return 0;
            }

            int thisMarker = 0, thisNumericChunk = 0;
            int thatMarker = 0, thatNumericChunk = 0;

            while ((thisMarker < s1.Length) || (thatMarker < s2.Length))
            {
                if (thisMarker >= s1.Length)
                {
                    return -1;
                }
                else if (thatMarker >= s2.Length)
                {
                    return 1;
                }
                char thisCh = s1[thisMarker];
                char thatCh = s2[thatMarker];

                StringBuilder thisChunk = new StringBuilder();
                StringBuilder thatChunk = new StringBuilder();

                while ((thisMarker < s1.Length) && (thisChunk.Length==0 ||InChunk(thisCh, thisChunk[0])))
                {
                    thisChunk.Append(thisCh);
                    thisMarker++;

                    if (thisMarker < s1.Length)
                    {
                        thisCh = s1[thisMarker];
                    }
                }

                while ((thatMarker < s2.Length) && (thatChunk.Length==0 ||InChunk(thatCh, thatChunk[0])))
                {
                    thatChunk.Append(thatCh);
                    thatMarker++;

                    if (thatMarker < s2.Length)
                    {
                        thatCh = s2[thatMarker];
                    }
                }

                int result = 0;
                // If both chunks contain numeric characters, sort them numerically
                if (char.IsDigit(thisChunk[0]) && char.IsDigit(thatChunk[0]))
                {
                    thisNumericChunk = Convert.ToInt32(thisChunk.ToString());
                    thatNumericChunk = Convert.ToInt32(thatChunk.ToString());

                    if (thisNumericChunk < thatNumericChunk)
                    {
                        result = -1;
                    }

                    if (thisNumericChunk > thatNumericChunk)
                    {
                        result = 1;
                    }
                }
                else
                {
                    result = thisChunk.ToString().CompareTo(thatChunk.ToString());
                }

                if (result != 0)
                {
                    return result;
                }
            }

            return 0;
        }
    }
}

A: Your comparer looks wrong to me. You're still just sorting in the default text ordering. Surely you want to be parsing the two numbers and sorting based on that:
public int Compare(Object stringA, Object stringB)
{
    string[] valueA = stringA.ToString().Split('/');
    string[] valueB = stringB.ToString().Split('/');

    if (valueA.Length != 2 || valueB.Length != 2)
    {
        stringA.ToString().CompareTo(stringB.ToString());
    }

    // Note: do error checking and consider i18n issues too :)
    if (valueA[0] == valueB[0])
    {
        return int.Parse(valueA[1]).CompareTo(int.Parse(valueB[1]));
    }
    else
    {
        return int.Parse(valueA[0]).CompareTo(int.Parse(valueB[0]));
    }
}

(Note that this doesn't sit well with your question stating that you've debugged through and verified that Compare is returning the right value - but I'm afraid I suspect human error on that front.)
Additionally, Sven's right - changing the value of items doesn't change your bound list at all. You should add:
this.Items = items;

at the bottom of your method.

A: The sorted list is only bound to the local variable items, not to the Items property of your binding list, hence it remains unsorted.
[Edit] Basically, you're simply throwing away the result of your sorting efforts ;-)

A: I encountered the issue of general natural sorting and blogged the solution here:
Natural Sort Compare with Linq OrderBy()
public class NaturalSortComparer<T> : IComparer<string>, IDisposable
{
    private bool isAscending;

    public NaturalSortComparer(bool inAscendingOrder = true)
    {
        this.isAscending = inAscendingOrder;
    }

    #region IComparer<string> Members

    public int Compare(string x, string y)
    {
        throw new NotImplementedException();
    }

    #endregion

    #region IComparer<string> Members

    int IComparer<string>.Compare(string x, string y)
    {
        if (x == y)
            return 0;

        string[] x1, y1;

        if (!table.TryGetValue(x, out x1))
        {
            x1 = Regex.Split(x.Replace(" ", ""), "([0-9]+)");
            table.Add(x, x1);
        }

        if (!table.TryGetValue(y, out y1))
        {
            y1 = Regex.Split(y.Replace(" ", ""), "([0-9]+)");
            table.Add(y, y1);
        }

        int returnVal;

        for (int i = 0; i < x1.Length && i < y1.Length; i++)
        {
            if (x1[i] != y1[i])
            {
                returnVal = PartCompare(x1[i], y1[i]);
                return isAscending ? returnVal : -returnVal;
            }
        }

        if (y1.Length > x1.Length)
        {
            returnVal = 1;
        }
        else if (x1.Length > y1.Length)
        {
            returnVal = -1;
        }
        else
        {
            returnVal = 0;
        }

        return isAscending ? returnVal : -returnVal;
    }

    private static int PartCompare(string left, string right)
    {
        int x, y;
        if (!int.TryParse(left, out x))
            return left.CompareTo(right);

        if (!int.TryParse(right, out y))
            return left.CompareTo(right);

        return x.CompareTo(y);
    }

    #endregion

    private Dictionary<string, string[]> table = new Dictionary<string, string[]>();

    public void Dispose()
    {
        table.Clear();
        table = null;
    }
}


text:
Q: Is it possible to define a function within a stored procedure? I have a stored procedure:
create proc sp_MyProc(@calcType tinyint) as
begin
    -- some stuff collating data into #MyTempTable

    if (@calcType = 1) -- sum
        select A, B, C, CalcField = sum(Amount)
        from #MyTempTable t
        join AnotherTable a on t.Field1 = a.Field1;
        group by A, B, C
    else if (@calcType = 2) -- average
        select A, B, C, CalcField = avg(Amount)
        from #MyTempTable t
        join AnotherTable a on t.Field1 = a.Field1;
        group by A, B, C
    else if (@calcType = 3) -- some other fancy formula
        select A, B, C, CalcField = sum(case when t.Type = 1 then 1 else 0 end) * t.Factor
        from #MyTempTable t
        join AnotherTable a on t.Field1 = a.Field1;
        group by A, B, C
    -- plus a whole bunch of other, similar cases
    else
        select A, B, C, CalcField = 0.0
        from #MyTempTable t
        join AnotherTable a on t.Field1 = a.Field1;
        group by A, B, C
end

Now all these different cases for different values of @calcType seem to be wasting a lot of space and causing me to copy and paste all over, which always sends shivers down my spine.
Is there some way of declaring a function for CalcField, similar to lambda notation in C#, to make my code more compact and maintainable?  I would want to do something like this:
declare @func FUNCTION(@t #MyTempTable) as real -- i.e. input is of type #MyTempTable and output is of type real

if (@calcType = 1) -- sum
    set @func = sum(@t.Amount)
else if (@calcType = 2) -- average
    set @func = avg(@t.Amount)
else if (@calcType = 3) -- some other fancy formula
    set @func = sum(case when @t.Type = 1 then 1 else 0 end) * @t.Factor
-- plus a whole bunch of other, similar cases
else
    set @func = 0;

select A, B, C, CalcField = @func(t)
from #MyTempTable t
join AnotherTable a on t.Field1 = a.Field1;
group by A, B, C

Obviously the syntax here doesn't work, but is there something that will achieve what I want?

A: No this isn't possible.
A permanent TVF or view isn't an option due to the reference to #MyTempTable
I've seen a connect item request for temporary views and agree sometimes they would be useful. This was closed as duplicate of one requesting Module-level table expressions.
You might be able to rewrite as
SELECT A,
       B,
       C,
       CASE @calcType
         WHEN 1
           THEN sum(Amount)
         WHEN 2
           THEN avg(Amount)
       END
FROM   #MyTempTable t
       JOIN AnotherTable a
         ON t.Field1 = a.Field1
GROUP  BY A,
          B,
          C

Or if your needs were more complex (e.g. same shape resultset and using same source but different grouping conditions)
WITH Base
     AS (SELECT A,
                B,
                C,
                Factor,
                Type
         FROM   #MyTempTable t
                JOIN AnotherTable a
                  ON t.Field1 = a.Field1)
SELECT A,
       B,
       C,
       sum(Amount)
FROM   Base
WHERE  @calcType = 1
GROUP  BY A,
          B,
          C
UNION ALL
SELECT A,
       B,
       C,
       CalcField = 0.0 * t.Factor
FROM   Base
WHERE  @calcType NOT IN ( 1, 2, 3 )

With the last one in particular you might consider OPTION (RECOMPILE) to simplify the plan. (Likely it would have a filter with a start up predicate without the hint and not actually execute the redundant branches but you would need to check. Also row estimates could be wrong with this approach if the startup predicate is retained).
If neither of those suited you would need to get into the realms of dynamic SQL.

A: Strictly speaking (T-SQL subroutine): No.
Technically speaking (a means to abstract formulas to be defined once): Yes.
Pragmatically speaking: It depends :).
Here are the issues that are currently impeding you regarding restrictions on T-SQL functions:

*

*They cannot be declared dynamically

*They cannot access temporary tables

*They cannot be aggregate functions (which is really what you are looking for)

However, this can all be done in SQLCLR (well, not the dynamic part, but that doesn't seem to be the focus here). Using SQLCLR you can create a function that can access a temp table, and it can even be an aggregate function. Of course, for simplistic computations such as SUM and AVG you might lose out on performance more than you gain on reducing code duplication, but that is a matter of testing (hence a large part of why "It depends").
Now in this specific case, it does not even seem like access to a temporary table is needed as the per-row values would naturally be sent into the User-Defined Aggregate. Assuming dbo.DynamicCalc has a signature of DynamicCalc(@CalcType TINYINT, @Amount FLOAT):
select A, B, C, CalcField = dbo.DynamicCalc(2, t.Amount)
from #MyTempTable t
join AnotherTable a
    on t.Field1 = a.Field1
group by A, B, C;

or:
select A, B, C, CalcField = dbo.DynamicCalc(3, IIF(t.Type = 1, t.Factor, 0))
from #MyTempTable t
join AnotherTable a
    on t.Field1 = a.Field1
group by A, B, C;

Or you could pass t.Factor in by itself as the @Amount param and add an additional param for @Type INT which will receive t.Type which will only be used if @CalcType = 3.
Again, whether or not to take this approach is a matter of practicality depending heavily on what formulas you have. The suggestion by @Martin to do the CASE @calcType statement to switch between formulas will be more efficient if the formulas are simple enough (as they appear to be based on the code shown in the question). But if those formulas get quite complex, or if you truly do need access to a temp table, then this is an option to consider.

A: That's not possible in SQL standards but if you really need that kind of SQL flow
you can just create stored function inside a stored procedure then after the stored procedure executes , drop the created function
But then again , it is not a good recommendation/practice
just forget about it.


text:
Q: iOS7: UITableViewCell from one of its subviews I have an UITableViewCell with an UIStepper on it. When the stepper value change it triggers a method:
-(void) stepperDidStep: (UIStepper*) sender

I need to get the UITableViewCell from the sender.
Until iOS7 this code worked fine:
-(void) stepperDidStep: (UIStepper*) sender
{
 UITableViewCell *cell = (UITableViewCell*) sender.superview.superview;
 //...
}

Now, in iOS7+Autolayout I get this:
UITableViewCell *cell = (UITableViewCell*) sender.superview;

cell is UITableViewCellContentView
UITableViewCell *cell = (UITableViewCell*) sender.superview.superview;

cell is UITableViewCellScrollView (???)
Question: What is the best way to get the cell from the stepper in iOS7?
Thanks
Nicola

A: Try this. I didn't test it, but i'm using similar code to find the viewcontroller of a view
- (UITableViewCell *)tableCellUnderView:(UIView *)view {
    Class class = [UITableViewCell class];
    // Traverse responder chain. Return first found UITableViewCell
    UIResponder *responder = view;
    while ((responder = [responder nextResponder]))
        if ([responder isKindOfClass:class])
            return (UITableViewCell *)responder;

    return nil;
}

A: Why don't you just set the tag of the UIStepper same as indexPath.Row in the data-source method cellForRowAtIndexPath?
Then in the stepperDidStep: method, get the desired cell using cellForRowAtIndexPath: like this:
-(void) stepperDidStep: (UIStepper*) sender{

     UITableViewCell *cell = (UITableViewCell*)[yourTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:sender.tag inSection:0];
}

A: Don't get the cell by checking the superview. It's too unreliable. The cell has some hidden views which complicates things even further.
Instead, subclass UIStepper and give it a custom property of UITableViewCell (possibly a weak reference) then set it to the cell when setting up the UIStepper, and then grab the cell when your stepperDidStep: method is called.
Something like:
@interface CellStepper : UIStepper
@property (nonatomic, weak) UITableViewCell* cell;
@end

.
-(void) stepperDidStep: (CellStepper*) sender
{
 UITableViewCell *cell = sender.cell;
 //...
}


text:
Q: Quiver 2D colormap I am plotting a dipole field which has a singularity at the origin.
Therefore I want to colour code the arrows to indicate the strength of the field.
Right now I manage to produce the arrows I want but the colour goes along the theta-axis and not along the r-axis:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import matplotlib.cm as cm
from matplotlib.colors import Normalize

fig = plt.figure(figsize=(15,10))
ax = fig.gca(projection='polar')

n=30
m=8

thetas = np.linspace(0, 2*np.pi, n)
radii = np.linspace(0.15, 1, m)
theta, r = np.meshgrid(thetas, radii)
p = .3
Er = p*2*np.cos(theta)#/r**3
Et = p*np.sin(theta)#/r**3

m = np.meshgrid(thetas,radii)
#This is where one should define m such that it results in the color coding I want. Unfortunately, I am not completely sure how the color is decoded in the quiver function.

ax.set_title("Dipole field", va='bottom')
ax.quiver(theta, r, Er * np.cos(theta) - Et * np.sin (theta), Er * np.sin(theta) + Et * np.cos(theta), m, pivot='mid')
plt.show()

I would like the arrows to be darker near the origin and brighter as the distance r=sqrt (x^2+y^2) from the origin grows.

A: Okay, thanks to the comments of @ImportanceOfBeingEarnest, I can answer the question as follows: The C-argument in the quiver function can just take a function of the plotting coordinates. Hence, it suffices to add "r" in the quiver function as follows:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

fig = plt.figure(figsize=(15,10))
ax = fig.gca(projection='polar')

n=30
m=8

thetas = np.linspace(0, 2*np.pi, n)
radii = np.linspace(0.15, 1, m)
theta, r = np.meshgrid(thetas, radii)
p = .3
Er = p*2*np.cos(theta)#/r**3
Et = p*np.sin(theta)#/r**3
#we leave out the 1/r**3 part because it would make our arrows infinitely long near the origin.
#Instead we use a colormap to indicate the strength of the field as follows

ax.set_title("Dipole field", va='bottom')
ax.quiver(theta, r, Er * np.cos(theta) - Et * np.sin (theta), Er * np.sin(theta) + Et * np.cos(theta), r, pivot='mid', cmap='YlGnBu_r')
plt.show()

The result looks as follows:

The cmap command makes the color coding appear according to the cmap YlGnBu_r.
More color coding maps are given here:
http://matplotlib.org/examples/color/colormaps_reference.html
and here
http://matplotlib.org/users/colormaps.html.


text:
Q: BOX SDK Error while uploading file This is the method I used to authenticate my box and it opens a web view and I successfully got authenticated:
- (IBAction)box:(id)sender {
                NSURL *authorizationURL = [BoxSDK sharedSDK].OAuth2Session.authorizeURL;
                NSString *redirectURI = [BoxSDK sharedSDK].OAuth2Session.redirectURIString;
                BoxAuthorizationViewController *authorizationViewController = [[BoxAuthorizationViewController alloc] initWithAuthorizationURL:authorizationURL redirectURI:redirectURI];
                BoxAuthorizationNavigationController *loginNavigation = [[BoxAuthorizationNavigationController alloc] initWithRootViewController:authorizationViewController];
                authorizationViewController.delegate = loginNavigation;
                loginNavigation.modalPresentationStyle = UIModalPresentationFormSheet;

                [self presentViewController:loginNavigation animated:YES completion:nil];

  }

After this process it returns to same view controller where I have a another action for upload (https://github.com/box/box-ios-sdk-sample-app):
- (IBAction)upload:(id)sender
{

        BoxFileBlock fileBlock = ^(BoxFile *file)
        {
            [self fetchFolderItemsWithFolderID:self.folderID name:self.navigationController.title];

            dispatch_sync(dispatch_get_main_queue(), ^{
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"File Upload Successful" message:[NSString stringWithFormat:@"File has id: %@", file.modelID] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [alertView show];
            });
        };

        BoxAPIJSONFailureBlock failureBlock = ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSDictionary *JSONDictionary)
        {
            BOXLog(@"status code: %i", response.statusCode);
            BOXLog(@"upload response JSON: %@", JSONDictionary);
        };

        BoxFilesRequestBuilder *builder = [[BoxFilesRequestBuilder alloc] init];
        builder.name = @"image1.jpg";
        builder.parentID = self.folderID;

         NSString *path = [[NSBundle mainBundle] pathForResource:@"image1.jpg" ofType:nil];
        NSInputStream *inputStream = [NSInputStream inputStreamWithFileAtPath:path];
        NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
        long long contentLength = [[fileAttributes objectForKey:NSFileSize] longLongValue];

        [[BoxSDK sharedSDK].filesManager uploadFileWithInputStream:inputStream contentLength:contentLength MIMEType:nil requestBuilder:builder success:fileBlock failure:failureBlock progress:nil];
    }

After clicking upload button I receive this following message in console


text:
Q: Can a live tile style be created in WPF? I'm exploring MahApps framework and I want to implement a live tile style.
My question is:
Is it possible to create a live tile style, where the tile's content (predefined images, texts; not content added dynamically) should change periodically and with an animation (MahApps transition)? If so, how can it be done?
I think this behavior could be achieved in code, but I'm wondering if it can be done only in xaml, in a style. Thank you!

A: Yes. It is possible, but it's a hell of a work. I've done it onces before a couple of years ago. I've used this as my guide for it: http://www.sourceblog.mc-auto.info/post/2011/11/23/Live-Icons-in-WPF.aspx
Another take on it would be to get the WP7 silverlight toolkit http://phone.codeplex.com/ and take a look at the HubTile and convert it to your needs.


text:
Q: Method not found: 'Nancy.ErrorPipeline Nancy.ErrorPipeline.op_Addition We updated Nancy from v1.2.0 to 1.3.0 via NuGet. According to the changelog there appear to be no breaking changes relevant to our application. However we are now getting the runtime error

Method not found: 'Nancy.ErrorPipeline
  Nancy.ErrorPipeline.op_Addition(Nancy.ErrorPipeline,
  System.Func`3)'.

in
base.ApplicationStartup(container, pipelines);

in our CustomBootstrapper. We are using Nancy.Bootstrappers.Autofac and have a custom IStatusCodeHandler.
I have cleaned out the packages folder, as well as bin/obj folders, and verified that there is only one version of Nancy after package restore.
How can I resolve or troubleshoot this?

A: (Caveat: I've never used Nancy. This is just a matter of looking at the history in Github.)
It looks like the + operator signature you're using changed from this in 1.2.0:
public static ErrorPipeline operator +
    (ErrorPipeline pipeline, Func<NancyContext, Exception, Response> func)

to this in 1.3.0:
public static ErrorPipeline operator +
    (ErrorPipeline pipeline, Func<NancyContext, Exception, dynamic> func)

That's not a backwardly-compatible change, at the very least at the binary level. As far as the CLR is concerned, that signature will be
public static ErrorPipeline operator +
    (ErrorPipeline pipeline, Func<NancyContext, Exception, object> func)

... so any binary with a reference to the earlier signature won't find what it's looking for.
Do any of your dependencies also depend on Nancy, possibly at v1.2.0? Basically, you need to find out which piece of code is expecting the old signature, so you can rebuild that code against 1.3.0.


text:
Q: Python - Dictionary to NodeTree I ask you for advice
I have a class NodeTree.
and then I have a function create_T (d)
This function takes as input a dictionary d that represents a tree, and creates a tree with nodes of type NodeTree
What do you advise me to do?
Thanks to all

A: Your info is quite scant, so I've made some assumptions. Basically I think you need to know where to start in the tree. If you pick a random point then you have to work upwards and downwards. If you can work out which is the top of the tree then you just need to work downwards. I calculated the top of the tree by doing a set comparison to see which node was not a child of any other nodes.
import itertools

# NodeTree
class Node(object):
    def __init__(self, name):
        self.name = name
        self.children = []

    def add_child(self, child_node):
        self.children.append(child_node)

    def __repr__(self):
        if not self.children:
            return '<%s/>' % self.name
        else:
            children = ''.join([repr(child) for child in self.children])
            return '<%s>%s</%s>' % (self.name, children, self.name)

# create_T(d)
def create_tree(tree_dict):
    # find which node is the top of the tree (assume it is well-formed)
    all_leaves = set(itertools.chain(*tree_dict.values()))
    top_of_the_tree = set(tree_dict.keys()) - all_leaves

    def get_node(name):
        node = Node(name)
        for child_name in tree_dict[name]:
            node.add_child(get_node(child_name))
        return node
    return get_node(top_of_the_tree.pop())

print create_tree({'a': ['b', 'c'],
                   'b': ['d'],
                   'c': ['e'],
                   'd': [],
                   'e': [],
                   'f': ['a']})

giving:

   <f><d/><c><e/></c></f>


text:
Q: How to parse the day of the Date object as an integer? I have a Date object, and I want to get the day number, and add to it another integer. The point is that I have a code like the one below, but it concatenates them as a string, doesn't evaluate them as an integer.
var d = inputDate.getDate();
var num = 4;
var temp = parseInt(d)+num;

Assuming, getDate returns 25 for the 25th day, and if I add 4, the result of temp becomes 254, instead of 29. Any ideas?
EDIT :
In HTML, I have something like this, a datepicker.
<form action="#" method="get">
       <input id="dpicker" type="date">
</form>

Then in JS, I have something like this:
$(document).on("pagechange", function(event, ui) {
    if ($.mobile.activePage[0].id == "ovulInfoPicker") {
        $('input[type="date"]').change(function() {
            inputDate = new Date(this.value);
        });
    }
});

Please also note, I'm using jQuery 1.9.1, and jQuery Mobile 1.3.1, and creating a small mobile app.
EDIT 2:
The value that I want to add to my day, is from a select/option element.

            How many days did your menstrual cycle last?
            <select id="menstrualCycle" onclick="changeFunc('menstrualCycle')">
                <option value="3">3</option>
                <option value="4">4</option>
                <option value="5">5</option>
                <option value="6">6</option>
                <option value="7">7</option>
            </select>

function changeFunc(select) {
    var selectBox = document.getElementById(select);
    var selectedValue = selectBox.options[selectBox.selectedIndex].value;

    if (select == 'monthCycle') {
        monthDays = selectedValue;
        console.log("Month value is: " + monthDays);
    } else if (select == 'menstrualCycle') {
        menstrualDays = selectedValue;
        console.log("Menstrual value is: " + menstrualDays);
    } else if (select == 'lutealPhase') {
        lutealValue = selectedValue;
        console.log("Luteal value is: " + lutealValue);
    }
}

var d = inputDate.getDate();
var temp = d+menstrualDays; // returns 254, for 25th day, and 4 as a value for menstrualDays

A: On changing the select the value will update.
JSFiddle Demo

How many days did your menstrual cycle last?
    <select onChange="changeFunc()" id="menstrualCycle">
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
    </select>

<input type="text" id="result" value="3">

    function changeFunc() {
    var myselect = document.getElementById("menstrualCycle");
    console.log(myselect.options[myselect.selectedIndex].value);

    var day = new Date();
    var z=$(dpicker).val().split("-");

    //var dt = new Date()
    if (myselect == 'monthCycle') {
        monthDays = selectedValue;
        //alert("Month value is: " + monthDays);
    } else if (myselect == 'menstrualCycle') {
        menstrualDays = selectedValue;
        //alert("Menstrual value is: " + menstrualDays);
    } else if (myselect == 'lutealPhase') {
        lutealValue = selectedValue;
        //alert("Luteal value is: " + lutealValue);
    }

    var number = myselect.options[myselect.selectedIndex].value
    var elem = document.getElementById("result");
    elem.value = parseInt(z[2]) + parseInt(number);
}

A: Like I mentioned in the comment, you have to parse the value you get from the options element.
Just for the record: The value is always a string as per definition (http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/idl-definitions.html). Here are all the values you get back from <option>
interface HTMLOptionElement : HTMLElement {
    readonly attribute HTMLFormElement  form;
             attribute boolean          defaultSelected;
    readonly attribute DOMString        text;
    readonly attribute long             index;
             attribute boolean          disabled;
             attribute DOMString        label;
             attribute boolean          selected;
             attribute DOMString        value;
  };


text: Q: Sharepoint enterprise search grey line When I search in the Sharepoint Enterpise Search. Sometimes the gray line is displayed. What are the default settings for displaying the gray line in SharePoint Enterprise Search?


text:
Q: How can i select duplicates in a dict list Python newbiew: I'm using a dict list to store an ascii character along with a score and what I would like to do now is, fill up another dict list that contains all duplicate characters (independent of the score). How can I do this?
I'm appendindg the values onto the list with: lpdictlist.append({"ascii_code":a[2],"confidence":a[6]})

A: You can use Counter class from collections module. One possible solution (works even if ascii_code is integer value):
from collections import Counter

lpdictlist = []
# lpdictlist.append({"ascii_code":a[2],"confidence":a[6]})
lpdictlist.append({"ascii_code":'a', "confidence":1})
lpdictlist.append({"ascii_code":'b', "confidence":2})
lpdictlist.append({"ascii_code":'a', "confidence":4})
lpdictlist.append({"ascii_code":'d', "confidence":10})

c = Counter(i['ascii_code'] for i in lpdictlist)
new_list = [k for k, v in c.items() if v > 1]
print(new_list)

Prints:
['a']