Passing parameters for methods in Scala (alternatives to change variables values) - scala

I need translate a Java code to Scala, but the compiler show me error. I understand that parameter input on methods are val type. Which alternative i can adopt if i need transform these values? I think to apply case class or class... Below the snippet code (in Scala):
def pmerge_FA(x: Pennant,y: Pennant): Pennant={
if(x == null && y == null && this.root == null){
return null
}else if(x == null && y == null){
return this
}else if(this.root == null && x == null){
return y
}else if(this.root == null && y == null){
return x
}else if(x == null){
y = y.pmerge(this) //error
null
}else if(this.root == null){
y = y.pmerge(x) //error
null
}else if (y == null){
y = this.pmerge(x) // error
null
}else{
y = y.pmerge(x)
this
}
}
Note that error is showed where y parameter is updated.
Thanks

Yes, the error is shown because you cannot reassign something to val, and parameters to methods in Scala are only sent as vals (immutables).
Because you don't provide the full definition of this, it's difficult to suggest an alternative solution, but:
In general, instead of if-else "Java" style, in Scala you can use pattern matching, and instead of null you can use Option, which is very powerful.
For Example, I suggest refactoring your method in this "Scala" Style (partial implementation)
def pmerge_FA(x: Pennant, y: Pennant): Option[Pennant] = {
(Option(x),Option(y), Option(this.root)) match {
case (None, None, None) => None
case (None, None, _) => Option("")
case (None, _, None) => Option(y)
case (_, None, None) => Option(x)
case (None, _, _) =>
....
}
}
Such that you will return the x, y as their new values, or create a case class like:
case class PennantCaseClass (x:Pennant, y:Pennant)
And returning it when needed.
Again, If you will provide some more info about Pennant class it will be easier to give a better alternative implementation for this method.

New values of y (namely y.pmerge(...)) are never used after assignments. So I guess all assignments y = y.pmerge(...) can be replaced with just invocations y.pmerge(...).
Does y.pmerge(...) do any side effects? Just in case, if not then values y.pmerge(...) are never used (only null or this is returned), so in such case lines y = y.pmerge(...) can be removed at all.
So the code can be either (if there are side effects)
def pmerge_FA(x: Pennant,y: Pennant): Pennant={
if(x == null && y == null && this.root == null){
null
}else if(x == null && y == null){
this
}else if(this.root == null && x == null){
y
}else if(this.root == null && y == null){
x
}else if(x == null){
y.pmerge(this)
null
}else if(this.root == null){
y.pmerge(x)
null
}else if (y == null){
this.pmerge(x)
null
}else{
y.pmerge(x)
this
}
}
or (if there are no side effects)
def pmerge_FA(x: Pennant,y: Pennant): Pennant={
if(x == null && y == null && this.root == null){
null
}else if(x == null && y == null){
this
}else if(this.root == null && x == null){
y
}else if(this.root == null && y == null){
x
}else if(x == null){
null
}else if(this.root == null){
null
}else if (y == null){
null
}else{
this
}
}

Oh, right! There are three classes to build a Bag data structure object, with nodes added in perfectly balanced tree. These methods works in that one. Below the complete code (in Java). The Pennant class build a forest using the node of graph object.
Node Class:
public class Node {
private Node left;
private Node right;
private int item;
public Node() {
left = null;
right = null;
item = 0;
}
public Node(int value) {
left = null;
right = null;
item = value;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
public int getItem() {
return this.item;
}
public void setItem(int item) {
this.item = item;
}
}
public class Pennant{
private Node root;
public Pennant() {
this.root = null;
}
public Pennant(int value) {
this.root = new Node(value);
}
public void setRoot(Node root) {
this.root = root;
}
public Node getRoot() {
return this.root;
}
public Pennant pmerge(Pennant y) {
if(this.getRoot() == null) {
return y;
}else {
this.getRoot().setRight(y.getRoot().getLeft());
y.getRoot().setLeft(this.getRoot());
}
return y;
}
public Pennant pmerge_FA(Pennant x, Pennant y) {
if(x == null && y == null && this.getRoot() == null) {
return null;
}else if(x == null && y == null) {
return this;
}else if(this.getRoot() == null && x == null) {
return y;
}else if(this.getRoot() == null && y == null) {
return x;
}else if(x == null) {
y = y.pmerge(this);
return null;
}else if(this.getRoot() == null) {
y = y.pmerge(x);
return null;
}else if (y == null) {
y = this.pmerge(x);
return null;
}else {
y = y.pmerge(x);
return this;
}
}
public Pennant psplit() {
if(this.getRoot() != null && this.getRoot().getLeft() != null) {
Pennant y = new Pennant();
y.setRoot(this.getRoot().getLeft());
this.getRoot().setLeft(y.getRoot().getRight());
y.getRoot().setRight(null);
return y;
}
return null;
}
public void remove_all(Node node) {
if (node.getLeft() != null) {
remove_all(node.getLeft());
}
if(node.getRight() != null) {
remove_all(node.getRight());
}
node = null;
}
}

Related

List Null after mapping the data Flutter

This Is my coding for mapping data and filter it by subs class:
Hi i have a problem where is my list is null after it mapping the data so can you help me for this solution
void onUserJobListData(Event e) {
Map data = Map.from(e.snapshot.value);
data?.forEach((a, b) {
print("key " + a);
// int i = _jobs.indexWhere((j) => j.jobId == a);
int i = _jobs == null ? 0 : _jobs.indexWhere((j) => j.jobId == a);
if (i >= 0) {
if (b['notification_date'] != null) {
_jobs[i].matchDetail.notificationDate = b['notification_date'];
}
if (b['status_date'] != null) {
_jobs[i].matchDetail.statusDate = b['status_date'];
}
if (b['event_status'] != null) {
_jobs[i].matchDetail.eventStatus = b['event_status'];
}
if (b['notification_status'] != null) {
_jobs[i].matchDetail.notificationStatus = b['notification_status'];
}
if (b['status'] != null) {
_jobs[i].matchDetail.status = b['status'];
}
}
});
print("Apa apa jerr");
jobState.setJobList(_jobs, JobState.USER_JOB);
}`

About mybatis3.3 databaseId,the code is useless

I study the mybatis3.3 sources code and now I have a question:in the XMLMapperBuilder.databaseIdMatchesCurrent()
private boolean databaseIdMatchesCurrent(String id, String databaseId, String requiredDatabaseId) {
if (requiredDatabaseId != null) {
if (!requiredDatabaseId.equals(databaseId)) {
return false;
}
} else {
if (databaseId != null) {
return false;
}
// skip this fragment if there is a previous one with a not null databaseId
if (this.sqlFragments.containsKey(id)) {
XNode context = this.sqlFragments.get(id);
if (context.getStringAttribute("databaseId") != null) {
return false;
}
}
}
return true;
}
if the (requiredDatabaseId == null && databaseId != null) ,then the function will return false.
So the code
if (this.sqlFragments.containsKey(id)) {
XNode context = this.sqlFragments.get(id);
if (context.getStringAttribute("databaseId") != null) {
return false;
}
}
certainly no way to return false and this code is useless.
I just want to questioning: I understand this, right?

Reset Boolean values?

I am trying to get my password verifier to loop until a correct response is give. It's looping right now, but its not resetting the boolean values after the first iteration, resulting in a valid response the second time no matter which password. How do I make the loop check for every value, or reset the table every time?
boolean atLeast8 = false;
boolean oneLower = false;
boolean oneUpper = false;
boolean oneNumber = false;
boolean oneSpecial = false;
boolean noAnd = false;
boolean noEnd = false;
do
{
System.out.println("Enter your password. " + '\n');
password = input.nextLine();
System.out.println();
for(int i=0; i<password.length(); i++) //Checks for values througout the length of the string
{
char c = password.charAt(i);
if(password.length() >= 8)
atLeast8 = true;
if(Character.isLowerCase(c))
oneLower = true;
if(Character.isUpperCase(c))
oneUpper = true;
if(Character.isDigit(c))
oneNumber = true;
if(c=='!' || c=='#' || c=='#' || c=='$' || c=='%' || c=='^' || c=='&' || c=='&' || c=='*')
oneSpecial = true;
if (password.indexOf("and") < 0)
noAnd = true;
if (password.indexOf("end") < 0)
noEnd = true;
}
if(atLeast8 && oneLower && oneUpper && oneNumber && oneSpecial && noAnd && noEnd) //Does the string contain any true values?
{
System.out.println("Valid.");
}
else
{
System.out.println("Invalid!"); //Does the string contain any false values?
}
if(!atLeast8)
{
System.out.println("Must be at least 8 characters long.");
}
if(!oneLower)
{
System.out.println("Must contain one lower case letter.");
}
if(!oneUpper)
{
System.out.println("Must contain one upper case letter.");
}
if(!oneNumber)
{
System.out.println("Must contain one numeric digit.");
}
if(!oneSpecial)
{
System.out.println("Must contain one special character.");
}
if(!noAnd)
{
System.out.println("Must not contain the word 'and'.");
}
if(!noEnd)
{
System.out.println("Must not contain the word 'end'.");
}
}while (atLeast8 == false || oneLower == false || oneUpper == false || oneNumber == false || oneSpecial == false || noAnd == false || noEnd == false);
}
}
Can't you just put
atLeast8 = false;
oneLower = false;
oneUpper = false;
oneNumber = false;
oneSpecial = false;
noAnd = false;
noEnd = false;
at the start of the loop (somewhere between the "do {" and the "for")
Or, is that being too simplistic?

video overwriting using ffmpeg - I want to Add video rotation code and rewrite the existing file..How can i do that?

I want to rotate the .mov file which is in portrait mode by 90 degrees, for that i used the following code..
It works but, it results in loss of video frames...
My code is,
public void encode(File source, File target, EncodingAttributes attributes,
EncoderProgressListener listener, Integer i) throws IllegalArgumentException,
InputFormatException, EncoderException {
String formatAttribute = attributes.getFormat();
Float offsetAttribute = attributes.getOffset();
Float durationAttribute = attributes.getDuration();
QualityScale qualityScale = attributes.getQualityScale();
AudioAttributes audioAttributes = attributes.getAudioAttributes();
VideoAttributes videoAttributes = attributes.getVideoAttributes();
if (audioAttributes == null && videoAttributes == null) {
throw new IllegalArgumentException(
"Both audio and video attributes are null");
}
target = target.getAbsoluteFile();
target.getParentFile().mkdirs();
FFMPEGExecutor ffmpeg = locator.createExecutor();
if (offsetAttribute != null) {
ffmpeg.addArgument("-ss");
ffmpeg.addArgument(String.valueOf(offsetAttribute.floatValue()));
}
ffmpeg.addArgument("-i");
ffmpeg.addArgument(source.getAbsolutePath());
if (durationAttribute != null) {
ffmpeg.addArgument("-t");
ffmpeg.addArgument(String.valueOf(durationAttribute.floatValue()));
}
if (qualityScale != null) {
ffmpeg.addArgument("-qscale:"+qualityScale.getQualityStreamSpecifier());
ffmpeg.addArgument(String.valueOf(qualityScale.getQualityValue()));
}
if (videoAttributes == null) {
ffmpeg.addArgument("-vn");
} else {
String codec = videoAttributes.getCodec();
if (codec != null) {
ffmpeg.addArgument("-vcodec");
ffmpeg.addArgument(codec);
}
String tag = videoAttributes.getTag();
if (tag != null) {
ffmpeg.addArgument("-vtag");
ffmpeg.addArgument(tag);
}
Integer bitRate = videoAttributes.getBitRate();
if (bitRate != null) {
ffmpeg.addArgument("-b");
ffmpeg.addArgument(String.valueOf(bitRate.intValue()));
}
Integer frameRate = videoAttributes.getFrameRate();
if (frameRate != null) {
ffmpeg.addArgument("-r");
ffmpeg.addArgument(String.valueOf(frameRate.intValue()));
}
VideoSize size = videoAttributes.getSize();
if (size != null) {
ffmpeg.addArgument("-s");
ffmpeg.addArgument(String.valueOf(size.getWidth()) + "x"
+ String.valueOf(size.getHeight()));
}
FilterGraph filterGraph = videoAttributes.getFilterGraph();
if (filterGraph != null) {
ffmpeg.addArgument("-vf");
if(videoAttributes.getRotate() != null && videoAttributes.getRotate() == 90){
ffmpeg.addArgument("transpose=1");
}else if(videoAttributes.getRotate() != null && videoAttributes.getRotate() == 180){
ffmpeg.addArgument("vflip,hflip");
}
else {
if (filterGraph.isUseExpression()) {
ffmpeg.addArgument(filterGraph.getFilterGraphExpression());
}
}
}
}
if (audioAttributes == null) {
ffmpeg.addArgument("-an");
} else {
String codec = audioAttributes.getCodec();
if (codec != null) {
ffmpeg.addArgument("-acodec");
ffmpeg.addArgument(codec);
}
Integer bitRate = audioAttributes.getBitRate();
if (bitRate != null) {
ffmpeg.addArgument("-ab");
ffmpeg.addArgument(String.valueOf(bitRate.intValue()));
}
Integer channels = audioAttributes.getChannels();
if (channels != null) {
ffmpeg.addArgument("-ac");
ffmpeg.addArgument(String.valueOf(channels.intValue()));
}
Integer samplingRate = audioAttributes.getSamplingRate();
if (samplingRate != null) {
ffmpeg.addArgument("-ar");
ffmpeg.addArgument(String.valueOf(samplingRate.intValue()));
}
Integer volume = audioAttributes.getVolume();
if (volume != null) {
ffmpeg.addArgument("-vol");
ffmpeg.addArgument(String.valueOf(volume.intValue()));
}
}
ffmpeg.addArgument("-f");
ffmpeg.addArgument(formatAttribute);
ffmpeg.addArgument("-y");
ffmpeg.addArgument(target.getAbsolutePath());
try {
ffmpeg.execute();
} catch (IOException e) {
throw new EncoderException(e);
}
try {
String lastWarning = null;
long duration;
long progress = 0;
RBufferedReader reader = null;
reader = new RBufferedReader(new InputStreamReader(ffmpeg
.getErrorStream()));
MultimediaInfo info = parseMultimediaInfo(source, reader);
if (durationAttribute != null) {
duration = (long) Math
.round((durationAttribute.floatValue() * 1000L));
} else {
duration = info.getDuration();
if (offsetAttribute != null) {
duration -= (long) Math
.round((offsetAttribute.floatValue() * 1000L));
}
}
if (listener != null) {
listener.sourceInfo(info);
}
int step = 0;
String line;
while ((line = reader.readLine()) != null) {
System.out.println("line::::"+line);
if (step == 0) {
if (line.startsWith("WARNING: ")) {
if (listener != null) {
listener.message(line);
}
} else if (!line.startsWith("Output #0")) {
//throw new EncoderException(line);
} else {
step++;
}
} else if (step == 1) {
if (!line.startsWith(" ")) {
step++;
} else {
System.out.println("line>>>>>>"+line);
Hashtable table1 = new Hashtable();
Matcher m = ROTATE_INFO_PATTERN.matcher(line);
while (m.find()) {
if (table1 == null) {
table1 = new Hashtable();
}
String key = m.group(1);
String value = m.group(2);
table1.put(key, value);
}
System.out.println("Table values"+table1.get("rotate"));
if(table1.get("rotate") != null){
Object videoRotateValue = table1.get("rotate");
int rotate = Integer.valueOf(videoRotateValue.toString());
switch(rotate){
case 90:
videoAttributes.setRotate(rotate);
if(i == 0){
i++;
encode(source, target, attributes, null, i);
}
break;
case 180:
videoAttributes.setRotate(rotate);
if(i == 0){
i++;
encode(source, target, attributes, null, i);
}
break;
case 270: System.out.println("case 3 :: "+videoRotateValue);
break;
}
}
}
}
if (step == 2) {
if (!line.startsWith("Stream mapping:")) {
throw new EncoderException(line);
} else {
step++;
}
} else if (step == 3) {
if (!line.startsWith(" ")) {
step++;
}
}
if (step == 4) {
line = line.trim();
if (line.length() > 0) {
Hashtable table = parseProgressInfoLine(line);
if (table == null) {
if (listener != null) {
listener.message(line);
}
lastWarning = line;
} else {
if (listener != null) {
String time = (String) table.get("time");
if (time != null) {
int dot = time.indexOf('.');
if (dot > 0 && dot == time.length() - 2
&& duration > 0) {
String p1 = time.substring(0, dot);
String p2 = time.substring(dot + 1);
try {
long i1 = Long.parseLong(p1);
long i2 = Long.parseLong(p2);
progress = (i1 * 1000L)
+ (i2 * 100L);
int perm = (int) Math
.round((double) (progress * 1000L)
/ (double) duration);
if (perm > 1000) {
perm = 1000;
}
listener.progress(perm);
} catch (NumberFormatException e) {
;
}
}
}
}
lastWarning = null;
}
}
}
}
if (lastWarning != null) {
if (!SUCCESS_PATTERN.matcher(lastWarning).matches()) {
throw new EncoderException(lastWarning);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
ffmpeg.destroy();
}
}
Please advise, how to achieve video rotation without any video Frame loss
Thanks In Advance
Lakshmi Priya . K
Worked for couple of days and finally tried to write the rotated video in different target file then i got the video output without any loss and video is also rotated....
Thanks
Lakshmi Priya. K

Compacting the code: same action for any element of a pair

Is there any way to make code more compact for this situation?
// pseudocode
if (A == 1) {
if (B == 2) {
action1;
}
if (B == 3) {
action2;
}
}
if (B == 1) {
if (A == 2) {
action1;
}
if (A == 3) {
action2;
}
}
in Objective-C/Objective-C++?
One more example:
if (((int)fixtureUserDataA == FIXTURE_FOOT_SENSOR || ((int)fixtureUserDataB == FIXTURE_FOOT_SENSOR ))) {
// Hero foot sensors
if (bodyA->GetUserData() != NULL) {
CCSprite * sprite = (CCSprite*)bodyA->GetUserData();
if (sprite.tag == TAG_HERO) {
[Hero sharedInstance].numFootContacts++;
}
}
if (bodyB->GetUserData() != NULL) {
CCSprite * sprite = (CCSprite*)bodyB->GetUserData();
if (sprite.tag == TAG_HERO) {
[Hero sharedInstance].numFootContacts++;
}
}
}
Is it possible to use only one if or more clear construction?
for 2nd example:
checkBody(bodyA);
checkBody(bodyB);
void checkBody(Body* body)
{
CCSprite * sprite = (CCSprite*)body->GetUserData();
if (sprite.tag == TAG_HERO) {
[Hero sharedInstance].numFootContacts++;
}
}
if (A == 1 || B == 1)
if (A + B == 3)
action1;
else if (A + B == 4)
action2;