text:
Q: UITableView lags when scrolling I realize that there are several similar questions to this one, and I have indeed checked a lot of them. However, the ones I checked were either in the wrong language, or not what I was looking for, therefore I'm asking a new question. For reference, I'm using XCode 7.3.1 in Swift 2.
There is one feature of my new iOS app that will search the internet for data, and display the results by populating a UITableView. My problem is that it displays pictures in each cell, which makes the scrolling very annoying.
My ideal solution would be to have a default picture display, and while allowing the user to continue scrolling, it will download in the background. Then, once it has retrieved it, it will replace the default. I saw some previous answers on how to do this, but none have worked for me.
P.S. If you see another question that solves this problem WITH SWIFT, post the url and I'll delete this one.
Here is the code I'm using currently (with the lag):
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {  // Creates each cell, by parsing through the data received from the Employees array which we returned from the database
    if (Employees.count == 0)
    {
        let cell = self.ResultsTable.dequeueReusableCellWithIdentifier("NORESULT", forIndexPath: indexPath) as! TruckSearchNRTableViewCell

        return cell
    }

    else {
        let cell = self.ResultsTable.dequeueReusableCellWithIdentifier("RESULT", forIndexPath: indexPath) as! TruckSearchTableViewCell

            cell.companyLabel.text = Employees[indexPath.row]["CompanyName"] as? String
            cell.nameLabel.text = Employees[indexPath.row]["EmployeeName"] as? String
        if let mobile = Employees[indexPath.row]["PhoneNumber"] as? String {
            if (mobile == "")
            {
                cell.mobileLabel.hidden = true
                cell.mobileTitle.hidden = true
            } else {
                cell.mobileTitle.hidden = false
                cell.mobileLabel.hidden = false
            }
            let phonenumber = mobile.stringByReplacingOccurrencesOfString("[^0-9]", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range:nil);
            cell.phoneNumber.text = phonenumber
        }
            cell.titleLabel.text = Employees[indexPath.row]["JobTitle"] as? String
            cell.truckLabel.text = Employees[indexPath.row]["TruckNumber"] as? String
            cell.supervisorLabel.text = Employees[indexPath.row]["SupervisorName"] as? String
        if (Employees[indexPath.row]["Synced"] as? Int) == 0 {
            turnRed(cell)
        } else {
            turnBlack(cell)
        }
        if let ePhoto = Employees[indexPath.row]["PicLocation"] as? String {  // Save complete URL of picture location, and save it to the table

            let url = NSURL(string: "https://exampleurl.com/\(ePhoto)")!
            if let data = NSData(contentsOfURL: url){
                let myImage = UIImage(data: data)
                cell.employeePhoto.image = myImage
            }
            else
            {
                cell.employeePhoto.image = UIImage(named: "person-generic")
            }

        }

        return cell
    }
}

A: The problem is that you are retrieving the picture on the main thread, which is blocking it. All UI operations, including scrolling, are performed on the main thread so that is why it is choppy at the moment.
To solve this, instead of:
if let data = NSData(contentsOfURL: url){

    let myImage = UIImage(data: data)
    cell.employeePhoto.image = myImage

} else {

    cell.employeePhoto.image = UIImage(named: "person-generic")

}

Put the image request on a background thread and then set the image on the main thread again.
Eg
let qos = QOS_CLASS_USER_INITIATED

dispatch_async(dispatch_get_global_queue(qos,  0), {

   if let data = NSData(contentsOfURL: url){

       let myImage = UIImage(data: data)

       dispatch_async(dispatch_get_main_queue(), {
           cell.employeePhoto.image = myImage
       })

   } else {

       dispatch_async(dispatch_get_main_queue(), {
           cell.employeePhoto.image = UIImage(named: "person-generic")
       })

   }

})

alternatively you can use an asynchronous url session to get the data like so:
let request: NSURLRequest = NSURLRequest(URL: url)
let mainQueue = NSOperationQueue.mainQueue()

NSURLConnection.sendAsynchronousRequest(request, queue: mainQueue, completionHandler: { (response, data, error) -> Void in

    if error == nil {

        let myImage = UIImage(data: data)

        dispatch_async(dispatch_get_main_queue(), {
            cell.employeePhoto.image = myImage
        })

    } else {

       dispatch_async(dispatch_get_main_queue(), {
           cell.employeePhoto.image = UIImage(named: "person-generic")
       })

    }

})


text:
Q: awk solution for pattern matching and allowing one ambiguity/mismatch I would like to count the number of strings in a document.
If input is:
GGTGGTGGTAT
GGTAGTGGTAT
GGTGGTGGTAT
GGTAATGGTAT

And I search for GGTGGTGGT I would like to find 3 matches.  Allowing for one ambiguity.
Using egrep it would look something like this and have an output of 3.
 egrep -c "GGTGGTGGT|.GTGGTGGT|G.TGGTGGT|GG.GGTGGT|GGT.GTGGT|GGTG.TGGT|GGTGG.GGT|GGTGGT.GT|GGTGGTG.T|GGTGGTGG." input

A: Here's a way to generate that regex with bash:
$ patt=(GGTGGTGGT)
$ for ((i=0; i<${#patt[0]}; i++)); do
    patt+=( "${patt[0]:0:i}.${patt[0]:i+1}" )
  done
$ regex=$(IFS='|'; echo "${patt[*]}")
$ echo "$regex"
GGTGGTGGT|.GTGGTGGT|G.TGGTGGT|GG.GGTGGT|GGT.GTGGT|GGTG.TGGT|GGTGG.GGT|GGTGGT.GT|GGTGGTG.T|GGTGGTGG.

and then:
awk -v regex="$regex" '$0 ~ regex' file

Or with awk only:
awk -v srch=GGTGGTGGT '
    BEGIN {
        regex = srch
        for (i=1; i<=length(srch); i++)
            regex = regex "|" substr(srch,1,i-1) "." substr(srch, i+1)
    }
    $0 ~ regex
' << END
GGTGGTGGTAT
GGTAGTGGTAT
GGTGGTGGTAT
GGTAATGGTAT
END

GGTGGTGGTAT
GGTAGTGGTAT
GGTGGTGGTAT

A: This awk executable script will create the patterns to match on, then test each line to count matches:
#!/usr/bin/awk -f

BEGIN { createPatternArray( pattern, a ) }

{
    for( k in a ) { if( $0 ~ k ) { total++; break } }
}

END { print total }

function createPatternArray( pattern, a,       pLen, i ) {
    a[pattern]
    pLen = length( pattern )
    for(i=1; i<=pLen; i++) {
        a[substr(pattern,1,i-1) "." substr(pattern,i+1)]
    }
    # for( k in a ) { print k }
}

If it was placed in a file like awko (and made executable), then running it on the data is like:
awko -v pattern=GGTGGTGGT data
3

The createPatternArray function makes entries in the array like:
.GTGGTGGT
G.TGGTGGT
GG.GGTGGT
GGT.GTGGT
GGTG.TGGT
GGTGG.GGT
GGTGGT.GT
GGTGGTG.T
GGTGGTGG.
GGTGGTGGT

For each line, the prefix of the line is tested against the entries in the array.  If there's a match, increment totals and then break ( there are multiple matches otherwise ).  At the END, print the total.

A: Here is a way using (G)awk and the gensub function
awk -va="GGTGGTGGT" '
        {for(i=1;i<=length(a);i++)if($0~gensub(/./,".",i,a)){print;next}}' file

Output
GGTGGTGGTAT
GGTAGTGGTAT
GGTGGTGGTAT

How it works
-va="GGTGGTGGT"

Sets the variable a to the value enclosed in the quotes(whatever you want)
{for(i=1;i<=length(a);i++)

Creates a loop from 1 to the length of the variable a.The length is the number of character inside the string.
if($0~gensub(/./,".",i,a))

I'll explain the gensub first.
The first two args swap .(any character) with a literal .. The 3rd argument is the occurrence of the match from argument 1. As we are searching for a single character, then this will just move through the string replacing each character with a .. The final arg is the string to edit and a is used. gensub also returns the string instead of editing the original.
$0~

Means the whole line contains whatever follows the ~
These are both contained in an if which when both evaluated will result in
$0~.GTGGTGGT
$0~G.TGGTGGT
$0~GG.GGTGGT
$0~GGT.GTGGT
$0~GGTG.TGGT
$0~GGTGG.GGT
$0~GGTGGT.GT
$0~GGTGGTG.T
$0~GGTGGTGG.

'
{print;next}

If any of those match then the line is print and all further instructions are skipped and the next line is processed.

Resources
https://www.gnu.org/software/gawk/manual/html_node/String-Functions.html

A: The necessary awk pattern is the same as your egrep solution:
awk '/GGTGGTGGT|.GTGGTGGT|G.TGGTGGT|GG.GGTGGT|GGT.GTGGT|GGTG.TGGT|GGTGG.GGT|GGTGGT.GT|GGTGGTG.T|GGTGGTGG./{print $0}' input

A: What you really want is agrep which stands for approximate grep.  It works incredibly well and is sometimes even faster than regular grep.
You can find the original here.
Installing is as simple as downloading the tar ball, running tar -xf <file>, navigating inside the resulting folder, and running make
Or the current (and possibly more bloated) version here
In your case you would simply:
agrep -1 GGTGGTGGT <file>

The -# is the number of mismatches you would like to allow.  The original version supports up to 8 mismatches.
It is important to note that agrep consideres a 'mismatch' to be either an insertion, deletion, or substitution.  So matches with one fewer or one extra character than the pattern string are considered, while all of the other answers here require the match to have the same number of characters.

redpajama_set_name: RedPajamaStackExchange


text:
Q: "Unidentified columns selected" I ran this code through RStudio and I received no errors:
rf.train.1 <- data.combined[1:891, c("Pclass", "Title")]
rf.label <- as.factor(train$Survived)

rf.1 <- randomForest(x = rf.train.1, y = rf.label, importance = TRUE, ntree = 1000)

However, when I try to do the same with a new variable it does not work and I receive an error stating that there are unidentified columns selected:
rf.train.2 <- data.combined[1:891, c("Pclass", "Title", "Sibsp")]

How can I stop receiving this error?


text:
Q: AES-CCM additional authenticated data length l(a) I implemented AES-CCM according to RFC-3610 and am wondering why the length of the additional authenticated data l(a) needs to be protected by the MAC.

A: Standard caveat: don't write your own encryption and use it. Use trusted libraries written by professional crypto people. There are ones for almost any language/ runtime you need or that should compile for it.
as to your question :
CBC-MAC by default only works on fixed length messages.  If an attacker knows a tag t on message m and and t' on message m', they can forge a tag on a third message that was not actually sent.  In fact this is
If you prepend  the length, its safer, though you can still get messages that are prefix's of each other and run into a similar problem. Hence one of the reasons a nonce is also prepended.


text:
Q: Error toDate() InvalidPipeArgument: 'Unable to convert Timestamp.. Firebase I have the following field in Firestore:

When I try to get it in my application, for example:

{{ fechaInicio | date }}

Get the following error:

ERROR Error: InvalidPipeArgument: 'Unable to convert
  "Timestamp(seconds=1553230800, nanoseconds=0)" into a date' for pipe
  'DatePipe'

then I saw that adding toDate() supposedly fixes the problem:

{{ fechaInicio.toDate() | date }}

This shows the date correctly, however I get the following error:

ERROR TypeError: Cannot read property 'toDate' of undefined

How can I solve that?

A: Just place a ? after fechaInicio like:

{{ fechaInicio?.toDate() | date }}

A: It seems like the variable 'fechaInicio' loads asynchronously. If so, 'fechaInicio' remains undefined till it get updated. Therefore, what you can do is hiding the html paragraph until the data get loaded to the variable.
Try the following modification.

{{ fechaInicio.toDate() | date }}


text:
Q: Created two different PHP Laravel contact forms both submit and send at the same time when you complete one form I have created two different contact forms using PHP Laravel, AJAX and Mailgun. Both forms are working as they both send mail via Mailgun. However, when you complete and send one form, it automatically sends the other form for some reason.
Here is the jQuery(AJAX) I used to send the mail:
$("form.wpcf7-form").submit(function(e){
    e.preventDefault();
    var token = $("input[name=_token]").val(); // The CSRF token
    var first_name = $("input[name=first-name]").val();
    var last_name = $("input[name=last-name]").val();
    var email = $("input[name=email]").val();
    var phone = $("input[name=phone]").val();
    var bodyMessage = $("textarea[name=message]").val();

    $.ajax({
       type:'POST',
       url:'/contact',
       dataType: 'json',
       data:{_token: token, first_name:first_name, last_name:last_name, email:email, phone:phone, bodyMessage:bodyMessage},
       success:function(data){
           $(".email-success-messge").append(data.success).fadeIn(999);

       }
    });
});

$("form.reservation-form").submit(function(e){
    e.preventDefault();
    var token = $("input[name=_token]").val(); // The CSRF token
    var fullname = $("input[name=fullname]").val();
    var phone = $("input[name=phone]").val();
    var email = $("input[name=email]").val();
    var number_of_guests = $("select[name=number_of_guests]").val();
    var date_of_reservation = $("input[name=date]").val();
    var time_of_reservation = $("input[name=time]").val();

    $.ajax({
       type:'POST',
       url:'/dine',
       dataType: 'json',
       data:{_token: token, fullname:fullname, phone:phone, email:email, phone:phone, number_of_guests:number_of_guests, date_of_reservation:date_of_reservation, time_of_reservation:time_of_reservation},
       success:function(data){
           $(".email-success-message").append(data.success).fadeIn(999);

       }
    });
});

My ReservationController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;
use Mail;
use Session;

class ReservationController extends Controller
{
    public function postReservation(Request $request){

        $data = array(
            'fullname' => $request->fullname,
            'phone' => $request->phone,
            'email' => $request->email,
            'number_of_guests' => $request->number_of_guests,
            'date_of_reservation' => $request->date_of_reservation,
            'time_of_reservation' => $request->time_of_reservation
        );

        Mail::send('emails.reservation', $data, function($message) use ($data){
            $message->from($data['email']);
            $message->to('jafar@calmcollective.co.uk');
            $message->subject('Reservation Details');
        });

        return response()->json(['success' => 'Thank you for making your reservation with us!'], 200);

    }
}

My ContactController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;
use Mail;
use Session;

class ContactController extends Controller
{
    public function postContact(Request $request){
        $this->validate($request, ['email' => 'required|email'] );

        $data = array(
            'first_name' => $request->first_name,
            'last_name' => $request->last_name,
            'email' => $request->email,
            'phone' => $request->phone,
            'bodyMessage' => $request->bodyMessage
        );

        Mail::send('emails.contact', $data, function($message) use ($data){
            $message->from($data['email']);
            $message->to('jafar@calmcollective.co.uk');
            $message->subject('Contact Details');
        });

        return response()->json(['success' => 'Thank you for getting in touch!'], 200);

    }
}

My routes
Route::post('/contact', 'ContactController@PostContact');

Route::post('/dine', 'ReservationController@postReservation');

Screenshot of my XHR requests:

A: From your post, there is surely an error in your HTML, a conflict between classes which causes a double Ajax call


text:
Q: Как можно выполнить модуль в python использовать переменную для имени модуля  path = 'bot.modules.msg'
 import path as main
 main.main()

A: Для этого лучше использовать importlib
import importlib

def main():
    msg = importlib.import_module('bot.modules.msg')
    msg.main()

if __name__ == '__main__':
    main()


text:
Q: Map offsite with matplotlib(using geopandas and cartopy) I have created a map like this:
The problem with it is that on the right side of the map is always a little bit offsite. I have set the bounds to:
ax.set_xlim(-215800,
            1000000)
ax.set_ylim(3402659,
            4879248)

No matter how I increase the xlim, or set margin the right side is still outside the bounds of the canvas. Can somebody help?
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from osgeo import ogr

import matplotlib.pyplot as plt
import matplotlib as mpl
import rasterio
import cartopy.crs as ccrs

import geopandas
from geopandas import *

from matplotlib import colors

MediumApple='#55FF00'
Cantaloupe='#FFA77F'
Marsred='#FF0000'
crs = ccrs.UTM(zone=10)
ax = plt.axes(projection=crs)
import matplotlib.patches as mpatches

for county in CAcountylist:
    with rasterio.drivers():
        with rasterio.open(r"CA\%s \%s.tif"%(county,county),"r") as src:
            meta = src.meta
            im=src.read().astype('f')
            im=np.transpose(im,[1,2,0])
            print im.shape
            print im.min(),im.max()
            im[im==0]=np.nan
            im=im.squeeze()
            xmin = src.transform[0]
            xmax = src.transform[0] + src.transform[1]*src.width
            print src.width,src.height
            ymin = src.transform[3] + src.transform[5]*src.height
            ymax = src.transform[3]
            colors=[MediumApple,Cantaloupe,Marsred]
             cmap=mpl.colors.ListedColormap([MediumApple,Cantaloupe,Marsred])
            bounds_color=[1,1,2,2,3,3]

            norm=mpl.colors.BoundaryNorm(bounds_color,cmap.N)
            print xmin,xmax,ymin,ymax
            ax.imshow(im, origin='upper', extent=[xmin,xmax,ymin,ymax], transform=crs, interpolation='nearest',cmap=cmap,norm=norm)
df=GeoDataFrame.from_file(r"\CACounty.shp")
df=df.to_crs(epsg=26910)
df.plot(axes=ax,alpha=0)
bounds = df.geometry.bounds
ax.set_xlim(-215800,
            1000000)
ax.set_ylim(3402659,
            4879248)
low_patch = mpatches.Patch(color='#55FF00', label='Low')
Moderate_patch = mpatches.Patch(color='#FFA77F', label='Moderate')
High_patch = mpatches.Patch(color='#FF0000', label='High')

plt.legend(handles=[low_patch,Moderate_patch,High_patch],loc=3)

plt.show()


text:
Q: DependencySQL, weird behavior on update I'm trying to use SQLDependency in my WPF application.
I have 2 different behavior, depending on how i update the database
The behavior 1 (Update from database) :

*

*On first database change (customer update) -> The soft receive the notification, the client list is updated.

*On second database change (customer update), the soft receive the notification, but the query result isn't updated.

*If the database change is "create customer" i receive the notification with ne new customer

The Behavior 2 (Changes from soft):

*

*I select one customer, from the customer list and update it. I receive a notification and the customer list is updated. If i re-update the save row, i still receive the notification but the query result isn't updated.

*But ! If i update another customer and change it, i can do it multiple time, the query results are ok ! only the first one bug.(from database, after the first one, i receive the notification, but query result isn't updated anyway)
Code :
    #region Updater
private IQueryable iCustomerquery = null;
private ImmediateNotificationRegister<Customer> notification = null;
RDatabase ctx = new RDatabase();

void createCustomerRefreshQuery()
{

    // Create the query.
    iCustomerquery = from p in ctx.Customers select p;

    notification = new ImmediateNotificationRegister<Customer>(ctx, iCustomerquery);
    notification.OnChanged += NotificationOnChanged;

}

/// <summary>
/// When changed the data, the method will be invoked.
/// </summary>
void NotificationOnChanged(object sender, EventArgs e)
{
    System.Windows.Application app = System.Windows.Application.Current;
    app.Dispatcher.BeginInvoke(new Action(UpdateCustomer), null);

}

void UpdateCustomer()
{

    if (CanRequestNotifications())
    {
        Console.WriteLine("UPDATE");

        try
        {
            var customers = (iCustomerquery as DbQuery<Customer>).ToList();
            ClientList.Clear();
            foreach (var customer in customers)
            {

                ClientList.Add(customer);
                OnPropertyChanged("ClientList");

            }
        }
        catch (Exception ex)
        {
            if (ex.InnerException != null)
            {
                Console.WriteLine(ex.Message + "(" + ex.InnerException.Message + ")");
            }
            else
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
    //iCustomerquery = from p in ctx.Customers select p;

}

private bool CanRequestNotifications()
{
    // In order to use the callback feature of the
    // SqlDependency, the application must have
    // the SqlClientPermission permission.
    try
    {
        SqlClientPermission perm =
            new SqlClientPermission(
            PermissionState.Unrestricted);

        perm.Demand();

        return true;
    }
    catch (SecurityException se)
    {
        Console.WriteLine(se.Message, "Permission Error");
        return false;
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message, "Error");
        return false;
    }
}
/// <summary>
/// Stop SqlDependency.
/// </summary>
private void StopSqlDependency(object sender, EventArgs e)
{
    try
    {
        Console.WriteLine("Stop sql dependency");
        if (notification != null)
        {
            notification.Dispose();
            notification = null;
        }
    }
    catch (ArgumentException ex)
    {
        //MessageBox.Show(ex.Message, "Paramter Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    catch (Exception ex)
    {
        if (ex.InnerException != null)
        {
            Console.WriteLine(ex.Message + "(" + ex.InnerException.Message + ")", "Failed to Stop SqlDependency");
        }
        else
        {
            Console.WriteLine(ex.Message, "Failed to Stop SqlDependency");
        }
    }
}

#endregion

I used this sample from msdn
ImmediateNotificationRegister :
    public class ImmediateNotificationRegister<TEntity> : IDisposable
    where TEntity : class
{
    private SqlConnection connection = null;
    private SqlCommand command = null;
    private IQueryable iquery = null;
    private ObjectQuery oquery = null;

    // Summary:
    //     Occurs when a notification is received for any of the commands associated
    //     with this ImmediateNotificationRegister object.
    public event EventHandler OnChanged;
    private SqlDependency dependency = null;

    /// <summary>
    /// Initializes a new instance of ImmediateNotificationRegister class.
    /// </summary>
    /// <param name="query">an instance of ObjectQuery is used to get connection string and
    /// command string to register SqlDependency nitification. </param>
    public ImmediateNotificationRegister(ObjectQuery query)
    {
        try
        {
            this.oquery = query;

            QueryExtension.GetSqlCommand(oquery, ref connection, ref command);

            BeginSqlDependency();
        }
        catch (ArgumentException ex)
        {
            throw new ArgumentException("Paramter cannot be null", "query", ex);
        }
        catch (Exception ex)
        {
            throw new Exception(
                "Fails to initialize a new instance of ImmediateNotificationRegister class.", ex);
        }
    }

    /// <summary>
    /// Initializes a new instance of ImmediateNotificationRegister class.
    /// </summary>
    /// <param name="context">an instance of DbContext is used to get an ObjectQuery object</param>
    /// <param name="query">an instance of IQueryable is used to get ObjectQuery object, and then get
    /// connection string and command string to register SqlDependency nitification. </param>
    public ImmediateNotificationRegister(DbContext context, IQueryable query)
    {
        try
        {
            this.iquery = query;

            // Get the ObjectQuery directly or convert the DbQuery to ObjectQuery.
            oquery = QueryExtension.GetObjectQuery<TEntity>(context, iquery);

            QueryExtension.GetSqlCommand(oquery, ref connection, ref command);

            BeginSqlDependency();
        }
        catch (ArgumentException ex)
        {
            if (ex.ParamName == "context")
            {
                throw new ArgumentException("Paramter cannot be null", "context", ex);
            }
            else
            {
                throw new ArgumentException("Paramter cannot be null", "query", ex);
            }
        }
        catch (Exception ex)
        {
            throw new Exception(
                "Fails to initialize a new instance of ImmediateNotificationRegister class.", ex);
        }
    }

    private void BeginSqlDependency()
    {
        // Before start the SqlDependency, stop all the SqlDependency.
        SqlDependency.Stop(QueryExtension.GetConnectionString(oquery));
        SqlDependency.Start(QueryExtension.GetConnectionString(oquery));

        RegisterSqlDependency();
    }

    private void RegisterSqlDependency()
    {
        if (command == null || connection == null)
        {
            throw new ArgumentException("command and connection cannot be null");
        }

        // Make sure the command object does not already have
        // a notification object associated with it.
        command.Notification = null;

        // Create and bind the SqlDependency object to the command object.
        dependency = new SqlDependency(command);
        dependency.OnChange += new OnChangeEventHandler(DependencyOnChange);

        // After register SqlDependency, the SqlCommand must be executed, or we can't
        // get the notification.
        RegisterSqlCommand();
    }

    private void DependencyOnChange(object sender, SqlNotificationEventArgs e)
    {
        // Move the original SqlDependency event handler.
        SqlDependency dependency = (SqlDependency)sender;
        dependency.OnChange -= DependencyOnChange;

        if (OnChanged != null)
        {
            OnChanged(this, null);
        }

        // We re-register the SqlDependency.
        RegisterSqlDependency();
    }

    private void RegisterSqlCommand()
    {
        if (connection != null && command != null)
        {
            connection.Open();
            command.ExecuteNonQuery();
            connection.Close();
        }
    }

    /// <summary>
    /// Releases all the resources by the ImmediateNotificationRegister.
    /// </summary>
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected void Dispose(Boolean disposed)
    {
        if (disposed)
        {
            if (StopSqlDependency())
            {
                if (command != null)
                {
                    command.Dispose();
                    command = null;
                }

                if (connection != null)
                {
                    connection.Dispose();
                    connection = null;
                }

                OnChanged = null;
                iquery = null;
                dependency.OnChange -= DependencyOnChange;
                dependency = null;
            }
        }
    }

    /// <summary>
    /// Stops the notification of SqlDependency.
    /// </summary>
    /// <returns>If be success, returns true;If fails, throw the exception</returns>
    public Boolean StopSqlDependency()
    {
        try
        {
            SqlDependency.Stop(QueryExtension.GetConnectionString(oquery));
            return true;
        }
        catch (ArgumentException ex)
        {
            throw new ArgumentException("Parameter cannot be null.", "query", ex);
        }
        catch (Exception ex)
        {
            throw new Exception("Fails to Stop the SqlDependency in the ImmediateNotificationRegister class.", ex);
        }
    }

    /// <summary>
    /// The SqlConnection is got from the Query.
    /// </summary>
    public SqlConnection Connection
    { get { return connection; } }

    /// <summary>
    /// The SqlCommand is got from the Query.
    /// </summary>
    public SqlCommand Command
    { get { return command; } }

    /// <summary>
    /// The ObjectQuery is got from the Query.
    /// </summary>
    public ObjectQuery Oquery
    { get { return oquery; } }
}

The query extension :
    public static class QueryExtension
{
    /// <summary>
    /// Return the ObjectQuery directly or convert the DbQuery to ObjectQuery.
    /// </summary>
    public static ObjectQuery GetObjectQuery<TEntity>(DbContext context, IQueryable query)
        where TEntity : class
    {
        if (query is ObjectQuery)
            return query as ObjectQuery;

        if (context == null)
            throw new ArgumentException("Paramter cannot be null", "context");

        // Use the DbContext to create the ObjectContext
        ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext;
        // Use the DbSet to create the ObjectSet and get the appropriate provider.
        IQueryable iqueryable = objectContext.CreateObjectSet<TEntity>() as IQueryable;
        IQueryProvider provider = iqueryable.Provider;

        // Use the provider and expression to create the ObjectQuery.
        return provider.CreateQuery(query.Expression) as ObjectQuery;
    }

    /// <summary>
    /// Use ObjectQuery to get SqlConnection and SqlCommand.
    /// </summary>
    public static void GetSqlCommand(ObjectQuery query, ref SqlConnection connection, ref SqlCommand command)
    {
        if (query == null)
            throw new System.ArgumentException("Paramter cannot be null", "query");

        if (connection == null)
        {
            connection = new SqlConnection(QueryExtension.GetConnectionString(query));
        }

        if (command == null)
        {
            command = new SqlCommand(QueryExtension.GetSqlString(query), connection);

            // Add all the paramters used in query.
            foreach (ObjectParameter parameter in query.Parameters)
            {
                command.Parameters.AddWithValue(parameter.Name, parameter.Value);
            }
        }
    }

    /// <summary>
    /// Use ObjectQuery to get the connection string.
    /// </summary>
    public static String GetConnectionString(ObjectQuery query)
    {
        if (query == null)
        {
            throw new ArgumentException("Paramter cannot be null", "query");
        }

        EntityConnection connection = query.Context.Connection as EntityConnection;
        return connection.StoreConnection.ConnectionString;
    }

    /// <summary>
    /// Use ObjectQuery to get the Sql string.
    /// </summary>
    public static String GetSqlString(ObjectQuery query)
    {
        if (query == null)
        {
            throw new ArgumentException("Paramter cannot be null", "query");
        }

        string s = query.ToTraceString();

        return s;
    }

}

Update 1 :
I didn't do the following should i ?
CREATE QUEUE CustomerChangeMessages;
CREATE SERVICE CustomerChangeNotifications
  ON QUEUE CustomerChangeMessages
([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification]);

A: I feel like one of 2 things is happening here, 1. You are removing the event handler prematurely, or 2 firing the primary trigger is invalidating the dependent trigger some how so it never fires.
Also your issue could be to do with all of the starting and stopping of the of the SqlDependency, anytime I have seen SqlDependency used, and when I have used it myself, its been started at the application start and stopped in application end, and the event handlers and recreation of the trigger itself has been used to manipulate firing.
A couple things I would try, (I am kinda guessing here because it is unclear what the issue is you are trying to resolve)
1. Move your start and stop to app start and app end
2. You could also recreate the all of the triggers whenever any are fired since they are dependent on each other.


text:
Q: Create new pandas column with same list as every row? I would like to create a new column in a dataframe that has a list at every row. I'm looking for something that will accomplish the following:
df = pd.DataFrame(data={'A': [1, 2, 3], 'B': ['x', 'y', 'z']})
list_=[1,2,3]
df['new_col] = list_
   A       B     new_col
0  1       x     [1,2,3]
1  2       y     [1,2,3]
2  3       z     [1,2,3]

Does anyone know how to accomplish this? Thank you!

A: df = pd.DataFrame(data={'A': [1, 2, 3], 'B': ['x', 'y', 'z']})
list_=[1,2,3]
df['new_col'] = [list_]*len(df)

Output:
    A   B   new_col
0   1   x   [1, 2, 3]
1   2   y   [1, 2, 3]
2   3   z   [1, 2, 3]

Tip: list as a variable name is not advised. list is a built in type like str, int etc.

A: df['new_col'] = pd.Series([mylist for x in range(len(df.index))])

("list" is a terrible variable name, so I'm using "mylist" in this example).

A: df['new_col'] = [[1,2,3] for j in range(df.shape[0])]


text:
Q: Getting started with a parser in Java code I am new to parsers. I like to fetch specific data from a website. I need to use parsers for that. How to get started with parsers? What do I need to download?
What would the code be to fetch the data from a website using parsers in Java?

A: My advice would be to use an open source HTML parser such as HTMLCleaner - http://htmlcleaner.sourceforge.net/
You can use HTMLCleaner (or similar) to create a representation of the web page DOM, and then use this to extract whatever information you want from the web pages.
The process looks something like this:
URL url = new URL("website you want to load");
HTMLCleaner h = new HTMLCleaner();
TagNode HtmlNode = h.clean(url.openStream());
//perform queries on the DOM to extract information


text:
Q: Мне необходимоСоставить программу для обработки массива из 12 вещественных чисел. и вывести нечетные числа, но выдает ошибку: тип real к integer Program Massiv1;
Uses Crt;
var k:array[1..12] of real;
i,c:integer;
begin
clrscr;
write('Введите элементы массива k:');
c:=0;
for i:=1 to 12 do
begin
readln(k[i]);
if (k[i] mod 2=0) then Inc(c);
end;
writeln;
writeln;
for i:=1 to 12 do write(k[i]:4:4);
writeln;
writeln('Количество нечетных элементов :',c);
readkey;
end.

A: У вас массив k типа real (вещественные числа), операцию целочисленного деления mod можно использовать только с целыми числами.
Вам нужно заменить real на integer в 3 строчке.


text:
Q: I need a dynamic way to apply css content based on DOM innerhtml values I currently use react js to dynamically render search results of an api inside a
 tag. The domain results render like this:

yahoo.com
bracket.io
codepin.io
samplesite.net

I have css applied to the div itself but how do I apply "css content" based on the innerHtml inside the DOM element (for example regex based on the actual words). The purpose I ask this is because I would like to append something in the css based on the tld of the returned domain, if I get a .com site, Id like css to know somehow that inside the div element a site named .com was rendered then dynamically apply this to include the same for all others.
.results {

content: site .com was rendered;
content: site .net was rendered;
}

An so forth.

A: You would have something like:
render() {

    { this.props.results.map ((tld) => {
      <span className=classNames({ [`results__${tld}`]: true });>
        // list of results

    }

}

where results would be an object that has been created in an adapter after getting your data from your api.
You would then adapt it in a way that would sort it into groups based on the tld.
JedWatson/classnames would give you the dynamic classNames


text:
Q: WinDbg cannot find symbols for ntdll on MS symbol server I'm trying to debug executable notepad.exe (from Windows 10 distribution), and symbols ntdll.pdb from Microsoft symbols server are required, but debugger returns an error that they cannot find file specified:
0:000> .reload
Reloading current modules
.................................
SYMSRV:  BYINDEX: 0x25
         http://msdl.microsoft.com/download/symbols
         ntdll.pdb
         BC08E2B7EBB349A18DCE18BE9AA6660E1
SYMSRV:  HTTPGET: /download/symbols/ntdll.pdb/BC08E2B7EBB349A18DCE18BE9AA6660E1/ntdll.pdb
SYMSRV:  HttpQueryInfo: 404 - HTTP_STATUS_NOT_FOUND
SYMSRV:  HTTPGET: /download/symbols/ntdll.pdb/BC08E2B7EBB349A18DCE18BE9AA6660E1/ntdll.pd_
SYMSRV:  HttpQueryInfo: 404 - HTTP_STATUS_NOT_FOUND
SYMSRV:  HTTPGET: /download/symbols/ntdll.pdb/BC08E2B7EBB349A18DCE18BE9AA6660E1/file.ptr

SYMSRV:  HttpQueryInfo: 404 - HTTP_STATUS_NOT_FOUND
SYMSRV:  C:\ProgramData\dbg\sym\ntdll.pdb\BC08E2B7EBB349A18DCE18BE9AA6660E1\ntdll.pdb - file not found
SYMSRV:  http://msdl.microsoft.com/download/symbols/ntdll.pdb/BC08E2B7EBB349A18DCE18BE9AA6660E1/ntdll.pdb not found
SYMSRV:  C:\ProgramData\dbg\sym\ntdll.pdb\BC08E2B7EBB349A18DCE18BE9AA6660E1\ntdll.pdb not found
DBGHELP: C:\WINDOWS\SYSTEM32\ntdll.pdb - file not found
DBGHELP: ntdll.pdb - file not found
*** ERROR: Symbol file could not be found.  Defaulted to export symbols for ntdll.dll -
DBGHELP: ntdll - export symbols

************* Symbol Loading Error Summary **************
Module name            Error
SharedUserData         No error - symbol load deferred
                Symbol loading has been deferred because this symbol is not needed
                at this time. Use reload /f to force load symbols.

ntdll                  The system cannot find the file specified : http://msdl.microsoft.com/download/symbols
                The SYMSRV client failed to find a file in the UNC store, or there
                is an invalid UNC store (an invalid path or the pingme.txt file is
                not present in the root directory), or the file is present in the
                symbol server exclusion list.

Is it possible that MS server does not contain required symbols?
It is: version 10.0.14393.447 (rs1_release_inmarket.161102-0100)

A: The NTDLL.PDB (ntdll.pdb\BC08E2B7EBB349A18DCE18BE9AA6660E1\ntdll.pdb) is now online and I was able to get the PDB:
00007ffb`c79c0000 00007ffb`c7b91000   ntdll
(pdb symbols) d:\sym\dl\nt\ntdll.pdb\BC08E2B7EBB349A18DCE18BE9AA6660E1\ntdll.pdb
    Loaded symbol image file: ntdll.dll
    Image path: C:\Windows\System32\ntdll.dll
    Image name: ntdll.dll
    Browse all global symbols  functions  data
    Timestamp:        Wed Nov  2 11:13:06 2016 (5819BC32)
    CheckSum:         001DA569
    ImageSize:        001D1000
    File version:     10.0.14393.447
    Product version:  10.0.14393.447
    File flags:       0 (Mask 3F)
    File OS:          40004 NT Win32
    File type:        2.0 Dll
    File date:        00000000.00000000
    Translations:     0409.04b0
    CompanyName:      Microsoft Corporation
    ProductName:      Microsoft® Windows® Operating System
    InternalName:     ntdll.dll
    OriginalFilename: ntdll.dll
    ProductVersion:   10.0.14393.447
    FileVersion:      10.0.14393.447 (rs1_release_inmarket.161102-0100)
    FileDescription:  NT Layer DLL
    LegalCopyright:   © Microsoft Corporation. All rights reserved.

So try again to load the symbols.


text:
Q: Database deploy with updates Does anybody know how to do smart database update in realtime.
E.g. I have a site with a great database. Suddenly I've made some code changes and database structure and data changes. Is there any standard plan to do it with deploy script or any deploy soft? In realtime without stopping the site?
E.g. switch between two clone databases or smth like that. How do experienced people do that?
Site is written in php, database is MySql.
Thanx!

A: Have you looked at DBdeploy? There's a good article here on managing database deployments using Phing and DBdeploy

A: Red Gate MySQL Compare has a 14-day fully functional trial. It preserves data when doing schema changes. There is also a separate MySQL Data Compare tool.
http://www.red-gate.com/products/sql-development/mysql-compare/


text:
Q: Fresh Ubuntu 19 install : stuck in 1024.x768 resolution Fresh install on PC to replace Fedora by Ubuntu
Intel 4790K, Nvidia 980 GTX plugged to a HD screen
I selected to install with Nvidia driver but after install is done, I'm stuck in 1024x768. The Display control panel does not offer any other resolution...


text:
Q: Laravel won't save variable to database via mobile brave browser Edit: Removing the brave shields didn't correct the issue on mobile.  Hard coding the variable does work (even though dumping the variable shows the variable is the same value as the hard coded value).
I have a section of a controller that receives the routes within the url and then saves the variables into the database. This is done through a get route.  Below is an obfuscated version of the code.
public function getDataAndSave($handle, $integer=null){

    $value = array('id' => $id,
            'integer' => $integer,
    );

    $ValueToUpdate = Table::where('id', '=', $id)->first();

    if(isset($ValueToUpdate->id)){
        $ValueToUpdate->update([
            'integer' => isset($value['integer']) ? $value['integer'] : $ValueToUpdate->integer,
            'text' => isset($value['text']) ? $value['text'] : $ValueToUpdate->text
        ]);
    }
}

//Route looks like this
Route::get('update-value/{handle}/{integer?}', ['middleware' => [],
            'uses' => 'UpdateValueController@getDataAndSave',
            'as' => 'UpdateValue.view',
            'roles' => []]

The Issue
This works fine in the Brave and other browsers on my laptop, but if I run it using brave browser on my mobile device, the $integer value saves as 0, while the text value saves as expected.  When I vardump the $integer or $value variables, it will show the proper integer, even when using the problematic browser on my phone.   If I turn off the Brave Browser's Shields then it works.  If I hard code an integer value instead of updating the integer variable using $integer like this:
    $ValueToUpdate->update([
        'integer' => isset($value['integer']) ? 5 : $ValueToUpdate->integer,
    ]);

It saves the 5 as I'd expect.
I know this is bad practice, but I'm saving this specific dataa within a get route (not a post).
Has anyone experienced something like this before and have a solution?  I'm going to toggle each shield protection from brave to find the cause, but thought I'd ask here in case someone experiences a similar issue in the future.
Additionally, here is the screenshot of my vardump on the object being saved after it's saved on my mobile phone.   You'll see that there is a "changes" section of my collection and it shows the variable rating set to 5 even though the save made by eloquent is saving 0.


text:
Q: cd to target folder after copying? This could be quite a simple one, but I can't find any answer for it.
If I am in a terminal and use the cp command, is there a way of instantly cding to the target directory? For example, is there some equivalent to cp foo/file.ext ../bar/subdir/; cd ../bar/subdir/ that doesn't require retyping the path to the target folder?

A: You can do:
cp foo/file.ext ../bar/subdir/

followed by:
cd !$

But this won't work in one line, like cp foo/file.ext ../bar/subdir/; cd !$.


text:
Q: Speed up parser: HTML into Database I need insert all html tags and attributes into database
el.driver.get(url_page)
txthtml = el.driver.page_source
soup = BeautifulSoup(txthtml, "html.parser")
body = soup.find('html')
html_parse(body, el, url_page_id, 0, 0, 0,url_page)

def html_parse(html, el, url_page_id, level, i, parent_id, url_page):
    txt = ""
    if len(html.text) > 0:
       txt = html.text.replace("\n","").replace("\t","").replace("\r","")
    ta = tag_list()
    ta.p_id = el.id
    ta.page_id = url_page_id
    ta.level = level
    ta.number = i
    ta.txt = txt
    ta.name = html.name
    ta.parent_id = parent_id
    ta.html = str(html)
    ta.save()
    insert_attr(html, el.id, url_page_id, ta.id, url_page)
    children = list(html.children)
    j = 0
    for child in children:
        if child.name is None:
            continue
        j = j + 1
        html_parse(child, el, url_page_id, level + 1, j, ta.id, url_page)

When I have recursive function html_parse

*

*html -  current html object

*el - driver class

*url_page_id - id of page

*level - level in DOM

*i - childe number

*parent_id - id of parent

*url_page - current URL

*tag_list - insert current tag

*insert_attr - insert into database attrs of tag

Every html_parse function run fast, but full html parsing run about 4-5 minutes per big html page.
How I can speed up the code?


text:
Q: Creating a new column that is an average of non-adjacent rows in the data frame I am very new to R. I have multiple columns of variables relating to different question responses on a questionnaire. I wish to generate a new column in the data frame that is an average of a set of these preceding variables. I have seen that rowMeans can be used for this, but this seems to only work for adjacent columns, but the columns I want to average are not adjacent. I also want some control over how missing data is dealt with. I created example data using
Var1<- c(1.5, 2.3, NA, NA, 2.3, 3.3)
Var2<- c(1.7, 2.2, 4.7, 13.3, 1.7, 1.5)
Var3<- c(5.1, 6.7, 3.4, 5.5, NA, 8.7)
Var4<- c(4.5, 5.4, NA, 4.5, 5.4, 8.9)

Which gives
  Var1 Var2 Var3 Var4
1  1.5  1.7  5.1  4.5
2  2.3  2.2  6.7  5.4
3  NA   4.7  3.4  NA
4  NA   13.3  5.5  4.5
5  2.3  1.7  NA  5.4
6  3.3  1.5  8.7  8.9

So I want to create a new column or variable in this data frame that is an average of Var1, Var2 and Var4 (but not Var3). I also want it to still produce an average of remaining data if data for one of the variables is missing, but I want it to return NA in the new column if there is missing data for two of the columns. So for person 3 the new column would be NA, but for person 4 and 5 an average of the available values in the three columns would be produced.
I hope this makes sense, any help much appreciated

A: We can use rowSums to check the number of NAs for the selected columns by subsetting the dataset.  If it is greater than 1, then return NA or else 1.  Then, with rowMeans get the mean of the rows for the selected columns and change those rows that have more than 1 NA to NA
# column index
ind <- c(1, 2, 4)
i1 <- NA^(rowSums(is.na(df1[ind])) > 1)
df1$newCol <- rowMeans(df1[ind], na.rm = TRUE) * i1

data
df1 <- data.frame(Var1, Var2, Var3, Var4)

A: Given..
df1 <- data.frame(Var1, Var2, Var3, Var4)

One line solution would be..
df1$newCol <- apply(df1[,-3],1,function(x){ifelse(sum(is.na(x))>1,NA,mean(x,na.rm=T))})


text:
Q: After updating Eclipse, I get an error when creating a new Android project I recently updated Eclipse, and now when I go to create a new project it will display an error that says "The SDK doesn't have the directory tool/progaurd.cfg".
How can I fix this?
Also, after you continue with the error there is no r.java file...

A: I had the same problem before. Updating the Android SDK Tool fixed it. Here is how: "Window" -> "Android SDK and ADV Manager" -> "Installed packages" -> "Update all...".

A: I too had this same issue. I had other projects too...But it didnt have this error..When I created a new one, one day it came with this error. My error went I placed this file into that folder.

A: FIXED IT. All you have to do is, reinstall the update ADT in eclipse. You do this by Help,AVD and SDK Manager,Available packages. Install the latest ones AGAIN even if you have already installed it.
This fixed it for me perfectly. So give it a try!


text:
Q: Multiple lines of text in extjs grid panel cell I have a gird. I want to display multiple lines in some grid cells. Following is the div that I am generating which has two lines of text. But this is not rendering the second line i.e. "test new line".

      XYZ funding round: Series C (Funding Round)

      test new line

It is an extjs 3.4 grid.
Any idea why this would not render two lines?

A: I solved this problem with grid's viewConfig option:
viewConfig: {
    loadingText: lang.loading,
    loadMask: true,
    stripeRows: true,
    getRowClass: function(record, rowIndex, rowParams, store) {
        return 'multiline-row';
    }
},

and in the CSS file:
.multiline-row .x-grid-cell-inner {
    overflow: auto !important;
    white-space: normal !important;
    text-overflow: ellipsis;
    display: block;
}

And works fine in ExtJS 4.
Hope it helps.

A: For that column:
 renderer: function (value, metaData) {
                 return '
' + value + '
';
             }

A: I know it is not exactly what you are doing (generating markup with line break), but it serves similar purpose - displaying multiple lines in a single cell, by providing custom cell XTemplate. Here is the code: https://fiddle.sencha.com/#fiddle/5qd
EDIT: I added line break to first column, it also works but inner cell styles are not applied to every line.


text:
Q: Memory Utilization of any Spark Job I have developed an algorithm in Spark and I need to report the memory consumption of my algorithm throughout its execution for different input data size. Specifically, I require the peak memory utilization and peak IO usage of my Spark job during its execution for each node or for a each executor. My questions are

*

*Spark UI provides RDD size in the storage tab. Will adding all RDD sizes be sufficient for the memory consumption or I have to look any other things.

*If I have to compare mine with other algorithms, how to check the memory consumption. Because in that case I won't have access the codes.

*How to calculate peak IO usage. Does Shuffle read/write will help in this case.


text:
Q: Two side-by-side columns with children and children's children filling 100% minus margins I'm stumped on this one.  I've literally tried everything from floated divs, to absolute\relative positioning, to table-cells.  Perhaps there is a better way to word the question but I am trying to have two columns in a container.  The columns are both of an unknown height since they are filled with dynamic content.  The columns must grow to match each other in height however the columns each contain a "box" with special backgrounds and borders (hence why the I can't just do the margin: -5000px; padding: 5000px; hack).
I also tried jQuery where each box has a "growth factor" at the bottom.  On $(window).load() I calculate the height of each column and set the growth factor on the smallest div to the difference.  This works but you can see the div snapping and I'd rather avoid JS.  I have to wait until $(window).load() due to the fact that one of the columns contains images which influence the height.
I mocked up a Fiddle here
Here's what I have:
(Link in comments)
Here's what I want:
(Other link in comments)
Here is my HTML and CSS:

Some stuff on the top

Box Header Left

LEFT

LEFT

LEFT

I neeed to somehow fill the remaining space.  The "box" (grey) should fill the column and the inner part of the box (this white) should fill the box, leaving the margins and padding intact

Box Header Right

RIGHT

RIGHT

RIGHT

RIGHT

RIGHT

RIGHT

RIGHT

RIGHT

RIGHT

RIGHT

RIGHT

RIGHT

RIGHT

RIGHT

Some stuff on the bottom, I need to be pushed down as the div set grows

CSS:
.container {
}

.column {
    float: left;
}

.left-column {
    width: 300px;
    margin-right: 10px;
}

.right-column {
    width: 200px;
}

.box {
    background: grey;
    border-radius: 5px;
    padding: 10px;
}

.inner-box {
    background: #FFF;
    padding: 0 10px;
    border-radius: 0 0 10px 10px;
}

.box-header {
    background: #FFFF00;
    border-radius: 10px 10px 0 0;
    height: 30px;
}

A: Here is what I did with display: table , row and cell. Definitely check out that positioning
http://jsfiddle.net/M9JWM/3/
//basic structure

    Lorem

        Lorem ipsum dolor sit amet, consectetur adipiscing elit.

css
.table{
display: table}
.row{
display: table-row}
.left.right{
display: table-cell}

A: Check heights of each box using jQuery and adjust accordingly.  In addition to the jQuery I added ids to your left and right boxes (like this:
)
var left_height = $('#left-box').height();
var right_height = $('#right-box').height();

if(left_height>right_height){
     $('#right-box .inner-box').css("height", left_height-30);
}else{
     $('#left-box .inner-box').css("height", right_height-30);
}

Subtract 30 from the height to adjust for padding.  Add or remove rows and the boxes move in line with each other.
jsFiddle Demo


text:
Q: About injective hull Let $M$ be an $A$-module. Is its injective hull affected by whether I regard $M$ as an $A$-module or $A/\mbox{Ann}(M)$-module ?

A: I'll follow up on what Karl said with an example closer to my own experience. Let $\mathbb{Z}$ be the ring of integers and $p$ a positive prime. Then $\mathbb{Z}/p\mathbb{Z}$ is injective as a $\mathbb{Z}/p\mathbb{Z}$ - module, being a vector space over a field, whence $\mathbb{Z}/p\mathbb{Z}$ is its own injective envelope (hull) as a $\mathbb{Z}/p\mathbb{Z}$ module. However, the injective envelope of $\mathbb{Z}/p\mathbb{Z}$ as an abelian group is $\mathbb{Z}(p^{\infty})$, which gives witness to Karl's statement that the injective envelope over $A$ can be much larger than the injective envelope over $A/\mathrm{ann}(M)$. You can play this game with $A$ any commutative Noetherian ring with 1, ann($M$) = any maximal ideal of $R$, and $M = A/I$ where $I$ is the chosen maximal ideal. Karl's example presents very limited choice for $I$ since $k[[x]]$is local. I think Proposition 2.27 and Lemma 4.24 of "Injective Modules" by Sharpe and Vamos present enough to figure out what is going on in the general case.

A: Yes, take $A = k[[x]]$ and $M = A/(x)$.  Then as a $k = A/(x) = A/\text{Ann}(M)$-module, the injective hull of $k$ is $k$.  As an $A$-module, the injective hull is much much bigger.


text:
Q: Constructing the open cover from given open cover with the desired property Let $\{U_1,U_2,\ldots\}$ be a cover of $\mathbb{R}^n$ by open sets. Prove that there is an open cover $\{V_1,V_2,\ldots\}$ such that

*

*$V_j \subset U_j$ for each $j$,

*each compact subset of $\mathbb{R}^n$ is disjoint from all but finitely many of the $V_j$.

My attempt:
First thing we noticed that any compact set $K\subset \mathbb{R}^n$ is contained in some closed ball $\mathbb{B}[0,n]=B_n.$ Now since, each of the $B_n$ are compact so for each $n\in \mathbb{N}$ there exists finitely many $U_J$'s which will cover the ball $B_n$. Now assume that $j_n$ be the smallest index such that $B_n\subset \bigcup_{j=1}^{j_n} U_j.$ Now I stuck how to construct the sets $V_j$ from these things.

A: I shall denote by $B'(p,r)$ the closed ball centered at $p$ with radius $r$.
We know that $B'(0,1)\subset\bigcup_{n\in\mathbb N}U_n$. Since $B'(0,1)$ is compact, it is contained in finitely many of them. Let $F_1\subset\mathbb N$ be a finite subset of natural numbers such that $B'(0,1)\subset\bigcup_{n\in F_1}U_n$.
Now, we start again with $B'(0,2)$. It is contained in some finite union $\bigcup_{b\in F_2}U_n$, with $F_2\supset F_1$. And we can start again: $B'(0,3)\subset\bigcup_{n\in F_3}U_n$ with $F_3$ finite and containing $F_2$. And so on…
Now, if $n\in F_1$, let $V_n=U_n$. If $n\in F_2\setminus F_1$, let $V_n=U_n\setminus B'(0,1)$. If $n\in F_3\setminus F_2$, let $V_n=U_n\setminus B'(0,2)$. And so on… Note that, with this definition, $V_n$ is open and a subset of $U_n$.
Finally, for each $m\in\mathbb{N}\setminus\bigcup_{n\in\mathbb N}F_n$, let $V_m=\emptyset$.
If $K$ is a compact subset of $\mathbb{R}^n$, then $K\subset B'(0,N)$, for some $N\in\mathbb N$. And therefore only finitely many $V_m$'s cover $K$: those such that $m\in F_N$. In other words, $K\subset\bigcup_{k\in F_N}V_k$. All other $V_k$'s are disjoint form $B'(0,N)$ and therefore disjoint from $K$.


text:
Q: Update Pages ONLY from Stage to Live (not products) I have a WordPress site that has a bunch of posts, a bunch of pages and a bunch of products (Woocommerce ones). I Staged the site and made loads of changes to the pages on stage, meanwhile the live site posts and products grew and grew. Now I am ready to deploy the changes that I made to the pages on stage on to the live site, however, when I publish the "...posts" and the "...postmeta" tables they overwrite the products.
So, how do I publish the changes I made on the stage site pages without impacting any other content?
FYI - my pages are built using Elementor, but i do not think that factors in this.
Kind regards,
John


text:
Q: Yii, file upload using CMultiFileUpload I'm total newbie in Yii so dont get mad. I cant figure out how CUploadFile works. I have my view file:

<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'image-temp-form',
    'enableAjaxValidation'=>false,
    'htmlOptions'=>array('enctype'=>'multipart/form-data' ),
)); ?>

Fields with * are required.

<?php echo $form->errorSummary($model); ?>

        <?php echo $form->labelEx($model,'car_type'); ?>
        <?php
        $this->widget('CMultiFileUpload', array(
            'model'=>$model,
            'attribute'=>'car_type',
            //'name' => 'files',
            'accept'=>'jpg|gif|png',
            'denied'=>'File is not allowed',
            'max'=>3,
        ));
        ?>
        <?php echo $form->error($model,'car_type'); ?>

        <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>

<?php $this->endWidget(); ?>

My controller broken down to bits:
public function actionCreate()
{
    $model=new EeCarTypes;

    if ( isset( $_FILES['EeCarTypes']))
    {
        $images = $_FILES['EeCarTypes'];
       $model->car_type = $images['name']['car_type'][0];
        $uploadedFile = CUploadedFile::getInstance($model, 'car_type');
        CVarDumper::Dump($uploadedFile, 10 ,true);
        $uploadedFile->saveAs(Yii::app()->basePath . '/../images/upload/cartypes/'.'hehehe');
    }

    $this->render('create',array(
        'model'=>$model,
    ));
}

and my model:
public $car_type;
public function rules()
    {
            // NOTE: you should only define rules for those attributes that
            // will receive user inputs.
            return array(
     //   array('image', 'file','types'=>'jpg, gif, png', 'allowEmpty'=>true, 'on'=>'update'),
                    array('car_type', 'length', 'max'=>255),
                    // The following rule is used by search().
                    // @todo Please remove those attributes that should not be searched.
                    array('id, car_type', 'safe', 'on'=>'search'),
            );
    }

Everting goes smooth until I try to upload in controller. Everything I put as arguments in CUploadedFile::getInstance(); results in NULL;

A: The file variable must be given a rule that forces it of type file.
    array('car_type', 'file', 'types'=>'jpg, gif, png')

References
http://www.yiiframework.com/wiki/2/how-to-upload-a-file-using-a-model/


text:
Q: python3: Create a dictionary from two inequal lists with two or more None key I want to create a dictionary from two inequal lists that number of keys is two times lower than the value:
a = [1, 2]
b = ['a', 'b', 'c', 'd', 'e']

>>> dict = {1: 'a', 2: 'b', None: 'c', None: 'd', None: 'e'}
Manually creating this dictionary is possible, but I need to create it in for loop.

A: It's kind of possible, just not how you might expect.
Given
import itertools as it
import collections as ct

a = [1, 2]
b = ['a', 'b', 'c', 'd', 'e']

Code
Dict of Lists
d = {}
for x, y in it.zip_longest(a, b):
    d.setdefault(x, []).append(y)

d
# {1: ['a'], 2: ['b'], None: ['c', 'd', 'e']}

dd = ct.defaultdict(list)
for x, y in it.zip_longest(a, b):
    dd[x].append(y)

dd
# defaultdict(list, {1: ['a'], 2: ['b'], None: ['c', 'd', 'e']})

Reversed Dict
dict(it.zip_longest(b, a))
# {'a': 1, 'b': 2, 'c': None, 'd': None, 'e': None}

Details
As mentioned, keys of Python dicts are unique.  Your options are a dict of lists, or a reversed dict.
However, if you insisted on an a:b key-value pair with None keys, you could make tuples of None with some unique value, e.g. list indices:
{x if x is not None else (x, i): y for i, (x, y) in enumerate(it.zip_longest(a, b))}
# {1: 'a', 2: 'b', (None, 2): 'c', (None, 3): 'd', (None, 4): 'e'}

In your case, I would suggest a reversed dict.


text:
Q: Cache related ActiveRecord objects for collection I'd like to select a collection of ActiveRecord objects and their belongs_to related object with a single query done. I.e. after calling
products = Product.joins(:image).limit(10)

and while iterating over products, I want that product.image didn't cause another query to the DB, but it had that image attribute already populated with Image instance cached from previous query instead.
How do I construct params for select, so that it selected all attributes needed to populate related objects? Or maybe I am looking in a wrong direction and there's some other way to reduce these unnecessary queries on each iteration:
Image Load (1.0ms)  SELECT "images".* FROM "images" WHERE "images"."id" = 270783 LIMIT 1
Image Load (1.2ms)  SELECT "images".* FROM "images" WHERE "images"."id" = 121344 LIMIT 1
Image Load (1.2ms)  SELECT "images".* FROM "images" WHERE "images"."id" = 196239 LIMIT 1
Image Load (1.2ms)  SELECT "images".* FROM "images" WHERE "images"."id" = 91194 LIMIT 1
Image Load (1.2ms)  SELECT "images".* FROM "images" WHERE "images"."id" = 116278 LIMIT 1
Image Load (1.2ms)  SELECT "images".* FROM "images" WHERE "images"."id" = 117207 LIMIT 1
Image Load (0.8ms)  SELECT "images".* FROM "images" WHERE "images"."id" = 244471 LIMIT 1
Image Load (0.8ms)  SELECT "images".* FROM "images" WHERE "images"."id" = 239287 LIMIT 1
Image Load (0.8ms)  SELECT "images".* FROM "images" WHERE "images"."id" = 15124 LIMIT 1
Image Load (1.2ms)  SELECT "images".* FROM "images" WHERE "images"."id" = 186670 LIMIT 1

A: What you want is called "eager loading". And all you have to do is change your .joins(:image) to .includes(:image) to get eager loading.
products = Product.includes(:image).limit(10)

See also the Rails Guide on Eager Loading.


text:
Q: map multiple Card components with Menu I have an array of items and for each item, I want to display a Card component. Each Card has a pop up Menu. I am having trouble opening just the specific clicked Menu to open. My code opens all Menus together. Here is the code snippet.
Second issue is that I get a warning about not being able to having a button within a button. I make the Card Header clickable, and then I have the Menu. What's the correct way to implement this in order to avoid the warning?
  const [anchorEl, setAnchorEl] = useState(null)

  const handleMenuClick = (e) => {
    e.stopPropagation()
    setAnchorEl(e.currentTarget)
  }

return (
  {
    props.items.map( (k, i) => (
      <Card className={classes.root}>
      <CardActionArea onClick={(e) => handleRedirect(e)}>
        <MyMenu key={i} index={i} anchor={anchorEl} />
        <CardHeader
           action={
             <IconButton id={i} aria-label="settings" onClick={handleMenuClick}>
                <MoreVertIcon />
             </IconButton>
           }
           title={k.title}
           subheader={getTimestamp(k._id)}
         />

       </CardActionArea>

MyMenu code:
const MyMenu = ( { index, anchor } ) => {
  const [anchorEl, setAnchorEl] = useState({})

  useEffect(() => {
    //setAnchorEl({[e.target.id]: anchor})

    if (anchor!==null) {
      if (index===anchor.id)
        setAnchorEl({[index]: anchor})
    }
  }, [anchor, index])

  const handleRedirect = (e) => {
    e.stopPropagation()
    //history.push('/item/'+ id)
  }

  const handleClose = (e) => {
    e.stopPropagation()
    setAnchorEl({[e.target.id]: null})
  };

  return (
    <Menu
      id={index}
      anchorEl={anchorEl[index]}
      open={Boolean(anchorEl[index])}
      onClose={handleClose}
    >
      <MenuItem onClick={(e) => handleRedirect(e)}>Read</MenuItem>
      <MenuItem onClick={(e) => handleRedirect(e)}>Edit</MenuItem>

    </Menu>
  )
}

A: You may try below.
const handleMenuClick = (e, setter) => {
  e.stopPropagation()
  setter(e.currentTarget)
}

return (
  {
      props.items.map( (k, i) => {

      const [anchorEl, setAnchorEl] = useState(null)

     return (
     <Card className={classes.root}>
      <CardActionArea onClick={(e) => handleRedirect(e)}>
        <MyMenu key={i} index={i} anchor={anchorEl} />
        <CardHeader
           action={
             <IconButton id={i} aria-label="settings" onClick={(e) => handleMenuClick(e, setAnchorEl)}>
                <MoreVertIcon />
             </IconButton>
           }
           title={k.title}
           subheader={getTimestamp(k._id)}
         />

       </CardActionArea>
     </Card>
     )

Basically in above, you are creating separate state for each mapped object. And I tweaked the click event to accept a setState callback.
Hope it helps.

A: Thanks @Sandy. I was able to resolve this by moving this code to the parent component
  const [anchorEl, setAnchorEl] = useState({})

  const handleMenuClick = (e) => {
    e.stopPropagation()
    setAnchorEl({[e.currentTarget.id]: e.currentTarget})
  }

...

<IconButton id={i} onClick={handleMenuClick}>


text:
Q: Uniforms not working after changing them to uniform blocks I have just switched my matrix uniforms to a single block but they are no longer working even though I have not changed the way my matrices are generated, only the way they get into the shader
My uniform block is defined as such:
layout(row_major, std140) uniform MatrixBlock {
    mat4 model;
    mat4 view;
    mat4 proj;
};

I set up the uniform block as such:
void UniformBlock::generateBuffer() {
    glGenBuffers(1, &buffer);
    glBindBuffer(GL_UNIFORM_BUFFER, buffer);
    glBufferData(GL_UNIFORM_BUFFER, size(), NULL, GL_STREAM_DRAW);
    glBindBufferRange(GL_UNIFORM_BUFFER, bindingIndex, buffer, 0, size());
    glBindBuffer(GL_UNIFORM_BUFFER, 0);
}

size() just returns 192 in this case.
I then bind the the program to the binding index like so:
void UniformBlock::bind(GLuint program) const {
    GLuint index = glGetUniformBlockIndex(program, getBlockName().c_str());

    if(index != GL_INVALID_INDEX) {
        glUniformBlockBinding(program, index, getBindingIndex());
    }
}

getBlockName() returns "MatrixBlock" in this case.
then I set the matrices using:
void MatrixBlock::bindMatrix(size_t offset, const Matrix4& matrix) {
    MatrixBlock& self = instance();

    glBindBuffer(GL_UNIFORM_BUFFER, self.getBuffer());
    glBufferSubData(GL_UNIFORM_BUFFER,
                    offset * Matrix4::size(),
                    Matrix4::size(),
                    matrix.asArray()); //Matrix4 holds the actual matrix data in a std::array<float, 16>, this method gets the std::array.begin()
    glBindBuffer(GL_UNIFORM_BUFFER, 0);
}

where offset is one of these:
enum Variables {
    MODEL = 0,
    VIEW = 1,
    PROJECTION = 2,
};

MatrixBlock is just a subclass to UniformBlock (it's a singleton hence the first line)
Matrix4::size() returns sizeof(float) * 16
Now when I query the size of the uniform's variables like so:
GLuint blockIndex;
GLuint indices[3];
GLint offsets[3];
GLsizei sizes[3];

glBindBuffer(GL_UNIFORM_BUFFER, MatrixBlock::instance().getBuffer());
blockIndex = glGetUniformBlockIndex(getProgram(), "MatrixBlock");
glGetActiveUniformBlockiv(getProgram(), blockIndex, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, (GLint*)indices);
glGetActiveUniformsiv(getProgram(), 3, indices, GL_UNIFORM_OFFSET, offsets);
glGetActiveUniformsiv(getProgram(), 3, indices, GL_UNIFORM_SIZE, sizes);
glBindBuffer(GL_UNIFORM_BUFFER, 0);

I get this
Name               Index Offset Size
MatrixBlock.model  0     0      1
MatrixBlock.view   1     64     1
MatrixBlock.proj   2     128    1

Why is the size reporting as one? Should it not be 64? Is this the source of my problem?

You can view the entire source on github here: lerp@github


text:
Q: who know android Parcelable efficiency when used intent.putExtra() I have a problem.
When I send a object' infomation to another activity by intent. I used the implement parcelable Object or(serialization) or a key-value bundle that every the object's field.
Which way is best?

A: As per the discussion at http://groups.google.com/group/android-developers/browse_thread/thread/e97689f91d3b9005?fwc=2

Serializable is slow largely because
  it is super general and completely
  deals with backwards compatibility,
  object references, automatically saves
  fields for you (reflection is slooow),
  etc.  Parcelable is fast because it
  does none of these things, and thus is
  only suitable for IPC and not
  persistent storage.

A: I think that its not a question of which is better. Passing the data thought a Bundle is useful when all you want is the data, a Parcelable is useful when you want to act on the data (i.e. call methods) because it allows for a full object reconstruction.


text:
Q: Load sa saved form template into sharepoint We have an issue where we can no longer publish to Sharepoint from InfoPath. I have saved the form template and have access to Sharepoint Designer. Is it possible using sharepoint designer to say I want to use that form template as my edit and new forms?
We are currently using Sharepoint 2010 and InfoPath 2013. Publish was working up until about a month ago and the sharepoint admins are not sure how to fix it, so need alternative methods.


text:
Q: How to import html file in typescript? Is there any way to import HTML file in typescript by not using require.
import abc from '../templates/abc.html'; -- This is not loading my html

A: import * as template from "template.html";
@Component({
selector: 'home',
directives: [RouterLink],
template: template
})


text:
Q: onclick operation not working in phonegap for FileAPI

        <title>FileWriter Example</title>

        <input type="button" id="b1" value="Write" onClick="gotFileWriter()"/>

        <input type="button" id="b2" value="Read" onClick="readAsText()" />

        <input type="button" id="b3" value="Append"/>

        <input type="button" id="b4" value="Delete"/>

Write File

Basically what i want is on clicking on write button it should write the content in file and on click of read button it should retrieve and display it but what happens is because of device ready the functions gets automatically called one after other so there is no use of giving on click method on buttons but what i want is onclick of write button it should write and on click of read button it should read .
So please anybody help me to sort out my problem.  :(
Note:when i pass gotFileWriter() method(without device ready) on click for writer it gives following error.  09-30 00:16:10.112: E/Web Console(829): TypeError: Result of expression 'file' [undefined] is not an object. at file:///android_asset/www/cordova-1.9.0.js:2404

A: I solved my problem . Below is my code

    <title>FileWriter Example</title>

MCA3B

Read,Write ,Append and Delete of File

 <input type="text" placeholder="Enter Some Text" id="t1"/>

 <input type="button" id="b2" value="Write"/>

 <input type="button" id="b1" value="Read"/>

 <input type="button" id="b3" value="Append"/>

 <input type="button" id="b4" value="Delete"/>


text:
Q: Keep the pseudo element in between the background and main content I am making buttons by using the anchor tag. I want to make an effect but it is not working as expected. pseudo-element is flowing over the button and text is also being hidden as well. But I want something like this, the pseudo-element will be in between the button and background.

section {
  padding: 80px 0;
}

section.one {
  background: #76B39D;
}

.button {
  color: white;
  margin: 10px;
  font-size: 17px;
  font-weight: 700;
  letter-spacing: 1px;
  text-transform: capitalize;
}

.button-type-1 {
  border: 2px solid #fff;
  padding: 10px 33px;
  overflow: hidden;
  position: relative;
}

.button-type-1:after {
  position: absolute;
  content: '';
  width: 0px;
  height: 0px;
  background: #fff;
  left: 50%;
  top: 50%;
  transform: translateX(-50%) translateY(-50%);
  border-radius: 50%;
  z-index: 0;
  transition: all 0.4s ease;
}

.button-type-1:hover:after {
  width: 200px;
  height: 200px;
}

.button-type-1:hover,
.button-type-1:focus {
  text-decoration: none;
}

  read

I like to do, the pseudo element background will be fit to button size on hover.
And the button text will also be seen but i thing z-index is messed up somewhere or anything else.

A: z-index 1 your relative .button-type-1 and -1 the :after pseudo.
Also, make your button inline-block to prevent the :after element overflow

section {
  padding: 80px 0;
}

section.one {
  background: #76B39D;
}

.button {
  color: white;
  margin: 10px;
  font-size: 17px;
  font-weight: 700;
  letter-spacing: 1px;
  text-transform: capitalize;
}

.button-type-1 {
  border: 2px solid #fff;
  padding: 10px 33px;
  overflow: hidden;
  position: relative;
  display: inline-block;
  z-index:1;
}

.button-type-1:after {
  position: absolute;
  content: '';
  width: 0px;
  height: 0px;
  background: #fff;
  left: 50%;
  top: 50%;
  transform: translateX(-50%) translateY(-50%);
  border-radius: 50%;
  z-index: -1;
  transition: all 0.4s ease;
}

.button-type-1:hover:after {
  width: 200px;
  height: 200px;
}

.button-type-1:hover,
.button-type-1:focus {
  text-decoration: none;
  color:#000;
}

  read


text:
Q: Is it possible to verify at compile time whether the required function is called for the Factory Class in Kotlin?  class ModelFactory {

    fun setA() : ModelFactory {
       // blabla...
    }

    fun setB() : ModelFactory {
      // blabla...
    }

    fun setC() : ModelFactory {
      // blabla...
    }

    fun build() : Model {
      // An error occurs if any of setA, setB, and setC is not called.
    }
}

//example

fun successTest() {
   ModelFactory().setA().setB().setC().build() // No error occurs at compile time
}

fun failTest() {
   ModelFactory().setA().build() // An error occurs at compile time because setB and setC are not called.
}

It's awkward grammatically, but I think it's been expressed what I want.
I have already implemented an error-raising runtime for this requirement, but I want to check this at compile time.
If possible, I think I should use annotations. But is this really possible at compile time?

A: With Kotlin, I have been avoiding builder pattern, as we can always specify default values for non-mandatory fields.
If you still want to use a builder pattern, you can use Step builder pattern that expects all mandatory fields to be set before creating the object. Note that each setter method returns the reference of next setter interface. You can have multiple Step builders based on the combination of mandatory fields.
class Model(val a: String = "", val b: String = "", val c: String = "")

class StepBuilder {
    companion object {
        fun builder(): AStep = Steps()
    }

    interface AStep {
        fun setA(a: String): BStep
    }

    interface BStep {
        fun setB(b: String): CStep
    }

    interface CStep {
        fun setC(c: String): BuildStep
    }

    interface BuildStep {
        //fun setOptionalField(x: String): BuildStep
        fun build(): Model
    }

    class Steps : AStep, BStep, CStep, BuildStep {
        private lateinit var a: String
        private lateinit var b: String
        private lateinit var c: String
        override fun setA(a: String): BStep {
            this.a = a
            return this
        }

        override fun setB(b: String): CStep {
            this.b = b
            return this
        }

        override fun setC(c: String): BuildStep {
            this.c = c
            return this
        }

        override fun build() = Model(a, b , c)
    }
}

fun main() {
    // cannot build until you call all three setters
    val model = StepBuilder.builder().setA("A").setB("B").setC("C").build()
}


text:
Q: Haskell - what is wrong with this function? i am trying to compute the harmonic series with the function below. But there's a type error and not quite sure what it mean? another question, why [5..1] would gives an empty list?

sumHR = foldr (+) 0 (\x -> map (1/) [1..x])

error message:
*** Expression     : foldr (+) 0 (\x -> map (1 /) (enumFromTo x 1))
*** Term           : \x -> map (1 /) (enumFromTo x 1)
*** Type           : b -> [b]
*** Does not match : [a]

A: The error is telling you that your code is not well-typed and thus doesn't make sense.
Your function:
sumHR = foldr (+) 0 (\x -> map (1/) [1..x])

Consider:
Prelude> :t foldr
foldr :: (a -> b -> b) -> b -> [a] -> b

So for this to be true, (+) is the first argument and the types must unify (a -> b -> b and Num a => a -> a -> a unify to Num a => a -> a -> a).
The second argument is given type variable b, which we already know must be Num a => a.  This is fine, you have provided 0 as the second argument.
The third argument must agree with the type Num a => [a]. However, you have provided a second argument that is a function:
Prelude> :t (\x -> map (1/) [1..x])
(\x -> map (1/) [1..x]) :: (Enum b, Fractional b) => b -> [b]

Unless you can show the compiler how a type of (Enum b, Fractional b) => b -> [b] can be made the same as Num a => [a] then you are stuck.
You might have ment a function such as:
sumHR x = foldr (+) 0 (map (1/) [1..x])

A: Were you trying to write it point-free? If so, you need to use the composition operator . to compose foldr (+) 0 with (\x -> map (1/) [1..x]).
sumHR = foldr (+) 0 . (\x -> map (1/) [1..x])

or, point-fully:
sumHR x = foldr (+) 0 (map (1/) [1..x])

(By the way, for efficiency you'll want to use foldl' instead of foldr)

A: The previous answers have explained how to fix the function with the signature you apparently want; however this isn't really a good way to compute a sequence since for each element you request it will have to start from the beginning. A far more efficient, an in Haskell actually easier, approach is to calculate one lazy list that represents the entire sequence. So, you start with
map (1/) [1..]

(or, perhaps more readable, [ 1/i | i<-[1..] ]), then perform "each element of the result is the sum of all preceding elements in the given list". This is called a scan. Since that is always strict in one entire side of the list (rather than just two elements, like a fold) it needs to be done from the left. You can write
sumHR' :: Fractional x => [x]
sumHR' = scanl (+) 0 [ 1/i | i<-[1..] ]

or, equivalently since the infinite list is never empty,
sumHR' = scanl1 (+) [ 1/i | i<-[1..] ]


text:
Q: Independence of two intertwined random variables Let $X_0$, $X_1$ and $X_2$ be three mutually independent random variables. We define two more random variables $D_1$ and $D_2$ as follows:
$$D_1 = X_1 + X_0\\[1ex]
D_2 = X_2 + X_0$$
We're interested in arguing (in the most effective and simple way) if

*

*$D_1$ and $D_2$ are independent

*$D_1|X_0=x_0$ and $D_2|X_0=x_0$ are independent

*

*

If $D_1$ and $D_2$ are independent, it must be $\text{Cov}(D_1,D_2)=0$:
$$\text{Cov}(D_1, D_2)=\mathbb{E}[D_1 D_2]-\mathbb{E}[D_1]\mathbb{E}[D_2] =\\
=\mathbb{E}\left[ (X_1+X_0)(X_2+X_0) \right] - \mathbb{E}\left[ X_1+X_0 \right]\mathbb{E}\left[ X_2+X_0 \right]=\\
=\mathbb{E}\left[ X_1 X_2 + X_1 X_0 + X_0 X_2 + X_0^2 \right] - \mathbb{E}\left[ X_1 \right]\mathbb{E}\left[ X_2 \right] - \mathbb{E}\left[ X_1 \right]\mathbb{E}\left[ X_0 \right] - \mathbb{E}\left[ X_0 \right]\mathbb{E}\left[ X_2 \right] - \left(\mathbb{E}\left[ X_0 \right]\right)^2=\\
=\mathbb{E}\left[ X_1 \right]\mathbb{E}\left[ X_2 \right] + \mathbb{E}\left[ X_1 \right]\mathbb{E}\left[ X_0 \right] + \mathbb{E}\left[ X_0 \right]\mathbb{E}\left[ X_2 \right] + \mathbb{E}\left[ X_0^2 \right] - \mathbb{E}\left[ X_1 \right]\mathbb{E}\left[ X_2 \right] - \mathbb{E}\left[ X_1 \right]\mathbb{E}\left[ X_0 \right] - \mathbb{E}\left[ X_0 \right]\mathbb{E}\left[ X_2 \right] - \left(\mathbb{E}\left[ X_0 \right]\right)^2=\\
=\mathbb{E}\left[ X_0^2 \right] - \left(\mathbb{E}\left[ X_0 \right]\right)^2 = \text{Var}(X_0)\neq 0$$
So, if not for the trivial case in which $X_0 = \text{constant}$, $\mathbf{D_1}$ and $\mathbf{D_2}$ are not independent.
2.
One could do the same thing of point 1. all over again or just notice that this case is exactly the trivial one in which $X_0 = x_0$, a fixed "constant". So, $\mathbf{D_1|X_0 =x_0}$ and $\mathbf{D_2|X_0 =x_0}$ are independent.

MY QUESTION
Are my proofs correct? Is there a simpler way to prove the same thing or even just argument the same results in a better, more intuitive way?
A BONUS QUESTION
How can I test these theoretical results with the following example? (In order to really "see" what I found)

$X_0$ is the outcome of the fair coin "COIN": $X_0=1$ if Heads, $X_0=0$ if Tails.

$X_1$ is the outcome of the 6-faced fair dice "DICE1": $X_1=\{1,2,3,4,5,6\}$

$X_2$ is the outcome of the 6-faced fair dice "DICE2": $X_2=\{1,2,3,4,5,6\}$

SOMETHING THAT PERPLEXES ME
Intuitively and "constructively", I would say that the event to observe $D_1=k$ is independent from that of observing $D_2 = h$, infact the first is the event of obtaining $X_1 + X_0 = k$ with a throw of DICE1 and a toss of COIN while the second is the event of obtaining $X_2 + X_0 = k$ with a throw of DICE2 and a different toss of COIN: these two "procedures" are totally independent from each other and so should be their probabilities (?)
But this contradicts my analytical results, doesn't it! Why is that?

A: Simulation with your coins and dice: With a million
replications of the experiment, results should be
accurate to two places.
set.seed(220)
x.0 = sample(0:1, 10^6, rep=T)
x.1 = sample(1:6, 10^6, rep=T)
x.2 = sample(1:6, 10^6, rep=T)
d.1 = x.1 + x.0
d.2 = x.2 + x.0
cov(d.1, d.2)
[1] 0.25046        # aprx 0.25
var(x.0)
[1] 0.2500002      # aprx 0.25

Matches your result that $Cov(D_1,D_2) = Var(X_0).$
cov(d.1[x.0==1], d.2[x.0==1])
[1] 0.0005137164   # aprx 0

Matches your result that the covariance of the conditional variables $D_1 | X_0=1$ and $D_2 | X_0=1$ is $0.$
If we simulate only 5000 values of each and uniformly
jitter them (to avoid over-plotting of the discrete points), we can visualize the nature of the association
between $D_1$ and $D_2$ in your example with coins and dice.

R code for figure:
set.seed(220);  m = 5000
x0 = sample(0:1, m, rep=T)
x1 = sample(1:6, m, rep=T)
x2 = sample(1:6, m, rep=T)
j1 = runif(m, -.2,.2);  j2 = runif(m, -.2,.2)
d1 = x1 + x0 + j1;  d2 = x2 + x0 + j2
plot(d1,d2, pch=".")


text:
Q: Why a function is thread safe when all references to the shared data are serialized? From HERE I read that

A thread-safe function can be called simultaneously from multiple
  threads, even when the invocations use shared data, because all
  references to the shared data are serialized.

I know to make a segment of code thread safe we use locks so that only one thread at a time can access it. But here it says a thread safe function can be called simultaneously because all it's data are serialized. I don't understand how serializing the references can make a function thread safe? Thanks.

A:
I don't understand how serializing the references can make a function
  thread safe?

You have misunderstood slightly. Its not serializing the references but it is serializing the ACCESS to the references.
Now when you use a lock to protect a reference the access to the reference can only be used by single thread at a time. So it is serial and not parallel. And thus thread safe.

A: Serialization is sometimes synonym of locking. Read "Thread-Safety" part of this article, and you will see, that they use QMutexLocker to access global data. Why they call this serialization? Because all critical parts of the code are protected by mutex, and actually run serially, even when executed from different threads.
Sometimes Serialization in multi-threaded environment means redirecting concurrent requests to a single thread, which has incoming command queue, and handles these requests serially. The meaning is the same - concurrent requests are serialized, i.e. cannot be executed in parallel.

A: Well I'm guessing that by serializing you mean queueing, and the reason explanation you can find here:
Dead lock prevention
the general idea of thread safe is eliminating the resource sharing:

*

*by using queue to keep task in order, you can pop from queue each request, so handling of request is serialized and not parallel (that solve the question I hope).

*"hold and wait" - means that you take everything as a hole, and not request resource one by one

*"No preemption" - not always possible or effective, but it means that resource can be taken from a process that is already using it.

*"circular wait" - nice algorithm to number all resource, and always acquiring from low number to high number, causing "loop" request order, that there is always one that can complete the task and free the resource to the other.


text:
Q: Titan DB - Hbase Compatibility Issue Trying to load data into HBase 1.2.0 using Titan DB 1.0.0 but I am getting below error: I know there is a compatibility issue with HBase version http://s3.thinkaurelius.com/docs/titan/1.0.0/version-compat.html, So I added this:conf.setProperty("storage.hbase.compat-class", "com.thinkaurelius.titan.diskstorage.hbase.HBaseCompat1_0") Below is my spark-submit job:
spark-submit --jars javassist-3.12.1.GA.jar,titan-hadoop-core-1.0.0.jar,titan-hbase-1.0.0.jar,titan-hadoop-2-1.0.0.jar,blueprints-core-2.6.0.jar,gremlin-core-3.0.1-incubating.jar,guava-16.0.jar,high-scale-lib-1.1.2.jar,titan-core-1.0.0.jar,titan-factory-0.12.1.jar,/usr/iop/4.2.0.0/hbase/lib/hbase-client-1.2.0-IBM-7.jar,/usr/iop/4.2.0.0/hbase/lib/hbase-hadoop-compat-1.2.0-IBM-7.jar,/usr/iop/4.2.0.0/hbase/lib/htrace-core-3.1.0-incubating.jar,/usr/iop/4.2.0.0/hbase/lib/hbase-common-1.2.0-IBM-7.jar,/usr/iop/4.2.0.0/hbase/lib/hbase-hadoop2-compat-1.2.0-IBM-7.jar,/usr/iop/4.2.0.0/hbase/lib/hbase-protocol.jar,/usr/iop/4.2.0.0/hbase/lib/hbase-server-1.2.0-IBM-7.jar,/usr/iop/4.2.0.0/hbase/lib/metrics-core-2.2.0.jar,/usr/iop/4.2.0.0/hbase/lib/hbase-annotations-1.2.0-IBM-7.jar --class com.souvik.titandb.testTitan cscdentalstreaming-0.0.1-SNAPSHOT.jar --driver-memory 20G --executor-memory 10G --num-executors 32
Exception in thread "main" java.lang.NoClassDefFoundError: org/reflections/Configuration
    at com.thinkaurelius.titan.diskstorage.configuration.ConfigNamespace.getChild(ConfigNamespace.java:68)
    at com.thinkaurelius.titan.diskstorage.configuration.ConfigElement.parse(ConfigElement.java:180)
    at com.thinkaurelius.titan.diskstorage.configuration.BasicConfiguration.getAll(BasicConfiguration.java:80)
    at com.thinkaurelius.titan.graphdb.configuration.GraphDatabaseConfiguration.<init>(GraphDatabaseConfiguration.java:1327)
    at com.thinkaurelius.titan.core.TitanFactory.open(TitanFactory.java:94)
    at com.thinkaurelius.titan.core.TitanFactory.open(TitanFactory.java:74)
    at com.metlife.titandb.testTitan$.getTitanConnection(testTitan.scala:330)
    at com.metlife.titandb.testTitan$.createSchema(testTitan.scala:206)
    at com.metlife.titandb.testTitan$.main(testTitan.scala:340)
    at com.metlife.titandb.testTitan.main(testTitan.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:731)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:181)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:206)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:121)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
    Caused by: java.lang.ClassNotFoundException: org.reflections.Configuration
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

A: Titan is no longer maintained, so it does not support newer versions of storage backends.
JanusGraph, a fork of Titan, has compatibility with HBase 1.2 out-of-the-box, so you can try using it going forward.
GitHub hosts JanusGraph releases.


text:
Q: Python Twisted Daemon I have written a simple twisted server -
from twisted.internet import reactor
from twisted.internet import protocol
from twisted.web import server, resource
from twisted.internet import reactor

class Index(resource.Resource):
    isLeaf = True
    def render_GET(self, request):
        args = request.args
        print 'Args: %s' %(repr(args))

print 'Serving on PORT: 8090'
site = server.Site(Index())
reactor.listenTCP(8090, site)
reactor.run()

This runs fine on 127.0.0.1:8090. Note this this runs in terminal (foreground), when I make the process run in background using nohup & ctrl+Z. the server does not respond to requests. What should I do to daemonize this twisted server

A: I'd recommend looking into twistd.  That way you don't have to worry about handling any of the start up, pid file management, etc.  The documentation on their site is quite good: http://twistedmatrix.com/documents/current/core/howto/basics.html.  Also check http://twistedmatrix.com/documents/current/core/howto/tap.html for how to implement the application file.

A: As nmichael and Rakis already mentioned, after "ctrl+z" type "bg" to resume suspended process as a background job.
To run it directly as background job, type
python myserver.py &

To run it directly as background job that won't stop when you logout, type
nohup python myserver.py &

Also note that nohup, is not true deamonization. See the differences here: What's the difference between nohup and a daemon?
If you really want to deamonize your Twisted server, the best option is to use twistd as Mark Loeser answered.


text:
Q: Is there any command to make the math symbol "not equal" appear in a string? For example, to print the greek letter alpha I used \u03B1 and the output is:
α
Now I want to print not equal like this:
≠

A: you could do the following :
print(u'\u2260')

A: u"\u2260"

source: https://www.fileformat.info/info/unicode/char/2260/index.htm
You could obtain most UTF encodings with a google search :)


text:
Q: FactoryGirl - define several factories in a loop I'm trying to save some time by defining 1 factory instead of 30.
Why is this not working?
(Assuming we have a class method called :wanted_attributes)
require 'rubygems'
require 'faker'

models = %w[Model1 Model2]

models.each do |model|
    factoryname = model.downcase + "_e"

    FactoryGirl.define do
        factory factoryname.to_sym, :class => model do
            model.constantize.wanted_attributes.each do |attribute|
                attribute Faker::Name.first_name
            end
        end
    end
end

I'm getting the error:

FactoryGirl::AttributeDefinitionError: Attribute already defined:
  attribute

A: When you are looping through the wanted_attributes, you are always creating a single attribute named 'attribute'.  You need to use the send method to make sure you use the value of the attribute variable instead of the name 'attribute':
require 'rubygems'
require 'faker'

models = %w[Model1 Model2]

models.each do |model|
    factoryname = model.downcase + "_e"

    FactoryGirl.define do
        factory factoryname.to_sym, :class => model do
            model.constantize.wanted_attributes.each do |attribute|
                send(attribute.to_sym, Faker::Name.first_name) ##### Use send
            end
        end
    end
end


text:
Q: Are Backpack views still in use? Views are mentioned on the github docs here, but I do not see them detailed on the Backpack tutorial docs here.
I created a view using backpack:view Product, but am not sure where it was put.

A: I'm using laravel 7 and backpack 4.1 and you can still use this command php artisan backpack:view {Entity_name}
I've tried this and laravel create the view in resources/views folder.


text:
Q: Scala filter to filter id's from list of string not working I have a df that has id (bigint) column and i need to filter these id's from list(string)
+-----------+
|id         |
 +-----------+
|       1231|
|       1331|
|       1431|
|       1531|
|       9431|
+-----------+

val a= List(1231,5031,1331,1441,1531)

Expected o/p
+-----------+
|id         |
+-----------+
|       1431|
|       9431|
+-----------+

I tried as below
df.filter(!col(("id")).isin(a  : _*))

But it is not filtering those ids.Any idea what's wrong here?

A: You need to use udf. Check this out
scala> val df = Seq(1231,1331,1431,1531,9431).toDF("id")
df: org.apache.spark.sql.DataFrame = [id: int]

scala> val a= List(1231,5031,1331,1441,1531)
a: List[Int] = List(1231, 5031, 1331, 1441, 1531)

scala> def udf_contain(x:Int)={
     | ! a.contains(x)
     | }
udf_contain: (x: Int)Boolean

scala> val myudf_contain = udf ( udf_contain(_:Int):Boolean )
myudf_contain: org.apache.spark.sql.expressions.UserDefinedFunction = UserDefinedFunction(<function1>,BooleanType,Some(List(IntegerType)))

scala> df.filter(myudf_contain('id)).show
+----+
|  id|
+----+
|1431|
|9431|
+----+

scala>

or the RDD way.
scala> val rdd = Seq(1231,1331,1431,1531,9431).toDF("id").rdd
rdd: org.apache.spark.rdd.RDD[org.apache.spark.sql.Row] = MapPartitionsRDD[14] at rdd at <console>:32

scala> val a= List(1231,5031,1331,1441,1531)
a: List[Int] = List(1231, 5031, 1331, 1441, 1531)

scala> def udf_contain(x:Int)={
     | ! a.contains(x)
     | }
udf_contain: (x: Int)Boolean

scala>

scala> rdd.filter(x=>udf_contain(Row(x(0)).mkString.toInt)).collect
res29: Array[org.apache.spark.sql.Row] = Array([1431], [9431])


text:
Q: The functional is not continuous in respect to the strong norm Let $V=C^1([a,b])$. If $J$ is a continuous functional for the norm $\|\cdot\|_\infty$ then it is continuous for the norm $\|\cdot\|_1:= ||y||_{\infty}+||y'||_{\infty}, y \in V$. But the converse is false.
In my book there is the hint that we can use the functional of arc length, in order to show that the converse does not hold.
The functional is this: $J(y)= \int_a^b \sqrt{1+y'(x)^2} dx$, right?
I have tried the following:
If $y_1, y_2 \in V$ then:
$$|J(y_2)-J(y_1)|= \left| \int_a^b \sqrt{1+y_2'(x)^2} dx- \int_a^b \sqrt{1+y_1'(x)^2}dx  \right| = \left| \int_a^b (\sqrt{1+y_2'(x)^2}-  \sqrt{1+y_1'(x)^2}) dx  \right|= \left| \int_a^b \frac{y_2'(x)^2-y_1'(x)^2}{\sqrt{1+y_2'(x)^2}+ \sqrt{1+y_1'(x)^2}} \right| \leq\int_a^b \frac{|y_2'(x)^2-y_1'(x)^2|}{|\sqrt{1+y_2'(x)^2}+ \sqrt{1+y_1'(x)^2}|} dx \leq \frac{1}{2} ||y_2'-y_1'||_{\infty} (b-a)$$
But $||y_1-y_2||_{\infty}+||y_1'-y_2'||_{\infty}$ didn't appear. So have I done something wrong?
EDIT: So we can bound  $\frac{1}{2} ||y_2'-y_1'||_{\infty} (b-a)$ by $\frac{1}{2} (||y_2-y_1||_{\infty}+||y_2'-y_1'||_{\infty}) (b-a)$ and so we deduce that $J$ is continuous for the $||\cdot||_1$ norm, right?
But how could we show that $|J(y_2)-J(y_1)|$ is not bounded by $||y_1-y_2||_{\infty}$?
EDIT: Or do we have to consider an other counter-example?


text:
Q: Use foreign keys not just for restraints I want to create a dynamic query that will know what table I am joining based on the foreign key. Is there a way to utilize a foreign key for that? I would like to create a statement that can look up where the foreign key points and use that to select the correct values. Something that would work like this:
"SELECT t.*, f.Name FROM $table t INNER JOIN {foreign table(will change based on the table selected and the foreign key it has)} f WHERE t.key = '$key'";

A: Foreign key information can be queried from the information_schema.key_column_usage table. Remember that:

*

*A foreign key may have several columns.

*A table may have more than one foreign keys pointing to the same table.

It's kind of tricky to do that in plain SQL. You'd need to write a stored routine and generate dynamic SQL. It's also likely to kill performance. If you have (at it seems) PHP at your disposal the dynamic SQL generation probably becomes easier and you're also able to implement some caching mechanism so information_schema is not queried every time.


text:
Q: Android Junit test - Mockito class not found exception I'm attempting to build a unit test on Android which utilizes the mockito-all-1.8.5.jar file from mockito.org.  I added the jar file to my project using project > properties > project build path > add external jar. This has always worked for me on non-Android java projects.
However, when I run the unit test, I get the following class not found exception:
java.lang.ClassNotFoundException: org.mockito.runners.VerboseMockitoJUnitRunner
Above it is the following message:
Cannot load class. Make sure it is in your apk. Class name: 'org.mockito.runners.VerboseMockitoJUnitRunner'. Message: org.mockito.runners.VerboseMockitoJUnitRunner
I checked the jar and the class is there.
I also tried adding according to this link:
How to use and package a JAR file with my Android app?
But, still no luck.  How can I get this class to be found?
Edit: I'm thinking there is a problem with whatever libraries Mockitto depends on - they may not be compatible with the Dalvik jvm. See this post:
http://daverog.wordpress.com/2009/12/14/why-android-isnt-ready-for-tdd-and-how-i-tried-anyway/
1) Import a mocking framework (e.g. mockito) into the project as an additional dependency.
Any imported jars containing class files not compiled to Dalvik bytecode (most) will not work. Attempting to compile the source along with your project will not work either because most libraries will make extensive use of parts of the Java language not compatible with Dalvik: it uses its own library built on a subset of the Apache Harmony Java implementation.

A: If you are executing inside the Dalvik JVM you won't be able to use Mockito.
If you are running your unit tests on your desktop JVM however (with a testing framework like Robolectric for example) then you are good to go. I am combining the two on my Android projects at present, to good effect.