text:
Q: Maven JavaDoc listed classes twice I am using the javadoc maven plugin and it creates the correct javadoc package, but all classes are created twice.
Maven dependency:
        <dependency>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>3.3.0</version>
    </dependency>

My build code
<build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-javadoc-plugin</artifactId>
                    <executions>
                        <execution>
                            <id>attach-javadocs</id>
                            <goals>
                                <goal>jar</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>

Can anyone help me please, what am I missing here?

command usage for doc generation
mvn clean install -Dresources="FirstProject/example_API"

A: I noticed the same problem and came upon a solution after enabling debug on the maven-javadoc-plugin maven plugin and seeing what it's doing. Specifically setting the sourcepath as shown below fixed the double listing problem for me and I've tried this on multiple version of Corretto 8 as well as Temurin 8. All had the double listing problem because it's an issue with the javadoc tool itself but setting the sourcepath manually fixed it for me.
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-javadoc-plugin</artifactId>
    <version>3.3.1</version>
    <configuration>
        <debug>true</debug>
        <sourcepath>${basedir}/src/main/java</sourcepath>
    </configuration>
    <executions>
        <execution>
            <id>attach-javadocs</id>
            <goals>
                <goal>jar</goal>
            </goals>
        </execution>
    </executions>
</plugin>

A: There's a bug in recent versions of the Maven Javadoc Plugin. The bug is known as MJAVADOC-700. It is dead easy to reproduce.
Downgrading to version 3.2.0 of the plugin fixes the problem. Setting the sourcepath explicitly is an alternative fix.


text:
Q: Textfield issue in IOS I have a textfield in my view controller under the textfield I have used a table view to show data in it and when we click any data from table view it shows in the textfield. Now when I press any cell of table view to show that data in text field it shows fine but textfield do not catch the data from table view it only send data manually written on the textfield. it shows me this in console,
<UITableViewCell: 0x7f9dad0a1000; frame = (0 132; 342 44); text = '2014'; autoresize = W; layer = <CALayer: 0x60400022ec20>>

My code is this,
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView==_year01) {
    return [year1Array count];
}else if (tableView == _carTable){
    return [carArray count];
}
return YES;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (tableView == _year01){
    cell.textLabel.text=[year1Array objectAtIndex:indexPath.row];
}else if (tableView == _carTable){
    cell.textLabel.text=[carArray objectAtIndex:indexPath.row];
}

cell.backgroundColor=[UIColor darkGrayColor];
cell.textLabel.textColor=[UIColor whiteColor];

 return cell;

}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *selectedCell=[tableView cellForRowAtIndexPath:indexPath];
NSLog(@"Cell %@",selectedCell);
if (tableView == _year01){
    self.year1.text=[year1Array objectAtIndex:indexPath.row];
    self.year01.hidden=YES;
}else{
    self.carName.text=[carArray objectAtIndex:indexPath.row];
    _carTable.hidden=YES;
    [_carName resignFirstResponder];
}
}

Code to manage spaces in textfield is this,
-(void)textFieldDidChanges :(UITextField *)theTextField{
result=self.carName.text;
result=[result stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSLog(@"RRR %@",result);
//just use this result where you want
}

Sending data to the next view,
- (IBAction)okay:(id)sender {

if ([_carName.text isEqualToString:@""] || [_year1.text isEqualToString:@""] || [_year2.text isEqualToString:@""] ) {

    NSString *message = @"Fill all the fields";

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Enter Data"
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];

    [self presentViewController:alert animated:YES completion:nil];

    int duration = 2; // duration in seconds

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        [alert dismissViewControllerAnimated:YES completion:nil];
    });

    _guideView.hidden=YES;
}else{

NSString *strAppend = [NSString stringWithFormat:@"%@-%@",_year1.text,_year2.text];
NSLog(@"%@",strAppend);

[[NSUserDefaults standardUserDefaults] setObject:result forKey:@"name"];
[[NSUserDefaults standardUserDefaults] setObject:strAppend forKey:@"year"];
[[NSUserDefaults standardUserDefaults] synchronize];
}

}

A: Empty your text field before assigning a new value in didSelectRow.
if (tableView == _year01)
{
   self.year1.text=@"";

   self.year1.text=[year1Array objectAtIndex:indexPath.row];
   self.year01.hidden=YES;
}
else
{
   self.carName.text=@"";

   self.carName.text=[carArray objectAtIndex:indexPath.row];
   _carTable.hidden=YES;
  [_carName resignFirstResponder];

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does that the current draft permit to form an overload set that consists of two non-static member declarations where one has ref-qualifier The basic.scope#scope-3.3.1 says

both declare functions with the same parameter-type-list, equivalent ([temp.over.link]) trailing requires-clauses (if any, except as specified in [temp.friend]), and, if both are non-static members, the same cv-qualifiers (if any) and ref-qualifier (if both have one)

The above rule could be understood to,  For two non-static member functions with the same parameter-type-list, if anyone has a cv-qualifiers then both declarations should have the same cv-qualifiers; if both declarations have ref-qualifier, they should have the same ref-qualifier. Otherwise, they do not correspond.
struct A{
    void show();  //#1
    void show() const &;  //#2
};

In this snippet, Does #1 correspond to #2? Since #2 has a cv-qualifier but #1 does not have, even if the condition for having the same  ref-qualifier is true, as per the rule(note the emphasized and  in that rule), they do not correspond. So, Does it mean that the draft permits to form an overload set from such two declarations? After all, the section over.load#2.3 was removed by P1787.

A: This change was an inadvertent result of phrasing the rules more orthogonally, but since that orthogonality allows a few additional meaningful overload sets, there hasn't been any hurry to "fix" it.  In particular, it might work well with the proposal for deducing this that's currently under consideration.


text:
Q: Deployment to Production Org using VS Code I need one help to deploy different components like classes, triggers, objects, profiles, permission sets, etc from sandbox to the production org.
I used following command to deploy all the items on the production. But I noticed that it only validates the changes and is not giving any option to deploy the components
sfdx force:source:deploy -m ApexClass:TestUtility -l RunLocalTests -c -w 3 -u myProdUserName

I read different blogs and found that we can use the command "sfdx force:mdapi:deploy" for the deployment. But, I didn't get the exact syntax/procedure or any option in the VS Code which allow deploying all the components on the production.

A: You should read through the documentation on force:source:deploy again
The reason why you're only validating the changes is because that's exactly what you're telling sfdx to do when you use the -c flag

-c | --checkonly
  Optional
Validates the deployed metadata and runs all Apex tests, but prevents the deployment from being saved to the org.

Further, when using the -m flag, you're either deploying everything in your project of a particular metadata type (when you use, for example -m ApexClass), or only deploying specific components (when you use -m ApexClass:MyClass, only MyClass is deployed)
Put into words, that command you're currently running says...

deploy the testUtility class (-m ApexClass:testUtility) to myOrgName (-u myOrgName), but only verify the changes (-c). Run all local tests (-l RunLocalTests), and stop listening for updates if the operation takes more than 3 minutes (-w 3)

Using the -p flag to specify a path to deploy to is probably the easiest way to do what you're describing. Using it and pointing to the "force-app" folder would deploy everything in your project unless you've done some serious modification to your project structure.

A: If you use -c , note that the command will just validate it.
I suggest you use the Visualstudio For Salesforce extension and deploy using the deploy to source option as shown below

If you are using CLI then you have to add all the metadata and be specific in format as shown below and it will be tedious exercise instead just deploy by clicking on the path.
sfdx force:source:deploy -m ApexClass, Profile:myprofile, ApexTrigger -l RunLocalTests -w 10 -u myProdUserName
Note do not put -c there as it will only validate.


text:
Q: opencv - rgb value keeps changing I'm having some problem with the rgb or in opencv bgr
What I'm trying to do is find the overall value of the bgr of a certain pictures
but every time I run the program without changing anything with exact same pictures the values of the bgr keeps changing..
This is how i coded to find the values of bgr
#include <opencv\cv.h>
#include <opencv\highgui.h>

using namespace std;
    char path[255];

int main( int argc, char** argv )
{
    IplImage *red[50];
    IplImage *green[50];
    IplImage *blue[50];

    for(int i = 1; i <= 50; i++)
    {
        IplImage *img;
        sprintf(path, "C:\\picture (%01).bmp", i);
        img = cvLoadImage(path);
        red[i] = cvCreateImage(cvGetSize(img), 8, 1);
        green[i] = cvCreateImage(cvGetSize(img), 8, 1);
        blue[i] = cvCreateImage(cvGetSize(img), 8, 1);
        cvSplit(img, blue[i], green[i], red[i], NULL);
        cvReleaseImage(&img);

        int total = (int)(blue[i]) + (int)(green[i]) + (int)(red[i]);
        cout << total << endl;
        cvWaitKey(1);
    }
cvWaitKey(0);
return 0;
}

A: I am not sure how did you achieve type casting from IplImage to int
int total = (int)(blue[i]) + (int)(green[i]) + (int)(red[i]);

but you certainly need to use pixel by pixel summation for each channel (not image by image) to find the overall values.

A: Try using two loops instead of one, one for loading the images and the other for performing your operation, and let me know if it works..


text:
Q: How to include blank value in Former::select I'm using the Former package for Laravel 4, along with TwigBridge.  I have a select field that I'm populating with a model:
{{ former_select('parent_id').fromQuery(sections, 'title', 'id') }}

However, I'd also like to add a blank value as the default option.  I've looked through the docs but could not see anything that mentioned this.
Can anyone help?
Thanks

A: It was actually quite simple.  Just use the addOption method and leave the parameters blank
{{ former_select('parent_id').addOption().fromQuery(sections) }}

A: For Former version 2.6.0 I had to use the 'placeholder' method
{{ Former::select('author_id')->placeholder('Please select')->label('author')->fromQuery(Author::get(), 'username', 'id') }}


text:
Q: Design: Object with single use? Context
I have a class called ImageLoader.
When I call ImageLoader's getPicture( pictureID ), if the picture is not cached, I store pictureID in an instance variable, create a new thread which eventually calls my callback() function in this same ImageLoader class.  callback() then uses this pictureID as the key to cache the picture.
Problem
Do you see the pickle?
If I call getPicture( somePictureID ) twice in a row, and the callback() function for the first call hasn't happened yet, I will overwrite the previous pictureID which the callback() function will use. (See the code below if you still don't see the pickle.)
Now I know you're thinking, why don't I just add a little synchronization on the variable to make it thread-safe?
Because who knows how long the thread querying the picture will take, and that could really slow down the whole process of loading multiple images.
How I'm Thinking of Solving It
So my bright idea is to create an inner class that servers as a slave and only has a single use.  I execute some function in this slave class once, and I never reuse the object.
Question
Is this an appropriate approach to solving this kind of problem? I feel like this might fall into some pattern I'm not aware of. If I'm totally off the mark with this one, can you suggest another solution?
Simplified Code
//the instance variable with a race condition
private int pictureID

//loads the image associated with the pictureID
public void getPicture( int pictureID )
{
     Bitmap bitmap = cache.get( pictureID );
     if ( bitmap != null )
     {
         //load image
         return;
     }

     int post_params[] = { pictureID, /* more parameters */ };

     this.pictureID = pictureID; //PROBLEM: race condition!
     new HttpRequest( this ).execute( post_params ); //starts new thread and queries server
}

 //gets called when the query finishes, json contains my image
 public void callback( JSONObject json )
 {
    Bitmap bitmap = getBitmap( json ); //made up method to simplify code
    cache.put( this.pictureID, bitmap ); //PROBLEM: race condition!

    //load image
 }

A: To me this looks like a classic case of the Memoizer pattern, and the easiest way to use it is probably Guava's CacheBuilder, something like:
private LoadingCache<Integer, Image> cache = CacheBuilder.newBuilder().
        build(new CacheLoader<Integer, Image>() {
            @Override
            public Image load(Integer key) throws Exception {
                return httpGetImageExpensively(key);
            }
        });

public Image getPicture(int pictureId) {
   return cache.getUnchecked(pictureId); // blocks until image is in cache
}

Now, the HTTP request will happen in the first thread that calls getPicture() for a given ID; subsequent callers with that ID will block until the first thread has put the image in cache, but you can make multiple concurrent requests for different IDs.
Things to think about:

*

*How slow is loading going to be? Do you need a timeout mechanism?

*What if the loading fails? The cache.get() method throws a (checked) ExecutionException, which is why I'm using getUnchecked() instead, but that just throws an (unchecked) UncheckedExecutionException instead. If possible, I would do most of the error handling in httpGetImageExpensively(), and think through the possible cases there (bad ID, DNS failure, etc.) but the callers of getPicture() will still need to deal with that somehow.

*If loading a given ID fails once, is it going to fail every time? If so, you probably don't want to waste time re-HTTP-GETting it every time, and you need to add a mechanism for that. Note though that the question of whether it's worth retrying may have a different answer for different types of failure.

*This implementation blocks each calling thread until there's an image ready for it. Is that workable for this application? If not, you may want to replace getPicture() with something a little fancier that takes an image handler callback object or lambda, and then internally put the actual calls to httpGetImageExpensively() on an ExecutorService, so getPicture() can return immediately. (Depending on the application, there may be other issues, e.g. in a Swing app it might be desirable to invoke the callback on the event dispatch thread.)

A: A thought besides: Thread creation is expensive.

*

*Create a thread pool (The Java API has support for this: http://docs.oracle.com/javase/tutorial/essential/concurrency/pools.html)

*Derive the Runnable class to implement your "task".

*Submit your Runnables to the Thread Pool Executor service.
pictureID should be an instance variable of for your Runnable-derived class. Your Runnable-derived class can be (but needn't be) implemented as inner class of your ImageLoader class.
EDIT: Example.
some_perhaps_inner_class MyRunable implements Runnable {
    private int someImportantId;

    MyRunnable(int someImportantId) {
        this.someImportantId = someImportantId;
    }

    @Override
    public void run() {
        doTheTimeConsumingStuffHere();
    }
}

ExecutorService myThreadPool = Executors.newFixedThreadPool(3);
myThreadPool.submit(new MyRunnable(someImportantId));

Details depend on your special needs. Take a look in the Java API to read further.

A: Rather than dealing with callbacks, this returns a Future of the bitmap that you can block on until it's ready. If you depend on multiple bitmaps and don't want to block separately on all of them, I'd retrofit this to work with Guava Futures.
public class AsyncMemoizingImageLoader {
    private final ConcurrentMap<Integer, Future<Bitmap>> bitmaps = new ConcurrentHashMap<>();
    private final ExecutorService executor = Executors.newFixedThreadPool(8);

    // TODO: shutdown executor when complete

    public Future<Bitmap> getPicture(final int pictureID) {
        if (!bitmaps.contains(pictureID)) {
            RunnableFuture<Bitmap> future = new FutureTask<Bitmap>(new Callable<Bitmap>() {
                @Override public Bitmap call() throws Exception {
                    // HTTP stuff goes here.  pictureID is accessible in this scope
                }
            });

            // This bit is key; only submit the future for completion if the
            // picture id isn't already being processed
            if (bitmaps.putIfAbsent(pictureID, future) == null) {
                executor.submit(future);
            }
        }

        return bitmaps.get(pictureID);
    }
}

A: How HttpRequest knows which picture we need? We do not send any information about it (pictureId is private field). If it is not related (pictureId - requested picture) just use priority queue.
//queue contains pictures id queue to load
private Queue<Integer> pictureIDQueue = new LinkedList<Integer>();

//loads the image associated with the pictureID
public void getPicture( int pictureID )
{
     Bitmap bitmap = cache.get( pictureID );
     if ( bitmap != null )
     {
         //load image
         return;
     }

     synchronized(pictureIDQueue)
     {
         this.pictureIDQueue.add(pictureID);
     }
     new HttpRequest( this ).execute(); //starts new thread and queries server
}

 //gets called when the query finishes, json contains my image
 public void callback( JSONObject json )
 {
    Bitmap bitmap = getBitmap( json ); //made up method to simplify code

    synchronized(pictureIDQueue)
    {
        cache.put( this.pictureIDQueue.poll(), bitmap );
    }
    //load image
 }

A: You could also try something like this:
private Map<Integer, Bitmap> cache = new HashMap<Integer,Bitmap>();
private Queue<Thread> threads = new LinkedList<Thread>();
//the instance variable with a race condition
private int pictureID;

//loads the image associated with the pictureID
public void getPicture(final int pmPictureID )
{
     Bitmap bitmap = cache.get( pictureID );
     if ( bitmap != null )
     {
         //load image
         return;
     }

     int post_params[] = { pictureID, /* more parameters */ };
     final ImageLoader instance = this;

     Thread currentThread = new Thread()
     {
         @Override
         public void run()
         {
             pictureID = pmPictureID;
             new HttpRequest(instance).execute( post_params ); //starts new thread and queries server
         }
     };

     if(threads.size() > 0)
     {
         threads.add(currentThread);
     }
     else
     {
         currentThread.start();
     }
}

 //gets called when the query finishes, json contains my image
 public void callback( JSONObject json )
 {
    Bitmap bitmap = getBitmap( json ); //made up method to simplify code
    cache.put( this.pictureID, bitmap ); //PROBLEM: race condition!

    if(threads.peek() != null)
    {
        threads.poll().start();
    }
    //load image
 }


text:
Q: disable anti-aliasing for UIBezierPath I need to render UIBezierPaths without anti-aliasing and then save them as PNG to retain the full pixel representations (for example, not let JPEG muck the image up). I've tried calling the CG functions below just before stroking the UIBezierPaths, but it seems none have any effect on the resultant rendered image. The paths are still rendered with anti-aliasing (i.e. smoothed).
CGContextSetShouldAntialias(c, NO);
CGContextSetAllowsAntialiasing(c, NO);
CGContextSetInterpolationQuality(c, kCGInterpolationNone);

Any hits would be greatly appreciated.

A: Where are you getting c from? Are you certain that c refers to the same thing as UIGraphicsGetCurrentContext() in the drawing cycle that you use [UIBezierPath stroke]? It's difficult to tell from the above sample.
If you want to be certain that you're drawing to the same context that you're configuring, fetch the CGPath from the UIBezierPath, and draw it directly:
- (void)drawRect:(CGRect)rect {
  CGContextRef context = UIGraphicGetCurrentContext();
  CGPathRef path = [self.bezier CGPath];
  CGContextSetShouldAntialias(context, NO);
  CGContextAddPath(context, path);
  CGContextStrokePath(context);
}

A: When I use those options, it turns off antialiasing. On the left is with the default options. On the right, with your options.

This is easy to control if you're using a UIView subclass. This is my drawRect:
- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetShouldAntialias(context, NO);

    [[UIColor redColor] setStroke];
    UIBezierPath *path = [self myPath];
    [path stroke];
}

And to capture the screen, from How to take a screenshot programmatically
- (void)captureScreen
{
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
        UIGraphicsBeginImageContextWithOptions(self.window.bounds.size, NO, [UIScreen mainScreen].scale);
    else
        UIGraphicsBeginImageContext(self.window.bounds.size);
    [self.window.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData *data = UIImagePNGRepresentation(image);
    [data writeToFile:[self screenShotFilename] atomically:YES];
}

If you're using a CAShapeLayer, then I don't think you can control the antialiasing on screen, because as the documentation says:

The shape will be drawn antialiased, and whenever possible it will be mapped into screen space before being rasterized to preserve resolution independence. However, certain kinds of image processing operations, such as CoreImage filters, applied to the layer or its ancestors may force rasterization in a local coordinate space.

But, regardless of the antialiasing on screen, if you want to have your snapshot of the screen not be antialiased, you can insert your CGContextSetShouldAntialias into the captureScreen routine:
- (void)captureScreen
{
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
        UIGraphicsBeginImageContextWithOptions(self.window.bounds.size, NO, [UIScreen mainScreen].scale);
    else
        UIGraphicsBeginImageContext(self.window.bounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetShouldAntialias(context, NO);
    [self.window.layer renderInContext:context];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData * data = UIImagePNGRepresentation(image);
    [data writeToFile:[self screenShotFilename] atomically:YES];
}


text:
Q: Can't load bootstrap css file I'm creating a django project in pycharm and I'm trying to use bootstrap blog example(https://getbootstrap.com/docs/4.4/examples/blog/). I came across a problem: bootstrap.min.css file is not working properly, when I link it like this it works properly,
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

but when I download this file then save it in my_app/static/my_app/bootstrap.min.css and link it like this,
<link rel="stylesheet" href="{% static 'blogs/bootstrap.min.css' %}" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

it doesn't work, the django development server is properly loading the css file
[14/Jan/2020 19:04:26] "GET /static/blogs/bootstrap.min.css HTTP/1.1" 304 0

but it just doesn't have any effect on the site apperance, the blog.css file does have effect as I can see fonts and a few thing change but the bootstrap.min.css file just doesn't.

A: Try to log your path if it return where your bootstrap.min.css file exists.
Then check if your browser's cache is clear if not then give it a try.

A: I checked the console in browser, as @tao said, turns out the problem was the
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"

in
<link rel="stylesheet" href="{% static 'blogs/bootstrap.min.css' %}" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

Thank your for your help


text:
Q: Median Value + Mode for Hybrid Functions of a Continuous Probability Density Function
To find the median:
should I set the integral to 0.5.... but because there are two functions that are non-zero, I am unaware of a method to find the median.
To find the mode:
would I need to derive each function that is non-zero, set this to zero and solve for x. Then sub the values of x back into f(x) for each non-zero function. I will select the x value that produced the largest f(x).

A: The area (probability) up to $0$ is $(1)(0.2)$, which is $0.2$. To get to area $0.5$, we need another $0.3$. So if $m$ is the median then
$$\int_0^m (0.2+1.2x)\,dx=0.3.$$
The rest is calculation. We could also solve the problem geometrically.
For the mode, graph the density function. It reaches its maximum at $1$.

A: Hint (to find median):$$0.5=\int_m^{\infty}f(x)dx=\int_m^1(0.2+1.2x)dx$$

A: Calculating the Mode:
You can see, that the function in the three intervals has no relative extremum. Thus you have to examine the bounderies.


text:
Q: Ajax entire page - display only one div and retain CSS and other header material? A client wants a merch shop on their site, and has set one up.  I could iFrame in the whole page to the merch page, but frankly the merch site is an eyesore, and their site has a very particular feel to it.  So I'm considering using an AJAX GET to grab the whole page, then javascript to display only the div with the merchandise in it.  However, there are a lot of javascript includes (etc) on the merch site that I'd need to make sure are still present for the div to work correctly.
Any feeling on if this would work or not?  Would the displayed div take its stylesheet and scripts from the AJAX'd page?  Can I put the div in an iframe instead?
Opinions?

A: It sounds like an ugly solution. Isn't it better to do this serverside instead, for example let a PHP script read in the page and to whatever magic it takes to display it?
Using AJAX to load entire pages is ugly for a couple of reasons, including:

*

*It breaks the URLs (can be worked around but requires extra work)

*It's hard for search engines to crawl your site

*It breaks some GUI elements in the browser, such as loading visualisations

A: looks like you can use jquery load function http://docs.jquery.com/Ajax/load


text:
Q: How to configure aws-sdk in Angular 7 When I do
npm install  aws-sdk

in Angular 7, I get an error

Error TS2580: Cannot find name 'Buffer'.
Do you need to install type definitions for node? Try npm i @types/node

and even though I do run install  npm i @types/node, I am still getting the same error:

A: Please modify your files as follows:
// aws-sdk requires global to exist
(window as any).global = window;

to /src/polyfills.ts
and
"types": ["node"]

to compilerOptions block in /src/tsconfig.app.json
credit to: afaneh262

A: To resolve this issue, you can try to add in your tsconfig.app.json the following line:
"types": ["node"]

Angular is complaining because some node environment types are needed.

A: You need to make a change in tsconfig.app.json file first inside compilerOptions as follows:
"types": ["node"]

After that, add a code in polyfills.js file. Otherwise you will get an error later (ReferenceError: global is not defined). Here is the code:
(window as any).global = window;


text:
Q: Selecting best combination of worker set that are capable to perform given set of tasks I have a set of workers W1, W2... Wn each with different capabilities/skillsets. I have a set of tasks T1, T2... Tn.

*

*T1 can be performed by W1 and W2

*T2 can be performed by W1

*T3 can be performed by W1, W2, W3

*T4 can be performed by W2

The tasks T1, T2, T3 and T4 HAVE to be done sequentially and it is fine if some workers are IDLE. In this case, the best worker set combination that are capable of performing all the tasks is {W1 and W2}. Is there an algorithm that can identify such a best fit combination?
I have looked into Set Cover Problem. By representing the problem as a 2D matrix with Tasks as Rows and Workers as Columns:
1   1   1   0
1   0   1   1
0   0   1   0
Identifying the minimal number of rows so that the union of those subsets is everything, i.e. so that all columns are represented is a NP hard problem. My question is if it really is a Set Cover problem or am I looking at it in the wrong direction? Are there other algorithms that help finding near-optimal solutions to these problems?


text:
Q: ¿Cual es el mejor lugar para guardar una contraseña dentro de una app Android? Estoy desarrollando una app y necesito consumir un WebService, antes de realizar el envío debo encriptar la información con una contraseña que solo el servidor y la app móvil conocen, esta contraseña me ayudará para poder encriptar y desencriptar el mensaje del servidor. ¿Cual sería el mejor lugar para guardar la contraseña? De tal manera que si alguien quiere hacer ingeniera inversa con el APK, la contraseña no sea visible y no pueda leer los mensajes del servidor.

A: Tu contraseña debe ser guardada en tu Base de datos almacenada en tu WS y suponiendo que unirás tu app android con el webservice mediante PHP puedes guardar la contraseña en formato SHA1 y así se guardará encriptada en tu base de datos, por ejemplo tu clave es 12345 en la base de datos se guardará como 8cb2237d0679ca88db6464eac60da96345513964
Nota: si quieres indagar mas en el tema mira aquí este enlace para que entiendas mas el tema.


text:
Q: Contact Form forms id I created a form on my local environment which I needed to use on the live site. I followed Contact Form documentation for exporting importing the forms:
https://contactform7.com/faq/how-can-i-export-import-contact-form-data/
Forms are imported correctly, however, with different ids. I need to keep the same id, because I use them to show the forms.
Why does CF imports the forms with different ids?
Solution?
Thank you.

A: Usually databases tend to generate unique ids, try changing that to a set variable and assign a specific value.


text:
Q: How to separate two different arrays in one loop? I want to separate in this way a -> num and b -> num2
But I can't add another part of the variable to the for loop, for (auto& i, i2 : arr, arr2)
Are there other ways to do this?
#include <charconv>

int64_t a = 123567893,
        b = 85162,
        test = 0,
        test2 = 0;

    string arr = to_string(a),
           arr2 = to_string(b),
           num,
           num2 ;

    for (auto& i : arr, arr2)
    {
        num.push_back(i);
        num2.push_back(i);
        cout << i;
        // cout << i2;
    }

    from_chars(num.data(), num.data() + num.size(), test);
    from_chars(num2.data(), num2.data() + num2.size(), test2);

    cout << "\n" << test << endl;
    cout << "\n" << test2 << endl;

A: You can use boost
#include <boost/range/combine.hpp>
#include <iostream>
#include <vector>

using namespace std;

int main() {
    std::string arr = "ABC";
    std::string arr2 = "XYZ";
    std::string num, num2;
    assert(arr.size() == arr2.size());
    for (const auto &i : boost::combine(arr, arr2)) {
        decltype(arr)::value_type a;
        decltype(arr2)::value_type b;
        boost::tie(a, b) = i;
        num.push_back(a);
        num2.push_back(b);
        cout << a;
        cout << b;
    }
}

Output is
AXBYCZ

I don't know if there is a solution for range-based for loops without boost . Of course, you could
#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

int main() {
    std::string arr = "ABC";
    std::string arr2 = "XYZ";
    std::string num, num2;
    for (unsigned int i{0}; i < std::max(arr.size(), arr2.size()); ++i) {
        if (i < arr.size()) num.push_back(arr[i]);
        if (i < arr2.size()) num2.push_back(arr2[i]);
        if (i < arr.size()) cout << arr[i];
        if (i < arr2.size()) cout << arr2[i];
    }
}

A: This here
for (auto& i : arr, arr2)

Won't work because that's not what the comma operator does. You can read about the comma operator here. In short, arr, arr2 returns arr2 so for (auto& i : arr, arr2) is equivalent to for (auto& i : arr2).
Instead, since arr and arr2 are std::string, you can just concatenate them with +:
for (auto& i : arr + arr2)
{
    num.push_back(i);
}

A: Why not this
for_each(arr.begin(),arr.end(), [&num](char c) {num.push_back(c);})
for_each(arr2.begin(),arr2.end(), [&num](char c) {num.push_back(c);})


text:
Q: Training the saving deep learning model in Pytorch I have a deep learning model in pytorch (here I provide a simple overview of that). Since I have to run the model each day. I want to save the model in the previous day and then I train the saved model for small number of epochs (3-4) epochs more. Here is the model:
class NET(nn.Module):

    def forward(self, y, par):

    def test(self, y, num_samples):

def train_batch(model, optimizer, device):
    model.train()
    optimizer.zero_grad()
    length = float(batch.size(0))
    ...
    return loss1

def trainv(model, device, epochs, train_iterator, optimizer, validate_iterator):

    for epoch in range(epochs):

        for local_batch, local_labels in train_iterator:

            train_loss = train_batch(model, optimizer, device)

        validate_loss = runs_for_validate(validate_iterator, n_samples)  # check on validate data

    return train_losses, validate_loss

model              = NET(inputs).to(device)

optimizer          = torch.optim.Adam(model.parameters(), lr =learning_rate )

train_losses, validate_loss = train(model, device, epochs, train_iterator, optimizer, validate_iterator)

My problem is that I dont know how to save the model and then again loading the saved model to train with more epochs.
previously I could save the model.state_dict() in '.pt' and can load it, but it seems it does not work here. I already saw this post, How can I save my training progress in PyTorch for a certain batch no.? , however I dont know which format I should save the model? and also when I should save the model? Could you please help me with this?

A: You can save the entire model, including the model architecture and its current state, by passing in the model object to the function.
torch.save(model, "model.pt")

You can save the model's state dictionary, which contains the model's parameters, separately.
torch.save(model.state_dict(), "model_state.pt")

You can load the model by using the torch.load function, passing in the path of the saved model.
model = torch.load("model.pt")

You can also load the state dictionary separately and use it to load the model's parameters.
state_dict = torch.load("model_state.pt")
model.load_state_dict(state_dict)

you can try like
class NET(nn.Module):
    def __init__(self, inputs):
        super(NET, self).__init__()
        self.inputs = inputs

    def forward(self, y, par):
        # Your forward pass here
        pass

    def test(self, y, num_samples):
        # Your test function here
        pass

def train_batch(model, optimizer, device):
    model.train()
    optimizer.zero_grad()
    length = float(batch.size(0))
    ...
    return loss1

def trainv(model, device, epochs, train_iterator, optimizer, validate_iterator, save_path):

    best_loss = float('inf')

    for epoch in range(epochs):

        for local_batch, local_labels in train_iterator:
            train_loss = train_batch(model, optimizer, device)

        validate_loss = runs_for_validate(validate_iterator, n_samples)  # check on validate data

        # Save the model if the validation loss improves
        if validate_loss < best_loss:
            best_loss = validate_loss
            torch.save(model.state_dict(), save_path)
    return train_losses, validate_loss

def load_model(model, load_path, device):
    state_dict = torch.load(load_path, map_location=device)
    model.load_state_dict(state_dict)
    return model

# Initialize the model
model = NET(inputs).to(device)

# Load the model if a save path is provided
if load_path is not None:
    model = load_model(model, load_path, device)

optimizer = torch.optim.Adam(model.parameters(), lr =learning_rate )

train_losses, validate_loss = trainv(model, device, epochs, train_iterator, optimizer, validate_iterator, save_path)


text:
Q: NSString is empty How do you test if an NSString is empty? or all whitespace or nil? with a single method call?

A: I use,
+ (BOOL ) stringIsEmpty:(NSString *) aString {

    if ((NSNull *) aString == [NSNull null]) {
        return YES;
    }

    if (aString == nil) {
        return YES;
    } else if ([aString length] == 0) {
        return YES;
    } else {
        aString = [aString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
        if ([aString length] == 0) {
            return YES;
        }
    }

    return NO;
}

+ (BOOL ) stringIsEmpty:(NSString *) aString shouldCleanWhiteSpace:(BOOL)cleanWhileSpace {

    if ((NSNull *) aString == [NSNull null]) {
        return YES;
    }

    if (aString == nil) {
        return YES;
    } else if ([aString length] == 0) {
        return YES;
    }

    if (cleanWhileSpace) {
        aString = [aString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
        if ([aString length] == 0) {
            return YES;
        }
    }

    return NO;
}

A: I hate to throw another log on this exceptionally old fire, but I'm leery about editing someone else's answer - especially when it's the selected answer.
Jacob asked a follow up question: How can I do this with a single method call?
The answer is, by creating a category - which basically extends the functionality of a base Objective-C class - and writing a "shorthand" method for all the other code.
However, technically, a string with white space characters is not empty - it just doesn't contain any visible glyphs (for the last couple of years I've been using a method called isEmptyString: and converted today after reading this question, answer, and comment set).
To create a category go to Option+Click -> New File... (or File -> New -> File... or just command+n) -> choose Objective-C Category. Pick a name for the category (this will help namespace it and reduce possible future conflicts) - choose NSString from the "Category on" drop down - save the file somewhere. (Note: The file will automatically be named NSString+YourCategoryName.h and .m.)
I personally appreciate the self-documenting nature of Objective-C; therefore, I have created the following category method on NSString modifying my original isEmptyString: method and opting for a more aptly declared method (I trust the compiler to compress the code later - maybe a little too much).
Header (.h):
#import <Foundation/Foundation.h>

@interface NSString (YourCategoryName)

/*! Strips the string of white space characters (inlcuding new line characters).
 @param string NSString object to be tested - if passed nil or @"" return will
     be negative
 @return BOOL if modified string length is greater than 0, returns YES;
 otherwise, returns NO */
+ (BOOL)visibleGlyphsExistInString:(NSString *)string;

@end

Implementation (.m):
@implementation NSString (YourCategoryName)

+ (BOOL)visibleGlyphsExistInString:(NSString *)string
{
    // copying string should ensure retain count does not increase
    // it was a recommendation I saw somewhere (I think on stack),
    // made sense, but not sure if still necessary/recommended with ARC
    NSString *copy = [string copy];

    // assume the string has visible glyphs
    BOOL visibleGlyphsExist = YES;
    if (
        copy == nil
        || copy.length == 0
        || [[copy stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0
        ) {
        // if the string is nil, no visible characters would exist
        // if the string length is 0, no visible characters would exist
        // and, of course, if the length after stripping the white space
        // is 0, the string contains no visible glyphs
        visibleGlyphsExist = NO;

    }
    return visibleGlyphsExist;

}

@end

To call the method be sure to #import the NSString+MyCategoryName.h file into the .h or .m (I prefer the .m for categories) class where you are running this sort of validation and do the following:
NSString* myString = @""; // or nil, or tabs, or spaces, or something else
BOOL hasGlyphs = [NSString visibleGlyphsExistInString:myString];

Hopefully that covers all the bases. I remember when I first started developing for Objective-C the category thing was one of those "huh?" ordeals for me - but now I use them quite a bit to increase reusability.
Edit: And I suppose, technically, if we're stripping characters, this:
[[copy stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0

Is really all that is needed (it should do everything that category method does, including the copy), but I could be wrong on that score.

A: I'm using this define as it works with nil strings as well as empty strings:
#define STR_EMPTY(str)  \
    str.length == 0

Actually now its like this:
#define STR_EMPTY(str)  \
    (![str isKindOfClass:[NSString class]] || str.length == 0)

A: This is what I use, an Extension to NSString:
+ (BOOL)isEmptyString:(NSString *)string;
// Returns YES if the string is nil or equal to @""
{
    // Note that [string length] == 0 can be false when [string isEqualToString:@""] is true, because these are Unicode strings.

    if (((NSNull *) string == [NSNull null]) || (string == nil) ) {
        return YES;
    }
    string = [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];

    if ([string isEqualToString:@""]) {
        return YES;
    }

    return NO;
}

A: You can try something like this:
@implementation NSString (JRAdditions)

+ (BOOL)isStringEmpty:(NSString *)string {
   if([string length] == 0) { //string is empty or nil
       return YES;
   }

   if(![[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]) {
       //string is all whitespace
       return YES;
   }

   return NO;
}

@end

Check out the NSString reference on ADC.

A: Maybe you can try something like this:
+ (BOOL)stringIsEmpty:(NSString *)str
{
    return (str == nil) || (([str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]).length == 0);
}

A: Based on the Jacob Relkin answer and  Jonathan comment:
@implementation TextUtils

    + (BOOL)isEmpty:(NSString*) string {

        if([string length] == 0 || ![[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]) {
            return YES;
        }

        return NO;
    }

    @end

A: Should be easier:
if (![[string stringByReplacingOccurencesOfString:@" " withString:@""] length]) { NSLog(@"This string is empty"); }


text:
Q: Is integral of adapted separable process adapted? Suppose $f(t,\omega)$ is separable stochastic process which is adapted to the filtration $F_t, 0<t<T$, is integral $\int_0^tf(s,\omega)ds$ measurable with respect to $F_t$? We assume that integral exists almost sure.
Definition: A stochastic process $(X(t), t\in I)$ is called separable if there exists a countable sequence $(t_j)$ that is a dense subset of $I$ and a subset N of $\Omega$ with $P(N)=0$ such that, if $\omega \notin N$, then
$$\{X(t, w) \in F\ for\ all\ t\in J\} = \{X(t_j, w) \in F\ for\ all\ t_j\in J\}$$
for any open subset J of I and for any closed subset F of R


text:
Q: FullCalendar HTML5 Drag & Drop Api I wanted to be able to drag and drop from multiple monitors, so I could have a list of tasks on one monitor and drag over to the second monitor's calendar. This wasn't feasible with the current implementation of JQuery UI because the scope is limited to the same window.
After playing around I found a hacky way to make this work for my needs. The answer still needs modifications but it could guide you if you are looking for something similar.

A: I'm sure this will still need some tweaking down the line but was able to get FullCalendar to work with HTML5 Drag & Drop API. Basically I'm using math to know where the item was dropped on the calendar and which time slot. I'm using the eventAfterAllRender feature built into full calendar to add my logic. This works for me and may be able to help you or get you in the right direction. On drop I'm setting a private onDrop function that takes the date/time to in which the item was dropped on. (Currently I do not have it as a momentjs object but plan to).
//Global Variables
var onDrop = null;
var currentMousePos = { x: -1, y: -1 };

eventAfterAllRender: function (view) {
                var currentDate = null;
                var currentTime = null;
                var dateRange = [];
                var timeRange = [];

                if (view.type == 'month') {
                    $('.fc-widget-content').each(function () {
                        if ($(this).attr('data-date') != null) {
                            var bounds = $(this)[0].getBoundingClientRect();

                            dateRange.push({
                                date: $(this).attr('data-date'),
                                bounds: bounds
                            })
                        }
                    });
                } else {
                    $('.fc-widget-header').each(function () {
                        if ($(this).attr('data-date') != null) {
                            var bounds = $(this)[0].getBoundingClientRect();

                            dateRange.push({
                                date: $(this).attr('data-date'),
                                bounds: bounds
                            })
                        }
                    });

                    $('.fc-slats tr').each(function () {
                        if ($(this).attr('data-time') != null) {
                            var bounds = $(this)[0].getBoundingClientRect();

                            timeRange.push({
                                time: $(this).attr('data-time'),
                                bounds: bounds
                            })
                        }
                    });
                }

                $(document).mousemove(function (event) {
                    currentMousePos.x = event.pageX;
                    currentMousePos.y = event.pageY;

                    currentDate = null;
                    currentTime = null;

                    for (var dIdx = 0; dIdx < dateRange.length; ++dIdx) {
                        if (dateRange[dIdx].bounds.left <= currentMousePos.x && dateRange[dIdx].bounds.right > currentMousePos.x) {
                            if (view.type == 'month') {
                                if (dateRange[dIdx].bounds.top < currentMousePos.y && dateRange[dIdx].bounds.bottom >= currentMousePos.y) {
                                    currentDate = dateRange[dIdx];
                                    break;
                                }
                            } else {
                                currentDate = dateRange[dIdx];
                                break;
                            }
                        }
                    }

                    for (var tIdx = 0; tIdx < timeRange.length; ++tIdx) {
                        if (timeRange[tIdx].bounds.top < currentMousePos.y && timeRange[tIdx].bounds.bottom >= currentMousePos.y) {
                            currentTime = timeRange[tIdx];
                            break;
                        }
                    }

                    if (currentDate != null && currentTime != null) {
                        var originalOnDrop = onDrop;
                        if (onDrop != null) {
                            onDrop = null;
                            if (originalOnDrop != null) {
                                originalOnDrop(currentDate.date + ' ' + currentTime.time);
                            }
                        }
                    } else if (currentDate != null) {
                        var originalOnDrop = onDrop;
                        if (onDrop != null) {
                            onDrop = null;
                            if (originalOnDrop != null) {
                                originalOnDrop(currentDate.date);
                            }
                        }
                    }
                });
            }

//HTML5 Drag Event Captured
self.HandleDrop = function (command, data) {
    switch (command) {
        case 'Workorder':
            onDrop = function (date) {
                $('#myTime').html(date);
                console.log(command);
                console.log(data);
            }
            break;
    }
}


text:
Q: Configuring Oracle XStream I'm trying to configure Oracle XStream out by official documentation
So, shortly, I'm connecting as sysdba
    sqlplus / as sysdba

Then executing commands create create CDB user and give him privileges
    > CREATE TABLESPACE xstream_tbs DATAFILE '$ORACLE/cdb/orcl/xstream_tbs.dbf' SIZE 25M REUSE AUTOEXTEND ON MAXSIZE UNLIMITED;
    > CREATE USER c##xstrmadmin IDENTIFIED BY password DEFAULT TABLESPACE xstream_tbs   QUOTA UNLIMITED ON xstream_tbs container=all;
    > GRANT CREATE SESSION, SET CONTAINER TO c##xstrmadmin CONTAINER=ALL;

After this step I should give permissions to user to use XStream
    > BEGIN
        DBMS_XSTREAM_AUTH.GRANT_ADMIN_PRIVILEGE(
          grantee                 => 'c##xstrmadmin',
          privilege_type          => 'CAPTURE',
          grant_select_privileges => TRUE,
          container => 'ALL');
      END;
      /

On this stage, I'm getting this error:
ERROR at line 1:
ORA-44001: invalid schema
ORA-06512: at "SYS.DBMS_XSTREAM_AUTH_IVK", line 3383
ORA-06512: at line 1
ORA-06512: at "SYS.DBMS_XSTREAM_AUTH_IVK", line 3500
ORA-06512: at "SYS.DBMS_XSTREAM_AUTH", line 34
ORA-06512: at line 2

Current container is cdb$root
Googling gives actually nothing and I have no idea whats wrong as I'm following DBA documentation.

A: I guess I found workaround.
If you connect to oracle with
> sqlplus /nolog

And then connect as sysdba
> conn / as sysdba

Then all works fine!
If this is only one way to resolve problem with creating permissions then problem is in sqlplus or oracle itself. Sad!


text:
Q: Passing cfquery to a cfc function from an element bind attribute I have a cfc function that accepts a query type argument (with the intent of running a query of query).
I am able to call the function successfully using <cfinvoke>.
However, what I really want to do is call the function from a hidden <cfinput>'s bind attribute, using
bind="cfc:cfcname.somefunction(queryVar)", and that code fails. There is no visible error, but it doesn't look like my function ever gets called - I have a cflog in there.
[The reason for the bind is not really relevant to my question, but it is because I need the function call to react to another control on the form - I've distilled all that out of my question]
If I replace the queryVar with some string variable, the function gets called fine, but obviously I cannot get the results I want without passing the query in.
If I use bind="cfc:cfcname.somefunction(#queryVar#)", I get a

"Complex type cannot be converted to simple type"

error.
I've searched for any documented restriction on passing query (or any complex type) to a cfc from a bind, but haven't found a clue.

A: You can use "bind" to send user-inputted data to another page for processing then send back the results. For example, If you use "bind" on a Birthdate field. When the user selects their birthdate, you can send that date to a CFC or CFM page and have it do the math #DateDiff('yyyy',birthdate,Now())# and return the result, which would be how many "years old" the user is.
But to my knowledge, you can't send a query to another page via the "bind" function. However, you could run the query again on another page and return the results.
Or perhaps look into JQuery to handle further processing after the page has loaded.


text:
Q: Get WebAuthenticationBroker.GetCurrentApplicationCallbackUri outside the Runtime We can get the current application callback URI by using the  WebAuthenticationBroker.GetCurrentApplicationCallbackUri method on Windows 8.1 Store Apps. Is there any way to get this application callback URI outside the runtime?
I need the application callback URI to register my client to the OAuth 2.0 provider I'm using right now. They validate the Redirect URI and if it doesn't match the one that you registered, the handshake fails.

A: According to this article you need to register your app in Windows Dev Center to get that uri.


text:
Q: Different background image for different pages in Bootstrap Hi good morning stackers,
I need your help with my Twitter Bootstrap page, site is not onepage scrolling neither horizontal nor vertical. The following problem: I have several pages this means index.html - work.html - about.html etc. I would like to have a fullscreen background image for each page. What opportunities are there? into CSS? or include on any page. So please help me to solve my problem

A: A common way to identify pages in CSS is mark the <body> element with different ids or classes.
frontpage.html:
<body id="page-front">

news.html:
<body id="page-news">

Then you can discriminate with different background in CSS:
#page-front { background: white url('koala.jpg'); }
#page-news { background: red url('blackmamba.jpg'); }

For an actual Bootstrap theme example you can look at here (mini logo not visible on the front age)


text:
Q: How to replace "\" with "\\" I've a path from wx.FileDialog (getpath()) shows "c:\test.jpg" which doesn't works with opencv cv.LoadImage() which needs "\\" or "/"
So, I've tried to use replace function for example:
s.replace("\","\\"[0:2]),s.replace("\\","\\\"[0:2])

but none those works.
And, this command s.replace("\\","/"[0:1]) returns the same path, I don't know why.
Could you help me solve this easy problem.
ps, I'm very new to python
thank you so much. sorry about my grammar

A: \ escapes the next character. To actually get a backslash, you must escape it. Use \\:
 s.replace("\\","/")

A: I think your looking for s.replace("\\","/")
Looking at the docs, and im not a Python programmer but its like so:
str.replace(old, new[, count])

So your do not need the 3rd parameter, but you need new and old obviusly.
s.replace("\\","/")

the reason we have \\ as because if we only had "\" this means that your escaping a quotation and your old parameter gets sent a  " that's if python don't trigger and error.
you need to send a Literal backslash like \ so what actually gets sent to the interpreter is a single \
you will notice with SO syntax highlighter where the string is being escaped..
s.replace("\","\\"[0:2]) #yours                        "
s.replace("\\","/") #mine

http://en.wikipedia.org/wiki/Escape_character

A: Its not entirely clear to me what you want to do with the paths, but there are a number of functions for dealing with them. You may want to use os.path.normpath() which will correct the slashes for whatever platform you are running on.

A: In Python you can use / independently from the OS as path separator (as RobertPitt pointed out, you can do this anyway).
But to answer your question, this should work:
str.replace("\\", "\\\\")

A: def onOpen(self, event): # wxGlade: MyFrame.<event_handler>
    dlg = wx.FileDialog(self, "Open an Image")
    if dlg.ShowModal() == wx.ID_OK:
        __imgpath__ = dlg.GetPath()
        print 'Selected:', dlg.GetPath()
        self.panel_2.LoadImage(cv.LoadImage(__imgpath__))

I don't know why, but it works with opencv.
output : "Selected: c:\test.jpg"
I'm sorry I didn't try it out first.


text:
Q: Interpreting random effect with multiple random intercepts in SAS proc glimmix We want run an event history analysis using logistic regression in SAS proc glimmix. We want to specify three random intercepts and we are using following code:
proc glimmix data=work method=laplace noclprint;
class level1 level2 level3;
model event(event='1')=exposure exposure2 health_condition gender well-being / solution ddfm=bw link=cloglog dist-binary;
random intercept / subject = level1*level2*level3;
covtest / wald;
run;

To my surprise SAS only outputs one estimate for the random effect, namely level1  * level2 * level3 in the covariance parameter estimate. How do I interpret this estimate? I expected to have a separate random intercept estimate for each level. Is this estimate the sum of all random effects?
Thanks!


text:
Q: SqlException (0x80131904): Incorrect syntax near '?' I am new to SQl and I'm running off of examples and I am wondering if anyone can help with a section of code that I have. I understand that there is a syntax error with one of my question marks but I can't figure out where it is or why it is happening for that matter.
Here is my code:
-

    <asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Overline="True"
        Font-Size="X-Large" Font-Underline="True" Text="Product Information Log"></asp:Label>

<asp:GridView ID="GridView1" runat="server"
    AllowSorting="True" AutoGenerateColumns="False" BackColor="White"
    BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3"
    DataSourceID="SqlDataSource1"
    EmptyDataText="There are no data records to display." ForeColor="Black"
    GridLines="Vertical">
    <AlternatingRowStyle BackColor="#808080" />
    <Columns>
        <asp:CommandField ShowSelectButton="True" />
        <asp:BoundField DataField="CICNumber" HeaderText="CICNumber"
            SortExpression="CICNumber" />
        <asp:BoundField DataField="ItemName" HeaderText="ItemName"
            SortExpression="ItemName" />
        <asp:BoundField DataField="ItemNumber" HeaderText="ItemNumber"
            SortExpression="ItemNumber" />
        <asp:BoundField DataField="PLUNumber" HeaderText="PLUNumber"
            SortExpression="PLUNumber" />
        <asp:BoundField DataField="PackSize" HeaderText="PackSize"
            SortExpression="PackSize" />
        <asp:BoundField DataField="CaseCost" HeaderText="CaseCost"
            SortExpression="CaseCost" />
        <asp:BoundField DataField="UnitRetailCost" HeaderText="UnitRetailCost"
            SortExpression="UnitRetailCost" />
            <asp:CommandField ShowDeleteButton="true" />
            <asp:CommandField ShowEditButton="true" />

    </Columns>
    <FooterStyle BackColor="#CCCCCC" />
    <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="Green" />
    <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
    <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
    <SortedAscendingCellStyle BackColor="#F1F1F1" />
    <SortedAscendingHeaderStyle BackColor="#808080" />
    <SortedDescendingCellStyle BackColor="#CAC9C9" />
    <SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server"

    ConnectionString="<%$ ConnectionStrings:ProductInfoConnectionString1 %>"
    DeleteCommand="DELETE FROM [tblProductInfo] WHERE [UserID] = ?"
    InsertCommand="INSERT INTO [tblProductInfo] ([CICNumber], [ItemName], [ItemNumber], [PLUNumber], [PackSize], [CaseCost], [UnitRetailCost]) VALUES (?, ?, ?, ?, ?, ?, ?)"
    ProviderName="<%$ ConnectionStrings:ProductInfoConnectionString1.ProviderName %>"
    SelectCommand="SELECT [CICNumber], [ItemName], [ItemNumber], [PLUNumber], [PackSize], [CaseCost], [UnitRetailCost] FROM [tblProductInfo]"
    UpdateCommand="UPDATE [tblProductInfo] SET [ItemName] = ?, [ItemNumber] = ?, [PLUNumber] = ?, [PackSize] = ?, [CaseCost] = ?, [UnitRetailCost] = ?, WHERE [CICNumber] = ?">

    <DeleteParameters>
                <asp:Parameter Name="CICNumber" Type="Int32" />
            </DeleteParameters>
            <UpdateParameters>
                <asp:Parameter Name="ItemName" Type="String" />
                <asp:Parameter Name="ItemNumber" Type="Int32" />
                <asp:Parameter Name="PLUNumber" Type="Int32" />
                <asp:Parameter Name="PackSize" Type="String" />
                <asp:Parameter Name="CaseCost" Type="Int32" />
                <asp:Parameter Name="UnitRetailCost" Type="Int32" />
            </UpdateParameters>
            <InsertParameters>
                <asp:Parameter Name="CICNumber" Type="Int32" />
                <asp:Parameter Name="ItemName" Type="String" />
                <asp:Parameter Name="ItemNumber" Type="Int32" />
                <asp:Parameter Name="PLUNumber" Type="Int32" />
                <asp:Parameter Name="PackSize" Type="String" />
                <asp:Parameter Name="CaseCost" Type="Int32" />
                <asp:Parameter Name="UnitRetailCost" Type="Int32" />
            </InsertParameters>

</asp:SqlDataSource>
</form>

A: You have
[UnitRetailCost] = ?, WHERE [CICNumber] = ?

at the end of the update statement, the comma needs to be removed:
[UnitRetailCost] = ? WHERE [CICNumber] = ?

A: In my case, there was just an unprintable character in the script that didn't show up in Visual-Studio, but is visible in bitbucket-source-viewer:


text:
Q: Running Async FeatureTask in Java stream I'm using Java-Streams to run FutureTasks and get the results.
It generally runs ok. But in recent days, if the API calls are frequent, the system blocks.
What might be a reason of this problem?
Code:
private List<ItemPriceVO> calculateItemPrices(PricingRequest request) {
    return request.getItemCodes()
        .stream()
        .map(itemCode -> executorService.submit(new TracerCallable<ItemPriceVO>() {
                @Override public ItemPriceVO doCall() throws Exception {
                    return calculateItemPrice(itemCode, request);
                }
            })
        ).map(future -> {
            try {
                return future.get();
            } catch (InterruptedException | ExecutionException e) {
                logger.error("calculate module price error, request:" + request, e);
                return null;
            }
        })
        .filter(Objects::nonNull)
        .collect(Collectors.toList());
}

Stack-trace:
"http-nio-7001-exec-250" #4853 daemon prio=5 os_prio=0 tid=0x00002afcc00f1800 nid=0x7a6a waiting on condition [0x00002afdb7c36000]
   java.lang.Thread.State: WAITING (parking)
  at sun.misc.Unsafe.park0(Native Method)
  - parking to wait for  <0x00000006e876dbf8> (a java.util.concurrent.FutureTask)
  at sun.misc.Unsafe.park(Unsafe.java:1025)
  at java.util.concurrent.locks.LockSupport.park(LockSupport.java:176)
  at java.util.concurrent.FutureTask.awaitDone(FutureTask.java:429)
  at java.util.concurrent.FutureTask.get(FutureTask.java:191)
  at com.alibaba.ons.open.web.channelbizfrt.pricing.PricingBizService.lambda$calculateItemPrices$56(PricingBizService.java:218)
  at com.alibaba.ons.open.web.channelbizfrt.pricing.PricingBizService$$Lambda$171/304812073.apply(Unknown Source)
  at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
  at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
  at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
  at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
  at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
  at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
  at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
  at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
  at com.alibaba.ons.open.web.channelbizfrt.pricing.PricingBizService.calculateItemPrices(PricingBizService.java:225)
  at com.alibaba.ons.open.web.channelbizfrt.pricing.PricingBizService.calculate(PricingBizService.java:124)
  at com.alibaba.ons.open.web.channelbizfrt.pricing.PricingBizService$$FastClassBySpringCGLIB$$7f5d865.invoke(<generated>)


text:
Q: "go run" is going in infinite loop using sublime text 3 I am trying to run go code in sublime text 3.
package main

import (
    "fmt"
)

func main() {
    fmt.Println("Hello, playground")
}

However, when I go under Tools -> Build I see that the program goes in infinite loop.
GoSublime r17.03.05-1 9o: type `help` for help and command documentation

[ `go run main.go` ⌛ ]
[ ~/Documents/SublimeWorkspace/ ] #

Please let me know what I might be missing here.

A: Open sublime
Goto Tools->Build System-> New build System. Paste below lines in the file and save by some_name.sublime-build
{
"shell_cmd": "go run $file",
"shell":true
}

Goto Tools->Build system-><select-your-build or automatic>
Goto Tools->Build
Done cheers :)


text:
Q: How to create a unique ID field in MySQL using Python How to automatically create unique ID field in MySQL (SuiteCRM)? For example: 'e3df34-dg324g-sdsew23-dsdsw2'
python:
    try:
        with connection.cursor() as cursor:
            sql = "INSERT INTO `accounts` (`id`, `name`) VALUES (%s, %s)"
            cursor.execute(sql, ('sdi_234023', 'Alex'))

        connection.commit()
    finally:
        connection.close()

A: You can you generate random uuid for the same. Using following code.
    from uuid import uuid4
    try:
        with connection.cursor() as cursor:
            sql = "INSERT INTO `accounts` (`id`, `name`) VALUES (%s, %s)"
            cursor.execute(sql, (str(uuid4), 'Alex'))

        connection.commit()
    finally:
        connection.close()


text:
Q: Most efficient way of converting String to Integer in java There are many ways of converting a String to an Integer object. Which is the most efficient among the below:
Integer.valueOf()
Integer.parseInt()
org.apache.commons.beanutils.converters.IntegerConverter

My usecase needs to create wrapper Integer objects...meaning no primitive int...and the converted data is used for read-only.

A: Here's a good article comparing the performance of different methods of parsing integers
And here's the code used, with overflow/underflow checks.
public static int parseInt( final String s )
{
    if ( string == null )
        throw new NumberFormatException( "Null string" );

    // Check for a sign.
    int num  = 0;
    int sign = -1;
    final int len  = s.length( );
    final char ch  = s.charAt( 0 );
    if ( ch == '-' )
    {
        if ( len == 1 )
            throw new NumberFormatException( "Missing digits:  " + s );
        sign = 1;
    }
    else
    {
        final int d = ch - '0';
        if ( d < 0 || d > 9 )
            throw new NumberFormatException( "Malformed:  " + s );
        num = -d;
    }

    // Build the number.
    final int max = (sign == -1) ?
        -Integer.MAX_VALUE : Integer.MIN_VALUE;
    final int multmax = max / 10;
    int i = 1;
    while ( i < len )
    {
        int d = s.charAt(i++) - '0';
        if ( d < 0 || d > 9 )
            throw new NumberFormatException( "Malformed:  " + s );
        if ( num < multmax )
            throw new NumberFormatException( "Over/underflow:  " + s );
        num *= 10;
        if ( num < (max+d) )
            throw new NumberFormatException( "Over/underflow:  " + s );
        num -= d;
    }

    return sign * num;
}

And even faster implementation, without overflow/underflow checks.
public static int parseInt( final String s )
{
    // Check for a sign.
    int num  = 0;
    int sign = -1;
    final int len  = s.length( );
    final char ch  = s.charAt( 0 );
    if ( ch == '-' )
        sign = 1;
    else
        num = '0' - ch;

    // Build the number.
    int i = 1;
    while ( i < len )
        num = num*10 + '0' - s.charAt( i++ );

    return sign * num;
}

A: Don't even waste time thinking about it.  Just pick one that seems to fit with the rest of the code (do other conversions use  the .parse__() or .valueOf() method? use that to be consistent).
Trying to decide which is "best" detracts your focus from solving the business problem or implementing the feature.
Don't bog yourself down with trivial details. :-)
On a side note, if your "use case" is specifying java object data types for your code - your BA needs to step back out of your domain.  BA's need to define "the business problem", and how the user would like to interact with the application when addressing the problem.
Developers determine how best to build that feature into the application with code - including the proper data types / objects to handle the data.

A: If efficiency is your concern, use int: it is much faster than Integer.
Otherwise, class Integer offers you at least a couple clear, clean ways:
Integer myInteger = new Integer(someString);
Integer anotherInteger = Integer.valueOf(someOtherString);

A: I tried a comparison of valueOf, parseInt, Ints.tryParse, NumberUtils.createInteger and NumberUtils.toInt with the program below. I was on jdk 1.8.0
As expected, the methods that did not need to create an Integer object were the fastest. My results were:
valueOf took: 77
parseInt took: 61
Ints.tryParse took: 117
numberUtils.createInteger took: 169
numberUtils.toInt took: 63

So the summary is:
If you can get by using an int, use Integer.parseInt.
If you absolutely need an Integer, use Integer.valueOf
If you need the convenience of not handling exceptions when you parse, or if you are unsure of the format of the input (i.e its a string that need not be a number) use Ints.tryParse
The code I used was:
public class HelloWorld {

public static int limit = 1000000;
public static String sint = "9999";

public static void main(String[] args) {

    long start = System.currentTimeMillis();
    for (int i = 0; i < limit; i++) {
       Integer integer = Integer.valueOf(sint);
    }
    long end = System.currentTimeMillis();

    System.out.println("valueOf took: " + (end - start));

    start = System.currentTimeMillis();
    for (int i = 0; i < limit; i++) {
        int integer = Integer.parseInt(sint);
    }
    end = System.currentTimeMillis();

    System.out.println("parseInt took: " + (end - start));

    start = System.currentTimeMillis();
    for (int i = 0; i < limit; i++) {
        int integer = Ints.tryParse(sint);
    }
    end = System.currentTimeMillis();

    System.out.println("Ints.tryParse took: " + (end - start));

    start = System.currentTimeMillis();
    for (int i = 0; i < limit; i++) {
        Integer integer = NumberUtils.createInteger(sint);
    }
    end = System.currentTimeMillis();

    System.out.println("numberUtils.createInteger took: " + (end - start));

    start = System.currentTimeMillis();
    for (int i = 0; i < limit; i++) {
        int integer = NumberUtils.toInt(sint);
    }
    end = System.currentTimeMillis();

    System.out.println("numberUtils.toInt took: " + (end - start));

}
}

A: If efficiency is your concern, then creating an Integer object is much more expensive than parsing it. If you have to create an Integer object, I wouldn't worry too much about how it is parsed.
Note: Java 6u14 allows you to increase the size of your Integer pool with a command line option -Djava.lang.Integer.IntegerCache.high=1024 for example.
Note 2: If you are reading raw data e.g. bytes from a file or network, the conversion of these bytes to a String is relatively expensive as well. If you are going to write a custom parser I suggest bypassing the step of conversing to a string and parse the raw source data.
Note 3: If you are creating an Integer so you can put it in a collection, you can avoid this by using GNU Trove (trove4j) which allows you to store primitives in collections, allowing you to drop the Integer creation as well.
Ideally, for best performance you want to avoid creating any objects at all.

A: Your best bet is to use Integer.parseInt.  This will return an int, but this can be auto-boxed to an Integer.  This is slightly faster than valueOf, as when your numbers are between -128 and 127 it will use the Integer cache and not create new objects.  The slowest is the Apache method.
private String data = "99";

public void testParseInt() throws Exception {
    long start = System.currentTimeMillis();
    long count = 0;
    for (int i = 0; i < 100000000; i++) {
        Integer o = Integer.parseInt(data);
        count += o.hashCode();
    }
    long diff = System.currentTimeMillis() - start;
    System.out.println("parseInt completed in " + diff + "ms");
    assert 9900000000L == count;
}

public void testValueOf() throws Exception {
    long start = System.currentTimeMillis();
    long count = 0;
    for (int i = 0; i < 100000000; i++) {
        Integer o = Integer.valueOf(data);
        count += o.hashCode();
    }
    long diff = System.currentTimeMillis() - start;
    System.out.println("valueOf completed in " + diff + "ms");
    assert 9900000000L == count;
}

public void testIntegerConverter() throws Exception {
    long start = System.currentTimeMillis();
    IntegerConverter c = new IntegerConverter();
    long count = 0;
    for (int i = 0; i < 100000000; i++) {
        Integer o = (Integer) c.convert(Integer.class, data);
        count += o.hashCode();
    }
    long diff = System.currentTimeMillis() - start;
    System.out.println("IntegerConverter completed in " + diff + "ms");
    assert 9900000000L == count;
}

parseInt completed in 5906ms
valueOf completed in 7047ms
IntegerConverter completed in 7906ms

A: I know this isn't amongst your options above.  IntegerConverter is ok, but you need to create an instance of it.  Take a look at NumberUtils in Commons Lang:
Commons Lang NumberUtils
this provides the method toInt:
static int toInt(java.lang.String str, int defaultValue)

which allows you to specify a default value in the case of a failure.
NumberUtils.toInt("1", 0)  = 1

That's the best solution I've found so far.

A: I'm always amazed how quickly many here dismiss some investigation into performance problems. Parsing a int for base 10 is a very common task in many programs. Making this faster could have a noticable positive effect in many environments.
As parsing and int is actually a rather trivial task, I tried to implement a more direct approach than the one used in the JDK implementation that has variable base. It turned out to be more than twice as fast and should otherwise behave exactly the same as Integer.parseInt().
public static int intValueOf( String str )
{
    int ival = 0, idx = 0, end;
    boolean sign = false;
    char ch;

    if( str == null || ( end = str.length() ) == 0 ||
       ( ( ch = str.charAt( 0 ) ) < '0' || ch > '9' )
          && ( !( sign = ch == '-' ) || ++idx == end || ( ( ch = str.charAt( idx ) ) < '0' || ch > '9' ) ) )
        throw new NumberFormatException( str );

    for(;; ival *= 10 )
    {
        ival += '0'- ch;
        if( ++idx == end )
            return sign ? ival : -ival;
        if( ( ch = str.charAt( idx ) ) < '0' || ch > '9' )
            throw new NumberFormatException( str );
    }
}

To get an Integer object of it, either use autoboxing or explicit
Interger.valueOf( intValueOf( str ) ).

A: ParseInt returns an int, not a java.lang.Integer, so if you use tat method you would have to do
new Integer (Integer.parseInt(number));

I´ve heard many times that calling Integer.valueOf() instead of new Integer() is better for memory reasons (this coming for pmd)

In JDK 1.5, calling new Integer()
  causes memory allocation.
  Integer.valueOf() is more memory
  friendly.

http://pmd.sourceforge.net/rules/migrating.html
In addition to that, Integer.valueOf allows caching, since values -127 to 128 are guaranteed to have cached instances. (since java 1.5)

A: Herro - kinda new to Java so forgive my ignorance.
I was searching for a a way to parse a mixed string (letters & numbers) into an INT (kinda like javascript does). Couldn't find anything in the JAVADOC files so after much searching i just wrote a function that does it:
// This function takes a string mixed with numbers and letters and returns an INT with
// the first occurrence of a number (INT) in said string, ignoring the rest;
// -- Basically, loop checks if char is a digit, if yes, puts digit back into new array, if no, puts a whitespace in its place
// this creates an array with only digits; By converting it to a string and then trimming whitespaces, it gets parsed into an INT

public static int mixedStringToInt (String str) {

    boolean flag = true;
    boolean isNumber = false;
    final String refNumbers = "0123456789";

    int strlen = str.length();
    char[] numberArray = new char[strlen];
    char[] stringArray = str.toCharArray();

    for (int i = 0; i < strlen;i++){
        if(refNumbers.indexOf(stringArray[i]) > 0 && flag){
            // if current char is a digit
            isNumber = true;
            while (flag){
                numberArray[i] = stringArray[i];
                if(i+1 >= strlen || refNumbers.indexOf(stringArray[i+1]) < 0) flag = false;
                i++;
            }
        } else {
            // if current char is not a digit
            numberArray[i] = ' ';
        }
    }
    if (isNumber){
        return Integer.valueOf(new String(numberArray).trim());
    } else return 0;
}

Is this useful for anyone besides me? Did i waste my time writing this as there is already a method that does what i wanted to do?

A: Another way is this method:
public class stringtoInteger {

    private static int stringtoInteger(String x) {
        String value = "";
        for (int i = 0; i < x.length(); i++) {
            char character = x.charAt(i);
            if (Character.isDigit(character)) {
                value = value + character;
            }
        }
        return Integer.parseInt(value);
    }
}

Hope it helps!


text:
Q: The expectation after Bayesian inference of a Normal r.v I'm confusing myself with this question.
Suppose there is a Normal r.v $X \sim \mathcal{N}(\mu, \sigma^2)$. We known the variance $\sigma^2$ however don't know the mean $\mu$, and choose to use Bayesian inference to update our belief.
Suppose further we have a prior distribution of $\mu$, also Normal, i.e $\mu \sim \mathcal{N}(\mu_0, \sigma_0^2)$, the observation is $x_0$.
Then what is the conditional expectation $\mathbb{E}(X|x_0)$ ? Would you please show me the derivation steps?
I know how to get the posterior distribution on $\mu$ when assuming $\sigma_0^2$ is fixed, i.e
$$\mu \sim \mathcal{N}(\mu'_0, \sigma_0^2), \;\;\; \mu'_0 = \frac{\sigma_0^2 x_0 + \sigma^2 \mu_0}{\sigma_0^2 + \sigma^2}$$
Many thanks!


text:
Q: Can't get angular/material to start working I've installed with the command:
npm install --save @angular/material @angular/cdk

I added to app.module.ts
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { MatButtonModule } from '@angular/material';

Package.json
"dependencies": {
    "@angular/animations": "^5.2.10",
    "@angular/cdk": "^6.0.1",
    "@angular/common": "^5.2.0",
    "@angular/compiler": "^5.2.0",
    "@angular/core": "^5.2.0",
    "@angular/forms": "^5.2.0",
    "@angular/http": "^5.2.0",
    "@angular/material": "^6.0.1",
    "@angular/platform-browser": "^5.2.0",
    "@angular/platform-browser-dynamic": "^5.2.0",
    "@angular/router": "^5.2.0",
    "core-js": "^2.4.1",
    "rxjs": "^5.5.6",
    "zone.js": "^0.8.19"
  },

I tried in my test.component.html to test out
<button mat-button>Click me!</button>

I get an error in the console like this:
bidi.es5.js:86 Uncaught TypeError: Object(...) is not a function
    at eval (bidi.es5.js:86)
    at eval (bidi.es5.js:88)
    at Object../node_modules/@angular/cdk/esm5/bidi.es5.js (vendor.bundle.js:39)
    at __webpack_require__ (inline.bundle.js:55)
    at eval (core.es5.js:60)
    at Object../node_modules/@angular/material/esm5/core.es5.js (vendor.bundle.js:255)
    at __webpack_require__ (inline.bundle.js:55)
    at eval (autocomplete.es5.js:17)
    at Object../node_modules/@angular/material/esm5/autocomplete.es5.js (vendor.bundle.js:191)
    at __webpack_require__ (inline.bundle.js:55)

ng -v gives me this:
Your global Angular CLI version (6.0.0) is greater than your local
version (1.7.4). The local Angular CLI version is used.
Angular CLI: 1.7.4
Node: 8.11.1
OS: win32 x64
Angular: 5.2.10

A: Did you import the module inside your test component? You need to import
import {MatButtonModule } from '@angular/material';

       imports: [BrowserAnimationsModule]

inside each component.
I think its mentioned somewhere in the documentations, that you shouldn't import it into the app.module or create a global module for it.

A: You have to use the same Angular version as to what Angular Material v6 uses: Angular v6
See https://update.angular.io for info on how to update your dependencies.
Alternatively, consider installing 5.x.x of Angular Material.


text:
Q: Is there a way to download "Responses In Progress" survey from Qualtrics? I'm looking for a way to download surveys that are still open on Qualtrics so that I can create a report on how many surveys are completed and how many are still in progress. I was able to follow their API documentation to download the completed surveys to a csv file but I couldn't find a way to do the same for the In Progress surveys. Thanks in advance for your help.

A: Not through the API.  You can do it manually through the Qualtrics interface.
If you need to use the API and the survey is invite only, an alternative would be to download the distribution history for all the distributions. That will tell you the status of each invitee.


text:
Q: Throw exception when get error on reflection I have library and console program. The program dynamically load library and get int array. But program throw exception. Can you help me fix it?
My library:
public class Class1
{
  public int [] arrayInt;
  public Class1()
  {
    arrayInt = new int[5] {1,2,3,4,5};
  }
}

My program:
    Assembly asm = Assembly.LoadFile(@"C:\TestLibrary.dll");
    Type Class1 = asm.GetType("TestLibrary.Class1") as Type;
    var testClass = Activator.CreateInstance(Class1);
    MemberInfo[] List = Class1.GetMember("arrayInt");
    foreach (FieldInfo field in List)
    {
        if (field.FieldType.IsArray)
        {
            int[] array = (int[])field.GetValue(null);//throw exception here
            Console.WriteLine("Count of list. "+array.length);
            foreach (var element in array)
                Console.WriteLine(element.ToString());
            break;
        }
    }

Exception message:

System.Reflection.TargetException: Non-static field requires a target. at System.Reflection.RtFieldInfo.CheckConsistency(Object target) at System.Reflection.RtFieldInfo.InternalGetValue(Object obj, StackCrawlMark& stackMark)   at System.Reflection.RtFieldInfo.GetValue(Object obj)   at Tets.Program.Main(String[] args)

P.S. Can you modified code, that first array doesn't take from Loop?

A: In field variable in your loop you have the definition of field and when you want to get the value of field you should pass the object to the GetValue method, so in your code you need to write something like this
int[] array = (int[])field.GetValue(testClass);

A: Since this Field instance field (None static) you need to pass instance to GetValue() method.
int[] array = (int[])field.GetValue(testClass);


text:
Q: Как эмулировать нажатие на Enter на Java? В общем, я только начинаю изучать Java и решил что уже в принципе это можно как-то использовать. Хочу попробовать написать маленькую программу, которая автоматически будет нажимать на Enter при появлении в игре кнопки принять.
Объясните новичку возможно ли вообще такое осуществить на Java и с чего начать? Базовые знания уже имеются, меня бы просто направить  Заранее спасибо!

A: Возможно, например при помощи java.awt.Robot, он умеет:

*

*Снимать скриншоты

*Манипулировать мышью и клавиатурой

*...

*Profit!

A: Можно сделать с помощью класса Robot. Например, для нажатии клавиши Enter:
Robot r = new Robot();
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);


text:
Q: How to generate an index page for a specific tag link in a tag cloud? Failed to find an answer for this question, though it must be quite simple. I'm a beginner in web dev and will highly appreciate your help.
I want to make a tag cloud on a web site which i'm working on. It's a sort of diary when each page corresponds to some date. No CMS, my own coding (just for learning reasons). There are many solutions how to generate a cloud itself from the given list of words, but I'm stuck on the further step, i.e. tag links:
Should I create an index page for every tag 'manually' or is there some way to automate this process? I mean, should I write in html/css every tag-connected page, which would contain links to the other pages linked to a particular tag, or is it possible to code some template and then generate pages for each tag based on that template? I have some knowledge of javascript, python and very little of php (but ready and eager to learn more :).
What would you suggest?
Thnx


text:
Q: Why does Seifert-Van Kampen not hold with $n$-th homotopy groups? My question concerns the Seifert-Van Kampen theorem, in the following form.
Let $X$ be an arch-wise connected topological space, consider a poin $x_{0}\in X$, and let $\{U_{i}\}_{i\in I}$ be an open covering by archwise-connected open subsets of $X$ such that $x_{0}\in U_{i}$ for all $i\in I$, and $U_{i}\cap U_{j}\in \{U_{i}\}_{i\in I}$ for all $i,j\in I$.
For any two elements of the covering $U_{i}$, $U_{j}$ such that $U_{i}\subseteq U_{j}$, let $\phi_{ij}:\pi_{1}(U_{i},x_{0})\longrightarrow \pi_{1}(U_{j},x_{0})$ be the map induced by the inclusion. Similarly, for any element of the covering $U_{i}$, let $\tau_{i}:\pi_{1}(U_{i},x_{0})\longrightarrow \pi_{1}(X,x_{0})$ be the map induced by the inclusion.
Let $H$ be a group and $\rho_{i}:\pi_{1}(U_{i},x_{0})\longrightarrow H$ any collection of homomorphisms defined for all $i\in I$ and such that if $U_{i}\subseteq U_{j}$ then $\rho_{i}=\rho_{j}\circ \phi_{ij}$. Then, there exists a unique homomorphism $\lambda:\pi_{1}(X,x_{0})\longrightarrow H$ such that $\rho_{i} = \lambda \circ \tau_{i}$, for all $i\in I$. Moreover, this universal mapping condition characterizes $\pi_{1}(X,x_{0})$ up to a unique isomorphism.
It is well-known that this statement does not always hold if we consider $n$-th homotopy groups with $n\geq 2$, and I believe that easy examples of this fact could be constructed. However, I would like to understand the intrinsic reason behind this phenomenon. We can roughly say that the proof of Seifert-Van Kampen is divided in two parts.
(1) With the notation above, the group $\pi_{1}(X,x_{0})$ is generated by the union of the images of $\pi_{1}(U_{i},x_{0})$ via the maps $\tau_{i}$.
(2) For any $[\alpha]\in\pi_{1}(X,x_{0})$, consider the decomposition $[\alpha]=  [\alpha_{1}]...[\alpha_{n}]$ given in point (1). Then the morphism $\lambda([\alpha])=\rho_{1}([\alpha_{1}])...\rho_{n}([\alpha_{n}])$ is well-defined.
Which one of the two parts fails with $n$-th homotopy groups? Why?

A: You ask a very subtle question!
One of the intrinsic reasons is that in homotopy theory identifications in low dimensions in a space usually have high dimensional  influences. An easy   example is to attach a whisker to a sphere, i.e. form $X=S^n \vee [0.1], n >1$. This has the same homotopy type as $S^n$. Now identify $0$ and $1$ in $X$, an identification in dimension $0$, to form $S^n \vee S^1$. The $n$-th homotopy group has changed! There are many more complicated examples, and this is the norm.
The answer which I have pursued over decades is that one needs "invariants"  which have structure in a range of dimensions. How to find such, and prove theorems?  It turns out that forms of multiple groupoids do a useful job, but they are nicely defined, and lead to calculations,  not for spaces but for spaces with structure.  The structures that have worked in this way are filtered spaces and $n$-cubes of spaces. See my presentation Galway as a start, but that explains only filtered spaces.
Part of the confusion is that a space with base point seems much like a space, but maybe it should be seen as profoundly different! Homotopy groups are defined for the former but not for the latter. So one is looking for functors
$\Pi: ($topological data$) \to ($algebraic data$) $
which preserve certain colimits. It turns out that the latter algebraic data come in many equivalent forms when including dimensions $>1$, partly due to the many forms of convex sets in Euclidean space of dimensions $>1$.
With regard to your questions $1,2$, in higher dimensions you have to consider higher dimensional compositions, and these are best expressed cubically. Thus in dimension $2$ we consider the following diagrams.

Going from left to right is subdivision, but going from right to left should be composition. We need algebraic inverses to subdivision and a homotopically defined gadget which can express this. How we got to one successful answer to this in all dimensions is described in the presentation Galway. Note that "double groups" are just abelian groups, by the interchange law (i.e. Eckmann-Hilton argument),  while double groupoids are much more complicated than groups, and so better able to express the complications of homotopy theory in dimension $2$. The book Nonabelian Algebraic Topology (pdf available) explains history and intuitions, before developing the theory.
It also turns out that one needs two kinds of algebraic data, which I have termed "broad" and "narrow" in the Galway talk. The broad data is for conjecturing and proving theorems, while the narrow data is used for relation to the classical theory, and for calculations. A substantial part of the work is to prove algebraically that these two categories of data are equivalent, so that one can hop from one to the other as desired.
Geometrically, these two kinds of data are related to the use of cubes and disks in defining homotopical constructions, such as homotopy groups. All this works nicely if the topological data are filtered spaces, where $\Pi X_*$, with $X_*$ a filtered space, is constructed using fundamental groupoids and relative homotopy groups, giving crossed complexes, the narrow model, while a less familiar construction, $\rho X_*$, modelled on cubes, gives the "broad" model, which allows us to express composition and subdivision in many dimensions. Cubes are also very helpful in discussing products and homotopies, because of the rule $I^m \times I^n \cong I^{m+n}$.
The above enables the  homotopical approach to basic algebraic topology, without using singular homology, described in the  book Nonabelian Algebraic Topology. To get further one needs some much more complicated gadgets, called cat$^n$-groups, and crossed $n$-cubes of groups, for which there is a survey article here. There have been complaints about this theory, for example that it was  unsuccessful at calculating higher homotopy groups of spheres, but few topologists have worked on it;   it enables calculations not previously available of homotopy types of some complexes, while group theorists have liked the nonabelian tensor product which arose from some pushout calculations, is related to commutator theory,   and now has a bibliography of 174 items.
Nov 16, 2019 The first mention of higher homotopy groups seems to hasve been at the 1932 ICM at Zurich, in a seminar of E.Cech. He proved they were abelian for $n\geq 2$, and on these grounds it was argued that they were not the hoped for at that time higher dimensional versions of the fundamental group. For accounts of this see books on the history of topology. Now we know that higher homotopy groupoids can be seen as a more reasonable such generalisation.  See the above references and also this, and another.


text:
Q: Java Simple Chat Box I am trying to create a very simple chat window that simply has the ability to display some text, which I add to from time to time.  However I get the following run time error when attempting to append text to the window:
java.lang.ClassCastException: javax.swing.JViewport cannot be cast to javax.swing.JTextPane
    at ChatBox.getTextPane(ChatBox.java:41)
    at ChatBox.getDocument(ChatBox.java:45)
    at ChatBox.addMessage(ChatBox.java:50)
    at ImageTest2.main(ImageTest2.java:160)

Here is the class to handle the basic operations:
public class ChatBox extends JScrollPane {

private Style style;

public ChatBox() {

    StyleContext context = new StyleContext();
    StyledDocument document = new DefaultStyledDocument(context);

    style = context.getStyle(StyleContext.DEFAULT_STYLE);
    StyleConstants.setAlignment(style, StyleConstants.ALIGN_LEFT);
    StyleConstants.setFontSize(style, 14);
    StyleConstants.setSpaceAbove(style, 4);
    StyleConstants.setSpaceBelow(style, 4);

    JTextPane textPane = new JTextPane(document);
    textPane.setEditable(false);

    this.add(textPane);
}

public JTextPane getTextPane() {
    return (JTextPane) this.getComponent(0);
}

public StyledDocument getDocument() {
    return (StyledDocument) getTextPane().getStyledDocument();
}

public void addMessage(String speaker, String message) {
    String combinedMessage = speaker + ": " + message;
    StyledDocument document = getDocument();

    try {
        document.insertString(document.getLength(), combinedMessage, style);
    } catch (BadLocationException badLocationException) {
        System.err.println("Oops");
    }
}
}

If there is a simpler way to do this, by all means let me know. I only need the text to be of a single font type, and uneditable by the user.  Aside from that, I just need to be able to append text on the fly.

A: You have two options:

*

*Store the JTextPane in a member variable and return that inside getTextPane().

*Modify getTextPane to return the JViewPort's view, like this
return (JTextPane) getViewport().getView();

See the Swing tutorials for more detail.
Also, as camickr (and the tutorials) pointed out, using add with a JScrollPane is incorrect. You should be either passing the component to the constructor or using setViewportView.
As a side note, I try not to subclass Swing components unless it's absolutely necessary (preferring composition over inheritance). But that's not particularly relevant to the question.

A: Don't extend a JScrollPane. You are NOT adding any functionality to it.
It looks like the basic problem is that your are trying to add the text pane to the scrollpane. This is not the way it works. You need to add the text pane to the viewport. The easy way to do this is:
JTextPane textPane = new JTextPane();
JScrollPane scrollPane = new JScrollPane( textPane );

or
scrollPane.setViewportView( textPane );

A: public JTextPane getTextPane() {
    return (JTextPane) this.getComponent(0);
}

this.getComponent(0) is returning the ScrollPane's JViewPort, not your JTextPane. It can't be casted, and so you get your exception.


text:
Q: EmguCV capture frames QueryFrame() I'm using emgu cv 3.0.0 and I would like to capture frames from a USB cam.
Unfortunately, I get an error while calling Image<Bgr, Byte> image = capture.QueryFrame();
It says, I can't convert from Emgu.CV.Mat to Emgu.CV.Image.

A: Try this line of code
Image<Bgr, Byte> image = capture.QueryFrame().ToImage<Bgr,Byte>();

A: In cv v 3.0.0 most methods use Mat for image representation.
You can try this to get the frame from the camera:
Mat frame = new Mat();
_capture.Retrieve(frame, 0);

For conversion to gray:
Mat grayFrame = new Mat();
CvInvoke.CvtColor(frame, grayFrame, ColorConversion.Bgr2Gray);

Also you can see how it works in examples here.


text:
Q: Broken logout link in chat mobile theme I tried to logout from SE via the logout button on the mobile chat interface:

However, the link points to https://chat.stackexchange.com/logout which gives Page Not Found.
In full site theme, the logout link in chat top bar is correct, pointing to https://stackexchange.com/users/logout as it should.