text:
Q: Detecting square in image At a school we are preparing artwork which we have scanned and want automatically crop to the correct size. The kids (attempt) to draw within a rectangle:

I want to detect the inner rectangle borders, so I have applied a few filters with accord.net:
var newImage = new Bitmap(@"C:\Temp\temp.jpg");
var g = Graphics.FromImage(newImage);
var pen = new Pen(Color.Purple, 10);

var grayScaleFilter = new Grayscale(1, 0, 0);
var image = grayScaleFilter.Apply(newImage);
image.Save(@"C:\temp\grey.jpg");

var skewChecker = new DocumentSkewChecker();
var angle = skewChecker.GetSkewAngle(image);
var rotationFilter = new RotateBilinear(-angle);
rotationFilter.FillColor = Color.White;
var rotatedImage = rotationFilter.Apply(image);
rotatedImage.Save(@"C:\Temp\rotated.jpg");

var thresholdFilter = new IterativeThreshold(10, 128);
thresholdFilter.ApplyInPlace(rotatedImage);
rotatedImage.Save(@"C:\temp\threshold.jpg");

var invertFilter = new Invert();
invertFilter.ApplyInPlace(rotatedImage);
rotatedImage.Save(@"C:\temp\inverted.jpg");

var bc = new BlobCounter
{
    BackgroundThreshold = Color.Black,
    FilterBlobs = true,
    MinWidth = 1000,
    MinHeight = 1000
};

bc.ProcessImage(rotatedImage);
foreach (var rect in bc.GetObjectsRectangles())
{
    g.DrawRectangle(pen, rect);
}

newImage.Save(@"C:\Temp\test.jpg");

This produces the following inverted image that the BlobCounter uses as input:

But the result of the blobcounter isn't super accurate, the purple lines indicate what the BC has detected.

Would there be a better alternative to the BlobCounter in accord.net or are there other C# library better suited for this kind of computer vision?

A: Here is a simple solution while I was bored on my lunch break.
Basically it just scans all the dimensions from outside to inside for a given color threshold (black), then takes the most prominent result.
Given
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool IsValid(int* scan0Ptr, int x, int y,int stride, double thresh)
{
   var c = *(scan0Ptr + x + y * stride);
   var r = ((c >> 16) & 255);
   var g = ((c >> 8) & 255);
   var b = ((c >> 0) & 255);

   // compare it against the threshold
   return r * r + g * g + b * b < thresh;
}

private static int GetBest(IEnumerable<int> array)
   => array.Where(x => x != 0)
      .GroupBy(i => i)
      .OrderByDescending(grp => grp.Count())
      .Select(grp => grp.Key)
      .First();

Example
private static unsafe Rectangle ConvertImage(string path, Color source,  double threshold)
{

   var thresh = threshold * threshold;

   using var bmp = new Bitmap(path);

   // lock the array for direct access
   var bitmapData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppPArgb);
   int left, top, bottom, right;

   try
   {
      // get the pointer
      var scan0Ptr = (int*)bitmapData.Scan0;
      // get the stride
      var stride = bitmapData.Stride / 4;

      var array = new int[bmp.Height];

      for (var y = 0; y < bmp.Height; y++)
      for (var x = 0; x < bmp.Width; x++)
         if (IsValid(scan0Ptr, x, y, stride, thresh))
         {
            array[y] = x;
            break;
         }

      left = GetBest(array);

      array = new int[bmp.Height];

      for (var y = 0; y < bmp.Height; y++)
      for (var x = bmp.Width-1; x > 0; x--)
         if (IsValid(scan0Ptr, x, y, stride, thresh))
         {
            array[y] = x;
            break;
         }

      right = GetBest(array);

      array = new int[bmp.Width];

      for (var x = 0; x < bmp.Width; x++)
      for (var y = 0; y < bmp.Height; y++)
         if (IsValid(scan0Ptr, x, y, stride, thresh))
         {
            array[x] = y;
            break;
         }

      top = GetBest(array);

      array = new int[bmp.Width];

      for (var x = 0; x < bmp.Width; x++)
      for (var y = bmp.Height-1; y > 0; y--)
         if (IsValid(scan0Ptr, x, y, stride, thresh))
         {
            array[x] = y;
            break;
         }

      bottom = GetBest(array);

   }
   finally
   {
      // unlock the bitmap
      bmp.UnlockBits(bitmapData);
   }

   return new Rectangle(left,top,right-left,bottom-top);

}

Usage
var fileName = @"D:\7548p.jpg";

var rect = ConvertImage(fileName, Color.Black, 50);

using var src = new Bitmap(fileName);
using var target = new Bitmap(rect.Width, rect.Height);
using var g = Graphics.FromImage(target);

g.DrawImage(src, new Rectangle(0, 0, target.Width, target.Height), rect, GraphicsUnit.Pixel);

target.Save(@"D:\Test.Bmp");

Output

Notes :

*

*This is not meant to be bulletproof or the best solution. Just a fast simple one.

*There are many approaches to this, even machine learning ones that are likely better and more robust.

*There is a lot of code repetition here, basically I just copied, pasted and tweaked for each side

*I have just picked an arbitrary threshold that seems to work. Play with it

*Getting the most common occurrence for the side is likely not the best approach, maybe you would want to bucket the results.

*You could probably sanity limit the amount a side needs to scan in.


text:
Q: How to access complex JSON data in PHP Here is the JSON response in which I need your help.
I need to access "age" key inside 'attribute'.
I really tried every possible ways that i could get. So can u please try to help me out :)

A: There are 2 ways I can see checking the json you just provided, one is by iterating the array, and the other one is accessing it by index:
$json = json_decode($response);
foreach ($json as $item) {
    $value = $item->item->attribute->age->value;
    var_dump($value);
}

the other way:
$value = $json[0]->item->attribute->age->value;

A: Another option, is that when you call json_decode by default you get a php object, however, if you add an optional boolean parameter you get an array which can be easier in situations like this to access nested elements.
// $data is the original json string
$json = json_decode($data, true);
print_r($json);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Please provide a Migration in the builder or call fallbackToDestructiveMigration in the builder in which case Room will re-create all of the tables I am using Room With RxJava2. I added a column in my table so I am migrating to new version. I have changed my Database version to 2.
Following is my migration code
static final Migration MIGRATION_1_2 = new Migration(1, 2) {
    @Override
    public void migrate(SupportSQLiteDatabase database) {
        database.execSQL("ALTER TABLE users "
        +"ADD COLUMN address String");

    }
};

AppDatabase db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, DB_NAME)
.addMigrations(MIGRATION_1_2)
.build();

If you want to see the full code,
I am refering to this example on Github, it does not have the migration code
https://github.com/alahammad/RoomSample

I am following the steps described in the documentation but still my app crashes.
Error Logs
Process: demo.karaoke.sensibol.com.roomrajava2, PID: 13655
    io.reactivex.exceptions.OnErrorNotImplementedException: A migration from 1 to 2 is necessary. Please provide a Migration in the builder or call fallbackToDestructiveMigration in the builder in which case Room will re-create all of the tables.
        at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:704)
        at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:701)
        at io.reactivex.internal.operators.maybe.MaybeCallbackObserver.onError(MaybeCallbackObserver.java:83)
        at io.reactivex.internal.operators.maybe.MaybeObserveOn$ObserveOnMaybeObserver.run(MaybeObserveOn.java:99)
        at io.reactivex.android.schedulers.HandlerScheduler$ScheduledRunnable.run(HandlerScheduler.java:109)
        at android.os.Handler.handleCallback(Handler.java:815)
        at android.os.Handler.dispatchMessage(Handler.java:104)
        at android.os.Looper.loop(Looper.java:194)
        at android.app.ActivityThread.main(ActivityThread.java:5643)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
     Caused by: java.lang.IllegalStateException: A migration from 1 to 2 is necessary. Please provide a Migration in the builder or call fallbackToDestructiveMigration in the builder in which case Room will re-create all of the tables.
        at android.arch.persistence.room.RoomOpenHelper.onUpgrade(RoomOpenHelper.java:82)
        at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.onUpgrade(FrameworkSQLiteOpenHelper.java:118)
        at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:256)
        at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
        at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:93)
        at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:54)
        at android.arch.persistence.room.RoomDatabase.query(RoomDatabase.java:193)
        at demo.karaoke.sensibol.com.roomrajava2.UserDao_Impl$4.call(UserDao_Impl.java:137)
        at demo.karaoke.sensibol.com.roomrajava2.UserDao_Impl$4.call(UserDao_Impl.java:135)
        at io.reactivex.internal.operators.maybe.MaybeFromCallable.subscribeActual(MaybeFromCallable.java:46)
        at io.reactivex.Maybe.subscribe(Maybe.java:3749)
        at io.reactivex.internal.operators.maybe.MaybeSubscribeOn$SubscribeTask.run(MaybeSubscribeOn.java:54)
        at io.reactivex.Scheduler$DisposeTask.run(Scheduler.java:452)
        at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:66)
        at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:57)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:818)

A: If you don't want to provide migrations and you specifically want your database to be cleared when you upgrade the version, call fallbackToDestructiveMigration in the database builder
database = Room.databaseBuilder(context.getApplicationContext(),
                    UsersDatabase.class, "Sample.db")
            .fallbackToDestructiveMigration()
            .build();

A: add ".fallbackToDestructiveMigration()" before build(),
and also increases your version number fixed for me. hope it fixes for someone searching. here.

A: add  ".fallbackToDestructiveMigration()" before build(),

A: I ran your app from GitHub and made a sample migration from ver 1 to ver 2. It turns out there's a mistake in SQL query. It should be:
static final Migration MIGRATION_1_2 = new Migration(1, 2) {
    @Override
    public void migrate(SupportSQLiteDatabase database) {
        database.execSQL("ALTER TABLE users "
        +"ADD COLUMN address TEXT");

    }
};

String > TEXT
It's also preferable to make Room's database instance a singleton, and use it only in Repo/CacheManager class. Please check the gist for a complete code changes - https://gist.github.com/lomza/0f311a1b1e9c896bc58dff925d65eab2

A: If it is acceptable to lose existing data call the fallbackToDestructiveMigration() builder method when you create the database
Example:
db = Room.databaseBuilder(getApplicationContext(),
                    User.class, "DB_Name")
            .fallbackToDestructiveMigration()
            .build();


text:
Q: How to add printed data i.e. odr_id of terminal to database using model.py or any alternative option? I have created selenium project which automates mobile recharge. In my selenium file, I want to add printed data i.e. odr_id of terminal to database using model.py or any alternative option?
After completion of "recharge successful" I need to send a success receipt into my database. I used print(order_id.text) to get receipt in my terminal. now I don't know how to send that receipt to my database (I am using sqlite3)
odr_id = pay.find_element_by_id('deep-dtyp-order-details-section')
sleep(3)
print(odr_id.text)

#views.py
def odr(request):
    name = odr_id.GET(request)

    return [Amazon.order_detail, name]

pass


text:
Q: All combinations of a row in a dataframe i have the following Dataframe (df = )  with around 40 mio rows.
No  Color
A   Red
A   Black
B   White
B   Orange
B   Green
C   Red
C   Green
D   Yellow
D   Orange
D   Green

i try to have the following output:
No  Color
A   Red
A   Black
B   White
B   Orange
B   White
B   Green
B   Orange
B   Green
C   Red
C   Green
D   Yellow
D   Orange
D   Yellow
D   Green
D   Orange
D   Green

at first i thought to use itertools combinations,    it.combinations(Colors["Colors"],2), but the problem was, that it gives me the combinations of the whole column and don't correlate to the column "No".
The next try was to aggregate the whole dataframe to have all the needed combination in a list and only have about 5000 rows
from:
No Colors
A   Red, Black
B   White, Orange, Green
C   Red, Green, Yellow
D   Orange, Green

to:
No  Colors              CombColors
A   Red,Black           Red, Black
B   White,Orange,Green  White, Orange, White, Green, Orange, Green
C   Red,Green,Yellow    Red, Green, Red, Yellow, Green, Yellow
D   Orange,Green        Orange, Green

with: df.apply(lambda x: list(it.combinations(x,2), axis =1) but this also doesn't work (all combinations in each row).
What is the right solution to achieve the wanted output (of attempt 1 or attempt 2)?
Edit: 1
if i try to use  df.apply(lambda x: list(it.combinations(x,2), axis =1) i generate following column
 No     Colors              CombColors
    A   Red,Black           [([Red, Black], [(['Red', 'Black'], ['White'..
    B   White,Orange,Green  [([White, Orange, Green], [(['Red', 'Black']...
    C   Red,Green,Yellow    [([Red, Green], [(['Red', 'Black'], ['White'...
    D   Orange,Green        [([Yellow, Orange, Green], [(['Red', 'Black']...

i think on problem is, i aggregate the Colors by a tuple or list (tuple is empty []). df.groupby("No")["Color"].apply(list).agg(tuple).to_frame()
nevertheless the itertool gives me a combination of every column.
Edit 2:
the solutions of alparslan mimaroğlu and Henry Vik work both and are (for me) astonishing. Till now i cannot understand the logic behind these, but i'll try! Thanks!

A: You can groupby by No and create the lists you want quite easily.
def combinations(group):
    return pd.Series(list(it.combinations(group['Color'].unique(), 2)))

df.groupby('No').apply(combinations).explode()

if you don't make it explode it will return you a list of color combinations

A: IIUC you can use groupby and agg:
print (df.groupby("No").agg(Colors=("Color", ", ".join),
                            CombColors=("Color", lambda d: ", ".join(chain.from_iterable(combinations(d, 2))))))

                   Colors                                    CombColors
No
A              Red, Black                                    Red, Black
B    White, Orange, Green    White, Orange, White, Green, Orange, Green
C              Red, Green                                    Red, Green
D   Yellow, Orange, Green  Yellow, Orange, Yellow, Green, Orange, Green


text:
Q: What does var = var && "*" mean in Javascript I am trying to work out some obfusicated code by reading it, and I was doing pretty well until a came across this:
a = a && "*"

Now I am still quite new to Javascript and these shortened uncommon javascript codes are still very foreign to me, this is the first time I have come across them.
Does anybody know what this does? I attempted it in a javascript code tester ad it just returned *, so I do not know.
Also, if anybody knows where I can look to find out what these uncommon lines of code do, that would be very helpful. They are all shortened and are sorts of things like this and
a = a || b

(I know what that one does)
But If there is some sort of name for this kind of javascript or a reference I can look at, that would be very helpful, I have been scouring Google for hours.
Thanks

A: If a is truthy, it assigns "*" to a.
If a is falsy, it remains untouched.

&& has short-circuit semantics: A compound expression (e1) && (e2)—where e1 and e2 are arbitrary expressions themselves—evaluates to either

*

*e1 if e1 evaluates to false in a boolean context—e2 is not evaluated

*e2 if e1 evaluates to true in a boolean context

This does not imply that e1 or e2 and the entire expression (e1) && (e2) need evaluate to true or false!
In a boolean context, the following values evaluate to false as per the spec:

*

*null

*undefined

*±0

*NaN

*false

*the empty string

All1 other values are considered true.
The above values are succinctly called "falsy" and the others "truthy".
Applied to your example: a = a && "*"
According to the aforementioned rules of short-circuit evaluation for &&, the expression evaluates to a if a is falsy, which is then in turn assigned to a, i.e. the statement simplifies to a = a.
If a is truthy, however, the expression on the right-hand side evaluates to *, which is in turn assigned to a.

As for your second question: (e1) || (e2) has similar semantics:
The entire expression evaluates to:

*

*e1 if e1 is truthy

*e2 if e1 is falsy

1 Exception


text:
Q: Запоминать нажатие на кнопки Telebot python При нажатии inline кнопок бот каждый раз заново вызывает функцию внутри метода, а как я могу записывать нажаты ли ранее кнопки?
@bot.callback_query_handler(func=lambda call: True)
def callBack(call):
    try:
        if call.data == 'yes':
            murkup = types.InlineKeyboardMarkup(row_width=2)
            button1 = types.InlineKeyboardButton("1", callback_data='yes1')
            button2 = types.InlineKeyboardButton("2", callback_data='yes2')
            button3 = types.InlineKeyboardButton("3", callback_data='yes3')
            button4 = types.InlineKeyboardButton("4", callback_data='yes4')
            button5 = types.InlineKeyboardButton("5", callback_data='yes5')
            murkup.add(button1, button2, button3, button4, button5)
            bot.send_message(call.message.chat.id, "Да, я так и думал. Разбираем роли ",
                             reply_markup=murkup)
        elif call.data == 'yes1':
            bot.send_message(call.message.chat.id,
                             "Роль КЕРРИ занята {0.first_name}".format(call.from_user),
                             parse_mode="html")
        elif call.data == 'yes2':
            bot.send_message(call.message.chat.id,
                             "Роль МИДЕР занята {0.first_name}".format(call.from_user),
                             parse_mode="html")
        elif call.data == 'yes3':
            bot.send_message(call.message.chat.id,
                             "Роль ХАРДЛАЙНЕР занята {0.first_name}".format(call.from_user),
                             parse_mode="html")
        elif call.data == 'yes4':
            bot.send_message(call.message.chat.id,
                             "Роль РОУМЕР занята {0.first_name}".format(call.from_user),
                             parse_mode="html")
        elif call.data == 'yes5':
            bot.send_message(call.message.chat.id,
                             "Роль САППОРТ занята {0.first_name}".format(call.from_user),
                             parse_mode="html")
        elif call.data == 'no':
            bot.send_message(call.message.chat.id, "Нет? А ты уверен  ?")
    except Exception as e:
        print(repr(e))

Если я пропишу в каждом if по переменной и запишу в неё True, то после следующего нажатия на кнопку всё обнулиться.

A: попробуйте сделать список и при нажатии проверять есть ли в списке, если нет то добавляешь,  если есть то пишешь что занято.
примерно вот так
roles = []
@bot.callback_query_handler(func=lambda call: True)
def callBack(call):
    try:
        if call.data == 'yes':
            murkup = types.InlineKeyboardMarkup(row_width=2)
            button1 = types.InlineKeyboardButton("1", callback_data='yes1')
            button2 = types.InlineKeyboardButton("2", callback_data='yes2')
            button3 = types.InlineKeyboardButton("3", callback_data='yes3')
            button4 = types.InlineKeyboardButton("4", callback_data='yes4')
            button5 = types.InlineKeyboardButton("5", callback_data='yes5')
            murkup.add(button1, button2, button3, button4, button5)
            bot.send_message(call.message.chat.id, "Да, я так и думал. Разбираем роли ",
                             reply_markup=murkup)
        elif call.data == 'yes1':
            if roles.count('yes1') > 0:
                bot.send_message(call.message.chat.id,
                             "Роль КЕРРИ занята {0.first_name}".format(call.from_user),
                             parse_mode="html")
            else:
                roles.append('yes1')
        elif call.data == 'yes2':
            if roles.count('yes2') > 0:
                bot.send_message(call.message.chat.id,
                             "Роль МИДЕР занята {0.first_name}".format(call.from_user),
                             parse_mode="html")
            else:
                roles.append('yes2')
        elif call.data == 'yes3':
            if roles.count('yes3') > 0:
                bot.send_message(call.message.chat.id,
                             "Роль ХАРДЛАЙНЕР занята {0.first_name}".format(call.from_user),
                             parse_mode="html")
            else:
                roles.append('yes3')
        elif call.data == 'yes4':
            if roles.count('yes4') > 0:
                bot.send_message(call.message.chat.id,
                             "Роль РОУМЕР занята {0.first_name}".format(call.from_user),
                             parse_mode="html")
            else:
                roles.append('yes4')
        elif call.data == 'yes5':
            if roles.count('yes5') > 0:
                bot.send_message(call.message.chat.id,
                             "Роль САППОРТ занята {0.first_name}".format(call.from_user),
                             parse_mode="html")
            else:
                roles.append('yes5')
        elif call.data == 'no':
            bot.send_message(call.message.chat.id, "Нет? А ты уверен  ?")
    except Exception as e:
        print(repr(e))


text:
Q: how many ways to do programming in Excel . except for VBA I want to manipulate data in excel with some complex functions.
It seems that I have to use VBA.
However I don't want to learn it.
Is there any other way to do programming in the excel? Some language like C#?
I don't want to create a independent C# application using some interface provided by Excel. Only program in excel, like VBA, but a different language.

A:
I don't want to create a independent C# application using some interface provided by Excel. Only program in excel, like VBA, but a different language.

You cannot unfortunately. To program in Excel from within Excel you will have to learn VBA.
To program for Excel, be it VBA, VSTO(C#, VB.Net) you need to understand the Excel Object Model (EOM) without which you cannot do programming for Excel.
You don't need to learn VBA per se if you want to develop Office solutions from C# but as you become familiar with the EOM, you will notice that you automatically develop an understanding for VBA.
EDIT
Excel Object Model from Excel's perspective
Excel Object Model Overview from VS's perspective

A: You can develop Excel "Add-Ins" in C# using VSTO - Visual Studio Tools for Office (MSDN link).
This is not truly "inside Excel," but once installed your add-in can run without having to start up any external application.

A: Excel has a VBA editor built in to use VBA only.
If you want to use another language it would need to be external.
While you could make a C# add in, this is not in the built in editor as you described.

A: To the best of my knowledge, you simply cannot do this right now. In Office 15 it looks as though you'll be able to use JS:
http://www.zdnet.com/blog/microsoft/microsoft-to-focus-on-html5-and-javascript-for-office-15-extensions/10266


text:
Q: combine associative arrays in PHP <?php
$arrayName1 = array(
    '0' => array('name' => 'steve' ,'age' =>51 ) ,
    '1' => array('name' => 'john' ,'age' =>48 ) ,
);

$arrayName2 = array(
    '0' => array('name' => 'Steve' ,'place' =>'downtown' ),
    '1' => array('name' => 'John' ,'place' =>'New York' ),
);

$output = array(
    '0' => array('name' => 'steve' ,'age' =>51, 'place' =>'downtown'  ),
    '1' => array('name' => 'john' ,'age' =>48 ,'place' =>'New York' ),
);

Looking forward to combine two arrays wrt the "name" key, and obtain the sample  result as $output. array_merge() isn't working as expected.

A: use array_replace_recursive
$arrayName1 = array(
        '0' => array('name' => 'steve' ,'age' =>51 ) ,
        '1' => array('name' => 'john' ,'age' =>48 ) ,
    );

$arrayName2 = array(
    '0' => array('name' => 'steve' ,'place' =>'downtown' ),
    '1' => array('name' => 'john' ,'place' =>'New York' ),
);

$out = array_replace_recursive($arrayName1, $arrayName2);
print_r($out);

Output will be
Array (
    [0] => Array
        (
            [name] => steve
            [age] => 51
            [place] => downtown
        )

    [1] => Array
        (
            [name] => john
            [age] => 48
            [place] => New York
        )

)

A: If there is no guarantee that the same names will occur at the same indexes in the two arrays, you need to search for the matching name value in $arrayName2 and then merge the values from that entry into the value from $arrayName1:
$names2 = array_map('strtolower', array_column($arrayName2, 'name'));
$output = array();
foreach ($arrayName1 as $array) {
    $key = array_search($array['name'], $names2);
    if ($key !== false) {
        $output[] = $array + $arrayName2[$key];
    }
    else {
        $output[] = $array;
    }
}
print_r($output);

Output:
Array
(
    [0] => Array
        (
            [name] => steve
            [age] => 51
            [place] => downtown
        )
    [1] => Array
        (
            [name] => john
            [age] => 48
            [place] => New York
        )
)

Demo on 3v4l.org

A: Try this
function combine_array($array1,$array2,$combineProp){

foreach($array1 as $item){
    $combinedKey = strtolower($item[$combineProp]);
    $combinedArr1[$combinedKey] =  $item;
}

foreach($array2 as $key => $item){
    unset($item[$combineProp]);
    $combinedKey = strtolower($array2[$key][$combineProp]);
    $combinedArr2[$combinedKey] =  $item;

}

foreach($combinedArr1 as $key => $item){
    $combinedItem = $item;
    if($combinedArr2[$key]){
       $combinedItem = array_merge($item,$combinedArr2[$key]);
    }
    $resultArr[] =  $combinedItem;
}

return $resultArr;

}
 $output = combine_array($arrayName1,$arrayName2,'name');


text:
Q: How to remove  element inside another a list element? How to remove <input> element inside another a list element? For example,

        <input type='checkbox'></input>
        test number
        test information

I only need to remove <input></input> and everything else remain the same.
Super Thanks,
Joe

A: Try this:
$("li input").remove();

You may want to make your selectors more specific than that obviously.
More info on remove()

A: maybe this will do it for you :
$('li p > input').remove();

This will delete all input tags which are direct children of a p element which is within any li element.

A: To remove an element from the DOM you can use jQuery's .remove() function.

A: General selector for an <input> element inside a
 element is $('li input'), then you just need to call the .remove() jQuery function to remove any matched elements from the DOM.


text:
Q: Internet explorer shows gibberish for save/open file? I have this C# code which downloads a file from server :
 public static void DownloadBinaryFile(byte[] _ByteArray, string fullfileName)
        {
             fullfileName = "רועי.pdf"; //"Royi.pdf" in hebrew
             System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + fullfileName);
             System.Web.HttpContext.Current.Response.BinaryWrite(_ByteArray);
             System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
             System.Web.HttpContext.Current.Response.Flush();
             System.Web.HttpContext.Current.Response.End();
        }

Notice that filename has a fixed value ( for testing).
When I click a button :

I DO see in FIDDLER the right name :

And Chrome does shows the right filename to save :

But Internet explorer shows gibberish :

Additional Information :
IE 11 , windows 7 64bit , Edge :

Page encoding :

Question:
Why does the  filename shown as gibberish and how can I fix it ?

A: Because you can't use non-ASCII characters inside Content-Disposition without additional escaping. See http://greenbytes.de/tech/webdav/rfc6266.html#disposition.parameter.filename.


text:
Q: Database2Entities.SaveChanges() Not Working I have a .sdf databsae set up using entity framework. My code is below. However when I try to update the first record, it shows this correctly using console.writeline(), however when I "show table data" in visual studio, I can see the original value still there, it is not updated:
static void Main(string[] args)
    {
        Database2Entities context = new Database2Entities();

        DbSet<Product> products = context.Products;

        foreach (var product in products)
        {
            Console.WriteLine(product.name);
        }

        Console.WriteLine("---");

        Product prod = products.First();

        prod.name = "Faux lion fur hat";

        context.SaveChanges();

        products = context.Products;

        foreach (var product in products)
        {
            Console.WriteLine(product.name);
        }

        Console.Read();
    }
/*Output:
gloves
scarves
coates
lionFurHat
boots
---
Faux lion fur hat //This doesn't show in the diagram.
scarves
coates
lionFurHat
boots*/

A: I am not sure if this is the real issue but maybe the old  context.Products; is being reassigned to the same products again try maybe using a different variable like
var productsUpdated=context.Products;

and you can also try to refresh it
http://msdn.microsoft.com/en-us/library/bb503718.aspx
context.Refresh(RefreshMode.StoreWins, Products);


text:
Q: What is the general integration of acceleration with respect to position? $$W = \int_{x_i}^{x_f} F_x dx + \int_{y_i}^{y_f} F_y dy \int_{z_i}^{z_f} F_z dz$$
same as saying
$$E = m\int_{0}^{x_f} a_x dx + m\int_{0}^{y_f} a_y dy + m\int_{0}^{z_f} a_z dz$$
Using definitions of $a_{avg} = \frac{1}{2}\frac{\Delta {v^2}}{\Delta x}$ and maybe $a_{avg} = \frac{\Delta{v}}{\Delta{t}}$
Not sure how to do the integration to prove that this leads to $E = \frac{1}{2}m{v^2}$
Does the integral simply resolve to $m a x_f$ where $\Delta x$ and $x_f$ reduce leaving $\frac{1}{2}m\Delta {V^2}$?
Does it make sense that one could integrate something like that?
I wouldn't do $\int x dx = xx = x^2$
Maybe I'm missing something with fundamental definitions (I derived $a_{avg}$ from Galilean Kinematic Equations for uniform acceleration)
edit: I guess an easier question is: Does $\int{a}{dx}$ resolve to the same expression as $\int{a}{dt}$? If not, how are the integrations performed using formal notation?

A: $$
\int a\mathrm dx=\int a\frac{\mathrm dx}{\mathrm dt}\mathrm dt=\int\frac{\mathrm d^2x}{\mathrm dt^2}\frac{\mathrm dx}{\mathrm dt}\mathrm dt=\frac12\left(\frac{\mathrm dx}{\mathrm dt}\right)^2+\text{const}\;.
$$


text:
Q: Index of unmatched string in a list of character vectors I have a list of character vectors and I want to use grep command to find locations of what is not matched. See example below:
x.lst <- list()
x.lst[[1]] <- c("she", "said", "hello")
x.lst[[2]] <- c("hello")
x.lst[[3]] <- c("whats", "up")

I want a function to return index of unmatched pattern in each vector. In my example, return index of everything except "hello".  If I use following :
lapply(x.lst, function(x) x[-grep("hello",x)])

I get:
[[1]]
[1] "she"  "said"

[[2]]
character(0)

[[3]]
character(0)

the desired output is:
[[1]]
[1] 1    2

[[2]]
[1] character(0)

[[3]]
[1] 1    2

Thanks for your help!

A: Use invert = TRUE to return the index of the elements which do not match.
lapply(x.lst, function(x) grep("hello",x, invert = TRUE))

#[[1]]
#[1] 1 2

#[[2]]
#integer(0)

#[[3]]
#[1] 1 2

A tidyverse alternative
library(tidyverse)
map(x.lst, ~ setdiff(seq_along(.), str_which(., "hello")))
#You can always do same as base here as well
#map(x.lst, ~ grep("hello",., invert = TRUE))

#[[1]]
#[1] 1 2

#[[2]]
#integer(0)

#[[3]]
#[1] 1 2

A: One option with Map from base R
unname(Map(grep, pattern = "hello", x.lst, invert = TRUE))

Or using tidyverse
library(tidyverse)
map(x.lst, ~ str_detect(.x, "hello") %>%
               `!` %>%
                which)
#[[1]]
#[1] 1 2

#[[2]]
#integer(0)

#[[3]]
#[1] 1 2


text:
Q: Trigger of button is not working in behind code on WPF There are 2 part for setting style of button.
The 1st is BackgroundProperty by Style.Setters. It's working well.
The 2nd is BackgroundProperty by Style.Triggers which is run by that Mouse is over a button. But, It's not working.
// the 1st BackgroundProperty by Style.Setters
Style style = new Style(typeof(Button));
style.Setters.Add(new Setter(Button.BackgroundProperty, imageSourceOn));

// the 2nd BackgroundPropert by Style.Triggers
Setter setter = new Setter();
setter.Property = Button.BackgroundProperty;
setter.Value = imageSourceOff;
Trigger trigger = new Trigger();
trigger.Property = IsMouseOverProperty;
trigger.Value = true;
trigger.Setters.Add(setter);
style.Triggers.Add(trigger);

Button button = new Button();
button.Margin = new Thickness(0, 5, 80, 5);
button.BorderThickness = new Thickness(0);
button.Name = name;
button.Click += handler;
button.VerticalContentAlignment = VerticalAlignment.Bottom;

// setting Style
button.Style = style;
return button;

A: Thanks Ed Plunkett.
I added ControlTemplate to override the control's background brush property.
Style style = new Style(typeof(Button));
style.Setters.Add(new Setter(Button.BackgroundProperty, imageSourceOn));

This is the ControlTemplate part what I add:
ControlTemplate template = new ControlTemplate(typeof(Button));
FrameworkElementFactory elemFactory = new FrameworkElementFactory(typeof(Border));
elemFactory.Name = "Border";
elemFactory.SetValue(Border.BackgroundProperty, new TemplateBindingExtension(Button.BackgroundProperty));
template.VisualTree = elemFactory;
elemFactory.AppendChild(new FrameworkElementFactory(typeof(ContentPresenter)));

And, It is trigger part.
Setter setter = new Setter();
setter.Property = Button.BackgroundProperty;
setter.Value = imageSourceOff;
Trigger trigger = new Trigger();
trigger.Property = IsMouseOverProperty;
trigger.Value = true;
trigger.Setters.Add(setter);

Finally, I set my ControlTemplate.
template.Triggers.Add(trigger);
setter = new Setter();
setter.Property = Button.TemplateProperty;
setter.Value = template;
style.Setters.Add(setter);

It works well.


text:
Q: OSX - Tor Guard and Little Snitch I have a question regarding two applications/services that I'm currently looking at.
Tor Guard is a VPN service.
Little Snitch is an OSX firewall.
Little snitch provides a gui window that shows you where in the world your traffic is destined for. Quite fun to watch. However after installing Tor Guard and connecting to their service, I'm still seeing a significant amount of traffic heading overseas and not to where my VPN is connected to.
I know Little Snitch operates at the application layer, but i'm wondering if I'm leaking loads of traffic, or there's something I'm missing here? I'm hoping for the latter.
Is there a good way of testing a VPN against the traffic your computer is generating/receiving that it's being funneled through the VPN? Would wireshark be the tool? And if so, how might I got about configuring it?
Thanks for your time.

A: Your VPN service provides a tunneled, virtual link to your VPN provider. Traffic through that tunnel is NATed at the end and appears to the outside as originating from that end. It cannot normally be attributed to you, except by the VPN provider.
Little Snitch analyzes local traffic - there, the traffic is destined for the original location which is what you're seeing. The traffic is encapsulated for VPN and sent through the tunnel - you should also be seeing that. The latter is the only remote traffic an observer could see.
Basically, an outside, all-seeing observer sees you communicating with the tunnel end. He also sees the tunnel end (or some other, potentially even completely different address) communicating with the end destinations. However, seeing many inbound tunnels he cannot (easily) match the tunneled traffic to the end-destination traffic.
For you to see which traffic is observable from the outside, you should filter out (ignore) the VPN interface traffic.


text:
Q: jax-rs returned String I am programming a jax-rs webservice which I want to contact from a java-program. I defined a @POST method which receives a String-array as input and is supposed to return a boolean value.
But really, how can i access this return value in java? I've been searching the web for several hours now, everybody writes example methods which return Strings or something else, but nobody shows how to access the returned value from another java program.
Here is the code from the program that contacts the @POST method:
ObjectOutputStream oos = null;
        String[] login = {"XXXXXX","XXXXXXX"};
        try {
            login[1] = PasswordGenerator.hashPassword(login[1]);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        URL url = new URL("XXXXX/XXXXXXX/XXXXXX/users/login/1");
        try {
            // creates a HTTP connection
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setUseCaches(false);
            httpConn.setDoOutput(true);
            httpConn.setRequestMethod("POST");
            httpConn.setRequestProperty("Boolean", "application/xml");
            OutputStream outputStream = httpConn.getOutputStream();
            oos = new ObjectOutputStream(outputStream);
            outputStream.close();

            System.out.println();
            } finally {
            if (oos != null) {
                oos.close();
            }
        }
    }

What I want to know is: What happens after I closed my outputStream? I mean, i started the POST method, but it is supposed to return a boolean value. Where is this value? How can I access it???

A: JAX-RS 2.0 has a Client API that provides you with a fluent API to retrieve the content of the response:
Client client = ClientBuilder.newClient();
    Boolean result = client.target("http://localhost:8080/xxx/")
            .path("user/login/1")
            .request(MediaType.TEXT_PLAIN_TYPE)
            .post(Entity.entity(login, MediaType.APPLICATION_XML) , Boolean.class);

But unfortunately, you'll need a custom MessageBodyWriter to convert the String[] into an XML document. Maybe you should change your server-side method (and client) to manipulate a DTO - a POJO with 2 fields, username and password - and annotated with @XmlRootElement ?
something like that:
(client-side)
Credentials credentials = new
credentials.setUsername("foo");
credentials.setUsername("hashedPwd");
Client client = ClientBuilder.newClient();
Boolean result = client.target("http://xxxxx")
            .path("/user/login/1")
            .request(MediaType.TEXT_PLAIN_TYPE)
            .post(Entity.entity(credentials, MediaType.APPLICATION_XML) , Boolean.class);
    System.out.println("Result: " + result);

(server-side)
@Path("/login/{id}")
@POST
public Boolean test(@PathParam("id") String login, Credentials credentials) {
...
}


text:
Q: Download the image from the urlencoded or base64encoded string My application sends urlencoded or base64encoded string via http get request, the string contain image data, that most be download from the php file, but i dont know how php would download image from my string that is either  urlencoded or base64encoded, please help me out guys... im lost

A: Serve image to a user
// we assume $imageData is PNG
$image = urldecode($imageData);
// or
$image = base64_decode($imageData);

// in case of force download change Content-Type: image/png to
// application/octet-stream and Content-Disposition: inline to attachment
header('Content-type: image/png');
header('Content-Disposition: inline; filename=' . md5($image) . '.png');
header('Content-Length: ' . strlen($image));

echo $image;
exit;

The problem si to detect correct Content-Type if you don't know it. But browsers should be able to autodetect it on its own.
Some notes about caching
PHP implicitly sends headers which prevents browser caching of retrieved data. I suggest you to set these headers manually (Cache-Control, Expires, Pragma). To work properly, every single image must be served by an unique URL. Also try to avoid of starting sessions. On heavily accessed website with public access you can easily flood webserver with redundant session files.
Save image to a file
$image = urlencode($imageData);
// or
$image = base64_decode($imageData);

if (!file_put_contents('abs/path/to/save/file.png', $image)) {
    throw new Exception('Image could not be saved');
}


text:
Q: Wordpress Add dropdown in custom post type add/edit post in admin I am new with wordpress.
i have created three "custom post" type like

*

*Two Wheeler

*Three Wheeler

*Four Wheeeler

I have used the following code to create custom post type in admin.
function create_post_type_two_wheeler()
{
    register_taxonomy_for_object_type('category', 'TwoWheeler'); // Register Taxonomies for Category
    register_taxonomy_for_object_type('post_tag', 'TwoWheeler');
    register_post_type('client', // Register Custom Post Type
        array(
            'labels' => array(
                'name' => __('TwoWheeler', 'vehicles'), // Rename these to suit
                'singular_name' => __('TwoWheeler', 'vehicles'),
                'add_new' => __('Add New', 'vehicles'),
                'add_new_item' => __('Add New TwoWheeler', 'vehicles'),
                'edit' => __('Edit', 'vehicles'),
                'edit_item' => __('Edit TwoWheeler', 'vehicles'),
                'new_item' => __('New TwoWheeler', 'vehicles'),
                'view' => __('View TwoWheeler', 'vehicles'),
                'view_item' => __('View TwoWheeler', 'vehicles'),
                'search_items' => __('Search TwoWheeler', 'vehicles'),
                'not_found' => __('No TwoWheeler found', 'vehicles'),
                'not_found_in_trash' => __('No TwoWheeler found in Trash', 'vehicles')
            ),
            'public' => true,
            'hierarchical' => true, // Allows your posts to behave like Hierarchy Pages
            'has_archive' => true,
            'supports' => array(
                'title',
                'editor',
                'excerpt',
                'thumbnail'
            ), // Go to Dashboard Custom HTML5 Blank post for supports
            'can_export' => true, // Allows export in Tools > Export
            'taxonomies' => array(
                'post_tag',
                'category'
            ) // Add Category and Post Tags support
        ));

}

add_action('init', 'create_post_type_two_wheeler');

Now i want to display Dropdown in admin Add/Edit post of "Two wheeler" custom post type.so user can select that option for that particular post and save that option in database.
Any google link that will help me to do this ??
i Need a way to start work on this.

A: I'm not sure that I fully understand the question, but if you want to add metabox for your custom post types, then you could look at this script:
WPAlchemy MetaBox


text:
Q: My app background won't fill the screen How do I make the background image fill the screen? I have tried several different suggestions and nothing seems to work.

Below is the code for my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.andrewvanpeter.upandaway.MainActivity">

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/background_flat_720x1280" />

</android.support.constraint.ConstraintLayout>

A: First solution :
You can put the layout_width and the layout_height of your ImageView to match_parent :
<ImageView
        android:id="@+id/imageView2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:srcCompat="@drawable/background_flat_720x1280" />

Second solution :
You can set the background directly in the ConstraintLayout (and don't forget to delete the ImageView) :
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background_flat_720x1280"
    tools:context="com.andrewvanpeter.upandaway.MainActivity">

A: You can also to set the scaletype of imageview to fitXY like this :
<ImageView
    android:id="@+id/imageView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="fitXY"
    app:srcCompat="@drawable/background_flat_720x1280" />


text:
Q: FadeIn//FadeOut some quotes I'm trying to get my quotes in this fiddle to have a fade in/out effect when the plus button is clicked. I've read up on it and looked at similar projects but can't figure it out.
I tried adding this (get ready to laugh at my attempt) but it of course broke the damn thing:
$("#random-quote").click(function() {
    $("#main-quote").fadeOut(300);
    $("#main-quote").fadeIn(300);
    }
};

Any help would be greatly appreciated, thanks!

A: If you'd like the text to fade out before changing, you can use the fadeout function which looks like this:
FadeOut
$("#main-quote").fadeOut(300, function() {});

You can wrap your $('#main-quote').text(); changes in this, and then call fadeIn(); at the end:
jQuery
$("#main-quote").fadeOut(300, function() {
  $('#main-quote').text(selectedQuote.quote);
  var selectedBG = selectedQuote.background;
  var selectedMovie = selectedQuote.movie;
  console.log(selectedBG);
  console.log(selectedMovie);
  $("body").css("background-image", "url('" + selectedBG + "')");

  $('#main-quote').text(selectedQuote.quote);
  var selectedMovie = selectedQuote.movie;
  console.log(selectedMovie);
  $("#what-movie").html(selectedMovie);
  $("#main-quote").fadeIn(300);
});

Also, for this to work, you need to remove your $('#random-quote').click(getQuote); line, which was making the background change twice because you're calling the same click function twice.
JSFiddle

A: Set css transition for background-image at body; also removed $('#random-quote').click(getQuote);
  transition: background-image 200ms ease-in-out;

javascript
function getQuote() {
    var randomIndex = Math.floor(Math.random() * quotes.length);
    var selectedQuote = quotes[randomIndex];
    // `.fadeOut` here
    $('#main-quote').fadeOut(200).text(selectedQuote.quote);
    var selectedBG = selectedQuote.background;
    console.log(selectedBG);
    $("body").css("background-image", "url('" + selectedBG + "')");
    // `.fadeIn` here
    $('#main-quote').text(selectedQuote.quote).fadeIn(200);
    var selectedMovie = selectedQuote.movie;
    console.log(selectedMovie);
    $("#what-movie").html(selectedMovie);
}

jsfiddle https://jsfiddle.net/hanyb9da/36/

A: Try fadeOut the entire box and after that run the function to change the text:
$('#main-box').fadeOut(800,function(){
    $("body").css("background-image", "url('" + selectedBG + "')");
    $('#main-quote').text(selectedQuote.quote);
    $(this).fadeIn(500)
});

Also to make "smooth" the background change use transition:
body {
    transition:all .3s linear;
}

Updated Fiddle

Note: I've also removed the click bind to the function  getQuote()

A: You can do that with CSS3.

.btn {
  background: red;
  padding: 20px;
  color:white;
  border:none;
  outline:none;
  transition: opacity .3s;
}
.btn:active {
  opacity: 0;
 }
<button class="btn">RAND</button>


text:
Q: Event observer not working //App/Code/Local/Acme/Datecontrol/etc/config.xml:
<config>
    <modules>
        <Acme_Datecontrol>
            <version>0.1.0</version>
        </Acme_Datecontrol>
    </modules>
    <frontend>
        <routers>
            <datecontrol>
                <use>standard</use>
                <args>
                    <module>Acme_Datecontrol</module>
                    <frontName>datecontrol</frontName>
                </args>
            </datecontrol>
        </routers>
    </frontend>
    <global>
        <events>
            <controller_front_init_before>
                <observers>
                    <Acme_Datecontrol_Model_Observer>
                        <type>singleton</type>
                        <class>Acme_Datecontrol_Model_Observer</class>
                        <method>checkDate</method>
                    </Acme_Datecontrol_Model_Observer>
                </observers>
            </controller_front_init_before>
        </events>
    </global>
</config>

And the observer,
//App/Code/Local/Acme/Datecontrol/Model/Observer.php:
class Acme_Datecontrol_Model_Observer {

    public function checkDate($observer) {
        Mage::log('Frontend Page loaded', null, 'FirstObserver.log');
    }
}

A: <config>
    <modules>
        <Acme_Datecontrol>
            <version>0.1.0</version>
        </Acme_Datecontrol>
    </modules>
    <global>
        <models>
            <datecontrol>
                <class>Acme_Datecontrol_Model</class>
            </datecontrol>
        </models>
    </global>
    <frontend>
        <routers>
            <datecontrol>
                <use>standard</use>
                <args>
                    <module>Acme_Datecontrol</module>
                    <frontName>datecontrol</frontName>
                </args>
            </datecontrol>
        </routers>
        <events>
            <controller_front_init_before> //does not allow type singleton, try using 'controller_action_predispatch' instead
                <observers>
                    <datecontrol_checkdate> //not important
                        <type>model</type>
                        <class>datecontrol/observer</class>
                        <method>checkDate</method>
                    </datecontrol_checkdate>
                </observers>
            </controller_front_init_before>
        </events>
    </frontend>
</config>

A: config.xml
<config>
    <modules>
        <Acme_Datecontrol>
            <version>0.1.0</version>
        </Acme_Datecontrol>
    </modules>
    <global>
        <models>
            <acme_datecontrol>
                <class>Acme_Datecontrol_Model</class>
            </acme_datecontrol>
        </models>
    </global>
    <frontend>
        <routers>
            <datecontrol>
                <use>standard</use>
                <args>
                    <module>Acme_Datecontrol</module>
                    <frontName>datecontrol</frontName>
                </args>
            </datecontrol>
        </routers>
        <events>
            <controller_front_init_before> //Im not sure for this event
                <observers>
                    <Acme_Datecontrol_Model_Observer>
                        <class>acme_datecontrol/observer</class>
                        <method>checkDate</method>
                    </Acme_Datecontrol_Model_Observer>
                </observers>
            </controller_front_init_before>
        </events>
    </frontend>
</config>

A: On a 1.6.2 version, I had the same problem and I managed to make it work using the events in the global node, instead of frontend :
<config>
    <modules>
        <Acme_Datecontrol>
            <version>0.1.0</version>
        </Acme_Datecontrol>
    </modules>
    <global>
        <models>
            <datecontrol>
                <class>Acme_Datecontrol_Model</class>
            </datecontrol>
        </models>
        <events>
            <controller_front_init_before>
                <observers>
                    <datecontrol_checkdate>
                        <type>model</type>
                        <class>datecontrol/observer</class>
                        <method>checkDate</method>
                    </datecontrol_checkdate>
                </observers>
            </controller_front_init_before>
        </events>
    </global>
    <frontend>
        <routers>
            <datecontrol>
                <use>standard</use>
                <args>
                    <module>Acme_Datecontrol</module>
                    <frontName>datecontrol</frontName>
                </args>
            </datecontrol>
        </routers>
    </frontend>
</config>


text:
Q: Get datatype of column in datatable I am trying to get dataType of datatable, code is
 for (int j = 0; j < dt.Columns.Count; j++)
 {
       columntypes[j] = dt.Columns[j].GetType().Name;//dt.Rows[0][j].GetType().Name;
 }

checked dt.Rows[0][j].GetType().Name;  works fine.But In case of empty datatable it throws a error,So i tried with dt.Columns[j].GetType().Name; but it doesnt give proper solution

A: You can try like this:
if(dt!=null && dt.Rows.Count > 0)
{
    for (int j = 0; j < dt.Columns.Count; j++)
     {
           columntypes[j] = dt.Columns[j].DataType.Name.ToString();
     }
}

ie, you need to use the DataType property

A: The DataTable.Columns property is a DataColumnCollection, which can be indexed by column name to get a DataColumn, which has a DataType property.
or You may do :
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SET FMTONLY ON; select column from table; SET FMTONLY OFF";
SqlDataReader reader = cmd.ExecuteReader();
SqlDbType type = (SqlDbType)(int)reader.GetSchemaTable().Rows[0] ["ProviderType"];

A: You can use like this also:
 int j=0;
 foreach (DataColumn dc in DT.Columns)
    {
       columntypes[j++] = dc.DataType.Name.ToString();
    }


text:
Q: Install psycopg2 to a target directory on Linux I'm trying to install psycopg2 using pip's target switch:
In an empty directory on a new AWS EC2 instance, the following happens:
[ec2-user@ip-172-25-10-192 ~]$ pip install -t psycopg2 .
You are using pip version 6.1.1, however version 7.1.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
Processing /home/ec2-user
No files/directories in /tmp/pip-3SPtE_-build/pip-egg-info (from PKG-INFO)

Even if I upgrade pip, I get a similar error:
[ec2-user@ip-172-25-10-192 ~]$ /usr/local/bin/pip install -t psycopg2 .
Processing /home/ec2-user
No files/directories in /tmp/pip-DHJzs3-build/pip-egg-info (from PKG-INFO)

EDIT:
For reference, here is my Dockerfile:
FROM centos:6

RUN yum -y update; yum clean all
RUN yum -y install gcc; yum clean all
RUN yum -y install epel-release; yum clean all
RUN yum -y install python python-pip python-devel; yum clean all
RUN yum -y install postgresql-devel; yum clean all
RUN yum -y install zip; yum clean all

RUN pip install psycopg2 -t deploy/
RUN rm -f deploy.zip; zip -r deploy.zip deploy/*


text:
Q: least upper bound lubAB=lubA*lubB (Revised) I just finished proving lub(A+B)=lubA+lubB and was wondering what the proof was for lubAB=lubAlubB this? How could I show this? Where A and B are positive and AB= {ab | a in A and b in B|
My previous question here

A: $\operatorname{lub}(A)\operatorname{lub}(B)\geq\operatorname{lub}(AB)$:
Suppose not for the sake of contradiction. Then, since $\operatorname{lub}(A)\operatorname{lub}(B)<\operatorname{lub}(AB)$, there is some $q\in AB$ such that $q>\operatorname{lub}(A)\operatorname{lub}(B)$. Now, for any $q\in AB$, there is some $a\in A$, $b\in B$ such that $ab=q$. But, since $\operatorname{lub}(A)\geq a$, $\operatorname{lub}(B)\geq b$, $\operatorname{lub}(A)\operatorname{lub}(B)\geq ab=q$, a contradiction.
$\operatorname{lub}(A)\operatorname{lub}(B)\leq\operatorname{lub}(AB)$:
Suppose not for the sake of contradiction. Then, there exists some $a\in A$, $b\in B$ such that $ab>\operatorname{lub}(AB)$. But, $ab\in AB$, so this is a contradiction.


text:
Q: consecuencias de stopPropagation Tengo una web, maquetada mayormente con Bootstrap y ciertas PCs no tan potentes (veasé un Core 2 Duo con 4gb de RAM) como ejemplo, mi web experimenta cierta "latencia" al clickear en elementos de formulario cómo inputs, buttons, selects y las animaciones css de estos se hacen como en cámara lenta.
Hace nada descubrí por accidente que algo como esto:
$("div").on("click", "input, select, button", function(e){
    e.stopPropagation();
});

Hacia maravillas con la experiencia de estos equipos en la página, haciendo estas acciones y sus animaciones muchisimo más fluidas (como debería ser).
La pregunta en cuestion entonces es, como yo solo he usado
e.stopPropagation();

para hacer que los clicks de algunos elementos no se ejecuten más de una vez en el pasado, realmente no tengo idea por que esto ocurre y a salvo de algunos elementos que no funcionan con normalidad y tendré que ajustar, con ése código la web se vuelve mucho más amena para los PCs menos potentes.
Esto puede traer algún problema que no estoy viendo?

A:

e.stopPropagation() es utilizado para detener la propagación de un
  evento, con el objetivo de que no se realice otra ejecución.

Mira el siguiente ejemplo.

function showContent(e) {
  alert('hola soy ' + this.id)
  //e.stopPropagation()
}

var divs = document.querySelectorAll('div')
divs.forEach(function (element) {
  element.addEventListener('click', showContent)
})
* { margin: 0; padding: 0; }

div {
  margin: auto;
  padding: 2em;
  position: relative;
  text-align: center;
  max-width: 260px;
}

div::before {
  position: absolute;
  top: 10px;
}

#uno { background: red; }
#dos { background: lightgreen; }
#tres { background: skyblue; }

#uno::before { content: "1"; }
#dos::before { content: "2"; }
#tres::before { content: "3"; }

Cuando das clic al elemento con el número tres verás que el evento clic se propaga hacia los elementos padres, esto es considerado como bubbling.
¿Qué tal si descomentas la linea de código donde utilizo stopPropagation?
Verás que la propagación del evento se detiene.
Te recomiendo leer sobre Bubbling y Capturing
Espero haberte ayudado!


text:
Q: How can we reduce the unnecessary loading of objects? In hibernate as well as simple ORM strategy,i am normally loading all the values for the objects.Is there any way to avoid this.
Due to this my app running slowly..

A: There are several ways to achieve this:

*

*Enable caching. While the SQL won't change, Hibernate will compare the results from the database and reuse existing objects. This doesn't give an enormous boost but it's simple to implement and maintain.

*Create a second mapping (same tables, different object) to load just a subset of the values.

*Move the rarely used data into a second table.

*Load your objects with a custom native SQL query. Here, you must make sure that you know how much has been loaded and how to "fill the gaps".

A: The Hibernate reference document has a chapter on Improving Performance. You could look at your fetching strategies or whether using caching would improve performance.
To be more specific you would need to provide more details on your application and how the objects loaded via ORM are used.

A: In yoru entities mapping use FetchType.LAZY.
i.e.:
@Entity
public class MyEntity {

private List<MyAnotherEntity> values;

@ManyToOne(fetch = FetchType.LAZY)
public List<MyAnotherEntity> getValues() {
 return values;
}

}

then, when you select entity with criteria you need set fetch mode if you need your collection to be mapped into object.
Criteria c = createCreteria(entityManager, MyEntity.class);
c.setFetchMode("values", FetchMode.JOIN);


text:
Q: Heroku Dep Issue: SSH, PubKey Failure (Errno::EISDIR) I'm currently working through Hartl's tutorial, struggling to deploy to heroku. Running OSX 10.8.1.
Experienced ssh issues and read thru three-dozen questions here, but can't figure it out.
I've added two additional ssh id's but it gives me the following error for id's 2 and 3.
$ heroku login
Enter your Heroku credentials.
Email: email@gmail.com
Password (typing will be hidden):
Found the following SSH public keys:
1) github_rsa.pub
2) id_dsa.pub
3) id_rsa.pub

Which would you like to use with your Heroku account? 3
Uploading SSH public key /Users/admin/.ssh/id_rsa.pub... failed
 !    Heroku client internal error.
 !    Search for help at: https://help.heroku.com
 !    Or report a bug at: https://github.com/heroku/heroku/issues/new

    Error:       Is a directory - /Users/admin/.ssh/id_rsa.pub (Errno::EISDIR)
    Backtrace:

  /Users/admin/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/heroku-2.32.4/lib/heroku/auth.rb:290:in `read'
  /Users/admin/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/heroku-2.32.4/lib/heroku/auth.rb:290:in `block in associate_key'
  /Users/admin/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/heroku-2.32.4/lib/heroku/helpers.rb:236:in `action'
  /Users/admin/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/heroku-2.32.4/lib/heroku/auth.rb:288:in `associate_key'
  /Users/admin/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/heroku-2.32.4/lib/heroku/auth.rb:269:in `associate_or_generate_ssh_key'
  /Users/admin/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/heroku-2.32.4/lib/heroku/auth.rb:239:in `check_for_associated_ssh_key'
  /Users/admin/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/heroku-2.32.4/lib/heroku/auth.rb:233:in `ask_for_and_save_credentials'
  /Users/admin/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/heroku-2.32.4/lib/heroku/auth.rb:84:in `get_credentials'
  /Users/admin/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/heroku-2.32.4/lib/heroku/auth.rb:41:in `login'
  /Users/admin/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/heroku-2.32.4/lib/heroku/command/auth.rb:31:in `login'
  /Users/admin/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/heroku-2.32.4/lib/heroku/command.rb:206:in `run'
  /Users/admin/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/heroku-2.32.4/lib/heroku/cli.rb:28:in `start'
  /Users/admin/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/heroku-2.32.4/bin/heroku:16:in `<top (required)>'
  /Users/admin/.rbenv/versions/1.9.3-p194/bin/heroku:23:in `load'
  /Users/admin/.rbenv/versions/1.9.3-p194/bin/heroku:23:in `<main>'

    Command:     heroku login
    Version:     heroku-toolbelt/2.32.4 (x86_64-darwin12.1.0) ruby/1.9.3 autoupdate

When I do get the id to load/authorize, I attempt to git push heroku master yet I'm met with:
Permission denied (publickey).
fatal: The remote end hung up unexpectedly

Could the issue perhaps be that I need to replace #1 with #3 (delete all but the #3 id?)
Would love your help!

A: Try regenerating your public key again. But before that, try heroku keys:add again. Otherwise, ssh-keygen -t rsa then heroku keys:add.
But do note that if you change your keys, the the rest of the applications which you have tied your previous keys too will have to be changes also.


text:
Q: Adding two paths to d3 I would appreciate any help on this! I am currently attempting to add two paths from two different csv files to code adapted from this Focus+Context via Brushing d3 visualization: http://bl.ocks.org/mbostock/1667367
<!DOCTYPE html>
<meta charset="utf-8">
<style>

svg {
  font: 10px sans-serif;
}

.area {
  fill: none;
stroke: #000;
  clip-path: url(#clip);
}

.area_ {
  fill: none;
stroke: #a0f2;
  clip-path: url(#clip);
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.brush .extent {
  stroke: #fff;
  fill-opacity: .125;
  shape-rendering: crispEdges;
}

.brush_ .extent {
  stroke: #fff;
  fill-opacity: .125;
  shape-rendering: crispEdges;
}

</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>

var margin = {top: 10, right: 10, bottom: 100, left: 40},
    margin2 = {top: 430, right: 10, bottom: 20, left: 40},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom,
    height2 = 500 - margin2.top - margin2.bottom;

var parseDate = d3.time.format("%b %Y").parse;

var x = d3.time.scale().range([0, width]),
    x2 = d3.time.scale().range([0, width]),
    y = d3.scale.linear().range([height, 0]),
    y2 = d3.scale.linear().range([height2, 0]),
x_ = d3.time.scale().range([0, width]),
    x2_ = d3.time.scale().range([0, width]),
    y_ = d3.scale.linear().range([height, 0]),
    y2_ = d3.scale.linear().range([height2, 0]);

var xAxis = d3.svg.axis().scale(x).orient("bottom"),
    xAxis2 = d3.svg.axis().scale(x2).orient("bottom"),
xAxis2_ = d3.svg.axis().scale(x2_).orient("bottom"),
 xAxis_ = d3.svg.axis().scale(x_).orient("bottom"),
    yAxis = d3.svg.axis().scale(y).orient("left"),
yAxis_ = d3.svg.axis().scale(y_).orient("left");

var brush = d3.svg.brush()
    .x(x2)
    .on("brush", brushed);

var brush_ = d3.svg.brush()
    .x(x2_)
    .on("brush", brushed);

var area = d3.svg.area()
    .interpolate("monotone")
    .x(function(d) { return x(d.date); })
    .y0(height)
    .y1(function(d) { return y(d.price); });

var area_ = d3.svg.area()
    .interpolate("monotone")
    .x(function(d) { return x_(d.date); })
    .y0(height)
    .y1(function(d) { return y_(d.price); });

var area2 = d3.svg.area()
    .interpolate("monotone")
    .x(function(d) { return x2(d.date); })
    .y0(height2)
    .y1(function(d) { return y2(d.price); });

var area2_ = d3.svg.area()
    .interpolate("monotone")
    .x(function(d) { return x2_(d.date); })
    .y0(height2)
    .y1(function(d) { return y2_(d.price); });

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom);

svg.append("defs").append("clipPath")
    .attr("id", "clip")
  .append("rect")
    .attr("width", width)
    .attr("height", height);

var focus = svg.append("g")
    .attr("class", "focus")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var context = svg.append("g")
    .attr("class", "context")
    .attr("transform", "translate(" + margin2.left + "," + margin2.top + ")");

d3.csv("sp500.csv", type, function(error, data) {
  x.domain(d3.extent(data.map(function(d) { return d.date; })));
  y.domain([0, d3.max(data.map(function(d) { return d.price; }))]);
  x2.domain(x.domain());
  y2.domain(y.domain());

  focus.append("path")
      .datum(data)
      .attr("class", "area")
      .attr("d", area);

  focus.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

  focus.append("g")
      .attr("class", "y axis")
      .call(yAxis);

  context.append("path")
      .datum(data)
      .attr("class", "area")
      .attr("d", area2);

  context.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height2 + ")")
      .call(xAxis2);

  context.append("g")
      .attr("class", "x brush")
      .call(brush)
    .selectAll("rect")
      .attr("y", -6)
      .attr("height", height2 + 7);
});

d3.csv("academia_score.csv", type, function(error, data) {
  x_.domain(d3.extent(data.map(function(d) { return d.date; })));
  y_.domain([0, d3.max(data.map(function(d) { return d.price; }))]);
  x2_.domain(x_.domain());
  y2_.domain(y_.domain());

  focus.append("path")
      .datum(data)
      .attr("class", "area")
      .attr("d", area_);

  context.append("path")
      .datum(data)
      .attr("class", "area")
      .attr("d", area2_);

  context.append("g")
      .attr("class", "x brush")
      .call(brush)
    .selectAll("rect")
      .attr("y", -6)
      .attr("height", height2 + 7);
});
function brushed() {
  x.domain(brush.empty() ? x2.domain() : brush.extent());
focus.select(".area").attr("d", area);
  focus.select(".area_").attr("d", area_);
  focus.select(".x.axis").call(xAxis);
}

function type(d) {
  d.date = parseDate(d.date);
  d.price = +d.price;
  return d;
}

</script>

However, the brush zoom is not working on my second path. The output can be viewed on this page: http://researchiq.net/comp.html Why isn't the zoom working on the second path??? Thanks!

A: Because d3.select() only selects a single element, not multiple, so focus.select(".area") is incorrect. Switch it to focus.selectAll(".area") and, assuming everything else was done properly, you'll be good to go.


text:
Q: How many threads does a .NET web application natively use? This has been bugging me for a while.  Assuming that I am not using any explicit form of task parallelism (e.g. Paralell.ForEach), how many threads are natively used when I deploy a web application to a Windows Server?
In other words, if the web server has an eight-core processor, does the application only use one of those cores if I am not explicitly telling it to use more?
I'll bet I have missed something simple here, so flame on--but I still want to know the answer.  Thanks.

A: First, you have to consider that a web server is, by its nature, a multi-threaded system because it has to be able to respond to multiple requests at the same time (there are ways to do this in a single threaded environment, but it's not very efficient, and IIS does not support it).  If two users access the site at the same time, two separate threads are servicing each request in most cases.
Once you get into scalability issues, and async support, then a thread can actually service multiple requests (or rather, a request can be put on a queue and the IIS worker threads can be reused to process other requests).
So you are looking at this from the aspect of a single user.  And that single user will likely run only a single thread of activity during that web request (ignoring async, io completion ports, etc..).  i.e. you can think of a single web request as being equal to a single thread in the general sense (but there are so many things that can spin off other threads, that this isn't something that you can really count on).
When you use something like Parallel.ForEach it's so that your single users request can now execute things in multiple threads to improve efficiency.
An IIS web site has a worker process associated with it.  That worker process can be configured and tuned to control how many threads it uses.  But just remember, that your web site is running under the control of IIS, not as it's own application.

A: The topic of threads can get really confusing as you move along .NET versions.
But to over-simplify, it depends on your processModel configuration for ASP.NET. (machine.config) autoConfig=true/false etc.
at a bare minimum, in .NET 4.0, the min/max WorkerThreads and min/max IOCompletionThreads determine the amount of threads in play.
e.g. If the minWorkerThreads = 1 (default value), then the total minThreads = 1 * no:of cores..
same with maxWorkerThreads.
Based on the load, the worker process can ramp up the threads needed to service the requests, using an undisclosed algorith.. minWorkerThreads to maxWorkerThreads. (of course based on availability of ThreadPool threads etc.)


text:
Q: How to disable imageSmoothingEnabled for geoImageLayer? Considering the code below (which uses openlayers and Viglino's ol-ext), how do I disable imageSmoothingEnabled for the geoImageLayer? I am trying to achieve the same thing as in this question, but for the geoImageLayer, which is part of Viglino's ol-ext.
var map = new ol.Map({
  target: 'map',
  view: new ol.View({
    zoom: 18,
    center: ol.proj.fromLonLat([4.8728,52.3316])
  }),
  layers: [new ol.layer.Tile({
    source: new ol.source.OSM()
  })]
})

var geoImageLayer = new ol.layer.Image({
  name: "Georef",
  opacity: 0.5,
  source: new ol.source.GeoImage({
    url: 'image.jpg',
    imageCenter: ol.proj.fromLonLat([4.8728,52.3316]),
    projection: 'EPSG:3857',
    imageScale: [1, 1]
  })
})
map.addLayer(geoimg);

The internet says that this should work:
map.on('precompose', function(evt) {
  evt.context.imageSmoothingEnabled = false;
});

And it does work for the background OSM layer, but it does nothing for the geoImageLayer
I've also tried,
geoImageLayer.on('change', function(evt) {
  evt.target.values_.source.canvas_.canvas_.getContext('2d').imageSmoothingEnabled = false;
});

but it didn't do the trick. Probably because I'm modifying a copy of the actual layer, but I don't have any other ideas.
Here is a jsfiddle with the above code.


text:
Q: How to get to the ascii code of a character in a string MASM Assembly Say I have a string named abc initialized as "something". To get the first character of this string I would do abc[0] which would show 's'. Is there some notation that I could use to get the ascii code for 's' which is 73h? I'm using MASM.
I'm trying to subtract the ascii code from a character to form a different character. So if 's' is 115d, I want to subtract 4 so it's 111d so then it becomes the letter 'o'.

A: If you have the ASCII string "something" and you read the first byte from that string you'll get 115, which also equals 's', which also equals 73h. There's no conversion necessary because it's just a byte with some value. Whether you want to view that value as 115, 's' or 73h doesn't really become relevant until you want to print it.
.data
something db "something",0

.code
mov al,[something]    ; al = 115 / 73h / 's'
sub al,4              ; al = 111 / 6Fh / 'o'


text:
Q: How do I get DropDownList selected value from user in Asp.Net(selectedIndexChange) How do I go about getting the selected value from the DropDownList in asp.Net using selectedIndexChanged with an update Panel? I've tried but when I add the AutoPostBack to my DropDownList, it sends me to an error page saying it cannot find the resource.(doesn't even hit my "selected_IndexChanged") I have the hiddenField being assigned the selected value.
Here is my DropDownList:
<asp:ScriptManager ID="ScriptManager1" runat="server" />
    <asp:UpdatePanel runat="server" ID="UpdatePanel1">
        <ContentTemplate>
            <asp:DropDownList runat="server" ID="ddlCaseFilesNew" DataSourceID="dsCaseFiles"
                DataTextField="Display" DataValueField="FileID" OnPreRender="ddl_PreRender" Width="300px"
                AutoPostBack="true" OnSelectedIndexChanged="ddlCaseFilesNew_SelectedIndexChanged" Visible="False">
                <asp:ListItem>Item 1</asp:ListItem>
            </asp:DropDownList>
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="ddlCaseFilesNew" EventName="SelectedIndexChanged" />
        </Triggers>
    </asp:UpdatePanel>

When I click on a value inside the DropDownList it sends me to a "cannot find resource" page. I have no idea why. It doesn't even touch my "onSelectedIndexChanged"
  <script runat="server">
    protected void ddlCaseFilesNew_SelectedIndexChanged(object sender, EventArgs e)
    {
        hidNewCaseFile.Value = ddlCaseFilesNew.SelectedItem.Value;
    }
</script>

A: In your SelectedIndex function, use
string sValue = ((DropDownList)sender).SelectedValue;

Since it's in an update panel, you likely won't have access to it via the designer (this.DdlId).
Based on your comment in the OP, this is likely what you need:
protected void ddlCaseFilesNew_SelectedIndexChanged(object sender, EventArgs e)
{
    hidNewCaseFile.Value = ((DropDownList)sender).SelectedValue;
}

You also need to move your hidden field into the ContentTemplate.

A: Use:
protected void myDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
    var res = this.myDropDownList.SelectedValue;
}

Or:
protected void myDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
    var ddl = sender as DropDownList;
    var res = ddl.SelectedValue;
}

Edit 1
You need to understand that the partial page rendering occurs for all controls inside an UpdatePanel, in your case, you are trying to set the Value property of hidNewCaseFile control which does not appear to be inside the UpdatePanel therefore, its value will never get updated


text:
Q: Error when compiling in AoT using an object with integers as key I have an enum file which contains all my route paths in an object like this:
export const mortgageFormEnum = {
 routes: {
    start: 0,
    whatsUp: 1,
    refinance: 17,
    newAddress: 19,
    deposit: 2,
    addBorrower: 3,
    primaryIncome: 4,
    secondaryIncome: 5,
    properties: {
      0: { url: '', name: 'Start' },
      1: { url: 'whats-up', name: 'Whats Up' },
      2: { url: 'deposit', name: 'Deposit' },
      3: { url: 'add-borrower', name: 'Add Borrower' },
      4: { url: 'primary-income', name: 'Primary Income' },
      5: { url: 'secondary-income', name: 'Secondary Income' }
    }
  }
}

When I compile using AoT, I get this error:

Error during template compile of 'MortgageFormModule'   Name expected
  in 'mortgageFormRoutes'
      'mortgageFormRoutes' references 'mortgageFormEnum' at src\app\mortgage\mortgage-form.routes.ts(50,11)
        'mortgageFormEnum' contains the error at src\app\mortgage\shared\mortgage-form.enums.ts(27,7).

Basically the error points to the properties object and complains that I am using an integer as the key instead of a name.
Is this a bug? or how should I get around this? This enum file contains many other enums with the properties object (so I can map the values coming back from the server to its' title etc), while not applicable to my routes, is applicable to other objects so I can't delete it, in any case a javascript object can be defined using integers as keys so I have no idea why the compiler is complaining... :(

A: I submitted this to the angular-cli team and it appears to be a bug.
FYI:
https://github.com/angular/angular-cli/issues/9890


text:
Q: Sizing of vertical bar delimiters by kpfonts This is a follow-up question to Restriction of a function: the subscript seems too low.
Typesetting the following math formulas with kpfonts
\documentclass{article}
\usepackage{kpfonts-otf}
\begin{document}
$\left.g\right\vert, \left.g\right\Vert$
\end{document}

produces a vertical bar that does not go sufficiently low to cover the descender of g. By contrast, the double vertical bar goes low enough.

The single bar is a single character:
\TU/KpMath-Regular.otf(1)/m/n/10
\vbox(8.85+0.0)x3.09, shifted 1.925, direction TLT
.\hbox(7.13+1.72)x3.09, direction TLT
..\TU/KpMath-Regular.otf(1)/m/n/10 |

The double bar is a constructed from an extensible character:
\TU/KpMath-Regular.otf(1)/m/n/10
\vbox(12.0+0.0)x5.18, shifted 3.5, direction TLT
.\hbox(0.11+4.61)x5.18, direction TLT
..\TU/KpMath-Regular.otf(1)/m/n/10 
.\glue -1.57 plus 1.37001
.\hbox(7.13+1.72)x5.18, direction TLT
..\TU/KpMath-Regular.otf(1)/m/n/10 ‖

When typesetting the same with Computer Modern instead of kpfonts, both vertical bars behave the same (a single character in both cases):

\OML/cmm/m/it/10 g
\kern0.35878 (italic)
\hbox(7.5+2.5)x2.77779, direction TLT
.\OMS/cmsy/m/n/10 j

\OML/cmm/m/it/10 g
\kern0.35878 (italic)
\hbox(7.5+2.5)x5.00002, direction TLT
.\OMS/cmsy/m/n/10 k

Why does the single vertical bar in kpfonts not behave in the same way as the double vertical bar?
Additional remark after reading the answer
The answer says

\vert is not extended (this is a bug)

But the vertical bar after a taller formula
$$\left.g\over h\right\vert$$

is extended:
\hbox(11.48+6.96)x7.62999, direction TLT
.\hbox(0.0+0.0)x1.2, shifted -2.5, direction TLT
.\vbox(11.48+6.96)x5.23, direction TLT
..\hbox(4.64+2.59)x5.23, glue set 0.28fil, direction TLT
...\glue 0.0 plus 1.0fil minus 1.0fil
...\TU/KpMath-Regular.otf(1)/m/n/10
...\glue 0.0 plus 1.0fil minus 1.0fil
..\kern1.5 (font)
..\rule(0.5+0.0)x*
..\kern1.89 (font)
..\hbox(7.22+0.1)x5.23, direction TLT
...\TU/KpMath-Regular.otf(1)/m/n/10 ℎ
.\hbox(0.0+0.0)x1.2, shifted -2.5, direction TLT
\vbox(17.03398+0.0)x3.09, glue set 0.68758, shifted 6.017, direction TLT
.\hbox(0.11+4.61)x3.09, direction TLT
..\TU/KpMath-Regular.otf(1)/m/n/10 
.\glue -1.57 plus 1.37001
.\hbox(0.11+4.61)x3.09, direction TLT
..\TU/KpMath-Regular.otf(1)/m/n/10 
.\glue -1.57 plus 1.37001
.\hbox(7.13+1.72)x3.09, direction TLT
..\TU/KpMath-Regular.otf(1)/m/n/10 |

A: The \vert delimiter has wrong parameters in the GlyphCompositionVertical field (fontforge) which makes the extension fail on this case. The other two \Vert and \Vvert are fine.
To make it clear: in your picture the \right\vert is not extended, it is a raw \vert while the \right\Vert is composed of \Vert plus a vertical extension. As both are (automatically) centered on the math axis, the \right\Vert goes deeper down and higher up.
Thanks for pointing this out, it will be fixed in the next version of kpfonts-otf.
Follow up: should \vert be extended or not?
The decision is made by the TeX engine: the extension is triggered if and only if g descends lower than \vert (vertically centred on the maths axis); this explains the different results between newpxmath and kpfonts-otf
Here is what you get with newpxmath (the red line shows the maths axis):

And with the current (v.045) kpfonts-otf:

As mentioned above, \vert is not extended (this is a bug) but \Vert, which has the same height and depth as \vert, is extended as expected.
Note: the gap between the total heights of \vert and \Vert above is too large. I will add intermediate sizes for a smoother transition.
Here is the source of these tests:
\documentclass{article}
\usepackage{xcolor,iftex}
\iftutex
  \usepackage{kpfonts-otf}
\else
  \usepackage{newpxmath}
\fi
\newlength{\height}
\newlength{\depth}
\parindent=0pt
\begin{document}
{\tiny
 \settoheight{\height}{h}        ht(h)=\the\height ;
 \settoheight{\height}{$\vert$}  ht(vert)=\the\height

 \settodepth {\depth}{g}         dp(g)=\the\depth ;
 \settodepth {\depth}{$\vert$}   dp(vert)=\the\depth
}

\makebox[0pt]{\color{red}\rule[2.5pt]{\textwidth}{0.2pt}}%
$\left.h\right\vert$, $\left.g\right\vert$,
\iftutex$\left.g\right\Vert$\fi
\end{document}


text:
Q: How to read and plot arrays from pandas df fast I have following data frame in pandas that contains array reading it directly from a sqlite db using pd.read_sql():
      ArrayID  Value
 0        0      0
 1        0      1
 2        0      2
 3        0      3
 4        0      4
 5        0      5
 6        1      0
 7        1      1
 8        1      2
 9        1      3

I would like to know a fast way to get the arrays so I can plot it:
Array0 [0,1,2,3,4,5]

Array1 [0,1,2,3]

The only way I could think was (really slow when the table has 1000 arrays with arrays varying on length having maxixum length of 500):
import pandas as pd
import matplotlib.pyplot as plt

# loop on
for id in df.ArrayID:
    array = df.loc[df["ArrayID"]==id, "Value"].values()
    plt.plot(array)

plt.show()

Or is the matplotlib beeing the issue?

A: Use groupby to obtain the groups in one call, (instead of many calls to df.loc and df['ArrayID'] == id):
for aid, grp in df.groupby(['ArrayID']):
    plt.plot(grp['Value'].values)

Note also that plt.plot is not very fast. Calling it 1000 times may feel pretty slow. Moreover, a plot with 1000 lines may not look very comprehensible. You may need to rethink the quantity (perhaps through clustering or aggregation) that you wish to visualize.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

N, M = 500, 1000
data = np.row_stack([np.column_stack(np.broadcast_arrays(i,
    (np.random.random(np.random.randint(N))-0.5).cumsum())) for i in range(M)])
df = pd.DataFrame(data, columns=['ArrayID', 'Value'])
for aid, grp in df.groupby(['ArrayID']):
    plt.plot(grp['Value'].values)
plt.show()


text:
Q: mysql calling a function inside a stored procedure using phpmyadmin I have the following code that works:
BEGIN
  DECLARE done INT DEFAULT FALSE;
  DECLARE user_id int(11);
  DECLARE cur1 CURSOR FOR SELECT id FROM users;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

  # drop and re-create user_rank TABLE

  DROP TABLE IF EXISTS user_rank;

  CREATE TABLE `user_rank` (
    `id` int(11) UNSIGNED NOT NULL,
    `has_hobbies` int(3) DEFAULT 0,
    `passed_test` int(3) DEFAULT 0,
    `has_picture` int(3) DEFAULT 0,
    `won_a_job` int(3) DEFAULT 0,
    `is_prolancer` int(3) DEFAULT 0,
    `is_verified` int(3) DEFAULT 0,
    `has_portfolio` int(3) DEFAULT 0,
    `has_likes` int(3) DEFAULT 0,
    `has_disputes` int(3) DEFAULT 0,
    `has-earnings` int(3) DEFAULT 0,
    `has_feebacks` int(3) DEFAULT 0,
    `has_invitations` int(3) DEFAULT 0,
    `has_views` int(3) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `user_rank`
    ADD PRIMARY KEY (`id`);

ALTER TABLE `user_rank`
    MODIFY `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT;

OPEN cur1;

read_loop: LOOP
FETCH cur1 INTO user_id;
IF done THEN
  LEAVE read_loop;
END IF;
INSERT INTO user_rank (id) values (user_id);
END LOOP;

CLOSE cur1;
END

it loops inside the table users using a cursor and copy all the user ids into the table user_rank. I have a function called "hasUserPassedTest" defined in my database that given a user id return 10 or 0. I would like to call the function in the loop above and insert it int the user_rank table but the following code does not work:
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE user_id int(11);
DECLARE cur1 CURSOR FOR SELECT id FROM users;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

# drop and re-create user_rank TABLE

DROP TABLE IF EXISTS user_rank;

CREATE TABLE `user_rank` (
    `id` int(11) UNSIGNED NOT NULL,
    `has_hobbies` int(3) DEFAULT 0,
    `passed_test` int(3) DEFAULT 0,
    `has_picture` int(3) DEFAULT 0,
    `won_a_job` int(3) DEFAULT 0,
    `is_prolancer` int(3) DEFAULT 0,
    `is_verified` int(3) DEFAULT 0,
    `has_portfolio` int(3) DEFAULT 0,
    `has_likes` int(3) DEFAULT 0,
    `has_disputes` int(3) DEFAULT 0,
    `has-earnings` int(3) DEFAULT 0,
    `has_feebacks` int(3) DEFAULT 0,
    `has_invitations` int(3) DEFAULT 0,
    `has_views` int(3) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `user_rank`
    ADD PRIMARY KEY (`id`);

ALTER TABLE `user_rank`
    MODIFY `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT;

OPEN cur1;

read_loop: LOOP
    FETCH cur1 INTO user_id;
    IF done THEN
    LEAVE read_loop;
    END IF;
    INSERT INTO user_rank (id, has_hobbies) values (user_id, CALL
    hasUserPassedTest(user_id));
 END LOOP;

  CLOSE cur1;
END

I am using CALL to invoke my function inside the stored procedure but does not work. How do I call my function within a stored procedure?

A:
I am using CALL to invoke my function inside the stored procedure but does not work

CALL is not used to execute a function.
CALL Statement

The CALL statement invokes a stored procedure that was defined previously with CREATE PROCEDURE.

it loops inside the table users using a cursor and copy all the user ids into the table user_rank.

Why so complex? procedure, cursor, handler, loop... a simple query is enough:
INSERT INTO user_rank (id, has_hobbies)
SELECT user_id, hasUserPassedTest(user_id)
FROM users;

UPDATE
The insertion may be combined with the table creation:
CREATE TABLE `user_rank` (
    `id` int(11) UNSIGNED NOT NULL,
    `has_hobbies` int(3) DEFAULT 0,
    `passed_test` int(3) DEFAULT 0,
    `has_picture` int(3) DEFAULT 0,
    `won_a_job` int(3) DEFAULT 0,
    `is_prolancer` int(3) DEFAULT 0,
    `is_verified` int(3) DEFAULT 0,
    `has_portfolio` int(3) DEFAULT 0,
    `has_likes` int(3) DEFAULT 0,
    `has_disputes` int(3) DEFAULT 0,
    `has-earnings` int(3) DEFAULT 0,
    `has_feebacks` int(3) DEFAULT 0,
    `has_invitations` int(3) DEFAULT 0,
    `has_views` int(3) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8
SELECT user_id AS id, hasUserPassedTest(user_id) AS has_hobbies
FROM users;

One subtlety - the fields inserted will be the last in the table structure. If the fields order makes sense then all fields must be mentioned in selection part:
CREATE TABLE `user_rank` (
    `id` int(11) UNSIGNED NOT NULL,
    `has_hobbies` int(3) DEFAULT 0,
    `passed_test` int(3) DEFAULT 0,
    `has_picture` int(3) DEFAULT 0,
    `won_a_job` int(3) DEFAULT 0,
    `is_prolancer` int(3) DEFAULT 0,
    `is_verified` int(3) DEFAULT 0,
    `has_portfolio` int(3) DEFAULT 0,
    `has_likes` int(3) DEFAULT 0,
    `has_disputes` int(3) DEFAULT 0,
    `has-earnings` int(3) DEFAULT 0,
    `has_feebacks` int(3) DEFAULT 0,
    `has_invitations` int(3) DEFAULT 0,
    `has_views` int(3) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8
SELECT user_id AS id,
       hasUserPassedTest(user_id) AS has_hobbies
       0 AS `passed_test`,
       0 AS `has_picture`,
       0 AS `won_a_job`,
       0 AS `is_prolancer`,
       0 AS `is_verified`,
       0 AS `has_portfolio`,
       0 AS `has_likes`,
       0 AS `has_disputes`,
       0 AS `has-earnings`,
       0 AS `has_feebacks`,
       0 AS `has_invitations`,
       0 AS `has_views`
FROM users;

DROP TABLE stays a separate query :(


text:
Q: How to get width of absolute positioned element in Angular I'm trying to get the width off a component but it is 0. I've also tried putting the code in ngOnChanges().
constructor(private element: ElementRef) {
  this.htmlElement = this.element.nativeElement;
  let width = this.htmlElement.offsetWidth;
}

Element style:
display: block;
position: absolute;
left: 100;

I tried using clientWidth() but it is 0 too. How can I get the width of an element in angular 2?
Update:
I don't use position absolute and the width is correct, so I suppose the question is how do I get the width of an absolute positioned element?

A: Try to move your code to AfterViewInit lifecycle hook method and use @ViewChild() decorator instead of injecting element directly in constructor.
Try this code:
import {Component, ElementRef, ViewChild, HTMLElement, AfterViewInit} from '@angular/core'

@Component({
  selector: 'my-app',
  template: `

Hello!

  `,
})
export class App implements AfterViewInit {
  @ViewChild('child') element: any;
  htmlElement: HTMLElement;

  constructor() {}

  ngAfterViewInit() {
    this.htmlElement = this.element.nativeElement;
    let width = this.element.nativeElement.offsetWidth;
  }
}

Or see the working example here. Also check comments for explanations.

A: Try to use:
const rect = this.element.nativeElement.getBoundingClientRect();
const width = rect.width;

A: You should associate it to the element to the elementRef
@ViewChild('foo') foo: TemplateRef;

Hello {{name}}

    {{foo.clientWidth}}

LIVE DEMO