text:
Q: Curses exception when drawing to (24, 79) I noticed a very curious bug. When I use windows (Curses.StdScr or a new Window), I get an exception when trying to draw to the very last screen position (y=24, x=79):
mvwaddnwstr() returned ERR
The code is:
w.Add(y, x, r) where y=24, x=79, and r='!'
Some weird facts:

*

*If I neglect this position, I can draw to every other position in the screen.

*If I call w.Box(), it draws the border fine

*If I catch and eat the exception for that position, it draws fine

It seems like a bug.  Is this a known bug or does it have a known work-around? Eating the exception cuts my FPS in half.
I've seen this in CursesSharp (C#), Ruby (ncurses), and the Python Curses wrapper.


text:
Q: Where in the java files do i find the reference of the tick i have circled in blue? i would like to know where in the java files i find reference of that tick
I want to add a date picker function such that when i click the tick to add a certain task to the bucket list then it will show the date that task was created.

A: in drawable folder, and in menu/menu_add_edit_task.xml

A: package com.tanakadanielphiri.zjutbucketlist.features.addEdit;

import android.content.Context;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatSpinner;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import com.tanakadanielphiri.zjutbucketlist.R;
import com.tanakadanielphiri.zjutbucketlist.models.Task;
import com.getkeepsafe.taptargetview.TapTarget;
import com.getkeepsafe.taptargetview.TapTargetView;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.realm.Realm;

public class AddEditActivity extends AppCompatActivity {

    public static final String TASK_ID = "taskID";
    private static final String PREF_TUTO_KEY = "prefTuto";

    private Realm realm;
    private AddEditPresenter presenter;
    private ActionBar ab;

    @BindView(R.id.toolbar) Toolbar toolbar;
    @BindView(R.id.container) ConstraintLayout container;
    @BindView(R.id.titleEt) EditText titleEt;
    @BindView(R.id.contentEt) EditText contentEt;
    @BindView(R.id.priority) AppCompatSpinner priority;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_edit);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);
        realm = Realm.getDefaultInstance();

        // Setup the priorities spinner
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.priorities, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        priority.setAdapter(adapter);

        // Setup the toolbar
        toolbar.inflateMenu(R.menu.menu_add_edit_task);
        ab = getSupportActionBar();

        // Setup the presenter
        presenter = new AddEditPresenter(this, realm);
        presenter.displayTask(getIntent().getStringExtra(TASK_ID));

        // Show the tutorial
        if (!getPreferences(Context.MODE_PRIVATE).getBoolean(PREF_TUTO_KEY, false)) {
            showTutorial();
        }
    }

    public void showTutorial() {
        TapTargetView.showFor(this,
                TapTarget.forToolbarMenuItem(toolbar,
                        R.id.action_save, getString(R.string.save_your_changes),
                        getString(R.string.dont_forget_to_save_your_changes))
                        .dimColor(R.color.primaryText)
                        .drawShadow(true));
        getPreferences(Context.MODE_PRIVATE).edit().putBoolean(PREF_TUTO_KEY, true).apply();
    }

    public void setupView(Task task) {
        if (ab != null) {
            ab.setTitle(task == null ? getString(R.string.add_task) : getString(R.string.edit_task));
            ab.setDisplayHomeAsUpEnabled(true);
        }

        if (task != null) {
            titleEt.setText(task.getTitle());
            contentEt.setText(task.getContent());
            priority.setSelection(task.getPriority());
        }
    }

    public void showError(String err) {
        Snackbar.make(container, err, Snackbar.LENGTH_LONG).show();
    }

    public void goBack() {
        onBackPressed();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_add_edit_task, menu);

        if (!presenter.hasTask()) {
            menu.removeItem(R.id.action_delete);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;
            case R.id.action_save:
                presenter.saveTask(titleEt.getText().toString(), contentEt.getText().toString(), priority.getSelectedItemPosition());
                break;
            case R.id.action_delete:
                presenter.deleteTask();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        realm.close();
    }
}

A: <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.tanakadanielphiri.zjutbucketlist.features.addEdit.AddEditActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="0dp"
        android:layout_height="56dp"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"/>

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:background="@android:color/transparent"
        tools:text="Title"
        android:ems="10"
        android:id="@+id/titleEt"
        android:layout_marginTop="16dp"
        android:textStyle="bold"
        android:textSize="18sp"
        android:textColor="@color/primaryText"
        android:hint="@string/task_title"
        android:nextFocusDown="@+id/contentEt"
        app:layout_constraintTop_toBottomOf="@+id/toolbar"
        android:layout_marginStart="16dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/priority"
        android:layout_marginEnd="8dp" />

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:background="@android:color/transparent"
        tools:text="My super content"
        android:ems="10"
        android:id="@+id/contentEt"
        android:textColor="@color/secondaryText"
        android:textSize="16sp"
        android:layout_marginTop="32dp"
        android:hint="@string/what_do_you_need_to_do"
        app:layout_constraintTop_toBottomOf="@+id/titleEt"
        android:layout_marginStart="16dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginEnd="16dp"
        app:layout_constraintRight_toRightOf="parent" />

    <android.support.v7.widget.AppCompatSpinner
        android:layout_width="wrap_content"
        android:layout_height="48dp"
        android:layout_marginEnd="16dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/titleEt"
        android:id="@+id/priority" />
</android.support.constraint.ConstraintLayout>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Could anybody possibly tell me if they are the same and right? She'll either pay for the ring or return it.
She either will pay for the ring or will return it.
Could anybody possibly tell me if they are the same and right?
Moreover, which one do you use?

A: Both versions are "valid", but in constructions involving an auxiliary verb (to be here forming a "future" tense), the word either normally comes between the auxiliary and the main verb. That's still the case if the auxiliary verb isn't contracted ("She will either pay...")
Here are a couple of thousand written instances of "He either will have" showing that the form is used (but note there are 77,900 instances of the more common "He will either have").
Note that this principle assumes either is being used to modify the verb (she'll either pay or return). If it modifies a noun it will normally come after the verb (as in "She'll pay for either the ring or the necklace").

TL;DR: There's a certain amount of flexibility in the positioning of either, but the tendency is to place it immediately before the main verb or the first (of two) nouns, depending on which it modifies.


text:
Q: Cut one string into two others in Objective-C I have an NSURLRequest being made that to a server that returns a string.
string = [[NSMutableString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];

receivedData is the mutable array that the downloaded data is stored in. Everything works fine.
I have now, however, added another value to that string. An example of the returned string would be 14587728000000 , 376.99. Originally it was one value so I didn't have to do any splicing. But, now that I have another value, I want to be able to separate it into two different strings.
What should I do to separate the two values into different string? Some kind of search that goes till the first space, or something like that. I have access to the server, and the string is generated in PHP so the separator can be anything.

A: You can do this with the NSString componentsSeparatedByString method:
NSString *string = @"14587728000000,376.99";
NSArray *chunks = [string componentsSeparatedByString: @","];

You can find some other common NSString tricks (where I found this one) here.

A: Use -(NSArray *)componentsSeparatedByString: and pass in the token to split by.


text:
Q: How to output True if these methods equal each other? I will be given a type of farm animals and the age of the animals.  If I get two animals with the same age, how do I return True.
I understand how to make it return true if I am giving the two items in the function, but I am not sure how to do it in the main function.
from src.winged_animal import WingedAnimal
class Chicken(WingedAnimal):

    def __init__(self, age):
        WingedAnimal.__init__(self, age)

    def chicken_equal(self, age):
        if self.age == self.age
            return True

    def make_sound(self):
        return WingedAnimal.make_sound(self) + " - cluck, cluck"

Given Chicken(1.1) and Chicken(1.1) I want to return that they equal each other in the method chicken_equal.  I don't even know how to begin this.

A: x1 = ["chicken", 1]
x2 = ["chicken", 1]
x = [x1, x2]

result = [0, 0]  # [animal type , age]

for item in x:
    if item[0] == "chicken":   # animal type
        result[0] = result[0] + 1
    if item[1] == 1:   # age
        result[1] = result[1] + 1

print (result)   # if 2, 2 then both are equal; in all other cases not.


text:
Q: how to implement IApplicationBuilder? I went through the documentation given in :
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware
I understood that IApplicationBuilder gives us the ability to plumb in different features in the pipeline.
Is it possible to see the implementation of IApplicationBuilder in the framework ?
If yes, can I write my own version of IApplicationBuilder and override the pipeline ?

A:
You can see the implementation of IAppbuilder here

Not sure why you would like to implement IAppbuilder.You do not have to do that normally unless you would like to create a new server implementation similar on OWIN specification .
OWIN is a specification and for OWIN implementation,you can look at any of these projects

*

*katana

*NoWin

*Suave
if you would like to add any Server Feature implementation,you can do that using Server Feaure .


text:
Q: How to stop an animation in GameQuery I have one image animation started using GameQuery. Now I want to stop the animation. For that, I have used the following code.
imgAnimation["myimage"] = new $.gameQuery.Animation({imageURL: imgPath + "test.png",  numberOfFrame: 3, delta: 130, rate: 236,
       type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_CALLBACK});

       $("#playground").playground({height: PLAYGROUND_HEIGHT, width: PLAYGROUND_WIDTH})
       .addGroup("actors", {width: PLAYGROUND_WIDTH, height: PLAYGROUND_HEIGHT})
       .addSprite("myimage",{animation: imgAnimation["myimage"],
       posx: imgXPos, posy: 0, width: 128, height: 384, callback: callbackAnimation})

       function callbackAnimation(){
         $("#myimage").stop();
         $("#myimage").clearQueue();
       }

       $.playground().startGame();

But this does not seem to be working. But at the same time, if I use the hide() method on the same animation element( $("#myimage") ), it works.
Both methods are part of the jQuery API only.
But why does the stop method not work?
Thanks in advance.

A: this wasn't possible with version 0.5.x from gameQuery, but 0.6 is just out and add pauseAnimation() and resumeAnumation() that should do just what you want.


text:
Q: Introductory book on differential geometry for engineering major I am an engineering major and looking for a straightforward, easy to understand basic book on differential geometry to get started. At starting point, I am not looking for a comprehensive book (may be Spivak's Comprehensive Introduction to Differential Geometry series). I have background of linear algebra and advanced calculus. I am looking to learn topics such as Lie derivative, covarient-contravarient derivatives, pushforward pullback operations, Riemannian manifolds, moving frames, etc. As I am not from math major, I am confused over many previous questions asking suggestions for differential geometry, such as this, this, this, and many other answers on the similar questions.
From search on good books on the topic, I found out O'neill's Elementary Differential Geometry is meant for first course on the differential geometry. However, as I have very limited knowledge about the differential geometry, I am not sure whether this would be good starting point.
Can someone suggest me a good reference (and prerequisites, if necessary,for studying above topics)? Thanks in Advance.

A: My 3 favourites are:

*

*Introduction to Smooth Manifolds - John M. Lee

*Introduction to Manifolds - Loring Wu. Tu

*Analysis on Manifolds - James R. Munkres - expensive and hard to get. I'd recommend for a physicist.

However I am loving:

*

*Smooth Manifolds - Rajnikant Sinha

And I think that may be better for a physicist. However I've only scanned a Library e-book, my copy will arrive on Monday hopefully.
A great topology book to complement ITSM by JML is:

*

*Introduction to Topological Manifolds - John M. Lee

*Topology - James R. Munkres

*Introduction to Topology - Gamelin and Greene (nice cheap Dover book, VERY good)

*Introduction to Topology - Bert Mendelson (nice cheap Dover book, VERY good, not as broad as the others but very good none the less)

A: I highly recommend Introduction to Manifolds by Loring Tu. The reason is that he specifically delays the need for topology so as to get into the meat of the subject quicker. This means that he develops the material on $\mathbb{R}^n$ first, and then uses these results plus minimal topology to generalize to manifolds. Tu's book really is the best to get into the subject quickly and concisely, particularly someone without a course in topology. I learned the material from a course that used Lee but used Tu as a reference for qualifying exams and also as a reference since then.
Introduction to Smooth Manifolds by John M. Lee is good, but it is more verbose, less focused, and requires a lot more topology to get through. Tu's book covers the same core material.
Given your background, you have the minimal prequisities for Tu, but it might be a little tough at first recalling a lot of your vector calculus and linear algebra. You will have to pick up pieces of algebra, analysis, and topology along the way, but I don't see a reason why you need to learn all of that before trying out Tu. Just go through it and read up on subjects when you need to.
If you truly find yourself stuck on Tu, then I recommend the following two books to help out:

*

*Advanced Calculus: A Geometric View by James Callahan

*Vector Calculus, Linear Algebra, and Differential Forms: A Unified Approach by Hubbard and Hubbard
Both of these books should get you back on track regarding any missing material from your background. They are both excellent.
Other books to be aware of regarding supplemental material are:

*

*The Geometry of Physics by Theodore Frankel - Really fantastic book, but I haven't gone through all of it as I have Tu and Lee. It is quite comprehensive, and there isn't a heavy emphasis (from what I have read) on proofs. Thus there are a ton of examples and applications.

*Applied Differential Geometry by William Burke - Lots of great pictures and insight. It's too quirky to use as your main learning source though, but it's great for supplemental insight.

*Geometrical Vectors by Gabriel Weinreich - This is a very short but insightful read that would help put vectors, covectors, etc. into context.

Three other books on the subject that I am aware of but have no experience with:

*

*First Steps in Differential Geometry by Andrew McInerney

*Manifolds and Differential Geometry by Jeffrey M. Lee

*Differential Geometry: Curves - Surfaces - Manifolds by Wolfgang Kuhnel


text:
Q: my application is not searchable on android market I have just published my application on the android market. After doing that I went on the android market and searched my application by name, no results came up. What could be the reason?
How long does it take for a published android application to be visible on the android market?
Edit:
My app did show up, it took about an hour. I guess the time for your app to be available once you publish it depends on the traffic on android market at that time.

A: It can take up to more than 10 hours for your application to show up.
Have you tried a direct link? I.e. market://search?q=pname:your.package.name.here?

A: Here you've got possible answers.


text:
Q: Multiple Long running IHostedSerivces or BackgroundService implementations I cant seem to find much on this issue. The problem I am having is I have the need to be running 2+ long running background services but only the first registered service's ExecuteAsync gets executed. I have tried implementing it via BackgroundService and putting the code in ExecuteAsync and I have tried implementing IHostedService directly and putting the long running code in StartAsync.
I think the issue is return Task.CompletedTask; is never called.
For example I have two Kafka consumers implemented as BackgroundServices
The code looks identical in both aside from the topic and an OnMessage methods
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
    var kafkaEndpoint = _kafkaConfig.Endpoint;

    var kafkaTopic = "PhoenixEventStore";

    var consumerConfig = new Dictionary<string, object>
    {
        { "group.id", "consumer1" },
        { "bootstrap.servers", kafkaEndpoint },
        { "auto.offset.reset", "earliest" }
    };

    using (var consumer = new Consumer<Null, string>(consumerConfig, null, new StringDeserializer(Encoding.UTF8)))
    {
        consumer.OnMessage += (obj, msg) =>
        {
            Log.Information($"Consumer1 Received {msg.Value}");
        };

        consumer.OnPartitionEOF += (_, end) =>
        {
            Log.Information($"Consumer1 Reached end of topic {end.Topic} partition {end.Partition}.");
        };

        consumer.OnError += (_, error) =>
        {
            Log.Error($"Consumer1 Error: {error}");
        };

        consumer.Subscribe(new List<string>() { kafkaTopic });

        while (!stoppingToken.IsCancellationRequested)
        {
            consumer.Poll(TimeSpan.FromSeconds(10));
        }

        //consider setting value that check whether the consumer has stopped polling.
    }
    return Task.CompletedTask;
}

Since both services are long running the Task.Complete is never hit. However if I comment out the while loop both services ExecuteAsync are hit instead of just the first one registered.
I have found a work around that seems to be working but wondering if anyone else has a better approach.
Basically I refactor the code to have the long running code run in a void method called StartConsumer then have my ExecuteAsync look like this
  protected override Task ExecuteAsync(CancellationToken stoppingToken)
  {
        Task.Run(() => StartConsumer(stoppingToken));
        return Task.CompletedTask;
  }

Both services are registered using
services.AddHostedService<MyHostedService1>
services.AddHostedService<MyHostedService2>

A: I have the same case and it works. The template is
 protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                await Foo()
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message, exception: ex);
            }

            await Task.Delay(timeInMlSeconds);
        }
    }


text:
Q: Shutdown Freezes on Ubuntu 14.04 (2015 Macbook Pro Dual-Boot) I recently did a dual-boot on my 2015 Macbook Pro Retina. I opted not to use rEFInd, instead selecting sda1 (/boot/efi) as the mountpoint for my boot partition.
I cannot shut down my computer without it freezing on the splash screen. Thus, I have to force shutdown every time I want to switch to my Mac OS, which is terrible for the machine.
I've tried multiple things, including:

*

*Erasing my whole Ubuntu dual-boot and restarting from scratch

*Changing the line in /etc/default/grub from:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"

to
GRUB_CMDLINE_LINUX_DEFAULT=""

and to
GRUB_CMDLINE_LINUX_DEFAULT="acpi=noirq acpi=force apm=power_off quiet splash"

and to
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash reboot=bios"

and updating grub, none of which worked.

*I have a 16GB swap partition (which I later found out was too big) which I turned off and reformated to ext4 which didn't solve the problem.
I dont know what else to try. I suspect that the system doesn't know I'm booting from the EFI partition which might be affecting shutdown?
Currently, the output that's displaying during shutdown is:
All processes ended within 1 seconds...

[skipping]

Deactivating swap...
Unmounting local filesystems...
Will now halt
[704....] reboot: Power down
_

I'm pretty unfamiliar with this kind of debugging, so I've probably already done something wrong. I'd appreciate any help/explanation. Thanks.


text:
Q: Disable auto zoom/field zoom on input tags on my Mobile Site - WITHOUT disabling all zoom capabilities I have spent all day looking for a solution, and this site keeps coming up, SO why not ask you guys.
I an building our companies mobile website and we want to disable the auto zoom mobile devices use to zoom into text/search/email inputs when they are focused on.
I am building the site in HTML5 and have seen/tested the
<meta name="viewport" content="width=device-width, user-scalable=no" />
solution. With various properties (ie. minimum-scale=#, maximum-scale=#" )
This, works in almost ALL mobile devices I am testing on. Only one problem. I want the user to be able to zoom in/out at their leisure. (we have some higher res product shots that would be nice to see up close)
How can I disable zooming in when clicking on input tags, while retaining full manual user zoom control?
p.s the site also uses jQuery. So any thoughts using that might help.
thank you
Jrak

A: It took me a while to find it but here's the best code that I found......http://nerd.vasilis.nl/prevent-ios-from-zooming-onfocus/
var $viewportMeta = $('meta[name="viewport"]');
$('input, select, textarea').bind('focus blur', function(event) {
$viewportMeta.attr('content', 'width=device-width,initial-scale=1,maximum-scale=' +        (event.type == 'blur' ? 10 : 1));
});

A: a very simple hack is to set:
input, textarea {font-size:16px;}

A: Setting the meta tag in the <head> like this worked for me:
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">

A: It may not work exactly for your styling, but if you set the font-size of input elements to be 16px or above, the onfocus zooming will stop.

A: See: Disable Auto Zoom in Input "Text" tag - Safari on iPhone
There's no clean way I could find, but here's a hack...
1) I noticed that the mouseover event happens prior to the zoom, but the zoom happens before mousedown or focus events.
2) You can dynamically change the META viewport tag using javascript (see Enable/disable zoom on iPhone safari with Javascript?)
So, try this (shown in jquery for compactness):
$("input[type=text], textarea").mouseover(zoomDisable).mousedown(zoomEnable);
function zoomDisable(){
  $('head meta[name=viewport]').remove();
  $('head').prepend('<meta name="viewport" content="user-scalable=0" />');
}
function zoomEnable(){
  $('head meta[name=viewport]').remove();
  $('head').prepend('<meta name="viewport" content="user-scalable=1" />');
}

This is definitely a hack... there may be situations where mouseover/down don't always catch entries/exits, but it worked well in my tests and is a solid start.

A: If you set a webkit transform to any value other than 1 (or 1.0)
then auto-zoom on selecting an input tag is disabled on iPhone.
document.body.style.webkitTransformOrigin= "0% 0%";
document.body.style.webkitTransform = "scale(1.1)";

I haven't tested other mobile browsers.


text:
Q: Dynamic sequential identity column and conditional constraints? Hoping you guys can help me brainstorm some ideas for a roadblock I'm hitting at work.  I'll try to give as much info as I can here.
1) ProductSerialEnum - This is a table that contains serial number enums for various product types.  What it does is define the range of Serial Numbers a product can have.  New Types will be constantly coming in so here's a current sample
ProductTypeId   SerialPrefix SerialStartRange     SerialEndRange
--------------- ------------ -------------------- --------------------
1               2            2000000000           2999999999
2               1            1000000000           1999999999
3               4            4000000000           4999999999
4               3            3000000000           3999999999
5               501          5010000000           5019999999
6               500          5000000000           5009999999
7               601          6010000000           6019999999
8               600          6000000000           6009999999
...             ...          ...                  ...

2) The desired results
Products - This is table of product attributes which I'll shorten down to the important bits.
Here is what I'd expect this table to look like, but I'm having issues meeting all my success criteria.
ProductId   ProductTypeId   SerialNumber
----------- --------------- ------------
1           2               100000000
2           2               100000001
3           2               100000002
4           2               100000003
5           2               100000004
6           2               100000005
7           2               100000006
8           2               100000007
9           4               300000000
10          4               300000001
11          4               300000002

And so on...
My question is what is the best way to populate the Products table to work like the sample I posted above.
When a Product has to be inserted I'm provided a ProductTypeId and upon insertion I'm expected to generate a Serial Number as defined by the range in the SerialEnum table.
These Serial Numbers have to be insert in sequential order per Enum type as you can see in the example that I'm expecting. Them being sequential is absolutely critical, we can't burn any serial numbers because these ranges are the ranges we are allotted.
My initial thoughts are to generated an insertion SP that takes in the Product info with my critical ProductType then hold what the maximum serial number is for that product's serial range then simply insert the next value.
However the database receives a ton of concurrent traffic so my biggest worry is serial number collisions and skipping large range chunks due to concurrency or locking issues.
I've considered other options like potentially partitioning the table and messing around with IDENTITY columns and ranges, however with the product types increasing in scope so frequently I wouldn't  be able to keep up with continually running a partition scheme every time the product types change.
So to sum it up, every product insert in to the table must generate a unique and sequential serial number based upon the serial number ranges defined in the ProductType table without wasting serial numbers or causing errors due to concurrency issues.
If anyone has some experience or ideas I'd be super thankful if you could bounce them off me!

A:
we can't burn any serial numbers

and

However the database receives a ton of concurrent traffic

are mutually exclusive.  If you can't throw them away then you need to serisalise your transactions to make 100% it committed and allocated a number before moving onto the next.  If you use fast, sequences or identity then you may have gaps as the IDs will be allocated from a sequence cache.  Fail or rollback will cause a gap.
If you are permitted, you can always assign the serial numbers after the event in bulk.  This would entail having a fast, sequence or identity column for the primary key and insterting a blank serial number.  Periodically you scan the database for blank SNs and allocate them using ROW_NUMBER() based on the order (but not value) of the surrogate ID.
This will guarantee no gaps but there will be a time when not all products will have a serial number.

A: I am assuming each range is sufficient to prevent rollover for the expected life of your app. Also, you can reduce the number of "burned" serial numbers by putting off their generation for as long as possible during the creation process, but I can't think of an effective method to eliminate it entirely. You will most likely have some gaps.
Do it in code, as a web service or whatever is most convenient to your app. Add a column to ProductSerialEnum called something like NextAvailableValue which starts out with the value in SerialStartRange. The code reads in this table on startup.
Your API defines an entry where the next available serial number is assigned, its copy is incremented and the procedure returns. The new NextAvalableValue will need to be persisted as a matter of course but that can be spawned off to take place whenever. That I/O then will not slow down the response time of the process.
You can do this by querying the database, of course, but an in-memory process can return thousands of serial numbers in the time it takes to perform one query.
There are many effective methods of keeping the in-database value updated periodically and persisting the changing in-memory values. These depend on your platform.
This is not strictly a database-oriented solution, but it is certainly faster and potentially much more robust than such a solution.


text:
Q: Heroku postbuild script not building client I'm trying to deploy a nodejs app with a react client folder on heroku. I have a heroku-postbuild script that's supposed cd into client and install dependencies and then build.
I've verified that this works perfectly if done manually via terminal, but for some reason when I push to heroku, the client folder never seems to actually be built.
Here's the log output:
Installing dependencies
remote:        Installing node modules (package.json)
remote:        audited 216 packages in 0.969s
remote:
remote:        21 packages are looking for funding
remote:          run `npm fund` for details
remote:
remote:        found 0 vulnerabilities
remote:
remote:
remote: -----> Build
remote:        Running heroku-postbuild
remote:
remote:        > chessalong2api@1.0.0 heroku-postbuild
/tmp/build_dk354b8k
remote:        > cd chessalong2 && npm install && npm run build
remote:
remote:        audited 216 packages in 1.083s
remote:
remote:        21 packages are looking for funding
remote:          run `npm fund` for details
remote:
remote:        found 0 vulnerabilities

Why is that the number of node modules installed is the same before and after the cd into the client? I'm interpreting this as heroku not being able to enter the client folder ("chessalong2" is the name of the client folder"). What could be going wrong?

A: Have you added a client folder in git changes ??


text:
Q: Sumif across two worksheets I am trying to add up various staff members costs on individual projects (contained in a separate worksheet called "Timesheet Entry") via a sumif (i.e. if the project number in the left hand column matches the timesheet entry then add up all of my staff costs for it, then do the next project, and so on.
The code is almost working! but returning 0 as the sum against each project.
With Worksheets("Cost Data Summary")

    Lastrow = .Cells(.Rows.Count, 1).End(xlUp).Row

        For i = 2 To Lastrow
        .Cells(i, 2).Value = Application.SumIf(Worksheets("Timesheet Entry").Range("A2:F50"), "=.Cells.Value(i, 2)", Worksheets("Timesheet Entry").Range("F2:F50"))

        Next i

End With

I can only assume that I am somehow referencing the criteria incorrectly. I want it to reference the text in the cell to the left of where the sumif answer goes.
Any help would be very much appreciated.

A: Try replacing
"=.Cells.Value(i, 2)"
with
.Cells.Value(i, 2)
When enclosed in quotes, the code turns into a string literal. You shouldn't need the = sign for the argument.


text:
Q: Direct Link to Child Route in Angular 4 I am trying to implement a basic list with details in Angular 4.
I have the following routes:
{
    path: 'list',
    component: ListComponent,
    children: [
      {
        path: 'detail',
        component: DetailComponent,
      }
}

I have a <router-outlet></router-outlet> in the ListComponent. Everything works fine when you click a link in the ListComponent to the child route. However, when you enter the link directly into the browser, I get the following error:

Cannot find primary outlet to load

I thought that when you navigate to a child route, it automatically loads the parent component. Am I missing something? How do I implement it so that I can also navigate to the URL directly?

Update: Here's the ListComponent file:

            {{ listItem.name }}

    <router-outlet></router-outlet>

A: The ListComponent  has an *ngIf that when it resolves to false, means the <router-outlet> is not in the DOM, giving you the error. You should move it outside of the *ngIf

            {{ listItem.name }}

<router-outlet></router-outlet>

A: What there might be over here is when you route to the child component using the parent link the low data will be present and as the Router outlet is inside an ngif it will get populated.
But now when you hit the URL directly with the child link the if block will have data and the child route is not shown


text:
Q: Datatables Individual column searching (select inputs) Reloading After ajax I have a Data table populated using ajax request then the Individual column searching (select inputs) api is called and i am able to use the search functionality,But on new data get appended to table the select feilds are not getting reinitilised and the select feild options still shows the old values

A: if you update by javascript function then try this
function updateTable(){
    //your updation code
    var table = $("#dataTable").DataTable(); // get api instance
    // load data using api
    table.ajax.url(ajax_source).load();
};


text:
Q: Aborting git stash pop I have a repo where I saved a stash on branch B which is ahead of branch A. Then on branch A I popped that stash and now have the problem of merge conflicts
I would very much like to abort the whole operation and perform stash pop on branch b. Is there a simple way to do it?
I do not care about the working copy in my directory too much as it was clean before popping the stash

A: If you don't care about your working copy, you can just git reset --hard back to HEAD to get back to A's most recent actual commit (and then swap to B).

A: You could do a
git stash save stashed_changes_from_b

when you are on branch A. This will create a stash which in essence is the same stash you had when you ran git stash on branch B. Now, A will not be having any of the changes and will be in the state it was before you did git stash pop. You can now do whatever you want with branch A and when you are done and want to pop the stash onto branch B, you simply checkout branch B and do a
 git stash pop.

(I use git stash save  to give my stashes a name because it helps me know at a glance what that stash contains when I run
git stash list.)


text:
Q: Javascript inheritance issue Judging by the # of "javascript inheritance" questions here I am going to assume my question was probably already answered elsewhere and I am just not understanding the other solutions...or javascript in general apparently.
My question is, why does the code below ( http://jsfiddle.net/Se9ZW/2/ ) print "test5" instead of "test1"?
var fake = { value:'test1'};
var fake2=fake;
fake2.value='test5';
document.getElementById('debug').innerHTML=fake.value;

These seems like something that is pretty obvious and so I am kinda embarassed to even be bringing it up but I guess ya gotta learn somehow.

A: fake and fake2 are references to the same object, so it is totally expected that they behave that way. It has nothing to do with inheritance.
Now, if you wanted to inherit, one way (quite naive, I might add) would be to do it like this:
var fake = { value:'test1'};
var fake2 = Object.create(fake); //creates a new object with fake as prototype
fake2.value = 'test5'; // "overrides" the value property from the prototype
console.log(fake.value);

and the output then would be:
test1

Note that this is from ECMAScript Edition 5 - which is fairly recent and may not work in every JavaScript engine implementation out there.
There are several way to implement/use inheritance in JavaScript. I am going to refer you to one of the explanations in accepted answer here.

A: This is because
var fake2 = fake;

creates a reference of fake into fake2. If you change anything in fake2, fake also gets changed.

A: Maybe you're getting confused by terminology? Here's an explanation without the words "reference" and "value":
{ value:'test1'} is a Object. You can think of it like a bucket full of things. In this case, the bucket has one thing inside named value.
On line 1, you're pointing fake to the bucket.
On line 2, you're pointing fake2 to fake. Since fake is just pointing to a bucket, fake2 also points to the exact same bucket.
On line 3, fake2.value is the thing named value in the bucket. fake2.value is the same thing in the same bucket.
Another way to say this same thing is that primitives (think: concrete things) are passed by value, and objects (think: containers and/or buckets) are passed by reference in javascript.

A: Because javascript passes by reference, meaning fake2 is not a copy of fake, it is another name  of fake and in fact the same object.


text: Q: Nueva Política de Cookies 2018 me gustaría saber si a día de hoy es obligatorio mostrar en nuestra web el mensaje de aviso de Cookies como había que hacer anteriormente, porque si mal no he leído, la nueva ley no obliga a tener que mostrar este mensaje cada vez que un usuario accede a nuestra web. Por favor, si hay algún compañero de España y que sepa acerca de este tema, es decir, de como está regulación en España, que me ayude. Muchas gracias.


text:
Q: How to find $\int \frac{f'(x)}{f(x)^2}\,\sin(x) \,dx$? Suppose I have a continuous function $f$ that is always positive over the range of integration and its derivative $f'$. Is there a way to find the following indefinite integral?
$$\int \frac{f'(x)}{f(x)^2}\,\sin(x) \, \mathrm d x$$
Could integration by parts or some clever substitution be used here?

A: Let $g(x)=\frac{1}{f(x)}$ and let us assume that $f(x)$ is positive and differentiable.
The given integral equals
$$\begin{eqnarray*} \int -g'(x)\sin(x)\,dx &\stackrel{\text{IBP}}{=}&C+ g'(x)\cos(x)-\int g''(x)\cos(x)\,dx\\&\stackrel{\text{IBP}}{=}&C+g'(x)\cos(x)-g''(x)\sin(x)+\int g'''(x)\sin(x) \end{eqnarray*}$$
or
$$ C+g'(x)\cos(x)-g''(x)\sin(x)+g'''(x)\cos(x)-g^{(4)}(x)\sin(x)+\ldots $$
provided that this expression actually makes sense.

A: Well, you can also use integration by parts to conclude that
$$\int_a^b \frac{f'(x)}{f(x)^2}\,\sin(x) \, \mathrm d x=\int_a^b \frac{1}{f(x)}\,\cos(x) \, \mathrm d x - \left[\frac{\sin(x)}{f(x)}\right]_a^b,$$
so the problem is simplified if $\int\frac{\cos(x)}{f(x)}\,\mathrm dx$ is easier to calculate.


text:
Q: Obtaining the result of a Mono in order to pass it onto a JpaRepository or another non reactive class I would like to know what is the appropriate way obtaining an object from a Mono (or Flux) to pass onto a non-reactive method such as a JpaRepository.
Here is the way I did it:
@Service
public class ReactiveAccountService {

    //AccountService's methods take non-mono/non-flux objects as arguments
    private AccountService accountService;

    public ReactiveAccountService(AccountService accountService) {
        this.accountService = accountService;
    }

    public Mono<Void> signUp(Mono<Account> accountMono) {
        //Account is a Jpa entity
        accountMono.subscribe(account -> accountService.signUp(account));
        return Mono.empty();
    }

}

How can this be improved? Can someone please advise?

A: The better way to do that is like this:
public Mono<Void> signUp(Mono<Account> accountMono) {
    //Account is a Jpa entity
    return accountMono.flatMap(account -> {
                  accountService.signUp(account);
                  return Mono.empty();
              });
}

This way you follow Reactive Streams requirements and don't bother the execution flow with your blocking code. Plus according the Spring WebFlux requirements you don't subscribe in your own code, but deffer everything to the container which is an initiator of that Mono<Account>. The actual execution will happen, when there is enough resources in the Web (Reactive) container to subscribe to the returned Mono.


text:
Q: Codeigniter rest server enable keys for login process I am using chriskacerguis Rest Server as my backend processor and have recently enabled
$config['rest_enable_keys'] = TRUE;

I created the required table and managed to generate api keys for each user. However, I discovered that I can only use this when a user is already logged in. If they are not, the server returns
{"status":false,"error":"Invalid API key "}

Is there a way to decide when this is activated and default to a standard username password authentication for logging in only?


text:
Q: NSStream for swift works on simulator but not iphone This code works on the simulator, but not on my iphone with ios 10.3.1. It is connecting to a python client.
//
//  ViewController.swift
//  1st robot app
//
//  Created by Tristan Chandraratna on 13/2/17.
//  Copyright © 2017 Tristan Chandraratna. All rights reserved.
//

import UIKit

class ViewController: UIViewController, StreamDelegate {

    //Button
    var buttonConnect : UIButton!

    //Label
    var label : UILabel!
    var labelConnection : UILabel!

    //Socket server
    let addr = "192.168.0.14"
    let port = 9876

    //Network variables
    var inStream: InputStream?
    var outStream: OutputStream?

    //Data received
    var buffer = [UInt8](repeating: 0, count: 200)

    override func viewDidLoad() {
        super.viewDidLoad()

        ButtonSetup()

        LabelSetup()
    }

    //Button Functions
    func ButtonSetup() {
        buttonConnect = UIButton(frame: CGRect(x: 20, y: 50, width: 300, height: 30))
        buttonConnect.setTitle("Connect to server", for: UIControlState())
        buttonConnect.setTitleColor(UIColor.blue, for: UIControlState())
        buttonConnect.setTitleColor(UIColor.cyan, for: UIControlState.highlighted)
        buttonConnect.addTarget(self, action: #selector(ViewController.btnConnectPressed(_:)), for: UIControlEvents.touchUpInside)
        view.addSubview(buttonConnect)

        let buttoniPhone = UIButton(frame: CGRect(x: 20, y: 100, width: 300, height: 30))
        buttoniPhone.setTitle("Send \"This is iPhone\"", for: UIControlState())
        buttoniPhone.setTitleColor(UIColor.blue, for: UIControlState())
        buttoniPhone.setTitleColor(UIColor.cyan, for: UIControlState.highlighted)
        buttoniPhone.addTarget(self, action: #selector(ViewController.btniPhonePressed(_:)), for: UIControlEvents.touchUpInside)
        view.addSubview(buttoniPhone)

        let buttonQuit = UIButton(frame: CGRect(x: 20, y: 150, width: 300, height: 30))
        buttonQuit.setTitle("Send \"Quit\"", for: UIControlState())
        buttonQuit.setTitleColor(UIColor.blue, for: UIControlState())
        buttonQuit.setTitleColor(UIColor.cyan, for: UIControlState.highlighted)
        buttonQuit.addTarget(self, action: #selector(ViewController.btnQuitPressed(_:)), for: UIControlEvents.touchUpInside)
        view.addSubview(buttonQuit)

        let LWslide = UISlider(frame: CGRect(x:0,y:0,width:50,height:300))
        LWslide.maximumValue = Float(1023)
        LWslide.minimumValue = Float(-1023)
        LWslide.value = Float(0)
    }

    func btnConnectPressed(_ sender: UIButton) {
        NetworkEnable()

        buttonConnect.alpha = 0.3
        buttonConnect.isEnabled = false
        buttonConnect.setTitleColor(UIColor.blue, for: UIControlState())
    }
    func btniPhonePressed(_ sender: UIButton) {
        print("sending")
        let data : Data = "This is iPhone".data(using: String.Encoding.utf8)!
        outStream?.write((data as NSData).bytes.bindMemory(to: UInt8.self, capacity: data.count), maxLength: data.count)
        print("sent")
    }
    func btnQuitPressed(_ sender: UIButton) {
        let data : Data = "Quit".data(using: String.Encoding.utf8)!
        outStream?.write((data as NSData).bytes.bindMemory(to: UInt8.self, capacity: data.count), maxLength: data.count)
    }
    //Label setup function
    func LabelSetup() {
        label = UILabel(frame: CGRect(x: 0,y: 0,width: 300,height: 150))
        label.center = CGPoint(x: view.center.x, y: view.center.y+100)
        label.textAlignment = NSTextAlignment.center
        label.numberOfLines = 0 //Multi-lines
        label.font = UIFont(name: "Helvetica-Bold", size: 20)
        view.addSubview(label)

        labelConnection = UILabel(frame: CGRect(x: 0,y: 0,width: 300,height: 30))
        labelConnection.center = view.center
        labelConnection.textAlignment = NSTextAlignment.center
        labelConnection.text = "Please connect to server"
        view.addSubview(labelConnection)
    }

    //Network functions
    func NetworkEnable() {
        print(addr)
        print("NetworkEnable")
        Stream.getStreamsToHost(withName: addr, port: port, inputStream: &inStream, outputStream: &outStream)
        if inStream != nil && outStream != nil{
            inStream!.delegate = self
            outStream!.delegate = self

            inStream!.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
            outStream!.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)

            inStream!.open()
            outStream!.open()
        }
        buffer = [UInt8](repeating: 0, count: 200)
        let data : Data = "iPhone connected".data(using: String.Encoding.utf8)!
        print((data as NSData).bytes.bindMemory(to: UInt8.self, capacity: data.count))
        outStream?.write((data as NSData).bytes.bindMemory(to: UInt8.self, capacity: data.count), maxLength: data.count)
        print("NetworkEnabled")
    }

    func stream(_ aStream: Stream, handle eventCode: Stream.Event) {

        switch eventCode {
        case Stream.Event.endEncountered:
            print("EndEncountered")
            labelConnection.text = "Connection stopped by server"
            inStream?.close()
            inStream?.remove(from: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
            outStream?.close()
            print("Stop outStream currentRunLoop")
            outStream?.remove(from: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
            buttonConnect.alpha = 1
            buttonConnect.isEnabled = true
        case Stream.Event.errorOccurred:
            print("ErrorOccurred")

            inStream?.close()
            inStream?.remove(from: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
            outStream?.close()
            outStream?.remove(from: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
            labelConnection.text = "Failed to connect to server"
            buttonConnect.alpha = 1
            buttonConnect.isEnabled = true
            label.text = ""
        case Stream.Event.hasBytesAvailable:
            print("HasBytesAvailable")

            if aStream == inStream {
                inStream!.read(&buffer, maxLength: buffer.count)
                let bufferStr = NSString(bytes: &buffer, length: buffer.count, encoding: String.Encoding.utf8.rawValue)
                label.text = bufferStr! as String
                print(bufferStr!)
            }

        case Stream.Event.hasSpaceAvailable:
            print("HasSpaceAvailable")
        case Stream.Event():
            print("None")
        case Stream.Event.openCompleted:
            print("OpenCompleted")
            labelConnection.text = "Connected to server"
        default:
            print("Unknown")
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}


text:
Q: Is "when" a conjunction in "I was going to call you when I got home." Is the word "when" a conjunction in:

I was going to call you when I got home.

If it's a conjunction I suppose "when" is usually reduced, what I mean by that is that the vowel in the word "when" is pronounced with a schwa sound. I said usually because I know stress can be shifted for special emphasis. Am I right?

A: Though dictionaries often label "when" as an adverb (So in Oald), the Oxford Guide to English Grammar by John Eastwood says:
We form an adverbial clause of time with a conjunction, eg

*

*Mozart could write music when he was only five. (Paragraph 250)

By the way, you can download this grammar. For more information on this grammar  Link

A:
I was going to call you when I got home.

In the sentence according to the modern grammar when is a preposition. Except a few, modern grammar classifies as preposition all the words that tradition grammar calls subordinating conjunction or simply subordinator. They argue that like verb why a preposition can't take a declarative clause.
A verb as a head can take a NP as complement.

He hit him. [The verb - hit - takes NP - him - as a complement]

But a verb as head can also take a declarative clause as complement, but then grammarians don't call them something else other than a verb.

I remember you promised to help. [The verb - remember - takes a declarative clause - you promised to help - as a complement]

So if a verb is called a verb regardless whether it takes a NP or a declarative clause as complement, then why a preposition to be called a conjunction if it takes a declarative clause as complement. Hence modern grammarians decided to call it a preposition even if they take declarative clause (though they call if, whether etc subordinator).

I was going to call you when I got home.

If we try to explain the POS of when from the point of view of traditional grammar, it's a conjunction, a subordinating conjunction that is. Because it connects two clause.

A: No, it is not a conjunction. Here 'when' is an adverb.

I was going to call you when I got home.

Take for instance the below segment of the sentence:

I was going to call you.

Okay when?

When I got home.

An Adverb is a word that describes or adds more meaning to a verb. Call is the verb here and when is an Adverb of Time.

A: It is a conjunction. Two things happen in the example sentence: first arrive home, and then call, refered to in two clauses and the when connects them.
However, it is a subordinating conjunction (sometimes called a "trigger word") introducing an adverbial clause, and on the principle that words introducing new information take a strong pronunciation the vowel is not reduced to a schwa.
As, when and while are conjunctions. In some uses as, when and while can mean the same, but they can also have slightly different meanings. We use them to introduce subordinate clauses.(From Cambridge "English Grammar Today")
A conjunction (also called a connective) is a word such as and, because, but, for, if, or, and when. Conjunctions are used to connect phrases, clauses, and sentences. (From Oxford Dictionary)
In English, there are lots of subordinating conjunctions, but the most common ones, along with a few examples of how subordinating conjunctions are used, are as follows:
when - "When I see you smile, I can face the world"
(From Your Dictionary)
As well as the coordinating conjunctions noted and explained above, there is a whole raft of subordinating conjunctions. Some of them are:
...
when
....
(From Bristol University Improve Your Writing)
Subordinating conjunctions are used to join independent clauses to make complex sentences. The subordinating conjunctions are as follows: after, although, as, as if, because, before, even if, even though, if, if only, rather than, since, that, though, unless, until, when, where, whereas, wherever, whether, which, and while. (From Purdue OWL)


text:
Q: Video compression on android using new MediaCodec Library In my app I'm trying to upload some videos that the user picked from gallery.
The problem is that usually the android video files are too big to upload and so- we want to compress them first by lower bitrate/ resolution.
I've just heard about the new MediaCodec api that introduce with API 16 (I perviously tried to do so with ffmpeg).
What I'm doing right now is the following:
First decode the input video using a video decoder, and configure it with the format that was read from the input file.
Next, I create a standard video encoder with some predefined parameters, and use it for encoding the decoder output buffer. Then I save the encoder output buffer to a file.
Everything looks good - the same number of packets are written and read from each input and output buffer, but the final file doesn't look like a video file and can't be opened by any video player.
Looks like the decoding is ok, because I test it by displaying it on Surface. I first configure the decoder to work with a Surface, and when we call releaseOutputBuffer we use the render flag, and we're able to see the video on the screen.
Here is the code I'm using:
    //init decoder
    MediaCodec decoder = MediaCodec.createDecoderByType(mime);
    decoder.configure(format, null , null , 0);
    decoder.start();
    ByteBuffer[] codecInputBuffers = decoder.getInputBuffers();
    ByteBuffer[] codecOutputBuffers = decoder.getOutputBuffers();

    //init encoder
    MediaCodec encoder = MediaCodec.createEncoderByType(mime);
    int width = format.getInteger(MediaFormat.KEY_WIDTH);
    int height = format.getInteger(MediaFormat.KEY_HEIGHT);
    MediaFormat mediaFormat = MediaFormat.createVideoFormat(mime, width, height);
    mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, 400000);
    mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 25);
    mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar);
    mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 5);
    encoder.configure(mediaFormat, null , null , MediaCodec.CONFIGURE_FLAG_ENCODE);
    encoder.start();
    ByteBuffer[] encoderInputBuffers = encoder.getInputBuffers();
    ByteBuffer[] encoderOutputBuffers = encoder.getOutputBuffers();

    extractor.selectTrack(0);

    boolean sawInputEOS = false;
    boolean sawOutputEOS = false;
    boolean sawOutputEOS2 = false;
    MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
    BufferInfo encoderInfo = new MediaCodec.BufferInfo();

    while (!sawInputEOS || !sawOutputEOS || !sawOutputEOS2) {
        if (!sawInputEOS) {
            sawInputEOS = decodeInput(extractor, decoder, codecInputBuffers);
        }

        if (!sawOutputEOS) {
            int outputBufIndex = decoder.dequeueOutputBuffer(info, 0);
            if (outputBufIndex >= 0) {
                sawOutputEOS = decodeEncode(extractor, decoder, encoder, codecOutputBuffers, encoderInputBuffers, info, outputBufIndex);
            } else if (outputBufIndex == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
                Log.d(LOG_TAG, "decoding INFO_OUTPUT_BUFFERS_CHANGED");
                codecOutputBuffers = decoder.getOutputBuffers();
            } else if (outputBufIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
                final MediaFormat oformat = decoder.getOutputFormat();
                Log.d(LOG_TAG, "decoding Output format has changed to " + oformat);
            } else if (outputBufIndex == MediaCodec.INFO_TRY_AGAIN_LATER) {
                 Log.d(LOG_TAG, "decoding dequeueOutputBuffer timed out!");
            }
        }

        if (!sawOutputEOS2) {
            int encodingOutputBufferIndex = encoder.dequeueOutputBuffer(encoderInfo, 0);
            if (encodingOutputBufferIndex >= 0) {
                sawOutputEOS2 = encodeOuput(outputStream, encoder, encoderOutputBuffers, encoderInfo, encodingOutputBufferIndex);
            } else if (encodingOutputBufferIndex == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
                Log.d(LOG_TAG, "encoding INFO_OUTPUT_BUFFERS_CHANGED");
                encoderOutputBuffers = encoder.getOutputBuffers();
            } else if (encodingOutputBufferIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
                final MediaFormat oformat = encoder.getOutputFormat();
                Log.d(LOG_TAG, "encoding Output format has changed to " + oformat);
            } else if (encodingOutputBufferIndex == MediaCodec.INFO_TRY_AGAIN_LATER) {
                Log.d(LOG_TAG, "encoding dequeueOutputBuffer timed out!");
            }
        }
    }
            //clear some stuff here...

and those are the method I use for decode/ encode:
    private boolean decodeInput(MediaExtractor extractor, MediaCodec decoder, ByteBuffer[] codecInputBuffers) {
        boolean sawInputEOS = false;
        int inputBufIndex = decoder.dequeueInputBuffer(0);
        if (inputBufIndex >= 0) {
            ByteBuffer dstBuf = codecInputBuffers[inputBufIndex];
            input1count++;

            int sampleSize = extractor.readSampleData(dstBuf, 0);
            long presentationTimeUs = 0;
            if (sampleSize < 0) {
                sawInputEOS = true;
                sampleSize = 0;
                Log.d(LOG_TAG, "done decoding input: #" + input1count);
            } else {
                presentationTimeUs = extractor.getSampleTime();
            }

            decoder.queueInputBuffer(inputBufIndex, 0, sampleSize, presentationTimeUs, sawInputEOS ? MediaCodec.BUFFER_FLAG_END_OF_STREAM : 0);
            if (!sawInputEOS) {
                extractor.advance();
            }
        }
        return sawInputEOS;
    }
    private boolean decodeOutputToFile(MediaExtractor extractor, MediaCodec decoder, ByteBuffer[] codecOutputBuffers,
            MediaCodec.BufferInfo info, int outputBufIndex, OutputStream output) throws IOException {
        boolean sawOutputEOS = false;

        ByteBuffer buf = codecOutputBuffers[outputBufIndex];
        if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
            sawOutputEOS = true;
            Log.d(LOG_TAG, "done decoding output: #" + output1count);
        }

        if (info.size > 0) {
            output1count++;
            byte[] outData = new byte[info.size];
            buf.get(outData);
            output.write(outData, 0, outData.length);
        } else {
            Log.d(LOG_TAG, "no data available " + info.size);
        }
        buf.clear();
        decoder.releaseOutputBuffer(outputBufIndex, false);
        return sawOutputEOS;
    }

    private boolean encodeInputFromFile(MediaCodec encoder, ByteBuffer[] encoderInputBuffers, MediaCodec.BufferInfo info, FileChannel channel) throws IOException {
            boolean sawInputEOS = false;
            int inputBufIndex = encoder.dequeueInputBuffer(0);
            if (inputBufIndex >= 0) {
                ByteBuffer dstBuf = encoderInputBuffers[inputBufIndex];
                input1count++;

                int sampleSize = channel.read(dstBuf);
                if (sampleSize < 0) {
                    sawInputEOS = true;
                    sampleSize = 0;
                    Log.d(LOG_TAG, "done encoding input: #" + input1count);
                }

                encoder.queueInputBuffer(inputBufIndex, 0, sampleSize, channel.position(), sawInputEOS ? MediaCodec.BUFFER_FLAG_END_OF_STREAM : 0);
            }
            return sawInputEOS;
    }

Any suggestion on what I'm doing wrong?
I didn't find too much examples for encoding with MediaCodec just a few samples code for decoding...
Thanks a lot for the help

A: The output of MediaCodec is a raw elementary stream.  You need to package it up into a video file format (possibly muxing the audio back in) before many players will recognize it.  FWIW, I've found that the GStreamer-based Totem Movie Player for Linux will play "raw" video/avc files.
Update:
The way to convert H.264 to .mp4 on Android is with the MediaMuxer class, introduced in Android 4.3 (API 18).  There are a couple of examples (EncodeAndMuxTest, CameraToMpegTest) that demonstrate its use.


text:
Q: problem in setting image over a background image android i have image-view in my xml for setting the image over a background image at a specified place of back ground image i set it for one emulator and it works but when i launch other emulator of different size image-view change it corresponding position with respect to background image so how to set image view over a background image so that imageview not changes its position for any size of screen
i am providing my code ...thanks in advance..
here is my splash.xml file ,button and imageview changes its position w.r.t. background image..for diffrent size screen emulator
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:id="@+id/TheSplashLayout"
  android:layout_gravity="center"
   android:background="@drawable/splashmodified"
  >
    <ImageView
        android:layout_width="60sp"
        android:layout_height="60sp"
        android:id="@+id/SplashImageView"
        android:layout_gravity="center"
        android:layout_marginTop="120sp"
        android:layout_marginLeft="55sp"
        />

    <Button
         android:text="SUBMIT"
         android:id="@+id/submitt"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_marginLeft="75px"
         android:layout_marginTop="300px"
        />
</RelativeLayout>

A: Did not understand the question, you might consider uploading some images and giving us links to them. Only thing I can tell is that you must avoid using px when indicating any dimensions. This will make your views look different on every device, that you probably don't want.

A: use dip instead of px and sp.
Your xml will be
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:id="@+id/TheSplashLayout"
  android:layout_gravity="center"
   android:background="@drawable/splashmodified"
  >
    <ImageView
        android:layout_width="60dip"
        android:layout_height="60dip"
        android:id="@+id/SplashImageView"

        android:layout_marginTop="120dip"
        android:layout_marginLeft="55dip"
        android:background="@drawable/a_thumb"
        />

    <Button
         android:text="SUBMIT"
         android:id="@+id/submitt"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_marginLeft="75dip"
         android:layout_marginTop="300dip"
        />
</RelativeLayout>

Thanks
Deepak


text:
Q: How to change CSS Parameter with JavaScript? I know it is not common way to modify CSS classes... but anyway >> I have the following function to change CSS parameter with JavaScript:
function changeCSSParameter(classId, param, value)
{
  var CSSRules;
  if (document.all)
  {
    CSSRules = 'rules';
  }
  else if (document.getElementById)
  {
    CSSRules = 'cssRules';
  }
  for (var i = 0; i < document.styleSheets[0][CSSRules].length; i++)
  {
    var classes = document.styleSheets[0][CSSRules][i].selectorText.split(/\s*,\s*/);
    for (var j = 0; j < classes.length; j++)
    {
      if (classes[j] == classId)
      {
        document.styleSheets[0][CSSRules][i].style.setProperty(param, value, '');
      }
    }
  }
}

However this function would not work as I wish if style classes are defined in groups, such as
.first, .second
{
  color: red;
}

...because any change would apply to both classes. How can I solve this issue? Please advice.
No jQuery, please, just old-fashion JavaScript.

A: My first question is how sure you are about the inference that the existence of document.all implies that a stylesheet will have a rules property and its nonexistence implies that it will have a cssRules property?  Because that seems rather sketchy to me?  What is it based on?
But assuming that it is a reasonable inference, why in the world are you making that CSSRules calculation on every call to your function?  Calculate it once at start-up and store it, returning your function inside a closure that contains the value.
That said, on to your main problem...
Your code will only work if the individual selectors (inside the comma-separated groups of selectors) are single class selectors such as .myClass.  Anything even slightly more complicated, such as div.myClass won't work, correct?  If that's all you're trying to do, I think I have a (fairly obnoxious, but workable) solution:  On encountering a comma-separated solution where one of them is a match, write new rules for each of the selectors, cloning the existing rule.  Then for the one that matches your class name, change the relevant property.  Finally, remove the original rule.
It's not fun, and it makes several assumptions that are clearly not warranted in the general case, but look like they might match what you're trying to do in your code.
Hey, I did say it was obnoxious!  :-)


text:
Q: Ext.List messes up rows and display after going forward on a view? I have a navigation view that contains a list view with a list of items, and when you click the item it pushes a new list detail page. Everything works fine and dandy, but when I go back to the previous list, it shows up all discombobulated.
I've tested this in Webkit and Mobile webkit browsers and the result is the same. I'm looking for any possible feedback or suggestions that might point me towards a) fixing the problem or b) repainting the window when this happens so it corrects itself.
Example:

Navigation view:
Ext.define('CA.view.speaker.Card', {
  extend: 'Ext.NavigationView',
  xtype: 'xSpeakerCard',

  config: {
    title: "Speakers",
    iconCls: "team",
    autoDestroy: false,

    items: [
      { xclass: 'CA.view.speaker.List' }
    ]
  }

});

List view:
Ext.define('CA.view.speaker.List', {

  extend: 'Ext.List',
  xtype: 'xSpeakerList',

  config: {
    title: "Speaker List",
    store: "Speakers",
    fullscreen: true,
    grouped: true,
    indexBar: true,
    itemTpl: [
        '{first_name} {last_name}'
    ]
  }
});

Detail View being pushed:
Ext.define('CA.view.speaker.Detail', {

  extend: 'Ext.Container',
  xtype: 'xSpeakerDetail',

  config: {
    layout: 'vbox',
    scrollable: 'vertical',
    title: '',
    items: [
      {
      xtype: 'xSpeakerDetailInfo',
      docked: 'top'
    },
    {
      xtype: 'list',
      store: 'SpeakerSessions',
      id: 'speaker-detail-info-session-list',
      flex: 3,
      itemTpl: [
        '{title}'
      ],
      items: [
        {
        xtype: 'listitemheader',
        cls: 'dark',
        html: 'Sessions'
      }
      ]
    }
    ]
  }

});


text:
Q: passing variables to a form using onclick I'm new to javascript and am trying to start somewhat simple. Is it possible to create a function that contains a form object that can be populated by an onclick event?
Right now I have a page with 7 buttons, each button is a submit for a separate form, they all link to the same php file on the backside of my site where they are processed. I would like to somehow create one single form, possibly in a javascript function, that would accept variables from the buttons when clicked and then submit the form to my php script. it will technically function the same as it does now with 7 different forms, one for each button, but will hopefully cut back on the code.
This example is only how I logically thought it might work from a couple of weeks searching around the internet and gathering bits from here and there, but in reality it is far from functional.
example:

A: If I understand you correctly, you have 7 forms with 7 buttons and want to use scripting so that when one of the forms is submitted, you'll copy the values to another form then submit that. I don't see how that will "cut down on the code".
Seems to me like it is increasing the amount of code - forms don't need any scripting at all. You could just use one form with 7 submit buttons, then sort things out on the sever based on the button that was clicked.
Edit
If you use a single form with multiple submit buttons like:
<form action="form.php?action=form_action">
  <input name="foo" value="bar">
  <input type="submit" value="Submit 1" name="Submit 1">
  <input type="submit" value="Submit 2" name="Submit 2">
</form>

then when the first submit is clicked the server will get:
...?foo=bar&Submit+1=Submit+1

and when the second button is clicked it will get:
...?foo=bar&Submit+2=Submit+2

so: one form, multiple submit buttons, no script, the server knows which one was clicked.
Of course you may want to use scripting to enhance the UI, but it isn't needed for the underlying functionality.


text:
Q: VBA ErrorHandler MsgBox Syntax This is a basic question, but I haven't found any solutions after a Google search.
Here's what I'm trying to do:
I can't get the MsgBox to launch properly: it's highlighted in red. I think this is a syntax issue.
Sub DataProcessingExperiment7
On Error GoTo ErrorHandler
...
ErrorHandler
MsgBox("Error detected" & vbNewLine & "Error" & Err.Number & ": " & Err.Description, vbCritical, "Error Handler: Error" & Err.Number, , , asVbMsgBoxResult)

A: You are missing a colon it should be ErrorHandler:

A: You call shouldn't be in parenthesis (brackets) unless you're wanting to return a value. Remove the brackets after msgbox
Sub DataProcessingExperiment7
On Error GoTo ErrorHandler
...

ErrorHandler:
MsgBox "Error detected" & vbNewLine & "Error" & Err.Number & ": " & Err.Description, vbCritical, "Error Handler: Error" & Err.Number, ,

Edit:
And you have too many arguments. Remove one

A: If you just want to show the user a message with an ok button then use:
MsgBox "This is the message", vbCritical, "This is the title"

The only bit you need is the message bit. You can use named parameters, like this (makes it easier to know which bit is what):
MsgBox Prompt:="This is the message", Buttons:=vbCritical, Title:="This is the title"

If you want to give the user a Yes/No, Ok/Cancel choice, then you use MsgBox as a function and store or use the result.
If vbNo = MsgBox(Prompt:="Do you want to continue?",Buttons:=vbQuestion + vbYesNo, Title:="Are you sure?") Then

For your code use:
ErrorHandler:
MsgBox Prompt:="Error detected" & vbNewLine & "Error" & Err.Number & ": " & Err.Description, Buttons:=vbCritical, Title:="Error Handler: Error" & Err.Number


text:
Q: Getting my head around implementations I have an interfaceFileService
And an implementation of it FileServiceBean
I want to be able to process multiple filetypes.
e.g. fileService.processFile(FileDescriptor);
Where, the fileDescriptor is a class e.g.
public class FileDescriptor {
@Column(name = "FILE_TYPE")
protected String fileType;

}
Then I want multiple extensions of the FileServiceBean to process different filetypes.  And FileServiceBean would have all the methods common to all filetypes.
e.g.
PhotoProcessingBean extends FileProcessingBean
VideoProcessingBean extends FileProcesingBean

How do I make the interface decide what implementation to use?  I am rather new to this and not really quite sure how to ask the question to search google for the answer.
Ideally it would not just accept FileDescriptor.  e.g. It could be something else like just File.
fileService.processFile(Object);

A: Well, in the end you have to put the decision logic somewhere, the only question is where?
I think this is a classic application of the factory-pattern: you create an object (the "factory") which has the sole purpose of deciding which concrete implemenation of a common interface to create for a given case. See https://en.wikipedia.org/wiki/Factory_method_pattern
Along the lines of:
PhotoProcessingBean extends FileProcessingBean {...}
VideoProcessingBean extends FileProcesingBean {...}

class FileProcessingFactory {
    public static FileService createFileService(FileDescriptor descriptor) {
        switch(descriptor.getFileType()) {
            case 'Photo': return new PhotoProcessingBean();
            case 'Video': return new VideoProcessingBean();
            default: // do some error handling
        }
    }
}

And using it:
for(FileDescriptor descriptor : /* wherever they come from */) {
    FileService processor = FileProcessingFactory.createFileService(descriptor);
    processor.processFile(descriptor);
}

Sure enough you can also soften up the interface by accepting objects instead of file descriptors. This depends on the concrete application.

A: Assuming you have an interface:
public interface IFileService{
    void processFile();
}

And the FileProcessingBean class that implements this:
public class FileProcessingBean implements IFileService{

    //other code here

    @Override
    public void processFile(){
        //add code for implementation of method
    }
}

If you have two other classes that extend FileProcessingBean:
public class PhotoProcessingBean extends FileProcessingBean{
    @Override
    public void processFile(){
        System.out.println("Processing PHOTO...");
    }
}

public class VideoProcessingBean extends FileProcessingBean{
    @Override
    public void processFile(){
        System.out.println("Processing VIDEO...");
    }
}

If you would like to use it:
//This is an OOP concept called Polymorphism:
IFileService photoProcess = new PhotoProcessingBean();
IFileService videoProcess = new VideoProcessingBean();

Calling photoProcess.processFile(); and videoProcess.processFile() would yield different the implementations:
photoProcess.processFile();
videoProcess.processFile();

And you'll get the following output:
Processing PHOTO...
Processing VIDEO...

Regarding your point about not just accepting FileDescriptor but also 'something else', my recommendation would be to either know exactly what sort of arguments you are expecting, and then either implementing overriding methods or via an interface. It would not be wise to use Object as a method argument as Object is a superclass from which all objects are descendants of. You would essentially be opening the 'floodgates' and potentially run into runtime errors.


text:
Q: Form submit programmatically does not invoke inner function I have the following autocomplete functions. The form gets autosubmitted when a one of suggested values is clicked:
var submitAutocompleteForm = function (event, ui) {
    var $input = $(this);
    $input.val(ui.item.value);
    var $form = $input.parents("form:first");
    $form.submit();
};

var createAutoComplete = function () {
    var $input = $(this);
    var options = {
        source: $input.attr("data-source-autocomplete"),
        select: submitAutocompleteForm,
    };
    $input.autocomplete(options);
};
$("input[data-source-autocomplete]").each(createAutoComplete);

This works just fine. The form has this additional hidden input:
<input id="autocomplete" name="autocomplete" type="hidden" value="False" />

Now, I want change submitAutocompleteForm function to change this input's value to true upon submit:
$form.submit(function (e) {
    $(this).children('#autocomplete').val(true);
});

but this inner function is never invoked. Even tried with a simple alert inside, this also never gets invoked.
What am I doing wrong?
EDIT:
Html code:
@using (Ajax.BeginForm("LoadBook", new { id = Model.CollectionId }, new AjaxOptions
{
    HttpMethod = "POST",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "bookDetailsPlaceHolder",
    OnComplete = "animateBookLoad"
}))
{
    @Html.Hidden("autocomplete", false)

                @Html.TextBox("bookDetails", null, new { @class = "form-control pull-left", @placeholder = "Szukaj tytułu", data_source_autocomplete = Url.Action("Autocomplete") })

                    <button id="addCopySearchBtn" class="btn btn-default" type="submit">

                    </button>

}

Also, I noticed that when I manually hit the submit button, the inner function gets invoked... So it seems to me that $form.submit() submits the form (obviously) but the $form.submit(function () { } actually gets invoked when the form is being submitted.
I'll try to specify whan I need:
I need the submitAutocompleteForm function to submit the value in TextBox, but also to change the hidden input's value. I cannot write something like $('#form").on('submit', function () { } as I do not want input's value to be changed when user manually submits the form.

A: $form.submit(function (e) {
    e.preventDefault();
    $(this).children('#autocomplete').val(true);
});

This stops the form from sending which means the function below will be able to manipulate the form elements. However this means you do have to AJAX the form data via JavaScript or submit the form again.


text:
Q: Unable to connect to Remote Server when we pass credentials as secure string but able to login when we are manually entering the password Unable to connect to Remote Server when we pass credentials as secure string but able to login when we are manually entering the password instead of converting into string.
The script i am using as below
param(

    [string]$ServiceAccount = 'xyz/v-abc',
    [string]$ServiceAccountPassword = '$Kxyz'
)
$pwdSecureString =  $password | ConvertTo-SecureString -AsPlainText -force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $ServiceAccount, $pwdSecureString
$appServer = 'xyz'
Invoke-Command -ComputerName $appServer -ScriptBlock {  Get-service -Name 'WinRM'} -Credential $cred

#The error i am facing is below
[xyz] Connecting to remote server xyz failed with the following error message : The user
name or password is incorrect. For more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo          : OpenError: (xyz) [], PSRemotingTransportException
+ FullyQualifiedErrorId : LogonFailure,PSSessionStateBroke
#I am able to connect to server when i use below command i.e., entering the password while script execution instead of passing the password as $cred
Invoke-Command -ComputerName $appServer -ScriptBlock {  Get-service -Name 'WinRM'} -Credential xyz
Can you please help us in connecting the remote server using invoke-command by passing the password as securedstring


text:
Q: How do I find the most frequent pairing with an item in Python I have a dataframe that shows order transactions but I am struggling to find a way to list down the most frequent purchased pairing with red wine. I saw it somewhere before but I can't seem to recall how to.
import pandas as pd
df_orders = pd.DataFrame(
    {'Order':[300,300,301,301,301,302,302,303,303],
    'Item':['Red wine','Chicken chop','Red wine',
            'Hawaiian Pizza','Garden Salad','Chicken chop',
            'Mineral Water','Garden Salad','Red wine']})

   Order           Item
0   300        Red wine
1   300    Chicken chop
2   301        Red wine
3   301  Hawaiian Pizza
4   301    Garden Salad
5   302    Chicken chop
6   302   Mineral Water
7   303    Garden Salad
8   303        Red wine

My aim is to find the most frequent items that is ordered at the same time as red wine.
Intended output:
              Item
0     Garden Salad     2
1     Chicken chop     1
2   Hawaiian Pizza     1

I tried using groupby, counter and a few other stuff but didn't get the desired output. Hopefully someone better than me can help me with this. Thank you.

A: Filter only order numbers which has 'Red wine' and then use Series.value_counts to count items.
df[df.Order.isin(df[df.Item == 'Red wine'].Order)].Item.value_counts().drop('Red wine')

A: Normally the advice is to not loop over a DataFrame. So if your DataFrame becomes larger this is probably not an efficient solution.
How I handled it was to go over each unique order. From all the orders collect all items. Check if "Red wine" was one of the items. If so add the other items to the dictionary.
Later transform the dictionary back to a DataFrame.
d = dict()

for order in set(df_orders.Order):
    items = list(df_orders[df_orders.Order == order].Item)
    if 'Red wine' in items:
        for it in items:
            if it != 'Red wine':
                if it in d.keys():
                    d[it] += 1
                else:
                    d[it] = 1
output = pd.DataFrame(d.items(), columns=['item', 'count'])

print(output)
             item  count
0    Chicken chop      1
1  Hawaiian Pizza      1
2    Garden Salad      2

A: You might consider using a filter and group by as following
orders_with_red_wine = df_orders[
    df_orders["Item"].eq("Red wine")]["Order"].unique()

df_orders[
    df_orders["Item"].ne("Red wine") &
    df_orders["Order"].isin(orders_with_red_wine)]\
    .groupby("Item").size()\
    .sort_values(ascending=False)\
    .reset_index(name="count")

Output
             Item  count
0    Garden Salad      2
1  Hawaiian Pizza      1
2    Chicken chop      1

Explanation

*

*We first get all orders that include "Red wine" as orders_with_red_wine.

*Then we consider only these orders and we exclude the Items "Red wine"

df_orders[
    df_orders["Item"].ne("Red wine") &
    df_orders["Order"].isin(orders_with_red_wine)]

*

*Finally it's just a matter of grouping by Item and counting.

A: I did this in two steps without looping, one selecting the 'Red wine' order numbers, then filtering to those orders and removing the 'Red wine' rows, then using value_counts to produce the frequency table, and finally some renaming to match your desired output
>>> orders = df_orders.loc[data['Item'] == 'Red wine']['Order'].values

>>> orders
array([300, 301, 303])

>>> data.loc[df_orders['Order'].isin(orders) & ~df_orders['Item'].eq('Red wine')]
        .Item
        .value_counts()
        .rename_axis('item')
        .reset_index(name='counts')

             item  counts
0    Garden Salad       2
1  Hawaiian Pizza       1
2    Chicken chop       1

A: If you just want to count the frequency of a column, you can set it as index and use index.value_counts() on it.
# reset index and save to new DataFrame
df = df_orders.reset_index()

# set index to 'Item' column
df1 = df.set_index('Item')

# get orders, where 'Red wine' is purchased at same time
orders = df1.loc['Red wine']['Order']

# set index to 'Order' column, filter with the orders selected above
df2 = df.set_index('Order').loc[orders]

# reset index to Item again
res = df2.reset_index().set_index('Item')

# optional: remove 'Red wine' if you don't want to show them
res = res.loc[res.index != 'Red wine']

# call index method value_counts
ret = res.index.value_counts()

# print your result: Orders includes 'Red wine' and list the frequency of other items bought together
print(ret)

You can also use index.value_counts(normalize=True) to return relative frequency by dividing all values by the sum of values.
PS: API to pandas.Index.value_counts()


text:
Q: Angular 2 - Input mask: Input box display formatted value, while model retains unformatted value I'm trying to have an input field format/mask values as they are typed, while having the actual model retain the raw (or differently formatted) value.  I'm thinking phone numbers etc, but for simplicity am using uppercase for testing.
I've tried a bunch of stuff, hoping its as simple as a directive.  But can't seem to get the display value to depart from the form value.
plunk: http://plnkr.co/edit/VH5zn4S8q28CBpFutBlx?p=preview
Here's the directive:
@Directive({
  selector: '[uppercase]',
  host: {
    '(input)': 'onInputChange()',
  }
})

export class UppercaseDirective {

  constructor(private model: NgFormControl) { }

  onInputChange() {
    let newValue = this.model.value.toUpperCase();
    this.model.viewToModelUpdate(newValue);
    this.model.valueAccessor.writeValue(newValue);
  }

}

and the form:
<form [ngFormModel]='myForm'>
  <input [ngFormControl]='myForm.controls.field' uppercase>

    {{ myForm.value.field }}

</form>

A: Try to update control reference directly like this:
onInputChange() {
  let newValue = this.model.value.toUpperCase();
  this.model.control.updateValue(newValue);
}

See also plunker http://plnkr.co/edit/XYPWYgA8lbg2EdxPqzWj?p=preview

A: To be honest, i am still learning angular2 and the tech is still really immature to say this is the best way of doing it but after playing around with it:
import {Directive, ElementRef, Output, EventEmitter} from '@angular/core';
import {NgFormControl} from '@angular/common';

@Directive({
  selector: '[uppercase]',
  host: {
    '(input)': 'onInputChange()',
  }
})

export class UppercaseDirective {

  @Output() onChange = new EventEmitter();
  rawValue: string = '';

  constructor(private model: NgFormControl, private elementRef: ElementRef) { }

  onInputChange() {
    let str = this.model.value;
    this.rawValue = this.rawValue.substring(0, str.length) + str.substring(this.rawValue.length, str.length);
    let newValue = this.rawValue.toUpperCase();
    this.model.viewToModelUpdate(newValue);
    this.model.valueAccessor.writeValue(newValue);
    this.onChange.emit(this.rawValue);
  }

}

then you can get it like this:
<input [ngFormControl]='myForm.controls.field' uppercase (onChange)="raw = $event">

   {{ raw }}

Since whenever you update the model, the variable will change. You have to do is separate. Tried it in your plnkr and it worked.
EDIT:
Might need some work for different scenarios though haha


text:
Q: How can I convert password string to Base64 string before sending form to backend? I have a sample registration form, it works properly for most cases, but when I try to register new user with password "U8$&#6G#CBj" I'm getting an exception "A potentially dangerous Request.Form value was detected from the client"
My idea is to convert password to Base64 format before sending it to backend and on backend convert it back. How can I do it?
@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
     {
        @Html.AntiForgeryToken()

Use a local account to log in.

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

           @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })

              @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
              @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })

           @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })

              @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
              @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })

                 @Html.CheckBoxFor(m => m.RememberMe)
                 @Html.LabelFor(m => m.RememberMe)

              <input type="submit" value="Log in" class="btn btn-default" />

           @Html.ActionLink("Register as a new user", "Register")

        @* Enable this once you have account confirmation enabled for password reset functionality *@

           @Html.ActionLink("Forgot your password?", "ForgotPassword")

     }

A: With help of Alexei Levenkov for frontend part and Vidhyadhar Galande for backend I solved my problem here is the code:
on View to form I have added this javascript function on submit event
function encode(){
        $('#Password').val(btoa($('#Password').val()));
        $('#ConfirmPassword').val(btoa($('#ConfirmPassword').val()));
    }

and on backend decode strings back:
private string DecodeFromBase64(string inputBas64)
{
    var base64EncodedBytesPassword = System.Convert.FromBase64String(model.Password);
    string password = System.Text.Encoding.UTF8.GetString(base64EncodedBytesPassword);
    return password;
}

A:
Try this

1) base64(Encode/decode)
 public static string base64Encode(string sData) // Encode
 {
   try
    {
       byte[] encData_byte = new byte[sData.Length];
       encData_byte = System.Text.Encoding.UTF8.GetBytes(sData);
       string encodedData = Convert.ToBase64String(encData_byte);
       return encodedData;
    }
   catch (Exception ex)
   {
       throw new Exception("Error in base64Encode" + ex.Message);
   }
 }

public static string base64Decode(string sData) //Decode
 {
    try
    {
      var encoder = new System.Text.UTF8Encoding();
      System.Text.Decoder utf8Decode = encoder.GetDecoder();
      byte[] todecodeByte = Convert.FromBase64String(sData);
      int charCount = utf8Decode.GetCharCount(todecodeByte, 0, todecodeByte.Length);
      [] decodedChar = new char[charCount];
      utf8Decode.GetChars(todecodeByte, 0, todecodeByte.Length, decodedChar, 0);
      string result = new String(decodedChar);
      return result;
   }
  catch (Exception ex)
   {
      throw new Exception("Error in base64Decode" + ex.Message);
    }
}

2) EncodePasswordMd5

 public static string EncodePassword(string pass, string salt) //encrypt password
   {
      byte[] bytes = Encoding.Unicode.GetBytes(pass);
      byte[] src = Encoding.Unicode.GetBytes(salt);
      byte[] dst = new byte[src.Length + bytes.Length];
      System.Buffer.BlockCopy(src, 0, dst, 0, src.Length);
      System.Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
      HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
      byte[] inArray = algorithm.ComputeHash(dst);
      //return Convert.ToBase64String(inArray);
      return EncodePasswordMd5(Convert.ToBase64String(inArray));
   }
  public static string EncodePasswordMd5(string pass) //Encrypt using MD5
   {
      Byte[] originalBytes;
      Byte[] encodedBytes;
      MD5 md5;
      //Instantiate MD5CryptoServiceProvider, get bytes for original password and compute hash (encoded password)
      md5 = new MD5CryptoServiceProvider();
      originalBytes = ASCIIEncoding.Default.GetBytes(pass);
      encodedBytes = md5.ComputeHash(originalBytes);
      //Convert encoded bytes back to a 'readable' string
      return BitConverter.ToString(encodedBytes);
  }

@Using Namespace

  using System;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;


text:
Q: How to override a vendor Process class? I'm trying to understand how to override a __construct in Process class. By default, construct only accepts an array as first parameter:
public function __construct(array $command, string $cwd = null, array $env = null, mixed $input = null, ?float $timeout = 60)

But I need for it to accepty strings aswell, which means something like this
public function __construct(array|string $command, string $cwd = null, array $env = null, mixed $input = null, ?float $timeout = 60)

Only overriding is accepted for solution tho, nothing else.
I need this because of Behat tests, since when I run them, I get error "Process::__construct(): Argument #1 ($command) must be of type array, string given"

A: As one option, you can change the incoming arguments by creating your own class extends the Process component:
use Symfony\Component\Process\Process;

class CustomProcess extends Process
{

    public function __construct(array|string $command, string $cwd = null, array $env = null, $input = null, ?float $timeout = 60)
    {
        if(is_string($command)){
            $command = [$command]; // do something with a string
        }
        parent::__construct($command, $cwd, $env, $input, $timeout);
    }
}

Then create an instance of your class in your controller like so:
$command = new CustomProcess('you command');
$command->run();


text:
Q: in c++ when overloading the cin and cout operators in a public class i get these errors this is the code
friend ostream& operator <<(ostream& output, const User& u)
        {
            output << endl << "User name :" << u.name << endl << "User id :" << u.id << endl << "User age :" << u.age << endl << "User email :" << u.email << endl << "User password :" << u.password << endl;
        }
        friend istream& operator >>(istream& input, User& u)
        {
            input >> u.name >> u.age >> u.email >> u.password;
        }

and this is the error visual studio gives me
77.cpp(94): error C4716: 'operator>>': must return a value
77.cpp(90): error C4716: 'operator<<': must return a value

A: Your function signatures indicate that they're returning a value (as they should), but you're not returning anything.
Return the result of the expression that you're outputting with, so other code can use chain the use of operator<< or operator>>.
Ex:
friend ostream& operator <<(ostream& output, const User& u)
{
    return output << endl << "User name :" << u.name << endl << "User id :" << u.id << endl << "User age :" << u.age << endl << "User email :" << u.email << endl << "User password :" << u.password << endl;
}

Alternatively, you can simply add a return at the end:
friend ostream& operator <<(ostream& output, const User& u)
{
    output << endl << "User name :" << u.name << endl << "User id :" << u.id << endl << "User age :" << u.age << endl << "User email :" << u.email << endl << "User password :" << u.password << endl;
    return output;
}


text:
Q: Disable selecting a range in JTextPane I have a JTextPane that i want the user to be able to edit normally, but i don't want the user to select a range of characters; i just want a cursor.  How would i do this?  Using JTextPane's setSelectionStart and setSelectionEnd works most of the time, but not always.
boolean selectionAlreadyHandled = false;
JTextPane jtextpane;

public void caretUpdate (CaretEvent evt)
  {
  if (selectionAlreadyHandled)
    {
    selectionAlreadyHandled = false;
    return;
    }

  int pos = evt.getDot();
  if (pos != evt.getMark())
    {
    selectionAlreadyHandled = true;
    if (pos < evt.getMark())
      jtextpane.setSelectionEnd(pos);
    if (pos > evt.getMark())
      jtextpanel.setSelectionBegin(pos);
    }

  //Event handling
  return;
  }

A: This should probably do it. And if it doesn't, I don't know if anything will

public class MyTextPane extends JTextPane {
  public void setSelectionStart(int spot) {
    super.setSelectionStart(spot);
    super.setSelectionEnd(spot);
  }

  public void setSelectionEnd(int spot) {
    super.setSelectionStart(spot);
    super.setSelectionEnd(spot);
  }

  public void select(int start, int end) {
    super.select(start, start);
  }
}