text:
Q: Is there a way to generate emails on Exchange with past sent/received dates We have a component that grabs emails/meetings from Exchange (Online, 2013, 2010) and we'd like to create email distribution in the past timeframe e.g. 6 month for testing purposes.
In order to achieve this we definitely need emails that have received/Sent dates to be in the past, not started from current (from generation moment) time when we started email generation.
We looked at EWS API - it does not support changing of the dates for created (generated) emails.
What other options exists?

A: You can create an Email with EWS that looks like it was received in the past if you change the Extended properties on the message eg
        EmailMessage OldMessage = new EmailMessage(service);
        OldMessage.ToRecipients.Add("user@domain.com");
        OldMessage.Sender= new EmailAddress("bob@domain.com");
        OldMessage.From = new EmailAddress("bob@domain.com");
        OldMessage.Subject = "This is an old message";
        OldMessage.Body = new MessageBody("test");
        ExtendedPropertyDefinition PR_Flags = new ExtendedPropertyDefinition(3591,MapiPropertyType.Integer);
        OldMessage.SetExtendedProperty(PR_Flags,1);
        ExtendedPropertyDefinition PR_CLIENT_SUBMIT_TIME = new ExtendedPropertyDefinition(0x0039,MapiPropertyType.SystemTime);
        ExtendedPropertyDefinition PR_MESSAGE_DELIVERY_TIME = new ExtendedPropertyDefinition(0x0E06,MapiPropertyType.SystemTime);
        OldMessage.SetExtendedProperty(PR_CLIENT_SUBMIT_TIME,DateTime.Now.AddMonths(-6));
        OldMessage.SetExtendedProperty(PR_MESSAGE_DELIVERY_TIME,DateTime.Now.AddMonths(-6));
        OldMessage.Save(WellKnownFolderName.Inbox);

You can also just import a message using the MimeContent that would do the same thing eg https://msdn.microsoft.com/en-us/library/office/dn672319(v=exchg.150).aspx
Cheers
Glen


text:
Q: Implementation of remote() I'm trying to find the implementation of remote(), as in:
remote()->transact(CODE, data, &reply);

Do you guys know where it is? Searching Google turned out futile.
Or if you know what that function does, it would be a big help for me.
Many thanks
Update: it seems remote() will return a pointer to an object of type BBinder, IBinder, BpBinder, or IPCThreadState but I'm not sure which one.

A: The implementation of remote is simple:
class BpRefBase : public virtual RefBase
{
protected:
                            BpRefBase(const sp<IBinder>& o);
    virtual                 ~BpRefBase();
    virtual void            onFirstRef();
    virtual void            onLastStrongRef(const void* id);
    virtual bool            onIncStrongAttempted(uint32_t flags, const void* id);

    inline  IBinder*        remote()                { return mRemote; }
    inline  IBinder*        remote() const          { return mRemote; }

private:
                            BpRefBase(const BpRefBase& o);
    BpRefBase&              operator=(const BpRefBase& o);

    IBinder* const          mRemote;
    RefBase::weakref_type*  mRefs;
    volatile int32_t        mState;
};

The ServiceManager will manage all the registered service, for how it works, check an existing answer. When you getService from ServiceManager, it will return an IBinder object represents that service, then this IBinder object will be put into a BpInterface. That is your remote. Then you can use that BpInterface to start binder transaction with the actual service(BnInterface).
template<typename INTERFACE>
class BpInterface : public INTERFACE, public BpRefBase
{
public:
                                BpInterface(const sp<IBinder>& remote);

protected:
    virtual IBinder*            onAsBinder();
};

All familiar BpXXX like BpCamera, BpCameraService extends from BpInterface.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Добавляю один код на сайт, перестаёт работать другой Здравствуйте, помогите решить проблему. Я в программировании вообще полный ноль, но постараюсь описать. На сайте discontica.ru есть счётчик отсчёта времени до завершения акции, когда добавляю форму подписки от smartresponder, счётчик перестаёт отображаться. ошибка из консоли Хрома

Uncaught TypeError: Object [object Object] has no method 'countdown'
(anonymous function)
p.fireWith
e.extend.ready
c.addEventListener.B

Код смартреспондера
_sr(function() {
    _sr('form[name="SR_form_133596_7"]').find('div#sr-preload_').prop('id', 'sr-preload_133596_7');
    _sr('#sr-preload_133596_7').css({'width':parseInt(_sr('form[name="SR_form_133596_7"]').width() + 'px'), 'height':parseInt(_sr('form[name="SR_form_133596_7"]').height()) + 'px', 'line-height':parseInt(_sr('form[name="SR_form_133596_7"]').height()) + 'px'}).show();
    if(_sr('form[name="SR_form_133596_7"]').find('input[name="script_url_133596_7"]').length) {
        _sr.ajax({
            url: _sr('input[name="script_url_133596_7"]').val() + '/' + (typeof document.charset !== 'undefined' ? document.charset : document.characterSet),
            dataType: "script",
            success: function() {
                _sr('#sr-preload_133596_7').hide();
            }
        });
    }
});

Код счётчика
(function($) {
$.fn.countdown = function (date, options) {
    options = $.extend({
        lang: {
            years:   ['год', 'года', 'лет'],
            months:  ['месяц', 'месяца', 'месяцев'],
            days:    ['день', 'дня', 'дней'],
            hours:   ['час', 'часа', 'часов'],
            minutes: ['минута', 'минуты', 'минут'],
            seconds: ['секунда', 'секунды', 'секунд'],
            plurar:  function(n) {
                return (n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
            }
        },
        prefix: "Осталось: ",
        finish: "Всё"
    }, options);

    var timeDifference = function(begin, end) {
        if (end < begin) {
            return false;
        }
        var diff = {
            seconds: [end.getSeconds() - begin.getSeconds(), 60],
            minutes: [end.getMinutes() - begin.getMinutes(), 60],
            hours: [end.getHours() - begin.getHours(), 24],
            days: [end.getDate()  - begin.getDate(), new Date(begin.getYear(), begin.getMonth() + 1, 0).getDate()],
            months: [end.getMonth() - begin.getMonth(), 12],
            years: [end.getYear()  - begin.getYear(), 0]
        };
        var result = new Array();
        var flag = false;
        for (i in diff) {
            if (flag) {
                diff[i][0]--;
                flag = false;
            }
            if (diff[i][0] < 0) {
                flag = true;
                diff[i][0] += diff[i][1];
            }
            if (!diff[i][0]) continue;
            result.push(diff[i][0] + ' ' + options.lang[i][options.lang.plurar(diff[i][0])]);
        }
        return result.reverse().join(' ');
    };
    var elem = $(this);
    var timeUpdate = function () {
        var s = timeDifference(new Date(), date);
        if (s.length) {
            elem.html(options.prefix + s);
        } else {
            clearInterval(timer);
            elem.html(options.finish);
        }
    };
    timeUpdate();
    var timer = setInterval(timeUpdate, 1000);
};

})(jQuery);
Надеюсь, что выложил именно те куски, которые нужны. Заранее благодарен откликнувшимся.
A: Может быть у вас такая же проблема как тут: Конфликт формы Smartresponder с плагинами в WordPress


text:
Q: Highcharts - How can I show arrow in "solidgauge"? I want to show arrow like speedometer in Highcharts solidgauge graph. Is it possible?

Plugin Link: http://www.highcharts.com/demo/gauge-solid
Version: 4.1.9

A: Given the example from http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/gauge-solid/
you just have to add a second Series with the type 'gauge' like this:
{
  name: 'Whatever',
  type: 'gauge',
  data: [80]
}

JSFiddle: http://jsfiddle.net/doc_snyder/j5owogor/


text:
Q: Processing: Simultaneous drawing of random particle trajectories class loc {
float[] x;
float[] y;
float v_o_x, v_o_y;

float[] locationx = new float[0];
float[] locationy = new float[0];

loc(float x_o, float y_o, float v_o, float theta, int t_end) {

theta = radians(theta);

v_o_x = v_o_x = v_o * cos(theta);

v_o_y = abs(v_o) * sin(theta);

for (int i=0; i<t_end; i++) {
  locationx = append(locationx, (v_o_x * i + x_o));
  locationy = append(locationy, (0.5*10*pow(i, 2) - v_o_y*i + y_o));
}

this.x = locationx;
this.y = locationy;
}
}

loc locations;

int wait = 75; // change delay between animation
int i = 0;
int j = 0;

float randV = random(-70, 70);
float randAng = random(30, 50);

int len = 17;

void setup() {

  size(1500, 800);

  background(255);
}

void draw() {

  fill(0);

  int d = 20; // diameter

  float[] xx, yy;

  if (i < len) {

    locations = new loc(width/2, height/3.5, randV, randAng, len);

    xx = locations.x;
    yy = locations.y;

    //background(255);
    rect(width/2-d, height/3.5+d, d*2, d*2);

    float s = 255/locations.x.length;
    fill((0+i*s));
    ellipse(xx[i], yy[i], d, d);

    i += 1;

    delay(wait);
  } else {
    randV = random(-70, 70);
    randAng = random(30, 50);
    i = 0;
  }
}

I have a simple code written that animates the trajectory of a ball for a random initial angle and velocity. As it currently runs, it will send one ball out, wait for it to land, and then send another random ball out. My hopes are to get it to simultaneously send out multiple random balls, to create a sort of fountain effect. I have had a lot of trouble getting it to do that, any suggestions?

A: Right now you've got some variables that represent the position (and past positions) of a single ball. For the sake of the question, I'll ignore for a second that you don't ever seem to use some of those variables.
You could copy all of those variables and repeat them for every ball you want. You would have ballOneLocations, ballTwoLocations, etc.
But that's pretty horrible, so you should wrap all of those variables up into a Ball class. Each instance of Ball would represent a separate ball and its past locations.
Then all you'd need to do is create an array or an ArrayList of Ball instances, and loop through them to update and draw them.
Here is a tutorial on how to use OOP in Processing to create multiple balls bouncing around the screen.

A: Agreed with Kevin Workman, classes are the way to go here.
One of the best resources for this stuff is Daniel Shiffman, particularly his book Nature of Code. Your question is dealt with in the Particle Systems chapter (Chapter 4).


text:
Q: locate Eclipse's Preferences menu item programmatically in OS X In Windows/Linux, I use WorkbenchWindow.getMenuManager() to navigate to the Windows menu and locate the Preferences menu item. In OS X, the Preferences menu item is located in Eclipse's application pulldown menu. What is the API to locate the Preference item in OS X? Thanks!

A: The actions for Preferences (and Help About and Quit) are still added in the normal places on the Mac but the action is marked as not visible (code is in WorkbenchActionBuilder).
The Mac only code CocoaUIHandler sets up the Mac only menu items, it just searches for the hidden actions when the action is invoked.
So you may not need to do anything special for the Mac.
Note: WorkbenchWindow is an internal class so it isn't part of the official API, this is probably not a concern for testing code (it is very substantially different between Eclipse 3.x and 4.x).


text:
Q: DB2 SQL Split Record by Delimiter if exists I would like to return the portion of a string BEFORE a delimiter (in this case, a hyphen). What I find is that DB2 is throwing an error because there's an inconsistency in the values of the column where some records have a hyphen meanwhile others do not. So, I'd like to return the string before hyphen if it exists, otherwise just return the string as is.
Example shown with COLUMN1 below:

ID
COLUMN1

1
ASHJE-JFE

2
QER-SK

3
KSETK

4
SDJ-EJLF

I wrote the following query to return the string prior/before '-' but, I get the following error:

The statement was not executed because a numeric argument of a scalar
function is out of range.

I believe this is because there are records where a hyphen does not exist...
select distinct column1, locate('-',column1), substr(column1,1, (locate('-',column1) - 1)) from db2.table
where column1 is not null
fetch first 25 rows only
with ur

Does anyone know how to accomplish something similar but return the string as is when a hyphen does not exist? Thank you!

A: You may use the following expression:
SUBSTR (COLUMN1, 1, COALESCE (NULLIF (LOCATE ('-', COLUMN1), 0) - 1, LENGTH (COLUMN1)))

A: You can use a CASE statement to search for the hyphen along with a LIKE operator and % wildcards.
SELECT ID, column1,
CASE WHEN column1 LIKE '%-%'
THEN substr(column1,1,locate('-',column1)-1)
ELSE column1
END AS column2
FROM fileName
WHERE column1 IS NOT NULL
FETCH FIRST 25 ROWS ONLY

See Fiddle
Result:

ID
COLUMN1
COLUMN2

1
ASHJE-JFE
ASHJE

2
QER-SK
QER

3
KSETK
KSETK

4
SDJ-EJLF
SDJ


text:
Q: SQL count show 0 if no rows including where condition I'm doing a COUNT but cannot get the value 0 when there are no rows in the result.
If I remove the where condition:
AND documentstats.OPENINGDATE >= '2021-01-01T00: 00: 00.000'

it works fine and I get the value 0 when there are no rows in the result.
I am looking for an option to return value 0 in the NumberOfViews column when no rows are found in my count.
Can anyone help me?
SELECT
    customertodocument.DocId,
    COUNT (documentstats.DocId) AS NumberOfViews
FROM
    customertodocument
LEFT JOIN
    documentstats ON customertodocument.DocId = documentstats.DocId
                  AND customertodocument.customerId = documentstats.customerId
WHERE
    customertodocument.customerId = '1111'
    AND documentstats.openingdate >= '2021-01-01T00:00:00.000'
GROUP BY
    customertodocument.DocId
ORDER BY
    NumberOfViews ASC

A: The second condition in the WHERE clause is filtering out all non-matches.  Because you have an explicit GROUP BY, the query will return no rows if the FROM clause has no rows.
If you want counts of 0, then move the condition to the ON clause of the LEFT JOIN.  Note:  Conditions on the second table go in the ON clause.
The query should look like:
SELECT cd.DocId, COUNT(ds.DocId) AS NumberOfViews
FROM customertodocument cd LEFT JOIN
     documentstats ds
     ON cd.DocId = ds.DocId AND
        cd.customerId = ds.customerId AND
        ds.openingdate >= '2021-01-01'
WHERE ds.customerId = 1111
GROUP BY cd.DocId
ORDER BY NumberOfViews ASC;

Notes:

*

*Table aliases make the query easier to write and to read.

*customerId looks like a number.  If it is, then the comparison should be to a number.  If the id is really a string, put the single quotes back in.

*You have a date constant.  There is no need to include the time.  No real harm, except it clutters the query.

A: My guess is that there are no records in the data that meet both of the conditions. You are grouping by customertodocument.DocId, but if no values of customertodocument.DocID exist after filtering with the WHERE clause, the aggregation will have nothing to group by and you'll get no results. You can test this by running the following query:
SELECT *
FROM customertodocument
LEFT JOIN documentstats on customertodocument.DocId = documentstats.DocId and customertodocument.customerId = documentstats.customerId
WHERE customertodocument.customerId = '1111' AND documentstats.openingdate >= '2021-01-01T00:00:00.000'

A: your WHERE condition returns nothing so you are not getting any record. Count alone in select clause can give you 0 but you have one column and then count so you are not getting any record
What value you are expecting in the customertodocument.DocId if no matching record found.
You can get the 0 count if you remove the customertodocument.DocId from select clause keeping only count in select clause and removing the GROUP BY clause


text:
Q: How do I convert a hex array into a UIImage? There are several unanswered questions related to printing images dynamically with P25mi, none with accepted answers. A couple links below.
How to convert image to bitmap code for bluetooth print in iphone
How to convert image into hexa decimal bytes array to send it to output stream in iOS sdk
The code sample below is a hard-coded working example that prints a static image to p25mi. The first 10 elements in the array are control and format commands for the p25.
I think converting the hex array below into a UIImage displayable in a UIImageView might shed some light on doing the reverse.
How do I determine the height, width and depth of the image represented in the code sample below?
How do I convert the hex array below into a UIImage?
unsigned char buffer3[796]={
    0x55 ,  0x66 ,  0x77 ,  0x88 ,  0x44 ,  0x1B ,  0x58 ,  0x31 ,
    0x19, 0x20,
    0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
    ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
    ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
    ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
    ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
    ,0x00 ,0x00 ,0x00 ,0x80 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
    ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x01 ,0xC0 ,0x00
    ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
    ,0x00 ,0x00 ,0x00 ,0x00 ,0x01 ,0x80 ,0x00 ,0x03 ,0x60 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
    ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x03
    ,0xA0 ,0x00 ,0x07 ,0xB0 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
    ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x05 ,0x60 ,0x00 ,0x07 ,0xD8 ,0x00
    ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
    ,0x00 ,0x00 ,0x00 ,0x00 ,0x05 ,0xA0 ,0x00 ,0x13 ,0xEC ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
    ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x04
    ,0x20 ,0x00 ,0x29 ,0xF4 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
    ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x03 ,0xC0 ,0x00 ,0x64 ,0xF9 ,0x00
    ,0x0F ,0xFF ,0x9C ,0x01 ,0xC0 ,0x19 ,0xFF ,0xC0 ,0x7F ,0xFC ,0x7F ,0xF9 ,0xC0 ,0x3D ,0xFF
    ,0xF1 ,0xFF ,0xE3 ,0xFF ,0xC0 ,0x00 ,0x00 ,0xF2 ,0x73 ,0x80 ,0x0F ,0xFF ,0x9C ,0x01 ,0xC0
    ,0x19 ,0xFF ,0xC0 ,0x7F ,0xFE ,0x7F ,0xFD ,0xE0 ,0x3D ,0xFF ,0xF1 ,0xFF ,0xE3 ,0xFF ,0xC0
    ,0x00 ,0x00 ,0x79 ,0x26 ,0xC0 ,0x0F ,0xFF ,0xDC ,0x01 ,0xC0 ,0x19 ,0xFF ,0xC0 ,0x7F ,0xFE
    ,0xFF ,0xFD ,0xF0 ,0x7D ,0xFF ,0xFB ,0xFF ,0xF7 ,0xFF ,0xE0 ,0x00 ,0x03 ,0x3C ,0x8F ,0x60
    ,0x0C ,0x01 ,0xDC ,0x01 ,0xC0 ,0x19 ,0x80 ,0x00 ,0x70 ,0x0E ,0xE0 ,0x1D ,0xF0 ,0x7D ,0x80
    ,0x3B ,0x80 ,0x77 ,0x00 ,0xE0 ,0x00 ,0x04 ,0x9E ,0x8F ,0xB0 ,0x0E ,0x01 ,0xDC ,0x01 ,0xC0
    ,0x19 ,0x80 ,0x00 ,0x70 ,0x0E ,0xE0 ,0x1D ,0xF8 ,0xFD ,0x80 ,0x33 ,0x80 ,0x77 ,0x00 ,0xE0
    ,0x00 ,0x0E ,0x4F ,0x27 ,0xD8 ,0x0F ,0xFF ,0x9C ,0x01 ,0xC0 ,0x19 ,0xFF ,0xC0 ,0x7F ,0xFC
    ,0xE0 ,0x1D ,0xF9 ,0xFD ,0xFF ,0xF3 ,0x80 ,0x77 ,0x00 ,0xE0 ,0x00 ,0x0F ,0x26 ,0x53 ,0xC8
    ,0x0F ,0xFF ,0x9C ,0x01 ,0xC0 ,0x19 ,0xFF ,0xC0 ,0x7F ,0xFC ,0xEF ,0xFD ,0xDD ,0xDD ,0xFF
    ,0xF3 ,0x80 ,0x77 ,0x00 ,0xE0 ,0x00 ,0x07 ,0x90 ,0xC9 ,0xF0 ,0x0F ,0xFF ,0xDC ,0x01 ,0xC0
    ,0x19 ,0xFF ,0xC0 ,0x7F ,0xFE ,0xEF ,0xFD ,0xDF ,0x9D ,0xFF ,0xFB ,0x80 ,0x77 ,0x00 ,0xE0
    ,0x00 ,0x03 ,0xC9 ,0xE4 ,0xE0 ,0x0C ,0x00 ,0xDC ,0x01 ,0xC0 ,0x19 ,0x80 ,0x00 ,0x70 ,0x06
    ,0xE7 ,0xFD ,0xCF ,0x9D ,0x80 ,0x3B ,0x80 ,0x77 ,0x00 ,0xE0 ,0x00 ,0x01 ,0xF0 ,0xF2 ,0x40
    ,0x0E ,0x01 ,0xDC ,0x00 ,0xC0 ,0x19 ,0x80 ,0x00 ,0x70 ,0x0E ,0xE0 ,0x1D ,0xCF ,0x1D ,0x80
    ,0x3B ,0x80 ,0x77 ,0x00 ,0xE0 ,0x00 ,0x00 ,0xE6 ,0x79 ,0x00 ,0x0F ,0xFF ,0xDF ,0xFC ,0xFF
    ,0xF9 ,0xFF ,0xC0 ,0x7F ,0xFE ,0xE0 ,0x1D ,0xC7 ,0x1D ,0xFF ,0xFB ,0xFF ,0xF7 ,0xFF ,0xE0
    ,0x00 ,0x00 ,0x49 ,0x3D ,0x00 ,0x0F ,0xFF ,0x9F ,0xFC ,0xFF ,0xF9 ,0xFF ,0xC0 ,0x7F ,0xFE
    ,0xE0 ,0x1D ,0xC2 ,0x1D ,0xFF ,0xF1 ,0xFF ,0xE3 ,0xFF ,0xC0 ,0x00 ,0x00 ,0x1C ,0x9E ,0x00
    ,0x0F ,0xFF ,0x1F ,0xFC ,0x7F ,0xE1 ,0xFF ,0xC0 ,0x7F ,0xFC ,0xE0 ,0x1D ,0xC0 ,0x1D ,0xFF
    ,0xE0 ,0xFF ,0xC1 ,0xFF ,0x80 ,0x00 ,0x00 ,0x1E ,0x4C ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
    ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
    ,0x00 ,0x00 ,0x0F ,0x20 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
    ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x07 ,0x90 ,0x00
    ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
    ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x03 ,0xE0 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
    ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
    ,0x00 ,0x00 ,0x01 ,0xC0 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
    ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x80 ,0x00
    ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
    ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
    ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
    ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
    ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00
    ,0x00 ,0x00 ,0x00
};

A: Have a look at the P25 Development Guide V3.4.1.
I don't understand what the first five characters are for. But the following characters are an esacpe sequence:
 0x1B,  0x58,  0x31,  0x19, 0x20

They are for printing a bit-image in horizontal mode. 0x19 and 0x20 are the horizontal dimension (times 8) and the vertical dimension, respectively. So the image is 200 by 32 pixel. The following 25 x 32 bytes then contain the pixels (black and white, 1 bit per pixel).
I would expect the whole thing to be 810 bytes long (5 bytes unidentified, 5 bytes escape sequence, 25 x 32 bytes of pixel data). I don't quite understand why it works with 796.
Update:
To convert a UIImage into the raw black and white data (without the escape sequence), the following code should help. I hope 1 bit per pixel bitmaps are still supported.
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
size_t bytesPerRow = (uiImage.size.width + 7) / 8;
size_t imageDataSize = uiImage.size.height * bytesPerRow;
unsigned char* imgData = (unsigned char*) malloc(imageDataSize);
CGContextRef context =  CGBitmapContextCreate(imgData,
    uiImage.size.width, uiImage.size.height,
    1, bytesPerRow,
    colorSpace, kCGImageAlphaNone);

UIGraphicsPushContext(context);
[uiImage drawInRect: CGRectMake(0.0, 0.0, uiImage.size.width, uiImage.size.height)];
UIGraphicsPopContext();

CGContextRelease(context);
CGColorSpaceRelease(colorSpace);

for (int i = 0; i < imageDataSize; i++)
    imgData[i] = ~imgData[i];

... send the image (imgData) to the printer ...

free(imgData);

A: Its easiest to start with a black and white image (I used .png) 4 bytes are allocated to each pixel, the data of which you can get by using CgContextRef and CgContextDrawImage (I used the CGBitmapContextCreate method to populate an array of pixel data as well as create a black and white image from the edited data array. I averaged the rgb values for each pixel and then changed all pixel values to black or white (alpha == 255) depending on the average of rgb's.
Then you need to package every 8 pixels into 1 print byte (thus for a pixel of 4 bytes, look at a set of 32 bytes in the data array and set the binary values of the print byte on or off depending on whether a pixel is black (add pow(2, 7 - (position of pixel in 8 pixel sequence) ) or white (do nothing).
I converted a .png image to black and white .png and then to binary and printed the values on my screen. Try to keep the width of your .png in multiples of 8 or you'll have trouble (since you need to convert 8 bytes into 1 byte.


text:
Q: JNI Error: com.sun.jna.platform.win32.Win32Exception: The system cannot find the file specified I'm using JNA 4.2.1 to access Windows Registry from Java (unfortunately it's only way to get the list of paired Bluetooth devices). It was working okay, until Windows 10 has installed some updates, now I have the following problem:

com.sun.jna.platform.win32.Win32Exception: The system cannot find the
  file specified.   at
  com.sun.jna.platform.win32.Advapi32Util.registryGetValues(Advapi32Util.java:1649)
    at IntelleWave.Devices.Device.getCOMportByBTUID(Device.java:243)    at
  IntelleWave.Devices.Device.getBTDeviceInstances(Device.java:163)  at
  IntelleWave.Devices.Device.getDeviceInstances(Device.java:112)    at
  IntelleWave.Devices.Device.(Device.java:72)     at
  IntelleWave.Devices.DeviceEnumerator.InitDevices(DeviceEnumerator.java:101)
    at
  IntelleWave.SettingsScreenController.UpdateDeviceList(SettingsScreenController.java:662)
    at
  IntelleWave.SettingsScreenController.initialize(SettingsScreenController.java:153)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)    at
  javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)     at
  javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)     at
  IntelleWave.ScreensController.loadScreen(ScreensController.java:46)
    at IntelleWave.IntelleWave.init(IntelleWave.java:175)   at
  com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:841)
    at
  com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:745)

For me it looks strange that I see Win32 Exception but in fact I have a Windows 64. Maybe problem related to that difference and I have to tell JNI to use x64 library (Advapi32Util)?
could you please advice.


text:
Q: Sort List objects based on object data type I have List of LabResults objects, i wanted to sort based on list object data,here is my collection
public class LabResult implements Serializable{

private String id;
private String name;
private String unit;
private String abnormal;  //Contains String either "A" or "N"

}
private List<LabResult> mLabResults;

I want to sort the list to show abnormal = "A" on top of list view and rest under that
can any one suggest me how to do that in java/android

A: Use a comparator
public class LabResultComparator implements Comparator<LabResult> {
    public int compare(LabResult p1, LabResult p2) {
        return p1.abnormal.compareTo(p2.abnormal);
    }
}

compareTo retuns 0 if the two strings are equal, a value less than 0 if  p1.abnormal is greater than p2.abnormal, and the other way around.


text:
Q: Is it possible to create a new sectioning level? I am wondering if it is any possible to create a new sectioning level above \part. I've already scrolled quite a few topics that seem to be related but they didn't really help. Somebody suggested somewhere to push all the levels one step down but (i) this will remove the possibility to use the subparagraph (all right?) and (ii) I am otherwise quite happy with the output I can get with the pre-existing settings and that would be rather troublesome to re-assign every single level (or is there any easy way to do it?).
In short, is it possible to define some sort of \superpart{} with the same settings than \part{} but written bigger or in upper case?
I hope my question was clear enough and I thank you in advance for your answers.
The document structure looks like the following:
\documentclass[a4paper, 10pt]{book}
\usepackage{blindtext}
\renewcommand{\thesection}{\arabic{section}}
\setcounter{secnumdepth}{5}

\begin{document}
\part{This is part1}
\chapter{Chapter title}
\section{This is a section}
\section{Section}
\subsection{Subsection}
\subsubsection{Subsubsection}
\paragraph{Paragraph}
\subparagraph{Subparagraph}

\blindtext

\end{document}

A: The memoir class (a superset of book and report) provides a \book division above the \part division. The manual provides general details about the code for this. Various aspects of the formatting of \book and \part are easily configurable.

A: Sure. There's no reason you can't go infinitely in any direction.
In book, the section level of \part is -1. You just need to define a level which has level -2.
Dig into book.cls and you'll find the relevant definition of \part:
\newcommand\part{%
  \if@openright
    \cleardoublepage
  \else
    \clearpage
  \fi
  \thispagestyle{plain}%
  \if@twocolumn
    \onecolumn
    \@tempswatrue
  \else
    \@tempswafalse
  \fi
  \null\vfil
  \secdef\@part\@spart}

\def\@part[#1]#2{%
    \ifnum \c@secnumdepth >-2\relax
      \refstepcounter{part}%
      \addcontentsline{toc}{part}{\thepart\hspace{1em}#1}%
    \else
      \addcontentsline{toc}{part}{#1}%
    \fi
    \markboth{}{}%
    {\centering
     \interlinepenalty \@M
     \normalfont
     \ifnum \c@secnumdepth >-2\relax
       \huge\bfseries \partname\nobreakspace\thepart
       \par
       \vskip 20\p@
     \fi
     \Huge \bfseries #2\par}%
    \@endpart}
\def\@spart#1{%
    {\centering
     \interlinepenalty \@M
     \normalfont
     \Huge \bfseries #1\par}%
    \@endpart}
\def\@endpart{\vfil\newpage
              \if@twoside
               \if@openright
                \null
                \thispagestyle{empty}%
                \newpage
               \fi
              \fi
              \if@tempswa
                \twocolumn
              \fi}

Rather than just cut and paste and edit to get our \superpart, let's have fun and redo the definition with twenty-first-century LaTeX and \NewDocumentCommmand.
The template for a sectioning command in xparse style is¹:
\NewDocumentCommand{\superpart}{s O{#3} m}{%

This says that our command has an optional star-form (s), an optional argument which defaults to the mandatory argument's value and then a mandatory argument.
Then we can do the stuff that \part does to open a new single-column page for the superpart title:
  \if@openright  % ❶
     \cleardoublepage
  \else
     \clearpage
  \fi
  \thispagestyle{plain}%
  \if@twocolumn
     \onecolumn
     \@tempswatrue
  \else
     \@tempswafalse
  \fi % ➀
  \null \vfil % ❷

A few things to note thusfar. On the line I've marked ❶, we check to see if we should be on a recto² page and if so we do \cleardoublepage which gets us to the an odd-numbered page. Otherwise, we just start a new page. Also note that we have commands that have @ in them which means that we need to either be in a class/package file or surround our definition with \makeatletter…\makeatother.
On the line marked with ❷, the \null before the \vfil is an empty box. Ordinarily, any glue at the top of a page is ignored. This allows us to have our superpart title centered on the page.
Next, we check to see if we're numbering superparts (we probably are) which depends on both whether the secnumdepth ≥ -2 and also whether we're doing a star form.
We'll explain what the ➀ is about at the bottom of this post.
  \IfBooleanF{#1}{%
     \ifnum\c@senumdepth > -3\relax
       \refstepcounter{superpart}%
       \addcontentsline{toc}{superpart}{\thesuperpart\hspace{1em}#2}%
     \else
       \addcontentsline{toc}{superpart}{#2}%
     \fi
     \superpartmark{#2}% ❸
  }%

I made a small change to the logic here at ❸ by introducing a new command we'll define later. book assumes that you don't want the part name going into headers and doesn't provide a facility to do so. But maybe you do.
Next we actually print the title.
  {%
     \centering
     \interlinepenalty \@M % ❹
     \normalfamily
     \IfBooleanF{#1}{%
       \ifnum\c@secnumdepth > -3\relax % ❺
         \Huge % ❻
         \bfseries
         \superpartname\nobreakspace\thesuperpart
         \par
         \vskip 20\p@
       \fi
     }%
  }

The setting at ❹ is misguided and a bad idea, but this is what LaTeX has done for 37 years so I'm not going to change it. It make LaTeX reluctant to break lines within a paragraph. This means that (a) if the title runs longer than a page, the (super)part number will get pushed to the bottom of the page and (2) if the title without the number is still too long to fit on a page, it will just spill over the bottom of the page. Moral of the story don't use long part titles.
I was originally thinking that I should use a temporary switch to avoid repeating the seemingly identical logic at ❺ and the previous code block, but a closer inspection will reveal that the two cases are not exactly identical, thanks to the call to \superpartmark above. Good case for not rushing to optimize early. Plus LaTeX provides @tempswa but not @tempswb.
I hate LaTeX's size selection commands like the one at ❻. They're a relic of the days of bitmapped fonts locked to Knuth's idiosyncratic choice of powers of 1.2 for type sizes. "Real" typographers would never set something in 17.28pt. The smaller sizes are even worse in that LaTeX uses, e.g., \footnotesize to mean both "two sizes smaller than the normal text size" and also "the formatting for footnotes." Personally, I think that, at the least, all of the sizing commands should have been private commands with @ in the name.
Finally, we wrap up the superpart page,
  \vfil\newpage
  \if@twoside
     \if@openright
       \null
       \thispagestyle{empty}% ❼
       \newpage
     \fi
  \fi
  \if@tempswa % ❽
     \twocolumn
  \fi
  \@afterheading ❾
}

At ❼, we make sure that if we have an open on recto pages setting, that we insert a blank page without headers or footers. Of course, as we noted above with the setting of \interlineskip, there's no guarantee that our part title actually will be printed on a single page (although there is a guarantee that it will be ugly if it is split across pages).
At ❽ remember way back in the first section when we set \@tempswatrue if we were in two column mode? Now we can take advantage of that by using that value to restore two column mode again.
The command at ❾ is not part of \part, but arguably should be. LaTeX usually suppresses the indent of text after a section heading³ and there's no good reason not to in this context.
Now we have some housekeeping to do. First we declare a counter for our superparts:
\newcounter{superpart}

We would also redefine \thesuperpart if we don't want it to be in arabic numerals which are the default. If you want to use xparse-style definitions, you would need to write, e.g.,
\RenewExpandableDocumentCommand{\thesuperpart}{}{\Roman{superpart}}

If we used \RenewDocumentCommand instead, we would discover that we got the wrong numbers printed in the table of contents and we would be sad. Normally, we want our commands to be robust and not change when they get written to, e.g., a table of contents, but for things like printing a counter value, we want the opposite so that we'll actually get MCMLXXXVIII written instead of \thesuperpart.
If we want parts to be numbered with superparts we would need to also add
\numberwithin{part}{superpart}

For printing the line in the table of contents we need to define \l@superpart. This isn't especially interesting so I've just made small modifications to book's \l@part:
\NewDocumentCommmand\l@superpart{m}{%
  \ifnum \c@tocdepth >-3\relax
    \addpenalty{-\@highpenalty}%
    \addvspace{2.25em \@plus\p@}%
    \setlength\@tempdima{3em}%
    \begingroup
      \parindent \z@ \rightskip \@pnumwidth
      \parfillskip -\@pnumwidth
      {\leavevmode
       \large \bfseries #1\hfil
       \hb@xt@\@pnumwidth{\hss #2%
                          \kern-\p@\kern\p@}}\par
       \nobreak
         \global\@nobreaktrue
         \everypar{\global\@nobreakfalse\everypar{}}%
    \endgroup
  \fi}

We will need to define the name that we print for a \superpart. How about being pretentious and calling it "Book"?
\NewDocumentCommand{\superpartname}{}{Book}

And finally, there's the hook that we created for using the superpart title in page headings should we so choose. I decided to have it do what \part does, which is just put empty text into both marks.
\NewDocumentCommand{\superpartmark}{m}{\markboth{}{}}

And that (modulo typos because this is, of course, all untested) is how you can define a sectioning command from scratch.
Edit Ulrike Fischer pointed out that some additional effort is necessary to get the hierarchical bookmarks of hyperref working.⁴ hyperref assumes that we're using the internal macros (and macro structure) of LaTeX to do its work. Here's what it does for \part:
\let\H@old@part\@part % ❿
\begingroup\expandafter\expandafter\expandafter\endgroup
\expandafter\ifx\csname chapter\endcsname\relax
  \let\Hy@secnum@part\z@
\else
  \let\Hy@secnum@part\m@ne
\fi
\def\@part{%
  \ifnum\Hy@secnum@part>\c@secnumdepth
    \phantomsection % ⓫
  \fi
  \H@old@part
}
%    \end{macrocode}
%    \begin{macrocode}
\let\H@old@spart\@spart % ❿
\def\@spart#1{%
  \Hy@MakeCurrentHrefAuto{part*}% ⓬
  \Hy@raisedlink{%
    \hyper@anchorstart{\@currentHref}\hyper@anchorend
  }%
  \H@old@spart{#1}%
}

At ❿ (which occurs twice), we use an old-school trick for patching a macro: \let\foo=\bar (the = is optional) copies the current meaning of \bar into \foo. This is handy when we want to redefine \bar but keep its functionality. For example
\let\foo\bar
\NewDocumentCommand{\bar}{%
   stuff before old bar
   \foo % old bar functionality
   stuff after old bar
}

The kids are all using the patchcmd package or ted to do their changes these days, which is more robust, but either way, these sorts of modifications assume that we know something about the internals of how commands are defined. In any event, hyperref knows nothing about our \superpart command, so it will do nothing.
⓫ is the part that matters for our purposes. \phantomsection adds an anchor at the location where it appears. The documentation indicates that it should be next to \addcontentsline, so we'll have to go back to our documentation and insert \phantomsection after the line that I've marked ➀, except we don't want to just insert this because maybe it doesn't exist! So we'll instead do
\ifdefined\phantomsection
  \phantomsection
\fi

at that point. What about the code at ⓬? Well, it turns out that this is nearly the exact same code as \phantomsection, the only difference being that \phantomsection says \Hy@MakeCurrentHrefAuto{section*} instead of \Hy@MakeCurrentHrefAuto{part*}. The fact that we use \phantomsection in the non-* case indicates that it's not that important what that value is, so we can just have one \phantomsection at the point we chose.
One more thing is necessary for hyperref to handle the hierarchy. We need to have
\NewDocumentCommand{\toclevel@superpart}{}{-2}}

The \toclevel@* commands aren't part of LaTeX's kernel but are used by, e.g., the ams* classes and hyperref takes advantage of this as well. If we don't have a level defined for a sectioning level, hyperref assumes a default of 0 (equivalent to \chapter in book) which is not what we want. Again, I've tested none of this, but I think I've got all the moving parts in place or at least explained it well enough that you should be able to fix any mistakes.

*

*I'm lying a little bit about this. There is one key difference between this and the default LaTeX definitions of sectioning commands: this definition allows you to write \superpart*[foo]{bar} which would, in default LaTeX be interpreted as \superpart*{[}  foo]{bar} where foo]{bar} would be the first paragraph after the \superpart*.  (This is mentioned in the xparse documentation, by the way, albeit a bit more tersely.)

*Fancy typographer-speak for right hand side. The left side is called verso.

*The cases where it does not are after \part and after \chapter in two-column mode. These are, I think, oversights, but 37-years later it's probably too late to change book.cls.

*He also caught a few typos which I've fixed. Thanks for the proofreading!


text:
Q: float right won't work I have been trying to float the social icons to the right of the page, but for some reason it won't work.
But the text at the top of the page floats perfectly.
Here is a fiddle:
check it out here

A:  clear:both

add the above css in social css

A: try this css
#wrapper {
    margin: 0px auto;
    width: 940px;
    padding: 15px 0px 0px;
    position: relative;
    text-align: left;

}
#header {
    width: 940px;
    margin: 0px;
    padding: 0px;
    background: none repeat scroll 0% 0% rgb(255, 255, 255);
    overflow: hidden;
}
#mast-head {
    width: 940px;
    float: left;
    margin: 0px;
    padding: 0px 0px 10px;
    background: none repeat scroll 0% 0% transparent !important;
    position: relative;
}
a.logo-txt {
    text-decoration: none;
    padding: 0px;
    display: block;
    float: left;
    margin: 0px;
}
a.logo-txt #logo {
    margin: 0px;
    padding: 0px;
}
.personalisation {
    margin: 0px auto;
    float: right;
}
.welcome {
    font-size: 12px;
    font-weight: bold;
}
.social {
    margin: 100px 0px auto;
    float: right;
    width:100%
}
.social a{
    float:right;
}

#nav{
  border:1px solid #ccc;
  border-width:1px 0;
  list-style:none;
  margin-top: 160px;
  padding:0;
  text-align:center;
}
#nav li{
  display:inline;
}
#nav a{
  display:inline-block;
  padding:10px;
}
#nav ul{
  position:absolute;
  left:-9999px;
  margin:0;
  padding:0;
  text-align:left;
}
#nav ul li{
  display:block;
}


text:
Q: EF5 Migrations Seed AddOrUpdate with a nullable selection criteria I have a question to which someone may have found a solution in the past. I'm seeding the database in the Configuration class of EF5 migrations, using the AddOrUpdate method.
Here's the quick example of the domain model:
 public class Club
{
    public virtual long Id { get; set; }
    public virtual string Name { get; set; }
}

public class Court
{
    public virtual long Id { get; set; }
    public virtual string Name { get; set; }

    public virtual long? ClubId { get; set; }
    public virtual Club Club { get; set; }
}

Then here is an extract from my seed method:
Club cb = new Club { Name = "Test Club 1" };
context.Set<Club>().AddOrUpdate(m=>m.Name, cb);
context.SaveChanges();

Court crt1 = new Court { ClubId = cb.Id, Name = "Court 1" };
Court crt2 = new Court { ClubId = cb.Id, Name = "Court 2" };
context.Set<Court>().AddOrUpdate(m => new { m.Name, m.ClubId }, crt1, crt2);
context.SaveChanges();

Now, once the code reaches line number 7, it throws an error:

The binary operator Equal is not defined for the types 'System.Nullable`1[System.Int64]' and 'System.Int64'.

From my investigation it's due to the fact that ClubId is a Nullable long.
Is there any way around this?
Not a major issue - I'm just a perfectionist, and would like to see how others may have solved this...
Thanks,
Nick Goloborodko

A: Had the same problem, implemented my own AddOrUpdate in the end.
First, we have to get the actual primary keys of our entity (maybe you need to add additional naming conventions here...):
private static PropertyInfo[] PrimaryKeys<TEntity>()
    where TEntity : class
{
    return typeof(TEntity).GetProperties()
                          .Where(p => Attribute.IsDefined(p, typeof(KeyAttribute))
                                   || "Id".Equals(p.Name, StringComparison.Ordinal))
                          .ToArray();
}

Then, we need to parse the "identifiers expression", which is used by AddOrUpdate to match  existing items (like the original AddOrUpdate):
private static PropertyInfo[] Properties<TEntity>(
    Expression<Func<TEntity, object>> identifiers)
    where TEntity : class
{
    // e => e.SomeValue
    var direct = identifiers.Body as MemberExpression;
    if (direct != null)
    {
        return new[] { (PropertyInfo)direct.Member };
    }

    // e => (object)e.SomeValue
    var convert = identifiers.Body as UnaryExpression;
    if (convert != null)
    {
        return new[] { (PropertyInfo)((MemberExpression)convert.Operand).Member };
    }

    // e => new { e.SomeValue, e.OtherValue }
    var multiple = identifiers.Body as NewExpression;
    if (multiple != null)
    {
        return multiple.Arguments
                       .Cast<MemberExpression>()
                       .Select(a => (PropertyInfo)a.Member)
                       .ToArray();
    }

    throw new NotSupportedException();
}

Thus, .AddOrUpdate(m => m.Name, ...) should work as well as .AddOrUpdate(m => new { m.Name, m.ClubId }, ...).
Finally, we build the where expression dynamically for every entity, match it with our current database, and act accordingly (add or update):
public static void AddOrUpdate<TEntity>(this DbContext context,
    Expression<Func<TEntity, object>> identifiers,
    params TEntity[] entities)
    where TEntity : class
{
    var primaryKeys = PrimaryKeys<TEntity>();
    var properties = Properties<TEntity>(identifiers);

    for (var i = 0; i < entities.Length; i++)
    {
        // build where condition for "identifiers"
        var parameter = Expression.Parameter(typeof(TEntity));
        var matches = properties.Select(p => Expression.Equal(
            Expression.Property(parameter, p),
            Expression.Constant(p.GetValue(entities[i]), p.PropertyType)));
        var match = Expression.Lambda<Func<TEntity, bool>>(
            matches.Aggregate((p, q) => Expression.AndAlso(p, q)),
            parameter);

        // match "identifiers" for current item
        var current = context.Set<TEntity>().SingleOrDefault(match);
        if (current != null)
        {
            // update primary keys
            foreach (var k in primaryKeys)
                k.SetValue(entities[i], k.GetValue(current));

            // update all the values
            context.Entry(current).CurrentValues.SetValues(entities[i]);

            // replace updated item
            entities[i] = current;
        }
        else
        {
            // add new item
            entities[i] = context.Set<TEntity>().Add(entities[i]);
        }
    }
}

Hope this helps, although the question is a bit old.

A: I don't have a very satisfactory answer, but I believe that there would need to be a code change to the AddOrUpdate implementation to fix this so I have applied a workaround.
Simply put, rather than use AddOrUpdate, you do the same task manually. For example:
private void AddOrUpdateCourt(long id, string name, string someOtherPropertyValue)
{
    var court = _context.Set<Court>().SingleOrDefault(c => c.Id = id && c.Name = name);
    if(court == null)
    {
        _context.Set<Court>().Add(new Court
        {
            ClubId=id,
            Name=name,
            SomeOtherProperty = someOtherPropertyValue
        });
    }
    else
    {
        court.SomeOtherProperty = someOtherPropertyValue;
    }
}


text:
Q: Using values from an ArrayList in a where clause without loads of queries? I'm trying to accomplish basically this:
Select * FROM x WHERE id != for(int i : arraylist)

So basically I have an arraylist with say 10 ids, I want the sql not to return any of the rows that have an ID the same as in my arraylist, and I'd rather not do it with like 10 queries. Is there any way to do this?

A: You're looking for the SQL IN keyword:
SELECT * FROM x WHERE id NOT IN ( 1, 2, 3, etc. )

A: in this way:
SELECT * FROM x WHERE id not in ( list of value ) // i.e. 'A', 'B', ...

Pay attention:
You can execute this statement only if yuo array has been filled.
If you have an array with no items NOT IN can cause problems.
So, you must check your condition before put NOT IN clause.


text:
Q: Is it possible to round values in css? Or, how to solve half/sub-pixels on % translated layouts? I have a curious problem. I built a flex/grid fullscreen responsive interface. I used % values. It works fine, but sometimes, randomly, by resizing the window a 1 px line appears between item (horizontal, vertical, or both). I think maybe that's because, using % values and being the elements liquid, the items size is not always perfect-pixel. Look:

How could I avoid that, still maintaining a responsive layout?
I managed to somewhat good by very little scaling the inner elements (images and rollover layers) like scale(1.005), but still it was not always perfect. The problem is that browsers can't round element sizes on fullscreen layouts, or something like that, don't know.
Just a little abstraction of my original code, just to add context. It's a 3 cols flex layout where 1 col is 50% width (the third one is off screen > the overall behaves like a 3 panels 'slideshow'). The second column, itself contains the grid on the picture:
/* HTML */

      <button type="button">a</button>
      <button type="button">b</button>
      <button type="button">c</button>
      <button type="button">d</button>

/* SCSS */

.sections-list{
  display: flex;
  justify-content: flex-start;
  min-height: 100vh;

  translateX(-50%);
}

.section{
  flex-grow:1;
  min-width: 50%;
  box-sizing:border-box;
  min-height: 100vh;
}

.grid{
  display: grid;
  height: 100%;
  grid-template:
    "a   b" 50%
    "c   d" 50%
    / 50% 50%;

  button{
    display: block;
    position: relative;
    overflow: hidden;
    padding: 0;
    min-width: none;
    max-width: none;
    height: auto;

    &:nth-child(1){ grid-area: a; }
    &:nth-child(2){ grid-area: b; }
    &:nth-child(3){ grid-area: c; }
    &:nth-child(4){ grid-area: d; }
  }
}

A: So, it turns out the problem was caused by the 50% translation on the main element. That caused half pixels when window.width was odd.
The solution to me was to recalculate and round the translation using a little javascript, css --properties and a fallback for legacy browsers. Here's some simplified code (and please look to the original's code too):
:root{
  --half-window: -50%;
}

.sections-list{
  display: flex;
  justify-content: flex-start;
  min-height: 100vh;

  transform: translatex(-50%); // legacy
  transform: translatex(var(--half-window));
}

then:
function round_half_window(){
  document.documentElement.style.setProperty('--half-window', -Math.round($(window).width()/2) + 'px');
}

$window.resize(_.debounce(function(){ round_half_window(); },500));
round_half_window();


text:
Q: Change colors in a WPF CheckBox I would like to specify particular colours for the border and background for a WPF checkbox. All the examples I've seen so far seem to be too complicated as they involve changing everything - I just want to change the colors.
This is what I have so far - the colors are correct but the checkbox has shrunk (cant see the 'tick' symbol)...
<Style TargetType="CheckBox">
    <Setter Property="VerticalAlignment" Value="Center" />
    <Setter Property="Padding" Value="0" />
    <Setter Property="Background" Value="#666666" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="CheckBox">
                <Border Background="{TemplateBinding Background}"
                        BorderThickness="1"
                        BorderBrush="Aquamarine">
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsChecked" Value="False">
            <Setter Property="BorderBrush" Value="Aquamarine"/>
        </Trigger>
        <Trigger Property="IsChecked" Value="True">
            <Setter Property="BorderBrush" Value="Aquamarine" />
        </Trigger>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Background" Value="#ffff00"/>
            <Setter Property="BorderBrush" Value="Aquamarine"/>
        </Trigger>
    </Style.Triggers>
</Style>

A: The problem is that ControlTemplates don't work as Styles. As you can't zoom in on a particular element, you need to declare everything each time. For example, you can't see the 'tick' symbol because you left out the dimensions for the border. This is easily fixed:
<Border Background="{TemplateBinding Background}"
        BorderThickness="1"
        BorderBrush="Aquamarine"
        Width="13"
        Height="13"
        >

But the main problem remains, you won't get a functional CheckBox. It seams easiest copying the original template and changing it to the way you like.


text:
Q: Switch to Neon Mode Raspberry Pi Cluster I'm getting the following error message when compiling a .S assembly file with

gcc -o output input.S

Error message:

Error: selected processor does not support `veor.f64 d2,d2' in ARM mode

How can i switch to the correct mode?

A: Assuming it's one of the later Pi models with an ARMv7 core, not the first version which was ARM11 (ARMv6), then you need to add -mfpu=NEON.


text:
Q: SSRS No Query Designer is Available I just created a data source  and now I'm adding a data set. I'm using a dataset that is embedded in my report and then I go click on Query Designer... and it tells me No cube can be found. I click okay and then it tells me No Query Designer is Available. Every time I click on Query Designer... again, it just goes straight to the No Query Designer is Available window.
I looked around for some answers, and some people said that the cube's visibility might be set to false in its properties. However, I checked and it was true. I don't know what to do anymore.
Is there any way I can get this MDX Query Designer window to open? Did I do something wrong?

A: I don't know if you managed to fix this problem, but when it happened for me it turned out to be a permissions issue with my data source.
I'll put this as an answer here just in case it helps anyone else out - I found the cube visibility answers quite misleading (although obviously it has helped some people).

A: I was able to fix this same problem.
I had an embedded datasource defined that connected to my cube. I temporarily created another dataset, selected to embed this dataset in my report, selected the embedded datasource and then attempted to use the Query Designer. It worked for this new dataset. So I then cancelled the creation of the new dataset, went back to the old non-working dataset and was able now open the Query Designer window


text:
Q: XPS writer fails with .Net 4 / font rendering bug? We have a WPF application that allows users to enter and style text as they wish. Their text is then transformed to XPS to be inserted in a PDF using ABCPdf.
We have recently switched to .Net 4, and now the XPS generation sometimes generates badly-formed XPS.
The only time when a badly-formed XPS is generated is when the user uses a font that overlaps two characters (such as Sevillana, available on Google Fonts). In .Net 4, the characters overlap, whereas in .Net 3.5, they do not. From another SO question I gather that it's because .Net 4.0 has changed its font rendering engine.
.Net 3.5 :

.Net 4.0 : (note how the "d" and "A" overlap)

It looks like .Net 4 does not take the apostrophe's spacing into account, or even negates it. If I remove the apostrophe, the spacing widens. I have created a simple test project to demonstrate the issue : https://github.com/tbroust-trepia/wpf-4-font-rendering
Our method to save a FlowDocument to XPS is pretty much the same as in creating an XPS Document from a FlowDocument and attach it on the fly (I suspect that the original developer just copy/pasted that code) ; it just saves the XPS to a file instead of in a stream.
The MS tool IsXPS says that a specific node is invalid. As a matter of fact, in Documents\1\Pages\1.fpage, the value of Indices is ;,-16;,84;;;;,30. I can see that "0.-16" is not really a number.
So, I have many questions:

*

*Why is it happening ? I don't understand how the values are converted into these Indices. I guess that the transformation engine tried to set it to "-0.16" but messed up ?

*Can I modify/check the value of this Indices before it's saved ?

*If I cannot, how can I check afterwards ? I have found a sort of XPS validator here but I don't understand how I can check the Indices value from there. I could do it manually, reading and parsing the XML, but I'm really sure it's not a good idea.

Edit
I have opened a bug at Microsoft, but I don't expect much there. I think I will try to modify the generated XPS. It's dirty but it might work.

A: While waiting for MS to do whatever they want, I have found a way to fix the broken XPS.
Warning: dirty hack ahead
public class XpsFile
{
    /// <summary>
    /// Regex to validate XPS "indices" property (gotten from ABCPDF)
    /// </summary>
    private static readonly string IndicesRegex = @"(((\(([1-9][0-9]*)(:([1-9][0-9]*))?\))?([0-9]+))?(,(\+?(([0-9]+(\.[0-9]+)?)|(\.[0-9]+))((e|E)(\-|\+)?[0-9]+)?)?(,((\-|\+)?(([0-9]+(\.[0-9]+)?)|(\.[0-9]+))((e|E)(\-|\+)?[0-9]+)?)?(,((\-|\+)?(([0-9]+(\.[0-9]+)?)|(\.[0-9]+))((e|E)(\-|\+)?[0-9]+)?))?)?)?)(;((\(([1-9][0-9]*)(:([1-9][0-9]*))?\))?([0-9]+))?(,(\+?(([0-9]+(\.[0-9]+)?)|(\.[0-9]+))((e|E)(\-|\+)?[0-9]+)?)?(,((\-|\+)?(([0-9]+(\.[0-9]+)?)|(\.[0-9]+))((e|E)(\-|\+)?[0-9]+)?)?(,((\-|\+)?(([0-9]+(\.[0-9]+)?)|(\.[0-9]+))((e|E)(\-|\+)?[0-9]+)?))?)?)?)*";

    /// <summary>
    /// Fixes the XPS problems it encounters and knows about
    /// </summary>
    public static void FixXps(string filePath)
    {
        // first we'll load the XPS file
        using (var currentPackage = Package.Open(filePath, FileMode.Open))
        {
            var pageUri = new Uri("/Documents/1/Pages/1.fpage", UriKind.Relative);

            // check that the file we'll modify exists
            if (!currentPackage.PartExists(pageUri))
            {
                throw new Exception(string.Format("Unable to find first page in XPS {0} - unable to fix this XPS !", filePath));
            }

            // assume the broken part is in the first page
            var firstPage = currentPackage.GetPart(pageUri);
            var relationships = firstPage.GetRelationships();
            var pageContent = XDocument.Load(firstPage.GetStream());

            // then we'll look up each glyph and check if their "Indices" property is valid
            XNamespace ns = pageContent.Root.GetDefaultNamespace();
            var glyphs = (from g in pageContent.Descendants(ns + "Glyphs")
                          where g.Attribute("Indices") != null
                          select g).ToList();
            for (var i = 0; i < glyphs.Count(); i ++)
            {
                glyphs[i] = FixGlyph(glyphs[i]);
            }

            // remove the current (corrupted) file from the package
            currentPackage.DeletePart(pageUri);

            // add the new (shiny) file to the package
            var newPage = currentPackage.CreatePart(pageUri, "application/vnd.ms-package.xps-fixedpage+xml", CompressionOption.NotCompressed);
            using (var ms = new MemoryStream())
            {
                // we need to remove XML declaration, so we need to use the XmlWriter
                var settings = new XmlWriterSettings();
                settings.Indent = false;
                settings.NewLineChars = string.Empty;
                settings.NewLineHandling = NewLineHandling.Replace;
                settings.OmitXmlDeclaration = true;
                using (var xw = XmlWriter.Create(ms, settings))
                {
                    pageContent.WriteTo(xw);
                }

                ms.Seek(0, SeekOrigin.Begin);
                CopyStream(newPage.GetStream(), ms);
            }

            // now we need to re-create the relationships between the Page file and the fonts
            foreach (var relation in relationships)
            {
                newPage.CreateRelationship(relation.TargetUri, relation.TargetMode, relation.RelationshipType, relation.Id);
            }
        }
    }

    /// <summary>
    /// Tries to load the XPS, and returns false if it fails
    /// </summary>
    public static bool IsValidXps(string filePath)
    {
        try
        {
            using (var xpsOld = new XpsDocument(filePath, FileAccess.Read))
            {
                var unused = xpsOld.GetFixedDocumentSequence();
            }

            return true;
        }
        catch (System.Windows.Markup.XamlParseException)
        {
            return false;
        }
    }

    /// <summary>
    /// Writes the whole content of a stream into another
    /// </summary>
    /// <remarks>
    /// http://stackoverflow.com/a/18885954/2354542
    /// </remarks>
    private static void CopyStream(Stream target, Stream source)
    {
        const int bufSize = 0x1000;
        byte[] buf = new byte[bufSize];
        int bytesRead = 0;
        while ((bytesRead = source.Read(buf, 0, bufSize)) > 0)
        {
            target.Write(buf, 0, bytesRead);
        }
    }

    /// <summary>
    /// Fixes the glyph, if necessary
    /// </summary>
    private static XElement FixGlyph(XElement g)
    {
        var matchAttribute = Regex.Match(g.Attribute("Indices").Value, IndicesRegex);
        if (!matchAttribute.Success)
        {
            return g;
        }

        var hasProblem = false;
        foreach (var token in matchAttribute.Value.Split(";".ToCharArray()))
        {
            if (token == ",")
            {
                hasProblem = true;
                break;
            }
        }

        if (hasProblem)
        {
            // the Indices attribute is not well-formed: let's try to fix the one(s) that are wrong
            var fixedTokens = new List<string>();
            foreach (var token in g.Attribute("Indices").Value.Split(";".ToCharArray()))
            {
                var newToken = token;
                var matchToken = Regex.Match(token, @",(-\d+)");
                if (matchToken.Success) // negative number, yay ! it's not allowed :-(
                {
                    newToken = ",0"; // it should be zero, I believe
                }

                fixedTokens.Add(newToken);
            }

            g.Attribute("Indices").Value = string.Join(";", fixedTokens);
        }

        return g;
    }
}


text:
Q: How to calculate all possible permutations of an assignment in Python? I am trying to calculate all possible ordered permutations of an assignment of n items to m entities (in Python), but I am stuck and would appreciate some help. In my case, all items are to be assigned, but it is not necessary for an entity to be assigned any items. By "ordered", I mean that the order matters so [0,1] is unique from [1,0].
In the case of three items and two entities, I am seeking to generate the following combinations (but I want to scale this up for larger m and n):
[[0,1,2],[]]
[[0,2,1],[]]
[[1,0,2],[]]
[[1,2,0],[]]
[[2,0,1],[]]
[[2,1,0],[]]
[[],[0,1,2]]
[[],[0,2,1]]
[[],[1,0,2]]
[[],[1,2,0]]
[[],[2,0,1]]
[[],[2,1,0]]
[[0,1],[2]]
[[1,0],[2]]
[[0,2],[1]]
[[2,0],[1]]
[[1,2],[0]]
[[2,1],[0]]
[[0],[1,2]]
[[0],[2,1]]
[[1],[0,2]]
[[1],[2,0]]
[[2],[0,1]]
[[2],[1,0]]
I have been trying to use Python's itertools.permutations, but I can't seem to think of anything that will scale up nicely. Can anyone suggest an algorithm or provide some guidance?

A: Here is a possible way:
from itertools import permutations, product, combinations_with_replacement

N_elems = 3
M_groups = 3

perm = permutations(range(N_elems))
bounds = combinations_with_replacement(range(N_elems+1), M_groups-1)
for p,b in product(perm, bounds):
    b = (0,)+b+(N_elems+1,)
    L = [p[b[i]:b[i+1]] for i in range(M_groups)]
    print(L)

Explanation:

*

*perm = permutations(range(N_elems)) gets you all possible orderings

*bounds = combinations_with_replacement(range(N_elems+1), M_groups-1) gets you all possible ways to split this ordering into M groups

*product(perm, bounds) gets you all possible orderings and splits leading to a different possible 'assignment'


text:
Q: ¿Como obtengo el View en un Fragment? Estoy empezando a programar en Android con Kotlin y estoy algo confuso con los Null Safety.
El problema principal viene al querer hacer un findViewById a partir del getView() (view en kotlin) en un fragment, he estado consultado y solo he encontrado la siguiente forma:
 fun setUpRecyclerView() {
    mRecyclerView = view?.findViewById<View>(R.id.recyclerView) as RecyclerView
    mRecyclerView.setHasFixedSize(true)
    mRecyclerView.layoutManager = LinearLayoutManager(this.activity)
    mAdapter.RecyclerAdapter(getMeals(), this.activity!!)
    mRecyclerView.adapter = mAdapter
}

En teoria si no me equivoco con view?.findViewById obtengo el view de la Activity enlazada a este fragment.
Aunque el IDE me obliga a poner el ? delante del view y cuando intenta obtener el RecyclerView me da el siguiente error:

E/AndroidRuntime: FATAL EXCEPTION: main
                    Process: com.chdzma.changeproject, PID: 29649
                    kotlin.TypeCastException: null cannot be cast to non-null type android.support.v7.widget.RecyclerView
                        at com.chdzma.changeproject.fragments.Meals.setUpRecyclerView(MealsFragment.kt:51)
                        at com.chdzma.changeproject.fragments.Meals.onCreate(MealsFragment.kt:47)
                        at android.support.v4.app.Fragment.performCreate(Fragment.java:2331)
                        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1386)
                        at android.support.v4.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1188)
                        at android.support.v4.app.FragmentTransition.calculateFragments(FragmentTransition.java:1071)
                        at android.support.v4.app.FragmentTransition.startTransitions(FragmentTransition.java:115)
                        at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2380)
                        at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2338)
                        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2245)
                        at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:703)
                        at android.os.Handler.handleCallback(Handler.java:789)
                        at android.os.Handler.dispatchMessage(Handler.java:98)
                        at android.os.Looper.loop(Looper.java:164)
                        at android.app.ActivityThread.main(ActivityThread.java:6809)
                        at java.lang.reflect.Method.invoke(Native Method)
                        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

He estado buscando en kotlin pero no encuentro la forma de que me funcione ni la mejor forma de hacerlo.

A: El problema esta que al momento de hace el casting, el compilador interpreta que el cast sera un objeto no nulo:
view?.findViewById<View>(R.id.recyclerView)
  as
     RecyclerView; //<-- No esta marcado como nullable por lo que si retorna null, lanza el error

Utiliza el operador de casteo seguro as? para evitar el error:
//...
 mRecyclerView = view?.findViewById<View>(R.id.recyclerView) as? RecyclerView
///


text:
Q: Merge two json files containing dict & list into single json using python? I'm trying to merge two JSON files into a single JSON using python.
File1:
{
    "key1":    "protocol1",
    "key2":     [
            {
                    "name": "user.name",
                    "value": "user@EXAMPLE123.COM"
            },
            {
                    "name": "user.shortname",
                    "value": "user"
            },
            {
                    "name": "proxyuser.hosts",
                    "value": "*"
            },
            {
                    "name": "kb.groups",
                    "value": "hadoop,users,localusers"
            },
            {
                    "name": "proxy.groups",
                    "value": "group1, group2, group3"
            },
            {
                    "name": "internal.user.groups",
                    "value": "group1, group2"
            }
    ]
}

File2:
{
    "key1":    "protocol1",
    "key2":     [
            {
                    "name": "user.name",
                    "value": "user@EXAMPLE456.COM"
            },
            {
                    "name": "user.shortname",
                    "value": "user"
            },
            {
                    "name": "proxyuser.hosts",
                    "value": "*"
            },
            {
                    "name": "kb.groups",
                    "value": ""
            },
            {
                    "name": "proxy.groups",
                    "value": "group3, group4, group5"
            },
            {
                    "name": "internal.groups",
                    "value": "none"
            }
    ]
}

Final expected result:
{
    "key1":    "protocol1",
    "key2":     [
            {
                    "name": "user.name",
                    "value": "user@EXAMPLE123.COM, user@EXAMPLE456.COM"
            },
            {
                    "name": "user.shortname",
                    "value": "user"
            },
            {
                    "name": "proxyuser.hosts",
                    "value": "*"
            },
            {
                    "name": "kb.groups",
                    "value": "hadoop,users,localusers"
            },
            {
                    "name": "proxy.groups",
                    "value": "group1, group2, group3, group4, group5"
            },
            {
                    "name": "internal.user.groups",
                    "value": "group1, group2"
            },
            {
                    "name": "internal.groups",
                    "value": "none"
            }
    ]
}

I need to merge based on below rules:

*

*If the 'name' key within the list(key2) match in both the files then concatenate the values.
e.g.
File1:
"key2": [{"name" : "firstname", "value" : "bob"}]

File2:
"key2": [{"name" : "firstname", "value" : "charlie"}]

Final output:
"key2": [{"name" : "firstname", "value" : "bob, charlie"}]

Some considerations while appending the values:

*

*If both files contain duplicate value(s) in 'value', final result should only be the union of the values.

*If any of 'value' contains ' * ', then final value should be ' * '.

*If 'name' key in 2nd JSON file is not present in 1st file, add it to first file.

I've written a python script to load the two JSON files and merge them but it seems to just concatenate everything into the first JSON file.
    def merge(a, b):
        "merges b into a"
        for key in b:
            if key in a:# if key is in both a and b
                if key == "key1":
                    pass
                elif key == "key2":
                    for d1, d2 in zip(a[key], b[key]):
                        for key, value in d1.items():
                            if value != d2[key]:
                                a.append({"name": d2[key], "value": d2["value"]})
                else:
                  a[key] = a[key]+ b[key]
            else: # if the key is not in dict a , add it to dict a
                a.update({key:b[key]})
        return a

Can someone point out how I can compare the value for the "name" section with the list for key2 in both the files and concatenate the values in "value"?

A: Here's a solution that runs in linear time using a dictionary to quickly look up an item in a given a name key. Dictionary b's key2 list is iterated through once and a modified in constant time as required. Sets are used to eliminate duplicates and handle asterisks.
def merge(a, b):
    lookup = {o['name']: o for o in a['key2']}

    for e in a['key2']:
        e['value'] = set([x.strip() for x in e['value'].split(",")])

    for e in b['key2']:
        if e['name'] in lookup:
            lookup[e['name']]['value'].update([x.strip() for x in e['value'].split(",")])
        else:
            e['value'] = set([x.strip() for x in e['value'].split(",")])
            a['key2'].append(e)

    for e in a['key2']:
        if "*" in e['value']:
            e['value'] = "*"
        else:
            e['value'] = ", ".join(sorted(list(e['value'])))

Sample output:
key1:
    protocol1
key2:
    {'name': 'user.name', 'value': 'user@EXAMPLE123.COM, user@EXAMPLE456.COM'}
    {'name': 'user.shortname', 'value': 'user'}
    {'name': 'proxyuser.hosts', 'value': '*'}
    {'name': 'kb.groups', 'value': ', hadoop, localusers, users'}
    {'name': 'proxy.groups', 'value': 'group1, group2, group3, group4, group5'}
    {'name': 'internal.user.groups', 'value': 'group1, group2'}
    {'name': 'internal.groups', 'value': 'none'}

A: Order of elements in a["key2"] and b["key2"] is not guaranteed to be the same, so you should build a mapping from the "name" value to the index in a["key2"], and then browse b["key2"] comparing each "name" value to that dict.
Code could be:
def merge(a, b):
    "merges b into a"
    for key in b:
        if key in a:# if key is in both a and b
            if key == "key2":
                # build a mapping from names from a[key2] to the member index
                akey2 = { d["name"]: i for i,d in enumerate(a[key]) }
                for d2 in b[key]:      # browse b["key2"]
                    if d2["name"] in akey2:   # a name from a["key2"] matches
                        a[key][akey2[d2["name"]]]["value"] += ", " + d2["value"]
                    else:
                        a[key].append(d2)     # when no match
        else: # if the key is not in dict a , add it to dict a
            a[key] = b[key]
    return a

You can then test it:
a = {"key1":    "value1",
     "key2": [{"name" : "firstname", "value" : "bob"}]
     }
b = {"key1":    "value2",
     "key2": [{"name" : "firstname", "value" : "charlie"},
          {"name" : "foo", "value": "bar"}]
     }
merge(a, b)

pprint.pprint(a)

gives as expected:
{'key1': 'value1',
 'key2': [{'name': 'firstname', 'value': 'bob, charlie'},
          {'name': 'foo', 'value': 'bar'}]}

A: Just loop through the keys if its not in the new dict add it if it is merge the two values
d1 = {"name" : "firstname", "value" : "bob"}
d2 = {"name" : "firstname", "value" : "charlie"}
d3 = {}

for i in d1:
    for j in d2:
        if i not in d3:
            d3[i] = d1[i]
        else:
            d3[i] = '{}, {}'.format(d1[i], d2[i])

print(d3)

(xenial)vash@localhost:~/python/stack_overflow$ python3.7 formats.py
{'name': 'firstname, firstname', 'value': 'bob, charlie'}


text:
Q: Is there a xsd file for "http://schemas.microsoft.com/2003/10/Serialization/" namespace? I want to create / infer schema for data-contract serialized classes.
When I use [DataContract(IsReference = true)] attribute the serializer is injecting attributes z:Id="i2" and z:Ref="i2" to reference the same object instances.
Both attributes are from http://schemas.microsoft.com/2003/10/Serialization/ namespace.
Questions:

*

*Is there a xsd schema file for the namespace used by serializer which I could import into my schema?

*For now I am defining those attributes as a xs:ID / xs:IDREF pair. Is that correct?

Thanks in advance.

A: The xsd schema is supposed to described here - look for the section Data Contract Serialization Schema. However, if you do look for your attributes, you will not find them in there - documentation bug!
To get the full schema, take a look at this and this - inside the WSDL types, you'll find the correct schema. As for your assumption regarding the attributes, yes, you are correct.
I am inlining it here, just in case:
<?xml version="1.0"?>
<xs:schema xmlns:tns2="http://schemas.microsoft.com/2003/10/Serialization/" attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://schemas.microsoft.com/2003/10/Serialization/" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="anyType" nillable="true" type="xs:anyType"/>
    <xs:element name="anyURI" nillable="true" type="xs:anyURI"/>
    <xs:element name="base64Binary" nillable="true" type="xs:base64Binary"/>
    <xs:element name="boolean" nillable="true" type="xs:boolean"/>
    <xs:element name="byte" nillable="true" type="xs:byte"/>
    <xs:element name="dateTime" nillable="true" type="xs:dateTime"/>
    <xs:element name="decimal" nillable="true" type="xs:decimal"/>
    <xs:element name="double" nillable="true" type="xs:double"/>
    <xs:element name="float" nillable="true" type="xs:float"/>
    <xs:element name="int" nillable="true" type="xs:int"/>
    <xs:element name="long" nillable="true" type="xs:long"/>
    <xs:element name="QName" nillable="true" type="xs:QName"/>
    <xs:element name="short" nillable="true" type="xs:short"/>
    <xs:element name="string" nillable="true" type="xs:string"/>
    <xs:element name="unsignedByte" nillable="true" type="xs:unsignedByte"/>
    <xs:element name="unsignedInt" nillable="true" type="xs:unsignedInt"/>
    <xs:element name="unsignedLong" nillable="true" type="xs:unsignedLong"/>
    <xs:element name="unsignedShort" nillable="true" type="xs:unsignedShort"/>
    <xs:element name="char" nillable="true" type="tns2:char"/>
    <xs:simpleType name="char">
        <xs:restriction base="xs:int"/>
    </xs:simpleType>
    <xs:element name="duration" nillable="true" type="tns2:duration"/>
    <xs:simpleType name="duration">
        <xs:restriction base="xs:duration">
            <xs:pattern value="\-?P(\d*D)?(T(\d*H)?(\d*M)?(\d*(\.\d*)?S)?)?"/>
            <xs:minInclusive value="-P10675199DT2H48M5.4775808S"/>
            <xs:maxInclusive value="P10675199DT2H48M5.4775807S"/>
        </xs:restriction>
    </xs:simpleType>
    <xs:element name="guid" nillable="true" type="tns2:guid"/>
    <xs:simpleType name="guid">
        <xs:restriction base="xs:string">
            <xs:pattern value="[\da-fA-F]{8}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12}"/>
        </xs:restriction>
    </xs:simpleType>
    <xs:attribute name="FactoryType" type="xs:QName"/>
    <xs:attribute name="Id" type="xs:ID"/>
    <xs:attribute name="Ref" type="xs:IDREF"/>
</xs:schema>


text:
Q: Oracle Apex 20.1 error after login, session has expired Using Apex 20.1 with Oracle DB XE 18c on Windows.
After installing any productivity App and after adding username and password and login to the application, an error appears: "Your session has expired, Click here to create a new session."
I tried many times to reinstall them without any good. The same message appears after login, and I can't run the application.
This is not Session Timeout error.
Any help please?

A: I find the solution the problem was with the firefox browser security with ORA_WWV_PACKAGED_APPLICATIONS whitch make him i think prevent the user/site cookies.
Once i add exception to the firefox security for Apex URL, it didn't happen again.


text:
Q: Popmodal from overriden back button I am having some issues having my back button properly pop my modal after a user acknowledged that they will lose their changes if they do so. I suppose the issue lies in how to properly await the async method within a method that cannot be async due to how it is coded.
In my code behind I have the following method:
protected override bool OnBackButtonPressed()
        {
            base.OnBackButtonPressed();
            Task<bool> confirm = DisplayAlert("Are you sure?", "All unsaved changes will be lost", "I'm Sure", "Cancel");
            confirm.ContinueWith(x =>
            {
                if(x.Result)
                {
                    var task = Navigation.PopModalAsync();
                    task.Wait();
                }
            });

            return true;
        }

I can see that it does properly hit my breakpoint inside if the user has clicked "I'm Sure". However, after doing that the modal still remains on the page.
I call my modal using the following method (it is wrapped in a NavigationPage as I wanted to be able to leverage Toolbar items, if this is an anti pattern please let me know)
private async void EditSwipeItem_Invoked(object sender, EventArgs e)
        {
            var unitOfWork = container.Resolve<IUnitOfWork>();
            var invoked = sender as SwipeItem;
            var element = invoked.BindingContext as InventoryModel;
            await Navigation.PushModalAsync(new NavigationPage(new AddEditInventoryList(true, "8dc9e483-1d63-4629-b386-680ad7c9a324", element.InventoryId, unitOfWork)));
        }

The code for the backbutton is based off of what I wrote for the CancelToolBar_Clicked, and it works correctly (That is, the modal is popped after the user acknowledges the prompt).
private async void CancelToolBar_Clicked(object sender, EventArgs e)
        {
            bool confirm = await DisplayAlert("Are you sure?", "All unsaved changes will be lost", "I'm Sure", "Cancel");

            if(confirm)
                await Navigation.PopModalAsync();
        }

Edit:
This is what my XAML looks like:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Invenutory.Views.Inventory.AddEditInventoryList">
    <ContentPage.ToolbarItems>
        <ToolbarItem Text="Save"
                     Order="Primary"
                     Clicked="SaveToolBarItem_Clicked"
                     Priority="1"/>
        <ToolbarItem Text="Cancel"
                     Order="Secondary"
                     Clicked="CancelToolBar_Clicked"
                     Priority="0"/>
    </ContentPage.ToolbarItems>
    <ContentPage.Content>
        <StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"
                     Padding="20">
            <Frame HorizontalOptions="FillAndExpand"
               VerticalOptions="Start"
               Padding="20"
               CornerRadius="8"
               BorderColor="AliceBlue">
                <StackLayout
                       HorizontalOptions="FillAndExpand"
                       VerticalOptions="StartAndExpand">

                    <StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand"
                                 Orientation="Vertical">
                        <Label Text="Name: " HorizontalOptions="Start" VerticalOptions="Start" />
                        <Entry HorizontalOptions="FillAndExpand" VerticalOptions="Start" Text="{Binding Name, Mode=TwoWay}" IsSpellCheckEnabled="True" IsTextPredictionEnabled="True" />
                    </StackLayout>

                    <StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand"
                                 Orientation="Vertical">
                        <Label Text="Description: " HorizontalOptions="StartAndExpand" VerticalOptions="Start"/>
                        <Editor HorizontalOptions="FillAndExpand" VerticalOptions="Start" Text="{Binding Description, Mode=TwoWay}" IsSpellCheckEnabled="True" IsTextPredictionEnabled="True" />
                    </StackLayout>

                    <StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand"
                                 Orientation="Vertical">
                        <Label Text="Count: " HorizontalOptions="Start" VerticalOptions="Start"/>
                        <Entry Keyboard="Numeric" HorizontalOptions="FillAndExpand" VerticalOptions="Start" Text="{Binding Count, Mode=TwoWay}" />
                    </StackLayout>
                </StackLayout>
            </Frame>
            <Frame HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" Padding="20" CornerRadius="8" BorderColor="AliceBlue">
                <StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
                    <Image HorizontalOptions="FillAndExpand" VerticalOptions="Start" HeightRequest="150" Aspect="AspectFit" BackgroundColor="Gray" Source="{Binding CapturedPhoto}" />
                    <Button Text="Take Photo" HorizontalOptions="FillAndExpand" VerticalOptions="Start" Command="{Binding TakePhotoCommand, Mode=TwoWay}"/>
                </StackLayout>
            </Frame>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

A: I was able to solve this by updating my inner .ContinueWith to look as follows:
confirm.ContinueWith(x =>
            {
                if(x.Result)
                {
                    MainThread.BeginInvokeOnMainThread(async () =>
                    {
                        await Navigation.PopModalAsync();
                    });
                }
            });


text:
Q: Searching for a german MIPS Processor Explaintation I'm currently searching for a german MIPS Manual, explaining how the processor works, it's operations and all that stuff like the MIPS IV-ISA PDF Document. The problem is: My english is really bad, I'm even doubting, that you can understand me. And reading stuff in english and translating it into my language is pretty hard for me. And because I don't want to misunderstand anything, I'm searching for a german MIPS Manual.
I'm currently working on an ASM Patching tool for a N64 Game, where I need to know how the processor actually works, what it does. Knowing the instructions of MIPS is not enough.
Mainly I'm searching for a german MIPS R4000/R4200 Manual.
Thank you in advance,
Cajetan.

A: English first ...
Your English as far as phrasing this question is nowhere near as bad as you think - it's clearly understandable and complete. That said, this doesn't necessarily mean you'll get better answers here than what the omniscient garbage pile spits out when asked ... a few leads, not exhaustive, and not MIPS4000 specific ... so less useful to you than you ask for. What one finds are largely links to websites at German universities using MIPS / MIPS Simulators for teaching.
German ...
So schlecht wie du denkst ist dein Englisch gar nicht - die Frage ist klar verstaendlich formuliert, und vollstaendig. Allerdings bedeutet das nicht unbedingt, dass du hier bessere Antworten bekommst als per Frage an die Allwissende Muellhalde. Jene spuckt einige Antworten aus, allerdings nicht so umfassend wie du gerne haettest, und auch nicht MIPS4000-spezifisch. Das meiste was man findet sind Links zu Webseiten von Unis, die MIPS und/oder MIPS-Simulatoren zu Lehrzwecken verwenden:

*

*MIPS (2000) Intro, TU Dresden

*MIPS 2000 via SPIM Emulator, Karlsruhe Technische Informatik

*MIPS Assembler, Technische Informatik II
(aus Vorlesung 'Grundlagen der Rechnerarchitektur', fundamentals of computer architecture) - sehr ausfuehrliche Einfuehrung in den MIPS Befehlssatz

*Vorlesung Rechnerarchitektur (Lecture 'computer architecture')
(BTU Chemnitz, relevant bzgl. Unterschiede MIPS3000 -> MIPS4000 sind Abschnitt 6.2 / 6.4)

Nach kurzem Durchblaettern muss ich allerdings sagen, dass der Befehlssatz und die Architektur-Besonderheiten (pipeline struktur, caches, ...) zwar gut abgedeckt sind, aber Verweise auf Kontroll-Register etc. fehlen; ob du vollkommen ohne die englischen Orginal-MIPS-Dokumente auskommst, ist daher schwer zu sagen.
waere ich du ... wuerde ich die obigen Dokumente zusammen mit dem MIPS4000 User's Manual benutzen um die Englisch-Luecken per "Kontext" zu fuellen ... das User's manual beschreibt den System Control Coprocessor - CP0, die FPU - CP1 und die MMU recht ausfuehrlich.
Viel Glueck !


text:
Q: x86 ASM div dividend register occupation For x86 div operation, can someone please help understand why the EAX register is not used when the operand/dividend size is a double word, instead of splitting them into DX:AX registers?
Given here: https://c9x.me/x86/html/file_module_x86_id_72.html
Is it something to do with the sign?
Thanks!

A: It's historical.  That's what the 16-bit 8086 did, because it had no 32-bit registers.  And when the 32-bit 80386 was introduced, one of its major "features" was backward compatibility with the 8086: it could run 8086 code in its "real" or "virtual 8086" modes.
So the 80386 CPU had to support an instruction that did a 32-bit divide of a dividend split across two 16-bit registers, for use in real/v86 modes.  And so it might as well use the same behavior in 32-bit protected mode, rather than use more transistors to implement an alternate form.  Anyhow, it was generally part of Intel's philosophy to have as much similarity between the 386 and 8086 as possible, even if that led to some awkward choices that wouldn't have made sense for a generic 32-bit machine.  (We're still paying for many of those choices, 35 years later.)
In 32-bit or 64-bit mode, rather than use this form, you may prefer to put your 32-bit dividend in eax, zero out edx, and do a 64->32 bit div (quadword/doubleword operand size).  This also allows you a full 32 bits for the result, which then cannot overflow; whereas with a 32->16 bit div, you will get an exception if the result does not fit in 16 bits.


text:
Q: How do I access the full path of a request in Akka HTTP request? In some contexts I can match on the remaining path using a PathDirective to get the information I need about the path.  For example, when route below is directly bound and handled by Akka HTTP, every request will echo back the requested path as desired.
val route =
  path(Remaining) { path =>
    complete(path)
  }

However, when the above route is combined elsewhere in the application, the path variable above may only hold part of the requested path not giving the desired results.
For example if the actual bound route is be,
val actualRoute = pathPrefix("echo") { route }

The "echo/" part of the overall path will be missing from the response given to the user.
How can the complete path be reliably accessed?

A: Directives extractMatchedPath and extractUnmatchedPath let you access the path without matching the path like you path directive does above.  These two can be combined to construct the full path:
val route =
  extractMatchedPath { matched =>
    extractUnmatchedPath { unmatched =>
      complete((matched.dropChars(1) ++ unmatched).toString)
    }
  }

However it is probably cleaner just to extract the Path from the URI directly:
val route =
  extractUri { uri =>
    complete(uri.toRelative.path.dropChars(1).toString)
  }

Note that in both cases we needed to call .dropChars(1) to drop the initial forward slash and be consistent with the output you got using the path directive.


text:
Q: Python - "IOError: [Errno 13] Permission denied" when running cron job but not when running from command line I have SSHed from my local machine (a Mac) to a remote machine called "ten-thousand-dollar-bill" as the user "chilge".
I want to run a Python script in the folder "/afs/athena.mit.edu/c/h/chilge/web_scripts" that generates and saves a .png image to the folder "/afs/athena.mit.edu/c/h/chilge/www/TAF_figures/KORD/1407". When I run the script from the command line, the image is generated and saved without any issues. When I run the script as cron job, though (the crontab resides in "/afs/athena.mit.edu/c/h/chilge/cron_scripts"), I get the following error:

Traceback (most recent call last):

File "/afs/athena.mit.edu/user/c/h/chilge/web_scripts/generate_plots.py", line 15, in
        save_taffig(taf,fig)
File "/afs/athena.mit.edu/user/c/h/chilge/web_scripts/plotting.py", line 928, in save_taffig
        fig.savefig(os.getcwd()+'/'+savename+'.png')
File "/usr/lib64/python2.7/site-packages/matplotlib/figure.py", line 1084, in savefig
        self.canvas.print_figure(*args, **kwargs)
File "/usr/lib64/python2.7/site-packages/matplotlib/backend_bases.py", line 1923, in print_figure
        **kwargs)
File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 443, in print_png
        filename_or_obj = file(filename_or_obj, 'wb')
IOError: [Errno 13] Permission denied: '/afs/athena.mit.edu/user/c/h/chilge/www/TAF_figures/KORD/1407/140723-1200_AMD_140723-1558.png'

I believe I've correctly changed the permissions of all of the necessary directories, but I'm still getting this error. I am not sure why the script would run fine from the command line, but fail when I try to run the script as a cron job.
(Also, I'm not sure if this will be relevant, but don't have sudo permissions on the remote machine.)

A: Maybe an other software opens the file which you want to overwrite?


text:
Q: Divisor on curve of genus $2$ I suffer from lack of concrete examples in Algebraic Geometry, so I will appreciate it if somebody can help me in understanding a bit better this one:
Let $\mathcal{C}$ be a genus $2$ curve (projective, smooth and complex). Let $K$ be the canonical class and take a couple of different points $p,q\in\mathcal{C}$. Consider the divisor $K+p+q$.
If I'm correct, (using Riemann-Roch theorem) this divisor defines a map taking $\mathcal{C}$ into a plane projective curve with one node. Is this map birational? How can I visualize it in a concrete way?.
Many thanks for any useful comments.

A: This is a very nice example! In fact, provided that $p+q$ is not a canonical divisor, the linear system $K+p+q$ separates "most" points, since $K$ is the only $g^1_2$ on the curve. Thus for any $r$ and $s$ not equal to $p$ and $q$, $\ell(K+p+q-r-s) = 1 = 3-2$, so $r$ and $s$ are separated by the linear system (the dimension drops twice, so you know that $s$ is not in every divisor of the linear system containing $r$, and thus $s$ maps to a different point). The only pair of points for which this doesn't happen is $p$ and $q$ themselves! So the image of $q$ is in every hyperplane ($=$line) containing the image of $p$ (note that imposing that a hyperplane section contain $p$ drops the dimension by $1$, from $3$ to $2$, but further imposing that it contain $q$ leaves the dimension at $2$). This shows that indeed the mapping is birational and that there is exactly one node, which is the image of both $p$ and $q$, in the image curve.


text:
Q: Create Checkbox Group from Slice I'm starting out with Go and therefore this may be a simple answer but I can't find it on the net so far.
I have the following structs:
type Answer struct {
    AnswerId   int
    AnswerText string
    Selected   bool
}

type Answers struct {
    answers []Answer
}

type Question struct {
    QuestionId int
    Answers
    QuestionText string
}

This is a simple look of the domain model that backs a web app for a questionnaire.
func loadPage() (*Question, error) {
    return &Question{
        QuestionId:   321,
        QuestionText: "What's the answer?",
        Answers: Answers{
            answers: []Answer{
                Answer{
                    AnswerId:   1,
                    AnswerText: "Answer number 1",
                    Selected:   false,
                },
                Answer{
                    AnswerId:   2,
                    AnswerText: "Answer number 2",
                    Selected:   false,
                },
            },
        },
    }, nil
}

Here you can see that I've stubbed out a Question with a few answers. This has been stubbed just so I can send something to the view.
func viewHandler(w http.ResponseWriter, r *http.Request) {
    p, _ := loadPage()
    fmt.Fprintf(w, for _,element := range p.Answers.answers {
      //Do something with each element in answers
    })
}

This is where I'm stuck; my viewHandler. What is the syntax that will allow me to create a checkbox group based upon the contents of my answers slice? Any help will be gratefully received.

A: First, here is what you can do to improve the code
Type Answers []Answer

type Question struct {
    QuestionId int
    // Question is not an "Answers" but has "Answers"
    Answers Answers
    QuestionText string
}

Instead of using embedded type to represent "IS-A" relationship, having an attribute of type Answers should be more appropriate and to avoid complex struct definition.
Now here is what your viewHandler might look like:
func ViewHandler(w http.ResponseWriter, r *http.Request) {

    // This should be loaded from another template file
    const tpl = `
    <!DOCTYPE html>

        <form action="demo" method="POST">

{{.QuestionText}}

            {{range .Answers}}
                <input type="radio" name="" {{if .Selected}}checked{{end}}
                >{{.AnswerText}}

            {{end}}

    `

    t, _ := template.New("questionaire").Parse(tpl)

    pagedata, _ := loadPage()

    // Pass in the data struct
    _ = t.Execute(w, pagedata)
}

You just have to parse the template, then with Execute pass the data struct you want its data available in the context of the response.
See the full code here https://play.golang.org/p/6PbX6YsLNt


text:
Q: The option selection in the Select box is not available The option selection in the Select box is not available.I don't know what the cause is. If you check the value by notifying, the first option is "12. Selecting "36" also outputs "12"
<form action="{{ route('penpal.index', ['list'=>$list,'page' => $page]) }}" method="post">
            @csrf
            <select id="inputState" class="form-control" style="height:35px; width:80%" name="list" onchange="this.form.submit()">
                <option value="12">@lang('penpal/component/indexMenu.twelve')</option>
                <option value="24">@lang('penpal/component/indexMenu.twenty_four')</option>
                <option value="36">@lang('penpal/component/indexMenu.thirty_six')</option>
            </select>
        </form>

 alert($("#inputState").val());

A: nothing is wrong with your code. you just dont get the logic properly. here is a modify version of your code i wrote. if its of help to you, vote me. thanx
//the blade form. the javascript gets the value of the selected item, assign it to the input box and submit your form automatically.

    <form action="{{ route('penpal.index', ['list'=>$list,'page' => $page]) }}" method="post" id="submitForm">
     {{ csrf_field() }}
    <select id="inputState" class="form-control" style="height:35px; width:80%" name="list">
     <option value="">-Please Select-</option>
      <option value="12">@lang('penpal/component/indexMenu.twelve')</option>
        <option value="24">@lang('penpal/component/indexMenu.twenty_four')</option>
        <option value="36">@lang('penpal/component/indexMenu.thirty_six')</option>
  </select>
  <input type="text" class="form-control" id="valueid" name="id" value="">
    </form>

//javascript code
<script>

  $(document).ready(function(){

       $("#inputState").change(function(e){
       var value= e.target.value;
       //alert(value);
       document.getElementById('valueid').value = value; //assign select value to input field.
       $('#submitForm').submit(); //submit form

    });

  });
</script>