text:
Q: How to limit the max rows without Using Pageable for JPASpecificationsExecutor? I am trying to understand and figure out the solution for the following use case
These are my entity classes
User
@Entity
@Table(name = "USER")
public class User  {
  private UserID id;
  private Set<UserAddress> addresses = new HashSet<UserAddress>(0);
  @EmbeddedId
  @AttributeOverrides( {
        @AttributeOverride(name = "userId", column = @Column(name = "USER_ID", nullable = false, length = 32)),
        @AttributeOverride(name = "userType", column = @Column(name = "USER_TYPE", nullable = false, precision = 12, scale = 0)) })
  public User getId() {
     return this.id;
  }
  @OneToMany(fetch = FetchType.EAGER,  mappedBy = "user", cascade={CascadeType.ALL})
  @BatchSize(size=50)
  public Set<UserAddress> getAddresses() {
    return this.addresses;
  }
  ........
}

UserAddress
@Entity
@Table(name = "USERADDRESS")
public class UserAddress  {
  private UserID id;
  Private User user;
  private String address;
  @EmbeddedId
  @AttributeOverrides( {
        @AttributeOverride(name = "userId", column = @Column(name = "USER_ID", nullable = false, length = 32)),
        @AttributeOverride(name = "userType", column = @Column(name = "USER_TYPE", nullable = false, precision = 12, scale = 0)) })
  public User getId() {
     return this.id;
  }
  @ManyToOne(fetch = FetchType.LAZY)
@JoinColumns( {
    @JoinColumn(name = "userId", referencedColumnName = "USER_ID", nullable = false, insertable=false, updatable=false),
    @JoinColumn(name = "userType", referencedColumnName = "USER_TYPE", nullable = false, insertable=false, updatable=false) })
  public User getUser() {
    return this.user;
  }
  ........
}

UserId
@Embeddable
public class UserId implements Serializable {
   private String userNo;
   private Long UserType;
   .......
   .......
}

I have created a staticmetamodel class for User, UserID and UserAddress and created query based on Specifications.
Metamodel class for User
@StaticMetamodel(User.class)
public abstract class User_ {

  public static volatile SetAttribute<User, UserAddress> addresses;
  public static volatile SingularAttribute<User, UserID> id;
}

Metamodel for UserId
@StaticMetamodel(UserID.class)
public abstract class UserID_ {
   public static volatile SingularAttribute<UserID, String> userNo;
   public static volatile SingularAttribute<UserID, Long> UserType;
}

I am trying to retrieve maximum of 10 User objects ordered by UserType and searched based on userId. The query has to retrieve the UserAddresses as an eager fetch.
My Specification Object is
UserSpecification
public class UserSpecifications {
   public static Specification<User> userNoIs(String userNo) {
      return (root, query, cb) -> {
        root.fetch(User_.addresses);
        return cb.equal(root.get(User_.id).get(UserID_.userNo),userNo);
      };
   }
}

DAO Function:
 Sort sortInstructions = new Sort(Sort.Direction.DESC, "id.userNo");
 Pageable pageInfo = new PageRequest(0, maxCount, sortInstructions);
 Specifications<User> specifications = Specifications.where(userNoIs(input.getUserNo()));
 Page<User> responseList= userRepository.findAll(specifications,pageInfo);

I am getting the following exception when I run the above statement.
Caused by: org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list [FromElement{explicit,not a collection join,fetch join,fetch non-lazy properties,classAlias=generatedAlias1,role=com.entity.User.addresses,tableName=USERADDRESS ,tableAlias=useraddress1_,origin=USER user0,columns={user0.USER_TYPE user0.USER_ID ,className=com.entity.UserAddress}}]

But apart from that I also need to understand how to limit the no of rows returned using Specification but without using Pageable . If I use Pageable, then a separate query will be fired to retrieve the count of rows and then actual query is being fired. My application is performance oriented, and I do not want to have any extra queries being fired.
Is there any way where I can limit the no of rows without using Pageable, but using Specifications ?


text:
Q: Multiple paths in CAShapeLayer I was wondering if it is somehow possible to let a CAShapeLayer stroke more than only one path since actually it only takes one path as parameter like:
CAShapeLayer* myLayer=[CAShapeLayer layer];
myLayer.path=myBezierPath

But what if I would like to stroke more than one path onto that layer?

A: Another way of doing this is to append paths like so...
UIBezierPath *left_path = [UIBezierPath bezierPathWithRect:frame_left];
UIBezierPath *right_path = [UIBezierPath bezierPathWithRect:frame_right];

[left_path appendPath:right_path];

CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = left_path.CGPath;

A: Ok, I found it out myself. One can do following:
CGMutablePathRef combinedPath= CGPathCreateMutableCopy(path.CGPath);
CGPathAddPath(combinedPath, NULL, path2.CGPath);
CGPathAddPath(combinedPath, NULL, path3.CGPath);
CGPathAddPath(combinedPath, NULL, path4.CGPath);
myLayer.path=combinedPath;

A: Use
void CGPathAddPath (
  CGMutablePathRef path1,     // The mutable path to change.
  const CGAffineTransform *m, // A pointer to an affine transformation matrix, or NULL if no transformation is needed. If specified, Quartz applies the transformation to path2 before it is added to path1.
  CGPathRef path2             // The path to add.
);

Code example:
CGMutablePathRef combinedPath = CGPathCreateMutableCopy(path.CGPath);
CGPathAddPath(combinedPath, NULL, path2.CGPath);
CGPathAddPath(combinedPath, NULL, path3.CGPath);
CGPathAddPath(combinedPath, NULL, path4.CGPath);
myLayer.path = combinedPath;

A: The Swift 4.1 version of @Kjuly's answer
In Swift You can use the CGMutablePath
Code example:
let combinedPath = CGMutablePath()
combinedPath.addPath(path1)
combinedPath.addPath(path2)
....
combinedPath.addPath(path_n)

myLayer.path = combinedPath

A: import UIKit
import QuartzCore
import CoreGraphics

class ViewController: UIViewController,UIGestureRecognizerDelegate {
var btnview : UIButton!
var buttonCenter = CGPoint.zero
var firstlayerpoint = CGPoint.zero
var firstLayer = CAShapeLayer()
var secondLayer = CAShapeLayer()
var thirdLayer = CAShapeLayer()
var initialPosition = CGRect()
let label = UILabel()
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var blueLabel: UILabel!
@IBOutlet weak var greenLabel: UILabel!
@IBOutlet weak var redLabel: UILabel!
    override func viewDidLoad() {
    super.viewDidLoad()

        firstLayer = self.createCircleWithBounds(bounds: CGRect(x:0, y:0, width:100,height:100), Position: self.view.center, StrokeColor: UIColor.blue, LineWidth: 20.0)
        firstLayer.strokeStart = 0.00
        firstLayer.strokeEnd = 0.33

        self.view.layer.addSublayer(firstLayer)

        secondLayer = self.createCircleWithBounds(bounds: CGRect(x:0, y:0, width:100,height:100), Position: self.view.center, StrokeColor: UIColor.red, LineWidth: 20.0)
        secondLayer.strokeStart = 0.33
        secondLayer.strokeEnd = 0.66
        self.view.layer.addSublayer(secondLayer)

        thirdLayer = self.createCircleWithBounds(bounds:  CGRect(x:0, y:0, width:100,height:100), Position: self.view.center, StrokeColor: UIColor.green, LineWidth: 20.0)
        thirdLayer.strokeStart = 0.66
        thirdLayer.strokeEnd = 1.00
        self.view.layer.addSublayer(thirdLayer)

    btnview = UIButton(frame: CGRect(x: self.view.center.x - 20 , y: self.view.center.y - 20 , width: 40, height: 40))
    btnview.backgroundColor = UIColor.gray
    btnview.isUserInteractionEnabled = true
    let panGesture = UIPanGestureRecognizer(target: self, action: #selector(self.panButton(panGesture:)))
    // panGesture.minimumNumberOfTouches = 1

    btnview.addGestureRecognizer(panGesture)

    self.view.addSubview(btnview)
    // Do any additional setup after loading the view, typically from a nib.
        nameLabel.isHidden = true
        blueLabel.isHidden = true
        greenLabel.isHidden = true
        redLabel.isHidden = true
}

func panButton(panGesture: UIPanGestureRecognizer) {

    //let translation = panGesture.translation(in: self.btnview)
    panGesture.view!.center =  btnview.center
    panGesture.setTranslation(CGPoint.zero, in: self.view)
    // var point = CGPoint.zero
    //  point = firstLayer.frame.size.center

    if panGesture.state == .began {

        label.isHidden = false
        buttonCenter = btnview.center // store old button center
    }
    else if panGesture.state == .ended || panGesture.state == .failed || panGesture.state == .cancelled {

        print(btnview.frame.origin.x)
        print(greenLabel.frame.origin.x)
        if btnview.frame.origin.x > greenLabel.frame.origin.x
        {
            //    lblflayer.isHidden = false
            //    lblsecondlayer.isHidden = true
            //    lblthirdlayer.isHidden = true
            nameLabel.isHidden = false
            nameLabel.text = "Blue"
            nameLabel.backgroundColor = UIColor.blue

        }
        else if btnview.frame.origin.x > blueLabel.frame.origin.x
        {
            // print(btnview.frame.origin.x)
            //  print(lblsecondlayer.frame.origin.x)
            //     lblsecondlayer.isHidden = false
            //   lblflayer.isHidden = true
            //    lblthirdlayer.isHidden = true
            nameLabel.isHidden = false
            nameLabel.text = "Red"
            nameLabel.backgroundColor = UIColor.red

        }

        else  if btnview.frame.origin.x > redLabel.frame.origin.x
        {
            print(btnview.frame.origin.x)
            print(redLabel.frame.origin.x)
            greenLabel.isHidden = true
            //  lblsecondlayer.isHidden = true
            //  lblthirdlayer.isHidden = false

            nameLabel.isHidden = false
            nameLabel.text = "Green"
            nameLabel.backgroundColor = UIColor.green
        }
        else
        {
            nameLabel.isHidden = true
            // lblflayer.isHidden = true
            // lblsecondlayer.isHidden = true
            //  lblthirdlayer.isHidden = true
        }

        btnview.center = buttonCenter // restore button center
    }
    else
    {
        let location = panGesture.location(in: view) // get pan location
        btnview.center = location // set button to where finger is
    }

}

func createCircleWithBounds(bounds: CGRect, Position position: CGPoint, StrokeColor color: UIColor, LineWidth lineWidth: CGFloat) -> CAShapeLayer {
    //let shapelayer = CAShapeLayer.layer
    let shapelayer = CAShapeLayer()
    shapelayer.strokeColor = color.cgColor
    shapelayer.fillColor = UIColor.clear.cgColor
    shapelayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: bounds.width / 2).cgPath
    shapelayer.bounds = bounds
    shapelayer.position = position
    shapelayer.lineCap = kCALineCapButt
    shapelayer.lineWidth = lineWidth
    return shapelayer
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Best Solution to Create a change History for several SQL Tables I've searched a long time and don't found an solution here yet. Also this question is a little bit subjectiv. But i really need a good solution for this task.
I have a table with Volumes, Security and much more informations.
This data are daily changed.
Now i need to keep this changes in a history.
What is the best Solution to do this?
Making a Second table with the same Structure and just insert the "old" data into this table?
Or just making an additional parameter with Status?
Making this server side with triggers?
Or programmatically with a LINQ procedure?

A: We chose separate tables as it will keep your primary table lean and faster.  We also opted for triggers, reasoning that if you ever change the entry mechanism, you wouldn't want to have to rewrite your auditing.  Also it can capture accidental DBA side changes.
Since update is effectively a delete and then an insert, you can achieve what has been suggested with a single trigger- this is what we did.

*

*Create a table exactly matching your existing table, but with some added columns:
AUDIT_GUID VARCHAR(40),
AUDIT_TIMESTAMP DATETIME,
AUDIT_ACTION VARCHAR(20)

*Create an "AFTER INSERT,DELETE,UPDATE" Trigger using the following general pattern (simply add more columns where necessary).
CREATE TRIGGER CustomerAudit ON Customer
AFTER INSERT,DELETE,UPDATE AS
BEGIN
    IF (TRIGGER_NESTLEVEL()>1) RETURN

    DECLARE @Time DateTime = CURRENT_TIMESTAMP
    DECLARE @Audit_GUID varchar(100) = NEWID()

    INSERT INTO Customer_History (FirstName, LastName, Audit_Date, Audit_Action, Audit_GUID)
    SELECT
        FirstName, LastName, @Time, 'Delete', @Audit_GUID
    FROM
        Deleted

    INSERT INTO Customer_History
(FirstName, LastName, Audit_Date, Audit_Action, Audit_GUID)
    SELECT
        FirstName, LastName, @Time, 'Insert', @Audit_GUID
    FROM
        Inserted
END

If you want to find updates, they will be rows in the history table that have a delete & update with the same Audit_GUID value. The timestamp also allows you to check changes made at a certain time, and we've also added a currentuser to find the person to blame if necessary!

A: I would opt for a ON DELETE/ON UPDATE trigger that stores deleted or modified rows to a second table.
This way you

*

*can keep up referential integrity

*can build sensible unique keys in your "live data" table

*don't have to remember adding WHERE IsDeleted = 'N' (or the like) with every query you make

*have automatic historization with your data even if you modify it directly on the database

This keeps usability and performance up with your live data. For historic data you'd have to go to your history tables, which in my experience can be cumbersome if the queries are complex and you want to mix live and historic data into one result. Depends on your use case if that kind of usage is a likely scenario.

A: I think its better to create a separate table to track the history along with required fields and date, so that you can query this table as and when required. You can use triggers to log.

A: I suggest to create an historical table (suffix _HIST) with all data.  You need three triggers to store UPDATES, DELETIONS and INSERTIONS.

A: Don't build what you can't buy off the shelf. Google for database auditing software, there's lots out there.


text:
Q: Lanczsos-Eigenvector in Mahout I am attempting machine learning in Mahout, Java. I have downloaded all the data I want with MySQL. The point where I am stuck is when my variable of type "SparseRowMatrix" has all computations and rearrangements done. I simply do not understand how to call any of the two methods I can see fit:
1) org.apache.mahout.math.decomposer.lanczos.LanczosSolver
2) org.apache.mahout.math.hadoop.decomposer.DistributedLanczosSolver
Any advice is helpful at this point!

A: DistributedLanczosSolver implements the Tool interface, so you can run it as a regular Hadoop job, for example:
hadoop jar $MAHOUT_HOME/mahout-examples-0.5-job.jar org.apache.mahout.math.hadoop.decomposer.DistributedLanczosSolver --input /path/to/input --output /path/to/output --numCols 42 --numRows 42 --cleansvd "true" --rank 5

You could also call this directly from Java using:
ToolRunner.run(new DistributedLanczosSolver().job(), args);

Alternatively if you don't need to do it in a distributed fashion, the LanczosSolver.solve method is what you are looking for, you have to pass it your matrix, your eigen vectors and eigen values. It does some complicated stuff behind the hood using Lanczos algorithm which I wouldn't be able to explain, so I recommend you look directly for more clarity in the source code.


text:
Q: Why enabling Voice Processing on AVAudioInputNode changes channels count on its format? I've noticed that enabling voice processing on AVAudioInputNode change the node's format - most noticeably channel count.
let inputNode = avEngine.inputNode
print("Format #1: \(inputNode.outputFormat(forBus: 0))")
// Format #1: <AVAudioFormat 0x600002bb4be0:  1 ch,  44100 Hz, Float32>
try! inputNode.setVoiceProcessingEnabled(true)
print("Format #2: \(inputNode.outputFormat(forBus: 0))")
// Format #2: <AVAudioFormat 0x600002b18f50:  3 ch,  44100 Hz, Float32, deinterleaved>

Is this expected? How can I interpret these channels?
My input device is an aggregate device where each channel comes from a different microphone. I then record each channels to separate files.
But when voice processing messes up with the channels layout, I cannot rely on this anymore.


text:
Q: How to get the difference in time using javascript? im trying to get the current time timeNow in javascript and at the end of the script get
timeEnd which is when the script finished executing for example:
newDate = new Date();
timeNow = newDate.getTime();

for(i=0; i < 5; i ++){

    console.log("printing" + i);
}

timeEnd = timeNow - newDate.getTime();

console.log(timeEnd);

i want to get the time it took to excute this script in seconds or milliseconds, but the result is 0. i don't see why, can you help me thanks.

A: The Date object does not keep ticking once it's constructed, it only represents a single instant in time.
You need to re-evaluate the time at the end of the script and then compare that value with the first one.
Note that on modern ES5 browsers you can use the "static" Date.now() function to get the current time.  This is less expensive that constructing a whole new Date object.  On older browsers you can emulate this function with this shim:
Date.now = Date.now || function() {
    return +(new Date);
};

At which point the required code becomes:
var start = Date.now();

// do your stuff here
...

var end = Date.now();

var elapsed = end - start;

FWIW, your simple loop reports 2ms when run on the Chrome console on my laptop.

A: This happens because you create only a single Date object. These don't change; you will have to do:
timeEnd = timeNow - new Date().getTime();

(note the blank between new and Date)

A: var t = new Date().getTime();
// code
console.log(new Date().getTime() - t);

A: Because it takes less than a millisecond to perform 5 iterations I would imagine.

A: you can use
starttime = Number(new Date());
endtime = Number(new Date());

A: I actually don't think it is iterating in less than an millisecond.  It think the problem is that when you call newDate.getTime() repeatedly it returns the same value each time.  The object, once you create it, is set at the time it was created.  You'll need to create a new Date() object to compare the original against.
From my Firebug Console:
>>> d = new Date()
Date {Thu Aug 23 2012 10:45:52 GMT-0600 (Mountain Daylight Time)}
>>> d.getTime()
1345740352582
>>> d.getTime()
1345740352582
>>> d.getTime()
1345740352582
>>> d.getTime()
1345740352582

I can assure you that I didn't manually make the calls to d.getTime() in less than a millisecond.

A: Basically, Do this
newDate = new Date();
timeNow = newDate.getTime();

for(i=0; i < 50; i++){
    console.log("printing" + i);
}

futureDate = new Date()
timeEnd =  futureDate.getTime();
timeLength = timeEnd - timeNow;

console.log(timeLength);


text:
Q: Java set and get method if statement I have this main class:
import java.util.Scanner;

public class Rec
{

    public static void main(String[] args)
    {
        rectangle myRectangle = new rectangle();
        float w;
        float h;
        Scanner input = new Scanner (System.in);
        System.out.println("Please enter the width of the rectangle");
        w = input.nextFloat();
        myRectangle.setWidth(w);
        //if(myRectangle.width)

        System.out.println("Please enter the height of the rectangle");
        h = input.nextFloat();
        myRectangle.setHeight(h);

        System.out.println("The Perimeter of a rectanle having height of " +myRectangle.height + " and width of " + myRectangle.width + " is " + myRectangle.FindPerimeter());
        //System.out.println(myRectangle.width);
        //System.out.println(myRectangle.FindPerimeter());
        //System.out.println(myRectangle.FindArea());
    }

}

And I have this rectangle class below. How can I code it so that when user inputs a number more than 20 or less than 0, the program will ask user to input again? Here is the rectangle class:
package rec;

public class rectangle
{

        float width=1;
        float height=1;
        float perimeter;

        public void setWidth(float w)
        {
           if(w<20 && w>0)
               width = w;
           else
           {
               System.out.println("invalid entry, please try again: ");
               //setWidth(w);
           }
        }

        public void setHeight(float h)
        {
           if(h<20 && h>0)
               height = h;
           else
           {
               System.out.println("invalid entry, please try again: ");
               //setWidth(h);
           }
        }

        public float getWidth()
        {
           return width;
        }
        public float getHeight()
        {
           return height;
        }
        public float FindPerimeter()
        {
           return (width+height)*2;
        }

        public float FindArea()
        {
           return width*height;
        }

}

Thanks in advance!

A: Don't do it in your setter. If you do you are mixing your "model" and your "input" in one class, so if you want to change it (say to read from a file) it's much harder.
Change your calling code:
h = -1;
while(h < 0 || h > 20) {
    System.out.println("Please enter the height of the rectangle");
    h = input.nextFloat();
}
myRectangle.setHeight(h);

The other approach would be to try setting the height and have the function return true on success or false on failure - this way all the validation is in the one place
bool done = false;
while(!done) {
    System.out.println("Please enter the height of the rectangle");
    h = input.nextFloat();
    done = myRectangle.setHeight(h);
}

public bool setHeight(float h)
{
   bool ok = false;
   if(h<20 && h>0) {
       height = h;
       ok = true;
   }
   return ok;
}

A: Having setHeight return a boolean to indicate whether the height is valid is one possible solution.  There are a couple of disadvantages, though:
(1) If you forget to check the result when you call setHeight, your program will think everything is fine when in fact the setHeight failed.  This is too easy to do in Java, because you can call a method and throw away the result:
setHeight(40.0);
// keep going as if everything were hunky dory

(2) If I'm not mistaken, there are some frameworks that expect "setter" methods to have void results.  I think this is in the definition of a "bean".
My approach would be to add methods to test for validity:
public class rectangle
{
    float width=1;
    float height=1;
    float perimeter;

    public boolean isValidWidth(float w) {
       return (w < 20 && w > 0);
    }

    public void setWidth(float w)
    {
       if(isValidWidth(w)) {
           width = w;
       } else {
           throw new IllegalArgumentException("Invalid width");
       }
    }

    // and similarly for height

}

Then the calling code would become something like:
boolean done = false;
while(!done) {
    System.out.println("Please enter the width of the rectangle");
    w = input.nextFloat();
    done = myRectangle.isValidWidth(w);
}
myRectangle.setWidth(w);

or
do {
    System.out.println("Please enter the width of the rectangle");
    w = input.nextFloat();
} while (!myRectangle.isValidWidth(w));  // keep going as long as width is *not* valid
myRectangle.setWidth(w);

The throw is there in case the program forgets to do the validity check first.  If the caller tries to call setWidth(w) and w is invalid, the program will not just continue on as if everything were OK.  Instead, the program would die on an exception (or would catch the exception somewhere else).
But both of these solutions put the validity check inside rectangle where it belongs; so I think both are better than requiring the caller to know what the bounds are.


text:
Q: Bootstrap not working in newly created page MVC C# I need to send some mails from my website.
I've made a template, a cshtml page, I want to use bootstrap for styling. I use bootstrap in the whole project. But the problem is, the styling is not working.
I use this in some views and I put this in this template:
 @model OnlineCarStore.Models.PurchaseVM
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" integrity="sha384-y3tfxAZXuh4HwSYylfB+J125MxIs6mR5FOHamPBG064zB+AFeWH94NdvaCBm8qnd" crossorigin="anonymous">

<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-glyphicons.css" type="text/css">

<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">

Thanks for the order!

Details:

Order details

No:

 @Model.Id

Date:

 @Model.Date.ToShortDateString()

In the other page the bootstrap is working well, the styling works. But in this page, the styling it's not working. All the details from order appears, but without any styling. It should appear like this:

Can you please advise what to, in order to make the bootstrap work in this page, too.

A: If styles in your sent email not work, write inline styles. Because when you send email only inline styles work.

A: You have this reference to bootstrap 4.0.0-alpha.2
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" integrity="sha384-y3tfxAZXuh4HwSYylfB+J125MxIs6mR5FOHamPBG064zB+AFeWH94NdvaCBm8qnd" crossorigin="anonymous">

but do not include the mathcing bootstrap.js

you then also have this reference for bootstrap 3.0.0-rc1:

<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/css/bootstrap.min.css">

and two jquery references:

you should choose either bootstrap 3 or 4, and not have both. Whichever you choose will need a single css, and a single js reference.
Similarly, you should only have one reference to jquery itself.


text:
Q: C++ : how to get the uncompressed size using zlib or lib_tar I tried the below code, but it is very slow,
Looking for any optimal way to caluclate the uncompressed data size.
I read somewhere using zstream structure -> inflate api we can speedup the performance. could you please help me to get it done.
 /* skip regfile */
int move_file_pointer(TAR *t)
{

    int i, k;
    size_t size;
    char buf[T_BLOCKSIZE];
    if (!TH_ISREG(t))
    {
        errno = EINVAL;
        return -1;
    }
    size = th_get_size(t);
    std::printf("\n Current File  Position - %lu", gztell(l_gzFile));
    long int luOffset= 0;
    int reminder =  size % T_BLOCKSIZE ;
    if(reminder == 0 )
    {
        luOffset = (size/T_BLOCKSIZE) * T_BLOCKSIZE;
    }
    else
    {
        luOffset = ((size/T_BLOCKSIZE) * T_BLOCKSIZE) + T_BLOCKSIZE ;
    }
    std::printf("\n Targeted Seek offset value %lu", luOffset);
    std::printf("\n Targeted Seek offset value %lu", luOffset);

    /*
    ######################################################
    If you look here gzseek is taking long time to complete. for small zip file such as 500 MB, it consuming 2 mins to move end of file.
    I have TAR *t datatype here.
    gzFile l_gzFile file pointer here.
    Using these two data types.
    How can i seek to end in fast / optimal way.
    ##################################################### */
    k = gzseek(l_gzFile, luOffset , SEEK_CUR); // l_gzFile is from gzFile data type.

    if (k == -1)
    {
        if (k != -1)
            errno = EINVAL;
    return -1;
    }
    std::printf("\n After Read Block - %lu", gztell(l_gzFile));
    return 0;
}

void getUnTarFileSize(std::string f_cSourePath)
{
    std::string dest = "/fs/usb0/untar_zlib/test/";
    TAR *l_pTarInfo = NULL;
    char *l_pcTarFileSourcePath = const_cast<char * >(f_cSourePath.c_str());
    char *l_pcTarFileDestPath =  const_cast<char * >(dest.c_str());
    //open tar archive
    if (0 != (tar_open(&l_pTarInfo, l_pcTarFileSourcePath, &gztype,  O_RDONLY, 0, TAR_GNU)))
    {
        std::printf("tar_open(): %s \n", std::strerror(errno));
    }
    else
    {
        int i = 0;
        unsigned long totalSize = 0;
        unsigned long current_size = 0;
        std::printf("\n Current File  Position - %lu \n", gztell(l_gzFile));
        while ((i = th_read(l_pTarInfo)) == 0)
        {
            char *fName = th_get_pathname(l_pTarInfo);
            current_size = th_get_size(l_pTarInfo);

            printf("\n Size of fName %s = %d", fName,current_size);
            totalSize += current_size;

            if (TH_ISREG(l_pTarInfo) && (move_file_pointer(l_pTarInfo) != 0)) {
                  fprintf(stderr, "tar_skip_regfile()\n");
                  printf("\n Value of read=%d, Error=%s\n",i,std::strerror(errno));
                  break;
            }
            fName = NULL;
            printf("\n\n");
        }
        if(-1 == i)
        {
            printf("\n Value of read=%d, Error=%s\n",i,std::strerror(errno));
        }
        else
        {
            printf("\n Total Size of given zip file=%d\n",totalSize);
        }
    }
}

int main()
{
    getUnTarFileSize("/fs/usb0/untar_zlib/a.tar.gz");
}

A: If you are asking how to know the uncompressed size of the contents of a gzip (.gz) file, then the only reliable way is to decompress it.  See this answer here for more details.


text:
Q: Configuration service throwing exception with Docker Okay so I am learning to work with microservices with docker
I got so far very simple services, however when I try to configure my config-server with another service I get an exception:
Exception:
Connect Timeout Exception on Url - http://config-server:8888/. Will be trying the next url if available
2021-12-20 20:26:09.425  WARN [currency-exchange,,] 1 --- [           main] o.s.b.context.config.ConfigDataLoader    : Could not locate PropertySource ([ConfigServerConfigDataResource@72d1ad2e uris = array<String>['http://config-server:8888/'], optional = true, profiles = list['default']]): I/O error on GET request for "http://config-server:8888/currency-exchange/default": Connection refused (Connection refused); nested exception is java.net.ConnectException: Connection refused (Connection refused)

config service properties:
server.port=8888
spring.application.name=spring-cloud-config-server
spring.cloud.config.server.git.default-label=main
spring.cloud.config.server.git.uri=https://github.com/fastaca/CloudConfig/

As you can see I am pointing url to a github repository.
Repository:
*currency-exchange.yml*

server:
  port: 8007

NOTE: the configuration service image name is config-server
currency-exchange properties:
spring.config.import=optional:configserver:http://config-server:8888/
spring.application.name=currency-exchange
spring.cloud.config.enabled=true

docker-compose.yaml:
config-server:
    image: config-server
    ports:
      - "8888:8888"
    networks:
      - currency-network
    environment:
      EUREKA.CLIENT.SERVICEURL.DEFAULTZONE: http://naming-server-microservice:8761/eureka
      SPRING.ZIPKIN.BASEURL: http://zipkin-server:9411/

  currency-exchange-microservice:
    image: currency-exchange-microservice
    networks:
      - currency-network
    depends_on:
      - naming-server-microservice
      - rabbitmq
    environment:
      EUREKA.CLIENT.SERVICEURL.DEFAULTZONE: http://naming-server-microservice:8761/eureka
      SPRING.ZIPKIN.BASEURL: http://zipkin-server:9411/
      RABBIT_URI: amqp://guest:guest@rabbitmq:5672
      SPRING_RABBITMQ_HOST: rabbitmq
      SPRING_ZIPKIN_SENDER_TYPE: rabbit

funny thing is I tried running the contrainer a couple of times and one time it was successful, but since then I keep getting that exception.
Still new to this.

A: What version of docker-compose are you using?
Try deleting the networks section from each compose service and try again. Sometimes adding networks causes the dns to mess up in docker-compose.


text:
Q: All combinations of a dataframe, grouped by ID and ordered by ascending elements I am new to Python and trying to create an output based on all the possible outcomes of a column whilst always starting with the first result on that ID. Here is an example dataframe similar to the data I'm using:
    ID A B C
    1  a 1 10
    1  b 3 40
    1  c 2 20
    2  a 3 90
    2  b 1 10
    2  c 4 60
    2  d 8 100

I want to group by the ID, to create an output where the a column is all the possible results based on A, and B & C are the sum of those combinations.
    ID  Combo  B  C
    1     a    1  10
    1    a,b   4  50
    1   a,b,c  6  70
    2     a    3  90
    2    a,b   4  100
    2   a,b,c  8  160
    2  a,b,c,d 16 260

I've tried using a groupby on ID in conjunction with permutations/combination/product, however the results always end up looking something like this... (I've not started the sum part yet)
  ID  Combo  B C
   1  a,b,c  x x
   1  a,c,b  x x
   1  b,a,c  x x
   1  c,a,b  x x
   1  b,c,a  x x
   1  c,b,a  x x
   etc.

Can anyone point me towards the right direction here please? I thought combination is the correct method here. It seems every question I've found always wants the format above, rather than aiming for the output I'm looking for, so I can't find the answers I need.

A: Use GroupBy with a cumulative sum over the string and numeric columns:
df['A'] = (
    df.groupby('ID')
    .apply(lambda x: x['A'].add(',').cumsum().str.strip(','))
    .reset_index(0, drop=True)
)
df[['B', 'C']] = df.groupby('ID').cumsum()
df = df.rename(columns={'A': 'Combo'})

   ID    Combo   B    C
0   1        a   1   10
1   1      a,b   4   50
2   1    a,b,c   6   70
3   2        a   3   90
4   2      a,b   4  100
5   2    a,b,c   8  160
6   2  a,b,c,d  16  260

A: Almost similar to @Erfan's answer but slightly optimized:
g = df.groupby("ID")
df["A"] = g["A"].apply(pd.Series.cumsum).str.join(",")
df[["B", "C"]] = g.cumsum()
print(df)

Output:
   ID        A   B    C
0   1        a   1   10
1   1      a,b   4   50
2   1    a,b,c   6   70
3   2        a   3   90
4   2      a,b   4  100
5   2    a,b,c   8  160
6   2  a,b,c,d  16  260


text:
Q: JuMP: How to get multiple solutions from getvalue(x) I'm solving this Multi-Objective problem

    f1(x,y) = x
    f2(x,y) = (2.0-exp(-((y-0.2)/0.004)^2)-0.8*exp(-((y-0.6)/0.4)^2) )/x

    isdefined(:f1) || JuMP.register(:f1, 2, f1, autodiff=true)
    isdefined(:f2) || JuMP.register(:f2, 2, f2, autodiff=true)

    m = Model(solver=IpoptSolver(print_level=0))
@variable(m, 0.1 <= x <= 1.0)
@variable(m, 0.0 <= y <= 1.0)
@variable(m, alpha1)
@variable(m, alpha2)
@NLobjective(m, Min, alpha1 + alpha2)
@constraint(m, f1(x,y) - z1_id >= -alpha1)
@constraint(m, f1(x,y) - z1_id <= alpha1)

@NLconstraint(m, f2(x,y) - z2_id >= -alpha2)
@NLconstraint(m, f2(x,y) - z2_id <= alpha2)
solve(m)
x_opt = getvalue(x)
y_opt = getvalue(y)

println("GOAL Programming (p=1): F1 = $(f1(x_opt, y_opt)), F2 = $(f2(x_opt, y_opt))")

It should have two solutions. I get only the first one with getvalue(x), how can I get all the others?

A: I ran into something similar, but in integer programming. Nevertheless, as my search for an answer to took me here, this seems like a good place to share my ideas.
To me it seems the way to go about this is to first solve the system and then add a constraint that the previously found solution is now unfeasible. My idea would be to append as per the following:
solve(m)
x_opt = getvalue(x)
y_opt = getvalue(y)
println("GOAL Programming (p=1): F1 = $(f1(x_opt, y_opt)), F2 = $(f2(x_opt, y_opt))")

eps = 1.e-15
@constraint(m, x - x_opt <= eps)
@constraint(m, x - x_opt >= eps)
@constraint(m, y - y_opt <= eps)
@constraint(m, y - y_opt >= eps)
solve(m)
println("GOAL Programming (p=1): F1 = $(f1(x_opt, y_opt)), F2 = $(f2(x_opt, y_opt))")

I've done the same within a loop for my integer programming, i.e. wrapping the last lines in while solve(m) == :Optimal, for finding more options.


text:
Q: Evidence for data mining (specification search) in published results Is there an established way to assess the prevalence of data mining (as in specification search, not in the machine learning sense) in academic publications?
I vaguely remember hearing something about meta studies plotting p-values against sample-sizes or something of that sort, but I can't seem to find a single reference and fail to see right-away why this would be informative.

A: One study dealing with this I came across studied the distribution of p values in published economics articles. They found that the common thresholds are usually just undercut. I.e. p-values cluster just below 5% and 10%. This is similar to what is asked for in the original question, but probably not the only/most well-known answer. Link to the article https://www.aeaweb.org/articles.php?doi=10.1257%2Fapp.20150044


text:
Q: Get all numbers from an integer array? How would i go upon getting all the numbers in a declared array, then get the length, meaning how many numbers in it, then divide by that to find the average of all the numbers in it.
package students;
import java.util.ArrayList;

public class students {

private ArrayList<Integer> scores = new ArrayList<Integer>();

    private String name;
    private int testScore;

    public students(){
        name = null;
        testScore = 0;
    }

    public students(String s, int t){
        name = s;
        testScore = t;
    }

    public void addQuiz(int t){
        scores.add(t);
    }

    public void averageGrade(){
        //get all the scores in the array and divide by the amount for average grade
    }
}

Theres my code

A: Since Java 8 there is a Method for calculating an average:
http://docs.oracle.com/javase/8/docs/api/java/util/DoubleSummaryStatistics.html#getAverage--
And the respective Integer version can be found here:
http://docs.oracle.com/javase/8/docs/api/java/util/IntSummaryStatistics.html#getAverage--

A: public void averageGrade() {

    int sum = 0;
    float average = 0.0f;

    for(int i = 0; i < scores.size(); i++)
        sum += scores.get(i);       // Compute total score

    average = (float)sum / scores.size();  // Compute average

    System.out.println(average);
}


text:
Q: Flask-migrate upgrade fails because the application needs to run code that modifies the db on startup I have a Flask application that needs to run code on startup. In my case, it detects available cloud resources and writes those to a table in a database.
The problem is that when I run flask db upgrade, then flask-migrate executes the application startup code, including the code that tries to write to the db table. Since the migration itself is what creates the table, the table doesn't exist yet, and the migration fails.
Here is the code, with irrelevant parts removed:
def create_app():
    app = Flask(__name__, static_url_path=None)
    with app.app_context():
        db = set_up_database_connection()

    Migrate(app, db)

    # This is what fails because the table doesn't exist yet
    run_startup_tasks()

    @app.get('/')
    def health_check():
        return 'OK'

    app.logger.info("Application created.")
    return app

I did a temporary workaround by using the @app.before_first_request annotation. With the workaround, the startup code runs just before the first request comes through. This is not ideal, though, since that causes the first request to the application to take a long time.
 @app.before_first_request
 def perform_startup_tasks():
     run_startup_tasks()

How do I run startup tasks that require the database without breaking flask-migrate?

A: I ended up solving this problem by just creating a separate file, which runs the startup tasks:
app = Flask(__name__, static_url_path=None)
with app.app_context():
    db = set_up_database_connection()

run_startup_tasks()

This file is run before the main application is run, and after the migrations are run:
flask db upgrade && python run_startup_tasks.py && flask run

This fixes the problem, since the main application (which flask-migrate uses) doesn't run startup tasks. It's run in a separate script.


text:
Q: Exact file extension match with GetFiles()? I'd like to retrieve a list of files whose extensions match a specified string exactly.
DirectoryInfo di = new DirectoryInfo(someValidPath);
List<FileInfo> myFiles = new List<FileInfo>();
foreach (FileInfo fi in di.GetFiles("*.txt"))
{
    myFiles.Add(fi);
}

I get the files with extension *.txt but I also get files with the extension *.txtx, so what I've coded amounts to getting the files whose extension starts with txt.
This isn't what I want.  Do I need to grab all of the filenames and do a regular expression match to "\\.txt$" (I think), or test each filename string with .EndsWith(".txt"), etc.,   to accomplish this?
Thanks!

A: Somewhat of a workaround, but you can filter out exact matches with the Where extesion method:
foreach (FileInfo fi in di.GetFiles("*.txt")
    .Where(fi => string.Compare(".txt", fi.Extension, StringComparison.OrdinalIgnoreCase) == 0))
{
   myFiles.Add(fi);
}

Note that this will make a case insensitive matching of the extension.

A: Using the AddRange feature of lists instead of doing the foreach loop and calling Add for each item returned by the expression below (which I save into the variable list).
var list = di.GetFiles("*.txt").Where(f => f.Extension == ".txt");
myFiles.AddRange(list);

I'm presuming you were just showing us a snippet of your code and myFiles already had values in it, if not, you could do instead.
List<FileInfo> myFiles = di.GetFiles("*.txt").Where(f => f.Extension == ".txt").ToList();

A: Regex might be overkill. Use the extension on FileInfo.
foreach (FileInfo fi in di.GetFiles("*.txt").Where(f => f.Extension == ".txt"))
{
     myFiles.Add(fi);
}

A: Try this:
DirectoryInfo di = new DirectoryInfo(someValidPath);
List<FileInfo> myFiles =
    (
        from file in di.GetFiles("*.txt")
        where file.Extension == ".txt"
        select file
    ).ToList();

A: DirectoryInfo di = new DirectoryInfo(someValidPath);
List<FileInfo> myFiles = new List<FileInfo>();
foreach (FileInfo fi in di.GetFiles("*.txt"))
{
   if (fi.Extension == ".txt")
      myFiles.Add(fi);
}

A: Couldn't you just add an if and check the last four characters of the filename?

A: If you are using C# 2.0
Isn't easier ?
string fileExtensionFilter = "*.txt";
            DirectoryInfo di = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
            List<FileInfo> myFiles = new List<FileInfo>();
            foreach (FileInfo fi in di.GetFiles(fileExtensionFilter))
            {
                if (fi.Extension == fileExtensionFilter.Substring(1)) myFiles.Add(fi);
            }

A: I had a user-supplied pattern so many of the other answers didn't suit me. I ended up with this more general purpose solution:
public string[] GetFiles(string path, string pattern)
{
    bool lastWildIsHook = false;
    if(pattern.EndsWith("?"))
    {
        pattern = pattern.Substring(0, pattern.Length - 1);
        lastWildIsHook = true;
    }
    var lastWildIndex = Math.Max(pattern.LastIndexOf("*"), pattern.LastIndexOf("?"));
    var endsWith = pattern.Length > lastWildIndex ? pattern.Substring(lastWildIndex + 1) : pattern;
    if(!lastWildIsHook)
        return Directory.GetFiles(path, pattern).Where(p => p.EndsWith(endsWith)).ToArray();
    else
        return Directory.GetFiles(path, pattern).Where(p => p.EndsWith(endsWith) || p.Substring(0, p.Length - 1).EndsWith(endsWith)).ToArray();
}


text:
Q: Visual C# Program 'xyz' does not contain a static 'Main' method suitable for an entry point I apologize if this question has already been asked. Also, please bear with me as I am new to C# and just beginning to learn it. I am trying to write a simple program (hello world) to learn, but when I compile the program I get an error. Below is the screen shot after I try to build the solution. I would appreciate any help on this.

A: Main, not main. C# is case-sensitive.


text:
Q: Status bar not changing during the splash screen loading Ionic I am using the ionic plugin.
And it works fine but when the app loads it doesn't implement the color chosen during the splash screen.
app.js
  if (window.StatusBar) {
    if (ionic.Platform.isAndroid()) {
      StatusBar.backgroundColorByHexString("#11c1f3");
    } else {
      StatusBar.styleLightContent();
    }
  }

I already have the splash screen plugin installed.


text:
Q: Github Actions - workflow_run three levels of workflows For example in my repository I have 3 github action workflows
integration.yml
name: integration

on:
  workflow_dispatch:
  push:
    branches: ["develop"]

jobs:
  tests:
    uses: blablablabla............

develop-tagging.yml
name: develop-tagging

on:
  workflow_dispatch:
  workflow_run:
    workflows: ["integration"]
    branches: ["develop"]
    types:
      - completed

jobs:
    actions-tagger:
      if: ${{ github.event.workflow_run.conclusion == 'success' }}
      runs-on: ubuntu-latest
      steps: blablablabla............

develop-deployment.yml
name: develop-deployment

    on:
      workflow_dispatch:
      workflow_run:
        workflows: ["develop-tagging"]
        branches: ["develop"]
        types:
          - completed

    jobs:
      actions-deployment:
      runs-on: ubuntu-latest
      steps: blablablabla............

When i make changes to develop
Expectation

integration --> develop-tagging --> develop-deployment

Reality

integration --> develop-tagging

In the documentation:
You cannot use workflow_run to chain more than three levels of workflows
https://docs.github.com/es/actions/learn-github-actions/events-that-trigger-workflows#workflow_run
Workflow develop-deployment never runs
Any suggestion?
Thanks

A: *

*see api Create a workflow dispatch event need ref to determine the branch, also you can see that in manual run.

*then see the event need file in default branch, and the GITHUB_REF is constant, so guess that event trigger the next workflow with the default branch.

*so run a demo, remove develop-deployment.yml braches limit, it works.

name: develop-deployment
on:
      workflow_dispatch:
      workflow_run:
        workflows: ["develop-tagging"]
        types:
          - completed

jobs:
  actions-deployment:
      runs-on: ubuntu-latest
      steps:
        - run: echo 'C'


text:
Q: Как решить задачу «читателя и писателя» с буферным пулом (динамическим массивом)? Сама задача:
Рассмотрим взаимодействие двух потоков, один из которых пишет данные в буферный пул, а другой считывает их из пула. Буферный пул состоит из N буферов, каждый содержит одну запись. В общем случае поток-писатель и поток-читатель имеют разные скорости (длительности выполнения операция чтения и записи) и обращаются к пулу с переменной интенсивностью (начинают выполнять операции в случайные моменты времени с равномерным законом распределения). Для правильной работы поток-писатель приостанавливается, когда все буферы заняты, и переходит в активное состояние при наличии хотя бы одного свободного буфера. Поток-читатель приостанавливается, когда все буферы пусты, и активизируется, когда появляется, по крайней мере, одна запись.
Количество потоков-писателей и читателей, длительности операций чтения и записи, размер буферного пула устанавливаются пользователем.
Буферный пул в данном случае - динамический массив, если я верно понял преподавателя. По условию задачи поток-читатель и поток-писатель приостанавливаются в ожидании непустого и пустого буфера соответственно.
Каким образом реализовать проверку на наличие пустого-непустого буфера, чтобы активизировались потоки?
Каким образом передавать в поток-читатель или в поток-писатель адрес освободившегося буфера для работы с ним?
Основной принцип работы потоков схож с примером на википедии (тут), но можно решить и с 2 семафорами.


text:
Q: Simple function display only home page I have a simple function that I need to assign to a hook, and then have it appear only on the home page.
I just cannot seem to get it right.
add_action( 'woo_content_before', 'woo_add_home_slider' );

function woo_add_home_slider () {
    if ( function_exists( 'soliloquy_slider' ) ) soliloquy_slider( '169' );
}

I need this to only show on my homepage.

A: To make your function display only on the home page, you would use the WordPress function is_home() and/or is_front_page, depending on your home page settings.
If your home page is set to list your blog posts, then this would be your solution:
function woo_add_home_slider() {
    if (is_home()) {
        if ( function_exists( 'soliloquy_slider' ) ) soliloquy_slider( '169' );
    }
}

If your home page is set to display a specific page:
function woo_add_home_slider() {
    if (is_front_page()) {
        if ( function_exists( 'soliloquy_slider' ) ) soliloquy_slider( '169' );
    }
}

Or, depending on your settings, you might be able to get the effect you want by combining the two with an or:
If your home page is set to list your blog posts, then this would be your solution:
function woo_add_home_slider() {
    if (is_home() || is_front_page()) {
        if ( function_exists( 'soliloquy_slider' ) ) soliloquy_slider( '169' );
    }
}

Of course, you could combine the ifs into a single condition, like so:
function woo_add_home_slider() {
    if ((is_home() || is_front_page()) && function_exists( 'soliloquy_slider' )) {
        soliloquy_slider( '169' );
    }
}


text:
Q: Flutter Http.put to update data coming from api I have a screen a user profile screen with all the user info, in that same screen i have a button that when presses it will send to edit profile screen where the user can change his account info, i get the account info from the api, im trying to use http.put so when the user writes something to update his name and surname and when the user presses the save changes button i want the data to update to what the user wrote, and in the profile screen the data should be updated. Im getting a 415 error message.
final editedFirstName = TextEditingController();
  final editedLastName = TextEditingController();

 body: FutureBuilder<Response>(
                future: futureData,
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    AccountData data3 = AccountData.fromJson(
                      json.decode(snapshot.data!.body),
                    );
                    updatedFirstName = data3.firstName;
                    updatedLastName = data3.lastName;

                                       child: TextField(
                                        controller: editedFirstName,
                                        //initialValue: updatedFirstName,
                                        decoration: InputDecoration(
                                          border: OutlineInputBorder(),
                                        ),
                                        style: TextStyle(
                                            fontSize: 17,
                                            fontWeight: FontWeight.bold),
                                        inputFormatters: [
                                          LengthLimitingTextInputFormatter(15)
                                        ],
                                      ),

                                      child: TextField(
                                        controller: editedLastName,
                                        //initialValue: updatedLastName,
                                        decoration: InputDecoration(
                                          border: OutlineInputBorder(),
                                        ),
                                        style: TextStyle(
                                            fontSize: 17,
                                            fontWeight: FontWeight.bold),
                                        inputFormatters: [
                                          LengthLimitingTextInputFormatter(15)
                                        ],
                                      ),

  late Future<Response> futureData;
  String? updatedFirstName;
  String? updatedLastName;

  final editedFirstName = TextEditingController();
  final editedLastName = TextEditingController();

  Future<void> putAccountData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? authorization = prefs.getString('authorization');
    var url = 'https://dev.api.wurk.skyver.co/api/v1/employees/account';
    final Map payload = {
      "firstName": editedFirstName.text,
      "lastName": editedLastName.text
    };
    try {
      final response = await http.put(Uri.parse(url),
          headers: <String, String>{
            'authorization': authorization ?? basicAuth.toString()
          },
          body: json.encode(payload));
      print(response.body);
    } catch (er) {
      print(er);
    }
  }

                              ElevatedButton(   // button to update changes and navigate to the
                                                profile screen with the updated data
                              child: const Text(
                                'Save Changes  ✓',
                                style: TextStyle(fontSize: 18),
                              ),
                              onPressed: () {
                                print(editedFirstName.text);
                                print(editedLastName.text);
                                Navigator.pushReplacement(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) => const ProfileScreen(),
                                  ),
                                );
                              },
                            ),

A: Try this:
ElevatedButton(
   child: const Text(
      'Save Changes  ✓',
      style: TextStyle(fontSize: 18),
   ),
   onPressed: () async {
      await putAccountData();
      print(editedFirstName.text);
      print(editedLastName.text);
      Navigator.pushReplacement(
         context,
         MaterialPageRoute(
            builder: (context) => const ProfileScreen()),
     );
   },
)

Put putAccountData outside the build method but in the class like so:
      Future<void> putAccountData() async {
         String url = 'some url';
         final Map payload = {
           "firstName": editedFirstName.text,
           "lastName": editedLastName.text
         };
         try {
            final response = await http.put(Uri.parse(url),
               body: jsonEncode(payload));
               print(response.body);
          } catch (er) {}
      }


text:
Q: Is it possible to specify a custom path for packages.config for nuget? I'm working on a little project and i'm running into an issue which is very likely related to my folder structure.
My Project
If possible at all for the folder structure to keep existing like that i would probably need a way to specify which packages.config to load on a per project basis.
I want this structure to ensure unique files without having to maintain references through file links.
However in order for the compiles to work some projects need other framework targets. Now unless i can specify a path to seperate packages.config i am forced to split up my csproj files into seperate folders again? Does anyone know a way around this issue?

A: You have multiple projects in the same directory. NuGet supports that with a packages.config file named after the project:
packages.ProjectName.config

If your project has a space in it then with NuGet 2 you need to replace the space with an underscore.
packages.Project_Name.config


text:
Q: C# Anonymous and returning filtered properties with JSON What is the best way to return only few properties to JSON Result from a collection IEnumerable?
Department object has 7properties I only need to 2 of them in client. Can I do this using C# anonymous types?
    public class Department
    {
        public string DeptId { get; set; }
        public string DeptName { get; set; }
        public string DeptLoc1 { get; set; }
        public string DeptLoc2 { get; set; }
        public string DeptMgr { get; set; }
        public string DeptEmp { get; set; }
        public string DeptEmp2 { get; set; }
    }

    [HttpGet]
    public JsonResult DepartmentSearch(string query)
    {

        IEnumerable<Department> depts = DeptSearchService.GetDepartments(query);

        //Department object has 15 properties, I ONLY need 2 (DeptID and DeptName) in the view via returns JSON result)

        return Json(depts, JsonRequestBehavior.AllowGet); // I don't want all the  properties of  a department object
   }

A: Sure, I json serialize anonymous types all the time. Is a sensible plan.

A: Use Linq projection
untested code
var deptsProjected = from d in depts
                    select new {
                       d.DeptId,
                       d.DeptName
                    };
 return Json(deptsProjected , JsonRequestBehavior.AllowGet);

A: var deptnames = depts.Select(d => new { d.DeptID, d.DeptName });

Then just use deptnames


text:
Q: How can I sum a list of numbers, which they're strings? I have this code, in which we get info from a .txt file, that when I go through the .txt, and .split() them, I get a list with a format ["Party", "Gender", "Name", and 13 entries of numbers, in strings "" (for example: "1", "15", "3", etc)], I wanna add this info as a tuple in a list called distrito17.
data = open("votacion.txt", "r", encoding="UTF-8")
distrito17 = []
for infocandidato in data:
    infocandidato=infocandidato.split()
    total = #?
    distrito17.append((infocandidato[:3], total)))

return distrito17

I know I can use this form:
... for vote in infocandidato[3:]
        total+=int(vote)

And then add it to the list, but I was wondering if there is a way to use sum(), because I can do a sum(), which would help but the entries are strings, so I can't make a sum out of strings obviusly, but I have seen in some codes people use some kind of codes where:
sum(for i in infocandidato[3:], ... )

Or some sort, does anyone have a idea?
Thanks in advance.

A: You're probably looking for
sum([int(i) for i in infocandidato[3:]])


text:
Q: Uncaught SyntaxError: Unexpected token < on each js file that invoked in the index html I am using mean stack to build a website, when testing, chrome returns the error like:

Uncaught SyntaxError: Unexpected token <   angular.js:1.

I don't know what's wrong and what should i do.

Here is the directory of my app:
E-study
  -client
   -app
   -components
    -all the libraries are here.
   -index.html
   -controllers.js
  -node_modules
  -server
   -config
    -server.js

And I run the server in E-study like :node server/config/server.js
The scripts in the index.html is<script src="client/components/angular/angular.js"></script>
Just don't know why all the js files are changed to index.html when open in the browser.

A: open up those library files and see if there are some extra symbol < probably you will find it in the beginning.. if still not able to fix... simply download the fresh library (if those are libraries) from the internet and try again.
make sure that you don't put <script> </script> tags in the included .js files. that is an incorrect syntax for script files.
also make sure you are providing the correct path??? providing incorrect path can return a builtin customized error page. which is html. may be that is the source of error because returned page is HTML which is most likely going to start with a < symbol. and offcourse not a js file.
to ensure that the incorrect path is the issue just copy the path you included in the code and and paste into your favorite browsers url bar and hit enter. if you are not getting the script in plain text.. then it means you are not providing the correct path.
and if it is return a customized error page like .. 404 not found  then probably it is returning the html and this is where the error is coming from.

A: In external js files, which you refer in some other files, don't use <script>..</script> tag.

A: For express server try to set the static path to entire project folder.It worked for me
app.use(express.static(__dirname ));

A: Could be a ReCaptcha bot checker type thing intercepting requests for JS files and serving up an HTML page instead, which is invalid HTML so it throws the < is invalid message error.
I know siteground specifically has issues with this intercepting CDN routed traffic.
Check with the host to remove this issue, in this case it's their anti-bot security setup.  This has remedied these issues with Siteground for me.


text:
Q: ExpressJS + React Native + MongoDB for creating mobile and Web? What do you use on making website and mobile apps in one project?
Someone advice this:

*

*Express JS for Website

*React Native for Mobile app

*MongoDB for database

Do you have any experience to build other way?
Any help would be appreciated


text:
Q: Method with generic collection parameter i have a method, which should accept collection (perhaps IEnumerable<T> or List<T>) of any type (e.g. List<int> or List<string>).
inside of method i need to iterate collection and each element convert to string and add them together into one final string, like:
"(12, 123, 22)"

Problem is how to define that parameter collection can be of any type. I guess this is something about generics, but i do not know much about it.
However, i thing method definition should look something like this:
public string myMethod(List<T> list) { }

However, compiler does not allow it. Can you please tell me correct syntax?

A: class A
{
    public string myMethod<T>(List<T> list) { }
}

or
class B<T>
{
    public string myMethod(List<T> list) { }
}

Probably you may want to use IEnumerable<T> because you need just to enumerate over the sequence.

The same you can achieve using built-in functions:
IEnumerable<X> input = new List<X> { new X(), new X() };
IEnumerable<string> s = list.Select(x => x.ToString());
string result = String.Join(", ", s); // "x, x"

See MSDN.


text:
Q: Getting current Git branch name using dulwich library I am trying to get the name of the current branch of a Git repository using the dulwich library. I have spent lots of time looking through dulwich's documentation but could not find out how to do this.

A: The active branch is whatever branch "HEAD" currently points at. You can get that ref in Dulwich using something like this:
 >>> from dulwich.repo import Repo
 >>> x = Repo('.')
 >>> ref_chain, commit_sha = x.refs.follow(b'HEAD')
 >>> ref_chain[1]
 b'refs/heads/master'

There is now also a dulwich.porcelain.active_branch function in master that can do this for you.

A: This is my final result, which removes the initial refs/heads/ prefix:
>>> from dulwich.repo import Repo
>>> import re
>>> repo = Repo('.')
>>> (_, ref), _ = repo.refs.follow(b'HEAD')
>>> match = re.search(r'/([^/]+)$', ref.decode('utf-8')
>>> match[1]
'master'


text:
Q: Determining distributions/relations between two random variables "A manufacturer of a certain product has a label weight for this product of 20.4 grams. The weight of the products are given by $X \sim N(21.37,0.16)$.
Suppose 15 of these products are selected randomly and weighed. Let Y be the number of these products that weigh less than $20.857$ grams. Find $P(Y \leq 2)$"
My first thought was that Y must be binomialy distributed, each element having the option of being either over or under the weight $20.857$. The number of trials is $n = 15$, the probability  $p = P(X \leq 20.857)$. Thus we seek to determine binomialcdf(n,p,k) = binomialcdf(15,p,2). To determine $p$ we calculate Normalcdf(a,b,$\mu$,$\sigma$) = Normalcdf(0,20.857,21.37,0.4) $\approx 0.099833$.
Thus we get binomialcdf(15,p,2) $\approx 0.81657$. The answer in the textbook is $0.8159$, frustratingly close. Is my entire line of reasoning wrong, or did I miss something in my calculations? (Note that in my actual caculations, I did not 'round' anything as I went along)

A: The solution of the textbook is based on rounding:
$\text{Normalcdf}(0,20.857,21.37,0.4)\approx 0.099833 \approx 0.1$
$P(Y\leq 2)=P(Y=0)+P(Y=1)+P(Y=2)$
$=\binom{15}{0} \cdot 0.1^0\cdot 0.9^{15}+\binom{15}{1} \cdot 0.1^1\cdot 0.9^{14}+\binom{15}{2} \cdot 0.1^2\cdot 0.9^{13}=0.8159$
Rounded up to 2 decimal places.


text:
Q: Call to undefined function App\Http\Controllers\Frontend\Auth\access() After inserting credentials for login, I got this below error in Laravel 6.16.1

Call to undefined function App\Http\Controllers\Frontend\Auth\access()

A: What that error is saying is that Laravel did not find the method you presume to have declared inside class App\Http\Controllers\Frontend\Auth. Your login method is not named access.
If it is so still, you probably want to run php artisan config:cache and composer du


text:
Q: Mixing a FLV audio stream with a WAV background track, and converting to MP3 with SoX and FFmpeg I'm building a Flash-based recording application for a contracted web site. It streams the recorded voice (via SWF) to a Red5 server, then uses a combination of FFmpeg and SoX to compile the vocal audio with a lower-in-volume background music track. This all has to happen on-demand, that is, when a user "saves" his or her vocal recording.
Here is an example command I will be running. Names have been changed to protect the innocent. The filenames describe their role in the final file:
sox --combine mix -p --no-show-progress --norm "|ffmpeg -i /usr/share/red5/webapps/audiorecorder/stream/SPOKEN_VOICE.flv -t wav pipe:1" /var/www/ufiles/music/BACKGROUND_MUSIC.wav - | ffmpeg -i pipe:1 /var/www/ufiles/recordings/COMPILED_AUDIO_RECORDING.mp3

When I run this command in the shell, this is what happens:
$ sox --combine mix -p --no-show-progress --norm "|ffmpeg -i audioStream_1321399534128_21.flv -ar 44100 -ac 2 -t wav pipe:1" wrong.wav - | ffmpeg -i pipe:1 ~/www/trauma101.com/compiled.mp3
ffmpeg version N-34884-g7575980, Copyright (c) 2000-2011 the FFmpeg developers
  built on Nov 15 2011 14:06:49 with gcc 4.4.5
  configuration: --enable-gpl --enable-version3 --enable-nonfree --enable-postproc --enable-libfaac --enable-libmp3lame --enable-libx264 --enable-x11grab --enable-libspeex
  libavutil    51. 25. 0 / 51. 25. 0
  libavcodec   53. 34. 0 / 53. 34. 0
  libavformat  53. 20. 0 / 53. 20. 0
  libavdevice  53.  4. 0 / 53.  4. 0
  libavfilter   2. 48. 1 /  2. 48. 1
  libswscale    2.  1. 0 /  2.  1. 0
  libpostproc  51.  2. 0 / 51.  2. 0
ffmpeg version N-34884-g7575980, Copyright (c) 2000-2011 the FFmpeg developers
  built on Nov 15 2011 14:06:49 with gcc 4.4.5
  configuration: --enable-gpl --enable-version3 --enable-nonfree --enable-postproc --enable-libfaac --enable-libmp3lame --enable-libx264 --enable-x11grab --enable-libspeex
  libavutil    51. 25. 0 / 51. 25. 0
  libavcodec   53. 34. 0 / 53. 34. 0
  libavformat  53. 20. 0 / 53. 20. 0
  libavdevice  53.  4. 0 / 53.  4. 0
  libavfilter   2. 48. 1 /  2. 48. 1
  libswscale    2.  1. 0 /  2.  1. 0
  libpostproc  51.  2. 0 / 51.  2. 0
[libspeex @ 0x1e36b20] Missing Speex header, assuming defaults.
Input #0, flv, from 'audioStream_1321399534128_21.flv':
  Metadata:
    novideocodec    : 0
    server          : Red5 Server 1.0.0 RC2 Rev: 4295
    creationdate    : Tue Nov 15 15:25:41 PST 2011
    canSeekToEnd    : true
  Duration: 00:00:06.77, start: 0.000000, bitrate: 43 kb/s
    Stream #0:0: Audio: speex, 16000 Hz, 1 channels, s16
Invalid duration specification for t: wav
sox FAIL formats: can't open input pipe `|ffmpeg -i audioStream_1321399534128_21.flv -ar 44100 -ac 2 -t wav pipe:1': premature EOF

I think the issue is stemming from the conversion from FLV to WAV in FFmpeg, and since it's being piped in it causes the whole process to fail. I always get that duration warning, but when FFmpeg outputs to a .wav file and the SoX command is run separately, I can still get a WAV from SoX and convert that to MP3 manually. I'd like to do all this in one line, piping the data between applications.
What do I do?

A: Problem is here:
sox FAIL formats: can't open input pipe

I assume you want sox to read from a pipe, normalize and convert to wav. In that case the mix argument is redundant. Something like this would do:
sox -p -t wav - gain -n | ...


text:
Q: mysql returns empty rsult set when searching for a string containing asterik sign I am not sure if the problem I have with the my search function in my system is really what I claimed in the title of this post but I am confused a little bit in this.
I have a search box that searched the database for the given words of characters. But there are some texts in some fields in the database that start with asterisk sign *. Searching for these stuff returns empty result set.
Please guide me for anything causing the problem. I really do appreciate that!
if $kw is * or starts with it, then I get no result records from the bellow query while I know there are alot of records for this sort of search value.
$this->db->select("p.code as pcode,c.category as category ,p.title as ptitle, c.code as ccode");
$this->db->from("promotions as p");
$this->db->join("promo_categories as c", "c.code = p.cat_code");
$this->db->like("p.other", $kw);
$records=$this->db->get();


text:
Q: Spreadsheet summing based on substring match I am struggling with one part of this exercise. I'm able to sum based on one column unique values (i.e. column G). I'm also to extract unique names from columns with multiple names in same cell (column I). What I am not able to do is get work assigned for the person from multiple rows. For simplicity, the work is just divided equally between number of people in that row.
Desired outcome is in column L. Sample sheet to work with is here
https://docs.google.com/spreadsheets/d/1xwv8IV-XNMArSFZEdT8mR-ZbOFHRFFZMfAm7dwm3bbE/edit#gid=741595390

A: Try it as (in J3),
=SUMPRODUCT((D$3:D$8)/(LEN(C$3:C$8)-LEN(SUBSTITUTE(C$3:C$8, " ", ""))+1), --ISNUMBER(SEARCH(I3, C$3:C$8)))


text:
Q: How can I apply a transformation matrix to a point in OpenCV? Suppose I have a transformation matrix Mat tr that I got from getAffineTransform() and a Point2d p. I want the point that is the result of warping p with tr. Does OpenCV provide a way of doing this?

A: cv::transform is used for transforming points with a transformation matrix.

Every element of the N -channel array src is interpreted as N -element vector that is transformed using the M x N or M x (N+1) matrix m to M-element vector - the corresponding element of the output array dst .
  The function may be used for geometrical transformation of N -dimensional points, arbitrary linear color space transformation (such as various kinds of RGB to YUV transforms), shuffling the image channels, and so forth.

There's a concise example in the InputArray documentation (otherwise not relevant):
std::vector<Point2f> vec;
// points or a circle
for( int i = 0; i < 30; i++ )
    vec.push_back(Point2f((float)(100 + 30*cos(i*CV_PI*2/5)),
                          (float)(100 - 30*sin(i*CV_PI*2/5))));
cv::transform(vec, vec, cv::Matx23f(0.707, -0.707, 10, 0.707, 0.707, 20));

Or you can likely just convert the Point2f into a Mat and multiply by the matrix.


text:
Q: Conditionally assign array indices I need to be able to create separate instances of an array depending on some conditional.
I know I can use the spread operator in tandem with a boolean to do the following.
const arr = ['foo',
             'bar',
              ...(conditional ? ['fizz'] : []),
              ...(conditional ? ['buzz'] : [])
            ];

My question is if this method is preferred or if it's better to just conditionally create separate instances of the array.. I.e.
let arr = [];
if (conditional) {
    arr = ['foo', 'bar', 'fizz', 'buzz'];
} else {
    arr = ['foo', 'bar'];
}

The order of the elements in the array does matter. An so I cannot simply assign foo, bar and then conditionally push on fizz, buzz I.e. I may want my array to be like
const arr = ['foo',
             ...(conditional ? ['bar'] : []),
             'fizz',
             ...(conditional ? ['buzz'] : [])
            ];

Any cool ideas?

A: You can use splice to insert elements at specified positions:
let arr = ["first", "third"]
if (condition)
{
    arr.splice(1,0,"second");
    arr.splice(3,0,"fourth");
}

I would prefer not using "smart" syntactic sugars. IMO they affect code readability which does no good in the long run.

A: You could approach the problem from the other end. Use the conditional to remove items.
let arr = ["foo","bar","tax","lax","fiz","buz"];

if (!condition)
{
   arr.splice(arr.indexOf("tax"),1); // removes the item by name
   arr.splice(4,1); // removes the item by position
}

A: Keep it simple:
const arr = [];
arr.push('foo', 'bar');
if (conditional) arr.push('fizz', 'buzz');
… // continue with conditional or non-conditional sections

or respectively:
const arr = [];
arr.push('foo');
if (conditional) arr.push('bar');
arr.push('fizz')
if (conditional) arr.push('buzz');


text:
Q: Node JS serving HTML pages Express I have a multiplayer game where a server connects two clients to play against each other. It works well. However, now I want to add a welcome page where they add their username. I need to send this username to the server. However, the problem is, when loading the welcome page it makes a connection to the server (which is good). But, when i want to load the next page using
location.href = "index.html"

it is not working. In fact, it disconnects from the server and does not reconnect. How do I load multiple files after a player hits a button? And how do I keep these files under the same "client" instance? (without disconnecting). Thank you.

A: Since you have no code, let me take a stab at it. To expand on what @anderson said, Make sure you have your static files available to your app via something like
const staticCont = express.static(__dirname + "/public");

Where "public" is, is the folder directory of all your static files. This way, any link in your app(on the front end) that requires loading of whatever files, will be available to you.
Next, assuming this was done, also, assuming your game is on a singular page, lets say "mygame.html", if you want to load another html or other content into this page without losing/navigating away from "mygame.html", then on the users button press you are going to need AJAX to load in content.
as an example:
Create  a dummy div that will hold your loaded content, lets call it

Then say you have a button on your app that fetches a users bio.
Lets call this button
<button id="usrBio">Get user bio</button>
and the html you want to load is called usrBioPage.html, then you'd need something like:
$('#usrBio').on('click', function(){
    $('#usrBioWrapper').load(' usrBioPage.html ');
});

Thats it. When the user clicks the button, it will load your content in that div. BUT remember, you must set the public directory in your app.js(backend node side) else it wont work.
hope this helps

A: Did you public your index.html file in Node js, to make sure your browser can access the file?


text:
Q: Converting a column list from A2:A142 to a list with commas into cell B1; holding a format as "0000" with leading zeros This code works to convert the column list to a concatenated list with commas, however the format doesn't have leading zeros while the VBA loops in B!.
Dim i As Integer

Dim s As String

i = 2

Do Until Cells(i, 1).Value = ""

If (s = "") Then

s = Cells(i, 1).Value

    Else
        s = s & ", " & Cells(i, 1).Value

    End If
    i = i + 1
Loop
Cells(1, 2).Value = s

A: We will just use formatted values:
Sub qwerty()
Dim i As Integer
Dim s As String

i = 2

Do Until Cells(i, 1).Value = ""
    If (s = "") Then
        s = Format(Cells(i, 1).Value, "0000")
    Else
        s = s & ", " & Format(Cells(i, 1).Value, "0000")
    End If
    i = i + 1
Loop

Cells(1, 2).Value = s
End Sub


text:
Q: Improve the Conditional structure? I am writing a script that checks the current url in the browser and acts accordingly, my code is as follow :
if (url.match("^https?://(www\.)?bing\..+$")) {
    engine = "bing";
} else {
    if (url.match("^https?://(www\.)?google\..+$"))
        engine = "google";
    else
    if (url.match("^https?://(www\.)?yahoo\..+$"))
        engine = "yahoo";
    else .... // etc.
}

and so on for 8 website, i just keep with the if else, is there a way to improve this code, cuz it looks to me dumb.

A: Put your engines in an array and loop,
something like this
   sengs = ['bing','google','yahoo'];
   foreach of yourarray {
        if(url.match("^https?://(www\.)?"+your value+"\..+$")){
            engine = your value;
        }
    }

A: Why not just grab the domain name from the url using match on the url? It would make your code a lot shorter and you don't need to write the almost-same check every time.
var engine = url.match(/:\/\/(.[^\.]+)/)[1];

This piece only grabs the first word after the protocol, which is www for most websites. to make sure you grab the correct name you could wrap this in a function with an extra check:
function getDomainName(url) {
    url = url.match(/:\/\/(.[^/]+)/)[1].split('.');
    return url[url.length - 2].toLowerCase();
}

Calling getDomainName(url) would now return the domain name, which you could use later.
getDomainName('http://bing.com/'); // bing
getDomainName('http://www.google.com/'); // google
getDomainName('http://stackoverflow.com/questions/18380805/improve-the-conditional-structure/'); // stackoverflow
// and so on

Now you just need to check if this value is inside an array of engined you accept. This could be done using Array.indexof.
var engines = ['google', 'bing', 'yahoo'];
var domain = getDomainName(url);

if (engines.indexOf(domain) > -1) {
    engine = domain;
}

Edit: Now you've got your engine name, use this in a switch-case (or if statements if you like these better) and do what you want to do. You can get rid of the engines array if you do this.
Putting all this together, this code is ALL you need:
function getDomainName(url) {
    url = url.match(/:\/\/(.[^/]+)/)[1].split('.');
    return url[url.length - 2].toLowerCase();
}

switch (getDomainName(url)) {
  case "google":
    // do stuff for google's engine.
    break;

  case "bing":
    // Do Bing stuff.
    break;

  case "yahoo":
    // and so on
    break;

  default:
    // None of the engines was found
    break;
}

A: Actually you can get the match position in your variable for the piece of the url that you are looking for.
Like so:
url = ['https://www.google.com','https://www.yahoo.com']

for (var i = 0; i<url.length; i++ )
{
    var site = url[i].match("^https?://(www\.)?([A-Za-z0-9]+)\..+$")[2]
    alert(site)
}

And with that in hand you can switch it to do whatever you are attempting to:
switch(site) {
     case "google": { /* do something..*/ } break;
     case "yahoo" : { /* do something..*/ } break;
}

Follows the working fiddle http://jsfiddle.net/XPT3L/


text:
Q: Is it possible to get rid of unwanted console messages in eclipse Messages in my eclipse (testNG & selenium) projects are getting so much now that wanted outputs from sysout command are getting lost between them. This started recently. They were never these much. I heard there is a way to get rid of the unwanted warning messages or reduce them, at least. How can this be possibly achieved?
I get duplicates of messages like:
    [BaseMessageSender] Connection established, starting reader thread
    [BaseMessageSender] ReaderThread waiting for an admin message
    [JsonMessageSender] Sending message [GenericMessage ==> suiteCount:1,

    testCount:1]
    TestNG] Time taken by org.testng.reporters.jq.Main@11531931: 80 ms
    [TestNG] Time taken by org.testng.reporters.EmailableReporter2@35bbe5e8: 19 ms
    [TestNG] Time taken by org.testng.reporters.XMLReporter@3f0ee7cb: 7 ms
    TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 1 ms
    [Utils] Attempting to create C:\Filepath\....

A: right click on the file you want to run ,then click on the Run Configurations then make sure verbose and Debug checkbox is unchecked .
image link


text:
Q: WIX RemoveFIle error LocalAppDataFolder I am getting the error
"The directory TestDir is in the user profile but is not in the RemoveFile table"
Basically I want my app to install into the local Common "All Users" folder instead of the Program Files folder.
so I have my directory structure as
<Directory Id="TARGETDIR" Name="SourceDir">
  <Directory Id="CommonAppDataFolder">
  </Directory>
  <Directory Id="SystemFolder"/>
  <Directory Id="StartupFolder"/>
  <Directory Id="DesktopFolder"/>
  <Directory Id="ProgramMenuFolder">
    <Directory Id="ProgramMenuVendorFolder" Name="Orion Integration">
    </Directory>
  </Directory>
  <Directory Id="LocalAppDataFolder">
     <Directory Id="ORIONDIR" Name="Orion Integration">
      <Directory Id="INSTALLDIR" Name="TestApp">
        <Directory Id="TestDir" Name="Test">

          <Component Id="BUILDINGFLOORMODELSDIR_C" Guid="A6BD61D8-FAC8-4D7D-881E-58CC2C4F9753"
            SharedDllRefCount="no" KeyPath="no" NeverOverwrite="no" Permanent="no" Transitive="no"
             Location="either">
            <RegistryValue
              Root="HKCU"
              Key="Software\Orion Integration\Orion CMS"
              Name="InstalledBuildingFloorModels"
              Type="integer"
              Value="1" />
           <CreateFolder/>
           <RemoveFolder Id="BUILDINGFLOORMODELSDIR" On="uninstall"/>
          </Component>

        </Directory>
      </Directory>
  </Directory>

...........
I have placed RemoveFIle in the compnent section and still getting errors

A: You need to specify a directory using the <RemoveFolder /> element.
Instead of
<RemoveFolder Id="BUILDINGFLOORMODELSDIR" On="uninstall"/>

try
<RemoveFolder Id="TestDir" On="uninstall"/>


text:
Q: Python IF query I am trying to make a program which calculates entrance costs.. I have managed to do it except from one part which requires if two adults and three childeren then the cost is $15. Should this be done using an if statement and how would I do it?
import math

loop = 1
choice = 0
while loop == 1:

    print "Welcome"

    print "What would you like to do?:"
    print " "
    print "1) Calculate entrance cost"

    print "2) Leave swimming centre"
    print " "

    choice = int(raw_input("Choose your option: ").strip())
    if choice == 1:
        add1 = input("Adults: ")
        add2 = input("Concessions: ")
        add3 = input("Children: ")
        print add1, "+", add2, "+", add3, "answer=", add1 *5 + add2 *3 + add3 *2
    elif choice == 2:
        loop = 0

Thank you for any help in advance, it will be much appreciated!!

A: You should place an if statement for a special case, where you have the 2 adults, 3 children. Otherwise you should calculate it normally. I have commented the area where this special case occurs.
This code also assumes that the special case does not affect the price of the concessions.
import math

loop = 1
choice = 0
while loop == 1:

    print "Welcome"

    print "What would you like to do?:"
    print " "
    print "1) Calculate entrance cost"

    print "2) Leave swimming centre"
    print " "

    choice = int(raw_input("Choose your option: ").strip())

    if choice == 1:
        add1 = input("Adults: ")
        add2 = input("Concessions: ")
        add3 = input("Children: ")

        cost = 0

        # special case for 2 adults, 3 children
        if add1 == 2 and add3 == 3:
            cost += 15
        else:
            cost += add1*5 + add3*2

        # concession cost
        cost += add2 *3

        print add1, "+", add2, "+", add3, "answer=", cost

    elif choice == 2:
        loop = 0

A: import math

choice = 0
while True:

    print """
       Welcome

       What would you like to do?:

       1)Calculate entrance cost
       2) Leave swimming centre
      """

   choice = int(raw_input("Choose your option: ").strip())
   if choice == 1:
       add1 = input("Adults: ")
       add2 = input("Concessions: ")
       add3 = input("Children: ")
       print add1, "+", add2, "+", add3, "answer=", add1 *5 + add2 *3 + add3 *2
   elif choice == 2:
       break


text:
Q: Safari removes word-spacing using Typekit with optimizeLegibility I have a problem with Safari removing the space between words using Typekit font and text-rendering: optimizeLegibility in the css..
It works well in Chrome, so it's not a webkit issue. it works nice in Firefox as well.
The reason I want to use optimizeLegibility is because the kerning is horrible in the webkit browsers..
Any suggestions of what to do?
Edit:
I've created a sample here
(It works well in Firefox and Chrome, but not in Safari 5.1.7(at least not in Windows))
As an alternative if someone could help me getting the start starting point in Firefox as in Chrome I can use lettering.js or something to kern it manually. I couldn't get it to work with text-rendering: optimizeSpeed;
Edit :
Got this answer from Typekit:

I'm sorry you ran into this issue. Unfortunately, we've seen some of
  these issues with: optimizeLegibility in Safari and Chrome. It seems
  to be very random and affect certain fonts.
I'm sorry to say but there isn't much we can do about this on our side
  other than file a bug with Safari/Webkit.
Could you tell me which font is showing the issue? Let me know and
  we'll take it from there.

Hopefully they'll figure something out :)
Edit: I've got more answers from Typekit now.

For the large headlines, you can simply change the setting with CSS.
  That way you have the same starting poing in Firefox:
text-rendering: optimizeSpeed;
This will change the text-rendering for Firefox and others. Then you
  can kern with lettering.js.
I hope this helps. Let me know if you have any further questions.

However I've already tried that, so I let them know, and unfortunately they couldn't help me any more with that issue.
I've attached an image of how it looks like in different browsers, all using Windows 7..

A: It actually is likely to be a webkit issue as webkits were actually invented by apple!
Rendering of fonts is down to the browser and even on the typekit website it seems all their fonts got rendered differently dependant on the browser.
A better alternative would be to use css3's new feature of @font-face and use whatever font you like without the need to use an external service.
The likelihood is that you can also render your text a lot better as you'll have more control over your content.
I'm not really sure where your problem lies, but maybe that alternative will help.
Extra info on webkits:
http://en.wikipedia.org/wiki/WebKit
If you look under origins it'll tell you about apple creating the webkit.


text:
Q: How to create a fractal spiral in python with turtle? I'm trying to create a python program that draws a fractal spiral with user input.
I have looked at other questions very similar to mine but it doesn't quite give me what I would like, and I keep getting error messages.
This is what I have tried:
a = int(input("Size? "))
b = int(input("Angle? "))
c = int(input("How many times do you want to repeat? "))

from turtle import *

def fractalSpiral(size, angle, amount):
  for i in range(amount):
    forward(size)
    left(angle)
    forward(size + 50)
    left(angle + 10)

fractalSpiral(a, b, c)

Witch the inputs a = 50, b = 60, and c = 9, I get the shape in the attachment, which does not look like a fractal spiral.
Can I have some help please?

A: From what I see in the second picture, you want a shape that is constructed of triangles where every triangle is a little bigger than the previous one and also set to a little different angle. I thought I would go with an Egyptian 3:4:5 triangle and came up with this:
def spiral(step, angle, max):
    for i in range(0, max, step):
        turtle.forward(i*3)
        turtle.left(126.87)
        turtle.forward(i*5)
        turtle.left(143.2)
        turtle.forward(i*4)
        turtle.left(90 + angle)

You can now play with the parameters to get a result that would please you. If you want a different triangle, you would need to recalculate its angles using trigonometry. Remember that to get angle alpha, you need to turn you turtle 180 - alpha.


text:
Q: emacs fails to clear image cache So firs of all
ELISP> (version)
"Aquamacs 3.2 GNU Emacs 24.4.51.2\n(x86_64-apple-darwin14.0.0, NS apple-appkit-1343.14)\n of 2014-11-07 (Aquamacs-3.2) on watson.local"

Then I create a solid green image
$ convert -size 100x100 "xc:#009900" /tmp/whatever.png

Then I open it in emacs (aquamacs) C-x C-f /tmp/whatever.png and it is indeed green.
Then M-: (clear-image-cache).
Then run on a shell.
$ convert -size 100x100 "xc:#990000" /tmp/whatever.png

Check that the image with an external program and it is indeed red now.
I M-x revert-buffer on the emacs buffer but the image is still green...
I tried closing the buffer and find-file again and still green.
Restart Aquamacs and the image is now red as it should. Am I missing something?

A: i ran into the same issue (in babel) and solved it by clearing the image cache and toggling display:
(defun redisplay-images ()
  (clear-image-cache)
  (org-redisplay-inline-images))

(add-hook 'org-babel-after-execute-hook 'redisplay-images)

hope it works for you


text:
Q: I have a differencing VHD that's eating away 90+% of my HDD. How can I shrink it? I have a differencing VHD that's eating away 90+% of my HDD. How can I shrink it?
The host OS is W7-64, the virtual is XP32.

A: First, shutdown the VM, then you can compact it.  Go under the VHD editor under Settings and compact it.


text:
Q: Getting 'undefined' returned when trying to sort array of objects with TimSort Here is a code snippet that is very close to what I'm trying to implement in my project: https://repl.it/@Twinbird24/TimSort-example
var timsort = require('timsort');

const arr = [
  {
    name: 'Amy',
    age: 23
  },
  {
    name: 'Bob',
    age: 34
  },
  {
    name: 'Cary',
    age: 18
  }
];

function sort(objectsArr, sortBy, sortOrder = 'ascending') {
  function stringCompare(a, b) {
    return a.sortBy - b.sortBy;
  }
  return timsort.sort(objectsArr, stringCompare);
}

const sortedArr = sort(arr, 'name');

console.log(sortedArr);

Here is the package I'm using: https://www.npmjs.com/package/timsort
I'm trying to sort my array of objects by each object's name property, which holds a string—although my function can also be passed another item to sort by (i.e. 'age').
The documentation for TimSort is not very clear and looking through the source code I'm still not quite able to figure out how to configure my code.
You'll notice in my code that I would also like to choose to sort by 'ascending' or 'descending' but I'm not sure how to add that into the TimSort method I'm using.

A: Your string compare doesn't compare strings.  It will only work for types like numbers or those that have a valueOf, like Date.
Perhaps if you changed it to a < b ? -1 : a > b ? 1 : 0, it would work a little better.  So how about this?:
function sort(objectsArr, sortBy, sortOrder = 'ascending') {
  function stringCompare(a, b) {
    const left = a[sortBy], right = b[sortBy];
    return left < right ? -1 : left > right ? 1 : 0;
  }
  return timsort.sort(objectsArr, stringCompare);
}

This still doesn't answer you ascending/descending question.  It should be straightforward from here, but please ask another question if you can't get it.


text:
Q: I can't create a SharpDX solution in Visual Studio I have recently installed SharpDX and it's Visual Studio extension to create ShardDX solutions. I assume the template used by this extension would add dll dependencies and using statements and etc. But the solution is never created, I get this error when I try:
Unable to find SharpDX installation directory. Expecting [SharpDXSdkDir] environment variable
I googled it and the only result is part of the Visual Studio extension code itself, in a git repository:
https://github.com/sharpdx/SharpDX/blob/master/Source/VisualStudio/SharpDX.VisualStudio.Package/MainWizard.cs
The exact line of the Visual Studio Wizard that is throwing the error:
// Check that SharpDX is correctly installed
        if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("SharpDXSdkDir")))
        {
            MessageBox.Show("Unable to find SharpDX installation directory. Expecting [SharpDXSdkDir] environment variable", "SharpDX Toolkit Wizard Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            throw new WizardCancelledException("Expecting [SharpDXSdkDir] environment variable");
        }

apparently, no one ever had this problem before. I tryed repairing my SharpDX installation but that did no good. Please help?
additional information: I use Visual Studio Ultimate 2012 and Windows 7. I had the SharpDXSdkDir variable already set before having this error (it's value is the installation folder of SharpDX: C:\Program Files (x86)\SharpDX). I tryed to create another variable, now a system variable instead of a user variable, with the same name and same value, and I still get the same error.
[off topic]: By the way, is SharpDX still an active project or has it been discontinued, like XNA? There is nothing on the website saying "we are discontinuing SharpDX" but still, their latest news is from 2013...

A: The problem seems to be that the installation of SharpDX is not creating some environment variables it needs, you can try setting these variables yourself by going to Control Panel->System->Advanced System Configuration, there under Advanced Options look for Environment Variables, under system variables add the required variable (SharpDXSdkDir).
Unfortunately I don't use SharpDX, but you may try by looking for "setting the required variables for SharpDX".

A: That was a bug in the extension code. This is me reporting the issue to their development team: https://github.com/sharpdx/SharpDX/issues/311
Now all I need is a way to fix the extension. I have no idea how. Any help?


text:
Q: android: string format specify bold I have a string defined in string.xml like
<string name="eventtitle">Title: %1$s </string>

which is formatted using string.format . How to define the string to get only the Titel: as Bold.
Thanks in advance for the help

A: Actually, many of the answers are obsolete. After researching by myself, what I've found out that the best answer is one by @Wahib. Here's the improved version:
Define the string resource as a:
<string name="styled_text">Hey, <b>this is bold</b> text</string>

Use the resource like this:
String text = getResources().getString(R.string.styled_text);
CharSequence styledText = HtmlCompat.fromHtml(text, HtmlCompat.FROM_HTML_MODE_LEGACY);
textview.setText(styledText);

Here's the result:

A: You can use HTML markup like "BOLD other text ...".
See this Google resource for more information.

A: You can do it like,
textView.setText(Html.fromHtml("Title: Text"));

If you have text in dynamic way..
And to define formatings in Strings.xml you can do like,
<string name="text1">This text uses bold and italics
by using inline tags such as  within the string file.</string>

see This Link

A: You have to style your string in the TextView in which in is displayed. See this link

A: Now, it is reasonably supported by Android.
you can define the string in xml as <string name="text_to_show">Hey <b>This is in bold</b>
Then in code, use this to convert to CharSequence and then use it for e.g in TextView
String text = getResources().getString(R.string.text-to_show);
CharSequence styledText = Html.fromHtml(text);
textview.setText(styledText);

A: Typeface tfaerial=Typeface.createFromAsset(getAssets(),"fonts/aerial.ttf");
Typeface tfTradeGothicLight=Typeface.createFromAsset(getAssets(), "fonts/TradeGothic-Light.OTF");

String strt_title_desc=this.getResources().getString(R.string.eventtitle);

int upto=strt_title_desc.indexOf(":"); //of you can specify  5
 if (strt_title_desc!=null)
    {
        aboutAuthTV.setTextColor(Color.BLACK);
        aboutAuthTV.setLineSpacing(1.2f, 1.5f);
        aboutAuthTV.setTextSize(23);
    SpannableString SS = new SpannableString(strt_title_desc);
    SS. setSpan ( new StyleSpan(tfTradeGothicLight.getStyle()), 0, upto,Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
    SS. setSpan ( new StyleSpan(tfaerial.getStyle()), upto, strt_dialog_desc.length(),Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
    yourtextView.setText(SS);
}

// this for changing the font size, style and colors
String str="Bold
 Then Normal Text

                         Then Italic " +
                       "
 this is simple sentence " +
                       "

this is simple sentence";
      Spanned strHtml= Html.fromHtml(str);

       TextView tv = (TextView)findViewById(R.id.textView);
       tv.setText(strHtml);

A: Now, it is reasonably supported by Android.
I have already given answer to this how to add styling within a string


text:
Q: Spectrum of a Rectangular signal?
I would be grateful if you can help me with i) ii) and iii) especially with ii and iii

A: Define $T=2$ms and write down the definition of the Fourier transform:
$$X(j\omega)=\int_{-\infty}^{\infty}x(t)e^{-j\omega t}dt=\int_0^{T}e^{-j\omega t}dt=-\frac{1}{j\omega}(e^{-j\omega T}-1)=\frac{1}{j\omega}e^{-j\omega T/2}(e^{j\omega T/2}-e^{-j\omega T/2})=e^{-j\omega T/2}T\frac{\sin(\omega T/2)}{\omega T/2}$$
The maximum value of $|X(j\omega)|$ is at $\omega=0$ and its value is $T$. The zeros of $X(j\omega)$ are are the zeros of $\sin(\omega T/2)$ apart from $\omega=0$, i.e. $\omega=2\pi k/T$, $k=\pm 1, \pm 2, \ldots$


text:
Q: Having trouble with JSFiddle and basic javascript I am trying to use JSFiddle to get a rudimentary base case working and then expand out from it. However, I must be doing something wrong, because I can't even get the js and html windows to work. So here is the code that works. All in the html window:

    <button onclick="myFunction()">click</button>

If I take the function and pop it down into the JS window (with the selector on the window set to LoadType of on Dom Ready. I get a console error of:
Uncaught ReferenceError: myFunction is not defined......
Can someone tell me what silly thing I am missing in order to save me from self-immolation today? Thanks!


text:
Q: ¿Cómo enviar audio con la librería Libshout a shoutcast? El siguiente código me va bien para enviar un audio en vivo hacia un servidor Icecast, podrían decirme como manipulo los datos o configuro para enviarlo a shoutcast ya que no tiene punto de montaje como, por ejemplo en icecast puedo tener "test.mp3" pero en shoutcast yo tengo ";", Además que esto solo en linux funciona, ¿cómo hago para compilarlo para windows?. Libhsout Github
byte[] buffer = new byte[1024];
InputStream mp3 = new BufferedInputStream(new FileInputStream(new File("test.mp3")));
Libshout icecast = new Libshout();
icecast.setHost("localhost");
icecast.setPort(8000);
icecast.setProtocol(Libshout.PROTOCOL_HTTP);
icecast.setPassword("hackme");
icecast.setMount("/mymount");
icecast.setFormat(Libshout.FORMAT_MP3);
icecast.open();
int read = mp3.read(buffer);
while (read > 0) {
    icecast.send(buffer, read);
    read = mp3.read(buffer);
}
icecast.close();
mp3.close();