text:
Q: How to get Length from Array Model in Typescript I am trying to get the length from Array interface. But getting error as:
error TS2339: Property 'length' does not exist on type 'ModelSubSystems'. In this case how to get the length. here is my TS code:
@Input() subsystems: ModelSubSystems;

resolve({ data: this.subsystems, totalCount: this.subsystems.length }); //error

here is my interfaces:
export interface ModelSubSystem {
    Id: number;
    Name: string;
    CreatedBy: string;
    CreatedDate: Date;
    UpdatedBy: string;
    UpdatedDate: Date;
}

export interface ModelSubSystems {
    subsystems: Array<ModelSubSystem>; //this is array!!
}

any one help me with correct approach.
Thanks in advance.

A: @Input() subsystems: ModelSubSystems this input variable will not have length because it is an interface with one property whose name is subsystems as well and is an array(the one you are trying to get length of).
The array property created in the interface can be accessed using this.subsystems.subsystems while the first subsystem here is you input of type systemsystem and the second one is the array in that interface.
If you want the subsystems input to be to be an array of ModelSubSystem,  instead of creating ModelSubSystems interface, directly declare this input as and array so that you can access its length:
@Input() subsystems: Array<ModelSubSystem>

A: Are you certain that the this.subsystems variable is initialised instead of only declared?
Typescript interface variables are undefined by default, so you will have to set them before they can be used / their methods can be called.
EDIT: as Jeff Bowman pointed out, what you actually need is this.subsystems.subsystems.length.
You could also add the length property to the interface, and have a class implement the desired behavior:
export interface IModelSubSystems {
  subsystems : Array<ModelSubSystem>;
  length : number;
}

export class ModelSubSystems implements IModelSubSystems {
  subsystems = new Array<ModelSubSystem>();
  get length() : number {
    return this.subsystems.length;
  }
}


text:
Q: How to solve the following error - An error occurred while sending the digest (undefined method `length' for true:TrueClass) I have been trying to configure a plugin from the following link - https://www.redmine.org/plugins/digest
and when i am trying to send a test mail, I am getting the following error.
undefined method `length' for true:TrueClass
This is the error in log file
Looking up projects to process...
Couldn't find all EnabledModules with 'id': (all, {:conditions=>["name = 'redmine_digest'"]}) (found 0 results, but was looking for 2)
undefined method `length' for true:TrueClass
["/home/administrator/redmine3.1/apps/redmine/htdocs/plugins/redmine_digest/app/controllers/digest_controller.rb:84:in `digest_send'", "/home/administrator/redmine3.1/apps/redmine/htdocs/plugins/redmine_digest/app/controllers/digest_controller.rb:129:in `test_email'", "/home/administrator/redmine3.1/apps/redmine/htdocs/vendor/bundle/ruby/2.0.0/gems/actionpack-4.2.4/lib/action_controller/metal/implicit_render.rb:4:in `send_action'",

digest_controller.rb file
if Rails::VERSION::MAJOR < 3
    require 'rdoc/markup/simple_markup'
    require 'rdoc/markup/simple_markup/to_html'
else
    require 'rdoc'
end
class DigestController < ApplicationController
    unloadable
layout 'admin'

def show_readme
    filename = 'README.rdoc'
    f = File.dirname(__FILE__) + '/../../' + filename
    input_string = File.open(f, 'rb').read
    if Rails::VERSION::MAJOR >=3
        h = RDoc::Markup::ToHtml.new
        instructions = h.convert(input_string)
    else
        p = SM::SimpleMarkup.new
        h = SM::ToHtml.new
        instructions = p.convert(input_string, h)
    end
    @readme = {
        :filename => filename,
        :content => instructions
    }
    respond_to do |format|
        format.html { render :template => 'settings/digest_readme.html.erb', :layout => 'admin',
        :locals => { :readme => @readme }}
    end
end

def digest_send(which, options={})
    is_session = @request.nil? && @_request.nil?
    is_session = !is_session
    if not is_session
        puts "setting request"
        @_request = ActionDispatch::Request.new(Rails.env)
    end
    if is_session
    raise_delivery_errors = ActionMailer::Base.raise_delivery_errors
    # Force ActionMailer to raise delivery errors so we can catch it
    ActionMailer::Base.raise_delivery_errors = true
    end
    begin
        case which
        when "options"
            @test = DigestMailer.digests(options)
            message = l(:notice_digests_sent)
        when "test"
            dbg "User.current: %s" % User.current
            dbg "User.current.mail: %s" % User.current.mail
            @test = DigestMailer.test(User.current)
            message = l(:notice_digest_sent_to, User.current.mail)
        when "all"
            @test = DigestMailer.digests
            message = l(:notice_digests_sent)
        else
            message "No case found for '%s'." % which
        end
        if @test.nil? #or @test.empty?
            message += "
%s
" % "There was no resulting email."
        else
            message += "
%d %s processed.
%s
" % [
                @test.length,
                @test.length == 1 ? "project was" : "projects were",
                @test.join("
")
            ]
        end
        dbg message
        if is_session
            flash[:notice] = message
        end
    rescue Exception => e
        dbg e.message
        dbg e.backtrace
        if Rails::VERSION::MAJOR >= 3
            logger.error("%s: " % e.message) unless logger.nil?
        else
            logger.error e.message, e.backtrace unless logger.nil?
        end
        flash[:error] = l(:notice_digest_error, e.message) unless session.nil?
        if is_session
            flash[:error] = l(:notice_digest_error, e.message)
        else
            puts "Exception occurred: %s" % e.message
        end
    end
    if is_session
        ActionMailer::Base.raise_delivery_errors = raise_delivery_errors
        redirect_to :controller => 'settings', :action => 'plugin', :id => 'redmine_digest'
    else
        puts "A session was not found."
    end
end

def send_digest(options={})
    dbg "Preparing to send digest..."
    dbg options.inspect
    digest_send("options", options)
end

def send_all
    dbg "Preparing to send digest for all projects."
    digest_send "all"
end

def test_email
    dbg "Preparing to send test digest."
    digest_send "test"
end

def dbg(message)
    if Setting.plugin_redmine_digest[:debugging_messages]
        puts message
        logger.info(message)
    else
        puts "debugging_messages: %s" % Setting.plugin_redmine_digest[:debugging_messages]
        logger.info("debugging_messages: %s" % Setting.plugin_redmine_digest[:debugging_messages])
    end
end

def self.logger
    if Rails::VERSION::MAJOR >= 3
        logger = Rails.logger
    else
        logger = RAILS_DEFAULT_LOGGER
    end
    return logger unless logger.nil?
    #ActionController::Base::logger
end

end

A: Checking for @test.nil? isn't enough; you also need to check for its type. Either you can convert it to String object by calling to_s method on @test, or you can check for its class, that either it is string or not like following:
if !@test.nil? && @test.is_a? String
  # do your stuff
else

end

redpajama_set_name: RedPajamaStackExchange


text:
Q: Testing functions with random output
*

*I am working on a test project to test a neural networks library...

*The problem is that this library sometimes uses random numbers..

*I need to derive test cases (input,expected output,actual output)...

Does anybody have an idea how to derive test cases (input,expected output,actual output) to a function that uses random numbers when taking actions and evaluating outputs??

A: Yes, you either have to run a large enough number of cases so that the randomness averages out, or you make the random source another input to your function or method so you can test it independently.
An example of the first kind (this is Python, but the principle can apply in any language).
def test_random_number():
    total = sum(random.uniform(0, 1) for _ in xrange(1000))
    assert 100 < total < 900

So this test can fail if you're unlucky, but it's still a reasonable test since it'll pass nearly all the time, and it's pretty simple to make this kind of test.
To do things 'properly', you need to inject the random source.
class DefaultRandomBehavior(object):
    def pick_left_or_right(self):
        return random.choice(['left', 'right'])

class AardvarkModeller(object):
    def __init__(self, random_source=None):
        self.random_source = random_source or DefaultRandomBehavior()

    def aardvark_direction(self):
        r = self.random_source.pick_left_or_right()
        return 'The aardvark faces ' + r

Now you can unit test this by either mocking out or faking the DefaultRandomBehavior class, thus completely side-stepping the non-determinism.

A: It's unlikely that the library is really using random numbers as computers just aren't very good at generating those. Instead it's probably using a pseudo-random number generator seeded in some way, possibly from a 'real' random source or maybe from the current time. One way to make your results reproducible would be to teach the library to be able to accept a user supplied PRNG seed and set this to some constant for your test cases. The internal sequence of random numbers would then always be the same for your tests.
The second (and maybe more useful) approach would be to compare the expected output and actual output in an approximate way. If the use of random numbers makes such a big difference to your calculation that the results are really not reproducible you may want to think about the usefulness of the calculation. The trick would be to find some properties of the output of the library which can be compared numerically, with an allowable error, so I suspect you would want to compare the results of doing something with the neural network rather than compare the networks directly.


text:
Q: Using touchmove to trigger hover event I'm relatively new to coding and am running into a particular issue with my website. My homepage has images on it with overlay text hover effect that occurs when a cursor is moved over the image. It works perfectly on desktop, however, not on mobile. I would like for the hover text to appear when the user swipes across the image in any direction. I've done some research and it appears that I should somehow be using jQuery and the touchmove function to make this happen. But I just can't figure it out. I am using Shopify (debut theme) to build my website. Any help will be greatly appreciated!
Here's my CSS for hover event:
//hover effect//
.container {
  position: relative;
  width: 100%;
}

.image {
  display: block;
  width: 100%;
  height: auto;
}

.overlay {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  height: 99%;
  width: 100%;
  opacity: 0;
  transition: .5s ease;
  background-color: #000000;
}

.container:hover .overlay {
  opacity: 0.7;
}

.text {
  color: white;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 20px;
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  text-align: center;
  white-space: pre;
}

Thanks!!!!

A: You'd need to apply a class with the desired effect to the target element.
You could do it with Jquery, but javascript is perfectly capable to do it on its own.
Something like:
Javascript:
const myTargetElement = document.getElementsByClassName('overlay')[0]; // index to be confirmed

// add hover style
myTargetElement.addEventListener('touchmove', function (e) {
    e.target.classList.add('hover'); // or whichever class name you'd like
});
// remove hover style on end
myTargetElement.addEventListener('touchend', function (e) {
    e.target.classList.remove('hover'); // or whichever class name you'd like
});

CSS:
.container:hover .overlay,
.overlay.hover {
   opacity: 0.7;
}

Note: if you want to target all the elements .overlay on your page with that code, you would need something like:
Javascript:
const myTargetElements = document.getElementsByClassName('overlay');

// convert HTML collection to array
const myTargetElementsArray = [].slice.call(myTargetElements);
myTargetElementsArray.forEach(function (element) {

    // add hover style
    element.addEventListener('touchmove', function (e) {
        e.target.classList.add('hover'); // or whichever class name you'd like
    });

    // remove hover style on end
    element.addEventListener('touchend', function (e) {
        e.target.classList.remove('hover'); // or whichever class name you'd like
    });
});

A: so Moustachiste's code works! It had a few syntax errors but I was able to resolve them quickly. Here's the final version:
const myTargetElements = document.getElementsByClassName('overlay');

// convert HTML collection to array
const myTargetElementsArray = [].slice.call(myTargetElements);
myTargetElementsArray.forEach(function (element) {

    // add hover style
    element.addEventListener('touchmove', function (e) {
        e.target.classList.add('hover'); // or whichever class name you'd like
    });

    // remove hover style on end
    element.addEventListener('touchend', function (e) {
        e.target.classList.remove('hover'); // or whichever class name you'd like
    });
    });

Paste the code into your theme.js and adjust the variable names accordingly. Should work for everyone!
Cheers to this guy!


text:
Q: jQuery image thumbnail change on click I have a working jsFiddle attached. Yes, it works, however what I am trying to achieve seems beyond my experience.
At the moment it shows a row of thumbnails and when you click on one of these it will show the same image bigger as the featured image.
What I need to do is be able to show the thumbnails as a different image to what will appear as a featured image.
For example, I have a product featured image which will also have a zoomed in cropped version of this image to be the thumbnail.
Thumbnail 1 (zoomed in cropped version) / Featured Image 1
Thumbnail 2 (zoomed in cropped version) / Featured Image 2
Thumbnail 3 (zoomed in cropped version) / Featured Image 3
https://jsfiddle.net/gq74rgc3/2/

$(document).ready(function () {
$(".thumb").click(function () {
    var dir = $(this).attr("src");
    $('#image').hide();
    $('#image').fadeIn('fast');
    $('#image').attr("src", dir);
});
});

Does this make sense?
Any help would be much appreciated.
Cheers

A: add a data tag to your thumbnail containing the url of the image you want to display on click then instead of getting the src of the img get the data attribute value.
see: https://jsfiddle.net/gq74rgc3/3/

and the javascript:
$(document).ready(function () {
    $(".thumb").click(function () {
        var dir = $(this).data("big");
        $('#image').hide();
        $('#image').fadeIn('fast');
        $('#image').attr("src", dir);
    });
});

A: Something like this?
$(document).ready(function () {
    var images_array = ["http://www.981powerfm.com.au/images/stories/2014/09/happy_animal_5.jpg","http://www.981powerfm.com.au/images/stories/2014/09/happy_animal_5.jpg","http://smartyvet.com/site/wp-content/uploads/2014/05/happy5.jpg","http://www.telegram.ee/wp-content/uploads/2013/11/a.aaa-Happy-animals.jpg"];
    $(".thumb").click(function () {
        var dir = $(this).attr("src");
        $('#image').hide();
        $('#image').fadeIn('fast');
        $('#image').attr("src", images_array[Math.floor((Math.random()*4))]);
    });
});

http://jsfiddle.net/xL3p0drv/1/
It takes a random index from the array and show the image


text:
Q: Existe algum comando no sql server que retorna o numero de registros de uma tabela? Possuo uma tabela chamada cliente com vários clientes já cadastrados e quero filtrar todos os clientes que tenham a mesma idade e obter um numero inteiro desses registros, no caso a quantidade de clientes com a mesma idade.

A: Estou considerando que você tem uma tabela chamada Cliente, e nessa tabela tem um campo chamado DataNasc.
O código abaixo retorna uma lista de todas as idades e a quantidade de registros com aquela idade:
declare @hoje as datetime = getdate()

select idade, count(*) as qtd_idade
from (
    select CASE WHEN datepart(mm,DataNasc) > datepart(mm,@hoje) OR
                      (datepart(mm,DataNasc) = datepart(mm,@hoje)
                   AND datepart(dd,DataNasc) >= datepart(dd,@hoje))
                THEN DATEDIFF(year, DataNasc, @hoje) - 1
                ELSE DATEDIFF(year, DataNasc, @hoje)
            end as idade
    from Cliente
) as t
group by idade

Me avise se eu tiver entendido errado.


text:
Q: Android : how to reload custom markers once the image is downloaded via Picasso? I'm trying to load dynamically users avatars as custom markers. I based my code on the google maps utils demo, but somehow it doesn't work, it loads only one image and all the others are empty:

Here is my code:
public class MapsActivity extends FragmentActivity implements ClusterManager.OnClusterItemClickListener<ModelUser>, ClusterManager.OnClusterItemInfoWindowClickListener<ModelUser> {

    private ClusterManager<ModelUser> mClusterManager;
    private GoogleMap mMap; // Might be null if Google Play services APK is not available.
    private QueryAPI query = new QueryAPI();
    private List<ModelUser> users = new ArrayList<ModelUser>();
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

    //UI
    NetworkImageView avatarImageView;
    TextView name;
    TextView infos;
    TextView distance;
    RelativeLayout detailView;

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

        setUpMapIfNeeded();

        detailView = (RelativeLayout) findViewById(R.id.detailView);
        avatarImageView = (NetworkImageView) findViewById(R.id.imageView);
        name = (TextView) findViewById(R.id.name);
        infos = (TextView) findViewById(R.id.info);
        distance = (TextView) findViewById(R.id.distance);

        query.nearUsers(new QueryAPI.ApiResponse<List<ModelUser>>() {
            @Override
            public void onCompletion(List<ModelUser> result) {

                users = result;

                setUpClusterer();
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
    }

    private void setUpMap() {
        mMap.setMyLocationEnabled(true);
    }

    private void setUpClusterer() {

        // Position the map.
        getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(46.155115, 2.473060), 5));

        // Initialize the manager with the context and the map.
        // (Activity extends context, so we can pass 'this' in the constructor.)
        mClusterManager = new ClusterManager<ModelUser>(this, getMap());

        // Point the map's listeners at the listeners implemented by the cluster
        // manager.
        getMap().setOnCameraChangeListener(mClusterManager);
        getMap().setOnMarkerClickListener(mClusterManager);
        mClusterManager.setRenderer(new PersonRenderer());
        mClusterManager.setOnClusterItemClickListener(this);
        mClusterManager.setOnClusterItemInfoWindowClickListener(this);

        // Add cluster items (markers) to the cluster manager.
        addItems();
    }

    private void addItems() {

        for (int i = 0; i < users.size(); i++) {

            ModelUser user = users.get(i);

            mClusterManager.addItem(user);
        }

    }

    protected GoogleMap getMap() {
        setUpMapIfNeeded();
        return mMap;
    }

    @Override
    public boolean onClusterItemClick(ModelUser item) {

        Log.d("User clicked:", item.getName());
        avatarImageView.setImageUrl(item.getAvatar_url(), imageLoader);
        name.setText(item.getName());
        infos.setText(item.getAge());
        double d = Double.parseDouble(item.getDistance());
        distance.setText( String.format("%.1f", d) + "Km");
        detailView.setVisibility(View.VISIBLE);
        return false;
    }

    @Override
    public void onClusterItemInfoWindowClick(ModelUser item) {

        Log.d("User Window clicked:", item.getName());
    }

    /**
     * Draws profile photos inside markers (using IconGenerator).
     * When there are multiple people in the cluster, draw multiple photos (using MultiDrawable).
     */
    private class PersonRenderer extends DefaultClusterRenderer<ModelUser> {
        private final IconGenerator mIconGenerator = new IconGenerator(getApplicationContext());
        private final UICircularImage mImageView;
        //private final int mDimension;

        public PersonRenderer() {
            super(getApplicationContext(), getMap(), mClusterManager);

            View profile = getLayoutInflater().inflate(R.layout.map_marker_item, null);
            mIconGenerator.setContentView(profile);
            mImageView = (UICircularImage) profile.findViewById(R.id.avatarImageView);

        }

        @Override
        protected void onBeforeClusterItemRendered(ModelUser user, MarkerOptions markerOptions) {
            // Draw a single person.
            // Set the info window to show their name.
           // mImageView.setImageUrl(user.getAvatar_url(), imageLoader);
            Picasso.with(getApplicationContext())
                .load(user.getAvatar_url())
                .noFade()
                .into(mImageView, new com.squareup.picasso.Callback() {
                    @Override
                    public void onSuccess() {

                       //reload the marker HERE

                    }

                    @Override
                    public void onError() {

                    }
                });
            Bitmap icon = mIconGenerator.makeIcon();
            markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon)).title(user.getName());
        }

    }

Any idea why?
EDIT: I realized that sometimes it does load all the images, I think the problem comes from the async task. So my question is now: if I implement a callback to know when Picasso has finished to load the image, how can I reload this specific marker?

A: We'll load raw bitmap from Picasso and then pass it to marker representing current user
Picasso.with(getApplicationContext())
        .load(user.getAvatar_url())
        .into(new com.squareup.picasso.Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                // let's find marker for this user
                Marker markerToChange = null;
                for (Marker marker : mClusterManager.getMarkerCollection().getMarkers()) {
                    if (marker.getPosition().equals(user.getPosition())) {
                        markerToChange = marker;
                        break;
                    }
                }
                // if found - change icon
                if (markerToChange != null) {
                    markerToChange.setIcon(BitmapDescriptorFactory.fromBitmap(bitmap));
                }
            }
            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
            }
            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {
            }
        });

I have some troubles with Picasso too. So, i recommend to use Glide
compile 'com.github.bumptech.glide:glide:3.5.2'

Glide.with(getApplicationContext()).
            load(user.getAvatar_url())
            .asBitmap()
            .fitCenter()
            .into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
                    // let's find marker for this user
                    Marker markerToChange = null;
                    for (Marker marker : mClusterManager.getMarkerCollection().getMarkers()) {
                        if (marker.getPosition().equals(user.getPosition())) {
                            markerToChange = marker;
                            break;
                        }
                    }
                    // if found - change icon
                    if (markerToChange != null) {
                        markerToChange.setIcon(BitmapDescriptorFactory.fromBitmap(bitmap));
                    }
                }
            });

A: hello man the previous answer is working with with libs and here is another answer with native code
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {

    ImageView image;
    LatLng latLng;

    public DownloadImage (double lat, double lng) {
        this.latLng = new LatLng(lat, lng);
    }

    protected Bitmap doInBackground(String... urls) {

        String url = urls[0];
        Bitmap bmpImg = null;

        try {
            InputStream in = new java.net.URL(url).openStream();
            bmpImg = BitmapFactory.decodeStream(in);

        } catch (Exception e) {

            Log.e("image", e.toString());
        }

        return bmpImg;
    }

    protected void onPostExecute(Bitmap bmpImg) {

        View viewLocationMarker = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.marker_custom_view, null);
        ImageView imageView = (ImageView) viewLocationMarker.findViewById(R.id.imgPic);

        try {
            imageView.setImageBitmap(bmpImg);
        } catch (Exception e) {
            imageView.setImageResource(R.drawable.place_holder);
        }

        Marker locationMarker = mMap.addMarker(new MarkerOptions()
                .position(latLng).title("Sattar").anchor(0.33f, 1)
                .icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(MapsActivity.this, viewLocationMarker))));
    }
}

public static Bitmap createDrawableFromView(Context context, View view) {
    DisplayMetrics displayMetrics = new DisplayMetrics();
    ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
    view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
    view.buildDrawingCache();
    Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(bitmap);
    view.draw(canvas);

    return bitmap;
}

A: Regarding about @Stas Parshin answer, there might be some problems with Glide if you put the request within onBeforeClusterItemRendered().
I placed it on onClusterItemRendered() and it worked beautifully. It is because Glide is using asynchronous process and might not able to load it into ImageView in time.
Hope it helps.


text:
Q: MYSQL -- Getting most popular item based on where condition in another table I have a table called forumposts(this contains the thread id which is auto incremented), which represents forum threads.I have another table, forumreplies(each reply has a threadid, which refers to the thread id from forumposts).
I would like to display only popular forum threads, basically get threads that have the highest numbers of replies for each forum thread.Is there any way to do it in mySQL?

A: Try this
SELECT ThreadId,
  COUNT(*) AS [Count]
FROM FORUMREPLIES
GROUP BY ThreadId
ORDER BY [Count] DESC

Thanks


text:
Q: remove chapterprecis from content table I am using chapterprecis to write a small summary for each chapter in memoir document class. However, I just noticed that in contents table, it shows the whole text of this chapterprecis. I am wondering how to get rid of it.
\documentclass[12pt]{memoir}
\usepackage{lipsum}
\usepackage{amssymb}
\usepackage{pgfplots}
\usepackage{geometry}
\usetikzlibrary{shapes,arrows,arrows.meta}
\pagestyle{companion}
\setlength\prechapterprecisshift{20pt}

\definecolor{ared}{rgb}{.647,.129,.149}
\renewcommand\colorchapnum{\color{ared}}
\renewcommand\colorchaptitle{\color{ared}}
\chapterstyle{pedersen}

\begin{document}
\tableofcontents
\chapter{This is a test.}
\chapterprecis{
This is a test to show that the chapterprecis shows in the contents table and I would like to know how to get rid of this.}
\section{section 1}
\lipsum[1-2]
\section{section 2}
\lipsum[1-2]
\end{document}

A: \chapterprecishere will not add the text to the table of contents. The corresponding command to only add the text to the toc is \chapterprecistoc.
\documentclass[12pt]{memoir}
\usepackage{lipsum}
\usepackage{amssymb}
\usepackage{pgfplots}
\usepackage{geometry}
\usetikzlibrary{shapes,arrows,arrows.meta}
\pagestyle{companion}
\setlength\prechapterprecisshift{20pt}

\definecolor{ared}{rgb}{.647,.129,.149}
\renewcommand\colorchapnum{\color{ared}}
\renewcommand\colorchaptitle{\color{ared}}
\chapterstyle{pedersen}

\begin{document}
\tableofcontents
\chapter{This is a test.}
\chapterprecishere{
This is a test to show that the chapterprecis shows in the contents table and I would like to know how to get rid of this.}
\section{section 1}
\lipsum[1-2]
\section{section 2}
\lipsum[1-2]
\end{document}


text:
Q: Spark agg to collect a single list for multiple columns Here is my current code:
pipe_exec_df_final_grouped = pipe_exec_df_final.groupBy("application_id").agg(collect_list("table_name").alias("tables"))

However, in my collected list, I would like multiple column values, so the aggregated column would be an array of arrays. Currently the result look like this:
1|[a,b,c,d]
2|[e,f,g,h]

However, I would also like to keep another column attached to the aggragation (lets call it 'status' column name).  So my new output would be:
1|[[a,pass],[b,fail],[c,fail],[d,pass]]
...

I tried collect_list("table_name, status")  however collect_list only takes one column name.  How can I accomplish what I am trying to do?

A: Use array to collect columns into an array column first, then apply collect_list:
df.groupBy(...).agg(collect_list(array("table_name", "status")))


text:
Q: TreeView Node forecolor not changing when called at certain times? I have a treeview, trvActors.
When I try to change the forecolor of a treenode by clicking on it, it does not seem to work, but the surrounding code works.
            ((Actor)_rightClickedNode.Tag).IsDefault = true;
            _rightClickedNode.ForeColor = Color.Red;

Weirdly enough, the isDefault value changes, but the node does not change color.  This is occurring on a toolstripmenuitem click, but the same thing is also occurring on a simple right click.
Here is the code for a right click on the         private void trvActors_MouseClick event:
  trvActors.SelectedNode = trvActors.GetNodeAt(e.X, e.Y);

        if (trvActors.SelectedNode != null)
        {
            if (e.Button == MouseButtons.Right)
            {
                _rightClickedNode = trvActors.SelectedNode;

                ((Actor)_rightClickedNode.Tag).IsDefault = true;
                _rightClickedNode.ForeColor = Color.Red;

            }
        }

Same outcome.  The only time I seem to be able to change the forecolor is when I am initially creating the nodes.  Any ideas?

A: what do you have FullRowSelect set to.. if it is true make it false also maybe  you should put your code in the NodeMouseClick or BeforeSelect events ?
Hope this helps you out,


text:
Q: Consulta MySQL - Contagem de registros cross tables Possuo as seguintes tabelas:

Cada tupla da tabela PageViews (principal) contém uma visualização de página única. Se por um acaso uma mesma pessoa em uma mesma sessão (Sessions) visualiza uma mesma página (Pages), não é acrescentada uma nova tupla em PageViews. Ao invés disso é incrementado o campo PageViews.quantity.
Em um dos relatórios, preciso da quantidade de visitantes únicos (COUNT DISTINCT Visitors.id) e pageviews (SUM PageViews.quantity) em um determinado período (no dia, na semana, no mes e no ano) de uma loja específica (da qual é informada o Stores.code).
As consultas que estou fazendo no momento são:
Visitantes
SELECT DISTINCT Visitors.id
    FROM PageViews
      INNER JOIN VisitorsStores ON VisitorsStores.id = PageViews.visitor
      INNER JOIN Stores ON Stores.id = VisitorsStores.store
      INNER JOIN Sessions ON Sessions.id = VisitorsStores.session
      INNER JOIN Visitors ON Visitors.id = Sessions.visitor
    WHERE
      DATE(PageViews.createdAt) BETWEEN '2017-11-01' AND '2017-11-30' AND
      Stores.code = 'loja1';

PageViews
SELECT SUM(quantity) AS qtde
    FROM PageViews
      INNER JOIN VisitorsStores ON VisitorsStores.id = PageViews.visitor
      INNER JOIN Stores ON Stores.id = VisitorsStores.store
    WHERE
      DATE(PageViews.createdAt) BETWEEN '2017-11-01' AND '2017-11-30' AND
      Stores.code = 'loja1';

Ambas
SET @loja := 'loja1';
SET @inicio := '2017-11-01';
SET @fim := '2017-11-31';

SELECT
  COUNT(tVisitors.qtdVisitors) AS visitors,
  SUM(tVisitors.qtdPageViews) as pageViews
FROM (
  SELECT
    Visitors.id   AS qtdVisitors,
    SUM(quantity) AS qtdPageViews
  FROM PageViews
    INNER JOIN VisitorsStores ON VisitorsStores.id = PageViews.visitor
    INNER JOIN Stores ON Stores.id = VisitorsStores.store
    INNER JOIN Sessions ON Sessions.id = VisitorsStores.session
    INNER JOIN Visitors ON Visitors.id = Sessions.visitor
  WHERE
    DATE(PageViews.createdAt) BETWEEN @inicio AND @fim AND Stores.code = @loja
  GROUP BY qtdVisitors
) as tVisitors;

Funciona direitinho quando uma loja tem poucos acessos diários. Mas, quando uma loja possui muitos acessos (algumas em torno de 300 visitantes e 5.000 pageviews) a consulta demora muito para concluir (32s foi o maior tempo, na situação mencionada. Lojas com menos de 1.000 pageviews costumam demorar menos de 3s).
A dúvida é: De que outro jeito eu poderia fazer essa consulta de forma a ser mais rápida?

EXPLAIN da query Ambas para um único dia (05/12)
(visitor: 696 | pageViews: 5809 | tempo de execução da query: 32s)
[
    {
        "id": 1,
        "select_type": "PRIMARY",
        "table": "<derived2>",
        "type": "ALL",
        "possible_keys": null,
        "key": null,
        "key_len": null,
        "ref": null,
        "rows": 6192,
        "Extra": ""
    },
    {
        "id": 1,
        "select_type": "PRIMARY",
        "table": "<derived3>",
        "type": "ALL",
        "possible_keys": null,
        "key": null,
        "key_len": null,
        "ref": null,
        "rows": 6192,
        "Extra": ""
    },
    {
        "id": 3,
        "select_type": "DERIVED",
        "table": "Stores",
        "type": "index",
        "possible_keys": "PRIMARY",
        "key": "code",
        "key_len": "62",
        "ref": null,
        "rows": 1,
        "Extra": "Using where; Using index"
    },
    {
        "id": 3,
        "select_type": "DERIVED",
        "table": "VisitorsStores",
        "type": "ref",
        "possible_keys": "PRIMARY,FK_VisitorsStores_Stores",
        "key": "FK_VisitorsStores_Stores",
        "key_len": "5",
        "ref": "tmw_views.Stores.id",
        "rows": 6192,
        "Extra": "Using index"
    },
    {
        "id": 3,
        "select_type": "DERIVED",
        "table": "PageViews",
        "type": "ref",
        "possible_keys": "FK_PageViews_VisitorsStores",
        "key": "FK_PageViews_VisitorsStores",
        "key_len": "8",
        "ref": "tmw_views.VisitorsStores.id",
        "rows": 1,
        "Extra": "Using where"
    },
    {
        "id": 2,
        "select_type": "DERIVED",
        "table": "Stores",
        "type": "index",
        "possible_keys": "PRIMARY",
        "key": "code",
        "key_len": "62",
        "ref": null,
        "rows": 1,
        "Extra": "Using where; Using index; Using temporary"
    },
    {
        "id": 2,
        "select_type": "DERIVED",
        "table": "VisitorsStores",
        "type": "ref",
        "possible_keys": "PRIMARY,FK_VisitorsStores_Sessions,FK_VisitorsStores_Stores",
        "key": "FK_VisitorsStores_Stores",
        "key_len": "5",
        "ref": "tmw_views.Stores.id",
        "rows": 6192,
        "Extra": "Using where"
    },
    {
        "id": 2,
        "select_type": "DERIVED",
        "table": "Sessions",
        "type": "eq_ref",
        "possible_keys": "PRIMARY,FK_Sessions_Visitors",
        "key": "PRIMARY",
        "key_len": "8",
        "ref": "tmw_views.VisitorsStores.session",
        "rows": 1,
        "Extra": ""
    },
    {
        "id": 2,
        "select_type": "DERIVED",
        "table": "Visitors",
        "type": "eq_ref",
        "possible_keys": "PRIMARY",
        "key": "PRIMARY",
        "key_len": "8",
        "ref": "tmw_views.Sessions.visitor",
        "rows": 1,
        "Extra": "Using index"
    },
    {
        "id": 2,
        "select_type": "DERIVED",
        "table": "PageViews",
        "type": "ref",
        "possible_keys": "FK_PageViews_VisitorsStores",
        "key": "FK_PageViews_VisitorsStores",
        "key_len": "8",
        "ref": "tmw_views.VisitorsStores.id",
        "rows": 1,
        "Extra": "Using where; Distinct"
    }
]

SHOW TABLE STATUS FROM tmw_views;
{
    "table": "TABLES",
    "rows":
    [
        {
            "Name": "PageViews",
            "Engine": "InnoDB",
            "Version": 10,
            "Row_format": "Compact",
            "Rows": 1560181,
            "Avg_row_length": 84,
            "Data_length": 131694592,
            "Max_data_length": 0,
            "Index_length": 194314240,
            "Data_free": 12582912,
            "Auto_increment": null,
            "Create_time": "2017-10-27 23:31:14",
            "Update_time": null,
            "Check_time": null,
            "Collation": "utf8_general_ci",
            "Checksum": null,
            "Create_options": "",
            "Comment": ""
        },
        {
            "Name": "PageViewsYear",
            "Engine": "InnoDB",
            "Version": 10,
            "Row_format": "Compact",
            "Rows": 25,
            "Avg_row_length": 655,
            "Data_length": 16384,
            "Max_data_length": 0,
            "Index_length": 32768,
            "Data_free": 0,
            "Auto_increment": 62,
            "Create_time": "2017-11-27 11:17:44",
            "Update_time": null,
            "Check_time": null,
            "Collation": "utf8_general_ci",
            "Checksum": null,
            "Create_options": "",
            "Comment": ""
        },
        {
            "Name": "Pages",
            "Engine": "InnoDB",
            "Version": 10,
            "Row_format": "Compact",
            "Rows": 94648,
            "Avg_row_length": 116,
            "Data_length": 11026432,
            "Max_data_length": 0,
            "Index_length": 0,
            "Data_free": 4194304,
            "Auto_increment": 205925,
            "Create_time": "2017-10-27 23:31:14",
            "Update_time": null,
            "Check_time": null,
            "Collation": "utf8_general_ci",
            "Checksum": null,
            "Create_options": "",
            "Comment": ""
        },
        {
            "Name": "Sessions",
            "Engine": "InnoDB",
            "Version": 10,
            "Row_format": "Compact",
            "Rows": 366180,
            "Avg_row_length": 73,
            "Data_length": 26804224,
            "Max_data_length": 0,
            "Index_length": 41058304,
            "Data_free": 3145728,
            "Auto_increment": 531262,
            "Create_time": "2017-10-27 23:31:14",
            "Update_time": null,
            "Check_time": null,
            "Collation": "utf8_general_ci",
            "Checksum": null,
            "Create_options": "",
            "Comment": ""
        },
        {
            "Name": "Stores",
            "Engine": "InnoDB",
            "Version": 10,
            "Row_format": "Compact",
            "Rows": 0,
            "Avg_row_length": 0,
            "Data_length": 16384,
            "Max_data_length": 0,
            "Index_length": 16384,
            "Data_free": 0,
            "Auto_increment": 31,
            "Create_time": "2017-10-27 23:31:14",
            "Update_time": null,
            "Check_time": null,
            "Collation": "utf8_general_ci",
            "Checksum": null,
            "Create_options": "",
            "Comment": ""
        },
        {
            "Name": "SystemLogs",
            "Engine": "InnoDB",
            "Version": 10,
            "Row_format": "Compact",
            "Rows": 5913,
            "Avg_row_length": 1687,
            "Data_length": 9977856,
            "Max_data_length": 0,
            "Index_length": 540672,
            "Data_free": 4194304,
            "Auto_increment": null,
            "Create_time": "2017-11-20 15:21:31",
            "Update_time": null,
            "Check_time": null,
            "Collation": "utf8_general_ci",
            "Checksum": null,
            "Create_options": "",
            "Comment": ""
        },
        {
            "Name": "Visitors",
            "Engine": "InnoDB",
            "Version": 10,
            "Row_format": "Compact",
            "Rows": 31067,
            "Avg_row_length": 51,
            "Data_length": 1589248,
            "Max_data_length": 0,
            "Index_length": 1589248,
            "Data_free": 4194304,
            "Auto_increment": 102579,
            "Create_time": "2017-10-27 23:31:14",
            "Update_time": null,
            "Check_time": null,
            "Collation": "utf8_general_ci",
            "Checksum": null,
            "Create_options": "",
            "Comment": ""
        },
        {
            "Name": "VisitorsStores",
            "Engine": "InnoDB",
            "Version": 10,
            "Row_format": "Compact",
            "Rows": 297216,
            "Avg_row_length": 44,
            "Data_length": 13107200,
            "Max_data_length": 0,
            "Index_length": 17842176,
            "Data_free": 4194304,
            "Auto_increment": 562767,
            "Create_time": "2017-10-27 23:31:14",
            "Update_time": null,
            "Check_time": null,
            "Collation": "utf8_general_ci",
            "Checksum": null,
            "Create_options": "",
            "Comment": ""
        }
    ]
}

SHOW VARIABLES LIKE 'query_cache%';
query_cache_limit             1048576
query_cache_min_res_unit      4096
query_cache_size              33554432
query_cache_strip_comments    OFF
query_cache_type              ON
query_cache_wlock_invalidate  OFF

A: O problema está no uso da função DATE(), posto que ele acaba atrapalhando o uso do índice.
Pense no seguinte: para cada tupla, o MySQL tem que executar a função antes de verificar se a data está dentro do limite.
Recomendo que, ao invés disso, coloque na data de inicio a hora inicial (2017-12-31 00:00:00) e na data de fim a hora final (2017-12-31 23:59:59).
Assim você não precisaria usar o DATE() e o índice aprimorará a velocidade da consulta, como deve ser.
SET @loja := 'loja1';
SET @inicio := '2017-11-01 00:00:00';
SET @fim := '2017-11-31 23:59:59';

SELECT
  COUNT(tVisitors.qtdVisitors) AS visitors,
  SUM(tVisitors.qtdPageViews) as pageViews
FROM (
  SELECT
    Visitors.id   AS qtdVisitors,
    SUM(quantity) AS qtdPageViews
  FROM PageViews
    INNER JOIN VisitorsStores ON VisitorsStores.id = PageViews.visitor
    INNER JOIN Stores ON Stores.id = VisitorsStores.store
    INNER JOIN Sessions ON Sessions.id = VisitorsStores.session
    INNER JOIN Visitors ON Visitors.id = Sessions.visitor
  WHERE
    PageViews.createdAt BETWEEN @inicio AND @fim AND Stores.code = @loja
  GROUP BY qtdVisitors
) as tVisitors;

A: Sendo bem direto: no momento é feito um JOIN implícito entre tVisitor com tPageViews na consulta Ambas.
Podemos melhorar e otimizar com Semi-Join [ WHERE Stores.id IN (Subqueries)], porque a ambas usam os mesmos dados na cláusula WHERE e a Subqueries tPageViews é apenas um COUNT().
 NOTA-1: consulta não testada no meu ambiente, é apenas uma abstração teórica de uma possível solução.
-- Teste de pageviews
SELECT SUM(quantity) AS qtdePageViews, COUNT(Visitors.id) AS visitor
FROM PageViews
  INNER JOIN VisitorsStores ON VisitorsStores.id = PageViews.visitor
  INNER JOIN Stores ON Stores.id = VisitorsStores.store
  INNER JOIN Sessions ON Sessions.id = VisitorsStores.session
  INNER JOIN Visitors ON Visitors.id = Sessions.visitor
WHERE Stores.id IN (
    SELECT Stores.id
    FROM PageViews
      INNER JOIN VisitorsStores ON VisitorsStores.id = PageViews.visitor
      INNER JOIN Stores ON Stores.id = VisitorsStores.store
    WHERE
      DATE(PageViews.createdAt) BETWEEN '2017-11-01' AND '2017-11-30'
      AND Stores.code = 'loja1'
);

Apenas para contribuir e facilitar a verificação, segue as tabelas com SQL no dialeto do MySQL:

Tabela Visitors:

CREATE TABLE `Visitors` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `ip` varchar(50) NOT NULL,
  `createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Tabela Stores:

CREATE TABLE `Stores` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `code` varchar(250) NOT NULL,
  `visitor` bigint(20) unsigned DEFAULT NULL,
  `createdAt` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `code_UNIQUE` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Tabela Pages:

CREATE TABLE `Pages` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `url` varchar(500) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Tabela VisitorsStores:

CREATE TABLE `VisitorsStores` (
  `id` bigint(20) unsigned NOT NULL,
  `session` bigint(20) unsigned DEFAULT NULL,
  `store` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `session_FKIndex_idx` (`session`),
  KEY `store_FKIndex_idx` (`store`),
  CONSTRAINT `session_FKIndex` FOREIGN KEY (`session`)
    REFERENCES `Sessions` (`id`) ON DELETE
        NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `store_FKIndex` FOREIGN KEY (`store`)
    REFERENCES `Stores` (`id`)
        ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Tabela PageViews:

CREATE TABLE `PageViews` (
  `page` int(10) unsigned NOT NULL,
  `visitor` bigint(20) unsigned NOT NULL,
  `quantity` int(10) unsigned DEFAULT NULL,
  `updatedAt` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `createdAt` datetime DEFAULT NULL,
  PRIMARY KEY (`page`,`visitor`),
  KEY `visitor_FKIndex_idx` (`visitor`),
  CONSTRAINT `page_FKIndex` FOREIGN KEY (`page`)
    REFERENCES `Pages` (`id`)
        ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `visitor_FKIndex` FOREIGN KEY (`visitor`)
    REFERENCES `VistitorsStores` (`id`)
        ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Tabela Sessions:

CREATE TABLE `Sessions` (
  `id` bigint(20) unsigned NOT NULL,
  `code` varchar(250) DEFAULT NULL,
  `visitor` bigint(20) unsigned DEFAULT NULL,
  `createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `session_FKIndex_visitor_idx` (`visitor`),
  CONSTRAINT `session_FKIndex_visitor` FOREIGN KEY (`visitor`)
    REFERENCES `Visitors` (`id`)
        ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Existem várias estratégias de otimização que podemos aproveitar para fazer as consultas serem mais rápidas. E a que considero prioritária é:

As consultas funcionam de forma mais eficiente quando você escolhe um Storage Engine com propriedades que melhor atendem aos requisitos da aplicação.

Otimizando consultas InnoDB [MySQL 5.6 -  2015, 1085 p.]

*

*Se você freqüentemente tem consultas recorrentes para tabelas que não são atualizadas com freqüência, habilite o cache da consulta:
[mysqld]
query_cache_type = 1
query_cache_size = 10M

*Não crie um índice secundário separado para cada coluna, pois cada consulta só pode usar um índice. Os índices em colunas ou colunas raramente testadas com apenas alguns valores diferentes podem não ser úteis para qualquer dúvida. Se você tiver muitas consultas para a mesma tabela, testando diferentes combinações de colunas, tente criar um pequeno número de índices concatenados em vez de um grande número de índices de uma única coluna. Se um índice contiver todas as colunas necessárias para o conjunto de resultados (conhecido como índice de cobertura), a consulta poderá evitar a leitura dos dados da tabela.

*Se uma coluna indexada não pode conter valores NULL, declare-a como NOT NULL quando você cria a tabela. O otimizador pode determinar melhor qual índice é mais efetivo para uma consulta, quando sabe se cada coluna contém valores NULL ou não.
 NOTA-2: No contexto aqui da pergunta, seria a tupla: `Stores`.`code` (varchar(250)) que é muito grande deve ser indexado conforme abaixo, usando índice de cobertura combinando o `Stores`.`id`com o `Stores`.`code`:
ALTER TABLE `Stores`
DROP INDEX `code_UNIQUE` ,
ADD UNIQUE INDEX `code_UNIQUE` USING BTREE (`id` ASC, `code`(62) ASC);

Otimizando o Servidor :: Parâmetros de memória [Paul DuBois et al -  2006, 543 p.]
Interessante ter em mente que quando pensamos em performance e otimizações não podemos esquecer do servidor. Sei que pode sair do escopo da pergunta, mas seria uma respostar incompleta se não otimizarmos o servidor. No contexto aqui, vamos nos concentrar em criar um arquivo my-large.cnf na pastar /usr/share/mysql com os seguintes valores:
[mysqld]
key_buffer_size = 256M
table_cache = 256
sort_buffer_size = 1M
query_cache_type = ON
query_cache_size = 16M

Otimizando o Servidor :: Query Cache [Paul DuBois et al -  2006, 549 p.]
[mysqld]
query_cache_type = 1
query_cache_size = 10M
query_cache_limit = 2M

 NOTA-3: Sempre que alterar arquivos de configuração é necessário reiniciar o servidor MySQL
Para verificar os valores Query Cache atuais do seu ambiente:
SHOW VARIABLES LIKE 'query_cache%';

Referência:
[MySQL 5.6 -  2015], MySQLTM, MySQL 5.6 Reference Manual: Including MySQL Cluster NDB 7.3-7.4 Reference Guide. Document generated on: 2015. May 08. (revision: 43103)
[Paul DuBois et al -  2006], Copyright © 2006 by MySQL AB, MySQL 5.0 Certification Study Guide
[Sheeri Cabral, Keith Murphy -  2009], Published by Wiley Publishing, Inc., MySQL® Administrator's Bible


text:
Q: Removing certain values from the dataframe in R I am not sure how I can do this, but what I need is I need to form a cluster of this dataframe mydf where I want to omit the inf(infitive) values and the values greater than 50. I need to get the table that has no inf and no values greater than 50. How can I get a table that contains no inf and no value greater than 50(may be by nullifying those cells)?  However, For clustering part, I don't have any problem because I can do this using mfuzz package. So the only problem I have is that I want to scale the cluster within 0-50 margin.
mydf
   s.no       A        B       C
    1         Inf     Inf      999.9
    2         0.43    30       23
    3         34      22       233
    4         3       43       45

A: You can use NA, the built in missing data indicator in R:
?NA

By doing this:
mydf[mydf > 50 | mydf == Inf] <- NA
mydf
  s.no     A  B  C
1    1    NA NA NA
2    2  0.43 30 23
3    3 34.00 22 NA
4    4  3.00 43 45

Any stuff you do downstream in R should have NA handling methods, even if it's just na.omit


text:
Q: Get All Diagonals in a 2 Dimensional Matrix Using LINQ Given a 2 dimensional matrix below
int[][] m = new int[][] {   new int[] { 1, 2, 3, 4 },
                            new int[] { 0, 1, 4, 3 },
                            new int[] { 4, 0, 2, 2 },
                            new int[] { 4, 2, 0, 1 }};

I would like to use LINQ to get all the diagonals i.e.
4
3 3
2 4 2
1 1 2 1
0 0 0
4 2
4
Right now I am using two ugly for loops but I know there has to be a better way.
List<List<int>> e = new List<List<int>>();
for (int i = 0; i < m.Count(); i++)
{
    for (int j = m.Count() - 1; j >= 0; j--)
    {
        if (i == 0 || (i > 0 && j == 0))
        {
            e.Add(new List<int> { m[i][j] });
        }

        if (i > 0 && j > 0)
        {
            e[i - j + m.Count() - 1].Add(m[i][j]);
        }
    }
}

A: Flattening the matrix and then grouping by the created key:
var d = m.SelectMany((row, rowIdx) =>
        row.Select((x, colIdx) => new { Key = rowIdx - colIdx, Value = x }))
    .GroupBy(x => x.Key, (key, values) => values.Select(i => i.Value).ToArray())
    .ToArray();

If diagonals need to be in the logical order, need to also sort the results:
var d2 = m.SelectMany((row, rowIdx) =>
         row.Select((x, colIdx) => new { Key = rowIdx - colIdx, Value = x }))
    .GroupBy(x => x.Key)
    .OrderBy(x => x.Key)
    .Select(values => values.Select(i => i.Value).ToArray())
    .ToArray();

A: Using LINQ
As far as I can see, this particular problem doesn't really get any performance benefit from using LINQ at all. Maybe you can explain that requirement further, as the performance loss and increased complexity doesn't seem to result in a more "elegant" solution that your current or any other solution that just implements an iterative approach to the problem.

Alternative: Using the Math.Abs Method
I would think that using Math.Abs() gives you an efficient loop
int length = 4;
for (int i = -length; i <= Math.Abs(length); i++)
{
    Console.WriteLine(i);
    // -4, -3, -2, -1,  0, +1, +2, +3, +4
}

This might be a potential solution that uses Math.Abs(). It reverses the order when it goes through the center diagonal.
int[][] m = new int[][] {
    new int[] { 1, 2, 3, 4 },
    new int[] { 0, 1, 4, 3 },
    new int[] { 4, 0, 2, 2 },
    new int[] { 4, 2, 0, 1 }};

int max = m.Length;
for (int i = -max+1; Math.Abs(i) < max; i++)
{
    for (int j = 0; j <= max - Math.Abs(i) - 1; j++)
    {
        int row = i < 0 ? j : i + j;
        int col = i > 0 ? j : (Math.Abs(i) + j);
        Console.Write(m[row][col]);
    }
    Console.WriteLine();
}


text:
Q: Image of Ubuntu 12.04 LTS for 64-bit I want to install Ubuntu 12.04 LTS on my Lenovo ThinkPad that has 64-bit architecture, but where do I find a 64-bit version of 12.04?
It doesn't seem to appear on this site

A: Here is the link to Ubuntu 12.04 64bit but its legit torrent file
or visit official site, at the bottom you will links to all supported ubuntu releases

if above links are not working, here is mirror link from University of Maryland


text:
Q: DistutilsArgError: no commands supplied I am trying to import this package (https://github.com/kandouss/marlgrid) in my script, by doing the following:
from setuptools import setup, find_packages

setup(
    name="marlgrid",
    version="0.0.5",
    packages=find_packages(),
    install_requires=["numpy", "tqdm", "gym", "gym-minigrid", "numba"],
)

import numpy as np
import marlgrid

from marlgrid.rendering import InteractivePlayerWindow
from marlgrid.agents import GridAgentInterface
from marlgrid.envs import env_from_config

However, I receive this error:
Traceback (most recent call last):

  File "C:\Users\bolot\anaconda3\lib\distutils\core.py", line 134, in setup
    ok = dist.parse_command_line()

  File "C:\Users\bolot\anaconda3\lib\distutils\dist.py", line 501, in parse_command_line
    raise DistutilsArgError("no commands supplied")

DistutilsArgError: no commands supplied

During handling of the above exception, another exception occurred:

SystemExit: usage: temp.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
   or: temp.py --help [cmd1 cmd2 ...]
   or: temp.py --help-commands
   or: temp.py cmd --help

error: no commands supplied

Could you please help?
Thanks!

A: Run your script from the command-line as python setup.py install
Note if you need to build first, run python setup.py build
Sources:
How do you run a setup.py file properly?
How to avoid a "No commands supplied" on setup.py with py.test


text:
Q: get page id's - not get pages? I'm trying to do something like this:
Hide a page in the admin end without a plugin?
However, I don't want to hardcode the page-ids. I want to get the page id's based on template-name.
$pages = get_posts(array(
        'post_type' => 'page',
    'meta_key' => '_wp_page_template',
    'meta_value' => 'product.php'
));

^^This probably does the job, but it gets entire pages, and I start worrying about efficiency, especially when I only need id's and there could be thousands of pages being returned by this command.
I know SQL pretty well, so if I should just write my own query, then let me know.
Or maybe I don't need to worry about this at all?

A: Use the parameter 'fields':
$pages = get_posts(
    array(
        'post_type'  => 'page',
        'meta_key'   => '_wp_page_template',
        'meta_value' => 'product.php',
        'fields'     => 'ids'
    )
);

Not tested, but it should fetch just the IDs.


text:
Q: Login to website and then web scrape data (Python) I kindly ask you to correct me what I am wrong here. The html code I obtain is again a page with login form. What I meant to do here is to get a token during one session and then to use it to log in. What I plan to do is to use bs4 to collect some data.
import bs4
import requests

session = requests.session
with requests.Session() as s:
    url = 'https://www.planetplus.pl/'
    res = requests.get(url)
    data = res.text
    soup = bs4.BeautifulSoup(data, 'lxml')
    token = soup.find_all('input', attrs={'name': '__RequestVerificationToken'})[0]['value']
    print(token)
    payload = {'UserName': 'xxx', 'Password': 'yyy',
               '__RequestVerificationToken': token}
    p = s.post(url, data=payload)
    r = s.get('https://www.planetplus.pl/moje-konto-cashback')
    print(r.text)

Website link: https://www.planetplus.pl/
Well, to be honest I am a beginner, so if you could correct me and even elaborate, suggest how to do it the best, this would be great!
Additionally, how much the procedure is different for website http://www.exsite.pl/, because I delete the token part in login credentials dictionary and also the output is access restricted page html code. And do not judge websites, first found with different login type, at least different for me ;)
import requests

with requests.Session() as s:
    session = requests.session
    url = 'http://exsite.pl//'
    payload = {'login_name': 'xxx', 'login_password': 'yyy!'}
    p = s.post(url, data=payload)
    #print(p.text)
    r = s.get('http://www.exsite.pl/filmy_video_movies/filmy-dvdrip-brrip/1378773-ukryte-piekno-collateral-beauty-2016-plsubbed480pbrripxvidac3-krt-napisy-pl.html')
    print(r.text)

A: Working example for https://www.planetplus.pl/
import bs4
import requests

BASE_URL = 'https://www.planetplus.pl/'
LOGIN_URL = BASE_URL + 'logowanie'

with requests.Session() as session:
    res = session.get(BASE_URL)

    soup = bs4.BeautifulSoup(res.text, 'lxml')
    token = soup.find_all('input', attrs={'name': '__RequestVerificationToken'})[0]['value']
    payload = {'UserName': '6r5anl+fnmps358bvh8@sharklasers.com', 'Password': 'qwerty',
               '__RequestVerificationToken': token}

    session.post(LOGIN_URL , data=payload)
    res = session.get(BASE_URL)
    print(res.text)


text:
Q: Get the time of the beginning and the end of the download I have to get the time of download in my android application, that's why I need to determine the time of beginning and end of dowload to determine the period od download.
I added these line in the beginning and the end of doInBackground:
Log.v("Download_INFO","i begin downloading at : "+" "+dt.getHours()+"h "+dt.getMinutes()+"min "
                        +dt.getSeconds()+"sec");

Log.v("Download_INFO","i complete downloading at : "+" "+dt.getHours()+"h "+dt.getMinutes()
                        +"min "+dt.getSeconds()+"sec");

But the surprise is that i had the some time. I can't understand the reason
this is my doInBackground method :
protected String doInBackground(String... aurl) {
        int count;

        try {
            File vSDCard = null;
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                vSDCard = Environment.getExternalStorageDirectory();
                File vFile = new File(vSDCard.getParent() + "/" + vSDCard.getName() + "/"
                        + "downloadTest.jpg");
                URL url = new URL(aurl[0]);
                URLConnection conexion = url.openConnection();
                conexion.connect();
                int lenghtOfFile = conexion.getContentLength();
                Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(vFile);
                byte data[] = new byte[1024];
                long total = 0;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                    output.write(data, 0, count);
                }

                Log.v("Download_INFO","i complete downloading at : "+" "+dt.getHours()+"h "+dt.getMinutes()
                        +"min "+dt.getSeconds()+"sec");
                output.flush();
                output.close();
                input.close();
                System.out.println(currentDateTimeString);
            }

        } catch (Exception e) {
            Log.d("ImageManager", "Error: " + e);
        }

        return null;
    }

what's the problem please !

A: It looks like you're using the same date object for both log statements. Add this before your "download complete" log statement:
dt = new Date();

By the way, all those methods (getSeconds, getHours, etc) of Date are depricated. You can get the timing simply by doing a System.currentTimeMillis() at the beginning of the download and again at the end and subtracting. This is the total duration in milliseconds which you can convert into hours/min/seconds if you want.


text:
Q: Google Apps Script error when trying to read into a database using jdbc I have a google apps script that is working in one instance, but not another
Both scripts are identical, the only difference I have programmed is the jdbc query.
Here is the working function:
function wbk() {
  var conn = Jdbc.getConnection("jdbc:mysql://aaa.aaaa.org:3306/aaaaa", "aaaa", "bbbbb");
  var stmt = conn.createStatement();
  stmt.setMaxRows(10000);
  var start = new Date();
  var rs = stmt.executeQuery("SELECT `DateUpdate`, `AllianceName`, `PlayerName`, `Score`, `Rank`, `TotalCities`, `FameTotal`, `FameRank`, `DefeatedTotal`, `DefeatedRank`, `PlunderTotal`, `PlunderRank` FROM `Member` WHERE AllianceID='2' OR AllianceID='48'");
  var doc = SpreadsheetApp.getActiveSpreadsheet();
  var first = doc.getSheetByName("WBK");
  first.activate();
  var cell = first.getRange('b2');
  var row = 0;
  while (rs.next()) {
    for (var col = 0; col < rs.getMetaData().getColumnCount(); col++) {
      cell.offset(row, col).setValue(rs.getString(col + 1));
    }
    row++;
  }
  rs.close();
  stmt.close();
  conn.close();
  var end = new Date();
  Logger.log("time took: " + (end.getTime() - start.getTime()));
};

I ran this twice, after updating the db and the results were perfect, just what was expected.
Now, when I try to use the same function, and only modify the query (and I checked the SQL statement in the db, that's just fine), the function fails.
Here is the non working function.
function WC_Combined() {
  var conn = Jdbc.getConnection("jdbc:mysql://aaa.aaaa.org:3306/aaaaa", "aaaa", "bbbbb");
  var stmt = conn.createStatement();
  stmt.setMaxRows(10000);
  var start = new Date();
  var rs = stmt.executeQuery("SELECT `DateUpdate`, `AllianceName`, `PlayerName`, `Score`, `Rank`, `TotalCities`, `FameTotal`, `FameRank`, `DefeatedTotal`, `DefeatedRank`, `PlunderTotal`, `PlunderRank` FROM `Member` where AllianceID='195' OR AllianceID='494'");
  var doc = SpreadsheetApp.getActiveSpreadsheet();
  var first = doc.getSheetByName("Combined");
  first.activate();
  var cell = first.getRange('b2');
  var row = 0;
  while (rs.next()) {
    for (var col = 0; col < rs.getMetaData().getColumnCount(); col++) {
      cell.offset(row, col).setValue(rs.getString(col + 1));
    }
    row++;
  }
  rs.close();
  stmt.close();
  conn.close();
  var end = new Date();
  Logger.log("time took: " + (end.getTime() - start.getTime()));
};

The error message I get in the debug console on Google is
Service error: Spreadsheets (line 110, file "Code")

Line 110 in my code is cell.offset(row, col).setValue(rs.getString(col + 1)); in the second function I have provided above; I cannot find any difference between this line in the 2nd function or the 1st example I have provided ---- and they both worked the first time I tried to run them.
Any ideas, anyone? I haven't even used custom code, the code is basically the google apps documentation example.
I am using Google scripting within a Google Docs Spreadsheet, connecting to mysql. I've opened up the remote connections to mysql, and have 2 working spreadsheets, so I know the connection works.

A: Issue 703 in the Issue Tracker has continued to see users report instances of this since July 2011. Visit and star the issue for updates, and add any information that may help the googlers to isolate the issue.

A: Is it possible that your loops are putting too much strain on the Spreadsheet API?
I would be more enclined to filling up a data structure from my sql rows and then appliying the resulting two dimensional data array to the correct range.
var data = [];
while (rs.next()) {
    var rowData = [];
    for (var col = 0; col < rs.getMetaData().getColumnCount(); col++) {
        rowData[col] = (rs.getString(col + 1));
    }
    data[row] = rowData;
    row++;
}

var range = first.getDataRange(1,2,row, col+1); // check edges or uses a1 notation

range.setValues(data);

This has the advantage of being much more efficient as well, and won't stress the API with a quick doubl e loop.
Let me know how it goes, if you need any more info.


text:
Q: Botstate.SetConversationData - Unexpected character encountered while parsing value I am trying to save conversation data via state client and I am getting inconsistent results between the emulator and the sms channels. Testing my bot app via emulator allows me to SetConversationData and GetConversationData fine, but as soon as I try it on sms with service url: https://sms.botframework.com/ I get the following error:

"exceptionMessage": "Unable to deserialize the response.",
    "exceptionType": "Microsoft.Rest.SerializationException",
    "stackTrace": "   at Microsoft.Bot.Connector.BotState.d__9.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.Bot.Connector.BotStateExtensions.d__9.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.Bot.Connector.BotStateExtensions.SetConversationData(IBotState operations, String channelId, String conversationId, BotData botData)\r\n   at OutboundTestApp.Controllers.OutboundController.Post(OutboundConversationData`1 outboundData)",
    "innerException": {
      "message": "An error has occurred.",
      "exceptionMessage": "Unexpected character encountered while parsing value: T. Path '', line 0, position 0.",
      "exceptionType": "Newtonsoft.Json.JsonReaderException",
      "stackTrace": "   at Newtonsoft.Json.JsonTextReader.ParseValue()\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)\r\n   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)\r\n   at Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject[T](String json, JsonSerializerSettings settings)\r\n   at Microsoft.Bot.Connector.BotState.d__9.MoveNext()"

Here is my code to set the data where the channelId is "sms", conversationId is a valid id and the data is just a simple POCO class:
   var stateClient = new StateClient(new Uri(serviceUrl), account);
    stateClient.BotState.SetConversationData(outboundData.ChannelId, conversationResponse.Id, new BotData(data: outboundData.Data));

Should I be using SetPrivateConversationDataWithHttpMessagesAsync and pass in the content type and set my botdata to a json string? I feel the state client is assuming json is being passed somewhere, but the object it is deserializing is actually not json.

A: The problem is that the serviceUrl was set incorrectly when creating the state client. The baseUri should be https://state.botframework.com.


text:
Q: Creating a group with Admin SDK Directory API in Google Apps Script doesn't work "On form submit" I've read through all of the relevant pages in the Admin ADK Directory API documentation and several questions on stackoverflow, and I'm still stuck.
I am the super admin of my Google Apps domain, and I want users in my domain to be able to create their own Google Groups. I made a Google Form where the user specifies the name and email of the group. Then the Google Form Responses sheet has an "On form submit" trigger that invokes my code to create the group.
This code works when I run createGroupTest() from the Script Editor. It creates the group in my Google apps domain immediately.
This code does not work when the "On form submit" trigger runs the onFormSubmit(e) function. I get the email from the catch(e) saying Exception: Failed to authenticate for service: Groups.
Does anyone know what is causing the oauth authentication to work from within the Script Editor but not when invoked by the onFormSubmit function?
function onFormSubmitTest() {

  var t = new Date();
  t = t.getTime();

  onFormSubmit([t, "AAA Test Group " + t], ["aaa.testgroup." + t + "@mydomain.com"], ["me@mydomain.com"]);

}

var consumerKey = "mydomain.com";
var consumerSecret = "xxxxxxxxxxxxxxxxxxxxxxxx";
var domainName = "mydomain.com";

function onFormSubmit(e) {

  var timestamp  = e.values[0];
  var groupName  = e.values[1];
  var groupEmail = e.values[2];
  var owner      = e.values[3];

  owner = owner.split("@")[0];

  var description = 'test';

  var requestBody = {email: groupEmail, name: groupName, description: description};

  var scope = "https://www.googleapis.com/auth/admin.directory.group";

  var fetchArgs                = googleOAuth_("Groups", scope);
  fetchArgs.method             = "POST";
  fetchArgs.contentType        = "application/json";
  fetchArgs.payload            = JSON.stringify(requestBody);
  fetchArgs.muteHttpExceptions = true;

  var url = 'https://www.googleapis.com/admin/directory/v1/groups?key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

  UrlFetchApp.fetch(url, fetchArgs);

}

function googleOAuth_(name,scope) {
  var oAuthConfig = UrlFetchApp.addOAuthService(name)
  oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
  oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
  oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
  oAuthConfig.setConsumerKey(consumerKey);
  oAuthConfig.setConsumerSecret(consumerSecret);
  return {oAuthServiceName:name, oAuthUseToken:'always'};
}

A: I figured it out: I had failed to include the domain extension in the groupEmail string (because my Google Form only asks the user to fill in the group email name without the domain extension).


text:
Q: Miktex and package update Initially the issue was circuitikz.sty was missing. Then I tried to update package from MiKTeX console package option and I got the error

SSL connect error

and the code was

code="35", url="https://ims.jit.ac.in/repo/tex-archive/systems/win32/miktex/tm/packages/miktex-zzdb1-2.9.tar.lzma"

Then I uninstalled MiKTeX and reinstalled it. After that MiKTeX console is not updating and doesn't let any package to be updated. When I try to check update for console, it shows

When I try to update packages, it shows:

Also the Texstudio has stopped the compilation. This is becoming a notorious problem for my purpose. Any sort of suggestion is welcome!

A: It appears the site https://ims.jit.ac.in/repo/tex-archive is having some issues. You can change the repository that MikTeX updates from by following the instructions at How can I change the package repository?


text:
Q: Android Studio:App crashes when countdown timer is started I made an app that counts the scored goals in a match (When you're playing with friends and you're too lazy to count the scores :D ) I want to make a countdown timer to count the time for the match.
My app crashes when I push a Start button to start the countdown timer.I have 2 Activities.The Main activity is the code that counts the scores for the 2 teams.
This is my Second Activity code(Where the CountDowntimer should be.):
    package com.example.robert.scorecount;

import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.concurrent.TimeUnit;

public class SecondActivity extends AppCompatActivity {

    Button StartButton,StopButton;
    TextView TimerText;

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

        Button StartButton = (Button) findViewById(R.id.StartButton);
        Button StopButton = (Button) findViewById(R.id.StopButton);
        TextView TimerText = (TextView) findViewById(R.id.Timer);

        TimerText.setText("00:00:00");

    final CounterClass timer = new CounterClass(3600000,1000);

        assert StartButton != null;
        StartButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                timer.start();
            }
        });

        assert StopButton != null;
        StopButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                timer.cancel();
            }
        });

    }

    public class CounterClass extends CountDownTimer{

        public CounterClass(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            String HourMinutesSeconds = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
                    TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
                    TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));
            TimerText.setText(HourMinutesSeconds);

        }

        @Override
        public void onFinish() {
            TimerText.setText("Finished.");

        }
    }

}

And This is my layout code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.robert.scorecount.SecondActivity">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Timer Settings"
        android:id="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:textSize="20dp"
        android:textAlignment="center" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Start"
        android:id="@+id/StartButton"
        android:layout_marginBottom="37dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="00:00"
        android:id="@+id/Timer"
        android:textSize="30dp"
        android:layout_marginTop="88dp"
        android:layout_below="@+id/ThirtyMinMatch"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Stop"
        android:id="@+id/StopButton"
        android:layout_above="@+id/StartButton"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="30 Minutes"
        android:id="@+id/ThirtyMinMatch"
        android:layout_marginTop="24dp"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_toLeftOf="@+id/Timer"
        android:layout_toStartOf="@+id/Timer" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1 Hour"
        android:id="@+id/OneHourMinMatch"
        android:layout_alignTop="@+id/ThirtyMinMatch"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_toRightOf="@+id/Timer"
        android:layout_toEndOf="@+id/Timer" />

</RelativeLayout>

A: Your code:
TextView TimerText = (TextView) findViewById(R.id.Timer);

Change this line and just delete "TextView", it's already on top.
TimerText = (TextView) findViewById(R.id.Timer);


text:
Q: iTunes on Mac: How to use an external music library on a NAS (Windows share)? I have a large music collection of mp3-encoded CDs stored on a NAS (Windows share). I can access the drive via SMB on the Mac. I'd like to change my default iTunes music library without importing the files to the local disk.
Please could somebody describe the procedure how to change that in iTunes. I see some options, but I'm not sure and I don't want to jeopardize my collection. Are there any caveats?

A: Hold the option (alt) key when opening iTunes and you'll be prompted to either create a library or choose an existing library.
You can then select the iTunes library that you have stored on the NAS share.
This method may require that the NAS share contains a iTunes library file. If it does, then you might be able to copy the default one created when iTunes starts for the first time and move it over to the NAS share.
The when you add music to iTunes, it will be written to the library file stored on the NAS share. YOu can turn off the options to make iTunes keep you music organised and turn off the copy files to iTunes Music Folder to prevent it from moving or creating dupes of your music files.

A: Be aware that having movies on a remote drive causes big slowdowns when trying to scroll through them in Front Row.  It made me move them all back to a USB/Firewire disk, which is much speedier.


text:
Q: UWP - programmatically trigger a Windows PC Lock I have been searching for a while for how to trigger a screen lock on windows programmatically from a UWP app, but the only thing found from MSDN is this and it doesn't even trigger a lock screen event. It creates a new lock screen.
My use case is this: I verify users via a UWP i have developed. If for one user the verification fails, i want to trigger the PC lock for this user.
Is this even possible through a UWP?
Thank you in advance!

A: Currently, there is no such api that could take over lock screen within uwp platform. For Windows.ApplicationModel.LockScreen api that is use to let your app show an indicator on the lock screen, not for taking over the lock screen. For more info please refer link here.


text:
Q: vue multiselect not being selected when tracking by _id in edit mode I am using Vue multi-select with model as categories and options as categoriesList
categories: ["5ddc465a46a56b19d17e9a15"],
categoriesList: [ { "_id": "5ddc465a46a56b19d17e9a15", "name": "Business Card", } ]

multiselect v-model="categories"
class="form-control"
tag-placeholder="Add this as new tag"
placeholder="Search or add a tag"
label="name"
track-by="_id"
:options="categoriesList"
value-field="_id"
text-field="_id"
:multiple="true"
/>

In edit mode my model may have below data which should be resulted to select option from categoriesList  which exist with  model's  _id matching.
either

categories: [{_id:"5ddc465a46a56b19d17e9a15"}],

or

categories: ["5ddc465a46a56b19d17e9a15"],

https://jsfiddle.net/1amyk9u4/

A:

new Vue({
  components: {
    Multiselect: window.VueMultiselect.default
  },
  data: {
    categories: [],
    categoriesList: [{
      "_id": "5ddc465a46a56b19d17e9a15",
      "name": "Business Card",
      "updatedBy": "5db95c3c61d80ebe8ba560af",
      "createdBy": "5db95c3c61d80ebe8ba560af",
      "isActive": true,
      "isGlobal": true,
      "logo": "Categories/5ddc465a46a56b19d17e9a15",
      "updatedAt": "2019-12-01 04:29:36",
      "createdAt": "2019-11-25 21:23:38"
    }, {
      "_id": "5ddc465a46a56b19d17e9a16",
      "name": "Credit Card",
      "updatedBy": "5db95c3c61d80ebe8ba560af",
      "createdBy": "5db95c3c61d80ebe8ba560af",
      "isActive": true,
      "isGlobal": true,
      "logo": "Categories/5ddc465a46a56b19d17e9a15",
      "updatedAt": "2019-12-01 04:29:36",
      "createdAt": "2019-11-25 21:23:38"
    }]
  },
  created() {
    this.categories.push(this.categoriesList[0]);
  }
}).$mount('#app')
* {
  font-family: 'Lato', 'Avenir', sans-serif;
}

<link rel="stylesheet" href="https://unpkg.com/vue-multiselect@2.1.0/dist/vue-multiselect.min.css">

  <multiselect v-model="categories" class="form-control" v-model="categories" tag-placeholder="Add this as new tag" placeholder="Search or add a tag" label="name" track-by="_id" :options="categoriesList" :multiple="true" :taggable="true">
  </multiselect>

{{ categories }}


text:
Q: Помогите найти решение задачи на java Имеется  следующая задача:
В спортивном зале города N появилась штанга и набор блинов с различными массами.
Для занятия спортом необходимо распределить блины по двум концам штанги таким
образом, чтобы суммарный вес по оба конца штанги был одинаковый. Рассчитайте
максимальный вес, который смогут поднимать спортсмены при заданном наборе блинов
(с допущением, что гриф штанги невесомый).
Решение должно быть представлено в виде java-программы, у которой:
На входе: массив целых чисел, обозначающих веса блинов, входящих в набор.
На выходе: целое число, обозначающее максимальный вес, который можно поднять с
заданным набором блинов.
Примеры:

*

*
*

*На входе: [1,2,3,6]

*На выходе: 12

*Пояснение: можно нацепить блины {1,2,3} с одной стороны и блин {6} с другой, что в сумме даст 12.

*
*

*На входе: [1,2,3,4,5,6]

*На выходе: 20

*Пояснение: можно нацепить блины {2,3,5} с одной стороны и блины {4,6} с другой, что в сумме даст 20. Оставшийся блин {1} не может быть нацеплен ни с одной из сторон без потери равновесия.

*
*

*На входе: [1,2]

*На выходе: 0

*Пояснение: данный набор блинов невозможно нацепить без потери равновесия.

Ограничения:

*

*Блин может весить от 0 до 20 фунтов.

*В наборе может присутствовать от 1 до 1000 блинов.

*Суммарный вес целого набора не может превышать 10000 фунтов.

Сейчас учусь java и решаю задачи. Никак не могу найти подход к данной задачи. Помогите пожалуйста решить, или направьте мысль в нужное русло.

A: Например так
    List<Integer> weights = Arrays.asList(1, 2, 3, 6);

    int size = weights.stream()
            .mapToInt(x -> x)
            .sum() / 2 + 1;

    int[] arr = new int[size];
    arr[0] = 2;
    for (int weight : weights) {

        for (int i = size - 1; i >= 0; i--) {
            if (arr[i] > 0 && i + weight < size) {
                arr[i + weight]++;
            }
        }
    }
    for (int i = size - 1; i > 0; i--) {
        if (arr[i] >= 2) {
            System.out.println(i);
            break;
        }
    }

EDIT
Я все таки домучал. Решение получилось почти в лоб. Оно строит все возможные способы получить все возможные суммы. Затем находит наибольшую сумму у которой есть два не пересекающихся разложения.
public class App {

    public static void main(String[] args) {
        List<W> weights = Stream.of(1, 2, 3, 4, 5, 9)
                .map(W::new)
                .collect(Collectors.toList());

        Map<Integer, List<List<W>>> arr = new HashMap<>();
        arr.put(0, Collections.singletonList(Collections.emptyList()));
        for (W weight : weights) {
            arr = arr.entrySet().stream()
                    .flatMap(x -> {
                                int newWeight = x.getKey() + weight.value;
                                List<List<W>> newList = x.getValue().stream()
                                        .map(ArrayList::new)
                                        .peek(y -> y.add(weight))
                                        .collect(Collectors.toList());
                                return Stream.of(
                                        new Pair<>(newWeight, newList),
                                        new Pair<>(x.getKey(), x.getValue())
                                );
                            }
                    )
                    .collect(Collectors.toMap(
                            Pair::getIndex,
                            Pair::getValue,
                            (x, y) -> {
                                List<List<W>> r = new ArrayList<>(x);
                                r.addAll(y);
                                return r;
                            }));
        }

        arr.entrySet().
                stream()
                .sorted(Comparator.comparing(Map.Entry::getKey, Comparator.reverseOrder()))
                .filter(x ->
                {
                    for (List<W> a : x.getValue()) {
                        for (List<W> b : x.getValue()) {
                            if(a == b) continue;
                            if (a.stream().noneMatch(b::contains)) {
                                return true;
                            }
                        }
                    }
                    return false;
                })
                .map(Map.Entry::getKey)
                .findFirst()
                .ifPresent(System.out::println);
    }

    @Data
    static class Pair<T> {
        private final int index;
        public final T value;
    }

    @AllArgsConstructor
    @Getter
    static class W {
        public final int value;
    }
}

Класс W нужен чтобы различать блины с одинаковыми весами.


text:
Q: Move qq-upload-list to another part of page in fineuploader? I'm using the following setup for my fineuploader;
$('#jquery-wrapped-fine-uploader').fineUploader({
    request: {
        endpoint: '/Handlers/PhotoUploadHandler'
    },
    multiple: true,
    validation: {
        allowedExtensions: ['jpeg', 'jpg', 'gif', 'png'],
        sizeLimit: 5242880
    },
    button: $(".buttonUploader"),
    text: {
        uploadButton: '',
        dropProcessing: '',
        deleteButton: '',
        retryButton: ''
    }
...

I'd like to move the qq-upload-list  that gets generated to another part of the page
Is this possible from the declaration of fineUploader like I can for the button, or do I need to dig elsewhere?

A: If you are using UI mode, then the listElement option would be your solution.
By default, Fine Uploader will use the .qq-upload-list <ul> specified in the template option, but if you provide your own listElement Fine Uploader will use it instead.
$('#jquery-wrapped-fine-uploader').fineUploader({
    listElement: $("#your-custom-list-element"),
    request: {
        endpoint: '/Handlers/PhotoUploadHandler'
    },
    multiple: true,
    validation: {
        allowedExtensions: ['jpeg', 'jpg', 'gif', 'png'],
        sizeLimit: 5242880
    },
    button: $(".buttonUploader"),
    text: {
        uploadButton: '',
        dropProcessing: '',
        deleteButton: '',
        retryButton: ''
    }


text:
Q: Java: compareTo not sorting correctly I have this compareTo code for my list:
public int compareTo(className a)
{
    return (this.long1 > a.long1) ? 1 : -1;
}

When I use Collections.sort(list), I get the following error: Comparison method violates its general contract!
When I change it to if (this.long1 >= a.long2), it works, but it does not sort properly. The longs are sorted in order, then out of order, then in order. Using >=, the output looks like this:
...
2000100
2000101
2000102
1000100
1000101
2000101
2000102
...

Now, duplicates do happen, and they need to be sorted correctly. It doesn't matter if the duplicates appear first or last, as long as they're properly grouped in order, like so:
...
2000100
2000101
2000101
2000102
2000102
1000100
1000101
...

How would I do this properly? Thank you.
UPDATE
The list is still being sorted out of order with all of the below suggestions. Is this because it's a List<Class> list = new ArrayList<Class>();? I can't use what I'm used to from C#: List<Class> list = new List<Class>().

A: You should return 0 when the two numbers are equal, or just use Long.compare :
public int compareTo(className a)
{
    return Long.compare(this.long1,a.long1);
}

A: return (this.long1 > a.long1) ? 1 : -1;

If both numbers are equal, this returns -1, not 0.
return (this.long1 >= a.long1) ? 1 : -1;

Now 1 is equal, still not 0.
Correct:
if(this.long1 > a.long1) return 1;
if(this.long1 < a.long1) return -1;
return 0;

A: A correct solution would do this:
public int compareTo(className a) {
    return this.long1 > a.long1 ? 1 : this.long1 < a.long1 ? -1 : 0;
}


text:
Q: Matlab multiple type numbers in same table I want to put those two types of number inside one table. One column with index int64 and another column with value single....
1359410513
1359410521
1359410529
1359410536
1359410542
1359410548
1359410554

40.299999
39.099998
37.900002
36.799999
35.700001
34.700001
33.599998

But when I put them in one the value says is: 2000 X 2 int64. So all the values are cut away after dot. like this:
40
39
38
37
36
35
34

Can anyone help me with this? how to put them in one table. Thanks
Here is one example code...so basic idea is when one column is int64, the other is single. the result always converte one of them into the same type and the result lose resolution:
value1=int64(sort((1359418241-20)*rand(30,1)+20,'ascend'));
value2=single(rand(30,1));
field1='index';
field2='value';
s=struct(field1,value1,field2,value2)

data_table=struct2table(s);
data_cell=table2cell(data_table);
data_mat = cell2mat(data_cell(:, 1));
data_mat1 = cell2mat(data_cell(:, 2));

start_time=701146404;
end_time=1221278149;
%Find the neighbour points
thresholdpoint_start = find(data_mat > start_time, 1)-1;
thresholdpoint_end = find(data_mat >= end_time, 1);
for i=1:thresholdpoint_end-thresholdpoint_start+1
    data_ss(i,2)=single(data_mat1(thresholdpoint_start+i-1,1));
    data_ss(i,1)=data_mat(thresholdpoint_start+i-1,1);

end

A: The correct structure for data with different data types is the cell array. There is no way to do the same with a standard array (matrix). What you can do however is to put all your data into a double array, which has enough precision to correctly represent your integers.


text:
Q: Reducing number of XY points within distance of one another using Integrate tool in ArcGIS for Desktop? I have XY data (lat/lon) that I'm importing into ArcMap.  I need to reduce the data to eliminate points that are within a certain distance of one another.  For example, if two points are less than 1km apart, I want to only retain one.
I thought this could be done with Integrate, which did allow my to successfully collapse all points within 1km to single points on the map, but all the original points are still in the underlying attribute table.  Is there a way to create a new attribute table or shapefile with just these "collapsed" points that I see on the map?  If there is a better tool for this, I'd be happy to know but I haven't been able to find anything else nor any tips on how to extract these new points after using the Integrate tool.

A: You can run the Dissolve tool but you have to first calculate two fields that represent the X and Y of every points. Points with identical coordinates (i.e., those that have been moved into the same place after running the Integrate tool) will be dissolved into single points. You can choose how you want to handle the attributes of every point in the group of points that share the same spot.
Alternatively, there is a tool Collect Events that will create a single point from those points that share the same spot and will add a new attribute to the output feature class telling you how many points this "aggregated" point represents.


text:
Q: AS3 ByteArray " The supplied index is out of bounds" Error I'm working on an application and I need to save an AS3 object to a db.
Here's what I'm doing:
private function getComplete(e:Event)
{

    var getVars:URLVariables = new URLVariables(unescape(e.target.data));
    var _saveData_obj =  readObjectFromStringBytes( getVars.saveData);

    // do something with the save data....

}

public function SaveGame() {
    var _save_data:Object = _puzzle.dataForSaving;
    var _serialized_string = escape(serializeToString(_save_data));
    var _round_time = Math.round( _elapsed_time);
    var _token =  MD5.hash( _id +
                            _difficulty +
                            "mysomewhatsecretstringhere" +
                            _round_time );

    var request:URLRequest =
             new URLRequest( _home + 'savegame.php' );
    request.method = URLRequestMethod.POST;
    var variables:URLVariables = new URLVariables();
    variables.saveData = _serialized_string;
    variables.time = _round_time;
    variables.id = _id;
    variables.dif = _difficulty;
    variables.token = _token;
    request.data = variables;
    var loader:URLLoader = new URLLoader (request);
    loader.addEventListener(Event.COMPLETE, postComplete);
    loader.dataFormat = URLLoaderDataFormat.TEXT;
    loader.load(request);

}

public function LoadGame() {

    var request:URLRequest =
        new URLRequest( _home + 'loadgame.php?id='+_id+"&dif="+_difficulty);
    request.method = URLRequestMethod.GET;

    var loader:URLLoader = new URLLoader (request);
    loader.addEventListener(Event.COMPLETE, getComplete);
    loader.addEventListener(IOErrorEvent.IO_ERROR, netError);
    loader.dataFormat = URLLoaderDataFormat.TEXT;

    loader.load(request);

}

public static function serializeToString(value:Object):String{
    if(value==null){
        throw new Error("null isn't a legal serialization candidate");
    }

    var bytes:ByteArray = new ByteArray();
    bytes.writeObject(value);
    bytes.position = 0;
    trace ("Saved: "+bytes.length);
    var be:String = Base64.encodeByteArray(bytes);

    return be;
}

public static function readObjectFromStringBytes(value:String):Object {
    var result:ByteArray=Base64.decodeToByteArray( value) as ByteArray;
    result.position = 0;
    var the_obj:Object = result.readObject();
    return the_obj
}

The problem is that I keep getting a "The supplied index is out of bounds" error when I try to read the object from the Base64 string.... I checked if the saved string and the loaded string are the same. Tried to save the Base64 string to a shared object and retrieve it - that works fine ... the only problem is when I save and load to/from the server.
Can you guys help me? What am I doing wrong?
Thanks.

A: try using ba.writeMultiByte(string, 'utf-8') and ba.readMultiByte(ba.bytesAvailable, 'utf-8') without converting to object

A: Ok, so it looks like we've come to a series of steps you can take to debug what's going on.

*

*(In save game) make sure that unescape( variables ).saveData == _puzzle.dataForSaving. If this does not work, then your issue is with either escape or unescape. I have to admit

*

*I am suspicious here, you should never need to escape data for a POST once it has been Base64 encoded (as3crypto's Base 64 encoding will return only one of these characters: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=. Those are all legit in a POST) and your URLLoader should take care of making it a legit request, so I have difficulty seeing the need.

*It is more consistent (and more expected) to have escape and unescape both accept strings as parameters and return strings.

*Instead of storing to the database and then retrieving, store to $_SESSION (or, if possible, just echo the value back). This will eliminate PHP as a possible culprit.

*In PHP, make sure that $_POST['saveData'] == /* whatever you echo */. If it isn't, then you have a DB encoding issue. You need to make sure that whatever encoding is used in MySQL is the same as the one used in AS.

As an aside, when working with AS, you'll often find it easier to use $_REQUEST instead of $_POST or $_GET. Since the requests are more or less abstracted, the URLRequests of AS don't really need to worry about being RESTful, and it is a heck of a lot easier to work with than exclusively using POSTs.