text:
Q: Enabling PUT and DELETE request in webservice I have a webservice that accepts bot GET and POST but when i call the webmethod using PUT or DELETE i get a response as

404.0 file not found

   [WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class reste : System.Web.Services.WebService
{
    HttpContext httpContext;
    dynamic response;
    string result;

    [WebMethod(true) ]
    public void clients()
    {
        initialize();

        ClientServices cl = new ClientServices(httpContext);
        result = cl.processRequest();

        sendResponse();

    }

here is the response headers
Status Code: 404
Date: Sun, 23 Feb 2014 21:47:28 GMT
Server: Microsoft-IIS/8.0
X-Powered-By: ASP.NET
Access-Control-Allow-Methods: GET,PUT,POST,DELETE,OPTIONS
Content-Type: text/html; charset=utf-8
Access-Control-Allow-Origin: *
Cache-Control: private
X-SourceFiles: =?UTF-8?B?        YzpcdXNlc
Access-Control-Allow-Headers: Content-Type
Content-Length: 4972

A: It seems like you cannot do put or delete request on asmx webservice files so i have implemented ihttphandler and routed request with help of web config

A: Yes, you are using WCF. Your code is executed by WCF. Read the other answer and you'll understand and find your solution right there.


text:
Q: NullPointerException for JFileChooser I've got problem with
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
when you leave path empty I've got this message.
There are many topics here about it but I can't really figure it out. I've read the post about NullPointer.
As far as I understand it it's because one of my variable is empty, when the path not going to be selected. Thanks for help and sorry for to bother.
Error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at com.bober.proj.WiewWindow$2.actionPerformed(WiewWindow.java:71)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$500(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

WiewWindow.java
package com.bober.proj;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JFileChooser;

public class WiewWindow {

    protected static final JFileChooser String = null;
    private JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    WiewWindow window = new WiewWindow();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public WiewWindow() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);
        JButton btnNewButton = new JButton("New button");
        JButton keyboardBT = new JButton("Keyboard...");

        final JComboBox<String> comboBox = new JComboBox<String>();
        final JComboBox<String> fixedFontSize = new JComboBox<String>();
        final JFileChooser chooser = new JFileChooser();

        comboBox.setModel(new DefaultComboBoxModel(new String[]{"Tak", "Nie", "Suka Bliac"}));
        fixedFontSize.setModel(new DefaultComboBoxModel(new String[]{"NO", "YES"}));

        btnNewButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {

                String text = (String) comboBox.getSelectedItem();
                String fixedF = (String) fixedFontSize.getSelectedItem();
                String path = chooser.getSelectedFile().getAbsolutePath();
                System.out.println(text);
                System.out.println(fixedF);
                System.out.println(path);

                FileOperation fo = new FileOperation();
                fo.writeToFle(text, fixedF, path);
            }
        });
        btnNewButton.setBounds(124, 206, 89, 23);
        frame.getContentPane().add(btnNewButton);

        comboBox.setBounds(246, 34, 121, 20);
        frame.getContentPane().add(comboBox);

        fixedFontSize.setBounds(10, 34, 89, 20);
        frame.getContentPane().add(fixedFontSize);

        keyboardBT.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                chooser.setCurrentDirectory(new java.io.File("C:\\test\\"));
                chooser.setDialogTitle("choosertitle");
                chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                chooser.setFileFilter(new FileNameExtensionFilter("KMP keyboard file", "kmp"));

                if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                    System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
                    System.out.println("getSelectedFile() : " + chooser.getSelectedFile().getName());

                } else {
                    System.out.println("No Selection");
                }

            }
        });
        keyboardBT.setBounds(246, 206, 105, 23);
        frame.getContentPane().add(keyboardBT);

    }
}

FileOperation.java
package com.bober.proj;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import javax.swing.JFileChooser;

public class FileOperation {

    public void writeToFle(String text, String fixedF, String path) {
        try {
            File dir = new File("C:\\test");
            File[] directoryListing = dir.listFiles();
            if (directoryListing != null) {
                for (File child : directoryListing) {
                    FileWriter writer = new FileWriter(child, true);
                    PrintWriter out = new PrintWriter(writer);
                    if (text == "Tak") {

                    } else {
                        out.println(text);
                    }
                    if (fixedF == "NO") {

                    } else {
                        out.println("fixedFontSize=true");
                    }
                    if (path != "") {
                        out.println("Filename=" + path);
                    } else {
                        System.out.println("Could not load path");
                    }
                    out.close();
                }
            }
        } catch (IOException e) {
            System.out.println("File error " + e.getMessage());
        }
        System.out.println("File saved");
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Extract a JAR file, possibly with WINRAR on CL I need to be able to extract jar files on the command line.
Piece of cake, you might say. Yes, except I need the extractor to rename same-named files.
To be specific, the Jar file has a file named:
classAX.class

and another named:
classax.class

in the same directory. I need it to extract them both, and preferably rename one:
classax (2).class

or something similar.
It must be able to do this without any user intervention.
Winrar has this capability, but when attempting to extract with unrar.exe, it says that the input file is not a valid RAR archive. (Though winrar has jar capabilities.)
Any way to force winrar to accept jars via command line, or perhaps another program?
Thanks,
~Kurt Nauck

A: You can develop your own programme in java, there is a Zip package that can deal with compressed files, an also you can deal with a rest of your needs

A: 7Zip command line util accomplishes this perfectly. Thanks for the answers.


text:
Q: Extra User Profile Field Upload File / Image I have been following the following tutorial to try and an upload form to the user profiles. http://www.scribd.com/doc/81666407/Add-and-Remove-WordPress-User-Profile-Fields-and-Display-Them-Within-Your-Theme-
I'd like to be able to make this a little more simple and just have an upload button and text box that allows the user to upload one file at a time rather than multiple files.
I was going to use Cimy Plugin which allows file uploads, however it doesn't seem to be possible to add sub headings for some fields.
If any of you have any recommendations that would be brilliant.

A: PHP CODE
/*
* Load style & scripts
*/
function itclanbd_admin_load_scripts( $hook ) {
    $allowed = ['profile.php', 'user-new.php', 'user-edit.php'];
    if ( ! in_array( $hook, $allowed ) ) {
        return;
    }
    wp_enqueue_media();
    wp_enqueue_style('finance2sell', plugins_url('css/style.css', __FILE__), array(), null);
    wp_enqueue_script('finance2sell', plugins_url('js/scripts.js', __FILE__), array(), '1.3', true);
}
add_action( 'admin_enqueue_scripts', 'itclanbd_admin_load_scripts' );

/**
 * Create custom fields
 * @param $user
 */
function itclanbd_add_custom_user_profile_fields($user) {
    $itclanbd_attachment_id = (int)get_user_meta( (int)$user->ID, 'itclanbd_attachment_id', true );
    ?>

                    <?php _e('Avatar', 'finance2sell'); ?>

                    <input type="number" name="itclanbd_attachment_id" class="itclanbd-attachment-id" value="<?php echo $itclanbd_attachment_id; ?>" />

                        <?php echo get_avatar($user->ID); ?>

                        <button class="button itclanbd-add-media" id="itclanbd-add-media"><?php _e('Select', 'finance2sell'); ?></button>
                        <button class="button itclanbd-remove-media"><?php _e('Remove', 'finance2sell'); ?></button>

    <?php
}
add_action( 'show_user_profile', 'itclanbd_add_custom_user_profile_fields' );
add_action( 'edit_user_profile', 'itclanbd_add_custom_user_profile_fields' );
add_action( 'user_new_form', 'itclanbd_add_custom_user_profile_fields' );

/**
 * Update custom fields
 * @param $user_id
 * @return bool
 */
function itclanbd_update_custom_user_profile_fields($user_id) {
    if( !current_user_can('edit_user', (int)$user_id) ) return false;

    delete_user_meta( (int)$user_id, 'itclanbd_attachment_id') ; //delete meta

    if( //validate POST data
        isset($_POST['itclanbd_attachment_id'])
        && is_numeric($_POST['itclanbd_attachment_id'])
        && $_POST['itclanbd_attachment_id'] > 0
    ) {
        add_user_meta( (int)$user_id, 'itclanbd_attachment_id', (int)$_POST['itclanbd_attachment_id'] ); //add user meta
    } else {
        return false;
    }

    return true;
}
add_action('user_register', 'itclanbd_update_custom_user_profile_fields');
add_action('profile_update', 'itclanbd_update_custom_user_profile_fields');

// Get custom field value
$attachment_id = get_user_meta( (int)$user_id, 'itclanbd_attachment_id', true );
$image = wp_get_attachment_image_src((int)$attachment_id, 'thumbnail');
echo $image[0]; // image url

JavaScript CODE
i create and place all code into a file name scripts.js
function wpMediaEditor() {
    wp.media.editor.open();
    wp.media.editor.send.attachment = function(props, attachment) {
        jQuery('input.itclanbd-attachment-id').val(attachment.id);
        jQuery('div.itclanbd-attachment-image img').remove();
        jQuery('div.itclanbd-attachment-image').append(
            jQuery('').attr({
                'src': attachment.sizes.thumbnail.url,
                'class': 'itclanbd-attachment-thumb',
                'alt': attachment.title
            })
        );
        jQuery('button.itclanbd-remove-media').fadeIn(250);
    };
}

function simpleUserAvatar() {
    var buttonAdd = jQuery('button.itclanbd-add-media');
    var buttonRemove = jQuery('button.itclanbd-remove-media');

    buttonAdd.on('click', function(event) {
        event.preventDefault();
        wpMediaEditor();
    });

    buttonRemove.on('click', function(event) {
        event.preventDefault();
        jQuery('input.itclanbd-attachment-id').val(0);
        jQuery('div.itclanbd-attachment-image img').remove();
        jQuery(this).fadeOut(250);
    });

    jQuery(document).on('click', 'div.itclanbd-attachment-image img', function() {
        wpMediaEditor();
    });

    if(
        jQuery('input.itclanbd-attachment-id').val() === 0
        || !jQuery('div.itclanbd-attachment-image img').length
    ) buttonRemove.css( 'display', 'none' );
}

jQuery(document).ready(function() {
    simpleUserAvatar();

    jQuery('table.form-table tr.user-profile-picture').remove();
});

CSS CODE
i create and place all code into a file name style.css
@charset "UTF-8";

table.form-table tr.user-profile-picture,
input.itclanbd-attachment-id {
    display: none;
}

div.itclanbd-attachment-image img {
    background-color: white;
    border: 1px solid #e1e1e1;
    border-radius: 2px;
    cursor: pointer;
    height: auto;
    margin-bottom: 10px;
    padding: 3px;
    width: 96px;
}

button.button.itclanbd-remove-media:hover,
button.button.itclanbd-remove-media {
    background-color: #990000;
    border-color: #560303;
    box-shadow: 0 1px 0 #560303;
    color: white;
}

button.button.itclanbd-remove-media:hover {
    background-color: #b40000;
}

It should look like:


text:
Q: Place Data from Same Column in Different Columns in Resultset I have a request I wasn't sure to handle. I was thinking of using PIVOT, but I wasn't sure if that would be the way to go.
I have the following Data:
EmployeeA, DepartmentB, 1/10/2010
EmployeeA, DepartmentA, 1/1/2000
EmployeeB, DepartmentC, 1/3/2011

They want output for only the employees that have been in different departments. Something that looks like this (order is important due to the dates):
EmployeeA, DepartmentA, DepartmentB

Any help is appreciated. For some reason, my mind isn't finding a good solution.

A: You can do this by doing a self JOIN on the table and then using a PIVOT to get the data in the format that you want:
SELECT *
FROM
(
    SELECT t1.emp, t1.dept, t1.dt
    FROM  test t1
    INNER JOIN test t2
        ON t1.emp = t2.emp
        AND t1.dept != t2.dept
) x
PIVOT
(
    min(dt)
    for dept in ([A], [B], [C], [D], [E])
) p

See SQL Fiddle with Demo
If you remove the JOIN you will get all records, but you stated you only want the records that have been in more than one department.

A: Here's the answer I got which I got largely based on your work. Pivot doesn't work because I don't know the categories (in this case Department) ahead of time and I can only have two of them.
Maybe there's an easier way. I didn't use a CTE, because I believe this should work for Sybase as well which I don't think supports that.
   select Meta1.[Employee ID],
Meta1.Department as PreviousDepartment,
Meta2.Department as CurrentDepartment
from
(
SELECT t1.[First Name], t1.[Last Name],
t1.[Employee ID], t1.Department, t1.[Hire Date],
ROW_NUMBER() over(PARTITION by t1.[EMPLOYEE ID] order by t1.[Hire Date]) as RowNum
FROM  EMPLOYEE t1
INNER JOIN EMPLOYEE t2
    ON t1.[Employee ID] = t2.[Employee ID]
    AND t1.Department != t2.Department
) Meta1
inner join
(
SELECT t1.[Employee ID], t1.Department, t1.[Hire Date],
ROW_NUMBER() over(PARTITION by t1.[EMPLOYEE ID] order by t1.[Hire Date]) as RowNum
FROM  EMPLOYEE t1
INNER JOIN EMPLOYEE t2
    ON t1.[Employee ID] = t2.[Employee ID]
    AND t1.Department != t2.Department
) Meta2
on Meta1.[Employee ID]=Meta2.[Employee ID]
where Meta1.RowNum=1
and Meta2.RowNum=2


text:
Q: How to use Xamarin.Form Controls and Native Controls On the same page I want to use Xamarin.Form Control inside my Native Android Page Controls. In my Android native page is there any way to load a Xamarin.Form Page inside my Native Android Fragment or LinearLayout?
According to Xamarin it's possible. But I cannot find how to achieve this.

A: As already discussed it is fairly simple on iOS (with .CreateViewController()) and WP (.ConvertPageToUIElement()).
But on Android all is not lost too: you can use .GetView() extension method from http://www.arturdr.ru/android/xamarin-forms-i-slozhnosti-integratsii-v-android-prilozheniya/
Here is an example on how to wrap Xamarin.Forms page in Android AlertDialog using that method:
https://github.com/OlexaLe/XFPageAsAndroidDialog

A: There's a few things being discussed, so bear with me:
The image snippet, from what I understand:
 "Not only are Xamarin.Forms pages mixable with custom screens" ...

This is like what @Stephane is mentioning allowing an application to use native screens as well as Xamarin.Forms screens.  Each platform stub-page can introduce a shared Xamarin.Forms page at any point in the application.  You don't have to use the Xamarin.Forms Navigation Stack.
 "but you can embed custom views built directly against Xamarin.IOS and Xamarin.Android into Xamarin.Forms pages."

This is what @Sten is mentioning, where if you create platform specific ContentRenderers you can render any kind of native controls into an existing Xamarin.Forms page, by passing this common View to each platform renderer.
So, for instance if you had a View:-
 public class MyView : ContentView
 {
     // Create some bindable properties here that can be used in your platform specific renderer,
     // i.e. DisplayText etc.
 }

You can use the above in a Xamarin.Forms page definition and then create platform specific renderers that would be called to render the content.
It is from within these platform specific content renderer classes that you can use native controls on each platform.
For instance in the ContentRenderer, for the event OnElementChanged you could do something like the following for WindowsPhone:-
 protected override void OnElementChanged(Xamarin.Forms.Platform.WinPhone.ElementChangedEventArgs<MyView> e)
 {
     base.onElementChanged(e);
     ...
     System.Windows.Controls.TextBox objPlatformSpecificTextBox = new System.Windows.Controls.TextBox();
     ...
     ...

However, what @Gulshan is really wanting I believe is to have a native page that is center-stage with the Xamarin.Forms content being rendered into a specific point in an already existing native page.
Its kinda-reversed, in thinking, however this is still possible:-
To achieve this you need to stimulate page-generation into a temporary new page.
For instance in WindowsPhone you would do this via:-
        PhoneApplicationPage objInnerPage_Temp = new PhoneApplicationPage();
        UIElement objInnerContent = App.GetMainPage().ConvertPageToUIElement(objInnerPage_Temp);

on the platform specific stub-page.
You can then inject the rendered contents into a native container that is appropriate on the platform, i.e. a Grid.
Update 1:-
==========
Although its very easy to do this on WindowsPhone it doesn't seem that this is possible when attempting something similar in Android unfortunately.
The Android page creation is very locked down, i.e. you can't gain access to the private fields for canvas and/or layout that it internally uses in AndroidActivity.
If this was possible then you could re-use this and take the contents rendered and inject similar to the solution  for the WindowsPhone platform.
Furthermore, the Platform class is flagged as internal also, preventing another way to generate the rendered contents.
There was hope I was thinking from approaching this from a Fragment implementation of generating an Activity into it, and this could well work - However - the issue here is that the implementation in Xamarin.Forms is expecting the ActionBar to be available of which it is not, and they aren't checking for a if null scenario to allow execution to continue if it is not available so it throws an exception preventing page content generation.
It doesn't therefore look possible?, unless they open up the layout / canvas fields in AndroidActivity or address the ActionBar expectation issue.

A: You are probably looking for a custom renderer.

*

*In your Forms project create a class MyView that inherits from View (or some other suitable class, say ContentView if you'll have child views etc)

*In your Android project create a renderer class MyViewRenderer that inherits ViewRenderer

*Add the attribute to that class that indicates it's a renderer before the namespace declaration
[assembly: ExportRenderer (typeof(MyView), typeof(MyViewRenderer))]

*In MyViewRenderer override OnElementChanged, call base.SetNativeView(ctl) where ctl is an instance of your native control

Take a look at Xamarin's guide
Another resource in Xamarin's Forums.
After looking at the issue and implementing my own Border I'd say VisualElementRenderer<TElement> is a better renderer to use. If you use that all you'd need to do is override OnElementChanged and do NativeView.Add(customUIView) and copy properties from the MyView instance. To handle dynamic changes in these properties override OnElementPropertyChanged and update the customUIView instance

A: Xamarin revised its website, so the image above is outdated. As the Xamarin.Forms library has evolved, it appears that it became tougher to mix Xamarin.Forms and platform-specific native views. I would not recommend doing this.
Advanced users can certainly attempt this, but my conversations with other developers suggest that this creates a lot of extra work and overhead. The best path forward is to either use Xamarin.Forms exclusively for your views, or use platform-specific native views.
Here's a screenshot from Xamarin's Xamarin.Forms page (shot taken on May 13, 2015):

A: You can create a new Activity that is backed by Xamarin.Forms by inheriting from Xamarin.Forms.Platform.Android.AndroidActivity and launch this new activity from another one in your Xamarin.Android application.


text:
Q: Convert enumerated records to php object I have a table containing a bunch of records like this:
+-----------+--------+----------+
| extension | fwd_to | type     |
+-----------+--------+----------+
| 800       | 11111  | noanswer |
| 800       | 12345  | uncond   |
| 800       | 22222  | unavail  |
| 800       | 54321  | busy     |
| 801       | 123    | uncond   |
+-----------+--------+----------+

etc
The query looks like this:
select fwd_to, type from forwards where extension='800';

Now I get back an array containing objects which look like the following
when printed with Kohana::debug:
(object) stdClass Object
(
    [fwd_to] => 11111
    [type] => noanswer
)

(object) stdClass Object
(
    [fwd_to] => 12345
    [type] => uncond
)

(object) stdClass Object
(
    [fwd_to] => 22222
    [type] => unavail
)

(object) stdClass Object
(
    [fwd_to] => 54321
    [type] => busy
)

What I'd like to do is convert this to an object of this form:
(object) stdClass Object
(
    [busy] => 54321
    [uncond] => 12345
    [unavail] => 22222
    [noanswer] => 11111
)

The reason being I want to then call json_encode on it.  This will allow me to use jquery populate to populate a form.
Is there a suggested way I can do this nicely?  I'm fairly new to PHP and I'm sure this is easy but it's eluding me at the moment.

A: It's a ugly hack, but does the job:
$newObj = new stdClass();
// $resultArray is the query return
foreach($resultArray as $obj) {
    $newObj->{$obj->type} = $obj->fwd_to;
}

A: Ok, this is my own answer.  Not sure if it's the most optimal way but it works.
Instead of using an object. I'm using an associative array which will also give the same result when calling json_encode.
$this->template->content->call_forwarding = array();

$forwards = $phones->fetch_call_forwarding_numbers($this->account, $id);
foreach($forwards as $value){
    $this->template->content->call_forwarding[$value->type] = $value->fwd_to;
}

echo Kohana::debug($this->template->content->call_forwarding);

outputs:
(array) Array
(
    [noanswer] => 11111
    [uncond] => 12345
    [unavail] => 22222
    [busy] => 54321
)

Then calling json_encode the result is what I'm after.
i.e. echo Kohana::debug(json_encode($this->template->content->call_forwarding));
(string) {"noanswer":"11111","uncond":"12345","unavail":"22222","busy":"54321"}


text:
Q: Efficiently calculating mathematical formulas with exponents I'm implementing a program that calculates an equation: F(n) = F(n-1) + 'a' + func1(func2(F(n-1))).
func1 takes every 'a' and makes it 'c' and every 'c' becomes 'a'.
func2 reverses the string (e.x. "xyz" becomes "zyx").
I want to calculate the Kth character of F(10**2017).
The basic rules are F(0) = "" (empty string), and examples are F(1) = "a", F(2) = "aac", and so on.
How do I do this efficiently?
The basic part of my code is this:
def op1 (str1):
     if str1 == 'a':
          return 'c'
     else:
          return 'a'

def op2 (str2):
     return str2[::-1]

sinitial = ''

while (counter < 10**2017):
    Finitial = Finitial + 'a' + op1(op2(Finitial))
    counter += 1

print Finitial

A: Let's start by fixing your original code and defining a function to compute F(n) for small n. We'll also print out the first few values of F. All code below is for Python 3; if you're using Python 2, you'll need to make some minor changes, like replacing str.maketrans with string.maketrans and range with xrange.
swap_ac = str.maketrans({ord('a'): 'c', ord('c'): 'a'})

def F(n):
    s = ''
    for _ in range(n):
        s = s + 'a' + s[::-1].translate(swap_ac)
    return s

for n in range(7):
    print("F({}) = {!r}".format(n, F(n)))

This gives the following output:
F(0) = ''
F(1) = 'a'
F(2) = 'aac'
F(3) = 'aacaacc'
F(4) = 'aacaaccaaaccacc'
F(5) = 'aacaaccaaaccaccaaacaacccaaccacc'
F(6) = 'aacaaccaaaccaccaaacaacccaaccaccaaacaaccaaaccacccaacaacccaaccacc'

A couple of observations at this point:

*

*F(n) is a string of length 2**n-1. That means that F(n) grows fast. Computing F(50) would already require some serious hardware: even if we stored one character per bit, we'd need over 100 terabytes to store the full string. F(200) has more characters than there are estimated atoms in the solar system. So the idea of computing F(10**2017) directly is laughable: we need a different approach.

*By construction, each F(n) is a prefix of F(n+1). So what we really have is a well-defined infinite string, where each F(n) merely gives us the first 2**n-1 characters of that infinite string, and we're looking to compute its kth character. And for any practical purpose, F(10**2017) might as well be that infinite string: for example, when we do our computation, we don't need to check that k < 2**(10**2017)-1, since a k exceeding this can't even be represented in normal binary notation in this universe.
Luckily, the structure of the string is simple enough that computing the kth character directly is straightforward. The major clue comes when we look at the characters at even and odd positions:
>>> F(6)[::2]
'acacacacacacacacacacacacacacacac'
>>> F(6)[1::2]
'aacaaccaaaccaccaaacaacccaaccacc'

The characters at even positions simply alternate between a and c (and it's straightforward to prove that this is true, based on the construction). So if our k is even, we can simply look at whether k/2 is odd or even to determine whether we'll get an a or a c.
What about the odd positions? Well F(6)[1::2] should look somewhat familiar: it's just F(5):
>>> F(6)[1::2] == F(5)
True

Again, it's straightforward to prove (e.g., by induction) that this isn't simply a coincidence, and that F(n+1)[1::2] == F(n) for all nonnegative n.
We now have an effective way to compute the kth character in our infinite string: if k is even, we just look at the parity of k/2. If k is odd, then we know that the character at position k is equal to that at position (k-1)/2. So here's a first solution to computing that character:
def char_at_pos(k):
    """
    Return the character at position k of the string F(n), for any
    n satisfying 2**n-1 > k.
    """
    while k % 2 == 1:
        k //= 2
    return 'ac'[k//2%2]

And a check that this does the right thing:
>>> ''.join(char_at_pos(i) for i in range(2**6-1))
'aacaaccaaaccaccaaacaacccaaccaccaaacaaccaaaccacccaacaacccaaccacc'
>>> ''.join(char_at_pos(i) for i in range(2**6-1)) == F(6)
True

But we can do better. We're effectively staring at the binary representation of k, removing all trailing '1's and the next '0', then simply looking at the next bit to determine whether we've got an 'a' or a 'c'. Identifying the trailing 1s can be done by bit-operation trickery. This gives us the following semi-obfuscated loop-free solution, which I leave it to you to unwind:
def char_at_pos2(k):
    """
    Return the character at position k of the string F(n), for any
    n satisfying 2**n-1 > k.
    """
    return 'ac'[k//(1+(k+1^k))%2]

Again, let's check:
>>> F(20) == ''.join(char_at_pos2(i) for i in range(2**20-1))
True

Final comments: this is a very well-known and well-studied sequence: it's called the dragon curve sequence, or the regular paper-folding sequence, and is sequence A014577 in the online encyclopaedia of integer sequences. Some Google searches will likely give you many other ways to compute its elements. See also this codegolf question.

A: Based on what you have already coded, here's my suggestion:
def main_function(num):
    if num == 0:
        return ''
    previous = main_function(num-1)
    return previous + 'a' + op1(op2(previous))

print(main_function(10**2017))

P.S: I'm not sure of the efficiency.


text:
Q: Centering contents of a div - using CSS I have the following source in a user control:

<asp:Panel runat="server" ID="PanelParametersList" CssClass="AccessReportParameterControls"></asp:Panel>

<asp:Button ID="Button1" runat="server" Text="View Report"
    onclick="Button1_Click"></asp:Button>
<asp:Button ID="Button2" runat="server" Text="Back"
    onclick="Button2_Click"></asp:Button>

In the header of the containing aspx page I am adding css styles:

I am trying to center the contents of the button panel div but am having no luck.....any ideas?

A: For centering content in a div
text-align:center;

A:

    <button />

Style:
.parent{
    text-align:center;
}

This is all you need to do. Set the text-align to center in any parent container and the inline elements will follow the rule.
As a good practice I would advice you to place your styles in a different style.css file and place this in your .asp files:
<link href="style.css" rel="stylesheet" type="text/css" />


text:
Q: Return integer index of 1D array for 2D array of coordinates pairs After reading 10+ threads about converting an entire array from 2D to 1D and vice versa, I'm wondering if there is a mathematical formula, requiring no iteration to return the index position of a pair of integers for a sorted 2D array.
My "grid" is always square, can be any size (it's 3x3 in this example), and I've got a sorted block of human friendly values from which I need to retrieve what I'm calling "True 1D indices" like this:
"Human-friendly" coordinates| Java 2D Indices    |  True 1D indices
    [1,1],[1,2],[1,3],  ==>   [0,0],[0,1],[0,2], ==>  0 , 1 , 2
    [2,1],[2,2],[2,3],  ==>   [1,0],[1,1],[1,2], ==>  3 , 4 , 5
    [3,1],[3,2],[3,3],  ==>   [2,0],[2,1],[2,2], ==>  6 , 7 , 8

So I need a method for my class to give me the following results:
I enter 1,1 and get back 0,
I enter 3,2 and get back 7,
I enter 2,3 and get back 5,
etc etc...
I've played around with half a dozen equations where I try things like adding the coordinates to the previous row index squared, and I can never get the right result for every cell in the grid. Is there some special operator or Math function I'm missing?
Thanks.

A: let the matrix be of 3*3 ,3 rows and 3 column and we have to find the indices of (i,j) then the formula will be.
indices= 3*(i-1)+j;
Note :- here 3*3 and i,j are not it java 2d array format it is in human friendly coordinates.
Example (i,j)=(2,3)
indices=3*(2-1)+3   =6
And since your indices starts from 0 you could simply subtract one from 6 i.e. 5.

A: If the indices are named [index1,index2],
1DIndex = (rowNumber*index1) + index2

Where rowNumber starts at 1 for the first row, and index1 and index2 are the Java indices.


text:
Q: android activity configuration change issue I have an activity and in manifest i set theme Theme.Translucent
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.theme"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:label="@string/app_name" android:icon="@drawable/icon">
        <activity android:name=".MyActivity"
                  android:theme="@android:style/Theme.Translucent"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

but now my activity does not changes orientation. Is it because of the theme? And do you know how to fix this without removing the theme?
public class MyActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }
}

A: It's not because of the theme, if you add this to your activity, can you check if it is called while debugging for example?
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
}


text:
Q: Can't show new features on map with Python addfeature() I wrote a script to receiave NMEA from socket:
it gets NMEA sentences and creates points in a memory layer on the map.
It works, but map doesn't show new created points until I move or zoom it.
Here's the code:
from threading import Thread
from qgis.PyQt.QtCore import QVariant
import socket
from qgis.core import *
from qgis.gui import QgsMapCanvas

# get parts of nmea sentence
def nmea_split(nmea_string):
    return nmea_string.split(",")

# get lon/lat
def get_coord_gga(nmea_string):
    fields = nmea_split(nmea_string)
    # extract lon/lat from fields[2] and fields[4]
    lat = fields[2]
    lon = fields[4]
    return float(lat), float(lon)

# create socket UDP
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.bind(("127.0.0.1", 12345))

# set an empty layer
layer = QgsVectorLayer("Point", "track", "memory")
pr = layer.dataProvider()
pr.addAttributes([QgsField("point",  QVariant.Int),
                  QgsField("lon", QVariant.Double),
                  QgsField("lat", QVariant.Double)])
layer.updateFields()
layer.updateExtents()
QgsProject.instance().addMapLayer(layer)

def startLogger():
    point_num = 0
    while True:
        data = s.recvfrom(1024)
        nmea = data[0].decode()
        code = nmea_split(nmea)[0]
        # if data match GGA NMEA-sentence
        if code == "$GPGGA":
            point_num = point_num + 1
            lat, lon = get_coord_gga(nmea)
            f = QgsFeature()
            f.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(lon, lat)))
            f.setAttributes([point_num, lon, lat])
            pr.addFeature(f)
            layer.updateFields()
            QgsProject.instance().addMapLayer(layer)
            selection = layer.selectedFeatures()

Thread(target=startLogger).start()

points are correclty added, but I have to move map to show them.
I tried with qgis.utils.iface.mapCanvas() zoom features, but it makes a sort of freezing to the map.
UPDATE:
to show what happens if I use some iface function, I add a gif:

As you see, when I simply add to code:
canvas = iface.mapCanvas()
canvas.zoomOut()

the zoom "freezes" map and deny to update map view to add new points.
I tried this, and other canvas updates but the result is the same.

A: Tank you to @Matt I found a solution.
Reading what he suggested in comment:
https://gis.stackexchange.com/a/448531/128665
in section Qtimer I found the funtion witch can update map everytime a new point is added.
The function to add is:
layer.triggerRepaint()

Tank you so much @Matt.
I also resolved correct use of iface.mapCanvas(), reading this post.
To prevent freezing during canvas operations, you need to use:
iface.mapCanvas().freeze() # toggles rendering off to prevent deadlocking the map
canvas.zoomIn() # or whatever..
iface.mapCanvas().freeze(False) # unfreeze renderer

reading post is suggested to do this operations also before adding a layer to map.
p.s: it's quite ironic.. freeze canvas to not freeze map.


text:
Q: Extracting lines from start of files I have an assignment:

Write a shell script that copies the first 3 lines of code from all ".c" files in the current directory to a temporary file provided as a positional parameter. The contents of the temporary file are displayed.

Initially I created files ending in ".c", and then I used head -3 *.c> touch $1 to be able to copy the first 3 lines of each file with that extension, but I want to know if I did okay or could solve in another way.

A: Your approach with head looks good at first glance, but you will notice how, when you run head on multiple files at once, the utility puts a header into the output with the file's name in it.
You might possibly want to avoid getting this header, just to follow the assignment text to the letter.
You also don't have to use touch at all. I've noticed in attempted solution to other homework assignments that people sometimes think they have to "create the file" first before redirecting data to it, and then they use touch to do this.
When you redirect with >filename, the given file will automatically be created if it does not already exist (and if permissions in the current directory permits it).  If the file exists, it will be truncated (emptied).
Ok, so how do we stop head from producing headers with filenames in the output? Well, if you're on a Linux system, you probably have GNU head.  This implementation of head has a non-standard -q option that suppresses the headers.
The script could therefor be written as
#!/bin/sh

head -q -n 3 -- *.c >"$1"

... assuming the user has GNU head.  Note the --. It is needed to signal "end of command line options" to head just in case any of the filenames matching the *.c filename globbing pattern starts with a dash.  That dash would potentially by taken as the start of an option string.
Another way to do that is to use head -q -n 3 ./*.c where ./*.c explicitly refers to files in the current directory. With each filename being prepended by ./, no argument has a chance to start with a dash, so -- is no longer needed.  Which way you do this is up to you, but test your script with a file called --help.c in the current directory (touch -- --help.c).
I've chosen to use /bin/sh as the interpreter for this script, rather than /bin/bash.  I did this because the script does not use anything bash it needs bash for, like arrays, process substitutions, brace expansions, regular expression matching, etc.
If you aren't on a Linux system, or if you want to by compliant to the POSIX standard and write a portable script, you should not use -q with head.
Instead, you may want to loop over the files and use head on each individual file:
#!/bin/sh

for name in *.c; do
    head -n 3 -- "$name"
done >"$1"

Note how we can redirect the output of the loop to a file.
You will also note that solving this by using a loop will make the script work even if you have many thousands of .c files.  Without the loop, you are likely to get an "argument list too long" error when the shell tries to run head with the expansion of all those thousands of filenames.  The downside is that running head against each file individually is rather slow, especially if you have thousands of files.
The next issue is to figure out what should happen if the user of this script doesn't supply a proper argument.  Let's say the user runs this script with a filename that already exists, or with no filename at all.  Lets catch that and complain without doing anything more:
#!/bin/sh

if [ "$#" -ne 1 ]; then
    printf 'expecting 1 argument, got %d\n' "$#" >&2
    exit 1
elif [ -e "$1" ]; then
    printf 'the name "%s" already exist, refusing to over-write\n' "$1" >&2
    exit 1
fi

for name in *.c; do
    head -n 3 -- "$name"
done >"$1"

This introduces an if statement that firsts test the number of command line arguments given to the script.  If it's not exactly one, complain and exit.  If it's one, but it refers to an already existing name, complain and exit.
Note that diagnostic messages (like errors) should be written to the standard error stream.  I do this here by redirecting the output with >&2.  I also terminate the script with a non-zero exit status when it's clear we can't continue.  This makes it possible to test whether your script ran successfully or not:
if ./your-script.sh hello world; then
    echo ok
else
    echo something went wrong
fi

The remaining issue is to handle the case where there are no .c files in the current directory.  When this happens, you will notice how your script generates a strange error:
head: *.c: No such file or directory

This is due to the fact that when a pattern such as *.c doesn't match anything, it remains unexpanded.  We can work around this by adding a small test in our loop:
for name in *.c; do
    [ ! -e "$name" ] && continue
    head -n 3 -- "$name"
done >"$1"

This means "if the file $name does not exist, then just skip this iteration of the loop".
If you write this script as a bash script, then you could leave the original loop and then set he nullglob shell option with shopt -s nullglob before the loop to make the shell remove unmatched patterns rather than retain them unexpanded.
Now when you run your script, it will not generate any errors when there are no .c files in the current directory, but the output file will be blank if that happens.  If this is undesired, then you may want to test whether *.c actually matches anything before starting the loop and redirecting to the output file:
outfile=$1

set -- *.c

if [ -e "$1" ]; then
   for name do
       head -n 3 -- "$name"
   done >"$outfile"
fi

Here, we first save the name of the output file in a separate variable, because we will overwrite the positional parameters (the arguments given to the script) with the names of all .c files (which is done with set).
If the first positional parameter is an existing filename, then we allow the loop to run and the output file to be created/truncated.
The loop, when not given anything to iterate over, as in this last piece of code, will iterate over the list of positional parameters by default.  We already set this list to the files with names ending in .c.

The other variants is to not use head at all, but an equivalent command such as sed 3q or awk '1; NR == 3 { exit }' or some other command.  By using the head utility, however, you make it clear what it is you're intending to do.


text:
Q: Анимация при вставке html кода .c_play {
    display: none;
    position: absolute;
    left: 50%;
    top: 50%;
    fill: #fff;
    width: 60px;
    z-index: 2;
    margin-left: -30px;
    margin-top: -30px;
    background: rgba(0,0,0,0.7);
    border-radius: 50%;
    animation: anip .5s linear 1 normal forwards;
    pointer-events: none;
}
@keyframes anip {0%{opacity:1}to{opacity:0; transform:scale(2)}}

<svg class="c_play" viewBox="0 0 36 36">
    <path d="M 12,26 18.5,22 18.5,14 12,10 z M 18.5,22 25,18 25,18 18.5,14 z"></path>
</svg>

Изначально выставлено свойство display: none;
Убираем свойство и происходит анимация.
Через js, прибегаю к settaimayt. Через .5 сек, вновь выставляю display:none.
Вопрос в том, возможно ли не прибегая к изменениям свойства display. Выполнить один раз анимацию, когда помещаем блок path в родителя svg??
Другими словами:
Через js, меняем содержимое svg блока. Помещаем туда
<path d="M 12,26 18.5,22 18.5,14 12,10 z M 18.5,22 25,18 25,18 18.5,14 z"></path>

В данный момент как только поместили, возможно выполнить анимацию?
Вешаю на path, который вставляю по клику
path {
    fill: #fff;
    width: 50%;
    z-index: 2;
    background: rgba(0,0,0,0.7);
    border-radius: 50%;
    animation: anips 1s linear 1 normal forwards;
    pointer-events: none;
}
@keyframes anips {0%{width: 50%;}to{width: 100%;opacity:0;}}

Дак, выполнить такую же анимацию не удается. Не изначальную ширину ни фона не выставляется, чтобы в дальнейшем применить анимацию...


text:
Q: React JS Best Practice I am planning to use my state as a form of signaling that I will gonna change back and forth to show my loading screen, main form and success or error message. But not sure if this is the best practice. Here is a sample code
div hidden={this.state.FormStatus.statusMode !== "Loading"}>
          <LoadingScreen />

div hidden={this.state.FormStatus.statusMode !== "Main"}>
          <MainForm/>

But I am not sure if this is the best way, I am worried that it can slowdown my application or eat my clients CPU with this one. Can you suggest better method?

A: render() {
  const { statusMode } = this.state.FormStatus;

  if (statusMode === 'Loading') {
    return <LoadingScreen />;
  } else if (statusMode === 'Main' {
    return <MainForm />;
  }
}

or
render() {
  const { statusMode } = this.state.FormStatus;

  return (

      Something you want to display no matter what
      {statusMode === 'Loading' && <Loading />}
      {statusMode === 'Main' && }

  );
}

A: Not sure how the performance improvement is over what you are doing but here is an idea.
render() {
  const { FormStatus: { statusMode } } = this.state;
  const component = { Loading: <LoadingScreen />, Main: <MainForm /> };

  return component[this.state.FormStatus.statusMode];
}

For the record, what you are doing is fine. Only real improvement is to only render one div instead of two.

A: If you using hook then,
const Example = () => {
     const [loading, setLoading] = React.useState(true)

     return (
        <>
           {loading && <Loading />}
           {!loading &&  }
        </>
     )
}


text:
Q: .click on list containing radio - can't select radio directly I have an unordered list containing radio inputs and labels. When a user clicks on the list item it toggles some info and selects the radio input.
However, due to the above, if the user clicks onto the actual radio input itself, it does not select it, as I guess the click is registered against the radio and not the list item itself?
Is there any cure?
    jQuery('#sdmlist li.item').click(function(e) {
       jQuery('#sdmlist li.item address').slideUp();
       jQuery("address",this).slideToggle("slow");
       jQuery("input[type=radio]", this).attr('checked',true);
       var element = jQuery("input[type=radio]", this).val();
       ...
       return false;
    });

and some html:

<input type="radio" name="1" id="1">1 <address>test 123</address>

<input type="radio" name="2" id="2">2 <address>test 23</address>

<input type="radio" name="3" id="3">3 <address>test 3</address>

A: That behavior is caused by return false stopping the default behavior of the click event who has been propagated by then click on the radio. The default behavior of the radio is, of course, the radio beign checked.
Just remove the return false and it work : http://jsfiddle.net/4v9R9/2/


text:
Q: How to go back to top of Programm Im new to python and wrote a programm that does a+b=c and the question is, how do i do that the programm  go back to the top?
This is what i have tried but it wont open
#def start():
   a = int(input("num1: "))
   b = int(input("num2: "))
   c = a + b

   print("sum of {0} + {1} = {2}" .format(a, b, c))
   restart = input("Exit or Again?: ")

   if restart == "Again" or "again":
       start()
   if restart == "Exit" or "exit":
       exit

Had looked up a few tutorials but none of them helped.
Thank you in advance.

A: Be careful with your condition restart == "Again" or "again" because it is equivalent to (restart == "Again") or "again". The boolean value of a string (here again) is True unless this string is empty. So this condition will always be True.
If you want to keep the same structure :
def start():
   a = int(input("num1: "))
   b = int(input("num2: "))
   c = a + b

   print("sum of {0} + {1} = {2}" .format(a, b, c))
   restart = input("Exit or Again?: ")

   if restart in ["Again", "again"]:
       start()
   else:
       print("Bye !")

start()

If you prefer to achieve it with a while loop :
restart = "again"
while restart in ["Again", "again"]:
    a = int(input("num1: "))
    b = int(input("num2: "))
    c = a + b
    print("sum of {0} + {1} = {2}" .format(a, b, c))
    restart = input("Exit or Again?: ")

A: You need a loop.
again = True
while again:
    ...
    if restart.lower() == 'exit':
        again = False

A: Your code only defines a function. If you want to run it from command line, you need to add some code to do so.
The 2 lines I added at the bottom detect if you're running this file directly and then invoke your function. If you imported this module, the if would be false and the logic within the if would not be run.
def start():
    a = int(input("num1: "))
    b = int(input("num2: "))
    c = a + b

    print("sum of {0} + {1} = {2}" .format(a, b, c))
    restart = input("Exit or Again?: ")

    if restart in ["Again", "again"]:
        start()
    else
        exit()

if __name__ == '__main__':
    start()


text:
Q: purrr map a t.test onto a split df I'm new to purrr, Hadley's promising functional programming R library. I'm trying to take a grouped and split dataframe and run a t-test on a variable. An example using a sample dataset might look like this.
mtcars %>%
  dplyr::select(cyl, mpg) %>%
  group_by(as.character(cyl)) %>%
  split(.$cyl) %>%
  map(~ t.test(.$`4`$mpg, .$`6`$mpg))

This results in the following error:
Error in var(x) : 'x' is NULL
In addition: Warning messages:
1: In is.na(x) : is.na() applied to non-(list or vector) of type 'NULL'
2: In mean.default(x) : argument is not numeric or logical: returning NA

Am I just misunderstanding how map works? Or is there a better way to think about this?

A: Especially when dealing with pipes that require multiple inputs (we don't have Haskell's Arrows here), I find it easier to reason by types/signatures first, then encapsulate logic in functions (which you can unit test), then write a concise chain.
In this case you want to compare all possible pairs of vectors, so I would set a goal of writing a function that takes a pair (i.e. a list of 2) of vectors and returns the 2-way t.test of them.
Once you've done this, you just need some glue. So the plan is:

*

*Write function that takes a list of vectors and performs the 2-way t-test.

*Write a function/pipe that fetches the vectors from mtcars (easy).

*Map the above over the list of pairs.

It's important to have this plan before writing any code. Things are somehow obfuscated by the fact that R is not strongly typed, but this way you reason about "types" first, implementation second.
Step 1
t.test takes dots, so we use purrr:lift to have it take a list. Since we don't want to match on the names of the elements of the list, we use .unnamed = TRUE. Also we make it extra clear we're using the t.test function with arity of 2 (though this extra step is not needed for the code to work).
t.test2 <- function(x, y) t.test(x, y)
liftedTT <- lift(t.test2, .unnamed = TRUE)

Step 2
Wrap the function we got in step 1 into a functional chain that takes a simple pair (here I use indexes, it should be easy to use cyl factor levels, but I don't have time to figure it out).
doTT <- function(pair) {
  mtcars %>%
    split(as.character(.$cyl)) %>%
    map(~ select(., mpg)) %>%
    extract(pair) %>%
    liftedTT %>%
    broom::tidy
}

Step 3
Now that we have all our lego pieces ready, composition is trivial.
1:length(unique(mtcars$cyl)) %>%
  combn(2) %>%
  as.data.frame %>%
  as.list %>%
  map(~ doTT(.))

$V1
  estimate estimate1 estimate2 statistic      p.value parameter conf.low conf.high
1 6.920779  26.66364  19.74286  4.719059 0.0004048495  12.95598 3.751376  10.09018

$V2
  estimate estimate1 estimate2 statistic      p.value parameter conf.low conf.high
1 11.56364  26.66364      15.1  7.596664 1.641348e-06  14.96675 8.318518  14.80876

$V3
  estimate estimate1 estimate2 statistic      p.value parameter conf.low conf.high
1 4.642857  19.74286      15.1  5.291135 4.540355e-05  18.50248 2.802925  6.482789

There's quite a bit here to clean up, mainly using factor levels and preserving them in the output (and not using globals in the second function) but I think the core of what you wanted is here. The trick not to get lost, in my experience, is to work from the inside out.

A: To perform the two sample t-tests, you have to create the combinations of the numbers of cylinders. I don't see that you can create the combinations using purrr functions.  However a way which uses only purrr and base R functions is
library(purrr)
t_test2 <- mtcars %>% split(.$cyl) %>%
          transpose() %>%
          .[["mpg"]] %>%
          (function(x) combn(names(x), m=2, function(y) t.test(flatten_dbl(x[y[1]]), flatten_dbl(x[y[2]])) , simplify=FALSE))

although this does seem a bit contrived.
A similar approach which uses only base R functions with chaining is
t_test <- mtcars %>% split(.$cyl) %>%
                          (function(x) combn(names(x), m=2, function(y) x[y], simplify=FALSE)) %>%
                           lapply( function(x) t.test(x[[1]]$mpg, x[[2]]$mpg))

A: I don't fully understand the expected result, but this might be a starting point for an answer.  map() from purrr uses .x in the formula argument.
Here is one way to accomplish what I think you are trying to do with just purrr.
mtcars %>%
  split(as.character(.$cyl)) %>%
  map(~t.test(.x$mpg))

But, purrr::by_slice() pairs nicely with dplyr::group_by().
library(purrr)
library(dplyr)

mtcars %>%
  dplyr::select(cyl, mpg) %>%
  group_by(as.character(cyl)) %>%
  by_slice(~ t.test(.x$mpg))

Or, you could skip purrr entirely using dplyr:::summarise().
library(purrr)
library(dplyr)

mtcars %>%
  dplyr::select(cyl, mpg) %>%
  group_by(as.character(cyl)) %>%
  summarise(t_test = data_frame(t.test(.$mpg)))

If the nested data.frame is confusing, broom can help us get an easy data.frame summary of the results.
purrr + broom + tidyr
library(broom)
library(tidyr)
mtcars %>%
  group_by(as.character(cyl)) %>%
  by_slice(~tidy(t.test(.x$mpg))) %>%
  unnest()

dplyr + broom
library(broom)

mtcars %>%
  dplyr::select(cyl, mpg) %>%
  group_by(as.character(cyl)) %>%
  do(tidy(t.test(.$mpg)))

Edited to include response to comment
With pipes, we can get carried away quite quickly.  I think Walt did a nice job in his answer, but I wanted to make sure that I provided a purrr-ty answer.  I hope the use of pipeR is not overly confusing.
library(purrr)
library(dplyr)
library(broom)
library(tidyr)
library(pipeR)

mtcars %>>%
  (split(.,.$cyl)) %>>%
  (split_cyl~
    names(split_cyl) %>>%
     (
       cross_d(
         list(against=.,tested=.),
         .filter = `==`
       )
     ) %>>%
     by_row(
       ~tidy(t.test(split_cyl[[.x$tested]]$mpg,split_cyl[[.x$against]]$mpg))
     )
  ) %>>%
  unnest()


text:
Q: Elements' styles are lost when app is deployed I have been working on a new version of my company's website using Polymer and Google App Engine. The design looks great on my local development server, but as it gets deployed polymer elements' styles are completely messed up.
This is what it looks like when deployed to the app engine:
http://data-buckeye-590.appspot.com/HTL
Any clues what might be causing it?

A: Thanks for the support Ryan. Got a tweet from @robdodson yesterday that solved the problem. Turns out that Google App Engine mod_pagespeed was messing up the internal styling of my polymer elements.
After turning off pagespeed on the application settings console the app is running as it should. But there is a catch!!!
It was impossible to find the pagespeed (enable/disable) checkbox on the new Developers Console https://console.developers.google.com
In order to turn pagespeed off it is best one visits the old application settings console at https://appengine.google.com/settings


text:
Q: How to do a transpose a dataframe group by key on pandas? I have this table from my database and I need a transpose group by survey_id
id  answer  survey_id   question_number questionid
216     0.0         69               3         2.0
217     3.0         69               4         3.0
218     0.0         69               5         4.0
219     0.0         69               6         5.0
221     0.0         69               8         7.0

Like this:
Survey P01  P02 P03 P04 P05
69     1    1   2   2   1

The cell is the answer and the column is format "P{question_number}"
I'm using pandas 0.18.1.
How can I do that?

A: You can use pivot, add_prefix and reset_index:
print (df.pivot(index='survey_id', columns='question_number', values='answer')
         .add_prefix('P')
         .reset_index())

question_number  survey_id   P3   P4   P5   P6   P8
0                       69  0.0  3.0  0.0  0.0  0.0


text:
Q: Use of 'const' for function parameters in forward declarations Is there any reason to include the 'const' qualifiers for parameters in a function declaration if the function definition ignores them anyway? I assumed that the C++ compiler would enforce the usage of 'const' if it was forward declared, but this does not seem to be the case.
// Compiles without warnings.
void foo(const int x);
void foo(int x) {}
int main() {foo(0); return 0;}

A: No, there is no good reason to do that*.
I'd argue that adding const in the declaration is a bad idea anyway, even if the definition has it too. Why? Because the language ignores it in the declaration, so there is no guarantee that the definition will have it. In any case, it is an implementation detail (essentially, choosing to use a const local variable), so it should appear, if needed, in the definition only.

* "that" refers to top-level const. Pointer to const or reference to const is not ignored by the language.


text:
Q: Link direcionando de forma errada com htacess Estou utilizando a seguinte estrutura em endereços/links para url amigável em fixos da minha página:
RewriteRule ^teste(.*)$ teste.php

Então, meu endereço fica da seguinte forma: www.site.com/teste
Acontece que se o usuario digitar a palavra teste junto de outro termo, o site encontra do mesmo jeito, sendo que deveria mandar para a pagina de erro 404..
Ex: www.site.com/teste123
Com o link acima digitado, ele redireciona para a pagina de teste normalmente..

A: Se você quiser que só funcione teste, não pode ter o .*.
RewriteRule ^teste$ teste.php

Se quiser que o URL aceite mais coisas, separadas por barras, pode usar assim:
RewriteRule ^teste(/.*)*$ teste.php


text:
Q: Simple Modal - more than one I'm using the simplemodal-demo-basic-1.4.1 and iam having trouble using it to open more than one window on a page (I don't need them to open at the same time or on top of one another).
I tried adding another class and calling out that class in my js file, but I'm not getting it.  I'm sure I'm missing something. -Can someone please help?

A: I'm assuming you're talking about the demo available on the simplemodal Google Code project
Here's what I had to do to add a second modal dialog to that demo:
Add the following HTML to index.html:

*

*inside the content div:

Basic Two Modal Dialog

The Second Modal

*inside the basic-modal div:
<input type='button' name='basicTwo' value='Demo Two' class='basicTwo'/> or Demo Two

Add the following CSS to basic.css:
    #basicTwo-modal-content { display: none; }

Add the following JavaScript to basic.js inside the jQuery load handler:
    $('#basic-modal .basicTwo').click(function (e) {
      $('#basicTwo-modal-content').modal();

      return false;
    });

Working Demo


text:
Q: Can I cap a local collection in meteor js I want to use a local (un-backed) mongo collection as a cache, but I need to cap it so that it doesn't explode in size. Does anyone know of a good way to do this?
e.g.
Cache._createCappedCollection(1024 * 1024 * 10); // 10MB

The above works if we're working with a mongo collection, but if the collection is unbacked, then it'll throw an error: Error("Can only call _createCappedCollection on server collections")


text:
Q: Flash banner with clickTAG and clickTARGET I need to adapt my swf banner so that will work with clickTAG and clickTARGET. Actionscript code is required to be
on (release) {
  if (clickTAG.substr(0,5) == "http:") {
    getURL(clickTAG, clickTARGET);
  }
}

and my HTML code looks like this:
<embed src="banner.swf?clickTAG=http://my-site.com&clickTARGET=_blank" height="250" width="300">

What is wrong?

A: Actually the wrong thing was that i was using Flash 8, upper code is for Flash from 4 to 7.
Right way to do it in Flash 4, 5, 6 or 7 in ActionScript 2:
on (release) {
   if (clickTAG.substr(0,5) == "http:") {
      getURL(clickTAG, clickTARGET);
   }
}

Right way to do it in Flash 8 or 9 in ActionScript 2
on (release) {
   if (_root.clickTAG.substr(0,5) == "http:") {
      getURL(_root.clickTAG, _root.clickTARGET);
   }
}

The implementation in HTML is following.
With embed tag:
<embed src="path_to_swf.swf?clickTAG=http://website-to-open.com&clickTARGET=_blank" width="300" height="250">

Or with object tag which should be better practice:
<object type="application/x-schockwave-flash" data="path_to_swf.swf" width="300" height="250">
<param name="flashvars" value="clickTAG=http://website-to-open.com&clickTARGET=_blank">
</object>

Target _blank can also be replaced with _self or _top.

A: Looks like you are using Actionscript 2. Not sure if you meant to;
in Actionscript 3 you might code something like
myButton.addEventListener(MouseEvent.CLICK, go};
 function go(event:MouseEvent):void {
    if (clickTAG.substr(0,5) == "http:") {
    getURL(clickTAG, clickTARGET);
  }
)


text:
Q: How to get an output out of arrays without using pointers? Firstly i am new to this site and i wanted your help to solve this small problem as i am a beginner in C programming.
Here's my code.
#include<stdio.h>
#include<time.h>
main()
{
 char user[10],temp[10];
 int t;
 printf("Welcome to the game of guessing\nThere are 2 choices namely a,and b\n");
 getch();
 printf("You just have to guess and see if u are lucky\n");
 getch();
 printf("Type a letter from a and b choices\n");
 scanf("%s",&user[0]);
 srand(time(NULL));
 t=rand();
 if(t%2==0)
 {
      char temp[0]="a";
 }else
 {
      char temp[0]="b";
 }
 if(strncmp(temp,user,1)==0)
 {
      printf("You have guessed right. The answer is %s",user[0]);
 }else
 {
      printf("You have guessed wrong. The answer is %s, try again",temp[0]);
 }
 getch();

}

Well this code creates a simple guessing game kinda thing where you have to enter an input and if the your input tallys with that of computer's then you will win or else you will lose.
The problem that i am having is in those last printf statements. Look at the last printf
printf("You have guessed wrong. The answer is %s, try again",temp[0]);
Here the output is kinda like this.
You have guessed wrong. The answer is null, try again
So whats this null and how do i make it get what temp holds.
Also i am always getting the output as wrong. is there a way i can fix this? since this is based on equal probability, i think i should be able to get equal choices between a and b.
Thanks.

A: Delete "char" in first if and else and change "a" to 'a' and "b" to 'b'.
And in printf should be
printf("You have guessed right. The answer is %c",user[0]);

instead of
printf("You have guessed right. The answer is %s",user[0]);

The same in second printf


text:
Q: Exporting logo animation from after effects to use as loading Small animations files to try here : https://www.wetransfer.com/downloads/25c485d490e415a430464bb6258958c320170214000506/eda56579b69e291a497414b7fd52024d20170214000506/093842
I'm not developer I'm just an designer so sorry for my lack of knowledge.
How do I export the logo animation from after effects to be used as loading animation on my website?
I tried plugin Bodymovin it does work, but not on all browsers.
And sorry for any typos english is not my native language
Thank you all guys in advance!

A: @nellement
As far as I know Adobe removed FLV and F4V, which were the codecs used to export a flash movie, which is I think what you are looking for.
You might be able to do it if you still have an older version of either After Effects or Adobe Media Encoder.
If you don't you best bet will be to use H.264, that is what Adobe is recommending, see this post
removal of FLV and F4V export features from Adobe Media Encoder, After Effects, and Premiere Pro
Things to take into account for your animation, how long is the animation, how big in screen size, 1920X1080, or is it just a banner, if it is full screen, can you go for a smaller size?
You can render an Animation 100 from after effects then run it thru Media Encoder using some of their sample setting until you get something that works for size and quality.
I hope this is of some help


text:
Q: AFCompoundResponseSerializer JSON issue I'm using AFNetworking's latest version in a project that connects to an API that returns both text responses and JSON responses so I use AFCompoundResponseSerializer to handle both response.
Request that return a JSON file are given to me as a NSString of the JSON response instead of an NSDictionnary that is normaly returned with AFJsonResponseSerializer, it looks like the AFCompoundResponseSerializer takes the response as plain text and doesn't send it to the AFJsonResponseSerializer
My code fore the CompoundSerializer is as follow:
        sharedSessionManager = [[self alloc] initWithBaseURL:[NSURL URLWithString:baseURL]];
    sharedSessionManager.responseSerializer=[AFCompoundResponseSerializer compoundSerializerWithResponseSerializers:@[[AFJSONResponseSerializer serializer], [AFHTTPResponseSerializer serializer]]];

A: I found out why this happened:
The server returned JSON as text/html so the serializer sended it directly to AFHTTPResponseSerializer which returned a string instead of parsing the JSON.
To fix this, just add text/html to the JSON serializer's acceptableContentTypes


text:
Q: Is there a way to change Google Maps background on Android? On the image below you can see that grey background. That is what I would like to change. I am aware you can style your maps with this handy thing. But there is no option to change the background. I use an empty map, with my custom overlay image only, so I have only the background color and my ground overlay object.
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NONE);

customMapOverlay = new
GroundOverlayOptions()
.image(BitmapDescriptorFactory.fromResource(R.drawable.test_image)
.position(.....);

mapOverlay = mMap.addGroundOverlay(customMapOverlay);

And it would be not a very elegant solution to style all map elements the same, so it looks like a solid background color. I could do that at the end. But it worth a question to know if there is an official way to do this?

A: You can try this :
 mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

or
 mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

or
 mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);

or
 mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);


text:
Q: How to create plus icon in grid recyclerview for adding images?
How do I create something like this using gridlayoutManager In a reyclerview? How to do this in an efficient way, so that whenever I click on the plus image I can fetch a new image from my device so that the image shows up in the grid at bottom or in a new column?

A: You can create two layouts : one with the + icon and other where image will be displayed for your grid adapter. Then you can check for the position and return the layout you want.
      private static final int VIEW_TYPE_ONE = 1;
      private static final int VIEW_TYPE_TWO = 2;

      // Determines the appropriate ViewType according to the position
@Override
public int getItemViewType(int position) {

    if (position == 0 ) {

        return VIEW_TYPE_ONE;
    } else {

        return VIEW_TYPE_TWO;
    }
}

Then in your onCreateviewHolder:
     // Inflates the appropriate layout according to the ViewType.
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view;

    if (viewType == VIEW_TYPE_ONE) {
        view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.your_plus_icon_layout, parent, false);
        return new PlusIconViewHolder(view);
    } else if (viewType == VIEW_TYPE_MESSAGE_TWO) {
        view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.your_normal_image_layout, parent, false);
        return new NormalViewHolder(view);
    }

    return null;
}

In your onBindViewHolder,
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    switch (holder.getItemViewType()) {
        case VIEW_TYPE_ONE:
             holder.bind();
            break;
        case VIEW_TYPE_MESSAGE_TWO:
             holder.bind(imageList.get(position -1));
    }
}

Note that i have send position - 1 item from the list.Its because images will be shown from 1 index because index 0 is occupied by your + icon.
And yes you have to create two veiwholders too for their respective functionalities.

A: You need to create an adapter that supports two types of items - photo one and '+' one. Then add special '+' item at first position in the list that you provide to the adapter.
Check this link: "A RecyclerView with multiple item types" by Vitaly Vivchar.


text:
Q: Why does python dictionary in function return 0 value as none def extract(lst,item):
    for i in lst:
        if i.get(item):
            return i[item]
print(extract([{'coin':0},{'xp':5}], 'coin'))

This code must return the value 0 as far as I understand but instead returns None. When I change the value of 0 to anything else it works correctly; looks like the only problem is that the function returns None instead of 0. The purpose of this function is to iterate through a list of dictionaries (lst) and return the value associated with the key (item).


text:
Q: How to SetTimeout Function I have a question.
I have a function that scans devices and if a devices was found it will be connect.
Now my problem is that this function could crash for a reason x.
If it gets stuck it does nothing else. I would like to set a setTimeout () so that if the function crashes, after a period of time it performs an action.
How can I set this setTimeout ()? thanks a lot!
scan1() {
    console.log(" ");
    console.log("-- Start scan device -- ");
    // IF there is error it prints only the console.log above.
    this.manager.startDeviceScan(null, null, (error, device) => {
      if (error) {
        return;
      }
      if (
        (device.name == this.model_dx(this.props.Model)) ||
        (device.name == this.model_sx(this.props.Model))
      ) {

        this.setState({ deviceId1: device.id });
        console.log("ID Device 1 (this.state.deviceId1): " + this.state.deviceId1);
        this.manager.stopDeviceScan();
        this.setState({deviceName1: device})
        console.log("(this.state.deviceName1 = device:): " + this.state.deviceName1);
        device
          .connect()
          .then(() => {
            console.log("--Connected.--");
            this.scan2();
          })
          .catch(() => {
            Alert.alert("No connection.");
            Actions.homepage();
          });
      }
      else {
        this.manager.stopDeviceScan();
        console.log("ERROR.")
      }
    });
  }

A: From what I gather the problem is that device.connect() doesn't error correctly so will just silently die and the catch will not work properly.
If so you could wrap device.connect() in another promise with a timeout to reject.
This gist would do the trick. Javascript Promise Timeout.
https://gist.github.com/john-doherty/bcf35d39d8b30d01ae51ccdecf6c94f5
The only problem being you can't actually cancel device.connect() so it may be doing something strange in the background after you think it has stopped or it maybe a problem to re-try. The best thing would be to check out the device.connect() and see if you can pass it a callback that can actually reject the promise. If you can't this should work.
function promiseTimeout(ms, promise){

  return new Promise(function(resolve, reject){

    // create a timeout to reject promise if not resolved
    var timer = setTimeout(function(){
        reject(
            // Do whatever you want here after the timeout
        );
    }, ms);

    promise
        .then(function(res){
            clearTimeout(timer);
            resolve(res);
        })
        .catch(function(err){
            clearTimeout(timer);
            reject(err);
        });
  });
};

scan1() {
    console.log(" ");
    console.log("-- Start scan device -- ");
    // IF there is error it prints only the console.log above.
    this.manager.startDeviceScan(null, null, (error, device) => {
      if (error) {
        return;
      }
      if (
        (device.name == this.model_dx(this.props.Model)) ||
        (device.name == this.model_sx(this.props.Model))
      ) {

        this.setState({ deviceId1: device.id });
        console.log("ID Device 1 (this.state.deviceId1): " + this.state.deviceId1);
        this.manager.stopDeviceScan();
        this.setState({deviceName1: device})
        console.log("(this.state.deviceName1 = device:): " + this.state.deviceName1);

promiseTimeout(device.connect(), 500)
  .then(() => {
    console.log("--Connected.--");
    this.scan2();
  })
  .catch(() => {
    Alert.alert("No connection.");
    Actions.homepage();
  });
}
      else {
        this.manager.stopDeviceScan();
        console.log("ERROR.")
      }
    });
  }


text:
Q: What is the role/permission for user to see the application UI that runs under SYSTEM account I have a Windows Service that automatically starts another WPF application ( from an .exe file)- I know this is not a good practice, however that is a requirement I got.
I am able now to start a UI application via Windows Service. This works fine on my local computer; I can see a UI and the application is running correctly. The application is running under the "SYSTEM" user as seen from the Windows Task Manager.
The problem only occurs when I move the code to our production computer, which is Windows Server 2012, and the account I use is given by our IT department (and it should have admin rights). After running the service, the application is running successfully; I can see it from the Task Manager. However, I cannot see the UI even though it is still running under "SYSTEM" account.
What sort of role or permission does a user need to see the UI application (or just an application in general) running under "SYSTEM" account?


text:
Q: Delphi subclasses inheritance When I write a class I know that I can use the inherted keyword so I can inherit the behavior or TObject, such as:
type
 TOperation = class(TObject)
   constructor Create(dest, r1, r2: integer);
 end;

And the constructor will have an inherited Create;. Look at the following class:
type
 TAddition = class(TOperation)
   constructor Create(a1, a2: integer);
 end;

If the first line of TAddition is inherited Create; it means that I am inheriting the behavior of TOperation of course. But does this mean that I am also inheriting the behavior of TObject? (which is a superclass of TOperation).
When I inherit from the constructor of a father class (look at TAddition) I am inheriting only the behaviour, don't I? I am not initializing anything from the father class
The complete code is here:
 TOperation = class(TOBject)
  private
   dest, v1, v2: integer;
  public
   constructor Create(dest, r1, r2: integer);
   property destination: integer read dest;
   property value1: integer read v1;
   property value2: integer read v2;
 end;

 TMemoria = class(TOperation )
  private
   dest, r1: integer;
  public
   constructor Create(dest, r1: integer);
   property destination: integer read dest;
   property register1: integer read r1;
 end;

 constructor TOperation.Create(dest, r1, r2: integer);
 begin

  //inherit from TObject
  inherited Create;
  Self.r1 := r1;
  Self.r2 := r2; //so on...

 end;

constructor TMemoria.Create(dest, r1: integer);
 begin

  //inherit from TObject OR inherit from TOperation?
  inherited Create;

 end;

A: constructor TMemoria.Create(dest, r1: integer);
begin
  inherited Create;
end;

This calls the parameterless constructor in TObject and does not call the constructor declared in the immediate ancestor. That much should be clear because no parameters are supplied.
For full details please see the documentation: http://docwiki.embarcadero.com/RADStudio/en/Methods_(Delphi)#Inherited
As a strong guiding principle you should not miss out calling inherited constructors from parent classes. Often this means that you fail to instantiate an object that is used by the parent class. I would regard the code in the question as very suspicious.


text:
Q: Creating Templates on Vim-latex suit template I have a question on creating templates on vim-LaTeX suite.
I placed a template file on
/usr/share/vim/addons/ftplugin/latex-suite/templates/

with the content of
<+      +>      !comp!  !exe!
%        File: !comp!expand("%:p:t")!comp!
%     Created: !comp!strftime("%a %b %d %I:00 %p %Y ").substitute(strftime('%Z'), '\<\(\w\)\(\w*\)\>\(\W\|$\)', '\1', 'g')!comp!
% Last Change: !comp!strftime("%a %b %d %I:00 %p %Y ").substitute(strftime('%Z'), '\<\(\w\)\(\w*\)\>\(\W\|$\)', '\1', 'g')!comp!
%
\documentclass[a4paper]{article}
\usepackage[top=1in, bottom=1in, left=1in, right=1in]{geometry}
\usepackage{amssymb}
\usepackage{amsmath}
\usepackage{graphicx}
\graphicspath{{<++>}}
\usepackage{fancyhdr}
\pagestyle{fancy}
\newcommand{\norm}[1]{\lVert#1\rVert}
\begin{document}
\lhead{<++>}
\rhead{<++>}
\cfoot{\thepage}
<++>
\end{document}

Then I created the soft link of it in directory:
/var/lib/vim/addons/ftplugin/latex-suite/templates/

If everything goes well, when create a new tex file on vim and type
:TTemplate

on the command line, I should be getting:
File with file name,
Created with date and time of creation
Last Change with date and time of when the last change was made.
and starting cursor should be on
   \lhead{ cursor here }
However, it seems that it won't show up any vim-formatted dates and initial position of the cursor doesn't be on where I want it to be.
Is there any solution to this problem?
I am using ubuntu 14.04, vim-latex suit.
Thank in advance.

A: Turns out, spaces were tabs, not spaces.
My post on stackoverflow
has more information. Thank you.


text:
Q: Compare two records based on date and return the latest record in cassandra I have a table in Cassandra and id and Date are Primary column and Clustering Column.

What I want is, i.e. latest records for every id based on Date.
I cannot create new table or view for this.
Thanks :)

A: In recent versions of Cassandra (starting with Cassandra 3.6 as per CASSANDRA-7017), there is support for clause PER PARTITION LIMIT that will return N records for every partition. In your case, you'll need to define sorting order for date field by descending order, and you'll able to write like this:
SELECT * from TABLE PER PARTITION LIMIT 1;


text:
Q: Rendering footer section in razor pages works cover button from body I got problem with my Razor page application. I already use render section for footer:

        @RenderSection("footer", required: false)

            © 2021 - EmployeeBook - Privacy

and use it also in employee list
@page
@model EmployeeBook.Pages.Employees.EmployeesModel
@{
    ViewData["Title"] = "Employees";
}

Employees razor page

<form method="get">

            @*asp-for two ways data binding*@
            <input type="search" class="form-control" asp-for="SearchTerm" />

                <button class="btn btn-default">Search</button>

</form>

@foreach (var employee in Model.Employees)
{
    <partial name="_Summary" model="employee" />
}

@*Remember about nullable values added to onGet/onPost if we want to use this method there*@

    Add nefw Employee

@section footer {

    @Model.Message

}

Result of that is something like that:

Im trying to use _summary partial view to display details of employees instead of common list. Could someone tell me where the problem can be? I use just classes from bootstrap. It start to works not correct when I add more employees.
@using EmployeeBook.Core
@*from lower case define just type of object into view*@
@*from upper case this is model property where we can go into*@
@model Employee

@Model.Name

        Type of employee @Model.TypeOfEmployee

            Details

            Edit

            Delete


text:
Q: take (something) off Can someone please guide me if it should be  'take your email off' or 'take you off'
I've also requested John to take your email off the notifications we receive from the HR team.
OR
I've also requested John to take you off the notifications we receive from the HR team.
Thanks

A: For this context, I'd suggest "Remove" or "Unsubscribe"

I've requested that John remove your/his/her email address from the HR Team notifications emails

or

I've requested that John unsubscribe you/his/her email address from the HR team notification mailing list


text:
Q: How to get the order id that the customer canceled with the hook I have another API inside plugin for making another order in a website so I want when the customer cancel the woocommerce order I've to canel also the other website order, I'll have the order id of woocommerce and the order id of the other website in wp_post_meta
I just want to know how to get the order id that customer canceled to call the order id and the other one to cancel both
function cancel_SP_order(){

// how to get the order id cancelation with the hook
get_post_meta() ..... // for example

// I get $order_id from wp_post_meta which has the other order id

// I cancel the other

}
add_action('woocommerce_cancelled_order','cancel_SP_order');

if there's a better way for sure I welcome

A: Luckily for you, the hook itself passes the $order_id.You can access it like this:
function cancel_SP_order( $order_id ){

// I get $order_id passed by the hook to use directly.

// I cancel the other

}
add_action('woocommerce_cancelled_order','cancel_SP_order', 10, 1);

The first parameter after your function name ('10') is the priority in which your function will run. The second one, '1', is the number of parameters passed from the hook to the function. In this case it is just '1', the order ID that you need.
Let me know if you need more help?


text:
Q: No se puede modificar información de la cabecera - Las cabeceras han sido enviadas por actualmente tengo un problema al desarrollar una página en wordpress, y esto me tiene trabado a seguir con el resto de la página. En el error log del hosting, me muestra lo siguiente:

PHP Warning:  Cannot modify header information - headers already sent by (output started at /home/teleredi/public_html/wp-includes/media-template.php:165) in /home/teleredi/public_html/wp-includes/option.php on line 824, referer: http://telered.ec/wp-admin/nav-menus.php?action=locations
PHP Warning:  Cannot modify header information - headers already sent by (output started at /home/teleredi/public_html/wp-includes/media-template.php:165) in /home/teleredi/public_html/wp-includes/option.php on line 823, referer: http://telered.ec/wp-admin/nav-menus.php?action=locations

Entonces, revisé la página php "media-template.php" en la línea que me menciona(165) y dice lo siguiente:
<div class="<?php echo $class; ?>">

Esto es parte de un script que lo pongo abajo:

Alguna idea del problema? Revisando ese código, es posible que esté bien realizado el tag div class y dentro un llamado php?

A: Las cookies son enviadas como encabezados HTTP. Por lo tanto, tienen que enviarse antes de imprimir cualquier caracter del cuerpo del HTML.
En tu caso, dentro del archivo /home/teleredi/public_html/wp-includes/option.php, se están seteando cookies luego de imprimir parte del cuerpo del HTML:
setcookie( 'wp-settings-' . $user_id, $settings, time() + YEAR_IN_SECONDS, SITECOOKIEPATH, null, $secure );
setcookie( 'wp-settings-time-' . $user_id, time(), time() + YEAR_IN_SECONDS, SITECOOKIEPATH, null, $secure );

Por lo tanto, deberías incluir a wp-includes/option.php antes de imprimir cualquier etiqueta del HTML (al principio del PHP). Y también hay que estar atento a que no haya espacios o saltos de línea antes de abrir la etiqueta <?php.
Este error, sin embargo, lo está generando el template wp-includes/media-template.php, por lo que deberías editarlo o contactar al autor del mismo.

A: El problema a ese conflicto es que existe un espacio en blanco antes de la etiqueta <?php la solución a ello es dejarlo sin espacio.


text:
Q: Should be the baseline included in MMRM? MMRM vs. cLDA In the cLDA (constrained longitudinal analysis) analysis the baseline value is already taken as a response, so it doesn't have to be included on the right side of the model.
But in MMRM ANCOVA (mixed-model for repeated measures; not a mixed model - it's just generalized least square) it's common to adjust the values (either raw or change from baseline) for the baseline on the right side. But should be then the baseline included in the response variable? If not, then how otherwise calculate contrasts vs. baseline (without doing it via modelling change)?

A: Typically you have change from baseline in the response variable, and you can still have baseline as a covariate in the MMRM.
Does that help?


text:
Q: Low performance on TaskCanceledException I need to run many (10-100k) convertation operations in parallel. In this case I use tasks, SymaphoreSlim to control degree of parallelism and CancellationTokenSource to prevent not running tasks to run when exception is thrown.
I'm trying to do something like this:
        var tasks = table.Body.Select(async row =>
        {
            await _semaphore.WaitAsync(_cts.Token).ConfigureAwait(false);
            try
            {
                await Convert(row, preparedData, table, mapper).ConfigureAwait(false);
            }
            catch (Exception)
            {

                _cts.Cancel();
                throw;
            }
        });

        await Task.WhenAll(tasks).ConfigureAwait(false);

But performance is awful. If I get rid of using tokens it takes just a few seconds.
        var tasks = table.Body.Select(async row =>
        {
            if (_canceled)
                return;

            await _semaphore.WaitAsync().ConfigureAwait(false);
            try
            {
                await Convert(row, preparedData, table, mapper).ConfigureAwait(false);
            }
            catch (Exception)
            {
                _canceled = true;
                throw;
            }
        });

        await Task.WhenAll(tasks).ConfigureAwait(false);

Is there a way to use CancellationTokens with a regular performance?

A: When your code does _semaphore.WaitAsync(_cts.Token), the semaphore has to set up a cancelable wait; this means it has to register with the cancellation token and when it is signaled, remove the wait from the wait queue. So yes, I would expect performance issues with 100k registrations.
If you don't need to cancel the wait, I wouldn't.
await _semaphore.WaitAsync().ConfigureAwait(false);
_cts.Token.ThrowIfCancellationRequested();


text:
Q: How to print each line of a script as it is run only for the top-level script being run? python's trace module will allow you to run a script printing each line of code as it is run in both the script and all imported modules like so:
 python -m trace -trace myscript.py

Is there a way to do the same thing, but only print the top-level calls, i.e. only print the lines in myscript.py as they are run?
I am trying to debug an abort trap failure and I can't figure out where it's dying.  Unfortunately, using the full --trace takes forever - the script normally takes 2-3 minutes to run, and the full trace has been going for hours.

A: Maybe lptrace can be useful for you.

A: The current accepted answer is good enough if only one file is being used to run all the code but when a whole project of files is being used is insufficient. One way to trace multiple files would be done listing all the files by hand in the following manner:
python -m trace --trace src/main.py | grep "main.py\|file2.py"

For small projects this may suffice but for big projects with a lot of files this may become annoying to list all the necessary file names and can be prone to error. In this manner, ideally you would need to construct a regex for your file names and using find list all the needed files for you to monitor.
Following this idea, I constructed a regex that matches all file names that do not start with a lower dash (to avoid matching on __init__.py files), do not contain any upper case letters in their name nor folder name and have the .py extension. To list all this files in an src folder the match those criteria the command is:
find src/ -type f -regextype sed -regex '\([a-z_]\+/\)\+[a-z][a-z_]\+.py'

Now for using those files in grep we just need to print them with a backward slash and a pipe between them. To print the names in that structure use the following command:
find src/ -type f -regextype sed -regex '\([a-z_]\+/\)\+[a-z][a-z_]\+.py' -printf '%f\\\\|' | awk '{ print substr ($0, 1, length($0)-3)}'

Lastly, we construct the command to match all files with the tracing:
python -m trace --trace src/main.py | grep "`find src/ -type f -regextype sed -regex '\([a-z_]\+/\)\+[a-z][a-z_]\+.py' -printf '%f\\\\|' | awk '{ print substr ($0, 1, length($0)-3)}'`"

This can be used to match filenames in specific folders of the project and the regex can be modified to include other important details that you might have with the names of the files you want to monitor.

A: I stumbled into this problem and found grep to be a quick and dirty solution:
python -m trace --trace my_script.py | grep my_script.py

My script runs in finite time though. This probably won't work well for more complex scripts.

A: It's not exactly what you want, but you may consider using py.test with "-s" which will prevent py.test from capturing the output of your print statment... So you can put some print statment here and there for each function you have in your script and create a dummy test which just execute your script as usual... You may then see where it failed.

A: If you don't get a traceback, you can use the technique called bisection.
Edit your main function or script body and put an exit(1) call aproximately in the middle. This is the first bisection.
Execute your script. If it reaches your exit, you know the fault is in the second half. If not, it's in the first half.
Move the exit to half of the first half, or half of the second half and try again.
With each cycle, you can narrow the location of the fault down by half of the remaining code.
If you've narrowed it down to one of your own functions, bisect that.

A: You may use decorator and decorate all the function of your module dynamically (no edit of each functions). You just need to paste these lines at the end of your script :
def dump_args(func):
    """This decorator dumps out the arguments passed to a function before calling it"""
    argnames = func.func_code.co_varnames[:func.func_code.co_argcount]
    fname = func.func_name
    def echo_func(*args,**kwargs):
        print fname, "(", ', '.join(
            '%s=%r' % entry
            for entry in zip(argnames,args[:len(argnames)])+[("args",list(args[len(argnames):]))]+[("kwargs",kwargs)]) +")"
    return echo_func

### Decorate all the above functions
import types
for k,v in globals().items():
    if isinstance(v, types.FunctionType):
        globals()[k] = dump_args(v)

Reference, code is coming from these two answers :
http://stackoverflow.com/questions/8951787/defining-python-decorators-for-a-complete-module
http://stackoverflow.com/questions/6200270/decorator-to-print-function-call-details-parameters-names-and-effective-values


text:
Q: what is the functionality of dt.jar file in Java? I want to know the functionality of dt.jar file in java which is located in jdk/lib folder. I have read oracle official documentation but can't understand their talk given below
"dt.jar, the DesignTime archive of BeanInfo files that tell interactive development environments (IDEs) how to display the Java components and how to let the developer customize them for an application."
Can anybody explain this to me?
Thanks in advance.

A: The dt.jar library is used by IDE applications to help design Swing GUI.
Hence, it is useful at design time , and is not to be included at runtime.
The jar contains BeanInfo classes for the Swing components, along with images representing the components.
From the Java Examples in a Nutshell, 3rd Edition book (Chapter 15.4 : Custom Events), by David Flanagan :

This BeanInfo class specifies a number of pieces of information for
  our bean:

*

*An icon that represents the bean.

*A BeanDescriptor object, which includes a reference to a Customizer    class for the bean. We'll see an implementation of this class later
  in the chapter.

*A list of the supported properties of the bean, along with a short    description of each one. Some beanbox tools (but not Sun's beanbox)
  display these strings to the user in some useful way.

*A method that returns the most commonly customized property of the    bean; this is called the "default" property.

*A reference to a PropertyEditor class for one of the properties.

This helps IDEs to provide useful graphical design tools using those bean components :

You may find more information here : Bean Customization


text:
Q: Unable to launch My first App on AVD I just installed Eclipse, Created AVD and able to launch it perfectly. I tried to launch my first app using  Run as -> 1 Android Application.  but there is no response either from Eclipse or AVD

A: I Accidentally used activity_main.xml instead of MainActivity.java and tried to run it. so, i didn't have any response. now problem solved.