text:
Q: Yii framework new column in database not showing in output of $model->getAttributes() method call? Yii version 1.1.8
I have added a column to a table in a mysql database,
but the new column is not showing in output of $model->getAttributes() method call
I deleted all files in protected/runtime folder, but still no column
config:  'schemaCachingDuration' => 0, // in seconds.  <1 means off
I can add data to the new column directly in the database.
Are there any other things that I can do to debug this?
index.php
<?php

// change the following paths if necessary
$yii=dirname(__FILE__).'/../../framework/yii.php';
$config=dirname(__FILE__).'/protected/config/main.php';

// remove the following line when in production mode
    //debug
        defined('YII_DEBUG') or define('YII_DEBUG',true );
        //show profiler
        defined('YII_DEBUG_SHOW_PROFILER') or define('YII_DEBUG_SHOW_PROFILER',true);
        //enable profiling
        defined('YII_DEBUG_PROFILING') or define('YII_DEBUG_PROFILING',true);
        //trace level
        defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',0);
        //execution time
        defined('YII_DEBUG_DISPLAY_TIME') or define('YII_DEBUG_DISPLAY_TIME',false);

require_once($yii);
Yii::createWebApplication($config)->run();

main.php
<?php
return CMap::mergeArray(array(
    'timeZone'=>'UTC',
    'basePath' => dirname(__FILE__) . DIRECTORY_SEPARATOR . '..',
    'catchAllRequest' => null, // null if online, array('site/offline') if offline,
    'sourceLanguage' => 'en_ca',
    'theme' => 'td',
    'charset' => 'UTF-8',
    'preload' => array('log'),
    'import' => array(
    'application.models.*',
    'application.components.*',
    'application.extensions.*'
    ),
    'modules' => array(
    ),
    // application components
    'components' => array(
    'format' => array(
    ),
    'user' => array(
        // enable cookie-based authentication
        'allowAutoLogin' => true,
        'autoRenewCookie' => true,
    ),
    'widgetFactory' => array(
        'enableSkin' => true,
    ),
    'urlManager' => array(
        ),
    ),
    'db' => array(
        'class' => 'CDbConnection',
        'connectionString' => 'mysql:host=localhost;dbname=mydb',
        'emulatePrepare' => true,
        'initSQLs'=>array("set time_zone='+00:00'"),
        'username' => 'root',
        'password' => '',
        'charset' => 'utf8',
        'tablePrefix' => 'tbl_',
        'enableParamLogging' => true, //show parameter values in log
//      'schemaCachingDuration' => 0, // in seconds.  <1 means off
        'enableProfiling' => YII_DEBUG_PROFILING, //show sql profile info in log
        'nullConversion' => true,
        //'initSQLs'=>array('set time_zone="+00:00"')
    ),
    'errorHandler' => array(
    ),
    'log' => array(
        'class' => 'CLogRouter',
        'routes' => array(
        array(
            'class' => 'CFileLogRoute',
            'levels' => 'error, warning',
            'filter' => 'CLogFilter',
            'enabled' => !YII_DEBUG
        ),
        array(
            'class' => 'CPhpMailerLogRoute',
            'levels' => 'error',
            'emails' => 'neilmcguigan+tderror@gmail.com',
            'filter' => 'CLogFilter',
            'enabled' => false,
        ),
        array(
            'class' => 'CWebLogRoute', // show log messages on web pages
            'enabled' => YII_DEBUG,
            'filter' => 'CLogFilter',
        //'showInFireBug' => false
        ),
        array(
            'class' => 'CProfileLogRoute',
            'enabled' => YII_DEBUG,
            'showInFireBug' => false
        )
        ),
    ),
    'request' => array(

    ),
    'securityManager'=>array(

    )
    ),
    // application-level parameters that can be accessed
    // using Yii::app()->params['paramName']
    'params' => array(
    ),
), require(dirname( __FILE__ ) . '/override.php'));

A: After you have added a new column in your table then just go to Gii and then click on model generator. In that put the name of your table again and then click preview. There would be an option of diff click on that and then copy the highlighted green code and copy paste it in your original modal or better still update overwrite your whole modal. Then check if you are able to get the values inside and are able to get the attributes. This should work.

A: Having just went through this problem -- I found out the new field names need to be in the attributeLabels function in the model
public function attributeLabels()
{
    return array(
        'id' => 'ID',
        'newfield' => 'New Field',
        ...

Be careful with using the "better still update overwrite your whole model" suggestion if you are like me and have a lot of custom code in your models.  As Sankalp Singha suggests, Just copy the "diff" (green part) from using gii and add the part from attributeLabels to your code.


text:
Q: calling categories in a custom post type I'm creating a custom post type by adding the add_action( 'init', 'create_radiotalks' ); text to the functions.php page:
add_action( 'init', 'create_radiotalks' );

function create_radiotalks() {
    register_post_type( 'radiotalks',
        array(
            'labels' => array(
            'name' => __( 'Radio Talks' ),
            'singular_name' => __( 'Radio Talk' ),
            'add_new' => __( 'Add New' ),
            'add_new_item' => __( 'Add New Radio Talk' ),
            'edit' => __( 'Edit' ),
            'edit_item' => __( 'Edit Radio Talk' ),
            'new_item' => __( 'New Radio Talk' ),
            'view' => __( 'View Radio Talk' ),
            'view_item' => __( 'View Radio Talk' ),
            'search_items' => __( 'Search Radio Talks' ),
            'not_found' => __( 'No radio talks found' ),
            'not_found_in_trash' => __( 'No radio talks found in Trash' ),
            'parent' => __( 'Parent Radio Talk' ),
),
            'public' => true,
        )
    );
}

when entering the add new radio talk info, I would like to add the applicable categories and tags, but they do not show up in the admin side bar? How do I make the categories/tags available to my custom post type? thanks for your help.
-don

A: By adding the 'taxonomies' argument:
'public' => true,
'taxonomies' => array( 'category', 'post_tag' ),

A: or by register taxonomy:
<?php
register_taxonomy_for_object_type('category', 'radiotalks');
register_taxonomy_for_object_type('post_tag', 'radiotalks');

redpajama_set_name: RedPajamaStackExchange


text:
Q: WPF binding validation not show error message I have problem when try to validate username textbox field. When i lost focus i except to validator show error.
I create UsernameValidator class where impement ValidationRule
  public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {

            if (this.username == null)
                return new ValidationResult(false, "value cannot be empty.");
            else
            {
                if (this.username.ToString().Length > 3)
                    return new ValidationResult
                    (false, "Name cannot be more than 3 characters long.");
            }
            return ValidationResult.ValidResult;
        }

In xaml i set control template
<ControlTemplate x:Key="validationErrorTemplate">
    <DockPanel>
    <StackPanel Orientation="Horizontal" DockPanel.Dock="Top">
        <Grid Width="12" Height="12">
            <Ellipse Width="12" Height="12"
            Fill="Red" HorizontalAlignment="Center"
            VerticalAlignment="Center"

                     ></Ellipse>
            <TextBlock Foreground="White" FontWeight="Heavy"
            FontSize="8" HorizontalAlignment="Center"
            VerticalAlignment="Center" TextAlignment="Center"
                       ToolTip="{Binding ElementName=ErrorAdorner,
                       Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"
                       >X</TextBlock>
        </Grid>
        <TextBlock Foreground="Red" FontWeight="12" Margin="2,0,0,0"
                   Text="{Binding ElementName=ErrorAdorner,
                   Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"
                   ></TextBlock>
        </StackPanel>
        <AdornedElementPlaceholder
        x:Name="ErrorAdorner" ></AdornedElementPlaceholder>
    </DockPanel>
</ControlTemplate>

And for my textBox username i declare
<TextBox x:Name="usernameTextBox" Validation.ErrorTemplate="{StaticResource validationErrorTemplate}" HorizontalAlignment="Left" Height="23" Margin="115,31,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="277" PreviewKeyDown="OnUsernameTextBoxKeyDown">
<TextBox.Text>
                <Binding Path="Username" Mode="TwoWay" UpdateSourceTrigger="LostFocus">
                    <Binding.ValidationRules>
                        <local:UsernameValidator></local:UsernameValidator>
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
</TextBox

UsernameValidator class is my class for validating .
Program is successfull compailed whitout errors and warrnings.
I follow this tutorial: http://www.codeproject.com/Tips/690130/Simple-Validation-in-WPF

A: WPF by-design silently fails binding operations (As in, nothing is displayed to the user during normal operation).
However when you run a WPF program under a debugger (such as the Run+Debug button in Visual Studio) then you'll see binding errors displayed in the Output window.


text:
Q: Is there a better upper bound in this word problem? Consider the subset $A_n$ of the free group freely generated by $n$ symbols given by those words $w$ that cannot be reduced to the trivial word and such that, whenever a chosen generator is substituted by $e$ on all its appearances on the word, the (changed) word $w$ can be reduced to the trivial word. Is there a better upper bound for $a_n:=\min\{\mathrm{len}(x) \mid x \in A_n\}$, other than the trivial
$$\mathrm{len}([a_1,[a_2,\cdots,[a_n,a_{n-1}]] \cdots ])=2^n+2^{n-1}-2?^{(1)}$$
And if there are better upper bounds, are they given by explicit words?
$^{(1)}$I hope I got it right.

The motivation comes from a "puzzle" that can be used to introduce people to algebraic topology. It consists of asking how you should make a knot around $n$ nails on the wall to hang a painting such that, if you remove any single nail, then the painting will fall.
In trying to reproduce it with a not very ideal chord, $n=4$ already poses quite a challenge ($2^4+2^3-2=22$ operations. Indeed, to be honest, $n=3$ is also quite a hassle).


text:
Q: Cannot add GitHub API header "Authorization token" to GET request in Retrofit2 GitHub APi documentation says that I need to pass access token in header.

This command works fine for me with replacing OAUTH_TOKEN to mine. I try to do the same in code:
    @GET("/user/repos")
    fun getAllUserRepos(
        @Header("Authorization: token") accessToken: String
    ): Call<List<RepoJson>>

But when I get error in enqueque onFailure: Unexpected char 0x20 at 14 in header name: Authorization: token. Then I remove space remove space between Authorization: and token in header and get Unauthorized message from responce in onResponce.
I tried this (also with space between Authorization: and token in header):
    @Headers("Authorization: token MY_VALID_TOKEN")
    @GET("/user/repos")
    fun getAllUserRepos(): Call<List<RepoJson>>

And it executed successfully (through enqueue).
My API:
val api: GiHubApi = Retrofit.Builder()
            .baseUrl("https://api.github.com")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(GitHubApi::class.java)

A: As per doc,
key="Authorization" and value="token VALID_TOKEN"
In the Retrofit,
you need to pass the key to @GET. But you're passing "Authorization: token"
So you need to do it like this.
@GET("/user/repos")
    fun getAllUserRepos(
        @Header("Authorization") accessToken: String
    ): Call<List<RepoJson>>

Call
getAllUserRepos("token $VALID_TOKEN")

A: The header should be:
@GET("/user/repos")
fun getAllUserRepos(
    @Header("Authorization") accessToken: String
): Call<List<RepoJson>>

Been there, done that.


text:
Q: Ruby Rack Heroku: Serving Static Files I have followed the Heroku guide on deploying static files using Ruby Rack (https://devcenter.heroku.com/articles/static-sites-ruby), but I was unable to access any HTML file in \public apart from index.html. Namely, localhost:9292/test.html still maps to index.html. (All my style and js files serve correctly).
Below is my config.ru file. I know what's wrong, but not sure about a valid solution?
use Rack::Static,    :urls => ["/images", "/js", "/css"],   :root => "public"

run lambda { |env|   [
    200,
    {
      'Content-Type'  => 'text/html',
      'Cache-Control' => 'public, max-age=86400'
    },
    File.open('public/index.html', File::RDONLY)   ] }

A: For your config.ru file, try:
use Rack::Static,
    :urls => ["/images", "/js", "/css"],
    :root => "public"

run Rack::File.new("public")

You could also replace the last line with run Rack::Directory.new("public") which would serve up all your files, but would give a file browser like interface if someone went to the url of a directory (like the root directory)

A: I have no Ruby experience and I found this boilerplate project helpful when trying to deploy a static website to Heroku:
heroku-static-site
Particularly, make sure you also have Gemfile and Gemfile.lock files besides the config.ru.
Author's project structure hosts everything in the root directory but you can easily move everything to public/ and correct the config.ru as @looby suggested.


text:
Q: Conversion of inline citations from MS Word to BibLaTeX This answer explains, referring to this article, how to export a bibliography from MS Word to a .bib file. The script has been slightly improved here. However, this script does not do much to convert the actual inline citations to LaTeX citations. For instance, let's apply it to the following sample document:

I get:

This isn't too bad, actually. The citations have been replaced by the tag names in parentheses. Let's update the script slightly, specifically by modifying the script from line 773–837 so that each citation output looks something like this:
<xsl:template match="b:Citation/b:Source[b:SourceType = 'Book']">
  <html xmlns="http://www.w3.org/TR/REC-html40">
    <body>
        <!-- Defines the output format as (Author, Year)-->
        <xsl:text>@@@parencite{</xsl:text>
        <xsl:value-of select="b:Tag"/>
        <xsl:text>}</xsl:text>
    </body>
  </html>
</xsl:template>

Then I get the following instead:

Now after using e.g. pandoc or writer2latex to convert this into LaTeX code, all I have to do is string replace @@@ by \, and I'll have myself a working BibLaTeX document.
The only problem is that the page number ("p. 223") from the second citation is gone. How can I get it to output @@@parencite[223]{Johnson22} in this case?
I tried looking at the +8000 line source code of the other citation styles, but they were unfortunately quite complicated. I managed to find the line of code <xsl:value-of select="$pages"/> somewhere, so I tried this:
<xsl:template match="b:Citation/b:Source[b:SourceType = 'Book']">
  <html xmlns="http://www.w3.org/TR/REC-html40">
    <body>
        <!-- Defines the output format as (Author, Year)-->
        <xsl:text>@@@parencite[</xsl:text>
        <xsl:value-of select="$pages"/>
        <xsl:text>]{</xsl:text>
        <xsl:value-of select="b:Tag"/>
        <xsl:text>}</xsl:text>
    </body>
  </html>
</xsl:template>

But then MS Word no longer recognized the style, which (according to my brief experience) means that the script is no longer valid.
How can I make this work?


text:
Q: order by in linq with multiple scenarios I have to order the following by contractor name with the following logic: first the columns that are parents followed by their children.

For example here in the image, I want this result:

*

*the first row should be Panhandle Mental Health Ctr/Region 1 because it is the first parent (in alphabetic order);

*the second row should be Panhandle Medical Health Center - Sidney because it is the first child in alphabetic order;

*the third row should be Region 1 - Panhandle Prevention Coalition

*the next rows should be the next parent, followed by his children and so on.

I have tried something like this so far, I am sure it's not correct approach, and it is still not satisfying all scenarios.
.AsEnumerable().OrderBy(x => x.ContractorName.Split(' ').First()).ThenBy(p=>p.ParentName).ToList<ContractModel.providers>()

A: To obtain what you are looking for you need to do as follows:
.AsEnumerable()
    .Where(p => p.IsParent)
    .OrderBy(p => p.ContractorName)
    .SelectMany(p =>
        {
            // You will return this list
            var list = new List<YourType>();
            // First you add the parent
            list.Add(p);
            // Then you add all the children ordered by name
            // (I assume you can get them via a relation)
            list.AddRange(p.Children.OrderBy(c => c.ContractorName).ToList());
            // Finally you return the list
            return list;
        }).ToList();

The logic here is to first extract the records that are parents and then concatenate all his children. The SelectMany will do the trick to return a List.

A: Create an CompareTo method
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Contractors> contractors = new List<Contractors>() {
                new Contractors() { ContractorName = "Panhandle Mental Health Center - Sidney", ParentName = "Panhandle Mental Health Ctr/Region 1"},
                new Contractors() { ContractorName = "Panhandle Mental Health Center - Sidney", ParentName = "Panhandle Mental Health Ctr/Region 1"},
                new Contractors() { ContractorName = "Panhandle Mental Health Ctr/Region 1"},
                new Contractors() { ContractorName = "Region 1 - Panhandle Prevention Coalition", ParentName = "Panhandle Mental Health Ctr/Region 1"},
                new Contractors() { ContractorName = "Region 1 Behavioral Health - Ave. D. Scottsbluff",ParentName = "Region 1 Behaviorial Health Authority"},
                new Contractors() { ContractorName = "Region 1 Behavioral Health Authority"},
                new Contractors() { ContractorName = "Region 1 Behavioral Health Authority - 16 St Scottsbluff", ParentName = "Region 1 Behaviorial Health Authority"},
            };
            contractors.Sort((x,y) => x.CompareTo(y));
        }
    }
    public class Contractors : IComparable< Contractors>
    {
        public string ContractorName { get; set; }
        public string ParentName { get; set; }

        public int CompareTo(Contractors contractor)
        {
            if (this.ContractorName == null || this.ContractorName.CompareTo(contractor.ContractorName) == 1)
                return 1;
            if (contractor.ContractorName == null || this.ContractorName.CompareTo(contractor.ContractorName) == -1)
                return -1;
            if (this.ParentName == null || this.ParentName.CompareTo(contractor.ParentName) == 1)
                return 1;
            if (this.ParentName == null || this.ParentName.CompareTo(contractor.ParentName) == -1)
                return -1;
            return 0;

        }

    }

}


text:
Q: Rank() with PhpMyAdmin I'm trying to calculate some data but I need the RANK() function. Sadly, PhpMyAdmin doesn't have it.
This is the Model

And this is how the query should be
SELECT bom.bom_id, RANK() OVER (PARTITION BY earlier_bom.bom_id ORDER BY bom.bom_id) AS pathIndex FROM bom RIGHT JOIN earlier_bom WHERE [condition]
Using this example I should get the PathIndex column.
I already got the Depth and Parent ID, but I can't get the index, so if you know another option to create a query similar to rank function it would be apreciated!


text:
Q: How to maintain a range definition in excel vba after underlying cell changes? Excel noob here (sorry).  My macro runs like this:
Dim CellA, CellB As Range
Range("A1") = 25
Set CellA = Range("A1")
Range("A1") = 50
Set CellB = Range("A1")

The problem is after this, CellA also will be equal to 50.
Is it possible to adjust the code to keep CellA as 25 but still use A1 as the source?

A: No, it's clearly not possible, I'll try to explain you why.
In this piece of code, you are saying:
Dim CellA As Range '<-- CellA will be an object of type "Range"
Set CellA = Range("A1") '<-- CellA will point to the Range("A1")

This means that, no matter what, CellA will always be pointing to Range("A1"). So, when you change:
Range("A1") = 50 '<-- please note: when you write this, you're "implicitely" writing Range("A1").Value = 50. The ".Value" is in fact the default property of the range object (if you don't specify anything, you will set that one).

... the value of CellA will be the value of Range("A1"), which is exactly what you told it to be when saying Set CellA = Range("A1").
If you want to store the value (and not the Range object, as you're doing now), and not the whole range object, then you should do this:
Dim CellA As Long
CellA = Range("A1").Value

Even if the value of Range("A1") will change later in run-time, the value of CellA will still be the old one.
And this is surely what you want to do, because you don't care about the whole range object but only about its value: do you?


text:
Q: Some Boolean Algebra Simplication basic I wanna ask some basic law of boolean algebra.
What i learn is :
 1. A+A'B=A+B
 2. A+AB'=A+B'
 3. A+AB=A
 4. A+A'B'=A+B'

but i meet some condition like :
A'+AB
so, what is the answer for A'+AB?

A: Let's say A' = D so when A is false, then D is true and vice versa.
Then A' + AB = D + D'B and if you understand your first equation:
D + D'B = D + B = A' + B

Regarding your comment:
I'll use this equality: AB + A'B = B and I will combine the first with the third and the second with the fifth term:
x'y'z'+x'yz+xy'z'+xy'z+xyz = y'z' + yz + xy'z

Now, from the result, I can do this:
y'z' + yz + xy'z = yz + y'(z' + zx)

and now, using using A' + AB = A' + B:
yz + y'(z' + zx) = yz + y'(z' + x) = yz + y'z' + y'x

or do this:
y'z' + yz + xy'z = y'z' + z(y+ xy') = y'z' + z(y + x) = y'z' + zy + xz

Are they different? No, take a look at this:
x y z | yz + y'z' + y'x | y'z' + zy + xz
0 0 0 |       1         |       1
0 0 1 |       0         |       0
0 1 0 |       0         |       0
0 1 1 |       1         |       1
1 0 0 |       1         |       1
1 0 1 |       1         |       1
1 1 0 |       0         |       0
1 1 1 |       1         |       1

A: You can use this open source project to solve basic boolean expression, its solve all the basic boolean expression


text:
Q: POSTGRES REPLICATION for new master We are putting together an architecture to support High Availability for our Postgres 9.5 Database. We have 1 master and 3 slaves Replicating the data of the master.  When The master goes down Slave 1 is promoted to new master but  Slave 2 and Slave 3 are still pointing to the previous master and not the updated master node.
 Is there a way to make the slaves to read from the new master dynamically . Or does it require changing the configurations manually and restarting the slaves?

A: There's no short answer, but I'll try:

*

*When primary server fails you'll promote one slave, and reconfigure all other slaves to target the new master. However there's one scenario in which reconfiguring other slaves might not be needed: if you are using "WAL archiving", and your archive is stored on a shared drive which survived the failure of the old primary. If the new primary continues to use the same shared store you might not need to reconfigure other slaves. Again, I've never tried this - you can try.

*If your replication mechanism is based on "replication slots" (introduced in PostgreSQL 9.4) - then you have to reconfigure all the slaves. In this case actually you'll have to rebuild replication on all other slaves from scratch (as if they've never been slaves at all). Nevertheless, in my opinion "replication slots" are better choice.

Regarding automation: You've asked if it is possible to automatically reconfigure other slaves, but thing you've missed to mention is if you have any failover automation implemented. What I'm trying to say is that PostgreSQL itself will not automatically perform failover (promote one of slaves when the master fails). At least you have to create "trigger file" on the slave to be promoted, and you have to do this manually or by using another product (for example pgpool2).
If you use pgpool2 - you can setup automatic slave reconfiguration by setting follow_master_command pgpool.conf value.
Finally I'll strongly recommend reading this tutorial - it'll make your life easier.
Edit:
I've forgot to say two things:

*

*Automatically reconfiguring all other slaves as soon as the new master is promoted might not be a good idea, especially if you have many slaves. It'll put additional pressure on your new primary, and on your network, so in some cases it is better to postpone this for night hours for example. More on this in the mentioned tutorial.

*I've wrote the tutorial.

A: As e4c5 commented, you can use repmgr for managing this type of tasks. I have tried repmgr and I was done without a problem.
I have followed a tutorial for doing that and here is the link:
http://jensd.be/591/linux/setup-a-redundant-postgresql-database-with-repmgr-and-pgpool
I hope following this tutorial you can do what you want without any problem.


text:
Q: Getting information from OrientationEventListener manually on Android I am using OrientationEventListener to get information from orientation sensor. I am @Overriding the onOrientationChanged(int orientation) method and everything is working great.
There is only one small problem, if the app is launched and the orientation does not change since it start I never get onOrientationChanged method to start and never get idea about the orientation of the phone.
Is there a way to somehow send information to OrientationEventLister that the orientation has "changed" manually? Thus running through the onOrientationChanged method and get the initial orientation at the beginning.

A: You can access current orientation via Configuration class. And you can access current configuration via Context instance.


text:
Q: Constructing contingency tables including transitions that do not occur I have a shuffled sequence of behaviours from a list constructed from my data. From this list of behaviours I want to create a contingency table with each transition from one step in the sequence to the next. Once I have this table, I want compare this to my real observed data. Basically comparing one contingency table to another. I have come across a problem where if there is one behaviour state that occurs only once, and happens to be randomly assigned to the first position, my contingency table does not contain one column or row (as the transition from a behaviour to that one does not occur). Then the arrays are non-conformable e.g. observed contingency table to shuffled contingency table.
example
    Pbehav1<- 0.9
    Pbehav2<- 0.1
    Pbehav3<- 0
    Pbehav4<- 0
    Pbehav5<- 0
    Pbehav6<-0
    Pbehav7<-0
    Pbehav8<-0
    Pbehav9<-0
    Pbehav10<-0

    Trans<-10

      Behavno<-2

      behaviourlist<-c(rep("a", round(Pbehav1*Trans)), rep("b", round(Pbehav2*Trans)), rep("c", round(Pbehav3*Trans)),rep("d", round(Pbehav4*Trans)), rep("e", round(Pbehav5*Trans)), rep("f", round(Pbehav6*Trans)),rep("g", round(Pbehav7*Trans)), rep("h", round(Pbehav8*Trans)), rep("i", round(Pbehav9*Trans)),rep("j", round(Pbehav10*Trans)))

    random<-sample(behaviourlist)
    random
     [1] "b" "a" "a" "a" "a" "a" "a" "a" "a" "a"
    random1<-random[1:(length(random)-1)]

    random2<-random[2: length(random)]

    shuffledcontingencytable <- table(random1, random2)
    shuffledcontingencytable
           random2
    random1 a
          a 8
          b 1

Another shuffle of the behaviourlist is more likely to produce:
 shuffledcontingencytable
           random2
    random1 a b
          a 7 1
          b 1 0

I need all shuffled contingency tables to contain both rows and columns (determined by the probability of each behaviour occurring --- Pbehav1<- 0.9
        Pbehav2<- 0.1), filled with 0's if a transition does not occur. This is part of loop to compare the shuffled contingency table to an observed (fixed) contingency table.
I'd really appreciate any help, I'm new to R and have been struggling with this for a couple of days.
Thanks!


text:
Q: mc: edit skin color I am trying to edit color skins for midnight commander. When using 256 color palette, the colors are called color1 to color255. I am looking for particular tone of blue. Is there a palette of all 256 colors, where I can choose from? So that I can actually see that color24 is dark blue, etc.

A: I believe the xterm-256 colors chart is what you're looking for.

A: Alternatively, you can use names rgb000 to rgb555, and gray0 to gray23. See the sand256.ini skin definition file for details. Also the 256colors2.pl script from xterm's source might come handy.


text:
Q: fadeOut current content and fadeIn new content jquery I am trying to create a side menu such that when user click on a link the current content in the div(middle of the page) should fadeout and new page content should fadeIn and I created this method:

However, the effect is not as expected, anyone know how to enhance this method?
I expected to fadeout current content to background page and fadeIn new content.
But the current content just disappears
My html code:

 Contact

 Register

 Login

 Submit paper

 tabs menu test

profile

check status of reviews

        About us | Terms of service | Privacy Policy

A: Try:

$("#content").fadeOut('slow', function(){
    $("#content").load(page, function () {
            $(this).fadeIn('slow');
    });
});

A: Use a Callback in your load. Otherwise it fades in instantly:
var content = $('#content');
content.fadeOut().load(page, function() {
    content.fadeIn();
});


text:
Q: Create folder failed when root is Thanks for others help , i can create folder succeed now.
But i get a strange issue if android emulator doesn't has sdcard, i can't create the folder.
I can't figure it out..
Here is my code:
try {
            if (Environment.getExternalStorageState()
                    .equals(Environment.MEDIA_MOUNTED)) {
                System.out.println("can be read and write");
                File sdFile = android.os.Environment.getExternalStorageDirectory();
                //String path = sdFile.getPath() + File.separator + "DestPdf";
                String path = sdFile.getPath() + "/DestPdf";
                File dirFile = new File(path);

                if (!dirFile.exists()) {// if folder doesn't exist
                    System.out.println("create file");
                    dirFile.mkdirs();// create file
                    System.out.println(dirFile.toString());
                }
            }
        } catch (Exception ex) {
            ex.toString();
        }

If my android emulator has sdcard root, i can create the folder DestPdf:

If there is no sdcard , i print the root is /storage/emulated/0/DestPdf, i create the folder failed, the folder emulated has nothing...

Any help would be appreciated .  Thanks in advance.

A: you can use your app Internal Package folder for saving data,
 context.getFilesDir().getPath()

context is here Activity instance.Ok?
Do with it..


text:
Q: Jquery can't load updated JSON file I have a local server (vagrant) and I'm loading a JSON file through jquery.
Every time I want to change the json file I need to create a new file because the jquery (getJSON) gets error if the file isnt identical as the first time imported.
I guess it's something in the ubuntu local server, but I can't figure out what.
Someone have any idea?


text:
Q: Is std::string() the same as std::string("") Suppose I have a function that returns a std::string. Certain circumstances mean that the string is not populated with anything.
Is returning std::string() exactly equivalent to std::string("")? For example, would c_str() or data() give you the same character sequence? Perhaps the std::string("") invokes a short string optimisation but std::string() does no such thing until some characters are added.
Does anyone know if the current standard (C++11) says anything definitive?

A: There's certainly no member function on std::string that would allow you to distinguish between a std::string() and a std::string("").
I defer to a philosopher or logician to verify if that satisfies any definition of equality.
As for the standard itself, it states that std::string() will leave the capacity unspecified but std::string("") will define a capacity of at least zero. So the internal state of the object could be different.
On my particular STL implementation (MSVC2012), std::string() calls a function called _Tidy whereas std::string("") calls _Tidy and assign. (The base class initialisation is identical). assign is a standard std::string function.
So could they be different? Yes.
Can you tell if they are different? No.

A: If we look at the effects of each constructor in the C++ standard, section § 21.4.2 [string.cons] :
For explicit basic_string(const Allocator& a = Allocator()) :

*

*data() : a non-null pointer that is copyable and can have 0 added to    it

*size() : 0

*capacity() : an unspecified value

For basic_string(const charT* s, const Allocator& a = Allocator()) :

*

*data() : points at the first element of an allocated copy of the array whose first element is pointed at by s

*size() : traits::length(s)

*capacity() : a value at least as large as size()

So strictly speaking, both constructs are not identical : in particular, the capacity of the constructed std::string objects might be different.
In practice, it's unlikely that this possible difference will have any observable effect on your code.

A: Yes, they are both same. Default constructor of std::string prepares an empty string same as ""

explicit basic_string( const Allocator& alloc = Allocator() );
Default constructor. Constructs empty string (zero size and
unspecified capacity)

basic_string( const CharT* s, const Allocator& alloc = Allocator() );
Constructs the string with the contents initialized with a copy of the null-terminated character string pointed to by s. The length of the string is determined by the first null character. The behavior is undefined if s does not point at an array of at least Traits::length(s)+1 elements of CharT.

A: The only difference is that  std::string() knows at compile-time that it will produce a zero-length string, while std::string("") has to use strlen or something similar to determine the length of the string it will construct at run-time.  Therefore the default-constructor should be faster.


text:
Q: Set Controller Property Asynchronously In Constructor I have a fully async MVC API that injects an interface into all of its controllers:
public PageController(IDataAdapter dataAdapter) {
    _dataAdapter = dataAdapter;
}

The implementation of the interface needs to have an access token set on its SQLConnection object. This access token is needed for the managed identity secure access (see https://learn.microsoft.com/en-us/azure/app-service/app-service-web-tutorial-connect-msi). This token needs to be set when the controller is constructed, so on every new request. The token can change, so we can't have it be a static value. This is what we have in the interface implementation today:
public partial class DataAdapter : BaseEntityDataAdapter, IDataAdapter {
    AppInsightsLogger _log = new AppInsightsLogger();

    #region Constructor
    /// <summary>
    /// Instantiate the data adapter and pull out the dsn information
    /// </summary>
    public DataAdapter() : base("db") {
        try {
            var conn = base.Database.Connection as System.Data.SqlClient.SqlConnection;
            conn.AccessToken = (new AzureServiceTokenProvider()).GetAccessTokenAsync("https://database.windows.net/").Result;
        } catch (Exception ex) {
            _log.LogError(ex);
            throw;
        }
    }
}

You can see that we use .Result to evaluate the async operation, which in turn is actually running it synchronously. I know I should be using a factory pattern, like this below instead:
public async Task<DataAdapter> ConstructAdapterAsync() {
    try {
        DataAdapter da = new DataAdapter();
        var conn = da.Database.Connection as System.Data.SqlClient.SqlConnection;
        conn.AccessToken = await (new AzureServiceTokenProvider()).GetAccessTokenAsync("https://database.windows.net/");

        return da;
    } catch (Exception ex) {
        _log.LogError(ex);
        throw;
    }
}

But this still leaves me with the problem that in the controller constructor, I can't call an async factory function without forcing it to run synchronously. Is there anyway that I can set this property asynchronously?

A: When I needed to some something similar, I used a factory pattern, but with two key things:

*

*Make the factory method a static method in the class itself, since this gives you access to the private properties and methods.

*Mark the constructor as private so that no one can use the class without using the factory method.

In your case, it would look something like this:
public partial class DataAdapter : BaseEntityDataAdapter, IDataAdapter {
    AppInsightsLogger _log = new AppInsightsLogger();

    private DataAdapter() : base("db") { }

    public static async Task<DataAdapter> ConstructAdapterAsync() {
        DataAdapter da = new DataAdapter();
        try {
            var conn = da.Database.Connection as System.Data.SqlClient.SqlConnection;
            conn.AccessToken = await (new AzureServiceTokenProvider()).GetAccessTokenAsync("https://database.windows.net/");

            return da;
        } catch (Exception ex) {
            da._log.LogError(ex);
            throw;
        }
    }
}


text:
Q: How can I make this C# code more efficient? I have a piece of code as follows: it retrieves a Json string, parses it, and if required sets the value in the specific node:
 JObject jObject = JObject.Parse(JsonString);
 dynamic dModel = jObject;
 var url = dModel.Value<string>("Urllink");

How can I change this to something like below by using the ? expression?
 if (string.IsNullOrEmpty(url))
     url = url;
 else
     url = "#_urlString";

How can I make lines 1 - 5 more efficient?

A: url=string.IsNullOrWhiteSpace(url) ? url : "#_urlString";


text:
Q: I am creating UML for an information system which is needed to help deal with the editing of the magazine I have been tasked to create one use case to cover the main functionality of the scenario below. So far the use case which I have come up with is create magazine issue and the actor is the Editor. However, I'm not sure about the part where the editor edits the advertisement and sends it to the processing centre and how to include that in the use case. Any advice on how I can go about doing correctly would be helpful or any improvements which can be made would be appreciated. I have attached what I have done so far as well as the case study.
This is the case study which I am creating the UML for
Use case created so far

A: There is much more process and behaviour described in the scenario text than is logical to represent in one Use Case. To me, this would be more usefully described as using many Use Cases and several actors.
Do you have a specific flow within the scenario that you want to model? For example, placing an advert, moderating an advert, sending to the print shop? All of these could be Use Cases on their own. You would do well weed out and narrow down more exactly. Remember that a Use Case needs to deliver something business-useful to the User or a Business that they represent and needs to have a clear and unambiguous objective.


text:
Q: DotNet app receives Gateway 502 (proxy server error) - after posting large file to web server I've seen questions like this asked in a few places but I haven't seen an answer which helps me.  Hoping that you can assist!
Situation:

*

*Uploading files using a .NET workstation client to an Apache web server backed by Tomcat.

*Small files work just fine. Larger files POSTS are rejected with http error 401 around the .copyto command.  The subsequent GetResponse errors out with the message "The remote server returned an error: (502) Bad Gateway. The proxy server received an invalid response from an upstream server"   The error is seen immediately.  It's not timing out.

*CURL can upload the same "large" file without issue.

*The terms "small" and "large" are relative:  small = 88 bytes.  large = 3.17 MB.  I understand that this "large" file is tiny for most purposes.

So, the problem must be in my code.   Here is a simplified form of that code (leaving out the exception handlers).
    Dim request As HttpWebRequest = CType(WebRequest.Create("http://mysite"), HttpWebRequest)
    request.Method = "POST"
    request.Credentials = New NetworkCredential("userid","password")
    request.ContentType = "application/octet-stream"
    request.SendChunked = True
    request.UserAgent = "Support Tools"
    request.CookieContainer = New CookieContainer

    Using fileStream As Stream = New FileStream("C:\sourceFile", FileMode.Open)
        request.ContentLength = fileStream.Length
        Dim uploadStream As Stream = request.GetRequestStream
        fileStream.CopyTo(uploadStream)
    End Using

    Dim response As WebResponse = request.GetResponse()

Thank you for your time.
Per request, here is the complete code.  Note that it relies upon variables defined elsewhere within the class.
    Public Sub SubmitFileToSis(ByVal operation As String, ByVal sourceFile As String)
    Dim request As HttpWebRequest = WebRequest.Create(_EndPoints(operation.ToLower))
    request.Method = "POST"
    request.Credentials = New NetworkCredential(_SisUserId, _SisUserPassword)
    request.ContentType = "application/octet-stream"
    request.SendChunked = True
    request.UserAgent = "Support  Tools"
    request.CookieContainer = New CookieContainer

    Try
        Using fileStream As Stream = New FileStream(sourceFile, FileMode.Open)
            request.ContentLength = fileStream.Length
            Dim uploadStream As Stream = request.GetRequestStream
            fileStream.CopyTo(uploadStream)
        End Using
    Catch ex As WebException
        If (ex.Status = WebExceptionStatus.ProtocolError) Then
            Dim response As WebResponse = ex.Response
            Using sr As StreamReader = New StreamReader(response.GetResponseStream())
                _SubmissionResult = String.Format("Error Uploading: {0} - {1} - {2}", ex.Status.ToString, ex.Message, sr.ReadToEnd())
            End Using
        Else
            _SubmissionResult = String.Format("Error Uploading: {0} - {1} ", ex.Status.ToString, ex.Message)
        End If
        Exit Sub
    Catch ex As Exception
        _SubmissionResult = String.Format("Error Uploading: {0} ", ex.Message)
        Exit Sub
    End Try

    Try
        Dim response As WebResponse = request.GetResponse()
        Using sr As New StreamReader(response.GetResponseStream(), Encoding.UTF8)
            _SubmissionResult = sr.ReadToEnd()
        End Using
        _SubmittedDataSetUid = GetBetween(_SubmissionResult, "reference code ", " to track")
    Catch ex As WebException When (ex.Status = WebExceptionStatus.ProtocolError)
        If (ex.Status = WebExceptionStatus.ProtocolError) Then
            Dim response As WebResponse = ex.Response
            Using sr As StreamReader = New StreamReader(response.GetResponseStream())
                _SubmissionResult = String.Format("Error Reading Response: {0} - {1} - {2}", ex.Status.ToString, ex.Message, sr.ReadToEnd())
            End Using
        Else
            _SubmissionResult = String.Format("Error Reading Response: {0} - {1} ", ex.Status.ToString, ex.Message)
        End If
        Exit Sub
    Catch ex As Exception
        _SubmissionResult = String.Format("Error Reading Response: {0} ", ex.Message)
        Exit Sub
    End Try

End Sub

A: Eureka!!  I needed to add "Authorization" to the HttpWebRequest Headers.  There were a couple of other minor changes but they were for readability and cleanliness.
The new working template (at least for crawling stage) is:
Dim request As HttpWebRequest = WebRequest.Create("http://mysite")
request.Method = WebRequestMethods.Http.Post
request.Credentials = New NetworkCredential("userid","password")
request.ContentType = "application/octet-stream"
request.SendChunked = True
request.UserAgent = "Support Tools"
request.CookieContainer = New CookieContainer
Dim authInfo As String = Convert.ToBase64String(Encoding.UTF8.GetBytes(String.Format("{0}:{1}", "userid","password")))
request.Headers.Add("Authorization", String.Format("Basic {0}", authInfo))

Using fileStream As Stream = New FileStream("C:\sourceFile", FileMode.Open, FileAccess.Read)
    request.ContentLength = fileStream.Length
    Dim uploadStream As Stream = request.GetRequestStream
    fileStream.CopyTo(uploadStream)
End Using

Dim response As WebResponse = request.GetResponse()


text:
Q: How can I add a "::" operator to my VIM syntax highlighting file? I am using a language embedded inside of Scala that has a :: operator. I would like to modify my scala.vim syntax file to recognize this new operator.
This is what I've tried (the first line works fine, but I don't know how to add the :: operator to it):
syn match   COperator "[&|~><!)(*#%@+/=?:;}{,.\^\-\[\]]"
syn match   COperator "\v::"
syn match   COperator "\v\:\:"
hi link COperator Special

Any advice?

A: An existing scalaOperator ":\{2,\}" was causing all sequences of : to match (if there are two or more series of :), overriding my own syn match COperator statements.
The solution to get :: to match as a COperator was to simply rename the scalaOperator that matches series of : to a COperator:
syn match COperator ":\{2,\}"

Summary: check for existing match rules that override your own match rules.


text:
Q: ts object not recognised in hybridModel of forecastHybrid package Data is something like this:
df <- tribble(
    ~y,~timestamp

    18.74682, 1500256800,

    19.00424, 1500260400,

    18.86993, 1500264000,

    18.74960, 1500267600,

    18.99854, 1500271200,

    18.85443, 1500274800,

    18.78031, 1500278400,

    18.97948, 1500282000,

    18.86576, 1500285600,

    18.55633, 1500289200,

    18.79052, 1500292800,

    18.74790, 1500296400,

    18.62743, 1500300000,

    19.04696, 1500303600,

    18.97851, 1500307200,

    18.70956, 1500310800,

    18.92302, 1500314400,

    18.91465, 1500318000,

    18.61556, 1500321600,

    19.03535, 1500325200 )

I'm trying to apply hybridModel on timeseries data to perform ensemble.Below is my code:
library(tidyquant)

library(forecast)

library(timetk)

library(sweep)

library(forecastHybrid)

df <- mutate(df, timestamp = as_datetime(timestamp))

tk_ts_df <- tk_ts(df, start = 1, freq = 3600, silent = TRUE)

fit <- hybridModel(tk_ts_df)

On fitting timeseries object tk_ts_df (ts object) to hybridModel; it's giving error : "The time series must be numeric and may not be a matrix or dataframe object."
But on link: https://cran.r-project.org/web/packages/forecastHybrid/vignettes/forecastHybrid.html
It's clearly mentioned : The workhorse function of the package is hybridModel(), a function that combines several component models from the "forecast" package. At a minimum, the user must supply a ts or numeric vector for y
Please suggest what I'm doing wrong.

A: The "forecastHybrid" requires that the input timeseries is a numeric vector or ts type. While the "timekit" package does return a ts object, it also adds additional attributes that are not in regular ts objects so input checks failed.
See discussion here. and the fixing commit here.
The latest version from Github incorporating the fix can be downloaded with

devtools::install_github("ellisp/forecastHybrid/pkg")


text:
Q: How to use if else condition in MariaDB stored procedure? When I am trying to use IF Else condition in my stored procedure, I am getting the syntax error

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'sortby = 1  THEN
value2, value3 ASC;

As per documentation, the syntax is
IF condition THEN
    statements;
ELSE
    else-statements;
END IF;

My Stored Procedure:
DELIMITER $$
      CREATE PROCEDURE test(IN _code  INT, IN testformat SMALLINT(5), IN testcurrency CHAR, IN testdate Date, IN tesval CHAR(1),  IN sortby INT)
      BEGIN
           SELECT   value1, valu2, value3, value4
           FROM     shop
           WHERE     CODE1  = _code
           ORDER BY
          IF  sortby = 1  THEN
             value2, value3 ASC;
          ELSE
            value2, value3 DESC;
         END;
     END$$
DELIMITER ;

I couldn't find the issue. Thanks for your help.

A: The IF/THEN/ELSE structure is a statement on its own. It is not an expression you can put in the ORDER BY clause of a query.
But you can't use the IF(condition, expr1, expr2) function, because that function must return a scalar, not a list of columns and an SQL keyword.
The solution to your question is:
DELIMITER $$
  CREATE PROCEDURE test(
    IN _code  INT,
    IN testformat SMALLINT(5),
    IN testcurrency CHAR,
    IN testdate Date,
    IN tesval CHAR(1),
    IN sortby INT)
  BEGIN
    IF sortby = 1 THEN
       SELECT   value1, valu2, value3, value4
       FROM     shop
       WHERE     CODE1  = _code
       ORDER BY value2, value3 ASC;
    ELSE
       SELECT   value1, valu2, value3, value4
       FROM     shop
       WHERE     CODE1  = _code
       ORDER BY value2, value3 DESC;
    END IF;
  END$$
DELIMITER ;

Since the only difference is an SQL keyword (not a value), the only way to shorten this would be to use dynamic SQL:
DELIMITER $$
  CREATE PROCEDURE test(
    IN _code  INT,
    IN testformat SMALLINT(5),
    IN testcurrency CHAR,
    IN testdate Date,
    IN tesval CHAR(1),
    IN sortby INT)
  BEGIN
    SET @query = CONCAT('
       SELECT   value1, valu2, value3, value4
       FROM     shop
       WHERE     CODE1  = _code
       ORDER BY value2, value3 ', IF(sortby=1, 'ASC', 'DESC'));
    PREPARE stmt FROM @query;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
  END$$
DELIMITER ;


text:
Q: Overloading << operator to print vector I'm trying to overload the << operator to print a vector that contains elements of type Position (vector).
I managed to overload the << operator for type Position, but I can't figure out how to do it for vector. Can you help?

//position.h

#ifndef POSITION_H
#define POSITION_H
#include <iostream>    // using IO functions
using namespace std;

class Position {
private:
    int row;
    int column;

public:
    friend ostream& operator<<(ostream& os, const Position& P);
    friend ostream& operator<<(ostream& os, const vector<Position>& VP);
};

#endif

//position.cpp
#include"Position.h"
#include <iostream>    // using IO functions
#include<vector>

ostream& operator<<(ostream& os, const Position& P)
{
    os << '(' << P.row << ',' << P.column << ')' << endl;
    return os;
}

ostream& operator<<(ostream& os, const vector<Position>& VP)
{
    Position placeholder;

    for (int i = 0; i != VP.size(); i++)
    {
        placeholder = VP.at(i);
        cout << placeholder << endl;
    }
    return os;
}

int main()
{
    Position C1(2, 1);
    Position C2(3, 1);
    Position C3(4, 1);

    vector<Position> cans;
    cans.push_back(C1);
    cans.push_back(C2);
    cans.push_back(C3);

    cout << cans;

    system("pause");
}

A: I'm sure there's a duplicate on StackOverflow somewhere, but I cannot find it. I'm a bit surprised about this question, as I don't really see a critical issue at first sight. Did you get a compiler error or segmentation fault?
Every time you assign to Placeholder, you make a copy. This is not necessary at all: you can directly access the element at the index. As you limit the index to 0 to size(), you don't have to worry about going out-of-bounds, so don't use .at(i), which throws an exception if you go out of bounds. Just use VP[i].
Also not that std::endl flushes the buffer, which is slow. A normal enter/end-line can be achieved with the '\n' character.
Finally, using namespace std; is considered bad practice.
You have multiple options for processing the elements of the vector:
index-based for loop:
for (int i = 0; i != VP.size(); ++i) {
    os << VP[i] << '\n';
}

Iterator-based for loop
for (auto it = cbegin(VP); it != cend(VP); ++it) {
    os << *it << '\n';
}

range-based for loop
for (auto const& el : VP) {
    os << el << '\n';
}

Algorithm for(each) loop
std::for_each(cbegin(VP), cend(VP),
   [](auto const& el) { os << el << '\n'; });

Copy to ostream_iterator
std::copy(cbegin(VP), cend(VP),
    std::ostream_iterator<Position>(os, "\n"));

Note that here you could also write <decltype(VP)::value> instead of <Position> to keep it generic, but that might be overkill in this situation.
And the last two have a C++20 ranges equivalent:
std::ranges::for_each(VP,
   [](auto const& el) { os << el << '\n'; });
std::ranges::copy(VP,
   std::ostream_iterator<Position>(os, "\n"));

Note:
friend ostream& operator<<(ostream& os, const vector<Position>& VP); doesn't have to be a friend of Position! It doesn't require access to the private members.


text:
Q: NullPointerException in game I'm trying to make a space invaders type game in Java, but can't work out why the game won't work. Here's the error
java.lang.NullPointerException
at UFO_Game.checkForHit(UFO_Game.java:131)
at UFO_Game.setup(UFO_Game.java:109)
at UFO_Game.run(UFO_Game.java:44)
at acm.program.Program.runHook(Program.java)
at acm.program.Program.startRun(Program.java)
at acm.program.Program.start(Program.java)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

and here's the code getting the error.
public void checkForHit(){
    GObject CHECK = getElementAt(Bullet.getX(), Bullet.getY());
    if(CHECK == SHIP){
        removeAll();
    }

By the way, I'm using the ACM stuff like in the Stanford methodology.

A: I suppose that Bullet is a field in your UFO_Game class. It isn't assigned a valid value (object fields are initialized with null). When you try to invoke getX(), a NullPointerException is thrown. To avoid this, initialize the Bullet field when you construct each UFO_Game object.
By the way, methods and field names in Java should start with a lower case letter. Anyone familiar with Java will read Bullet.getX() as an invocation of a static (class) method.


text:
Q: Maximize font size for PRE element to use all available horizontal space I want to include a changing pre-formatted text into a web page and display it as big as possible.
The text is inside a PRE tag so whitespace and formatting remain intact.
What I'm currently using is this:

pre {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 2vw;
}

div {
    position: relative;
    width: 100%;
    height: 100%;
    overflow: hidden;
    white-space: nowrap;
}

    the text here
       and it continues of a couple of lines

This works pretty well, but only if the content of the PRE tag is around 80 characters wide.
Is there a way to maximimze the font-size of the PRE element even if the content is narrower or wider? Ideally with only CSS and no JavaScript.


text:
Q: Who hired the hit squad that disrupted Furlong's capture? Near the beginning of Freejack, Alex Furlong is pulled into the future by bonejackers.
But their plans to lobotomize (?) Furlong are disrupted when they come under fire from a hit squad, and Furlong is able to escape.
What was that hit squad trying to achieve?  Was it hired by any of the major players in the film?

A: Michelette hired the goons
Michelette wanted to succeed Ian McCandless as head of the McCandless Corporation.  This would not happen for decades, if ever, if Ian McCandless survived by downloading himself into Furlong's body.  Therefore, Michelette hired the goons who repeatedly attempted to kill Furlong and/or interfere with Vacendak capturing him.  (Killing Furlong was Plan A, but Michelette could also achieve the same objective by preventing Furlong's capture until McCandless was out of time.)


text:
Q: Java Regex ReplaceAll on range -> String.replaceAll() on string X after (not including) some char Y ~> until (including) end of case-ignored string Z I am trying to replace all instances of a substring from the first character following ":" until the end of a substring "user" with case-ignored using the (?i)
So, an example would be:
Input
u:sdneUSER|r:endsUser(&g:againuser)

Replace All :
sdneUSER -> root
endsUser -> root
againuser -> root

Expected Output:
u:root|r:root(&g:root)

Reference :
Ignore case https://stackoverflow.com/a/5055036

A: You can use this regex :.*?(?=[^a-zA-Z]+) with replaceAll like this :
String text = "u:sdneUSER|r:endsUser(&g:againuser)";
text = text.replaceAll(":.*?(?=[^a-zA-Z]+)", ":root");

Output
u:root|r:root(&g:root)

regex demo


text:
Q: How to add custom html in django admin field? Basically, what I want to achieve is to have a media form that show an image  thumbnail after I choose the file in the add or edit interface. I try using this code but it returned in this error.
Unknown field(s) (admin_image) specified for ImageMedia.
Check fields/fieldsets/exclude attributes of class ImageMediaAdmin.

This is the model class:
class ImageMedia(models.Model):
    caption = models.CharField(max_length=64)
    picture = models.ImageField(upload_to='image_media', blank=True)

    def admin_image(self):
        return '<img src="%s" height="300px"/>' % self.picture
    admin_image.allow_tags = True

    def __str__(self):
        return self.caption

This is the admin class
class ImageMediaAdmin(admin.ModelAdmin):
    list_display = ('caption', 'picture', 'admin_image')
    search_fields = ('caption', 'picture')
    fields = ('caption', 'picture', 'admin_image')

admin.site.register(ImageMedia, ImageMediaAdmin)

A: You need to change ImageMediaAdmin to specify admin_image as a readonly_field.
class ImageMediaAdmin(admin.ModelAdmin):
    list_display = ('caption', 'picture', 'admin_image')
    search_fields = ('caption', 'picture')
    fields = ('caption', 'picture', 'admin_image')
    readonly_fields = ['admin_image']


text:
Q: Mallocing array of structs within a struct (C) I'm having trouble finding the answer to this problem; I've found similar examples of this online but none that address my problem.
I have a struct for the data for a company, Company, and a second struct for collections of companies, Consortium. The second struct will contain variable length arrays of the first struct, the company data struct. The number of elements of the variable length arrays will depend on the number of companies in a consortium.
I want to dynamically allocate whatever is required but I'm getting a bit lost. These are the structs:
typedef struct {
    char  code[];
    double sharePrice;
    int numShares;
    double totalVal;
    double totalDebts;
} Company;

typedef struct {
    int numCore;
    int numAssoc;
    Company core[];
    Company assoc[];
} Consortium;

There will be a number of core companies, and this number will be the size of the core array in the Consortium struct. Same goes for associate companies.
I came up with this expression but I'm not sure what I'm missing:
Consortium *consort=((Consortium*)malloc((numCore+numAssoc)*(sizeof(Consortium));

A: You'll need to use pointers and allocate the arrays separately:
typedef struct
{
    char  *code;
    double sharePrice;
    int numShares;
    double totalVal;
    double totalDebts;
} Company;

typedef struct
{
    int numCore;
    int numAssoc;
    Company *core;
    Company *assoc;
} Consortium;

Consortium *c = malloc(sizeof(*c));    // Error check
c->numCore = 4;
c->core = malloc(sizeof(*c->core) * c->numCore);    // Error check
c->numAssoc = 3;
c->assoc = malloc(sizeof(*c->assoc) * c->numAssoc);    // Error check

for (int i = 0; i < c->numCore; i++)
    c->core[i].code = malloc(32);    // Error check

for (int i = 0; i < c->numAssoc; i++)
    c->assoc[i].code = malloc(32);    // Error check

// Worry about other data member initializations!

It would be simpler and possibly better to modify the Company type to:
typedef struct
{
    char   code[32];
    double sharePrice;
    int    numShares;
    double totalVal;
    double totalDebts;
} Company;

That saves the loops allocating the code elements.

A: You might consider that you make the Consortium struct a bit simpler.  Since you have the counts for each type, core and assoc, you can have just a single array, the first part of which is for core and the second part of which is for assoc.
So your struct would look something like the following source (which has not been compiled and is just jotted down rather than tested so caveat emptor):
typedef struct {
    int numCore;    // number of core companies, first part of m_companies
    int numAssoc;   // number of assoc companies, second part of m_companies
    Company m_companies[1];
} Consortium;

Then you would create your actual data structure by something like:
Consortium *makeConsortium (int numCore, int numAssoc) {
  Consortium *pConsortium = malloc (sizeof(Consortium) + sizeof(Company) * (numCore, numAssoc));
  if (pConsortium) {
      pConsortium->numCore = numCore;
      pConsortium->numAssoc = numAssoc;
  }
  return pConsortium;
}

After this you could fill it in by some functions which indicate success or not:
int addCompanyCore (Consortium *pConsortium, int index, Company *pCompany) {
  int iRetStatus = 0;
  if (pConsortium && index < pConsortium->numCore) {
    pConsortium->m_companies[index] = *pCompany;
    iRetStatus = 1;
  }
  return iRetStatus;
}
int addCompanyAssoc (Consortium *pConsortium, int index, Company *pCompany) {
  int iRetStatus = 0;
  if (pConsortium && index < pConsortium->numAssoc) {
    index += pConsortium->numCore;
    pConsortium->m_companies[index] = *pCompany;
    iRetStatus = 1;
  }
  return iRetStatus;
}

And then you would access them with another set of helper functions.
Company  *getCompanyCore (Consortium *pConsortium, int index) {
  Company *pCompany = 0;
  if (pConsortium && index < pConsortium->numCore) {
    pCompany = pConsortium->m_companies + index;
  }
  return pCompany;
}
Company * getCompanyAssoc (Consortium *pConsortium, int index) {
  Company *pCompany = 0;
  if (pConsortium && index < pConsortium->numAssoc) {
    index += pConsortium->numCore;
    pCompany = pConsortium->m_companies + index;
  }
  return pCompany;
}


text:
Q: Calculating a sample's representativeness to confirm/refute a given hypothesis? Why hello! I'm fairly new to statistics, which is why I'm somewhat confused as to how I can approach this problem in a scientific way.
The problem:
Experiments are conducted to find the probabilities for several possible outcomes; let's say they are $X_1$ to $X_4$. There is no other outcome, so the "combined" probabilities must amount to $P = 1$ ($100\%$). It is, however, unknown how exactly this grand total is divided... It might be an equal $25\%$ or a random percentage between $0.01$ and $0.96$ for each.
The goal is to ultimately find out with a confidence level ($1\%, 3\%, 5\%$... doesn't matter) how the probabilities may be distributed among $X_1$ to $X_4$.
The hypothesis:
It is thought that $X_1$ to $X_4$ have an equal probability of $25\%$ each. This is most likely wrong, but the hypothesis remains to be refuted by means of "proving" a different probability for each by observing a sufficiently large sample (the experiment mentioned above, which can be repeated indefinitely if need be).
Where I require your aid:
Well... I have read up on everything I thought relevant to the problem, but I remain uncertain how to "formalize" everything. The calculations should be the lesser problem afterwards. When exactly will the observation sample size be large enough for a given confidence level? What kind of "mean" can I calculate from the observation if the individual events are different results and not simple numbers?
Say, $X_1$ -> "The computer catches fire" and $X_2$ -> "You win tomorrow's lottery" (random examples). They're not related to each other (such as $X_1 \rightarrow 1/\text{Heads}$, $X2 \rightarrow 0/\text{Tails}$), so I fail to see how I can apply the formulae available for mean, deviation, error and all the other possible statistical quantities I read about.

A: A couple preliminary clarifications/remarks on your problem:

*

*From your wording, it appears that these probabilities are not only exhaustive but also mutually exclusive, so that one, and only one, outcome can occur in each experimental trial, correct?

*What kind of confidence level do you want? I assume you want a set of family-wise confidence intervals, so that there is a, say, 95% confidence that all of the intervals cover the true probability of each occurrence.
I will assume the above in my answer.
When you are testing multiple outcomes that are related in some way (here, they are exhaustive so they add to 1) then you want to use the categorical distribution, which is related to the multinomial distribution not the normal approximation or the t-distribution for single-outcome statistics, as you have indicated. You are trying to force-fit a multi-dimensional problem into a one-dimensional testing scheme. The multinomial will give you the needed flexibility. As a basic primer on categorical data, see this.
To do a hypothesis test of equality of probabilities, you can use the Chi-square goodness of fit test, although it relies on a multivariate normal approximation to the set of estimated probabilities you get from the experiments. To get confidence intervals, see this.
I think the links and above explanations will get you largely where you want to go.

A: Assumption 1 is correct; only one event may happen and exactly one event is always happening for any given experimental trial.
Assumption 2 I took to mean that this set of confidence intervals, containing a confidence interval for all of the possible outcomes, would then allow one to say with the required certainty (e.g., 95%) that ALL estimated probabilities are indeed as close to the true probability (again, for each event) as was required. If so, this also is true, but from what I read the "certainty" only means all values are included in said interval, i.e., 95% of all values would be in the interval. However, how does this enable one to say how close to the truth the probabilities are?
For what it's worth, I understand that I have to use a different model, and I'd now start like this:
Let X_i be the (categorical) random variable that represents the outcome of each trial 0 < i < N+1, where N is the number of trials performed.
That is, X_i assumes the value of events 1 to 4 (in the example above), where i=4 and N, the number of trials performed, and there are N values X_i that represent the whole sample data. Since X can assume only one of the 4 possible outcomes the property "mutually exclusive" is thusly included in my "model".
To rephrase the main problem, let me quote Wikipedia:

Certain factors may affect the confidence interval size including size
  of sample, level of confidence, and population variability. A larger
  sample size normally will lead to a better estimate of the population
  parameter.

Now what I am interested in is, how large should the sample size be to be 90%, 95%, ..., sure that my estimated probabilities for all events are "correct" and the error is small enough to have certainty regarding the calculated percentages? I'm also not sure how to set the margin of error (usually called 'e' in the formulae), apparently a value of 0.1 is small enough?
To use real sample data, this might be the outcomes of N=300 trials:
X_1 : 105 times
X_2 : 105 times
X_3 : 67 times (<-- This and...
X_4 : 23 times (<-- ... this makes it, in my opinion, very unlikely that all events should have an equal probability of 25, especially considering the sample size. But how can I be "sure"?)
The sample mean of X calculates to ~2 with an estimated sample variance of 0.88. Now, taking z = 2 for a 95% confidence level, it appears with an error margin of 0.1 (to each side of the interval), a very rough estimate of the required number of trials would be:
n >= ((2*0.88)/0.1)^2 =~ 300
This is only a very rough estimate, but wouldn't it mean that a sample size of more or less 300 is already large enough to be sufficiently (95%!?) sure that the calculated probability for each event is indeed within the confidence interval of e = 0.1 ?
But even then, I don't see why exactly, and I also think the error is only referring to X, which however does not represent any percentage, but the average (mean) value of ~2. That is, the mean of an infinite amount of trials should amount to something in the interval [~1.9 ; ~2.1] and we can say that and only that with the required certainty of 95%?
It doesn't really solve the problem, from what I understand.
PS. Since I did not calculate multiple confidence intervals, I believe all of this must be horribly wrong. I apologize for not understanding the "advanced" links you posted about them. The test of goodness was only required to disprove the hypothesis that 0.25% = p_i for all events i, was it not?
If so, I was hoping I could simply "disprove" it by stating with close-to certainty that any other percentage that is very much different from an equal share is the true probability (indirectly, that is).


text:
Q: Android-Getting text from string array So I wanna display items from a string array in a text view in order by pressing a button for next or previous item.I am pretty newbie at coding so this is what I managed to do.
String[] PeopleFactsArray;
Button pplnextbtn, pplprevbtn;
TextView pplfacts;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.people_facts);
    PeopleFactsArray=getResources().getStringArray(R.array.people_facts);
    pplnextbtn=(Button) findViewById(R.id.pplnextbtn);
    pplprevbtn=(Button) findViewById(R.id.pplprevbtn);
    pplfacts=(TextView) findViewById(R.id.pplfacts);
    pplnextbtn.setOnClickListener(new FactSelect());
    pplprevbtn.setOnClickListener(new FactSelect());
    int factcount=0;
    pplfacts.setText(PeopleFactsArray[factcount]);

}
class FactSelect implements View.OnClickListener {
    @Override
    public void onClick(View v) {
        TextView pplfacts = null;
        int factcount=0;
        int factlist=PeopleFactsArray.length;
        pplfacts.setText(PeopleFactsArray[factcount]);
        if (v.getId() == R.id.pplnextbtn)
        {
            for (factcount = 0; factcount < factlist; factcount++)
            {
                factcount = factcount + 1;
            }
        }
        else if (v.getId() == R.id.pplprevbtn)
        {
            for (factcount = factlist; factcount > 0; factcount--)
            {

                factcount = factcount - 1;
             }
        }

    }
}

and my textview is as follows
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/people_layout">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Large Text"
    android:id="@+id/pplfacts"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="70dp" />

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Next"
    android:id="@+id/pplnextbtn"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="84dp" />

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Prev"
    android:id="@+id/pplprevbtn"
    android:layout_alignTop="@+id/pplnextbtn"
    android:layout_toLeftOf="@+id/pplfacts"
    android:layout_toStartOf="@+id/pplfacts" />

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Share"
    android:id="@+id/pplsharebtn"
    android:layout_alignTop="@+id/pplnextbtn"
    android:layout_toRightOf="@+id/pplfacts"
    android:layout_toEndOf="@+id/pplfacts" />
</RelativeLayout>

and my string array is as follows
    <?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="people_facts">
        <item>people fact 1</item>
        <item>people fact 2</item>
        <item>people fact 3</item>
        <item>people fact 4</item>
        <item>people fact 5</item>
        <item>people fact 6</item>
        <item>people fact 7</item>
        <item>people fact 8</item>
        <item>people fact 9</item>
        <item>people fact 10</item>
    </string-array>

</resources>

when I run it and try to press next or prev buttons my app crashes. if someone could steer me in the right direction I would greatly appreciate it. thank you.

A: Replace your onClick implementation with this:
@Override
    public void onClick(View v) {
        int factcount=indexOfCurrentSelection;
        int factlist=PeopleFactsArray.length;
        if (v.getId() == R.id.pplnextbtn)
        {
               if(factcount < factlist-1) factcount = factcount + 1;
        }
        else if (v.getId() == R.id.pplprevbtn)
        {
               if(factcount > 0) factcount = factcount - 1;
        }
        pplfacts.setText(PeopleFactsArray[factcount]);
        indexOfCurrentSelection = factcount;
    }

Declare indexOfCurrentSelection as a global variable & initialize it to 0.


text:
Q: Pass ROWID in ListView to new Activity when clicked Very new to programming here. I am working on an android application that allows the user to create and manage a database for food products that he has at home. Currently the SQL database allows you to create new database entries where each entry consists of a rowid, a product name, the amount you have of the product and finally an expiry date.
Then a ListView is populated with any existing data in the database and an OnItemClickListener for this ListView is setup to handle a click event so that if the user clicks on a row in the ListView he is send to a new edit activity. Here he can edit the name, the amount and the expiry date if needed.
Now I am trying to retrieve the data (name, amount, date) when a specific row is clicked to send it to the next activity and here's what I've got so far..
Setup a public cursor in the SQL database to get all KEYS for a specific rowid:
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME, KEY_AMOUNT, KEY_DATE};

public Cursor getRow(long rowId) {
    String where = KEY_ROWID + "=" + rowId;
    Cursor c = ourDatabase.query(true,  DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
    if (c != null) {
        c.moveToFirst();
    }
    return c;
}

Then in the activity with the ListView I have the following set up to launch the new edit activity:
private void listViewItemClick(){
    ListView ourList = (ListView) findViewById(R.id.lvProducts);
    ourList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // TODO Auto-generated method stub

            Intent openProductsEdit = new Intent(Products.this,
                    ProductsEdit.class);
            startActivity(openProductsEdit);
            finish();

        }
    });
}

And finally I would like to set the EditTexts in my edit activity to the data passed on during the click event:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.products_edit);

    initiate();

    Intent getProductName = getIntent();
    String productName = getProductName.getStringExtra("productName");
    etName.setText(productName);

    Intent getProductAmount = getIntent();
    String productAmount = getProductAmount.getStringExtra("productAmount");
    etAmount.setText(productName);

    Intent getProductDate = getIntent();
    String productDate = getProductDate.getStringExtra("productDate");
    etDate.setText(productName);

I have been trying to retrieve the specific data for a clicked row through the cursor I have setup in the SQL database and then pass it on with openProductsEdit.putExtra in the onItemClick method, but I can't seem to successfully connect the two together.
Any suggestions on how to solve this would be greatly appreciated.
EDIT: I solved my problem by coding my onSetItemClickListener like this
private void listViewItemClick(){
    final ListView ourList = (ListView) findViewById(R.id.lvProducts);
    ourList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // TODO Auto-generated method stub

            Cursor cursor = (Cursor) ourList.getItemAtPosition(position);
            Intent openProductsEdit = new Intent(Products.this,
                    ProductsEdit.class);
            int rowid = cursor.getInt(0);
            String name = cursor.getString(1);
            String amount = cursor.getString(2);
            String date = cursor.getString(3);
            openProductsEdit.putExtra("rowid", rowid);
            openProductsEdit.putExtra("name", name);
            openProductsEdit.putExtra("amount", amount);
            openProductsEdit.putExtra("date", date);
            startActivity(openProductsEdit);

            finish();

        }
    });

Here the cursor.getString(1) sets a string to the second column of the selected row (in this case a product name). This is then passed on to an edit activity where the data is put into corresponding EditTexts.
PROBLEM SOLVED! ;)


text:
Q: PythonTeX rendering problem I tried the PythonTeX package, and the output it produced contained question marks instead of running python code, what should i do ??

A: Packages which call other programs, such as sagetex, python, gnuplot, or (as G. Poore confirms) PythonTeX require you to process the your document in a similar fashion:
1. (pdf)latex your document to create a special file (with sagetex it's a .sage file.
2. Process the special file with the program/script (Sage/Python/gnuplot)
3. (pdf)latex your document again.
After step 1 your output will have ?? marks where the computations/pictures are supposed to be. I suspect you didn't realize that 2 more steps of processing are necessary. As G. Poore indicates above your second step will be "run the PythonTeX script (pythontex2.py or pythontex3.py, depending on your Python version)". Depending on the package you might be able to streamline the process with a shell escape in your tex file or configuration of your IDE


text:
Q: Reading GMail with Cocoa I've been trying to do this all morning. I just want to get the XML feed from my gmail account:
It looks like I am having authentication problems, even though I am passing username and pass. Is there a way to work with GMail in Objective-C?
- (void) awakeFromNib {

//go and grab the weather data
NSString *username = @"xxxxxxxxx@gmail.com";
NSString *userpass = @"xxxxxxxxxx";
NSString *urlstring = [NSString stringWithFormat:@"https://%@:%@@gmail.google.com/mail/feed/atom", username, userpass];
NSString *encodedString = [urlstring stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:encodedString];

NSError* error = nil;
NSString* testString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
NSArray *listItems = [testString componentsSeparatedByString:@","];

[self parseXMLFile:url];
}

- (void) parseXMLFile : (NSURL *) url {

BOOL success;

if (dataParser) // addressParser is an NSXMLParser instance variable

    [dataParser release];

dataParser = [[NSXMLParser alloc] initWithContentsOfURL:url];

[dataParser setDelegate:self];

[dataParser setShouldResolveExternalEntities:YES];

success = [dataParser parse]; // return value not used

// if not successful, delegate is informed of error

}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{

currentKey = nil;
currentStringValue = nil;
[currentStringValue release];

currentKey = [NSString stringWithFormat: @"%@", elementName];

return;
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
currentStringValue = [[NSString alloc] initWithFormat:@"%@", string];
NSLog(@"%@", currentStringValue);
}

My partial log results:
2011-11-16 12:27:55.986 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.986 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.987 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.987 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.987 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.988 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.988 GoogleDataApp[48759:10b] New to Gmail?
2011-11-16 12:27:55.988 GoogleDataApp[48759:10b] Create an account
2011-11-16 12:27:55.989 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.989 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.989 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.990 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.990 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.990 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.991 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.991 GoogleDataApp[48759:10b] Sign in
2011-11-16 12:27:55.992 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.992 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.993 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.993 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.993 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.994 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.994 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.995 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.995 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.995 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.996 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.996 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.996 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.997 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.997 GoogleDataApp[48759:10b] Username
2011-11-16 12:27:55.997 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.998 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.998 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.998 GoogleDataApp[48759:10b]
2011-11-16 12:27:55.999 GoogleDataApp[48759:10b] Password
2011-11-16 12:27:55.999 GoogleDataApp[48759:10b]


text:
Q: Vectorizing splitting string values in a column based on strings in another column in a pandas DataFrame Hey so I have this problem of splitting strings in a column based on another column's values, I managed to figure out a solution with df.apply but I wonder if there are any str.split related ways to vectorize this implementation?
            name field
0            b_b     b
1            b_c     b
2            b_d     b
3        a_paris     a
4  a_tokyo_ghoul     a
5           a_xx     a

I would like to convert the 'name' column into
0              b
1              c
2              d
3          paris
4    tokyo_ghoul
5             xx

and my current implementation is
df.apply(lambda row: row['name'].split(f"{row['field']}_")[-1], axis=1)

A: Assuming you want to extract the field after the first _ and validate that the initial string is the same as df['field']:
df2 = df['name'].str.split('_', n=1, expand=True)

df['name2'] = df2[1].where(df2[0].eq(df['field']))

output:
            name field        name2
0            b_b     b            b
1            b_c     b            c
2            b_d     b            d
3        a_paris     a        paris
4  a_tokyo_ghoul     a  tokyo_ghoul
5           a_xx     a           xx

A: If all the name contains '' in your name column, then you can split the column on basis of '', this way you got prefix and postfix of data of the name column.
After call the postfix data that come-after '_', this way you get desired output.
Edit*:-  You can also use other columns as a base that contains the prefix data of name field and put filtter that for field str match name column then split rest part


text:
Q: How to include images in an HTML email in Android I'm trying to send images using HTML in my email body but images are not sending. I don't know what I did wrong. I tried using the code below:
Intent i = new Intent(Intent.ACTION_SEND_MULTIPLE);
i.setType("text/html");
String tempStr = "<title></title>quick   ";
i.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(tempStr));
i.putExtra(Intent.EXTRA_EMAIL, new String[] {"ashwini.soma@gmail.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
startActivity(i);

try {
    startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
    Toast.makeText(SavePage.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}

A: This frustratingly does not seem to be supported natively in Android. One workaround is the use Java Mail and figure it out yourself. What I did was use the droidQuery library to help write my HTML to a file and attach it to the email:
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
String html = "
Place Your HTML here.
";
shareIntent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(html));
shareIntent.setType("text/html");
$.with(this).write(html, FileLocation.EXTERNAL, "email.html", false, false, new Function() {

    @Override
    public void invoke($ droidQuery, Object... params) {
        String file = ((File) params[1]).getAbsolutePath();
        shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + file));
        startActivity(shareIntent);
    }
}, new Function() {
    @Override
        public void invoke($ droidQuery, Object... params) {
            Log.e("$", (String) params[1]);
        }
});

Then added this block at the top of the html  (also poorly formatted on Android email):

    Trouble viewing this email? Open the attachment to view in your web browser.

If you are considering the first approach (Java Mail), I would recommend using the droidMail extension for droidQuery, which uses the library to provide a simplified API.

A: The image needs to be hosted somewhere. When the user receives the email, the client will be looking for the image "images/assaultoffences.png" which won't exist.
Host it somewhere, then specify the full URL in the email, such as http://mydomain.com/images/assaultoffences.png

A: Hey you can use this reference for your solution.
I hope this will help your to solve your problem.
Thanks.

A: Just because the html references an image doesn't mean the email application will read the html, parse it, find the referenced images, attach them to the email, and change the references to be internal.
There's already a question and answer describing how to attach files to emails when sending them.
This answer shows you how to reference your attached image from html to make them show up in the body (it works for Outlook at least).


text:
Q: Is it possible to install/embed jquery to your web Browser? Is it possible to install/embed jQuery in the browser?
The area, where I live, will block anything related to google. For example:
//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js

I can visit stackoverflow.com but with a js error if I don't use VPN.
I don't mean my own site. When I visit some site, I know the error is JQuery is missing. If I have the JQuery.js. I will not need the VPN.

A: Very related: Use of ajax.googleapis.com not China-friendly.
The solution given there is to use Hola, a browser plugin that lets you browse through a VPN, although I'm afraid that also may not work.
I think the best solution is to host the files on a local webserver or on your own remove server, and change the hosts file in Windows to make googleapis.com redirect to that location.


text:
Q: Evaluate $\int_1^4 \frac{1}{x^2}\left(1+\frac{1}{x} \right)^{\frac{1}{2}} \, dx$ The correct answer is (4*2^.5/3)-(5*5^.5/12)
I set $u = x^{-2}$
therefore, $du = -2x^{-3} dx$
$dx = x^3 / 2$
The next step I took was: $u(1/2)(1+x^{-1})^{.5}(-x^{-2})+C$
When I plug $4$ and $1$ into these equations, I arrive at $5^{.5} / 80$ for $F(4)$ and $2^{.5} / 4$ for $F(1)$
I am going seriously wrong somewhere, and I can't figure out what I am doing here.

A: You want to find
$$
\int_1^4 \left(\frac{1}{x^2}\right)\left(1 + \frac{1}{x}\right)^{1/2}\;dx
$$
It looks like you are using integration by substitution. Maybe try with $u = 1 + \frac{1}{x}$. Then
$$
-du = x^{-2}dx
$$
and you you get
$$
\int_?^? -\sqrt{u}\; du = \dots
$$


text:
Q: How to implement this algorithm? I am not an expert in programming, and looking online i found a challenge that block me.
The text is really long, so i will post only the part that stuck me.
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ <- reference word (r)
b b a a b c c b c c b c a b c <- my guess (p)
/ + | + + + | + + / + + + + + <- result (res)
i created successfully the algorithm that given the guess in input return the result in output.
In short:
For every 1 ≤ i ≤ k, we have that

*

*res[i] is the + character if the i-th character of p is equal to the i-th character of r
that is, if it holds that p[i] = r[i], then p[i] is "in the correct position";

*res[i] is the character / s and the i-th character of p does not compare anywhere in r;

*res[i] is the | character if the i-th character of p (referred to below as p[i]) compares in r,
but not in the i-th position; however, if n instances of p[i] appear in r, if ci is the number of
instances of the character p[i] which are in the correct position (clearly it must hold that ci ≤ ni) and
if there are before the i-th character in p at least ni-ci characters equal to p[i] which are in
incorrect position, then res[i] must be / instead of |.

Now from a pool of word, i have to remove the one don't satisfy the boundaries given from the result. For example, from the top example i know that b should be in position 2 - 5 -..., and there are exactly 5 b, because the 6 gives /..
These are the boundaries:

*

*if the symbol does not belong to r

*places where that symbol must appear in r

*places where that symbol cannot appear in r

*minimum number of times the symbol appears in r

*exact number of times the symbol appears in r
How do i implement this? What data structure should i use for the boundaries?
For now i have this data structure:
// Linked list
struct node
{
    int valid;
    char *boundaries;
    char *data;
    struct node *next;
    struct node *prev;
    struct node *head;
};

So I have the word, with the boundaries it generated when entered. But i got lost trying to implement the various algorithm.
I tried writing some stuff for at least the first 3 point but it's really messy:
void updateValidity(Node L)
{
    Node temp1 = L->next;
    while (temp1 != NULL)
    {

        for (int i = 0; i < wordLenght; i++)
        {

            if (temp1->boundaries != NULL)
            {
                // Number of times the letter appear in the reference word
                int c = 0;
                int d = 0;

                if (strchr(referenceWord, temp1->data[i]) != NULL)
                    c++;
                if (strchr(temp1->data, temp1->data[i]) != NULL)
                    d++;
                if (temp1->boundaries[i] == '/' && c < d)
                {
                    // Number of times the letter appear in the word

                    Node temp2 = L->next;

                    while (temp2 != NULL)
                    {
                        for (int j = 0; j < wordLenght; j++)
                        {
                            if (temp1->data[i] == temp2->data[j])
                            {
                                temp2->valid = 0;
                                break;
                            }
                        }
                        temp2 = temp2->next;
                    }
                }
                // 2
                if (temp1->boundaries[i] == '+')
                {
                    Node temp2 = L->next;
                    while (temp2 != NULL)
                    {
                        if (temp1->data[i] != temp2->data[i])
                        {
                            temp2->valid = 0;
                        }
                        temp2 = temp2->next;
                    }
                }
                // 3
                if (temp1->boundaries[i] == '|')
                {
                    Node temp2 = L->next;
                    while (temp2 != NULL)
                    {
                        if (temp1->data[i] == temp2->data[i])
                        {
                            temp2->valid = 0;
                            break;
                        }
                        temp2 = temp2->next;
                    }
                }
            }
        }

        temp1 = temp1->next;
    }
}

Please help me!


text:
Q: Mockito: stubbing long call stack I have a service in which injected many other objects(which should be mocked), and I need to write unit test on some method. The problem is, that this method use many other methods in this service so I need to write many lines like when(someMock.someMethod()).thenReturn(someValue). I had to write about 12 lines like above, and I manually copy-pasted those from 5 methods which used by method I test.
It's very troublesome to manually track which method will be called next, and I wonder if three some IDE plugin where I can specify start and end of execution for particular test case and it shows objects which need to be mocked?
I can't test each method separately, because most of methods in call stack is private, and I need to test exception which thrown by last method in call stack.

A: First of all, if you need to mock so many things this is clear signal you need to refactor. So I assume you are not in position to refactor that code at the moment.
I don't think there are plugins to do that. Such plugin would need to execute the code to figure our all dependencies that should be mocked as some things that require mocking becomes visible in runtime only.
If I work with legacy code like this and can't refactor right now I use the test itself to help me find all the mocks like this using Mockito:
Configure automatic mocks injection with @InjectMocks
@InjectMocks private MyService sut;

Create your test:
@Test
public void testSomething() {
    sut.doSomething();

    // assert something
}

Now the goal is to make your assertion fail by adding required mocks. Just run the test. It will fail most probably with NullPointerException on invocation of some mock.
Add that mock just before the test method (this assumes that MyService uses fields or setters based injection):
@Mock private SomeDependency someDependency;

@Test
public void testSomething() {
    sut.doSomething();

    // assert something
}

Rerun the test. If SomeDepenency is just invoked and default value returned by it is enough you'll hit the next unmocked depenedency and handle it the same way.
If it is required to return some specific value from the mock invocation you add a configuration of the mock in a test:
when(someMock.someMethod()).thenReturn(someValue)

You repeat this until you get the assertion failure you created at the very beginning.
Then I move all defined mocks to the beginning of the test class.


text:
Q: "white-space: pre-line" causes weird stretching on non-block elements When using white-space: pre-line on non-block elements, Chrome, Opera and Safari (I suspect WebKit- and WebKit-derivative-based browsers) seem to stretch the element to seemingly fit the whitespace, which I believe they are supposed to collapse.

div
{
    white-space: pre-line;
    display: inline-block;
    border: solid 1px #333;
}

single line

multi
                                             line

multi
                                             line

crazy
                                                                                indentation

In Chrome, Opera and Safari the above code produces:

While in Firefox, it turns up (somewhat) as I would expect it to:

Interestingly, this seems to  determined only by the length of the last line of the element:

div
{
    white-space: pre-line;
    display: inline-block;
    border: solid 1px #333;
}

multi
                                             line

According to my understanding of the specification, white-space: pre-line is supposed to collapse multiple consecutive spaces (and tabs) into at most a single character.
This seems to be happening to some extent, as there is no whitespace to be selected with the mouse in the boxes in the first example.
However, the box model seems to treat the last line of its content as if white-space: pre had been applied.

*

*Is this a bug in the WebKit engine, or is there some obscure reason for which this is allowed, or even supposed to be happening?

*There are at least two HTML workarounds (use
 or remove indentation), but I'd rather leave my markup readable. So is there a CSS-only way to "fix" the box width?


text:
Q: i need help reversing a chmod, chown and 'whoiam' code I used this code on an app:
chmod 600 /Applications/Freedom.app ; chown 'whoami':staff /Applications/Freedom.app
Does anyone know how to undo this?

A: To undo the chmod use :
sudo chown -R alexandertollman:alexandertollman   /Applications/Freedom.app

To set back to permission level 755 use :
sudo chmod -R 755 /Applications/Freedom.app

The whoami only prints the username associated with the current effective user ID.