text:
Q: Logrotate and Shell Script Given logfiles in a directory stamped like this:

log_from_2012_08_14-11:57:21_To_2012_09_14-11:56:12.zip
log_from_2012_10_14-11:57:21_To_2012_11_14-11:56:12.zip

And given that there are about 155450 files like this, how can I do the following in a simple or efficient way:
Use logrotate, or another tool, to make a folder for each month : mkdir $currentMont = october, for example, and put all of the October, 2012 files there, and so on, for each month.

A: It sounds like a bash script with a couple nested for loops would do the trick.
something like:
for year in $(seq -f "%02g" 0 20); do
    for month in $(seq -f "%02g" 0 12); do
        dest = "20${year}-${month}"
        mkdir "$dest"
        mv "log_from_${dest}*" "${dest}";
    done;
done;

Clearly you would need to tweak this to your needs.  If there are too many files in one directory you could run into the line glob limit in which case you will have to use find . | xargs mv to avoid that problem.


text:
Q: `nix-shell -p [package] --command [command]` I'm trying to run a command in script using nix-shell -p [package] --command [comand] and getting an error Permission denied on files, that the command needs to operate on. The command needs only read access and if I try to do nix-shell -p [package] and then run the [command] there by hand, then everything is okay, but if I try to do it through the --command [command] it gives me an error. Why is that?
Edit:
The command looks like this: nix-shell -p ormolu --command "ormolu --mode check $(find . -name '*.hs')"

A: This has nothing to do with nix-shell (or ormolu). Try this instead:
nix-shell -p ormolu --command "find . -name '*.hs' -exec ormolu --mode check {} + "

The reason you've got permission denied is that you actually passing the first output of the find command to ormolu, and trying to execute the rest of the .hs files.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Plotting estimates using ggplot2 & facet_wrap WITHOUT re-fitting models I am pretty new to ggplot2 and am looking to produce a figure with multiple scatter plots with their respective regression estimates. However I am using non-standard regression approaches (e.g quantile regression and total regression) that are not among the list of method arguments available in geom_smooth(). I have a list of fitted models and corresponding data. Below is a working example.
require(data.table); require(ggplot2)
N <- 1000 # Generate some data
DT <- NULL
models <- list() # list of of fitted models. For simplicity i am using lm in this example
for(i in 1:8){
  x <- rnorm(N)
  y <- i*x + rnorm(N)
  z <- rep(i,N)
  DT <- rbind(DT,data.table(cbind(x=x,y=y,z=z)))
  models[[i]] <- lm(y~x,DT)
}

# Traditional way to plot the data with regression estimates is to use geom_smooth
my.plot <- ggplot(DT, aes(x=x, y=y)) + geom_point() +
  facet_wrap(~ z, nrow=2, ncol=4) +
  geom_smooth(method = "lm", se=FALSE, color="red", formula = y ~ x)
my.plot

I need a way to plot the red regression estimates without fitting regression models within geom_smooth. Is there a work around that would make my separate list of fitted Models compatible with facet_wrap?

A: Because it's not clear how you'll be mapping aesthetics to variables used in your model, you'll need to calculate the values for the lines yourself and then just add them as a standard geom_line layer rather than using geom_smooth. For example
lines <- purrr::map_dfr(models, function(m) {
  xrng <- range(m$model$x)
  data.frame(x=xrng, y=predict(m, data.frame(x=xrng)))
}, .id="z")

ggplot(DT, aes(x=x, y=y)) + geom_point() +
  facet_wrap(~ z, nrow=2, ncol=4) +
  geom_line(color="red", data=lines)

Note that the slopes look a bit "off" here but this matches what you actually modeled (you used the entire DT each time). If you wanted to estimate the slopes separately in each iteration, you loop should have looked more like
for(i in 1:8){
  x <- rnorm(N)
  y <- i*x + rnorm(N)
  z <- rep(i,N)
  chunk <- data.table(x=x,y=y,z=z)
  models[[i]] <- lm(y~x,chunk)
  DT <- rbind(DT, chunk)
}


text:
Q: Is there a need to do a if(log.isDebugEnabled()) { ... } check? is there a need to do an explicit if(log.isDebugEnabled()) { ... }  check?
I mean i have seen some post mentioning that log.debug("something") does an implicit call to see if debug mode logging has been enabled, before it does the logging. Am i missing something or is there an intermediary step that is to be performed before this is used?
Thanks!
log.debug("ResultSet rs is retrieved from OracleTypes");

vs
if(log.isDebugEnabled()){
     log.debug("ResultSet rs is retrieved from OracleTypes");
}

Edit:
Did a write up on this:
http://java.sg/whether-to-do-a-isdebugenabled-checking-before-printing-out-your-log-statement/

A: The statement:
if(log.isDebugEnabled()){

Is used just for performance reasons. It's use is optional since it is called by the log method internally.
But now you ask if this check is made internally, so why should I use it?
It's very simple: if you log something as simple as this:
log.debug("ResultSet rs is retrieved from OracleTypes");

Then you don't need to do any check. If you compose a string to log using the append operator (+) like this:
log.debug("[" + System.getTimeInMillis() + "] ResultSet rs is retrieved from OracleTypes");

In this case you should check if the log is enabled or not, because if it isn't, even if the log is not made, the string composition is. And I must remind you that the use of operator "+" to concatenate strings is very inefficient.

A: The recent versions of Logger streamline this, so there's not much difference.
The biggest difference is you don't have to create the stuff to log - sometimes there's a lot of string addition going on.

A: I checked with the below code by performing the check in my code vs not performing the check. Interestingly if the check is performed in our code for a 4 log statement executed a million times it takes 400 ms extra. I am using SLF4J 1.6.6. If you can afford to loose 400 ms per million request ,you don't need the check.
    long startTime = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
        if (logger.isTraceEnabled()) {
            logger.trace(request.getUserID());
            logger.trace(request.getEntitlementResource().getResourceString());
            logger.trace(request.getEntitlementResource().getActionString());
            logger.trace(request.getContextMap());
        }
    }
    long endTime = System.currentTimeMillis();
    logger.fatal("With Check Enabled : " + (endTime - startTime) + " ms");

    startTime = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {

        logger.trace(request.getUserID());
        logger.trace(request.getEntitlementResource().getResourceString());
        logger.trace(request.getEntitlementResource().getActionString());
        logger.trace(request.getContextMap());

    }
    endTime = System.currentTimeMillis();
    logger.fatal("With Check Disabled : " + (endTime - startTime)  + " ms");

---OUTPUT---
*2016-01-07 10:49:11,501 ERROR [:http-bio-8080-exec-3] [com.citi.cmb.entitlement.service.EntitlementServiceImpl][]- With Check Enabled : 661 ms
2016-01-07 10:49:57,141 ERROR [:http-bio-8080-exec-3] [com.citi.cmb.entitlement.service.EntitlementServiceImpl][]- With Check Disabled : 1043 ms

A: I know this is old, but for anyone just finding this...
If you use SLF4J, you can avoid the isDebugEnabled() call, by using messaging formatting.
For example, instead of:
Object entry = new SomeObject();
logger.debug("The entry is " + entry + ".");

Use:
Object entry = new SomeObject();
logger.debug("The entry is {}.", entry);

The message formatting will not be evaluated unless debug is enabled.
So, for simple cases, you could avoid isDebugEnabled().
But in a case where building one of the parameters might be expensive, you would still want to use isDebugEnabled() (even with SLF4J).
For example:
if (logger.isDebugEnabled()) {
    logger.debug("Here is the SQL: {}", sqlWrapper.buildSQL());  // assume buildSQL() is an expensive operation
}

In that case, you don't want to evaluate buildSQL() unless debug is actually enabled.
With SLF4J, there's some debate over using it always vs using it selectively. It really boils down to personal preference. You may want to use everywhere, to guard against another developer (unknowingly) changing your log message to something more complex/expensive in the future.

A: The reason this is done is for performance reasons.  If checking this first, the log.debug(... statement shouldn't be evaluated.
It is indeed functionally the same.


text:
Q: CSS3 Scale Animation Keyframes having a few issues using css3 animation scale, opacity and other things work but cant seem to get scale to work.
snippet:

    #treeLeaves {
        background: url(https://i.pinimg.com/originals/72/c0/8e/72c08eefa235ae1c8aa72caa71eeba39.jpg);
        background-repeat:no-repeat;
        width:100%;
        height:375px;
        z-index:5;
        position:absolute;
        bottom:140px;
        left:0px;
    }

    @keyframe leaves {
        0% {
            transform: scale(1.0);
            -webkit-transform: scale(1.0);
        }
        100% {
            transform: scale(2.0);
            -webkit-transform: scale(2.0);
        }
    }

    #treeLeaves {
        animation: leaves 5s ease-in-out infinite alternate;
        -webkit-animation: leaves 5s ease-in-out infinite alternate;
    }

basically its 1 img that i wanted to scale up and down constantly over time.
only using webkit because it only needs to work in chrome.
thanks.

A: I think you forgot the 's' in keyframes.
try @keyframes and @-webkit-keyframes.

A: You just missed s in keyframes keyword.
@keyframes leaves {
    0% {
        transform: scale(1.0);
    }
    100% {
        transform: scale(2.0);
    }
}

Working demo


text:
Q: Ubuntu 14.04.1 LTS and OpenSSL Does Ubuntu Ubuntu 14.04.1 LTS have any OpenSSL vulnerabilities in connection with the Heartbleed bug?
I downloaded the ISO today and I am installing it and I would like to know if there are any existing vulnerabilities.

A: As long as you perform the needed updates, Ubuntu 14.04 does not exhibit the Heartbleed bug.
If you get the latest ISO, 14.04.1, you definitely have the latest versions of the packages and are OK with regards to Heartbleed.


text:
Q: pandas AND of two negation conditions gives weird result I am tryin to apply  AND of two negation conditions on a dataframe, that gives weird result:
import pandas as pd
df = pd.DataFrame([{'name':'John', 'gneder':None, 'gneder1':None, 'gneder2':'M3'},{'name':'Jack', 'gneder':'Unclassified', 'gneder1':'M2', 'gneder2':None},{'name':'Jessy', 'gneder':None, 'gneder1':'F2', 'gneder2':None}])
df

src_col = 'gneder'
target_col = 'GENDER'
df[target_col] = ""

df.loc[ df[src_col] != 'Unclassified' ]

name    gneder  gneder1 gneder2 GENDER
0   John    None    None    M3
2   Jessy   None    F2  None

df.loc[ ~df[src_col].isnull()]

    name    gneder  gneder1 gneder2 GENDER
1   Jack    Unclassified    M2  None

df.loc[  ((~df[src_col].isnull()) & df[src_col] != 'Unclassified')]

name    gneder  gneder1 gneder2 GENDER
0   John    None    None    M3
1   Jack    Unclassified    M2  None
2   Jessy   None    F2  None

I am expecting the final filter to return no records, but it return all records

A: There is parantheses mismatch - first was removed because not compare by operators like ==, !=, >... and for second condition was added because priority of operations:
df = df.loc[ ~df[src_col].isnull() & (df[src_col] != 'Unclassified')]
#df = df.loc[ df[src_col].notna() & (df[src_col] != 'Unclassified')]
print (df)
Empty DataFrame
Columns: [name, gneder, gneder1, gneder2, GENDER]
Index: []


text:
Q: Normal estimates curvature field coming back NAN I am computing the surface normals for an organized point cloud as follows:
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud = create_point_cloud_ptr(cap_depth, cap_rgb);

// estimate normals
pcl::PointCloud<pcl::Normal>::Ptr normals (new pcl::PointCloud<pcl::Normal>);

pcl::IntegralImageNormalEstimation<pcl::PointXYZRGB, pcl::Normal> ne;
ne.setNormalEstimationMethod (ne.AVERAGE_3D_GRADIENT);
ne.setMaxDepthChangeFactor(15);
ne.setNormalSmoothingSize(10.0f);
ne.setInputCloud(cloud);
ne.compute(*normals);

When I iterate through the normals, the curvature field is set to NAN for all points. Am I doing something wrong in the calculation?

A: Turns out the AVERAGE_3D_GRADIENT method does not compute surface curvature, need to use ne.COVARIANCE_MATRIX


text:
Q: Goroutine already started in Go web server from request but client disconnects, is it possible for a web server to close that particular goroutine? Whenever a web request comes in from the client it would spawn a goroutine to handle each. If the client just happen to disconnect from the connection, is it possible for a web server to close that particular goroutine or will that goroutine find out that the client had already diconnected after it had executed all its code?

A: Other than exiting on the return from a called handler on a read or write error - the executing go routine will not automatically handle cleaning up longer running operations, but Go provides nice ways of handling this.
First, if you are not familiar with the context package - it is a powerful and idiomatic way to synchronize go routines with cancellation behavior, I highly recommend reading the blog Go Concurrency Patterns: Context.
Something like the following:
func MyServiceFunc(ctx context.Context) {
    for {
        select {
        case <-ctx.Done():
            break
        default:
            //do work
        }
    }
}

func MyRequestHandler(res http.ResponseWriter, req *http.Request) {
    MyServiceFunc(req.Context())
   //write response...
}

Or you could use the CloseNotifier interface of which a http.ResponseWriter also implements, you could do something like the following simple example:
func MyServiceFunc(notifier <-chan bool) {
    for {
        select {
        case <-notifier:
            break
        default:
            //do work
        }
    }
}

func MyRequestHandler(res http.ResponseWriter, req *http.Request) {
    notifier := res.(http.CloseNotifier).CloseNotify()
    MyServiceFunc(notifier)
    //write response...
}

Or, and simple example using combining both approaches:
func MyRequestHandler(res http.ResponseWriter, req *http.Request) {

    notifier := res.(http.CloseNotifier).CloseNotify()
    ctx, cancel := context.WithCancel(req.Context())

    go func(closer <-chan bool) {
        <-closer //the notifer blocks until the send
        cancel() //explicitly cancel all go routines
    }(notifier)

    go MyServiceFunc(ctx)
    MyOtherServiceFunc(ctx)
    //write response...
}

A: The per-connection goroutine exits on return from the handler if there's an error reading or writing to the connection, or when request or response headers indicate that the connection should be closed.
Handlers can check for a closed connection using the Context returned from Request.Context().


text:
Q: message attachment sent by office365 rest api is not shown in inbox I am using office 365 rest api and sending attachment, when I am sending attachment to any email address other than office 365 mail like(gmail.com, yahoo.com etc) then attachment seen in inbox, but in case of office 365 mail it showing only content.
Thanks,
Shankar

A: I am able to send attachment to both office 365 and yahoo, gmail etc by using rest api of office 365.
Attachment array need to created as follows
     <?php
      $k=0;
         $attchmentArr=array();
        foreach($requestjson['name'] as $file){
                $attchmentArr[]=array(
                     "@odata.type"=> "#Microsoft.OutlookServices.FileAttachment",
                    "Name"=> $file,
                    "ContentBytes"=> $requestjson['content_bytes'][$k],
                );
          $k++;
        }
?>

You need to create an array like following.
<?php
 $post_data=array(
             "Message"=>array(
                 "Subject"=>$requestjson['subject'],
                 "Body"=>array(
                     'ContentType'=>'HTML',
                     'Content'=> $requestjson['message'],
                 ),
                 "From"=>array(
                     "EmailAddress"=>array(
                         'Name'=>$fromName[0],
                         'Address'=>CARE_ACOCUNT
                     )
                 ),
                "ToRecipients"=>array(
                      array(
                          "EmailAddress"=>array(
                                        'Name'=>$toName[0],
                                        "Address"=>$requestjson['to_address']
                                    )
                            )
                  ),
                  "Attachments"=>$attchmentArr,
             ),
            "SaveToSentItems"=> "true"
         );
?>

then use curl to send mail
<?php
$url="https://outlook.office365.com/api/beta/me/sendmail";
  $post_data = json_encode($post_data);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL,$url);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
            curl_setopt($ch, CURLOPT_USERPWD, CARE_ACOCUNT . ':' . CARE_PASS);
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $post_header);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($ch);
            $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $response = json_decode($response, true);

            $status_arr=array(200,201,202,204);
            curl_close($ch);
            if(in_array($status,$status_arr)){
                return $response;
            } else {
                return 'error';
            }


text:
Q: Getting two different views in single RecyclerView using Firebase in Android I have developed an application in which there are two posts

*

*The image post using picasso

*the Video post using Youtube Api.

I have implemented both by using RecyclerView and Firebase recyclerAdapter but the problem is that I dont know that how to differentiate both views, if I use Video view using Youtube Api it gets attached with image view and also gets copy to all of items in recyclerView, and then there is only one video playing in all items. What I want is that if I want to show an image then the item only gets image and if I want to show video then the reyclerView item only gets video without repetition. Like Instagram. I have searched many forums but did not got any help from them. please help. I am using Firebase as my database and ViewHolders are according to that.
Class file for Image and Video posts:
FirebaseRecyclerAdapter <post, postViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<post, postViewHolder>(
    post.class,
    R.layout.post_row_recycle_home,
    postViewHolder.class,
    mDatabaseReference
) {
    @Override
    protected void populateViewHolder(postViewHolder viewHolder, post model, int position) {
        viewHolder.setimage(getApplicationContext(), model.getImage());
        viewHolder.setYoutube(model.getYoutube());
    }
};

mrecyclerView.setAdapter(firebaseRecyclerAdapter);

Holder:
public static class postViewHolder extends RecyclerViewPager.ViewHolder{

    View mView;

    public postViewHolder(View itemView) {
        super(itemView);
        mView = itemView;
    }

    public void setYoutube(final String youtube){
        final YouTubePlayerView youPlay = (YouTubePlayerView) mView.findViewById(R.id.youtuber);
        youPlay.initialize("SOME KEY",
            new YouTubePlayer.OnInitializedListener() {
                @Override
                public void onInitializationSuccess(YouTubePlayer.Provider provider,
                                                    YouTubePlayer youTubePlayer, boolean b) {

                    youTubePlayer.cueVideo(youtube);
                }
                @Override
                public void onInitializationFailure(YouTubePlayer.Provider provider,
                                                    YouTubeInitializationResult youTubeInitializationResult) {

            }
        });
    }

    public void setimage(final Context ctx, final String image){
        final ImageView post_image = (ImageView)mView.findViewById(R.id.post_image);

         Picasso.with(ctx).load(image)
            .networkPolicy(NetworkPolicy.OFFLINE).into(post_image, new Callback() {

            @Override
            public void onSuccess() {
            }
            @Override
            public void onError() {
                Picasso.with(ctx).load(image).into(post_image);
            }
        });
    }
}

Example screenshot:

A: Simply using viewType will solve this issue for you.
First of all FirebaseRecyclerAdapter should include RecyclerView.ViewHolder.class instead of postViewHolder.class
Then you switch between type in each child assume image carry type 1 and video carry type 2 and you achieve that in onCreateViewHolder between you handle that in getItemViewType
Code should be look like:-
protected void populateViewHolder(final RecyclerView.ViewHolder viewHolder, final post model,
                                          final int position) {
            switch (model.getType()) {
                case 1:
                    populateType1((ViewHolder1) viewHolder, model, position);
                    break;
                case 2:
                    populateType2((ViewHolder2) viewHolder, model, position);
                    break;
            }

onCreatView should be look like:-
 @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            switch (viewType) {
                case 1:
                    View modelType1 = LayoutInflater.from(parent.getContext())
                            .inflate(R.layout.item_type1, parent, false);
                    return new ViewHolder1(modelType1);
                case 2:
                    View modelType2 = LayoutInflater.from(parent.getContext())
                            .inflate(R.layout.item_type2, parent, false);
                    return new ViewHolder2(modelType2);
            }
            return super.onCreateViewHolder(parent, viewType);
        }

And getItemViewType
@Override
        public int getItemViewType(int position) {
            post model = getItem(position);
            switch (model.getType()) {
                case 1:
                    return model1;
                case 2:
                    return model2;

            }
            return super.getItemViewType(position);
        }

A: You can decide which type of view to show with the adapters getItemViewType method. Inside firebaseRecyclerAdapter add the following:
private static final int TYPE_YOUTUBE = 1111;
private static final int TYPE_IMAGE = 2222;

@Override
public int getItemViewType(int position) {
    //note: classes should start with uppercase
    Post model = getItem(position);
    if (model.isYoutube()) { //note: you'll have to define this method
        return TYPE_YOUTUBE;
    } else {
        return TYPE_IMAGE;
    }
}

Then inside onCreateViewHolder you check which type to create:
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    RecyclerView.ViewHolder holder;
    switch (viewType) {
        case TYPE_YOUTUBE:
                //note: save an inflater when you construct the adapter
                return new YtViewHolder(inflater.inflate(R.layout.item_youtube, parent, false));
        case TYPE_IMAGE:
                return new ImgViewHolder(inflater.inflate(R.layout.item_image, parent, false));
        }

    }

Separate your VH models:
public abstract class PostViewHolder extends RecyclerView.ViewHolder { //note: extends changed
    public abstract void bind(final String input){
}

public static class YtViewHolder extends PostViewHolder { //note: extends changed

    private YouTubePlayerView mView;

    public YtViewHolder(View itemView) {
        super(itemView);
        mView = (YouTubePlayerView) itemView.findViewById(R.id.youtuber);
    }

    public void bind(final String youtube){
        mView.initialize("SOME KEY",
            new YouTubePlayer.OnInitializedListener() {
                @Override
                public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
                    youTubePlayer.cueVideo(youtube);
                }

                @Override
                public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {

                }
        });
    }

}

public static class ImgViewHolder extends PostViewHolder {

    private ImageView mView;

    public ImageView(View itemView) {
        super(itemView);
        mView = (ImageView) itemView.findViewById(R.id.post_image);
    }

    public void bind(final String image){
        Picasso.with(mView.getContext()).load(image).networkPolicy(NetworkPolicy.OFFLINE).into(mView, new Callback() {

            @Override
            public void onSuccess() {
            }
            @Override
            public void onError() {
                Picasso.with(ctx).load(image).into(mView);
            }
        });
    }

}

Your populate method can then be simplified as follows:
@Override
protected void populateViewHolder(PostViewHolder viewHolder, post model, int position) {
    viewHolder.bind(model.isYoutube()? model.getYoutube() : model.getImage());
}

Different Items:

then there is only one video playing in all items

This is a bit concerning. If I understand correctly every single item in the list has the same image and video. This probably means you are returning the same model to every position. Make sure that if you implement getItem you return a different item for each position (the Firebase adapter will do this by default). Also make sure that model.getYoutube etc. are not returning static data.

A: viewHolders with two views
public class MultiViewAdapter extends RecyclerView.Adapter {

private ArrayList dataSet;
Context mContext;
int total_types;

/*
   Image TypeViewHolder
 */
public class ImageTypeViewHolder extends RecyclerView.ViewHolder {

    ImageView img;
    public ImageTypeViewHolder(View itemView) {
        super(itemView);
        this.img = (ImageView) itemView.findViewById(R.id.imageview);

    }
}

/*
    Youtube View Holder
 */
public  class YoutubeTypeViewHolder extends RecyclerView.ViewHolder {

    public YoutubeTypeViewHolder(View itemView) {
        super(itemView);

        // add

    }
}

public MultiViewAdapter(ArrayList data, Context context) {
    this.dataSet = data;
    this.mContext = context;
    total_types = dataSet.size();
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view;
    switch (viewType) {

        case typeImage:
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.type_image, parent, false);
            return new ImageTypeViewHolder(view);

        case typeVideo:
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.type_video, parent, false);
            return new YoutubeTypeViewHolder(view);
    }
    return null;
}

@Override
public int getItemViewType(int position) {

    switch (position) {

        case 0:
            return typeImage;
        case 1:
            return typeVideo;

    }
}

@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int listPosition) {

    Post object = getItem(listPosition);

    if (object != null) {
        switch (object.type) {

            case typeImage:

                ((ImageTypeViewHolder) holder).image.setImageResource(object.data);
                break;
            case typeVideo:
                // ADD video
                break;

        }
    }
}

   @Override
   public int getItemCount() {
       return dataSet.size();
   }
}


text:
Q: Start mysql server from java How to start and stop mysql server from java(OSX) programtically?Can someone provide a code snippet for this.
Non of the code snippets given in stackoverflow are working properly.

A: I'm sorry, I can't comment because I do not have enough reputation.
What you could try is running the start script from the command line. That means getting the runtime and setting the command tou need. i.e,
Runtime.getRuntime.exec("sudo /usr/local/mysql/support-files/mysql.server start");

Another possibility would be to create a ProccesBuilder and set the params you need for the startup.
Hope this helps.


text:
Q: Integration Question - MGF I am trying to integrate this function with respect to z.
$$\frac{1}{\sqrt{2\pi}}\int_{-\infty}^{\infty}e^{-\frac{z^2}{2}(1-2s)+tz}dz$$
The answer book is telling me it should be:
$$\sqrt{\frac{2 \pi}{1-2s}}$$
If someone has any idea how that's possible that would be awesome! Thanks.
Question

A: Note that the integral is of the form:
$$\int_{-\infty}^{\infty}e^{-a\phi^2}d\phi=\sqrt{\frac{\pi}{a}}$$
And if you substitute again with $$\phi=z-\frac{t}{1-2s}$$
You'll get the integral into the required form.

A: You can refer to standard tables of gaussian integrals to get the answer. Typically when solving these types of problems you say "refer to the table of integrals for this gaussian integral". The identity you need can be found on wikipedia:
\begin{equation}
\int_{-\infty}^{\infty}e^{-ax^2+bx+c}dx=\sqrt{\frac{\pi}{a}}e^{\frac{b^2}{4a}+c}
\end{equation}
So for your integral:
\begin{equation}
\frac{1}{\sqrt{2\pi}}\int_{-\infty}^{\infty}e^{-\frac{(1-2s)}{2}z^2+tz}dx
\end{equation}
you have $a=\frac{1-2s}{2}$, $b=t$ and $c=0$.
As such your solution is:
\begin{equation}
\sqrt{\frac{1}{1-2s}}e^{\frac{t^2}{2(1-2s)}}
\end{equation}
This has the same form as the answer you provide, however, differs by a multiplicative factor. Either the book is missing this factor or there could be a mistake earlier in your math.


text:
Q: Problems installing Memcache (PECL extension) I have installed memcached fine, and now I will need to install PECL extension memcache. Im running RedHat x86_64 es5. The installation gives me this:
downloading memcache-2.2.6.tgz ...
Starting to download memcache-2.2.6.tgz (35,957 bytes)
..........done: 35,957 bytes
11 source files, building
running: phpize
Configuring for:
PHP Api Version:         20090626
Zend Module Api No:      20090626
Zend Extension Api No:   220090626
Enable memcache session handler support? [yes] :
Notice: Use of undefined constant STDIN - assumed 'STDIN' in PEAR/Frontend/CLI.php on line 304

Warning: fgets() expects parameter 1 to be resource, string given in PEAR/Frontend/CLI.php on line 304

Warning: fgets() expects parameter 1 to be resource, string given in /usr/lib/php/PEAR/Frontend/CLI.php on line 304
building in /root/tmp/pear-build-root/memcache-2.2.6
running: /root/tmp/pear/memcache/configure --enable-memcache-session=yes
checking for egrep... grep -E
checking for a sed that does not truncate output... /bin/sed
checking for cc... cc
checking for C compiler default output file name... a.out
checking whether the C compiler works... yes
checking whether we are cross compiling... no
checking for suffix of executables...
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether cc accepts -g... yes
checking for cc option to accept ANSI C... none needed
checking how to run the C preprocessor... cc -E
checking for icc... no
checking for suncc... no
checking whether cc understands -c and -o together... yes
checking for system library directory... lib
checking if compiler supports -R... no
checking if compiler supports -Wl,-rpath,... yes
checking build system type... x86_64-unknown-linux-gnu
checking host system type... x86_64-unknown-linux-gnu
checking target system type... x86_64-unknown-linux-gnu
checking for PHP prefix... /usr
checking for PHP includes... -I/usr/include/php -I/usr/include/php/main -I/usr/include/php/TSRM -I/usr/include/php/Zend -I/usr/include/php/ext -I/usr/include/php/ext/date/lib
checking for PHP extension directory... /usr/lib/php/extensions/no-debug-non-zts-20090626
checking for PHP installed headers prefix... /usr/include/php
checking if debug is enabled... no
checking if zts is enabled... no
checking for re2c... re2c
checking for re2c version... invalid
configure: WARNING: You will need re2c 0.13.4 or later if you want to regenerate PHP parsers.
checking for gawk... gawk
checking whether to enable memcache support... yes, shared
checking whether to enable memcache session handler support... yes
checking for the location of ZLIB... no
checking for the location of zlib... /usr
checking for session includes... /usr/include/php
checking for memcache session support... enabled
checking for ld used by cc... /usr/bin/ld
checking if the linker (/usr/bin/ld) is GNU ld... yes
checking for /usr/bin/ld option to reload object files... -r
checking for BSD-compatible nm... /usr/bin/nm -B
checking whether ln -s works... yes
checking how to recognize dependent libraries... pass_all
checking for ANSI C header files... yes
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for unistd.h... yes
checking dlfcn.h usability... yes
checking dlfcn.h presence... yes
checking for dlfcn.h... yes
checking the maximum length of command line arguments... 98304
checking command to parse /usr/bin/nm -B output from cc object... ok
checking for objdir... .libs
checking for ar... ar
checking for ranlib... ranlib
checking for strip... strip
checking if cc supports -fno-rtti -fno-exceptions... no
checking for cc option to produce PIC... -fPIC
checking if cc PIC flag -fPIC works... yes
checking if cc static flag -static works... yes
checking if cc supports -c -o file.o... yes
checking whether the cc linker (/usr/bin/ld -m elf_x86_64) supports shared libraries... yes
checking whether -lc should be explicitly linked in... no
checking dynamic linker characteristics... GNU/Linux ld.so
checking how to hardcode library paths into programs... immediate
checking whether stripping libraries is possible... yes
checking if libtool supports shared libraries... yes
checking whether to build shared libraries... yes
checking whether to build static libraries... no

creating libtool
appending configuration tag "CXX" to libtool
configure: creating ./config.status
config.status: creating config.h
running: make
/bin/sh /root/tmp/pear-build-root/memcache-2.2.6/libtool --mode=compile cc -I/usr/include/php -I. -I/root/tmp/pear/memcache -DPHP_ATOM_INC -I/root/tmp/pear-build-root/memcache-2.2.6/include -I/root/tmp/pear-build-root/memcache-2.2.6/main -I/root/tmp/pear/memcache -I/usr/include/php -I/usr/include/php/main -I/usr/include/php/TSRM -I/usr/include/php/Zend -I/usr/include/php/ext -I/usr/include/php/ext/date/lib  -DHAVE_CONFIG_H  -g -O2   -c /root/tmp/pear/memcache/memcache.c -o memcache.lo
mkdir .libs
 cc -I/usr/include/php -I. -I/root/tmp/pear/memcache -DPHP_ATOM_INC -I/root/tmp/pear-build-root/memcache-2.2.6/include -I/root/tmp/pear-build-root/memcache-2.2.6/main -I/root/tmp/pear/memcache -I/usr/include/php -I/usr/include/php/main -I/usr/include/php/TSRM -I/usr/include/php/Zend -I/usr/include/php/ext -I/usr/include/php/ext/date/lib -DHAVE_CONFIG_H -g -O2 -c /root/tmp/pear/memcache/memcache.c  -fPIC -DPIC -o .libs/memcache.o
/bin/sh /root/tmp/pear-build-root/memcache-2.2.6/libtool --mode=compile cc -I/usr/include/php -I. -I/root/tmp/pear/memcache -DPHP_ATOM_INC -I/root/tmp/pear-build-root/memcache-2.2.6/include -I/root/tmp/pear-build-root/memcache-2.2.6/main -I/root/tmp/pear/memcache -I/usr/include/php -I/usr/include/php/main -I/usr/include/php/TSRM -I/usr/include/php/Zend -I/usr/include/php/ext -I/usr/include/php/ext/date/lib  -DHAVE_CONFIG_H  -g -O2   -c /root/tmp/pear/memcache/memcache_queue.c -o memcache_queue.lo
 cc -I/usr/include/php -I. -I/root/tmp/pear/memcache -DPHP_ATOM_INC -I/root/tmp/pear-build-root/memcache-2.2.6/include -I/root/tmp/pear-build-root/memcache-2.2.6/main -I/root/tmp/pear/memcache -I/usr/include/php -I/usr/include/php/main -I/usr/include/php/TSRM -I/usr/include/php/Zend -I/usr/include/php/ext -I/usr/include/php/ext/date/lib -DHAVE_CONFIG_H -g -O2 -c /root/tmp/pear/memcache/memcache_queue.c  -fPIC -DPIC -o .libs/memcache_queue.o
/bin/sh /root/tmp/pear-build-root/memcache-2.2.6/libtool --mode=compile cc -I/usr/include/php -I. -I/root/tmp/pear/memcache -DPHP_ATOM_INC -I/root/tmp/pear-build-root/memcache-2.2.6/include -I/root/tmp/pear-build-root/memcache-2.2.6/main -I/root/tmp/pear/memcache -I/usr/include/php -I/usr/include/php/main -I/usr/include/php/TSRM -I/usr/include/php/Zend -I/usr/include/php/ext -I/usr/include/php/ext/date/lib  -DHAVE_CONFIG_H  -g -O2   -c /root/tmp/pear/memcache/memcache_standard_hash.c -o memcache_standard_hash.lo
 cc -I/usr/include/php -I. -I/root/tmp/pear/memcache -DPHP_ATOM_INC -I/root/tmp/pear-build-root/memcache-2.2.6/include -I/root/tmp/pear-build-root/memcache-2.2.6/main -I/root/tmp/pear/memcache -I/usr/include/php -I/usr/include/php/main -I/usr/include/php/TSRM -I/usr/include/php/Zend -I/usr/include/php/ext -I/usr/include/php/ext/date/lib -DHAVE_CONFIG_H -g -O2 -c /root/tmp/pear/memcache/memcache_standard_hash.c  -fPIC -DPIC -o .libs/memcache_standard_hash.o
/bin/sh /root/tmp/pear-build-root/memcache-2.2.6/libtool --mode=compile cc -I/usr/include/php -I. -I/root/tmp/pear/memcache -DPHP_ATOM_INC -I/root/tmp/pear-build-root/memcache-2.2.6/include -I/root/tmp/pear-build-root/memcache-2.2.6/main -I/root/tmp/pear/memcache -I/usr/include/php -I/usr/include/php/main -I/usr/include/php/TSRM -I/usr/include/php/Zend -I/usr/include/php/ext -I/usr/include/php/ext/date/lib  -DHAVE_CONFIG_H  -g -O2   -c /root/tmp/pear/memcache/memcache_consistent_hash.c -o memcache_consistent_hash.lo
 cc -I/usr/include/php -I. -I/root/tmp/pear/memcache -DPHP_ATOM_INC -I/root/tmp/pear-build-root/memcache-2.2.6/include -I/root/tmp/pear-build-root/memcache-2.2.6/main -I/root/tmp/pear/memcache -I/usr/include/php -I/usr/include/php/main -I/usr/include/php/TSRM -I/usr/include/php/Zend -I/usr/include/php/ext -I/usr/include/php/ext/date/lib -DHAVE_CONFIG_H -g -O2 -c /root/tmp/pear/memcache/memcache_consistent_hash.c  -fPIC -DPIC -o .libs/memcache_consistent_hash.o
/bin/sh /root/tmp/pear-build-root/memcache-2.2.6/libtool --mode=compile cc -I/usr/include/php -I. -I/root/tmp/pear/memcache -DPHP_ATOM_INC -I/root/tmp/pear-build-root/memcache-2.2.6/include -I/root/tmp/pear-build-root/memcache-2.2.6/main -I/root/tmp/pear/memcache -I/usr/include/php -I/usr/include/php/main -I/usr/include/php/TSRM -I/usr/include/php/Zend -I/usr/include/php/ext -I/usr/include/php/ext/date/lib  -DHAVE_CONFIG_H  -g -O2   -c /root/tmp/pear/memcache/memcache_session.c -o memcache_session.lo
 cc -I/usr/include/php -I. -I/root/tmp/pear/memcache -DPHP_ATOM_INC -I/root/tmp/pear-build-root/memcache-2.2.6/include -I/root/tmp/pear-build-root/memcache-2.2.6/main -I/root/tmp/pear/memcache -I/usr/include/php -I/usr/include/php/main -I/usr/include/php/TSRM -I/usr/include/php/Zend -I/usr/include/php/ext -I/usr/include/php/ext/date/lib -DHAVE_CONFIG_H -g -O2 -c /root/tmp/pear/memcache/memcache_session.c  -fPIC -DPIC -o .libs/memcache_session.o
/bin/sh /root/tmp/pear-build-root/memcache-2.2.6/libtool --mode=link cc -DPHP_ATOM_INC -I/root/tmp/pear-build-root/memcache-2.2.6/include -I/root/tmp/pear-build-root/memcache-2.2.6/main -I/root/tmp/pear/memcache -I/usr/include/php -I/usr/include/php/main -I/usr/include/php/TSRM -I/usr/include/php/Zend -I/usr/include/php/ext -I/usr/include/php/ext/date/lib  -DHAVE_CONFIG_H  -g -O2   -o memcache.la -export-dynamic -avoid-version -prefer-pic -module -rpath /root/tmp/pear-build-root/memcache-2.2.6/modules  memcache.lo memcache_queue.lo memcache_standard_hash.lo memcache_consistent_hash.lo memcache_session.lo
cc -shared  .libs/memcache.o .libs/memcache_queue.o .libs/memcache_standard_hash.o .libs/memcache_consistent_hash.o .libs/memcache_session.o   -Wl,-soname -Wl,memcache.so -o .libs/memcache.so
creating memcache.la
(cd .libs && rm -f memcache.la && ln -s ../memcache.la memcache.la)
/bin/sh /root/tmp/pear-build-root/memcache-2.2.6/libtool --mode=install cp ./memcache.la /root/tmp/pear-build-root/memcache-2.2.6/modules
cp ./.libs/memcache.so /root/tmp/pear-build-root/memcache-2.2.6/modules/memcache.so
cp ./.libs/memcache.lai /root/tmp/pear-build-root/memcache-2.2.6/modules/memcache.la
PATH="$PATH:/sbin" ldconfig -n /root/tmp/pear-build-root/memcache-2.2.6/modules
----------------------------------------------------------------------
Libraries have been installed in:
   /root/tmp/pear-build-root/memcache-2.2.6/modules

If you ever happen to want to link against installed libraries
in a given directory, LIBDIR, you must either use libtool, and
specify the full pathname of the library, or use the `-LLIBDIR'
flag during linking and do at least one of the following:
   - add LIBDIR to the `LD_LIBRARY_PATH' environment variable
     during execution
   - add LIBDIR to the `LD_RUN_PATH' environment variable
     during linking
   - use the `-Wl,--rpath -Wl,LIBDIR' linker flag
   - have your system administrator add LIBDIR to `/etc/ld.so.conf'

See any operating system documentation about shared libraries for
more information, such as the ld(1) and ld.so(8) manual pages.
----------------------------------------------------------------------

Build complete.
Don't forget to run 'make test'.

running: make INSTALL_ROOT="/root/tmp/pear-build-root/install-memcache-2.2.6" install
Installing shared extensions:     /root/tmp/pear-build-root/install-memcache-2.2.6/usr/lib/php/extensions/no-debug-non-zts-20090626/
running: find "/root/tmp/pear-build-root/install-memcache-2.2.6" | xargs ls -dils
361232   4 drwxr-xr-x 3 root root   4096 Jan 28 10:47 /root/tmp/pear-build-root/install-memcache-2.2.6
361263   4 drwxr-xr-x 3 root root   4096 Jan 28 10:47 /root/tmp/pear-build-root/install-memcache-2.2.6/usr
361264   4 drwxr-xr-x 3 root root   4096 Jan 28 10:47 /root/tmp/pear-build-root/install-memcache-2.2.6/usr/lib
361265   4 drwxr-xr-x 3 root root   4096 Jan 28 10:47 /root/tmp/pear-build-root/install-memcache-2.2.6/usr/lib/php
361266   4 drwxr-xr-x 3 root root   4096 Jan 28 10:47 /root/tmp/pear-build-root/install-memcache-2.2.6/usr/lib/php/extensions
361267   4 drwxr-xr-x 2 root root   4096 Jan 28 10:47 /root/tmp/pear-build-root/install-memcache-2.2.6/usr/lib/php/extensions/no-debug-non-zts-20090626
361262 236 -rwxr-xr-x 1 root root 235575 Jan 28 10:47 /root/tmp/pear-build-root/install-memcache-2.2.6/usr/lib/php/extensions/no-debug-non-zts-20090626/memcache.so

Build process completed successfully
Installing '/usr/lib/php/extensions/no-debug-non-zts-20090626/memcache.so'
install ok: channel://pecl.php.net/memcache-2.2.6
Extension memcache enabled in php.ini
The memcache.so object is not in /usr/local/lib/php/extensions/no-debug-non-zts-20090626

I tried as well to install this extension "memcached 1.0.2 (PHP extension for interfacing with memcached via libmemcached library)" but it failed:
downloading memcached-1.0.2.tgz ...
Starting to download memcached-1.0.2.tgz (22,724 bytes)
........done: 22,724 bytes
4 source files, building
running: phpize
Configuring for:
PHP Api Version:         20090626
Zend Module Api No:      20090626
Zend Extension Api No:   220090626
building in /root/tmp/pear-build-root/memcached-1.0.2
running: /root/tmp/pear/memcached/configure
checking for egrep... grep -E
checking for a sed that does not truncate output... /bin/sed
checking for cc... cc
checking for C compiler default output file name... a.out
checking whether the C compiler works... yes
checking whether we are cross compiling... no
checking for suffix of executables...
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether cc accepts -g... yes
checking for cc option to accept ANSI C... none needed
checking how to run the C preprocessor... cc -E
checking for icc... no
checking for suncc... no
checking whether cc understands -c and -o together... yes
checking for system library directory... lib
checking if compiler supports -R... no
checking if compiler supports -Wl,-rpath,... yes
checking build system type... x86_64-unknown-linux-gnu
checking host system type... x86_64-unknown-linux-gnu
checking target system type... x86_64-unknown-linux-gnu
checking for PHP prefix... /usr
checking for PHP includes... -I/usr/include/php -I/usr/include/php/main -I/usr/include/php/TSRM -I/usr/include/php/Zend -I/usr/include/php/ext -I/usr/include/php/ext/date/lib
checking for PHP extension directory... /usr/lib/php/extensions/no-debug-non-zts-20090626
checking for PHP installed headers prefix... /usr/include/php
checking if debug is enabled... no
checking if zts is enabled... no
checking for re2c... re2c
checking for re2c version... invalid
configure: WARNING: You will need re2c 0.13.4 or later if you want to regenerate PHP parsers.
checking for gawk... gawk
checking whether to enable memcached support... yes, shared
checking for libmemcached... yes, shared
checking whether to enable memcached session handler support... yes
checking whether to enable memcached igbinary serializer support... no
checking for ZLIB... yes, shared
checking for zlib location... /usr
checking for session includes... /usr/include/php
checking for memcached session support... enabled
checking for memcached igbinary support... disabled
checking for libmemcached location... configure: error: memcached support requires libmemcached. Use --with-libmemcached-dir=
to specify the prefix where libmemcached headers and library are located ERROR: `/root/tmp/pear/memcached/configure' failed The memcached.so object is not in /usr/local/lib/php/extensions/no-debug-non-zts-20090626

Is there a kind soul out there that can solve this puzzle?

A: Install libmemcached-devel
# yum install libmemcached-devel

A: I've just hit the same snag. If you actually look at the install log for memcache, you'll notice that it compiles and installs it in the following directory:

/usr/lib/php/extensions/no-debug-non-zts-20090626/memcache.so

Yet, Apache tries to load the extension from the following location:

/usr/local/lib/php/extensions/no-debug-non-zts-20090626/memcache.so

Seems like it is a bug with WHM. What you can do is create a link and restart Apache.
ln /usr/lib/php/extensions/no-debug-non-zts-20090626/memcache.so /usr/local/lib/php/extensions/no-debug-non-zts-20090626/memcache.so

chmod 0755 /usr/local/lib/php/extensions/no-debug-non-zts-20090626/memcache.so

/scripts/restartsrv_apache

A: To resolve the error checking for the location of zlib... configure: error: memcache support requires ZLIB. Use --with-zlib-dir=<DIR> to specify prefix where ZLIB include and library are located, run the command:
yum install zlib-devel


text:
Q: Big O confusion I'm testing out some functions I made and I am trying to figure out the time complexity.
My problem is that even after reading up on some articles on Big O I can't figure out what the following should be:

1000 loops : 15000 objects : time 6
1000 loops : 30000 objects : time 9
1000 loops : 60000 objects : time 15
1000 loops : 120000 objects : time 75

The difference between the first 2 is 3 ms, then 6 ms, and then 60, so the time doubles up with each iteration. I know this isn't O(n), and I think it's not O(log n).
When I try out different sets of data, the time doesn't always go up. For example take this sequence (ms): 11-17-26-90-78-173-300
The 78 ms looks out of place. Is this even possible?
Edit:
NVM, I'll just have to talk this over with my college tutor.
The output of time differs too much with different variables.
Thanks for those who tried to help though!

A: Big O notation is not about how long it takes exactly for an operation to complete. It is a (very rough) estimation of how various algorithms compare asymptotically with respect to changing input sizes, expressed in generic "steps". That is "how many steps does my algorithm do for an input of N elements?".
Having said this, note that in the Big O notation constants are ignored. Therefore a loop over N elements doing 100 calculations at each iteration would be 100 * N but still equal to O(N). Similarly, a loop doing 10000 calculations would still be O(N).
Hence in your example, if you have something like:
for(int i = 0; i < 1000; i++)
   for(int j = 0; j < N; j++)
      // computations

it would be 1000 * N = O(N).
Big O is just a simplified algorithm running time estimation, which basically says that if an algorithm has running time O(N) and another one has O(N^2) then the first one will eventually be faster than the second one for some value of N. This estimation of course does not take into account anything related to the underlying platform like CPU speed, caching, I/O bottlenecks, etc.

A: Assuming you can't get O(n) from theory alone, then I think you need to look over more orders of magnitude in O(n) -- at least three, preferably six or more (you will just need to experiment to see what variation in n is required).  Leave the thing running overnight if you have to.  Then plot the results logarithmically.
Basically I suspect you are looking at noise right now.

A: Without seeing your actual algorithm, I can only guess:
If you allow a constant initialisation overhead of 3ms, you end up with
1000x15,000 = (OH:3) + 3
1000x30,000 = (OH:3) + 6
1000x60,000 = (OH:3) + 12

This, to me, appears to be O(n)
The disparity in your timestamping of differing datasets could be due to any number of factors.


text:
Q: Algorithm for best-effort classification of vector Given four binary vectors which represent "classes":
[1,0,0,0,0,0,0,0,0,0]
[0,0,0,0,0,0,0,0,0,1]
[0,1,1,1,1,1,1,1,1,0]
[0,1,0,0,0,0,0,0,0,0]

What methods are available for classifying a vector of floating point values into one of these "classes"?
Basic rounding works in most cases:
round([0.8,0,0,0,0.3,0,0.1,0,0,0]) = [1 0 0 0 0 0 0 0 0 0]

But how can I handle some interference?
round([0.8,0,0,0,0.6,0,0.1,0,0,0]) != [1 0 0 0 0 1 0 0 0 0]

This second case should be a better match for 1000000000, but instead, I have lost the solution entirely as there is no clear match.
I want to use MATLAB for this task.

A: Find the SSD (sum of squared differences) of your test vector with each "class" and use the one with the least SSD.
Here's some code: I added a 0 to the end of the test vector you provided since it was only 9 digits whereas the classes had 10.
CLASSES = [1,0,0,0,0,0,0,0,0,0
           0,0,0,0,0,0,0,0,0,1
           0,1,1,1,1,1,1,1,1,0
           0,1,0,0,0,0,0,0,0,0];

TEST = [0.8,0,0,0,0.6,0,0.1,0,0,0];

% Find the difference between the TEST vector and each row in CLASSES
difference = bsxfun(@minus,CLASSES,TEST);
% Class differences
class_diff = sum(difference.^2,2);
% Store the row index of the vector with the minimum difference from TEST
[val CLASS_ID] = min(class_diff);
% Display
disp(CLASSES(CLASS_ID,:))

For illustrative purposes, difference looks like this:
 0.2    0   0   0   -0.6    0   -0.1    0   0   0
-0.8    0   0   0   -0.6    0   -0.1    0   0   1
-0.8    1   1   1    0.4    1    0.9    1   1   0
-0.8    1   0   0   -0.6    0   -0.1    0   0   0

And the distance of each class from TEST looks like this, class_diff:
 0.41
 2.01
 7.61
 2.01

And obviously, the first one is the best match since it has the least difference.

A: This is the same thing as Jacob did, only with four different distance measures:

*

*Euclidean distance

*City-block distance

*Cosine distance

*Chebychev distance

%%
CLASSES = [1,0,0,0,0,0,0,0,0,0
           0,0,0,0,0,0,0,0,0,1
           0,1,1,1,1,1,1,1,1,0
           0,1,0,0,0,0,0,0,0,0];

TEST = [0.8,0,0,0,0.6,0,0.1,0,0,0];

%%
% sqrt( sum((x-y).^2) )
euclidean = sqrt( sum(bsxfun(@minus,CLASSES,TEST).^2, 2) );

% sum( |x-y| )
cityblock = sum(abs(bsxfun(@minus,CLASSES,TEST)), 2);

% 1 - dot(x,y)/(sqrt(dot(x,x))*sqrt(dot(y,y)))
cosine = 1 - ( CLASSES*TEST' ./ (norm(TEST)*sqrt(sum(CLASSES.^2,2))) );

% max( |x-y| )
chebychev = max( abs(bsxfun(@minus,CLASSES,TEST)), [], 2 );

dist = [euclidean cityblock cosine chebychev];

%%
[minDist classIdx] = min(dist);

Pick the one you like :)

A: A simple Euclidean distance algorithm should suffice. The class with the minimum distance to the point would be your candidate.
http://en.wikipedia.org/wiki/Euclidean_distance


text:
Q: Error converting date in sql server I get this error when I run the following code:

Conversion failed when converting date and/or time from character
  string.

Declare @t date
Set @t = DATEADD(DAY, -75, GETDATE())

Select * from
(
SELECT changeField,  CONVERT(date, newValue) newDate, changeDateTime, pubId, changeType, @t today
      FROM ChangeLog
      WHERE ISDATE(newValue) = 1
) dates
where newDate < today

If I comment out where newDate < today, it works.  There should not be any conversion in the where clause.


text:
Q: dynamically dropdowns through angularjs Having one select tag in html now i want to make select tag dynamic through angularjs so that i can get drop downs from one select options and also want to give different ng-options for every new drop down created
"

  dropdown1
  <select ng-options=''></select>

"

A: To be honest, your question is for me a little unclear, but it may help you:

  {{object.name}}
  <select ng-options="object.myOptions"></select>

this in js:
function AppCtrl ($scope) {
  $scope.myObjects = {
    "Select1": {
      "name": "dropdown1",
      "myOptions": [
        "one",
        "two"
      ]
    }, ....

A:

var app =angular.module('pof', []);

  app.controller('myController2', function($scope){
      $scope.statuses = [{
        id: 1,
        name: "First Value"
    }, {
        id: 2,
        name: "Second Value"
    }, {
        id: 3,
        name: "Third Value"
    }, {
        id: 4,
        name: "Fourth Value"
    }];
    $scope.selected_status = 3;

  })

  app.directive('bsDropdown', function ($compile) {
    return {
        restrict: 'E',
        scope: {
            items: '=dropdownData',
            doSelect: '&selectVal',
            selectedItem: '=preselectedItem'
        },
        link: function (scope, element, attrs) {
            var html = '';
            switch (attrs.menuType) {
                case "button":
                    html += '
<button class="btn button-label btn-info">Action</button><button class="btn btn-info dropdown-toggle" data-toggle="dropdown"></button>';
                    break;
                default:
                    html += '
Dropdown';
                    break;
            }
            html += '

{{item.name}}

';
            element.append($compile(html)(scope));
            for (var i = 0; i < scope.items.length; i++) {
                if (scope.items[i].id === scope.selectedItem) {
                    scope.bSelectedItem = scope.items[i];
                    break;
                }
            }
            scope.selectVal = function (item) {
                switch (attrs.menuType) {
                    case "button":
                        $('button.button-label', element).html(item.name);
                        break;
                    default:
                        $('a.dropdown-toggle', element).html(' ' + item.name);
                        break;
                }
                scope.doSelect({
                    selectedVal: item.id
                });
            };
            scope.selectVal(scope.bSelectedItem);
        }
    };
});
<link href="http://st.pimg.net/cdn/libs/bootstrap/2.2/css/bootstrap.min.css" rel="stylesheet"/>

      <select ng-init="selected_status = statuses[1].id" ng-model="selected_status" ng-options="status.id as status.name for status in statuses"></select>

 Selected Value : {{selected_status}}

A: I don't know what your model looks like but maybe something like this:

  {{item.label}}
  <select ng-options="item.options"></select>

In your controller you would have an array $scope.items that contain all your dropdowns/select elements and their options.
$scope.items = [
  {'label':'Item 1','options':{"option 1.1","option 1.2"}},
  {'label':'Item 2','options':{"option 2.1","option 2.2"}}
];


text:
Q: Error: Attempted to handle event 'becameInvalid' while in state root.loaded.created.invalid I'm trying to make a form field validation system. When the focus-out event is triggered by the component, it adds a fake error. Here's my jsbin.
If you type something on the textarea and then focus out, it will add the "fake error" as expected. However if you do it again, it will raise the following error:
Error: Attempted to handle event 'becameInvalid' on <App.Book:ember418:null> while in state root.loaded.created.invalid.

I notice It worked well until I switched ember-data from 1.13.6. to 1.13.7. So if you want to see the JSBIN working without error, switch ember-data to 1.13.6.
I would like to know if I'm doing something wrong.
Thanks for helping!


text:
Q: How do you call a class (that's not an activity) in an activity class in Android Studio? I'm learning Android Studio and I decided to create a Java class and then call it in MainActivity. However, the app crashes on startup - see below. I just don't understand what the error means. Any thoughts?
MainActivity.java
   package com.example.daniel.hamblaster;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        generateText obj = new generateText();
        obj.generate();

    }
}

Java class:
package com.example.daniel.hamblaster;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class generateText extends AppCompatActivity {

    Button myButton = (Button) findViewById(R.id.myButton);

    public void generate() {
        myButton.setOnClickListener(
            new Button.OnClickListener() {
                public void onClick(View v) {
                    TextView myText = (TextView) findViewById(R.id.myText);
                    myText.setText("blablaba");
                }
            }
        );
    }
}

Error:

E/AndroidRuntime: FATAL EXCEPTION: main
                    Process: com.example.daniel.hamblaster, PID: 5560
                    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.daniel.hamblaster/com.example.daniel.hamblaster.MainActivity}:
  java.lang.NullPointerException: Attempt to invoke virtual method
  'android.view.Window$Callback android.view.Window.getCallback()' on a
  null object reference
                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                        at android.app.ActivityThread.-wrap12(ActivityThread.java)
                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                        at android.os.Handler.dispatchMessage(Handler.java:102)
                        at android.os.Looper.loop(Looper.java:154)
                        at android.app.ActivityThread.main(ActivityThread.java:6119)
                        at java.lang.reflect.Method.invoke(Native Method)
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback
  android.view.Window.getCallback()' on a null object reference
                        at android.support.v7.app.AppCompatDelegateImplBase.(AppCompatDelegateImplBase.java:120)
                        at android.support.v7.app.AppCompatDelegateImplV9.(AppCompatDelegateImplV9.java:151)
                        at android.support.v7.app.AppCompatDelegateImplV11.(AppCompatDelegateImplV11.java:31)
                        at android.support.v7.app.AppCompatDelegateImplV14.(AppCompatDelegateImplV14.java:55)
                        at android.support.v7.app.AppCompatDelegateImplV23.(AppCompatDelegateImplV23.java:33)
                        at android.support.v7.app.AppCompatDelegateImplN.(AppCompatDelegateImplN.java:33)
                        at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:201)
                        at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:185)
                        at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:525)
                        at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:193)
                        at com.example.daniel.hamblaster.generateText.(generateText.java:9)
                        at com.example.daniel.hamblaster.MainActivity.onCreate(MainActivity.java:14)
                        at android.app.Activity.performCreate(Activity.java:6679)
                        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                        at android.app.ActivityThread.-wrap12(ActivityThread.java)
                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                        at android.os.Handler.dispatchMessage(Handler.java:102)
                        at android.os.Looper.loop(Looper.java:154)
                        at android.app.ActivityThread.main(ActivityThread.java:6119)
                        at java.lang.reflect.Method.invoke(Native Method)
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
  Application terminated.

A: You are trying to make impossible stuff.
Activities are not to be created as an ordinary class.
I can see that you are starting to get a grip of what Java is. Take your time and learn Java basics before running into Android.
For short:
Activities are not to be instantiated with new Activity();
If you are trying to, please, use Intents.
Intent a = new Intent(this, ActivityB.class);
this.startActivity(a);

This is the way to open an activity from another.
And if you REALLY want to just instantiate a class, remove that extension from generateText class and just handle it just like a normal and ordinary class.
You should, as well, check some Java code standards :)
Do never create a Class with lowercase first letter.
Best of luck.

A: 1) If you are working with UI, do it in the activity you are currently in.
2) If you want to start another activity, use:
Intent intent = new Intent(ActivityA.this, ActivityB.class);
startActivity(intent);
3) If you want to execute a method of another class, let it be
public static <return-type> method() {...} in that class. This way you even do not need to initialize you class (make it static too, btw).


text:
Q: What is the meaning of "he was there"? What is the meaning of "he was there" in this sentence?

It had taken him a while to talk himself out of his compunctions about this shocking notion, but by the mid-1950 he was there.

A: It is probably visualizing his attitude (with or without compunctions about the shocking notion) as a location, and saying by mid-1950, his attitude was now in a place where he had no compunctions about the shocking notion.


text:
Q: Subquery returned more than 1 value. i have query with this problem..
any people can help me?
this is my query
select t_tarif.lama,
    t_tarif.id,
    t_tarif.kurir,
    t_tarif.id_propd,
    t_lokasi.propinsi as 'propinsi_asal',
    t_tarif.kota_asal,
    t_tarif.id_propt,
    (select
        t_lokasi.propinsi
        from t_lokasi,t_tarif
        where t_lokasi.id_prop =t_tarif.id_propt)as 'propinsi_tujuan',
    t_tarif.kota_tujuan,
    t_tarif.tarif
from t_tarif,t_lokasi
where t_lokasi.id_prop = t_tarif.id_propd

A: The problem is in this select:
(select t_lokasi.propinsi from t_lokasi,t_tarif where t_lokasi.id_prop =t_tarif.id_propt)

It can only return 1 value and it's returning more.

A possible solution is using JOIN:
select t.lama,
       t.id,
       t.kurir,
       t.id_propd,
       l.propinsi as 'propinsi_asal',
       t.kota_asal,
       t.id_propt,
       l2.propinsi as 'propinsi_tujuan',
       t.kota_tujuan,
       t.tarif
from t_tarif t
inner join t_lokasi on l.id_prop = t.id_propd
left outer join t_lokasi l2 on l2.id_prop = t.id_propt

I've used a left join to get the other clause because it seemed that's what you needed.


text:
Q: The Newton-Raphson method in Banach spaces I am not sure if this question is too easy for mathoverflow - please tell me to remove this question if it is too e before any downvotes. I have asked this on MSE (Link), but it received only a few comments and no answers.
Note: the screenshot at the bottom is where my question comes from.
This question is quite different from other versions of conditions of convergence of Newton iteration. For example, Kantorovich theorem.
I am now analysing the Newton-Raphson iteration in general Banach spaces $E,F$. Let $x_0\in E$, and let $f:B_t(x_0)\to F$ be a differentiable function. ($B$ denotes an open ball with radius $t$.) $L(E,F)$ is the set of linear mapping from $E$ to $F$.
By definition, $f$ is differentiable at $x$ with derivative $Df_x\in L(E,F)$ (which is a linear functional from $E$ to $F$) if $\exists r(h),f(x+h)=f(x)+Df_x(h)+r(h)$, where $r(h)/\|h\|\to 0$ as $h\to 0$.
To make it simple, I assume that there exist $s>0$ such that

*

*$\|f(x_0)\|\leq t/(2s)$

*If $x,y\in B_t(x_0)$ then $\|Df_x-Df_y\|\leq 1/(2s)$

*$\forall x\in B_t(x_0),\exists J_x\in L(F,E)$ such that $J_xDf_x=Df_xJ_x=I_E$ and $\|J_x\|\leq s$.

Now let's work on the iteration. Let's fix $x\in B_t(x_0)$. Set $x_n=x_{n-1}-J_x(f(x_{n-1}))$. In real analysis course, we often take $x=x_{n-1}$, but here I have to fix $x$ to be anything in $B_t(x_0)$. Just assume for a moment that $\forall x\in B_t(x_0)$. I will explain why later.
Firstly I have to show that $x_n$ converges. Now I can use the inequality
$$
\|f(a)-f(b)-T(a-b)\|\leq \|a-b\|\sup_{c\in [a,b]} \|Df_c-T\|,
$$
where $[a,b]$ is the line segment joining $a,b$, and $T\in L(E,F)$.
To use this inequality, we define $g(y)=J_x(f(y))$, so $x_n=x_{n-1}-g(x_{n-1})$, and $Dg_y=J_xDf_y$.(The reason why I cannot set $x=x_{n-1}$ is that if I do it that way, then $g(y)=J_y(f(y))$, and I cannot find the derivative of $g$ in this case.) Since $x$ is fixed, we can assume there is NO $x$ dependence in $g$. Therefore,
$$
\|x_{n+1}-x_{n}\|=\|f(x_{n})-f(x_{n-1})-(x_{n}-x_{n-1})\|\\ \leq \|x_{n}-x_{n-1}\|\sup_{c\in [x_n,x_{n-1}]} \|Dg_c-I\|\\=\|x_{n}-x_{n-1}\|\sup_{c\in [x_n,x_{n-1}]} \|J_xDf_c-J_xDf_x\|\\ \leq \|x_{n}-x_{n-1}\|\|J_x\|\|Df_c-Df_x\|\\ \leq \frac{1}{2} \|x_{n}-x_{n-1}\|.
$$
Also,
$$
\|x_1-x_0\|=\|J_x(f(x_0))\|\leq t/2
$$
The conclusion is $\|x_n-x_{n-1}\|\leq t/2^n$.
My question: is it really OK to let $x$ be anything fixed in $B_t(x_0)$? Does that really work? If it is wrong, how can I fix it?

To prove that $f(x_n)$ converges to zero, I feel that I should prove something like $\|f(x_n)\|\leq t/(2^{n+1}s)$(Suggested in a book of real analysis). I try to start by considering this:
$$
\|f(x_n)\|\leq \|Df_x\|\|x_{n+1}-x_n\|
$$
but it goes nowhere. From $\|J_x\|\leq s$ we cannot obtain an upper bound on $Df_x$.
So how can I prove $\|f(x_n)\|\leq t/(2^{n+1}s)$?

It should be clear that $x_n$ is a Cauchy sequence - but it might not converge into $B_t(x_0)$ - is that a problem?
It is a long question, so if I have made mistakes please point it out.
Please look at the following screenshot if the above is not clear.

Source of my problem: A course in mathematical analysis (screenshot)

Here is a theorem of Kantorovich which is related but not the same.

A: You don't need to fix an arbitrary $x$.
Indeed you would have a problem in that you know nothing about the derivative of the mapping $x \mapsto J_x(f(x))$: but the key is to realize that you only wanted the derivative as a way to control a difference. Using a derivative is somewhat wasteful, especially as you already have assumed something about the difference $Df_y - Df_x$. So the trick is to try to use the hypothesized difference instead of a derivative and see where this gets you.

Consider the following: let
$$ y := x - J_x \cdot f(x).\tag{0}$$
Considering $x$ as a fixed parameter, let us consider the function
$$ G(z;x) = f(z) - f(x) - Df_x\cdot (z - x) $$
Notice that
$$ G(x;x) = f(x) - f(x) - 0 = 0 $$
and for $y$ defined as in equation (0)
$$ G(y;x) = f(y) - f(x) + Df_x \cdot J_x \cdot f(x) = f(y) $$
Now apply the mean value inequality to the $z$ variable in $G(z;x)$, treating $x$ as fixed, on the segment connecting $x$ to $y$.
$$ \| G(y;x) - G(x;x) \| \leq \|y - x\| \cdot \sup_{\xi \in [x,y]} \|DG_\xi\| $$
The quantity $DG$ we evaluate explicitly as $DG_\xi = Df_\xi - Df_x$. And our computations above gives us the estimate
$$ \| f(y) \| \leq \|J_x \cdot f(x) \| \sup_{\xi \in [x,y]} \|Df_\xi - Df_x\| \tag{A} $$
Lemma Under the assumptions given in the OP concerning the function $f$ and $J_x$, if $\|x - x_0\| \leq t(1 - 2^{-k})$ and $\|f(x)\| \leq t / 2^{k+1} s$, then $y$ (as defined by formula (0)) satisfies

*

*$\|y - x_0\| \leq t(1 - 2^{-k-1})$

*$\|f(y) \| \leq t / 2^{k+2} s$
Proof:
For the first statement, notice that $\|y - x\| \leq \|J_x\| \cdot \|f(x)\| \leq t / 2^{k+1}$ since by assumption $x \in B_t(x_0)$. By triangle inequality the first claim follows, which also implies $y \in B_t(x_0)$.
By convexity of $B_t(x_0)$ we note that the entire segment $[x,y]$ lies in $B_t(x_0)$.
Therefore we can control $Df_\xi - Df_x$ in formula (A), which yields
$$ \|f(y) \| \leq \frac{1}{2s} \cdot s \cdot \|f(x)\| \leq \frac{t}{2^{k+2}s} $$
And the claims are proved.
The hypotheses of the Lemma holds for $x = x_0$ with $k = 0$. By induction it then holds for $x_n$ defined by $x_n = x_{n-1} - J_{x_{n-1}} \cdot f(x_{n-1})$.
As part of the construction clearly the sequence $x_n$ is Cauchy. In fact the construction shows that $\| \lim x_n - x_0 \| \leq t$. (If you want the inequality to be strict, you need one of the assumed inequalities in the hypotheses to also be a strict one.)


text:
Q: AddEventListener function variable scope issue in IE 11 I have a function that works fine in Chrome, but testing in IE, it cannot access the variable outside of the function:
if (cipher[i].solved == false){
    bottom.classList.add("HighlightBox");
    bottom.classList.add("bg-warning");
    bottom.addEventListener('click', function(){
        // IE cannot access cipher[i] in this function
        cipher[i].solved = true;
        hintsUsed++;
        runHint(true);
        populateAnswerKey(puzzleWord, cipher, false);
        populatePuzzleBoard(puzzleWord, cipher);

    });
}

cipher[i] is not able to be accessed by IE (though it works fine in Chrome). Is there a way to pass cipher[i] through, or another easy adjustment I can make so that IE can access that variable when it creates the event listener?
EDIT: After more testing, it seems that the issue is that IE does not retain the value of the iterator [i]. It always remains one higher than the final pass through regardless of which event is clicked. Chrome can retain the iterator's value.
EDIT2: https://www.dan-teacher.com/cryptogram/41SXLPS1 - This is the game. It works in Chrome, but fails in (my version) of IE when I click "Use Hint" and then click one of the boxes.

A: let statement in loop doesn't work as expected in IE
"let" has issues in Internet Explorer. The simple workaround was to change:
for (let i = 0, i < cipher.length; i++){
    // code
}

to
for (let k = 0, k < cipher.length; k++){
    let i = k;
    // code
}


text:
Q: Clear circles in google maps I'm trying to remove some circles from a map but isn't working as expected. Here are my code.
Function I have used to draw circles:
for (var city in citymap) {
    var circleOptions = {
      map: GoogleMap,
      radius: distance, //In meters
      strokeColor: circleColor,
      fillOpacity: 0.0,
      strokeWeight: circleWeight,
      strokeOpacity: 0.5,
      center: citymap[city].center,
      };
    // Add the circle for this city to the map.

    cityCircle[circleId] = new google.maps.Circle(circleOptions);
}

Looking at the cityCircle Array I have eight elements, from 0 to 7. I tryed to remove them using the following function grabbed here stackoverflow forum:
function RemoveOverlays(overlays) {
    for (var i = 0; i < overlays.length; i++) {
        overlays[i].setMap(null);
    }

I call the function inside of an else if loop like this:
else if  (zoom <6 ){
   if (typeof cityCircle[0] !=undefined && cityCircle[0] !=null) {
    RemoveOverlays(cityCircle)
   }
}

At the end I have just the latest drawn circle removed. What I'm doing wrong? Thanks!

Here is the entire code.
// Listeners for newly created Map
google.maps.event.addListener(GoogleMap, 'center_changed', function() {
      localStorage['CenterLat'] = GoogleMap.getCenter().lat();
      localStorage['CenterLon'] = GoogleMap.getCenter().lng();
});

google.maps.event.addListener(GoogleMap, 'zoom_changed', function() {
      localStorage['ZoomLvl']  = GoogleMap.getZoom();
        var zoom = GoogleMap.getZoom(); //gets zoom level.

        if (SiteCircles && zoom >=6) {
           for (var i=0;i<SiteCirclesDistances.length;i++) {
            for (var circleId=0; circleId < size; circleId++) {
            drawCircle(marker, SiteCirclesDistances[i], circleId); // in meters
            }
           }
        } else if  (zoom <6 ){
               if (typeof cityCircle[index] !="undefined" && cityCircle.length >0) {
                RemoveOverlays(cityCircle)
                }
            }
        });

        // Add home marker if requested
    if (SiteShow && (typeof SiteLat !==  'undefined' || typeof SiteLon !==  'undefined')) {
        for (var city in citymap) {
        var siteMarker  = new google.maps.LatLng(citymap[city].SiteLat, citymap[city].SiteLon);
    var markerImage = circleImage; //Defined on config.js

                var marker = new google.maps.Marker({
            position: siteMarker,
            map: GoogleMap,
            icon: {url:markerImage, scaledSize: new google.maps.Size(32, 32)},
            title: citymap[city].title,
            zIndex: -99999
         });
    }

function drawCircle(marker, distance, circleId) {
    if (typeof distance === 'undefined') {
        return false;

        if (!(!isNaN(parseFloat(distance)) && isFinite(distance)) || distance < 0) {
            return false;
        }
    }

    distance *= 1000.0;
    if (!Metric) {
        distance *= 1.852;
    }

//Create range circles

    for (var city in citymap) {
          var circleOptions = {
          map: GoogleMap,
      radius: distance, //In meters
      strokeColor: circleColor,
      fillOpacity: 0.0,
      strokeWeight: circleWeight,
      strokeOpacity: 0.5,
      center: citymap[city].center,
      };
    // Add the circle for this city to the map.

    cityCircle[circleId] = new google.maps.Circle(circleOptions);

  }

}

A: typeof operator convert type to String value so you should check by:
typeof cityCircle[0] != "undefined"


text:
Q: (Scheme) Find out if some of the numbers in a list add up to a certain number? I'm making a program that takes a list and a sum. If some of the numbers in the list add up to the sum, it returns true. Else, return false. It seems to be working for some cases but not for others. For example,
if I input this:
(numlist-sum '(5 9) 9)

It should return true because one of the numbers (9) equals the sum (9). But, for some reason, its returning false.
I can't figure out what the problem is. Help please?
(define (numlist-sum? ls sum)
  (if (null? ls) #t
    (if (and (null? (cdr ls)) (equal? (car ls) sum)) #t
      (if (equal? (car ls) sum) #t
          (if (equal? (cdr ls) sum) #t
              (if (equal? (apply + (car ls) (cdr ls)) sum) #t
                  #f))))))

A: I'll give you some hints for solving this problem (looks like homework). First write a procedure that generates all the possible subsets of the list (e.g., the power set of the list). For example:
(powerset '(1 2 3))
=> '(() (1) (2) (3) (1 2) (1 3) (2 3) (1 2 3))

With the above procedure in hand (and it's easy to find the algorithm, Google is your best friend), simply iterate over each of the sublists and sum its values:
(apply + '(2 3))
=> 5

If one of the sublists' sum equals the expected value, return #t. If none of the sums satisfy the expected value, return #f.
EDIT:
I forgot to mention, this is a well-known problem - it's the subset sum problem, which can be efficiently solved (at least, more efficiently than generating the power set) using dynamic programming. But I don't think that's the goal of this homework in particular.

A: Here is a solution that checks each element one by one and then recurses down the list if the first element isn't the sum.
(define (numlist-sum list sum)
  (and (not (null? list))
       (let ((head (car list)))
         (cond ((number? head)
                (or (= sum head)
                    (numlist-sum (cdr list) sum)))
               ((list? head)
                (or (= sum (apply + head))
                    (numlist-sum (cdr list) sum)))
               (else 'ill-formed-list)))))

Also, note that your code can be rewritten as:
(define (numlist-sum? ls sum)
  (or (null? ls)
      (if (and (null? (cdr ls)) (equal? (car ls) sum))
      (equal? (car ls) sum)
      (equal? (cdr ls) sum)
      (equal? (apply + (car ls) (cdr ls)) sum)))

I'd say the use of '(if pred #t else ...) is a bit awkward and hides the true logic of the code.


text:
Q: Entity Framework - change connectionstring has error with sqlite My original connection string:
<add name="mainEntities"
     connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;
                 provider=System.Data.SQLite.EF6;
                 provider connection string='data source="
  C:\Users\Nam\source\repos\WindowsFormsApp1\WindowsFormsApp1\Product.db"'"
     providerName="System.Data.EntityClient"/>

My new connection string (I edited my old connection string):
<add name="mainEntities"
     connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;
         provider=System.Data.SQLite.EF6;
         provider connection string='data source="|DataDirectory|Product.db"'"
     providerName="System.Data.EntityClient"/>

And my code in my winform is:
 var db = new mainEntities();

 if (db.FCUsers.Count() == 1)
      MessageBox.Show("ok");

When I debug my project It was like:

System.InvalidOperationException: 'No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SQLite'. Make sure the provider is registered in the 'entityFramework' section of the application config file. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.

enter image description here
I saw the way is put file.db into file debug. I has to do this But it still doesn't work. Please help me.
Thanks.


text:
Q: How to query an XML field with a date filter I have an XML field that I'm trying to query. I figured out how to return the first item, second, etc. I need to figure out how to return the item based on a date filter. A date is included in the XML field but I can't figure out the format. Here is an example of the XML field called [AMOUNT].
<X C="1" I="0">
  <E D="0Y56M0W0D" P="0" A="122039" />
  <E D="0Y10M0W0D" P="0" A="125739" />
  <E D="1000Y0M0W0D" P="1" A="131739" />
</X>

I can query to specify which item to return by using the below query.
SELECT
 cast(AMOUNT as XML).value('(/X/E)[1]/@A','varchar(10)') AS [TEST],
 cast(AMOUNT as XML).value('(/X/E)[2]/@A','varchar(10)') AS [TEST2],
 cast(AMOUNT as XML).value('(/X/E)[3]/@A','varchar(10)') AS [TEST3]
FROM MEASURE

I need help finding a way to return the [AMOUNT] that's in effect on a specific date, let's say 2016-11-01. Below is what the front end shows the data as. There's also a [STARTDATE] field and in this case it equals 2012-01-01.
DATE       | MONTH | AMOUNT |
2012-01-01 |      1|  122039|
2016-09-01 |     57|  125739|
2017-07-01 |     67|  131739|

I need help writing a query to pull the [AMOUNT]  of 125,739 for the date filter of 2016-11-01. Any help would be greatly appreciated. I'm using SQL Server 2008.

A: This seems to be the solution to the question How is this interpreted? but not yet to the actual question How should I use this in a filter?. Do you need help with this once you've understood how to read this?
DECLARE @d1 DATETIME={d'2012-01-01'};
DECLARE @d2 DATETIME=(SELECT DATEADD(MONTH,56,@d1));
DECLARE @d3 DATETIME=(SELECT DATEADD(MONTH,10,@d2));

SELECT @d1,@d2,@d3;

The string D="0Y56M0W0D" seems to point the Distance to the next date.
The string D="0Y10M0W0D" is the Distance to the following and D="1000Y0M0W0D points to I am the last, because nobody is bothering what happens in 1000 years!
UPDATE: A fully working example
Some hints

*

*The first CTE reads the XML row-wise and returnes a derived table.

*Using CHARINDEX and SUBSTRING allows to pick the numbers between the letters Y, M, W and D.

*The amount is divided by 1000 and casted to decimal.

As you are using SQL-Server 2008 you cannot use the cummulative SUM() OVER(), that's why I use a recursive CTE to traverse down your dates and add the Distance to the date of the previous row.
Try this:
DECLARE @xml XML=
N'<X C="1" I="0">
  <E D="0Y56M0W0D" P="0" A="122039" />
  <E D="0Y10M0W0D" P="0" A="125739" />
  <E D="1000Y0M0W0D" P="1" A="131739" />
</X>';

DECLARE @StartDate DATETIME={d'2012-01-01'};

--Here's the first CTE
WITH Shredded AS
(
    SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS SortNr
          ,D.Dist AS Distance
          ,e.value('@P','int') AS P
          ,CAST(e.value('@A','int') AS DECIMAL(10,4))/1000 AS Amount
          ,CAST(SUBSTRING(D.Dist,1,PosY-1) AS INT) AS Y
          ,CAST(SUBSTRING(D.Dist,PosY+1,PosM-PosY-1) AS INT) AS M
          ,CAST(SUBSTRING(D.Dist,PosM+1,PosW-PosM-1) AS INT) AS W
          ,CAST(SUBSTRING(D.Dist,PosW+1,PosD-PosW-1) AS INT) AS D
    FROM  @xml.nodes('/X/E') AS A(e)
    CROSS APPLY (SELECT e.value('@D','nvarchar(100)') AS Dist) AS D
    CROSS APPLY(SELECT CHARINDEX('Y',D.Dist) AS PosY
                      ,CHARINDEX('M',D.Dist) AS PosM
                      ,CHARINDEX('W',D.Dist) AS PosW
                      ,CHARINDEX('D',D.Dist) AS PosD
    ) AS Positions
)

--The recursive CTE
,RecCTE AS
(
    SELECT @StartDate AS ActualDate,*
    FROM Shredded
    WHERE SortNr=1

    UNION ALL

    SELECT DATEADD(YEAR,r.Y,DATEADD(MONTH,r.M,DATEADD(WEEK,r.W,DATEADD(DAY,r.D,r.ActualDate))))
          ,s.*
    FROM RecCTE AS r
    INNER JOIN Shredded AS s ON s.SortNr=r.SortNr+1
)

--And the final query
SELECT * FROM RecCTE

+-------------------------+--------+-------------+---+---------------+------+----+---+---+
| ActualDate              | SortNr | Distance    | P | Amount        | Y    | M  | W | D |
+-------------------------+--------+-------------+---+---------------+------+----+---+---+
| 2012-01-01 00:00:00.000 | 1      | 0Y56M0W0D   | 0 | 122.039000000 | 0    | 56 | 0 | 0 |
+-------------------------+--------+-------------+---+---------------+------+----+---+---+
| 2016-09-01 00:00:00.000 | 2      | 0Y10M0W0D   | 0 | 125.739000000 | 0    | 10 | 0 | 0 |
+-------------------------+--------+-------------+---+---------------+------+----+---+---+
| 2017-07-01 00:00:00.000 | 3      | 1000Y0M0W0D | 1 | 131.739000000 | 1000 | 0  | 0 | 0 |
+-------------------------+--------+-------------+---+---------------+------+----+---+---+


text:
Q: SQL to count distinct sets, reusing rows multiple times I'm trying to write a query, or set of queries to count unique sets which span multiple rows, but data in rows may need to be counted more than once.
In the following set, I want a count of the following grouped by Year
Number of unique SID, Year, Flag1  //2013=2, 2014=2
Number of unique SID, Year, Flag2  //2013=1, 2014=0
Number of unique SID, Year, Flag3  //2013=1, 2014=2

Then I want to do the same thing, grouped by year/month
Number of unique SID, Year, Month, Flag1  //2013-Jan=2, 2013-Feb=2, 2013-Mar=1, etc
Number of unique SID, Year, Month, Flag2  //2013-Jan=1, 2013-Feb=1, 2013-Mar=1, etc
Number of unique SID, Year, Month, Flag3, //2013-Jan=1, 2013-Feb=1, 2013-Mar=1, etc

Data Set
SID    Year     Month     Flag1     Flag2     Flag3
--------------------------------------------------
1      2013     Jan         Y         Y         Y
1      2013     Feb         Y         Y         Y
1      2013     Mar         Y         Y         Y
1      2014     Jan         Y                   Y
1      2014     Feb         Y
2      2013     Jan         Y
2      2013     Feb         Y
2      2014     Jan         Y                   Y
2      2014     Feb         Y                   Y

I can do this with a single query for each count, but would really like to consolidate it into one query.
My multiple counts for the year look like:
select count(*) from
( select distinct SID, Year, Flag1 from Table WHERE Year = '2013' ) as 2013Flag1

select count(*) from
( select distinct SID, Year, Flag2 from Table WHERE Year = '2013' ) as 2013Flag2

select count(*) from
( select distinct SID, Year, Flag1 from Table WHERE Year = '2014' ) as 2014Flag1

etc...
And the month counts look like:
select count(*) from
( select distinct SID, Year, Month, Flag1 from Table WHERE Year = '2013' and Month = 'Jan' ) as 2013JanFlag1

etc...
Is this easier to do with queries for each count, or can I do some type of Cartesian product I can select from?  Any ideas would be wonderful.   This is coming from an Oracle database.  I believe it's version 10g.

A:  SELECT G.SID, G.YEAR, G.MONTH, G.FLAG, COUNT(*)
 FROM (
 SELECT Y.YEAR, Y.SID, Y.MONTH, 1 AS FLAG
 (SELECT DISTINCT SID, YEAR FROM TABLE) AS Y
 JOIN TABLE AS F
   ON F.YEAR = Y.YEAR
  AND F.FLAG1 = 'Y'
 UNION ALL
 SELECT Y.YEAR, Y.SID, Y.MONTH, 2 AS FLAG
 (SELECT DISTINCT SID, YEAR FROM TABLE) AS Y
 JOIN TABLE AS F
   ON F.YEAR = Y.YEAR
  AND F.FLAG2 = 'Y'
 UNION ALL
 SELECT Y.YEAR, Y.SID, Y.MONTH, 3 AS FLAG
 (SELECT DISTINCT SID, YEAR FROM TABLE) AS Y
 JOIN TABLE AS F
   ON F.YEAR = Y.YEAR
  AND F.FLAG3 = 'Y' ) AS G
  GROUP BY G.SID, G.YEAR, G.FLAG, G.MONTH
  ORDER BY G.SID, G.YEAR, G.FLAG, G.MONTH

A: I did not get the logic regarding the flags but maybe ROLLUP or CUBE makes the query easier and faster.
Following statements are equivalent:
SELECT COUNT(DISTINCT SID), YEAR, MONTH, flag1, flag2, flag3
FROM a_table
GROUP BY flag1, flag2, flag3, ROLLUP(YEAR, MONTH);

SELECT COUNT(DISTINCT SID), YEAR, MONTH, flag1, flag2, flag3
FROM a_table
GROUP BY flag1, flag2, flag3, YEAR, MONTH
UNION ALL
SELECT COUNT(DISTINCT SID), YEAR, NULL AS MONTH, flag1, flag2, flag3
FROM a_table
GROUP BY flag1, flag2, flag3, YEAR
UNION ALL
SELECT COUNT(DISTINCT SID), NULL AS YEAR, NULL AS MONTH, flag1, flag2, flag3
FROM a_table
GROUP BY flag1, flag2, flag3;

And another example for CUBE:
SELECT COUNT(DISTINCT SID), YEAR, MONTH, flag1, flag2, flag3, GROUPING_ID(flag1, flag2, flag3) AS flag_ID
FROM a_table
GROUP BY YEAR, MONTH, CUBE(flag1, flag2, flag3)

SELECT COUNT(DISTINCT SID), YEAR, MONTH, flag1, flag2, flag3, 0 AS flag_id
FROM a_table
GROUP BY YEAR, MONTH, flag1, flag2, flag3
UNION ALL
SELECT COUNT(DISTINCT SID), YEAR, MONTH, flag1, flag2, NULL AS flag3, 1 AS flag_id
FROM a_table
GROUP BY YEAR, MONTH, flag1, flag2
UNION ALL
SELECT COUNT(DISTINCT SID), YEAR, MONTH, flag1, NULL AS flag2, flag3, 2 AS flag_id
FROM a_table
GROUP BY YEAR, MONTH, flag1, flag3
UNION ALL
SELECT COUNT(DISTINCT SID), YEAR, MONTH, flag1, NULL AS flag2, NULL AS flag3, 3 AS flag_id
FROM a_table
GROUP BY YEAR, MONTH, flag1
UNION ALL
SELECT COUNT(DISTINCT SID), YEAR, MONTH, NULL AS flag1, flag2, flag3, 4 AS flag_id
FROM a_table
GROUP BY YEAR, MONTH, flag2, flag3
UNION ALL
SELECT COUNT(DISTINCT SID), YEAR, MONTH, NULL AS flag1, flag2, NULL AS flag3, 5 AS flag_id
FROM a_table
GROUP BY YEAR, MONTH, flag2
UNION ALL
SELECT COUNT(DISTINCT SID), YEAR, MONTH, NULL AS flag1, NULL AS flag2, flag3, 6 AS flag_id
FROM a_table
GROUP BY YEAR, MONTH, flag3
UNION ALL
SELECT COUNT(DISTINCT SID), YEAR, MONTH, NULL AS flag1, NULL AS flag2, NULL AS flag3, 7 AS flag_id
FROM a_table
GROUP BY YEAR, MONTH

You can use both, ROLLUP and CUBE in one GROUP BY clause.
ROLLUP and CUBE clause documentation you find here: http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_10002.htm#SQLRF55331
Check also functions GROUPING_ID and GROUPING. This you can use for example in HAVING clause to limit the output according to your needs.


text:
Q: Get records between by range in Laravel 5.2 I have a table with fields like firstname, lastname and of course age where age value will be automatically populated since I have a function in the controller that would calculate age based on date birthday and current year.Now I want get data on a table based on a query a dynamic query, with age as the parameters
In database, I have a people table with  fields like so
name   lastname   age
john   simons     40
olivia newtin     100
sylvia gay        390

Now I want to get people who's age is from 40 to 100. Of course I am expecting john simons and olivia newtin will be the value returned.But I am getting null. How would you solve this?
controller
public function getAllPeopleByThisAge()
{
   //query to repository
    $min = 40;
    $max =  100
    $somereturn = $this->student->getAllPeopleByThisAge($min, $max);
}

Now somewhere in my repository
   public function getAllPeopleByThisAge($min,$max)
   {
      $this->people = DB::table('students')
                    ->select('students.age')
                    ->whereBetween('age',[$min, $max])
                    ->get();
   }

My databases show columns with age saved as integer.e.g 15, 20, 100 , 70.....

A: When you call select('students.age') it will return a list of user ages and then you call ->whereBetween('age',[$min, $max])->get(); of course it will return null as there is no field age on your query result of select('students.age'). Try to remove select('students.age') and leave everything after that,
DB::table('students')->whereBetween('age',[$min, $max])->get();


text:
Q: how to find out a cell that has checkbox in it in watir? I have a table with several columns and rows, in some cells there are checkboxes.
so how can i flash those cells in watir?
Is there method that returns what element is located in particular cell?

A: Without seeing sample HTML, this is a total shot-in-the-dark, but here's a possible approach.
Given this contrived HTML snippet:

<input type="checkbox" name="foo">

<input type="checkbox" name="bar">

text

You could use the checkboxes method to locate the checkboxes and then use the parent method to get the id of the cell that contains the checkbox (assuming the cell has an id):
b.checkboxes.each { |checkbox| puts checkbox.parent.id}
#=> foo
#=> bar

If you want to flash the checkboxes, this might work depending on how the page is implemented:
b.checkboxes.each { |checkbox| checkbox.flash}

Like I said, total guess.  But it's the giving season, so there you go.


text:
Q: The last statement in a 'do' block must be an expression Like it says in the title: What does The last statement in a 'do' construct must be an expression mean? I know there are other subjects similar to mine, but I still can't find my error.
Code:
import System.Environment

check_args argc args i = do
        putStrLn $ show (args !! i)
        i <- return (i + 1)
        if argc > i
                then mydisplay2 argc args i
                else return i

loop_args argc args = do
        let i = 0
        i <- check_args argc args i

main = do
        args <- getArgs
        putStrLn "The arguments are:"
        loop_args (length args) args

A: The problem is located in the loop_args function:
loop_args argc args = do
        let i = 0
        i <- check_args argc args i
It makes no sense to write i <- …, since you here define a new variable named i (that has not much to do with the i in let i = 0), and you do not use that variable at all. You can replace it with check_args argc args i and the error will go away, but likely it will still not work the way you want this to work.
But in general, the program looks imperative, whereas Haskell is a declarative language. It means that every variable (so i) is immutable, you thus can not loop by incrementing a variable. Furthermore in a declarative language, there is not much "looping", etc. The aim is not to specify how you want to do something, but what you want to do.
You likely here want to use a mapM_ :: (Foldable f, Monad m) => (a -> m b) -> f a -> m () that can move through a Foldable object, and apply the monadic function on all items:
main = do
    args <- getArgs
    putStrLn "The arguments are:"
    mapM_ putStrLn args


text:
Q: Compose keywords with Robot Let's assume that I have a Python library to manipulate blog posts:
class BlogPost(object):
    def __init__(self):
        ...
    def create_a_blog_post(self):
        ...
    def add_category(self, category):
        ...
    def add_title(self, title):
        ...

I would like to have the following test cases:
*** Test Cases ***
Create post with category
    Create a blog post with category "myCategory"
Create post with title
    Create a blog post with title "myTitle"
Create post with both
    Create a blog post with category "myCategory" and title "myTitle"

Should I create separate user keywords for having only category, only title and for both? Or is there anyway to make add any number of "modifiers" to a keyword?
Also, how would one create such keyword, if we have to pass the result of one keyword to another:
*** Keywords ***
Create a blog post with category
    Create a blog post
    Add category  <-- How do I pass the blog post I just created to "Add category"

I purposefully left out the arguments handling from my examples as it's not the point here :)

A: I would create a keyword called "create a blog post", and then pass either keyword arguments or key/value pairs depending on your preference.
Your test would then look like this:
*** Test Cases ***
Create post with category
    Create a blog post  category  myCategory

Create post with title
    Create a blog post  title  myTitle

Create post with both
    Create a blog post
    ...  category  myCategory
    ...  title     myTitle

I prefer key/value pairs over keyword arguments since it lets you line up the keys and the values as shown in the "both" example. If you prefer keyword arguments, it might look like this:
Create post with category
    Create a blog post  category=myCategory

Create post with title
    Create a blog post  title=myTitle

Create post with both
    Create a blog post
    ...  category=myCategory
    ...  title=myTitle

The implementation simply needs to iterate either over the arguments in pairs in the case of name/value pairs, or over the keyword args.

Also, how would one create such keyword, if we have to pass the result of one keyword to another:

The simplest way is to save the result of the first keyword in a variable, and then pass that variable to the next keyword.
Create another blog post
    ${post}=  Create a blog post
    Add blog post category  ${post}  thisCategory
    Add blog post category  ${post}  thatCategory

Or, a slightly more programatic approach is for Create a blog post to return an object with methods to add categories, and then you can call methods on that object with Call Method:
Create another blog post
    ${post}=  Create a blog post
    Call method  ${post}  add_category  thisCategory
    Call method  ${post}  add_category  thatCategory

    Add blog post category  ${post}  thisCategory
    Add blog post category  ${post}  thatCategory


text:
Q: Postfix Header Checks Good morning everyone, I'm trying to create a rule of changing the FROM header on sent email.
My need is to change the FROM of all the mails that come from a specific mailbox (software@domain.com) and that have in CC the mail of a specific store (store04@domain.com).
For Example the mail sent to SMTP Server will have as FROM:software@domain.com, as CC:store@domain.com and as TO: customer@company.com, the mail that will have to exit need to have  header with FROM: store@domain.com and TO:customer@company.com only.
I already tested some rules in header checks config (/etc/postfix/header_checks) but without any working results.
Thanks in advance.

A: Something like the below might work:
if /^From: software@domain.com$/
    /^From: software@domain.com$/ REPLACE From: store@domain.com
    /^CC: store@domain.com$/ IGNORE
endif

I haven't tested this and I am by no means a Postfix expert, but from my reading of http://www.postfix.org/header_checks.5.html, I think I have got all you need.

A: Can't comment to Jacobs answer but want to add that http://www.postfix.org/header_checks.5.html states

          Note: do not prepend whitespace to patterns inside if..endif.


text:
Q: How to make not showing of volume dialogue While pressing volume I want to do some actions without showing the volume dialogue. I use AudioManager to hide this dialogue. But it doesn't work. The dialogue shows up. Please help me.
@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                AudioManager     mAudioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
                     mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                                                      AudioManager.ADJUST_LOWER,
                                                      AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                 return true;
        }
        return super.onKeyDown(keyCode, event);
    }

A: The volume popup won't appear if you use mAudioManager.setStreamVolume(), although you will have to handle the increment yourself. You can get the current volume from mAudioManager.getStreamVolume(). The value must range from 0 to mAudioManager.getStreamMaxVolume().