text:
Q: Text selection action popup buggy Steps to reproduce:

*

*Open anything with selectable text, e.g. any question.

*Hold down on some regular (non-editable) question text to select it.

Expected behavior: text is selected and the action menu pops up above it (containing Copy/Define/etc. actions).
Actual behavior: text is selected, but the action menu does not pop up. The usual iOS behavior is that tapping on the selected text should also/again trigger the menu; it does not.

Actual necessary steps to open the menu: tap elsewhere to deselect the text, select again, menu works as expected now.

*

*App Version: 1.4.3.7

*Device: iPhone 5c (Global)

*OS Version: Version 9.2.1 (Build 13D15)

A: This will be fixed in 1.4.4.2, shipping in mid-February.
I used a variation of this fix and am actually astonished at how many apps exhibit this problem that I've never noticed before.
Fix is as follows:

*

*Create a UIWebView subclass that overrides canBecomeFirstResponder to always be true.

*Add a long press gesture recognizer to that view (or a parent view).

*Have that gesture recognizer simultaneously recognize with all other gesture recognizers.

*When recognized, if a child view isn't first responder, become first responder.  If you always try becoming first responder on long press, you will break reselection, so it needs a quick recursive check.
That this looks like in practice:
// Part 1 from https://stackoverflow.com/a/33077990/860000
@interface _SEHTMLWebView : UIWebView
@end

@implementation _SEHTMLWebView

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

@end

...
// Part 2 from https://stackoverflow.com/a/33077990/860000
- (void)addLongPressGestureRecognizer
{
    UIGestureRecognizer *longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGestureRecognizer:)];
    longPressGestureRecognizer.delegate = self;
    [self addGestureRecognizer:longPressGestureRecognizer];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

- (void)longPressGestureRecognizer:(UILongPressGestureRecognizer *)gestureRecognizer
{
    if (gestureRecognizer.state == UIGestureRecognizerStateRecognized) {
        if (![self.webView SE_findFirstResponderInSubviews]) {
            [self.webView becomeFirstResponder];
        }
    }
}


text:
Q: How to return value from function in color? I have this function:
add_filter( 'woocommerce_variation_is_active',
'grey_out_variations_when_is_backorder', 10, 2 );
function grey_out_variations_when_is_backorder( $grey_out, $variation ) {

if ( ! $variation->is_in_stock() && $variation->backorders_require_notification() )
    $grey_out = false;

return $grey_out; // Here want to return value in some color?

}

So want to know how to return value in some color? Function is for gray out the products that is not in Stock in WooCommerce shop. Currently only back gray out selection in some gray color. Some tip ,or advice how to get back value in color?
Current State:

I want to show like this:

A: If the frontend is disabling the grayed out select>option items (disabled="disabled"), then you can apply some CSS to those items:
select option:disabled {
    color: #F00;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get R data frames to keep and display unicode characters How can I include Greek letters in my data frames (and save them into Excel worksheets that way)? When I try, they are replaced with spaces (with data_frame from dplyr) or X (in data.frame).
d <- data_frame(` L` = 5, ` ` = 6)

names(d)
#[1] " L" " "

d <- data.frame(` L` = 5, ` ` = 6)

names(d)
#[1] "X.L" "X."

Sys.setlocale(locale="UTF-8")
#[1] ""
#Warning message:
#In Sys.setlocale(locale = "UTF-8") :
#  OS reports request to set locale to "UTF-8" cannot be honored

cat *-release
# CentOS release 6.3 (Final)

Sys.getlocale()
#[1] "LC_CTYPE=en_US.UTF-8;
#     LC_NUMERIC=C;
#     LC_TIME=en_US.UTF-8;
#     LC_COLLATE=en_US.UTF-8;
#     LC_MONETARY=en_US.UTF-8;
#     LC_MESSAGES=en_US.iso885915;
#     LC_PAPER=en_US.iso885915;
#     LC_NAME=en_US.iso885915;
#     LC_ADDRESS=en_US.iso885915;
#     LC_TELEPHONE=en_US.iso885915;
#     LC_MEASUREMENT=en_US.iso885915;
#     LC_IDENTIFICATION=en_US.iso885915"

Interestingly, I can't even get them to show up from the browser. The first space should be a greek small letter mu and the second should be a greek small letter beta.


text:
Q: Form drop down(spinner) & trying to change the value to the selected items value I am using a form spinner(essentially a form drop down in android terms.)
I want to be able to change the value to the selected spinner item instead of what it does now which is nothing.
How can I make it so that it does change value when selected?
Here is my jsfiddle with a working spinner but its not changing values on select yet
Here is the html code that makes the spinner:

          Set Repetition

Once

Daily

Weekly

Monthly

Custom

A: to update the text on click
$('.spinner-item').click(function (item){
    $('.toggle-spinner').text( $(this).text());
});


text:
Q: Prevent audio lags on heavy cpu load I'm creating an audio player with WPF and NAudio in C#.
Whenever the performance of my computer is low, the audio starts to lag extremely which sounds aweful. I noticed that this does not seem to be the case for similar applications like Spotify or Windows Media Player.
How can I increase the performance of the audio thread? Is there a way to give it priority before other threads?
Edit: Code
WavePlayer = new WaveOut();
source = new AudioFileReader(Filepath)
WavePlayer.Init(source);
WavePlayer.Play();

A: By default, in a WinForms / WPF app, WaveOut will use the UI thread to fill the audio buffers. If you use WaveOutEvent instead, you'll get a background thread doing that work for you. WasapiOut and DirectSoundOut also work this way.
Remember that if you can't fill buffers in a timely fashion you will get stuttering/drop outs in audio. So if switching driver model doesn't work for you, you might need to optimise your audio code, or increase the buffer durations.


text:
Q: C# remove last dynamically created textbox Almost totally noob here. Im stucked. I know how to delete all dc textboxes but have no idea how to delete only last created one. Thx
piece of my code:
int B = 1;
    public void NovIntRazd()
    {
        TextBox txt = new TextBox();
        this.Controls.Add(txt);
        txt.Top = B * 30;
        txt.Left = 26;
        txt.Height = 20;
        txt.Width = 65;
        txt.Name = "txtIntRazd" + this.B.ToString();
        B++;
    }

A: If you only need to ever remove one textbox, you can just keep the reference to the last one:
int B = 1;
TextBox txt;
public void NovIntRazd()
{
    txt = new TextBox();
    this.Controls.Add(txt);
    txt.Top = B * 30;
    txt.Left = 26;
    txt.Height = 20;
    txt.Width = 65;
    txt.Name = "txtIntRazd" + this.B.ToString();
    B++;
}

public void RemoveLast()
{
    if (txt == null) return;
    Controls.Remove(txt);
    txt = null;
}

Alternatively, a good practice is to put dynamically created controls in their own container, like a panel. It sounds like your case is a perfect use for a FlowLayoutPanel, which will handle control positioning too. When you remove any control, all the others are automatically moved around to the right places.
Then to remove the last added control, you can just do
if (pnl.Controls.Count > 0) pnl.Controls.RemoveAt(pnl.Controls.Count - 1);

If you really want to keep the controls mixed up in the top-level form, you can easily organize the dynamic textboxes by using a Stack:
Stack<TextBox> textboxes = new Stack<TextBox>();

public void NovIntRazd()
{
    var txt = new TextBox()
       {
         Top = (textboxes.Count + 1) * 30,
         Left = 26,
         Height = 20,
         Width = 65,
         Name = "txtIntRazd" + (textboxes.Count + 1).ToString()
       };

    this.Controls.Add(txt);
    textboxes.Push(txt);
}

public void RemoveLast()
{
    if (textboxes.Count == 0) return;
    Controls.Remove(textboxes.Pop());
}


text:
Q: Joining 2 statements to pull data from different tables I have this code:
<?php
$data = mysql_query("SELECT * FROM repin WHERE new_pin_id LIKE ".$pinDetails->id) or         die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
Print "".$info['from_pin_id'].",".$info['new_pin_id']."";
}
?>

Obtained thanks to this article: Check field for identical number
I'm trying to use the detail I pulled: ".$info['from_pin_id']." to get data from another table. I'm looking for the best way to do this.
I thought about making it a variable and then running a second statement within the same <?php?> which would look something like this:
Print "".$info['from_pin_id'].",".$info['new_pin_id']."";
}
$newdata = "".$info['from_pin_id']."";
// new statement here.
?>

But 1. it won't work and 2. it looks messy.
What is the best way to achieve it?
FYI, what I need to do is use ".$info['from_pin_id']." to match a field in another table where the data is the same ID, then pull more info based on the match.

A: Use the following query:
"SELECT *
FROM repin r
LEFT JOIN otherTable o
ON o.someColumn = r.from_pin_id
WHERE r.new_pin_id LIKE '".$pinDetails->id."'"

Also, the argument to LIKE must be a string; you need to put quotes around it.


text:
Q: LinearLayout is slow to move, if I load one image in ImageView I have a list, it captured moving finger, and you can delete an item by sliding your finger
if  the  image is not loaded  in my container, with ImageView.setImage(), the container moves correctly.
However, if I loaded one image the container moves slowler.
Why is this happening?
Attach images below.
1.moves correctly

*not moves correctly

always moves the container from left to rigth

Why is it?
Thanks.
UPDATE 19/01/2014
i reduced bitmap to 150 kb and continue equal.
leave my code
    objelementos.lnyDatosCliente.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, final MotionEvent event) {

         final  CCliente objcCCliente = lstLista.get(objelementos.posicion);
        CAnimaciones objAnmanim = new CAnimaciones();
        Display pantalla =  afrmGstionClientes.getActivity().getWindowManager().getDefaultDisplay();
        final int ancho = pantalla.getWidth();

        switch ( event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                fdYPrimeroPulsado = event.getRawY();
                fdXPulsadoInicio = event.getRawX();
                fdXUltimaPulsado = event.getRawX();
                iTamanioLnyPulsado =0;

            break;
            case MotionEvent.ACTION_MOVE:

                        float fdXPulsado = event.getRawX();
                        float fdXMovimiento = fdXPulsado- fdXUltimaPulsado;
                        objelementos.lnyDatosCliente.setVisibility(4);
                        objelementos.lnyDatosClienteToMove.setVisibility(0);
                        objelementos.lnyDatosClienteToMove.setX(fdXMovimiento);
                        iTamanioLnyPulsado =1;

                break;

            case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL:

                float fdXPulsad = event.getRawX();
                float xmov =fdXPulsad- fdXUltimaPulsado;
                fdYUltimoPulsado = event.getRawY();

                        int difx = (int)fdXPulsad- (int)fdXPulsadoInicio;

                        if (difx>120){
                            ObjectAnimator animaciion = objAnmanim.CrearAnimacion(objelementos.lnyDatosClienteToMove, xmov, ancho+10, "x", 85);//(xFin-20, ancho+10, 200) ;
                            animaciion.start();

                            new Handler().postDelayed(new Runnable() {
                                public void run() {
                                float num = objcCCliente.getposicionXInicio();

                               AlertDialog.Builder builder = new AlertDialog.Builder(
                                        getContext());
                                builder.setIcon(R.drawable.ic_launcher);
                                builder.setTitle("!AVISO!");
                                builder.setMessage("¿Estas seguro de eliminar el cliente?")
                                        .setPositiveButton("Si", new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int id) {
                                            CustomAdapterListadoClientes.this.lstLista.remove(objelementos.posicion);
                                            CustomAdapterListadoClientes.this.notifyDataSetChanged();
                                            dialog.dismiss();
                                          }
                                        })
                                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int id) {
                                            vol(ancho-10, objelementos.lnyDatosCliente.getX(), objelementos.lnyDatosClienteToMove, 180, objelementos.lnyDatosCliente);
                                            dialog.dismiss();
                                            }
                                        });
                                AlertDialog dialog = builder.create();
                                dialog.show();
                                }
                            }, animaciion.getDuration());

                        }else{

                            if (iTamanioLnyPulsado==0){
                                float dify = fdYPrimeroPulsado -fdYUltimoPulsado;
                                if (dify<0){
                                    dify*=-1;
                                }

                                if (dify<10){
                                float fddondeesta = objelementos.lnyDatosCliente.getY();
                                ObjectAnimator animaciion = objAnmanim.CrearAnimacion(objelementos.lnyDatosCliente, fddondeesta-1, fddondeesta, "x",50);

                                animaciion.start();
                                Cnavegar objNavegar = new Cnavegar();
                                AfrmHigthModificationCliente afrmModificacion = new AfrmHigthModificationCliente(true, objcCCliente,afrmGstionClientes);
                                objNavegar.RemplazarFragmento(R.id.rtlAltas, afrmModificacion, "AfrmHigthModificationCliente", afrmGstionClientes.getActivity().getSupportFragmentManager());
                                }
                            }else{

                                 if (difx>0){
                                     vol(xmov, objelementos.lnyDatosCliente.getX(), objelementos.lnyDatosClienteToMove, 180, objelementos.lnyDatosCliente);
                                 }else{
                                     vol(xmov, objelementos.lnyDatosCliente.getX(), objelementos.lnyDatosClienteToMove, 180, objelementos.lnyDatosCliente);
                                 }

                            }

                        }

                break;
            }

                return true;
        }
    });

A: Are you using ViewHolder pattern?
Are you loading your images on another thread?
For load images I use Picasso library.

A: solve my problem of slow , which resided not in the size of the image
I used two linear layout changing your visibility associated with this adapter to change it to visible or invisiblo gone.
he adapter had to rewrite the  code again and has this was because my problem.
now only work with linerar layout unchanged visibility, position and only my application I run to perfection
thanks for your help everyone


text:
Q: How do i make update function run every frame after I use OnTriggerEnter2D function in Unity? So i am designing a game where once the object collides with the powerup it should wait for 10 seconds and go back to normal. I am using update function to keep count but once OnTriggerEnter function is used the update function stops running every frame. How do i counter it. Please help
   public class Powerup_1act : MonoBehaviour {
    //This powerup temporarily passes through all lasers

    public GameObject EffectiveTo;
    private float TimeRemaining;
    int flag=0;
    float timer=0.0f;
    public float alphalevel=.20f;
    public GameObject laserfield;
    float flag2=0f;
    float countdown=0;
    void OnTriggerEnter2D(Collider2D other)
    {
        //Check the provided Collider2D parameter other to see if it is tagged "PickUp", if it is...
        if (other.gameObject.CompareTag("Player"))
        {
            gameObject.SetActive(false);
            laserfield.gameObject.tag = "Temp";
            flag2 = 1;
            changealpha ();
            Debug.Log ("Active?"+gameObject.activeInHierarchy);
            StartCoroutine(Powerup());
        }
    }
    private IEnumerator Powerup()
    {
        countdown = 10f;
        while (countdown >= 0) {
            Debug.Log (timer);
            timer += Time.deltaTime;
            if (flag2 == 1) {
//changes the alpha level between 0.2f and 0
                if (alphalevel > 0 && flag == 0) {
                    alphalevel -= .05f;
                    changealpha ();
                } else if ((alphalevel == 0 || flag == 1) && alphalevel < .20) {
                    alphalevel += .05f;
                    changealpha ();
                    Debug.Log (alphalevel);
                    flag = 1;
                } else if (alphalevel == .20) {
                    flag = 0;
                }
                countdown-=Time.smoothDeltaTime;
                yield return null;
            }
        }
            alphalevel = 1f;
            changealpha ();
            laserfield.gameObject.tag = "Laser";
            flag2 = 0;
     }
    //heres a function to change transparency of player when a powerup is in effect
        void changealpha()
        {
            EffectiveTo.GetComponent<SpriteRenderer> ().color = new Color (1f, 1f, 1f, alphalevel);
        }

    }

A: Use Coroutine's for your advantage:
void OnTriggerEnter2D(Collider2D other)
{
     StartCoroutine(PowerUp());
}

private IEnumerator PowerUp()
{
    countDown = 10f;
    while (countDown >= 0)
    {
        // Logic during the 10 seconds

        countDown -= Time.smoothDeltaTime;
        yield return null;
    }
}

A: What is happening is that when you disable the gameobject, the script that this gameobject has stop working too.
In your case when the OnTriggerEnter2D is fired you're setting you gameobject to false gameObject.SetActive(false); which means that this script will stop working because you've also placed this script on the gameobject you've just disabled.
You should move the OnTriggerEnter2D event on the other object that dosen't get disabled and you can disable this gameobject from there. What you do in Update would also be moved to that other gameobject.
From Unity documentation:

Making a GameObject inactive will disable every component, turning off any attached renderers, colliders, rigidbodies, scripts, etc... Any scripts that you have attached to the GameObject will no longer have Update() called, for example.


text:
Q: Tool to generate step by step box diagrams for Lisp Is there a tool that takes a short Lisp code snippet and then generate a series of box diagrams to represent state for each step of the code?
I am thinking of something like this: Online Python Tutor.
Something like this can be good for answering newbie Lisp questions. A lot of newbie questions are based on confusion on one or more of the following:

*

*implications of pass by sharing

*shared structure

*destructive functions
all of which can be demonstrated easily and visually by invoking such a tool. I wouldn't have to draw a box diagram to help a fellow newbie, I could just generate the diagrams by feeding the newbie's code or my example code into that tool. I wouldn't have to hope that the newbie would know words like reference, same object, different object, object identity, fresh cons, because the diagrams would tell the whole story, even help explain what those words mean.


text:
Q: How to load a random file from a directory I am trying to create a question bank on GitHub Pages.
I load a specific file using:
$(document).ready(function() {

    var theQuestion = "./questionsBank/"+"question-4"+".html"; //path to load
    $("#question").load(theQuestion);  //loading the question

  });

Now, there are many files in the questionsBank directory and I would like to have a script picking and loading a random one, but I don't know how to do in JS.

*

*How do you retrieve all filenames in questionsBank directory?

I would like to do something like below but don't know how to read filenames in a directory into an array:
var questionFolder = './some directory';
var questionFiles = [];
questionFiles = readingFilesandPopulatingIntoArray(questionFolder); \\how to do this?
var folderSize = questionFiles.length ;
randomNumber = Math.floor(Math.random() * folderSize);
randomQuestion = questionFiles[randomNumber];
$("#question").load(randomQuestion);

A: As commented by @Lawrence Cherone, the only way of getting the contents of a remote directory is by having an index of it.
Of course Apache has it's own directory scanner, which if configured ok, can render an HTML page with its contents. Then you could fetch that index and loop over the file links in it.
But GitHub Pages does not generates such indexes, so you need to generate it by your own. To do so, you need to do it during the build/deploy process of your page (which we don't know). There, you can add a NodeJS script (or whatever other language you prefer to use, like a plain bash script) using, for example, node's fs dir.read() to get the files list in ./questionsBank/ directory and generating a file to save it somehow (for example, a JSON file containing an Array).
Finally, you can include it directly in your code during the build process by importing it somewhere, or fetching it as you'd fetch any other URL containing a JSON (or whatever other format you decided to use).


text:
Q: How to stop Hosted Blazor WASM from navigating to api I have designed my blazor wasm application and its hosted in blazor server app, therefore both applications share the same base url. When i launch my server app, it successfully launchers the wasm app. My problem is that when i hit the refresh button on the web browser , the api/server app loads in the browser instead of refreshing the blazor web assembly. How can i stop this?
This is my Server Startup class
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddRazorPages();
        services.AddControllersWithViews();

        services.AddEndpointsApiExplorer();
        services.AddSwaggerGen();

        services.ConfigureCors();
        services.ConfigureIISIntegration();
        services.ConfigureLoggerService();
        services.ConfigureMySqlContext(Configuration);
        services.ConfigureRepositoryWrapper();
        services.AddAutoMapper(typeof(Startup));
        services.AddControllers();
        services.AddRouting(options => options.LowercaseUrls = true);

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            //app.UseSwagger();
            //app.UseSwaggerUI();
            app.UseWebAssemblyDebugging();

        }
        else
        {
            app.UseHsts();
        }

        app.UseBlazorFrameworkFiles();
        app.UseStaticFiles();
        app.UseHttpsRedirection();

        //app.UseCors("CorsPolicy");

        app.UseForwardedHeaders(new ForwardedHeadersOptions
        {
            ForwardedHeaders = ForwardedHeaders.All
        });

       app.UseRouting();

        app.UseAuthorization();
        app.UseMiddleware<ApiKeyMiddleware>();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
            endpoints.MapControllers();
            endpoints.MapFallbackToFile("index.html");

        });
    }
}

My WASM Program.cs file
public class Program
{
    public static async Task Main(string[] args)
    {
        var builder = WebAssemblyHostBuilder.CreateDefault(args);
        builder.RootComponents.Add<App>("#app");

        builder.Services.AddScoped(sp => new HttpClient(new AddHeadersDelegatingHandler())
        {
            BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
        });

        builder.Services.AddAntDesign();
        builder.Services.Configure<ProSettings>(builder.Configuration.GetSection("ProSettings"));
        builder.Services.AddScoped<IChartService, ChartService>();
        builder.Services.AddScoped<IProjectService, ProjectService>();
        builder.Services.AddScoped<IUserService, UserService>();
        builder.Services.AddScoped<IAccountService, AccountService>();
        builder.Services.AddScoped<IProfileService, ProfileService>();

        await builder.Build().RunAsync();

    }
}


text:
Q: Aligning label for multiple select in center of select box this is my html page

In the above picture, I want label client to be in center of select box. How can I do this?

A: http://fiddle.jshell.net/n6dNR/2/
label,select {
 display: inline-block;
 vertical-align: middle;
}


text:
Q: Text Overlay on Images in a Grid Upon Mouse Hover I've been trying to get a grid set up correctly but can't quite figure out how to do so. I'd like to get it into a 2x2 with a text overlay and change of opacity over each image when the mouse hovers over the image. I'm using the skeleton CSS framework.
JSFiddle(for my CSS scroll down to the bottom): https://jsfiddle.net/w758bg0s/1/
Here is the code I have written:
HTML:

This season's specials:

Southwest "Panzanella," Pickled Nopales, Jicama, Corn Tortilla

CSS:
/* Specials
–––––––––––––––––––––––––––––––––––––––––––––––––– */
#specials{
  background-image: url(http://i.lmnd3.com/images/LemonadeBkg_Avoc.jpg);
  text-align: center;
  min-height: 800px;
}
#specials h2{
  margin-top: 10rem;
  color: #FFFFFF;
  text-shadow: 0px 1px 0px rgba(0, 0, 0, 0.25);
  text-transform: uppercase;
}
#specials .food-image{

  margin-top: 2rem;
  max-width: 500px;
  max-height: 250px;

}
#specials img{
  height: 100%;
  width: 100%;
}
#specials .img-descrip{

  color: #fff;
  text-align: center;
}

Any help or suggestions would be greatly appreciated!
All the best -

A: Try
#specials .img-descrip {
    color: #000;
    margin-top: -5em;
    position: relative;
    text-align: center;
}

#specials img {
    height: 100%;
    opacity: 0.5;
    width: 100%;
}

#specials .food-image:hover img{
   opacity:1;
}


text:
Q: Install PECL Oauth MAMP OSX 10.8 I am trying to install the PECL Oauth extension on OSX 10.8 with MAMP version 2.1.3. This version of MAMP has PHP 5.4.10 and 5.2.17 with it, I have already added the stuff to the include folder of 5.2.17 and run the ./configure. Although when I go to run
cd /Applications/MAMP/bin/php/php5.2.17/bin; ./pecl install oauth

I get
downloading oauth-1.2.3.tgz ...
Could not download from "http://pecl.php.net/get/oauth-1.2.3.tgz", cannot download "pecl/oauth" (could not open /tmp/pear/install/oauth-1.2.3.tgz for writing)
Error: cannot download "pecl/oauth"
Download failed
install failed

Now I am not 100% sure that MAMP is using the 5.2.17 version of PHP, I have changed it in the apache httpd.conf file and when I look at the phpinfo page in MAMP it shows up as using version 5.2.17 so I do not think this is the issue.


text:
Q: SSIS: addrows stops after adding one row out of many I'm trying to process an xml file I'm getting from a vendor.  I managed to get some c# code to read in all 26 items in the xml.  This code I placed into a script component in SSIS and fed that into a Union All task.  I then placed a dataviewer so I can verify what I received.  I use this code to add the rows to the output buffer:
            Roles roles = GetWebServiceResult(wUrl);
        MessageBox.Show("We have read in " + roles.Items.Length + " items");

        //Add each role entry to the output buffer.
        for (int i = 0; i < roles.Items.Length; i++)
        {
            MessageBox.Show("Adding item " + (i + 1) + " to the output");
            Transfer role = getRole(roles.Items[i]);
            Output0Buffer.AddRow();
            Output0Buffer.roleKey = role.roleKey;
            Output0Buffer.text = role.text;
            Output0Buffer.Item = role.Item;
            Output0Buffer.Users = role.Users;
        }

When I run this I get a popup saying that there are 26 items to process, but I only get one more popup after that, telling me that item #1 has been added.  the job then stops with no errors, but I only have one row of output in the dataviewer.  I don't understand why this is happening when I know that there are 25 more items to add.
Additional: On a whim, I took out the Output0Buffer code and it went through all 26 items.

A: I figured it out.  I ran it using Ctrl-F5 and studied the output in the console.  Turns out a column wasn't big enough.  I made that column larger and everything works.  I would have thought that error would have stopped the processing.


text:
Q: Azure RoR capistrano all the instructions Azure: goo.gl/fGNhrp
during the deployment phase received an error:
C:\Users\Maksym\Project\blog_app>bundle exec cap production setup
DL is deprecated, please use Fiddle
DL is deprecated, please use Fiddle
DEBUG [39ea3015] Running /usr/bin/env [ -d ~/.rbenv/versions/2.0.0-p451 ] as joo
j@j00j.cloudapp.net
DEBUG [39ea3015] Command: [ -d ~/.rbenv/versions/2.0.0-p451 ]
(Backtrace restricted to imported tasks)
cap aborted!
SSHKit::Runner::ExecuteError: Exception while executing as jooj@jooj.cloudapp.net: Authentication failed for user jooj@jooj.cloudapp.net

Net::SSH::AuthenticationFailed: Authentication failed for user jooj@jooj.cloudapp.net

Tasks: TOP => rbenv:validate
(See full trace by running task with --trace)


text:
Q: DeprecationWarning in scikit-learn while using pos_label I am getting the following warning when I run my code
DeprecationWarning: From version 0.18, binary input will not be handled
specially when using averaged precision/recall/F-score. Please use
average='binary' to report only the positive class performance.
'positive class performance.', DeprecationWarning

Here's my code
splits = StratifiedShuffleSplit(labels, n_iter = 5, test_size = 0.2)
if(condition):
    scorefunc = make_scorer(fbeta_score, beta = 1, pos_label = labels[0])
else:
    scorefunc = make_scorer(fbeta_score, beta = 1, pos_label = None)

params1 = {'penalty':['l1'],'C':[0.0001, 0.001, 0.01, 0.1, 1.0]}
lr = GridSearchCV(LogisticRegression(), param_grid = params1, cv = splits, n_jobs = 5, scoring = scorefunc)
lr.fit(matrix, labels)

I am suspecting that this has something to do with how I am handling the pos_label parameter, but reading the documentation I could not figure out what it is that I am doing wrong. Any thoughts on this?


text:
Q: Execute task after reaching threshold for maximumRedeliveries in Camel I have implemented a retry functionality in my code using camel retry. It will  retry a maximum of five times.
onException(Exception.class)
    .maximumRedeliveries(5)
    .retryAttemptedLogLevel(LoggingLevel.WARN)
    .backOffMultiplier(5)
    .maximumRedeliveryDelay(5)
    .useExponentialBackOff();

Now I want to call a custom method if the threshold has been reached instead of throwing an exception. How can I achieve this?

A: This is exact use-case for Dead Letter Channel EIP pattern. I would suggest converting your onException block to errorHandler and use deadLetterChannel builder.
errorHandler(
        deadLetterChannel("direct:redeliveryExhausted")
                .maximumRedeliveries(5)
                .retryAttemptedLogLevel(LoggingLevel.WARN)
                .backOffMultiplier(5)
                .maximumRedeliveryDelay(5)
                .useExponentialBackOff()
);

from("direct:redeliveryExhausted")
        .log("I am going to handle non-deliverable message")
        .log("Because of this exception: ${exception}")
        .to("log:failed");

A: You can set the handled-flagto true and then call your custom bean.
onException(Exception.class)
    .maximumRedeliveries(5)
    .retryAttemptedLogLevel(LoggingLevel.WARN)
    .backOffMultiplier(5)
    .maximumRedeliveryDelay(5)
    .useExponentialBackOff()
    .handled(true)
    .to("bean:myCustomBean");


text:
Q: How to change entity class in form type? I have tree almost identical entity classes: A, B, C (they all extends one superclass via Doctrine class table inheritance).
And i have a form that allows to choose proper entity class via ChoiceType. In fact i need possibility to change entity class via form on entity creation (when its not persisted)
I cant figure out how to create controller action that will hande:

*

*creation of new A/B/C entity

*changing the entity class (when i change class field - form will submit)

*persisting the entity

Update
I updated description and found solution (see lower)

A: I think you can easily use a DataTransformer to do that.
see http://symfony.com/doc/current/form/data_transformers.html for how to doc it.
You can use the choice content to choose which class you need to create.

A: Mulitple ways to go. Because I have little information here are some options:
On form level:
Add a Form-Type for all of your entities. Add an option to configure the data_class for the ChoiceType:
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setRequired(['entity_class']);
}

Now use it when generating the form field:
$form->add(
    'entity',
    ChoiceType.class,
    ['data_class' => $options['entity_class']]
)

On database level:
Checkout how Doctrine handles Single Map Inheritance. It gives you the ability to create a BaseEntity and extend entities A,B and C from it. Now you can simply add a ChoiceType (or EntityType for that matter) and select the BaseEntity as the entity.
The form will then show all entities within one field.

A: So, solution looks like that. Maybe someone will find it useful
MySuperClassType.php
protected function getAvailableEntityTypes()
{
    $availableTypes = array();

    // here i get all subclasses of MySuperClass to fill em in choice form

    foreach ($this->em->getMetadataFactory()->getAllMetadata() as $classMetadata) {
        if (is_subclass_of($classMetadata->getName(), MySuperClass::class)) {
            $availableTypes[$classMetadata->getName()] = EntityLabelBuilder::getEntityLabelTranslationKey(
                $classMetadata->getName()
            );
        }
    }

    return $availableTypes;
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
    // here i add choice field with all available entity classes

    $builder
        ->add(
            'entityClass',
            ChoiceType::class,
            [
                'mapped' => false,
                'choices' => $this->getAvailableEntityTypes(),
            ]
        );

}

MySuperClassController.php
public function createAction()
{
    // initial entity creation
    $entity = new MySuperClass();

    // here i retrieve form data and recreate entity with class chosen in form
    $request = $this->get('request');
    if (in_array($request->getMethod(), array('POST', 'PUT'))) {
        $form = clone $this->get('my_app.my_super_class.form');
        $form->submit($request);
        $entityClass = $form['entityClass']->getData();

        $entity = new $entityClass();
    }

    // here i call form handler
    return $this->update($spend);
}


text:
Q: How to add minutes to a struct tm that contains UTC time? The set_time() function is supposed to take a particular time and add the specified number of minutes to this time and save it in *t.
#include <stdio.h>
#include <time.h>

enum {JAN, FEB, MAR, APR, MAY, JUNE, JULY, AUG, SEP, OCT, NOV, DEC};

void set_time(struct tm *t,
              int year, int mon, int day,
              int hour, int min, int sec,
              int mins_to_add)
{
    /* Copy all the values. */
    t->tm_year = (year - 1900);
    t->tm_mon = mon;
    t->tm_mday = day;
    t->tm_hour = hour;
    t->tm_min = min;
    t->tm_sec = sec;

    // No DST since we are storing UTC time.
    t->tm_isdst = 0;

    /* Add minutes to time. */
    t->tm_min += mins_to_add;
    mktime(t);

    /* Debug print */
    printf("%s\n", asctime(t));
}

int main(int argc, char **argv)
{
    struct tm t;
    set_time(&t, 2011, AUG, 1, 10, 00, 00, 0);
    return 0;
}

So, I ask set_time() to add nothing to Aug 01 10:00:00 2011. However, if my Windows system is set to EST time zone, the output I get is: Mon Aug 01 11:00:00 2011
The error happens because I do the task of adding the specified number of minutes (0 in the above example) to the specified time (Aug 01 10:00:00 2011 in the above example) with this part of the code:
    /* Add minutes to time. */
    t->tm_min += mins_to_add;
    mktime(t);

mktime() is called to adjust all other member variables of the structure in case t->tm_min exceeds 59 due to the addition. But mktime() treats the time in struct tm object as local time. So, when it sees that the date is Aug 01 2011 and local time zone as EST, it assumes that DST needs to be applied but it finds that t->tm_isdst is set to 0 (meaning DST isn't applied to the time in *t). So, it applies DST, adjusts the date from Aug 01 10:00:00 2011 to Aug 01 11:00:00 2011 and sets t->tm_isdst to 1.
Had I initialized t->tm_isdst to 1, this issue wouldn't have occurred because mktime() would have found that the time in *t already has DST applied to it. However, it would have messed up the result if I asked set_time() to add nothing to a date on which DST should not not applied, say Jan 01 10:00:00 2011. Now, it would try to turn off DST in *t thereby setting t->tm_isdst to 0 and re-adjusting the date to Jan 01 09:00:00 2011.
As a result, this has the undesirable effect of adding an extra hour to or subtracting an extra hour from the specified time when I wanted to add nothing to it. This happens because when mktime() finds that the DST setting in t->tm_isdst is not what it should be as per the local time-zone of the system, it tries to set it correctly by readjusting the time in *t.
What is the right way to solve this problem?

A: The documentation on struct tm says

The Daylight Saving Time flag (tm_isdst) is ... less than zero if the
  information is not available.

I suggest you set it to -1 and see if that fixes things.

A: The Windows function _mkgmtime can be used instead of mktime order to perform this conversion safely (regardless of the local time zone settings).


text:
Q: Java Exception Handling Specificity I think it's easier to explain my question if I show my code first, so here it is:
import java.util.Scanner;
public class a{
    public static void main(String[]args){
        Scanner s = new Scanner(System.in);
        System.out.print("Enter either a, b, or c: ");
        try{
            String a = s.nextLine();
            if (!a.equalsIgnoreCase("a")&&!a.equalsIgnoreCase("b")&&!a.equalsIgnoreCase("c")){
                throw new IllegalArgumentException();
            }
            System.out.print("Entered letter: "+a);
        }
        catch (IllegalArgumentException b){
            System.out.println("Invalid input. Only enter a, b, or c.");
        }
    }
}

My question is, is there a way to make three(3) different catch statements in order to specify in the error message that the user entered

*

*another letter other than a, b, or c;

*a non-letter character (number or symbol) OR

*a blank space?

The thing that crossed my mind for the number error was NumberF

A: Rather than creating three separate catch blocks you can modify your catch to :
try {
    String a = s.nextLine();
    if (!a.equalsIgnoreCase("a") && !a.equalsIgnoreCase("b") && !a.equalsIgnoreCase("c")) {
        throw new IllegalArgumentException(a);                 // observe this
    }
    System.out.print("Entered letter: " + a);
} catch (IllegalArgumentException ex) {
    String input = ex.getMessage();

    // check for spaces
    if (input.trim().length() == 0) {
        System.out.println("Only black spaces entered");
    }

    // check for numeric/special characters
    else if (input.matches("^[0-9!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>\\/?]*$")) {
        System.out.println("User entered a non-letter character (number or symbol)");
    }

    // check if it isn't a, b or c
    else if ((!input.trim().matches("a|b|c"))) {
        System.out.println("User entered value other than a, b or c");
    }
}

Observe here:

*

*We are including the input entered by the user while throwing the
exception

*In the catch block we are fetching the value entered by the user
and then based on some if conditions printing out the desired
exceptions.

You can tweak the conditions within the catch logic as per your convenience, I hope you get the idea behind it. Also, you can create a separate method for handling the exception and call it from the catch block.


text:
Q: tab separation problem I usually used this to create tab separated files for excel:
sb.AppendLine(String.Format(@"{0}\t{1}" ...

Strangely it does not work anymore. Any ideas?
C

A: surely no @ symbol sb.AppendLine(String.Format("{0}\t{1}"...
The @ symbol tells the compiler to interpret the string literally so it places 2 characters  a backslash and a t in string. If you don't use the @ symbol it tells the compiler to interpret the string so \t is changed into the escape character for TAB.


text:
Q: jQuery each() first iteration is wrong, the rest are correct So, I'm creating a piece of code so the images in my div are automatically centered and adjusted, so they fit in a squared box.
Currently, I've managed to do so, but, something is wrong with the first iteration, because I get the wrong result, let me show you the code.

// news section height calculator
    $(window).load(function () {
        $('.news-picture').find('img').each(function () {

            var screenImage = $(this);
            var theImage = new Image();
            theImage.src = screenImage.attr("src");

// Get accurate measurements from that.
            var imageWidth = theImage.width;
            var imageHeight = theImage.height;

            var $imgClass = (imageWidth / imageHeight);
            var $imgPos = -((imageWidth - $(window).width()) / 2);
            console.log(imageWidth);
            console.log($(window).width());

            if ($imgClass >= 1) {
                $(this).addClass('wide').css("left" , $imgPos);
            } else {
                $(this).addClass('tall');
            }
        });
    });

                        <a href="<?php echo wp_get_shortlink(); ?>"><?php the_post_thumbnail('large'); ?>

<a href="<?php echo wp_get_shortlink(); ?>"><?php the_title(); ?>

<time datetime="<?php the_time('l, F j, Y'); ?>"><?php the_time('l, F j, Y'); ?></time>

As you may notice, I'm working with Wordpress, and specifically with post images.
The case; The iteration runs 3 times, it is supposed to assign a class, and a left value, which will center the image.
But, the first iteration gets the height value of the second iteration, which in first place should be getting the width, of its own iteration. Weird huh.
I'll attach an image of what i'm trying to accomplish, maybe you have suggestions as to how to approach this dilemma.Structure

A: Thank you for paying attention, I actually fixed by adding two lines only, specifying the current and rendered width and height of the image.

// news section height calculator
    $(window).load(function () {
        $('.news-picture').find('img').each(function () {

            var screenImage = $(this);
            var theImage = new Image();
            theImage.src = screenImage.attr("src");
            theImage.width = screenImage.attr("width");
            theImage.height = screenImage.attr("height");

// Get accurate measurements from that.
            var imageWidth = theImage.width;
            var imageHeight = theImage.height;

            var $imgClass = (imageWidth / imageHeight);
            var $imgPos = -((imageWidth - $(window).width()) / 2);
            console.log(imageWidth);
            console.log($(window).width());

            if ($imgClass >= 1) {
                $(this).addClass('wide').css("left" , $imgPos);
            } else {
                $(this).addClass('tall');
            }
        });
    });
body {
  margin:0;
}
.news-content {
background-color: #fff;
    margin: 25px auto;
}

.news-picture {
    -webkit-filter: grayscale(100%);
    filter: grayscale(100%);
    position: relative;
    overflow: hidden;
    width: 100vw;
    height: 100vw;
    margin: 0 auto;
  }
.news-picture:after {
    -moz-box-shadow: 0 0 10em #000 inset;
    -webkit-box-shadow: 0 0 10em #000 inset;
    box-shadow: 0 0 10em #000 inset;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    content: "";
}
.news-picture a {
    border: 0;
    display: block;
}
.wide {
    height: 100vw;
    width: auto;
    max-width: initial;
    position: relative;
}
h1 {

}
.news-title {
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1;
    position: absolute;
    bottom: 0;
    width: 100%;
    }
    .news-title h1 {
    padding: 15px 10px 0 10px;
    margin: 0;
    text-align: center;
    line-height: 22px;
    font-size: 16px;
}
.news-title h1 a {
    color: #fff;
    margin: 0;
    text-decoration: none;
    font-family: "Oswald", sans-serif;
}
.datetime {
    font-family: "Titillium Web", sans-serif;
    font-size: 10px;
    padding: 5px;
    margin-bottom: 5px;
    text-align: center;
    text-transform: uppercase;
    letter-spacing: 2px;
    color: #fff;
}

First Iteration of the problem

<time datetime="Sunday, October 23, 2016">Sunday, October 23, 2016</time>

Second Iteration of the problem

<time datetime="Sunday, October 23, 2016">Sunday, October 23, 2016</time>

Third Iteration of the problem

<time datetime="Sunday, October 23, 2016">Sunday, October 23, 2016</time>


text:
Q: import photos option in app
Possible Duplicate:
How do I access photos from my iphone app?

I'm building an app that allows the user to import a photo currently on their phone. I noticed several other apps have this option (WhatsApp, Facebook come to mind). Is there an example how this is done?
I've searched for an API for this...and not finding it. I did however, find this:
https://github.com/andreyvit/SoloComponents-iOS
It allows to show the photos, but how do we get the photos currently on the phone?

A: You can find the full documentation here: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIImagePickerController_Class/UIImagePickerController/UIImagePickerController.html As a bonus, you can also take pictures with this class.

A: You can use the UIImagePickerController for doing this.
This is a simple tutorial which may help you. Also check this link for integrating the camera photos


text:
Q: Wix Bundle Upgrade Without Resupplying Password I have authored an MSI that requires an account and password to be supplied to install and start a Windows Service, so I've added a couple of properties to my 'Product' element for that. I have a requirement that these properties should not need to be resupplied to perform an upgrade and since one of those properties is a password I don't want to persist it's value to the registry (or anywhere). I have achieved this with
<MajorUpgrade ... Schedule="afterInstallExecute" />

Now I'm authoring an exe bootstrapper to bundle this MSI with it's prerequisite, similarly the exe will need to receive values for the properties and pass them to the MSI, so I've added some 'Variable' elements to my bundle and passed them to my 'MsiPackage' element with child 'MsiProperty' elements. And this works great during first install when the values are supplied, but now when I want to upgrade the bundle without supplying values for the properties the bootstrapper passes empty values to the MSI. Something equivalent to...
msiexec /i MyMsi.msi ACCOUNT= PASSWORD=

Which breaks the upgrade. The new version of the Windows Service is attempting to start with an empty value for account and password.
Is there a way to conditionally pass variable values to MSI's as property values?
What happens when both the 'Variable' element attributes 'Hidden' and 'Persisted' are set? Will the password really be hidden?
Is there another pattern I don't know about / haven't thought of?
Something like this doesn't feel like it should require a custom action.

A: On upgrades you can disable the <InstallServices> standard action.
In one of the products I work with I have the following:
<!-- http://stackoverflow.com/questions/15965539/how-to-only-stop-and-not-uninstall-windows-services-when-major-upgrade-in-wix don't change service config on upgrade -->
<DeleteServices>NOT UPGRADINGPRODUCTCODE</DeleteServices>
<InstallServices>NOT WIX_UPGRADE_DETECTED OR V6INSTALLED</InstallServices>

Because I didn't want to reset the start types of the services is the user has decided to start them manually instead of automatically (it's an option in our product to set this).
By doing this, it should leave the service already installed as is when upgrading  instead of trying to re-add it with empty parmeters for the login user/pass

An alternative is to make a salted hash of the password and store the user and salted&hashed password into the registry. On upgrades you can read these values decode the password and use those values.


text:
Q: Root privliges on UBUNTU 16.04 I am trying to upload files to my MP3 player from my UBUNTU 16.04 but it states the following error:
"You don't have the right permissions to extract archives in the folder "571A-A01E""
So I tried to find the right root privliges, so I typed in the terminal
"gksudo nautilus" to have root privliges but it seems I cannot write to this MP3 player from my machine.
I checked the properties of this MP3 player:
the owner has permissions to create and delete files on this player but the group doesn't have permissions to read and write, I tried to change it but I all the time get the following error:"
Sorry, could not change the permissions of "571A-A01E": Error setting permissions: Read-only file system".
I am getting nutsy, can anyone help with this?
Thanks!


text:
Q: Agile practices to avoid deprecated code? I am converting an open source Java library to C#, which has a number of methods and classes tagged as deprecated. This project is an opportunity to start with a clean slate, so I plan to remove them entirely. However, being new to working on larger projects, I am nervous that the situation will arise again. Since much of agile development revolves around making something work now and refactoring later if needed, it seems like deprecation of APIs must be a common problem. Are there preventative measures I can take to avoid/minimize API deprecation, even if I am not entirely sure of the future direction of a project?

A: As Matt says, the Obsolete attribute is your friend... but whenever you apply it, provide details of how to change calling code. That way you've got a lot better chance of people actually changing. You might also want to consider specifying which version you anticipate removing the method in (probably the next major release).
Of course, you should be diligent in making sure you don't call the obsolete code - particularly in sample code.

A:
Since much of agile development revolves around making something work now and refactoring later if needed

That's not agile. It's cowboy coding disguised under the label of agile.
The ideal is that whatever you complete, is complete, according to whatever Definition of Done you have. Usually the DoD states something along the lines of "feature impelmented, tested and related code refactored". Of course, if you are working on a throwaway prototype, you can have a more relaxed DoD.
API modifications are a difficult beast. If they are only project-internal APIs you are modifying, the best way to go is to refactor early. If you need to change the internal API, just go ahead and change all API clients at the same time. This way the refactoring debt does not grow very large and you don't have to use deprecation.
For published APIs you probably have some source and binary compatibility guarantees you have to maintain, at least until the next major release or so. Marking the old APIs deprecated works while maintaining compatibility. As with internal APIs, you should fix your internal code as soon as possible to not use the deprecated APIs.

A: I'm not sure there is much you can do. Requirements change, and if you absolutely have to make sure that clients of the API are not broken by newer API version, you'll have rely on simply deprecating code until you think that no-one is using the deprecated code.
Placing [Obsolete] attributes on code causes the compiler to create warnings if there are any references to the obsolete methods. This way clients of the API, if they are diligent about fixing their compiler warnings, can gradually move to the new methods without having everything break with the new version.
Its useful if you use the ObsoleteAttribute's override which takes a string:
[Obsolete("Foo is deprecated. Use Bar instead for munging widgets.")]

<frivolous>
Perhaps you could create a TimeBombAttribute:
[TimeBomb(new DateTime(2010,1,1), "Foo will blow up! Better use Bar, or else."]

In your code, reflect for methods with the timebomb attribute and throw KaboomException if they are called after the specified date. That'll make sure that after 1st January 2010 no-one is using the obsolete methods, and you can clean up your API nicely. :)
</frivolous>

A: Matt's answer is solid advice. I just wanted to mention that intially you probably want to use something along the lines of:
[Obsolete("Please use ... instead ", false)]

Once you have the code ported, change the false to true and the compiler will then treat all the calls to the method as an error.

A: Watch Josh Bloch's "How to Design a Good API and Why It Matters"
Most important w/r/t deprecation is knowing that "when in doubt, leave it out."  Watch the video for clarification, but it has to do with having to support what you provide forever.  If you are realistically expecting that API to be reused, you're effectively setting your decisions in stone.
I think API design is a much trickier thing to do in an Agile fashion because you're expecting it to be reused probably in many different ways.  You have to worry about breaking others that are dependent on you, and so while it can be done, it's tough to have the right design emerge without getting a quick turnaround from other teams.  Of course deprecation is going to help here, but I think YAGNI is a lot better design heuristic when it comes to APIs.

A: I think deprecation of code is an inevitable byproduct of Agile processes like continuous refactoring and incremental development.  So if you end up with deprecated code as you work on your project, that's not necessarily a bad thing--just a fact of life.  Of course, you will probably find that, rather than deprecating code, you end up keeping a lot of code but refactoring it into different methods, classes, and so on.
So, bottom line: I wouldn't worry about deprecating code during Agile development.  If it served its purpose for a while, you're doing the right thing.

A: The rule of thumb for API design is to focus on what it does, rather than how it does it. Once you know the end goal, figure out the absolute minimum input you need and use that. Avoid passing your own objects as parameters, pass only data.
Seperate configuration from execution. For exmaple, maybe you have an image encoder/decoder.
Instead of making a call like:
Encoder.Encode( bytes, width, height,  compression_type, compression_ratio, palette, etc etc);

Make it
Encoder.setCompressionType(compression_type);
Encoder.setCompressionType(compression_ratio);
etc,etc
Encoder.Encode(bytes, width, height);

That way adding or removing settings is much less likely to break existing implementations.

A: For deprecation, there's basically 3 types of APIs: internal, external, and public.
Internal is when its only your team working on the code.  Deprecating these APIs isn't a big deal.  Your team is the only one using it, so they aren't around long, there's pressure to change them, people aren't afraid to change them, and people know how to change them.
External is when its the same code base, but different teams are using it.  This might be some common libraries in a large company, or a popular open source library.  The point is, people can choose the version of code they compile with.  The ease of deprecating an API depends on the size of the organization and how well they communicate.  IMO, its the deprecator's job to update old code, rather than mark it deprecated and let warnings fly throughout the code base.  Why the deprecator instead of the deprecatee?  Because the depcarator is in the know; they know what changed and why.
Those two cases are pretty easy.  So long as there is backwards compatibility, you can generally do whatever you'd like, update the clients yourself, or convince the maintainers to do it.
Then there are public api's.  These are basically external API's that the clients don't have much control over, such as a web API.  These are incredibly hard to update or deprecate.  Most won't notice its broken, won't have someone to fix it, won't get notifications that its changing, and will only fix it once its broken (after they've yelled at you for breaking it, over course).
I've had to do the above a few times, and it is such a chore.  I think the best you can do is purposefully break it early, wait a bit, and then restore it.  You send out the usual warnings and deprecations first, of course, but - trust me - nothing will happen until something breaks.
An idea I've yet to try is to let people register simple apps that run small tests.  When you want to do an API update, you run the external tests and contact the affected people.

A: Another approach to be popular is to have clients depend on (web) services.  There are constructs out there that allow you to version your services and allow clients to perform lookups.  This adds a lot more moving parts and complexity into the equation, but can be helpful if you are looking at turning over a lot of versions, and having to support multiple versions in production.
This article does a good job of explaining the problem and an approach.


text:
Q: requireJS with JQuery, Masonry, & ImagesLoaded: Object [object Object] has no method 'imagesLoaded' RequireJS newbie here.  Trying to convert some JQuery code I had working fine in the old way to work w/ RequireJS.
Header of my page loads three JS files via script tags -- require.js itself, my require.cfg.js, and boot/main.js with the site-specific functionality.
Relevant require.cfg.js excerpt:
,paths: {
    'boot': 'src/boot'
    ,'jquery': 'lib/jquery.min'
    ,'jquery.masonry': 'lib/plugins/masonry.pkgd.min'
    ,'jquery.imagesloaded': 'lib/plugins/imagesloaded.pkgd.min'
}

,shim: {
    'jquery': {
        exports: 'jQuery'
    }
    ,'jquery.masonry': ['jquery']
    ,'jquery.imagesloaded': ['jquery']
}

boot/main.js:
require([
'jquery',
'jquery.masonry',
'jquery.imagesloaded',
], function($) {

    // The following code worked just fine when I included it in the header of the page as-is
$(function() {

    var $container = $('#container');
    // This doesn't work
    $container.imagesLoaded(function() {
                    // Neither does this
            $('#container').masonry({itemSelector : '.item',});
        });

});

});

I can confirm that all of these JS files are being found and loaded by the browser.  And I confirm that if I do:
require([
'jquery',
'jquery.masonry',
'jquery.imagesloaded',
], function($, Masonry, ImagesLoad) {

the Masonry and ImagesLoaded variables are set correctly.... but I don't want to proceed w/o jQuery
But when I try to call .imagesLoaded() and .masonry() on the JQuery container object, I get:
Uncaught TypeError: Object [object Object] has no method 'imagesLoaded'
And if I comment out the imagesLoaded line, I get:
Uncaught TypeError: Object [object Object] has no method 'masonry'
Not sure what I'm doing wrong here...?  From what I've read in other StackOverflow questions, the code looks correct to me...?
Thanks!
Update:
If I use this code the non-JQuery way like so, it works:
        var container = document.querySelector('#container');
        imagesLoaded(container, function() {
            var msnry = new Masonry( container, {
                itemSelector: '.item',
            });
        });

A: Try defining exports for each plugin in the shim too...
, paths: {
    boot: 'src/boot'
    , jquery: 'bower_components/jquery'
    , masonry: 'bower_components/masonry',
    , imagesloaded: 'bower_components/imagesloaded'
}
, shim: {
    jquery: {
        exports: 'jQuery'
    }
    , masonry: {
        deps : ['jquery'],
        exports : 'jQuery.masonry'
    }
    , imagesloaded: {
        deps : ['jquery'],
        exports : 'jQuery.imagesLoaded'
    }
}

A: Try this instead:
require([
'jquery',
'jquery.masonry',
'jquery.imagesloaded',
], function($, Masonry, ImagesLoad) {

    // The following code worked just fine when I included it in the header of the page as-is
$(function() {

    var $container = $('#container');
    // This doesn't work
    $container.imagesLoaded(function() {
                    // Neither does this
            $('#container').masonry({itemSelector : '.item',});
        });

});

});

A: Ok, I think I have the answer to your problem (and mine!).
If you're installing the versions hosted on github, you're probably installing the "vanilla" version, not the jquery plugin. That's what you'll be doing if you install via bower, for example, which is what I was doing.
Here's what I found with a search on bower:
% bower search masonry
# jquery-masonry git://github.com/desandro/masonry
# masonry git://github.com/desandro/masonry.git
# $.masonry git://github.com/tysoncadenhead/masonry
# angular-masonry git://github.com/passy/angular-masonry.git
# jquery.masonry git://github.com/tysoncadenhead/masonry.git

AFAICT, jquery-masonry, $.masonry and jquery.masonry are all pointing to the same source (in two different locations), and it's not the jquery plugin it's just the "vanilla" version of masonry.
Instead, just download from here and extract the file jquery.masonry.js, but it in your assets path, and add a shim for it with a dependency on jquery.
After you do all that, it should work. Of course since it's not installed through bower, you can't manage dependencies as you would with other bower packages. I honestly don't understand what's going on but it looks like a problem on the package-maintainer's side.
Hope that helps.
UPDATE: Although the above works, note that the version downloaded from meta.metafizzy.co is quite old and depends on an outdated version of jquery. I think I'm just going to go with the vanilla version, it seems that the plugin is not being maintained.

A: Try using jquery-bridget: https://github.com/desandro/jquery-bridget to convert masonry to a jquery plugin. I created a new js file that gets loaded by requirejs to ensure it is converted before the application starts running:
//masonry-config.js:
'use strict'

define(['jquery-bridget', 'masonry'], function(Bridget, Masonry){
    Bridget('masonry', Masonry );
});

Then in my requirejs file
//main.js
require.config({
   paths: {
       'masonry-config': 'masonry-config'
       .....
   },
   shim: {
       'angular-masonry': ['angular', 'masonry'],
       'angular' : {
         deps: ['imagesloaded', 'masonry-config'],
         exports: 'angular'
       },
       'masonry': ['imagesloaded'],
   }
}

This is for my app using angular and angular-masonry (with masonry) so you might need to config a little differently but hopefully that give you some idea.

A: In our particular case we had RequireJS included and configured in our main template, but wanted to include Masonry/ImagesLoaded on one particular page.
We kept our code in the template:
<script type="text/javascript" src="/path/to/require.min.js"></script>
<script type="text/javascript">
    require.config({
        waitSeconds: 0,
        paths: {
            'jquery': "/path/to/jquery.min",
            // ...
        },
        shim: {
            // ...
        }
    });
    require(["jquery", /* ... */], function ($) {
        // ...
    });
</script>

Then we included a JavaScript file after this, on the page that used Masonry, that triggered Masonry/ImagesLoaded:
requirejs(['jquery', 'https://unpkg.com/masonry-layout@4.2.2/dist/masonry.pkgd.min.js', 'https://unpkg.com/imagesloaded@4.1.4/imagesloaded.pkgd.min.js'],
    function ($, Masonry, ImagesLoaded) {
        $(document).ready(function () {
            ImagesLoaded('.js-masonry', function () {
                new Masonry('.js-masonry', {
                    // This was required for us, but from what I can tell shouldn't need to be/may need to be updated per-usage.
                    itemSelector: '.item'
                });
            });
        });
    }
);

I'm sure this could be further optimized, but it resolved the errors and didn't require any new packages to be included.


text:
Q: fedora can not boot - sendmail sm-client exim abandoned I am having an issue with booting fedora. it hangs with error message:

sendmail sm-client exim abandoned unknown malformed or incomplete option -L

how can i fix the issue ? is there any way to exclude sendmail from boot init ? but cant boot and login to fedora, no idea how to proceed.
thanks in advance for any help or direction.

A: I think the problem may actually be with exim.
You should boot into single user mode and then:
chkconfig sendmail off
chkconfig exim off

to stop sendmail/exim from starting via init.


text:
Q: jQuery fails on DOM element inserted by AJAX I have wrote a simple jQuery function on class named close.
$(function () {
    $(".close").click(function () {
        $(this).parent().fadeTo(400, 0, function () { // Links with the class "close" will close parent
            $(this).slideUp(400);
        });
        return false;
    });
});

Its working well but if I insert new DOM element using AJAX this function fails? Why it is so? Though I know solution that to write same function on page that is inserted through AJAX response. I did it and it's working. Why is it not working globally?
I tried to replace the $(".close").click(function () { with $(".close").on("click", function(event){ but it didn't gave me exact solution of my issue.

A: that is becuase for click event to work the element should be present in the document...use  on delegated event
$(document).on("click",".close",function () {
    $(this).parent().fadeTo(400, 0, function () { // Links with the class "close" will close parent
        $(this).slideUp(400);
    });
    return false;
});

adding you click event after ajax success function works but then I prefer to go with the on delegated event (since on in jquery was introduce for this purpose)..
I recommend you to use the closest static parent,  than the document itself for better performance...
link to read more about delgated on event

A: Because jQuery binded click event to elements when DOM was ready. It doesn't watch for new elements matching selectors so any elements added after will not have click event binded to your function. To do this, you must do $('.close').click(...) after AJAX request is finished.

A: Use on and fadeOut:
$("body").on('click', '.close', function() {
    $(this).parent().fadeOut();
    return false;
});

*

*Also, you do not need to slideUp after fading out, as the element is already hidden.

*Secondly, the default fade duration is already 400, you do not need to state the speed again.

A: Did you tried using 'live' method.
$(".close").live('click',function () {
    $(this).parent().fadeTo(400, 0, function () { // Links with the class "close" will close parent
        $(this).slideUp(400);
    });
    return false;
});


text:
Q: How do you set the BindingContext of a nested collection in Maui? I am not sure how to refer to another collection object for a BindingContext of a CollectionView inside another CollectionView in Maui/XAML. Take the following example:
XAML:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="NestedContextExample.MainPage"
         xmlns:model="clr-namespace:NestedContextExample"
         Title="{Binding Name}">
<ContentPage.BindingContext>
    <model:Form />
</ContentPage.BindingContext>
<ScrollView Padding="10">
    <CollectionView ItemsSource="{Binding FieldGroups}">
        <CollectionView.ItemTemplate>
            <DataTemplate>
                <StackLayout>
                    <Label Text="{Binding Name}" />
                    <!-- something like this -->
                    <CollectionView ItemsSource="{Binding Source={x:Reference Answers.Where(a => Fields.Contains(a.Field)}}">
                        <CollectionView.ItemTemplate>
                            <DataTemplate>
                                <VerticalStackLayout>
                                    <Label Text="{Binding Field.Name}" />
                                    <Label Text="{Binding Value}" />
                                </VerticalStackLayout>
                            </DataTemplate>
                        </CollectionView.ItemTemplate>
                    </CollectionView>
                </StackLayout>
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>
</ScrollView>

Code Behind:
namespace NestedContextExample;

public partial class MainPage : ContentPage
{
    public Form Form { get; set; }
    public List<Answer> Answers { get; set; }

    public MainPage()
    {
        InitializeComponent();
        Form = new Form
        {
            Name = "My Form",
            FieldGroups = new List<FieldGroup>
            {
                new FieldGroup
                {
                    Name = "Group A",
                    Fields = new List<Field> {
                        new Field
                        {
                            Name = "Field 1"
                        },
                        new Field
                        {
                            Name = "Field 2"
                        }
                    }
                },
                new FieldGroup
                {
                    Name = "Group B",
                    Fields = new List<Field> {
                        new Field
                        {
                            Name = "Field 3"
                        },
                        new Field
                        {
                            Name = "Field 4"
                        }
                    }
                }
            }
        };
        Answers = Form.FieldGroups.SelectMany(g => g.Fields).Select(f => new Answer
        {
            Field = f
        }).ToList();
        BindingContext = Form;
    }
}

public class Form
{
    public string Name { get; set; }
    public List<FieldGroup> FieldGroups { get; set; }
}

public class FieldGroup
{
    public string Name { get; set; }
    public List<Field> Fields { get; set; }
}

public class Field
{
    public string Name { get; set; }
}

public class Answer
{
    public Field Field { get; set; }
    public string Value { get; set; }
}

So, I want the nested collection to be bound to the subset of the list of Answer objects with fields within the current FieldGroup, rather than the Fields of the current FieldGroup. Note the ItemsSource="{Binding Source={x:Reference Answers.Where(a => Fields.Contains(a.Field)}}" - that obviously doesn't work, but that is what I am basically trying to achieve. How would I go about that?


text:
Q: How to make a SCNNode glow? I'm trying to make my SCNNode which is a sphere to glow like this picture of our planet:

I tried creating another node and applying a CIFilter with no luck:
let filter = CIFilter(name: "CIGaussianBlur")!
filter.setDefaults()
filter.setValue(1, forKey: kCIInputRadiusKey)
let atmosphere=SCNSphere(radius: 21)
atmosphere.firstMaterial?.diffuse.contents=UIColor.blueColor()
let atmosphereNode = SCNNode(geometry: atmosphere)
atmosphereNode.filters=[filter]

From what I could research this is due to Metal not supporting CIFilter but using OpenGL might work but I don't know how to change my project to OpenGL.


text:
Q: Inverse every n rows in a dataframe How would I go about reversing every n rows in a dataframe. I have a dataframe where the rows start with H24 and end with H1 for every day. Now I would like to reverse every 24 rows so the day starts with H1 and ends with H24 (for all the days in the dataframe). Do i need to loop over the dataframe or is there a more efficient solution?
The dataframe looks like this:
df5
and this is the code i used so far:
import pandas as pd

df0 = pd.read_csv('Podatki_vsi_NOVE.csv',sep=';')
df1 = pd.read_csv('Podatki_vsi_OVE.csv')
df5 = df1.reindex(index=df1.index[::-1])

The problem is that one set of data (df0) starts at an earlier date for example (1.1.2016) and continues to the last date (1.1.2018) but the second set of data start at the last date (1.1.2018) and ends with earlier date (1.1.2016). Now, as it can be seen, from the code, I have already inversed the entire dataframe df1 and the result is df5. the problem of df5 (as seen from the picture) is that every day, now that it is inversed, starts with H24 not with H1 as it should.
Output:
output1
output2

A: Try this code:
df5["hour"] = df5["Unnamed: 0"].apply(lambda x: int(x[1:]))
df5 = df5.sort_values(["datum", "hour"])


text:
Q: Custom ProgressBar change Bitmap programmatically I spent a lot of hours researching but with no hope. What i want to do is to change the bitmap drawable (android:id="progress) of progress_bar_clip.xml programmatically.
progress_bar_clip.xml
<?xml version="1.0" encoding="utf-8"?>

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

<item android:id="@android:id/background">
    <clip
        android:clipOrientation="vertical"
        android:drawable="@drawable/body_empty"
        android:gravity="bottom" />
</item>
<item android:id="@android:id/progress">
    <clip
        android:clipOrientation="vertical"
        android:gravity="bottom" >
        <bitmap android:src="@drawable/body_empty"
        android:id="@+id/to_be_changed" >
        </bitmap>
    </clip>
</item>

</layer-list>

<ProgressBar
    android:id="@+id/progressbar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="180dp"
    android:layout_height="240dp"
    android:layout_marginTop="80dp"
    android:indeterminateOnly="false"
    android:max="100"
    android:progress="-500"
    android:progressDrawable="@drawable/progress_bar_clip"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    >
</ProgressBar>

code
Resources res = getResources();
LayerDrawable layerDrawable = (LayerDrawable)res.getDrawable(R.drawable.progress_bar_clip);

Drawable newDrawable = res.getDrawable(R.drawable.i_want_to_set_this);

layerDrawable.setDrawableByLayerId(R.id.to_be_changed, newDrawable);

Animation
private void wireResultAnimation(View view)  {
    final ProgressBar bar = (ProgressBar) view.findViewById(R.id.progressbar);

    final Handler handler = new Handler();
    runnable = new Runnable() {

        @Override
        public void run() {

            if (bar.getProgress() != 100) {
                bar.incrementProgressBy(1);
                handler.postDelayed(runnable, 20);
            }
        }
    };

    handler.post(runnable);

}

The animation works fine however, the drawable is not changing.


text:
Q: Permissions access The new version 2 API introduce methods to access permissions. Apps can create, delete, modify and read one permission but why the get method does't return the value property which limits what apps can do with permissions ? The JavaScript embeddable sharing component is a solution for some use cases but not for all.

A: The value property is omitted in order to preserve privacy. A user that can read the permissions on a file should not be able to see the email addresses of all the other users with permissions.
You should use the permission id, which can be found with the about method as the about resource, and is:
The current user's ID as visible in the permissions collection.


text:
Q: parse JSON from url using Eniro search API in Rails I am trying to use an external API from eniro http://api.eniro.com/ for my rails application.
They have provided a code snippet to use for ruby as a working example, but I need further assist on how I can use it. The code below is my controller.
My Controller
class ListanController < ApplicationController

  require 'open-uri'
  require 'rubygems'
  require 'json'

  def get_json
@json = JSON.parse( open('http://api.eniro.com/partnerapi/cs/search/basic?profile=[*******]&key=[**********]&country=se&version=1.1.3&search_word=pizza').read )
@json['adverts'].each do |advert|
puts advert['companyInfo']['companyName']
end
end

def index
    @json = JSON.parse(open('http://api.eniro.com/cs/search/basic?profile=mrshawn191&key=5582158511111471396&country=se&version=1.1.3&search_word=pizza').read )
end

end

My view

Test site

<%= form_tag("/search", method: "get") do %>
  <%= label_tag(:q, "Search for:") %>
  <%= text_field_tag :index, params[:index] %>
  <%= submit_tag("Search") %>
<% end %>

<% @json['adverts'].each do |advert| %>
  <%= advert['companyInfo']['companyName'] %>
<% end %>

How do I interact with this controller in my view?
I want simply to create a search form in my view that is connected to the external API, so whenever I search for something it will redirect me to a new page and display the result from the api.I don't know much but what I'm guessing is that I have to

*

*In my controller, specify a method where I parse url into json object

*In my view puts that json objekt? depending on what the keyword is?

*Configure routes.rb to match the search path

I'm lost, can anyone give any guidelines where to start? How would the code look in my view?

A: The code parts
@json['adverts'].each do |advert|
  puts advert['companyInfo']['companyName']
end

merely print it to the console. Since you want it showing in your view, you can just remove those.
In your view (if you're using ERB), add
<% @json['adverts'].each do |advert| %>
  <%= advert['companyInfo']['companyName'] %>
<% end %>

which should then do the same as your putscode, just for the HTML rendered on page. Format as appropriate.


text:
Q: Given entire functions $f,p$, find holomorphic $g$ with $g \circ p = f$ Let $f,p: \mathbb{C} \to \mathbb{C}$ be two entire functions, where $p$ is non-constant (so that $\Omega := p(\mathbb{C})$ is open, by the open mapping theorem).
Assume also that the following condition holds:
$$\forall z,w\in \Omega, \quad p(z)=p(w)\implies f(z)=f(w).$$
This means that the function:
$$g:\Omega \to \mathbb{C},\quad g(p(z)):=f(z) $$
is well-defined.
Question: is $g$ necessarily holomorphic in $\Omega$?
It's a nice exercise to show that this holds if $p(z)=z^k$ for $k\ge 1$, but I'm not sure if it holds in general.
Here's the strategy I had in mind:
Step 1: If $z_0\in \mathbb{C}$ satisfies $p'(z_0)\neq 0$, then $p$ is locally invertible in a neighborhood $V\ni z_0$, and then $g$ is holomorphic in $p(V)$ as $g=f\circ p^{-1}$ there.
Thus, $g$ is holomorphic in $\Omega - p(E)$, where $E := \{p' = 0 \}$ is a discrete subset of $\mathbb{C}$.
Step 2: Show that $p(E)$ is a discrete subset of $\mathbb{C}$.
I don't know how to do this step- I'm not even sure if $p(E)$ is closed (as $p$ is not necessarily a closed map).
If true, this would imply that the points of $p(E)$ are isolated singularities of $g$.
Step 3: If $w_0 = p(z_0) \in p(E)$, then $g$ is bounded in a neighborhood of $w_0$: indeed, if $B\ni z_0$ is any open ball around $z_0$, then $V = p(B) \ni w_0$ is an open neighborhood of $w_0$, and $g(V)=(g\circ p)(B)=f(B)$ is a bounded subset of $\mathbb{C}$.
Thus, each such $w_0$ is a removable singularity of $g$.
Step 4: We're almost done- by step 3, there's a holomorphic function $h:\Omega \to \mathbb{C}$ such that $h=g$ on $\Omega - p(E)$ (formed by adding the values of the removable singularities).
However, I'm not sure how to show that $g=h$ on $p(E)$. It would suffice to show that $g$ is continuous on the points of $p(E)$.

Is my outline correct? If so, how can we justify steps 2,4?


text:
Q: Handle data in angularjs with loop $scope.forms = [
        {id: 1, text: 'h_form'},
        {id: 2, text: 'S_form'},
        {id: 3, text: 'l_form'},
        {id: 4, text: 'g_form'},
        {id: 5, text: 'f_form'},
        {id: 7, text: 'b_form'},
        {id: 8, text: 's_form'}
      ];

I'm achieving some validation with these codes but thats weired called multiple times that's not correct
if($scope.form.userInfo.h_form != undefined){
        if($scope.form.userInfo.h_form.$invalid){
         if(setPlayerProfileId == ''){
          setPlayerProfileId = 'sportdetailform';
         }
        }
      }

      if($scope.form.userInfo.g_form != undefined){
        if($scope.form.userInfo.g_form.$invalid){
         if(setPlayerProfileId == ''){
          setPlayerProfileId = 'sportdetailform';
         }
        }
      }

      if($scope.form.userInfo.f_form != undefined){
        if($scope.form.userInfo.f_form.$invalid){
         if(setPlayerProfileId == ''){
          setPlayerProfileId = 'sportdetailform';
         }
        }
      }

I typically do not want to run this code multiple time so i used foreach function but doesn't work for me please suggest how to fixed out those
angular.forEach($scope.forms, function(value, key){
          var check = value.text;
            if($scope.form.userInfo.check != undefined){
              if($scope.form.userInfo.check.$invalid){
               if(setPlayerProfileId == ''){
                setPlayerProfileId = 'sportdetailform';
               }
              }
            }

      })

A: Change your forEach in the following way:
angular.forEach($scope.forms, function(value, key){
        if($scope.form.userInfo[value.text] != undefined){
          if($scope.form.userInfo[value.text].$invalid){
           if(setPlayerProfileId == ''){
            setPlayerProfileId = 'sportdetailform';
           }
          }
        }

  });


text:
Q: Python groupby nested dictionary is ambiguous in aggregation I am currently working on my thesis and facing some problems in a groupby function I want to do. I am trying to find out someone's total purchase amount, average purchase amount, purchase count, how many products bought in total and the average value per product.
The data looks like thise:
    id  purchase_amount price_products  #_products
0   123 30              20.00           2
2   123 NaN             10.00           NaN
3   124 50.00           25.00           3
4   124 NaN             15.00           NaN
5   124 NaN             10.00           NaN

My code looks like this:
df.groupby('id')[['purchase_amount','price_products','#_products']].agg(total_purchase_amount=('purchase_amount','sum'),average_purchase_amount=('purchase_amount','mean'),times_purchased=('#_products','count'),total_amount_products_purchased=('price_products','count'),average_value_products=('price_products','mean'))

But I get the following error:

SpecificationError: nested dictionary is ambiguous in aggregation

I cannot seem to find what I am doing wrong, hopefully someone can help me!

A: Do like this for all calculations
df.groupby('id')['purchase_amount'].agg({'total_purchase_amount':'sum'})

A: Since you have several variables to aggregate, I would suggest using the following form of aggregation:
df.groupby('id')[<variables-list>].agg([<statistics-list>])
For example:
df_agg = df.groupby('id')[['purchase_amount','price_products','#_products']].agg(["count", "mean", "sum"])
This will create a column-wise multi-level output data frame df_agg that looks like:
    purchase_amount             price_products          #_products
              count  mean   sum          count mean sum      count mean  sum
id
123               1  30.0  30.0              2   15  30          1  2.0  2.0
124               1  50.0  50.0              3   17  51          1  3.0  3.0

You can then refer to a particular entry in the output data frame using the multi-index as follows:
df_agg['purchase_amount']['mean']
id
123    30.0
124    50.0
Name: mean, dtype: float64

or if you want e.g. all the means, use the cross-sectional method xs():
df_agg.xs('mean', axis=1, level=1)
     purchase_amount  price_products  #_products
id
123             30.0              15         2.0
124             50.0              17         3.0

Note: presumably, the above piece of code will make Python compute more statistics than needed, as is the case in your example. But this may not be an issue in certain contexts, and it has the advantage that the code is shorter and generalizable to any set and number of (numeric and float) variables to aggregate.

A: You can do this in an organized way using a dictionary for your aggregation.
df = pd.DataFrame([[123, 30, 20, 2],
                   [123, np.nan, 10, np.nan],
                   [124, 50, 25, 3],
                   [124, np.nan, 15, np.nan],
                   [124, np.nan, 10, np.nan]],
                  columns=['id', 'purchase_amount', 'price_products', 'num_products']
                  )

agg_dict = {
    'purchase_amount': [np.sum, np.mean],
    'num_products': [np.count_nonzero],
    'price_products': [np.count_nonzero, np.mean],
}

print(df.groupby('id').agg(agg_dict))

output:
    purchase_amount        num_products price_products
                sum  mean count_nonzero  count_nonzero       mean
id
123            30.0  30.0           2.0              2  15.000000
124            50.0  50.0           3.0              3  16.666667


text:
Q: Use bukkit server with snapshot? I use Mojang's server for my single player games so that I can share them with other people and I thought I might as well switch to Bukkit since it can do more.
The only problem is... I am using the 12w26a snapshot and I already have a save file on my server which I want to move over to Bukkit.
I can handle transferring the maps but how can I make Bukkit work with 12w26a?

A: Bukkit does not update for snapshots. You cannot run a Bukkit server on anything except a primary release. Unfortunately, you are out of luck. You'll have to run a vanilla server or just wait for the next full version to be released.

A: On the Bukkit wiki homepage there's a link to download the development snapshot for both CraftBukkit and Bukkit.


text:
Q: Spring cloud stream binder gives "Failed to create consumer binding" when connecting to google pubsub Assume that we have a pubsub topic A in Project A.
I am running a spring boot application in project B.
It uses a Service Account - test-sa-projectB.
The application is set up in the below way to consume the data from topic A.
https://cloud.google.com/pubsub/docs/spring#receiving-messages-using-stream-binder
Service Account test-sa-projectB is given pubsub-subscriber role to topic A.
Now when I run the application to consume  the topic, I get the following error.
org.springframework.cloud.stream.binder.BinderException: Exception thrown while starting consumer:
    at org.springframework.cloud.stream.binder.AbstractMessageChannelBinder.doBindConsumer(AbstractMessageChannelBinder.java:480)
    at org.springframework.cloud.stream.binder.AbstractMessageChannelBinder.doBindConsumer(AbstractMessageChannelBinder.java:92)
    at org.springframework.cloud.stream.binder.AbstractBinder.bindConsumer(AbstractBinder.java:143)
    at org.springframework.cloud.stream.binding.BindingService.doBindConsumer(BindingService.java:180)
    at org.springframework.cloud.stream.binding.BindingService.bindConsumer(BindingService.java:137)
    at org.springframework.cloud.stream.binding.AbstractBindableProxyFactory.createAndBindInputs(AbstractBindableProxyFactory.java:118)
    at org.springframework.cloud.stream.binding.InputBindingLifecycle.doStartWithBindable(InputBindingLifecycle.java:58)
    at java.base/java.util.LinkedHashMap$LinkedValues.forEach(LinkedHashMap.java:608)
    at org.springframework.cloud.stream.binding.AbstractBindingLifecycle.start(AbstractBindingLifecycle.java:57)
    at org.springframework.cloud.stream.binding.InputBindingLifecycle.start(InputBindingLifecycle.java:34)
    at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:178)
    at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54)
    at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356)
    at java.base/java.lang.Iterable.forEach(Iterable.java:75)
    at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155)
    at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123)
    at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:935)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:586)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:308)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295)
    at com.ingka.soim.ApplicationKt.main(Application.kt:15)
Caused by: com.google.api.gax.rpc.PermissionDeniedException: io.grpc.StatusRuntimeException: PERMISSION_DENIED: User not authorized to perform this action.
    at com.google.api.gax.rpc.ApiExceptionFactory.createException(ApiExceptionFactory.java:53)
Caused by: com.google.api.gax.rpc.PermissionDeniedException: io.grpc.StatusRuntimeException: PERMISSION_DENIED: User not authorized to perform this action.

    at com.google.api.gax.grpc.GrpcApiExceptionFactory.create(GrpcApiExceptionFactory.java:72)
    at com.google.api.gax.grpc.GrpcApiExceptionFactory.create(GrpcApiExceptionFactory.java:60)
    at com.google.api.gax.grpc.GrpcExceptionCallable$ExceptionTransformingFuture.onFailure(GrpcExceptionCallable.java:97)
    at com.google.api.core.ApiFutures$1.onFailure(ApiFutures.java:67)
    at com.google.common.util.concurrent.Futures$CallbackListener.run(Futures.java:1132)
    at com.google.common.util.concurrent.DirectExecutor.execute(DirectExecutor.java:31)
    at com.google.common.util.concurrent.AbstractFuture.executeListener(AbstractFuture.java:1270)
    at com.google.common.util.concurrent.AbstractFuture.complete(AbstractFuture.java:1038)
    at com.google.common.util.concurrent.AbstractFuture.setException(AbstractFuture.java:808)
    at io.grpc.stub.ClientCalls$GrpcFuture.setException(ClientCalls.java:563)
    at io.grpc.stub.ClientCalls$UnaryStreamToFuture.onClose(ClientCalls.java:533)
    at io.grpc.PartialForwardingClientCallListener.onClose(PartialForwardingClientCallListener.java:39)
    at io.grpc.ForwardingClientCallListener.onClose(ForwardingClientCallListener.java:23)
    at io.grpc.ForwardingClientCallListener$SimpleForwardingClientCallListener.onClose(ForwardingClientCallListener.java:40)
    at com.google.api.gax.grpc.ChannelPool$ReleasingClientCall$1.onClose(ChannelPool.java:535)
    at io.grpc.internal.DelayedClientCall$DelayedListener$3.run(DelayedClientCall.java:463)
    at io.grpc.internal.DelayedClientCall$DelayedListener.delayOrExecute(DelayedClientCall.java:427)
    at io.grpc.internal.DelayedClientCall$DelayedListener.onClose(DelayedClientCall.java:460)
    at io.grpc.internal.ClientCallImpl.closeObserver(ClientCallImpl.java:562)
    at io.grpc.internal.ClientCallImpl.access$300(ClientCallImpl.java:70)
    at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInternal(ClientCallImpl.java:743)
    at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInContext(ClientCallImpl.java:722)
    at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:37)
    at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:133)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:829)
    Suppressed: com.google.api.gax.rpc.AsyncTaskException: Asynchronous task failed
        at com.google.api.gax.rpc.ApiExceptions.callAndTranslateApiException(ApiExceptions.java:57)
        at com.google.api.gax.rpc.UnaryCallable.call(UnaryCallable.java:112)
        at com.google.cloud.pubsub.v1.TopicAdminClient.getTopic(TopicAdminClient.java:549)
        at com.google.cloud.pubsub.v1.TopicAdminClient.getTopic(TopicAdminClient.java:479)
        at com.google.cloud.spring.pubsub.PubSubAdmin.getTopic(PubSubAdmin.java:137)
        at com.google.cloud.spring.stream.binder.pubsub.provisioning.PubSubChannelProvisioner.ensureTopicExists(PubSubChannelProvisioner.java:136)
        at com.google.cloud.spring.stream.binder.pubsub.provisioning.PubSubChannelProvisioner.provisionConsumerDestination(PubSubChannelProvisioner.java:82)
        at com.google.cloud.spring.stream.binder.pubsub.provisioning.PubSubChannelProvisioner.provisionConsumerDestination(PubSubChannelProvisioner.java:42)
        at org.springframework.cloud.stream.binder.AbstractMessageChannelBinder.doBindConsumer(AbstractMessageChannelBinder.java:421)
        at org.springframework.cloud.stream.binder.AbstractMessageChannelBinder.doBindConsumer(AbstractMessageChannelBinder.java:92)
        at org.springframework.cloud.stream.binder.AbstractBinder.bindConsumer(AbstractBinder.java:143)
        at org.springframework.cloud.stream.binding.BindingService.doBindConsumer(BindingService.java:180)
        at org.springframework.cloud.stream.binding.BindingService.bindConsumer(BindingService.java:137)
        at org.springframework.cloud.stream.binding.AbstractBindableProxyFactory.createAndBindInputs(AbstractBindableProxyFactory.java:118)
        at org.springframework.cloud.stream.binding.InputBindingLifecycle.doStartWithBindable(InputBindingLifecycle.java:58)
        at java.base/java.util.LinkedHashMap$LinkedValues.forEach(LinkedHashMap.java:608)
        at org.springframework.cloud.stream.binding.AbstractBindingLifecycle.start(AbstractBindingLifecycle.java:57)
        at org.springframework.cloud.stream.binding.InputBindingLifecycle.start(InputBindingLifecycle.java:34)
        at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:178)
        at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54)
        at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356)
        at java.base/java.lang.Iterable.forEach(Iterable.java:75)
        at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155)
        at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123)
        at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:935)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:586)
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734)
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:308)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295)
        at com.ingka.soim.ApplicationKt.main(Application.kt:15)

It looks like it is trying to verify if topic exists in that project.
But only with subscriber role, it cant verify topic existence.
Is there any way to skip the check of topic existence in PubSubChannelProvisioner?
Can anyone suggest something on this?


text:
Q: Is it a good practice to run identd in 2010? I know in the "old days" it was good practice to shut this off.
But nowadays I have heard that it improves deliverability of email. In the old days people were not worried about spam (or having their outbound email rejected), so that made sense.
Of course, the question is only relevant to servers that send email.
What is the current, common practice among discerning Linux admins? Run identd or leave it off?
Thanks

A: The days of finger or ident are long since past.  They belong in the protocol dustbin with gopher and rlogin.

A: I use identd (well, oidentd) for IRC and Postgres.

A: I don't run an ident daemon ever anymore.  I wouldn't consider it part of any e-Mail delivery best practices.
IRC networks sometimes require it, which is why many IRC clients have a daemon built in.
It might be worth weighing the benefit of running on a multi-user system where the users have system level access but wouldn't by default due to information disclosure.

A: If you might have clients using IRC, run identd.
If you are hosting shells or IRC bouncers, RUN IDENTD.
This will allow IRC networks to ban people by their ident@ip instead of *@ip.
Additionally, running identd has no real security implications - someone else can never know if the ident response contains a real or a spoofed username.
Besides that, mail servers might give you a lower spam score if there is a valid identd response. Especially when sending newsletters etc. everything that lowers spam ratings is good.

A: I haven't seen a mail server running identd for a long time.  It doesn't mean much on Windows, and few Unix admins accept the resulting risks.  I haven't logged probes to the port for a while, but last time I did, there weren't enough to indicate it was being used.  Some firewall still reject packets on the port rather than drop them, just in case.