Q: Hibernate gives a strange ClassCast exception (using Transformers) This code:
@Override
public List<FactCodeDto> getAllFactsWithoutParentsAsFactDto() {
    String completeQuery = FactCodeQueries.SELECT_DTO_FROM_FACT_WITH_NO_PARENTS;
    Query query = createHibernateQueryForUnmappedTypeFactDto(completeQuery);

    List<FactCodeDto> factDtoList = query.list(); //line 133
    return factDtoList;
}

calling this method:
private Query createHibernateQueryForUnmappedTypeFactDto(String sqlQuery) throws HibernateException {
    return FactCodeQueries.addScalars(createSQLQuery(sqlQuery)).setResultTransformer(Transformers.aliasToBean(FactCodeDto.class));
}

gives me a ClassCastException -> part of the trace:
Caused by: java.lang.ClassCastException: org.bamboomy.cjr.dto.FactCodeDto cannot be cast to java.util.Map
    at org.hibernate.property.access.internal.PropertyAccessMapImpl$SetterImpl.set(PropertyAccessMapImpl.java:102)
    at org.hibernate.transform.AliasToBeanResultTransformer.transformTuple(AliasToBeanResultTransformer.java:78)
    at org.hibernate.hql.internal.HolderInstantiator.instantiate(HolderInstantiator.java:75)
    at org.hibernate.loader.custom.CustomLoader.getResultList(CustomLoader.java:435)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2423)
    at org.hibernate.loader.Loader.list(Loader.java:2418)
    at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:336)
    at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:1898)
    at org.hibernate.internal.AbstractSessionImpl.list(AbstractSessionImpl.java:318)
    at org.hibernate.internal.SQLQueryImpl.list(SQLQueryImpl.java:125)
    at org.bamboomy.cjr.dao.factcode.FactCodeDAOImpl.getAllFactsWithoutParentsAsFactDto(FactCodeDAOImpl.java:133)

Which is pretty strange because, indeed, if you look up the source code of Hibernate it tries to do this:
@Override
@SuppressWarnings("unchecked")
public void set(Object target, Object value, SessionFactoryImplementor factory) {
    ( (Map) target ).put( propertyName, value ); //line 102
}

Which doesn't make any sense...
target is of type Class and this code tries to cast it to Map,
why does it try to do that???
any pointers are more than welcome...
I'm using Hibernate 5 (and am upgrading from 3)...
edit: I also use Spring (4.2.1.RELEASE; also upgrading) which calls these methods upon deploy, any debugging pointers are most welcome as well...
edit 2: (the whole FactCodeDto class, as requested)
package org.bamboomy.cjr.dto;

import org.bamboomy.cjr.model.FactCode;
import org.bamboomy.cjr.model.FactCodeType;
import org.bamboomy.cjr.utility.FullDateUtil;
import org.bamboomy.cjr.utility.Locales;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.util.Assert;

import java.util.*;

@Getter
@Setter
@ToString
public class FactCodeDto extends TreeNodeValue {

    private String cdFact;
    private String cdFactSuffix;
    private Boolean isSupplementCode;
    private Boolean isTitleCode;
    private Boolean mustBeFollowed;

    private Date activeFrom;
    private Date activeTo;
    private Boolean isCode;
    private Long idFact;
    private Long idParent;
    private String type;
    Map<Locale, String> description = new HashMap<Locale, String>(3);

    public FactCodeDto() {
    }

    public FactCodeDto(String prefix, String suffix) {
        super();
        this.cdFact = prefix;
        this.cdFactSuffix = suffix;
    }

    public FactCodeDto(String cdFact, String cdFactSuffix, Boolean isSupplementCode,  Boolean mustBeFollowed) {
        super();
        this.cdFact = cdFact;
        this.cdFactSuffix = cdFactSuffix;
        this.isSupplementCode = isSupplementCode;
        this.mustBeFollowed = mustBeFollowed;

    }

    public FactCodeDto(String cdFact, String cdFactSuffix, Boolean isSupplementCode,  Boolean mustBeFollowed, Long idFact, Long idParent, Boolean isCode, Boolean isTitleCode, Date from, Date to, Map<Locale, String> descriptions,String type) {
        super();
        this.cdFact = cdFact;
        this.cdFactSuffix = cdFactSuffix;
        this.isSupplementCode = isSupplementCode;
        this.mustBeFollowed = mustBeFollowed;
        this.idFact = idFact;
        this.idParent = idParent;
        this.isCode = isCode;
        this.isTitleCode = isTitleCode;
        this.activeFrom = from;
        this.activeTo = to;
        if (descriptions != null) {
            this.description = descriptions;
        }

        this.type = type;

    }

    public FactCodeDto(FactCode fc) {
        this(fc.getPrefix(), fc.getSuffix(), fc.isSupplementCode(), fc.isHasMandatorySupplCodes(), fc.getId(), fc.getParent(), fc.isActualCode(), fc.isTitleCode(), fc.getActiveFrom(), fc.getActiveTo(), fc.getAllDesc(),fc.getType().getCode());
    }

    public String formatCode() {
        return FactCode.formatCode(cdFact, cdFactSuffix);
    }

    public boolean isActive() {
        Date now = new Date(System.currentTimeMillis());
        return FullDateUtil.isBetweenDates(now, this.activeFrom, this.activeTo);

    }

    public void setDescFr(String s) {
        description.put(Locales.FRENCH, s);
    }

    public void setDescNl(String s) {
        description.put(Locales.DUTCH, s);
    }

    public void setDescDe(String s) {
        description.put(Locales.GERMAN, s);
    }

    /**
     * public String toString() {
     * StringBuilder sb = new StringBuilder();
     * sb.append(getIdFact() + ": ")
     * .append(getIdParent() + ": ")
     * .append(" " + cdFact + cdFactSuffix + ": " + (isSupplementCode ? "NO Principal " : "   Principal "))
     * .append((mustBeFollowed ? "    Must Be Followed " : "NOT Must Be Followed "));
     * return sb.toString();
     * }
     */

    public Map<Locale, String> getDescription() {
        return description;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        String fullCode = formatCode();
        result = prime * result + ((fullCode == null) ? 0 : fullCode.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        FactCodeDto other = (FactCodeDto) obj;

        return formatCode().equals(other.formatCode());
    }

    @Override
    public boolean isChildOf(TreeNodeValue value) {
        Assert.notNull(value);
        boolean isChild = false;
        if (value instanceof FactCodeDto) {
            if (this.getIdParent() != null) {
                isChild = this.getIdParent().equals(((FactCodeDto) value).getIdFact());
            }

        }
        return isChild;
    }

    @Override
    public boolean isBrotherOf(TreeNodeValue value) {
        Assert.notNull(value);
        boolean isBrother = false;
        if (value instanceof FactCodeDto) {
            if (this.getIdParent() != null) {
                isBrother = this.getIdParent().equals(((FactCodeDto) value).getIdParent());
            }

        }
        return isBrother;
    }

    @Override
    public boolean isParentOf(TreeNodeValue value) {
        Assert.notNull(value);
        boolean isParent = false;
        if (value instanceof FactCodeDto) {
            isParent = this.getIdFact().equals(((FactCodeDto) value).getIdParent());
        }
        return isParent;
    }

    @Override
    public int compareTo(TreeNodeValue to) {
        if (to instanceof FactCodeDto) {
            return formatCode().compareTo(((FactCodeDto) to).formatCode());
        } else return 1;

    }

    public String getCode() {
        return formatCode();
    }

}

A: I found that AliasToBean has changed in Hibernate 5. For me adding getter for my field fixed the problem.

A: This exception occurs when the setters and getters are not mapped correctly to the column names.
Make sure you have the correct getters and setters for the query(Correct names and correct datatypes).
Read more about it here:
http://javahonk.com/java-lang-classcastexception-com-wfs-otc-datamodels-imagineexpirymodel-cannot-cast-java-util-map/

A: I do some investigation on this question. The problem is that Hibernate converts aliases for column names to upper case — cdFact becomesCDFACT.
Read for a more deeply explanation and workaround here:
mapping Hibernate query results to custom class?

A: In the end it wasn't so hard to find a solution,
I just created my own (custom) ResultTransformer and specified that in the setResultTransformer method:
private Query createHibernateQueryForUnmappedTypeFactDto(String sqlQuery) throws HibernateException {
    return FactCodeQueries.addScalars(createSQLQuery(sqlQuery)).setResultTransformer(new FactCodeDtoResultTransformer());
    //return FactCodeQueries.addScalars(createSQLQuery(sqlQuery)).setResultTransformer(Transformers.aliasToBean(FactCodeDto.class));
}

the code of the custom result transformer:
package org.bamboomy.cjr.dao.factcode;

import org.bamboomy.cjr.dto.FactCodeDto;

import java.util.Date;
import java.util.List;

/**
 * Created by a162299 on 3-11-2015.
 */
public class FactCodeDtoResultTransformer implements org.hibernate.transform.ResultTransformer {

    @Override
    public Object transformTuple(Object[] objects, String[] strings) {

        FactCodeDto result = new FactCodeDto();

        for (int i = 0; i < objects.length; i++) {
            setField(result, strings[i], objects[i]);
        }

        return result;
    }

    private void setField(FactCodeDto result, String string, Object object) {

        if (string.equalsIgnoreCase("cdFact")) {
            result.setCdFact((String) object);
        } else if (string.equalsIgnoreCase("cdFactSuffix")) {
            result.setCdFactSuffix((String) object);
        } else if (string.equalsIgnoreCase("isSupplementCode")) {
            result.setIsSupplementCode((Boolean) object);
        } else if (string.equalsIgnoreCase("isTitleCode")) {
            result.setIsTitleCode((Boolean) object);
        } else if (string.equalsIgnoreCase("mustBeFollowed")) {
            result.setMustBeFollowed((Boolean) object);
        } else if (string.equalsIgnoreCase("activeFrom")) {
            result.setActiveFrom((Date) object);
        } else if (string.equalsIgnoreCase("activeTo")) {
            result.setActiveTo((Date) object);
        } else if (string.equalsIgnoreCase("descFr")) {
            result.setDescFr((String) object);
        } else if (string.equalsIgnoreCase("descNl")) {
            result.setDescNl((String) object);
        } else if (string.equalsIgnoreCase("descDe")) {
            result.setDescDe((String) object);
        } else if (string.equalsIgnoreCase("type")) {
            result.setType((String) object);
        } else if (string.equalsIgnoreCase("idFact")) {
            result.setIdFact((Long) object);
        } else if (string.equalsIgnoreCase("idParent")) {
            result.setIdParent((Long) object);
        } else if (string.equalsIgnoreCase("isCode")) {
            result.setIsCode((Boolean) object);
        } else {
            throw new RuntimeException("unknown field");
        }

    }

    @Override
    public List transformList(List list) {
        return list;
    }
}

in hibernate 3 you could set Aliasses to queries but you can't do that anymore in hibernate 5 (correct me if I'm wrong) hence the aliasToBean is something you only can use when actually using aliasses; which I didn't, hence the exception.

A: Im my case :

 => write sql query and try to map result to Class List
 => Use "Transformers.aliasToBean"
 => get Error "cannot be cast to java.util.Map"

Solution :
      => just put \" before and after query aliases
      ex:
      "select first_name as \"firstName\" from test"

The problem is that Hibernate converts aliases for column names to upper case or lower case

A: I solved it by defining my own custom transformer as given below -
import org.hibernate.transform.BasicTransformerAdapter;

public class FluentHibernateResultTransformer extends BasicTransformerAdapter {

    private static final long serialVersionUID = 6825154815776629666L;

    private final Class<?> resultClass;

    private NestedSetter[] setters;

    public FluentHibernateResultTransformer(Class<?> resultClass) {
        this.resultClass = resultClass;
    }

    @Override
    public Object transformTuple(Object[] tuple, String[] aliases) {
        createCachedSetters(resultClass, aliases);

        Object result = ClassUtils.newInstance(resultClass);

        for (int i = 0; i < aliases.length; i++) {
            setters[i].set(result, tuple[i]);
        }

        return result;
    }

    private void createCachedSetters(Class<?> resultClass, String[] aliases) {
        if (setters == null) {
            setters = createSetters(resultClass, aliases);
        }
    }

    private static NestedSetter[] createSetters(Class<?> resultClass, String[] aliases) {
        NestedSetter[] result = new NestedSetter[aliases.length];

        for (int i = 0; i < aliases.length; i++) {
            result[i] = NestedSetter.create(resultClass, aliases[i]);
        }

        return result;
    }
}

And used this way inside the repository method -
@Override
    public List<WalletVO> getWalletRelatedData(WalletRequest walletRequest,
            Set<String> requiredVariablesSet) throws GenericBusinessException {
        String query = getWalletQuery(requiredVariablesSet);

        try {
            if (query != null && !query.isEmpty()) {
                SQLQuery sqlQuery = mEntityManager.unwrap(Session.class).createSQLQuery(query);
                return sqlQuery.setResultTransformer(new FluentHibernateResultTransformer(WalletVO.class))
                        .list();
            }
        } catch (Exception ex) {
            exceptionThrower.throwDatabaseException(null, false);
        }

        return Collections.emptyList();
    }

It worked perfectly !!!

A: Try putting Column names and field names both in capital letters.

A: This exception occurs when the class that you specified in the AliasToBeanResultTransformer does not have getter for the corresponding columns. Although the exception details from the hibernate are misleading.


Q: RxJava: Observable and default thread I have the following code:
Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(@NonNull final ObservableEmitter<String> s) throws Exception {
                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        s.onNext("1");
                        s.onComplete();
                    }
                });
                thread.setName("background-thread-1");
                thread.start();
            }
        }).map(new Function<String, String>() {
            @Override
            public String apply(@NonNull String s) throws Exception {
                String threadName = Thread.currentThread().getName();
                logger.logDebug("map: thread=" + threadName);
                return "map-" + s;
            }
        }).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {}

            @Override
            public void onNext(String s) {
                String threadName = Thread.currentThread().getName();
                logger.logDebug("onNext: thread=" + threadName + ", value=" + s);
            }

            @Override
            public void onError(Throwable e) {}

            @Override
            public void onComplete() {
                String threadName = Thread.currentThread().getName();
                logger.logDebug("onComplete: thread=" + threadName);
            }
        });

And here's the output:
map: thread=background-thread-1
onNext: thread=background-thread-1, value=map-1
onComplete: thread=background-thread-1

Important detail: I'm calling the subscribe method from another thread (main thread in Android).
So looks like Observable class is synchronous and by default and it performs everything (operators like map + notifying subscribers) on the same thread which emits events (s.onNext), right? I wonder... is it intended behaviour or I just misunderstood something? Actually I was expecting that at least onNext and onComplete callbacks will be called on the caller's thread, not on the one emitting events. Do I understand correctly that in this particular case actual caller's thread doesn't matter? At least when events are generated asynchronously.
Another concern - what if I receive some Observable as a parameter from some external source (i.e. I don't generate it on my own)... there is no way for me as its user to check if whether it is synchronous or asynchronous and I just have to explicitly specify where I want to receive callbacks via subscribeOn and observeOn methods, right?
Thanks!

A: RxJava is unopinionated about concurrency. It will produce values on the subscribing thread if you do not use any other mechanisem like observeOn/ subscribeOn. Please don't use low-level constructs like Thread in operators, you could break the contract.
Due to the use of Thread, the onNext will be called from the calling Thread ('background-thread-1'). The subscription happens on the calling (UI-Thread). Every operator down the chain will be called from 'background-thread-1'-calling-Thread. The subscription onNext will also be called from 'background-thread-1'.
If you want to produce values not on the calling thread use: subscribeOn. If you want to switch the thread back to main use observeOn somewhere in the chain. Most likely before subscribing to it.
Example:
Observable.just(1,2,3) // creation of observable happens on Computational-Threads
            .subscribeOn(Schedulers.computation()) // subscribeOn happens only once in chain. Nearest to source wins
            .map(integer -> integer) // map happens on Computational-Threads
            .observeOn(AndroidSchedulers.mainThread()) // Will switch every onNext to Main-Thread
            .subscribe(integer -> {
                // called from mainThread
            });

Here is a good explanitation.
http://tomstechnicalblog.blogspot.de/2016/02/rxjava-understanding-observeon-and.html


Q: How to use a for loop to display an image depending on a position in an index? This is inside a react-native project:
I have a progress bar that has 10 positions, and each position as a possibility of three states - incomplete, active, complete. There is an image that corresponds to each of those states. I was thinking I could use a for loop that would look for the index number of the page, which I'll store in an object, and depending on the relationship between the position in the loop and and the index number, that would determine which image gets displayed. Something like this:
if the position in the loop > index number, display the incomplete image

if the position in the loop = index number, display the active image

if the position in the loop < index number, display the complete image

Beyond this, I'm not even sure on where to start.

A: In your class/component:
  state = {
    indexNum: 4, // arbitrary value
  }

  displayStatus(item) {
    if(item.id > this.state.indexNum){ // Incomplete
      return <View style={styles.progressPoint}><Text>I</Text></View>;
    }
    else if(item.id == this.state.indexNum){ // Active
      return <View style={styles.progressPoint}><Text>A</Text></View>;
    }
    else if(item.id < this.state.indexNum){ // Complete : you can use only 'else' here
      return <View style={styles.progressPoint}><Text>C</Text></View>;
    }

  }

In render() of your class/component:
    // Positions/Pages - these will serve as basis for .map - you can add more than 'id'
    const positions  = [{"id": 1},{"id": 2},{"id": 3},{"id": 4},{"id": 5},
                       {"id": 6},{"id": 7},{"id": 8},{"id": 9},{"id": 10}];
    return (
       <View style={styles.container}>
          {positions.map((item) => (
             this.displayStatus(item)
          ))}
       </View>
    );

Here's an Expo Snack of the above (based on the scope of your question) to get you started.
You can store the index number of the page in state and update this state at completion of each progress position. Note: if you are not using redux, you may need to pass/handle state (index number) on each page individually (depending on your navigation or components structure).


Q: CORS Configuration Flask, Angular and NGINX I'm trying to upload an angular application to a digital ocean droplet using nginx. This app consumes an API in flask. In local everything works pretty well, but on the VPS is not working. It says something about Cross-origin request blocked: Same origin policy does not allow reading of remote resources at http://127.0.0.1:5001/api/talk/
Here's my nginx configuration:
server {
    server_name x.domain.com;
    location / {
            proxy_pass http://127.0.0.1:4200;
            proxy_set_header Host x.domain.com;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Protocol $scheme;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Origin "";
            add_header "Access-Control-Allow-Origin"  "*";
            add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
            add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
    }
 }
 server {

    location / {
            proxy_pass http://127.0.0.1:5001;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Protocol $scheme;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Origin "";
            add_header "Access-Control-Allow-Origin"  "*";
            add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
            add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
    }

    location /api/talk/ {
            proxy_pass http://127.0.0.1:5001;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Protocol $scheme;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Origin "";
    }

    location /api/response/ {
            proxy_pass http://127.0.0.1:5001;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Protocol $scheme;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Origin "";
    }
 }

Here's my flask configuration:
app = Flask(__name__)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})

chat = Chat()

@app.route('/api/talk/', methods=['POST'])
@cross_origin(origin='localhost')
def index():
  print(request.data.decode("utf-8"))
  chat.send_message(request.data)
  return request.data

@app.route('/api/response/', methods=['GET'])
@cross_origin(origin='localhost')
def get():
  response = chat.response
  return response

def options(self):
  return {'Allow': 'POST'}, 200, \
    {'Access-Control-Allow-Origin': '*',
     'Access-Control-Allow-Methods': 'POST,GET'}

if __name__ == '__main__':
  app.run(host='127.0.0.1', port=5001, debug=True)

And angular consumes the flask API here:
export class Message {
  constructor(public content: string, public sentBy: string){ }
}

@Injectable({
  providedIn: "root",
})
export class MessageService {
  conversation = new BehaviorSubject<Message[]>([]);
  readonly SERVER_URL = "http://127.0.0.1:5001";
  public httpClient = axios.create();

  constructor(){}

  update(msg: Message) {
    this.conversation.next([msg]);
  }

  converse(msg: string) {
    const userMessage = new Message(msg, 'user');
    this.update(userMessage);
    this.sendMessage(userMessage.content)
  }

  sendMessage(msg: string) {
    console.log(msg)
    const config = {
    headers: {
      'Content-Type': 'text/plain',
      'Access-Control-Allow-Headers': 'Content-Type',
      'Access-Control-Allow-Methods': 'GET POST',
      'Access-Control-Allow-Origin': '*'
    },
  };
  this.httpClient.post(this.SERVER_URL+'/api/talk/', btoa(msg), config)
    .then(function (response) {
  })
  .catch(function (error) {
     console.log(error);
   });
 }

 async getResponse() {
  await this.delay(900);
  let msg = ''
  return this.httpClient.get(this.SERVER_URL+'/api/response/')
  .then(response => {
     msg = response.data
     const botMessage = new Message(msg, 'chucho');
     this.update(botMessage);
     return msg
  })
  .catch(function (error) {
    console.log(error);
  });
}

 delay(ms: number) {
   return new Promise( resolve => setTimeout(resolve, ms) );
 }
}

My angular App runs on the 4200 port and the Flask API is on the 5001 port.
Hope you can help me.

A: Try enabling CORS like this -
but first install latest flask-cors by running -

pip install -U flask-cors

from flask import Flask
from flask_cors import CORS, cross_origin
app = Flask(__name__)
cors = CORS(app) # This will enable CORS for all routes

@app.route("/")
@cross_origin()
def helloWorld():
  return "Helloworld!"


Q: Difference between SomeValue {get;} = true; vs SomeValue => true; in Properties In C# you could declare a property in two ways that seem very similar:
public string SomeProperty => "SomeValue";

vs
public string SomeProperty { get; } = "SomeValue";

Is there a difference between these two? (Ignoring the fact that "SomeValue" is not a very interesting value, it could be the result of a method call or whatever else would express a difference between the two forms).

A: In your example there is no functional difference because you're always returning a constant value.  However if the value could change, e.g.
public string SomeProperty => DateTime.Now.ToString();

vs
public string SomeProperty { get; } = DateTime.Now.ToString();

The first would execute the expression each time the property was called.  The second would return the same value every time the property was accessed since the value is set at initialization.
In pre-C#6 syntax the equivalent code for each would be
public string SomeProperty
{
    get { return DateTime.Now.ToString();}
}

vs
private string _SomeProperty = DateTime.Now.ToString();
public string SomeProperty
{
    get {return _SomeProperty;}
}


Q: OrientDB: Select unique vertices but retain the edges I am trying to do the following weird thing. I have a group of edges that point towards a group of vertices, but there is some repetition - multiple edges point to the same vertices.
Given a SELECT command that gives me the list of edges, I want to:

*

*SELECT the unique vertices from all of the 'out' vertices

*Return, along with the @rid of the unique vertices, a list of all the edges that pointed towards them.

E.g. the result should be a list of vertices with (vertex rid, [edge 1, edge 2, edge 3]).
Another way to think about this is I want to GROUP BY outgoing vertex but somehow retain in a field the @rid's of all the edges I grouped.
Thanks!

A: You can try this:
in this you get for every vertex the outgoing edges
select $a.@rid, $a.outE() from 'your class'
let $a = (select from 'your class' where $parent.current.@rid = @rid)

if you want the ingoing vertices you have to change $a.outE() with inE(), like below:
select $a.@rid, $a.inE() from 'your class'
let $a = (select from 'your class' where $parent.current.@rid = @rid)

Hope it helps.
Regards.


Q: Use if/else statement without else branch I don't know how to use if else in this case. When score > 10, stop insert. Else continue insert as normally. But what is the syntax to do that?
CREATE TRIGGER invalidScore ON dbo.dbo_score
AFTER INSERT
AS
DECLARE @score DECIMAL;
SET @score = (SELECT s.score FROM Inserted s);
IF(@score > 10)
BEGIN
  RETURN 'score must be less than 10'
  ROLLBACK TRAN
END
ELSE
BEGIN
END

A: First, creating these types of sql objects should use begin.. end blocks. Second is,you can ignore the else statement.
CREATE TRIGGER invalidScore ON dbo.dbo_score
AFTER INSERT
AS
BEGIN
    DECLARE @score DECIMAL;
    SET @score = (SELECT s.score FROM Inserted s);
    IF(@score > 10)
        BEGIN
            RETURN 'score must be less than 10'
            ROLLBACK TRAN
        END
END

A: There are 3 things you need to change for this trigger to work:

*

*Remove the else section - its optional.

*Handle the fact that Inserted may have multiple rows.

*Throw the error rather than using the return statement so you can handle it in the client. And throw it after rolling back the transaction in progress.

Corrected trigger follows:
create trigger invalidScore on dbo.dbo_score
after insert
as
begin
  if exists (select 1 from Inserted S where S.Score > 10) begin
    rollback tran;
    throw 51000, 'score must be less than 10', 1;
  end
end

A: 'Else' is an option section you can remove this and use it,but i may like you to consider using check constraints for scenarios like this rather than adding a trigger check on score column
e.g.
CREATE TABLE dbo.dbo_score(
Score int CHECK (score < 10)

);
A CHECK constraint is faster, simpler, more portable, needs less code and is less error prone


Q: Getting Warning on Play Store for using WRITE_CALL_LOG permission in android app I'm working on a project based on cloud backup which saves and restore user's call log. It was working fine for the previous version but now getting following warning. I added a description before taking permission from the user but still getting the warning.

Your app is requesting the following permission which is used by less
  than 1% of functionally similar apps: WRITE_CALL_LOG
Users prefer apps that request fewer permissions and requesting
  unnecessary permissions can affect your app's visibility on the Play
  Store. If these permissions aren't necessary, you may be able to use
  alternative methods in your app and request fewer permissions. If they
  are, we recommend providing an explanation to users of why you need
  the permissions. Learn more
Note: This guidance is based on a comparison with functionally similar
  apps, which change over time as new apps get published and existing
  apps change behavior. Therefore the warning may change even if you
  don't change your permission usage.

A: Its a warning.  If you need that permission (and it seems your app does), then you're fine.  If you didn't really need it, you should remove it.  Google isn't going to scan your description to see if you explain it, that level of AI isn't really possible yet.  So you'll continue to get the warning.


Q: panels expanded in viewport in my west region panel there is smth. like the task panel here:
http://dev.sencha.com/deploy/dev/examples/tasks/tasks.html
the data is loaded from 2 different 's containing only  with links
the first "task" group is always expanded to all the height of the document, though there are much less data there.
here is the code:
new Ext.Panel({
            region: 'west',
            title: 'דוחות',
            id: 'w',
            header: false,
            width: 190,
            split: true,
            layout: 'fit',
            collapseMode: 'mini',
            //minWidth: 100,
            baseCls:'x-plain',
            margins: '0 1 0 0',
            items: [ new Ext.Panel({
                    id:'wp',
                    frame:true,
                    title: 'דוחות לעובדים',
                    collapsible:true,
                    contentEl: 'workerRep',
                    //titleCollapse: true
                    }),
                    new Ext.Panel({
                    frame:true,
                    id:'mp'
                    title: 'דוחות למכונות',
                    collapsible:true,
                    contentEl:'machRep',
                    layout: 'fit',
                    //titleCollapse: true
                    })
                     ]

What could be the problem?

A: Ext.layout.FitLayout ( which is what layout: 'fit' stands for) is for situations when you anly have one item in a container, because it tries to 'fit' this one component to the full size of the container.
From manual:

This is a base class for layouts that contain a single item that automatically expands to fill the layout's container.

If you have more than one item in container use different layout like Ext.layout.ContainerLayout (default one), Ext.layout.VBoxLayout or perhaps Ext.layout.TableLayout.

A: found the answer, the problem was here:
baseCls:'x-plain',


Q: How to append to array in for loop? How can I append my results in this array so I can use it later ?
 var animalQuestion = [(orderlist: Int, questionid:String, question: String, description: String)]()

This is my array which I declared in my class above.
let stmt = try db.prepare("SELECT * FROM allquestion_other where allquestion_other.name= 'animalChoice' and allquestion_other.id NOT IN (select answerresult.questionId FROM answerresult where answerresult.friendUserId='\(friendUserId)')")
        for row in stmt {

            let orderlist = row[4]
            let questionid = row[0]
            let question = row[6]
            let description = row[7]

        animalQuestion.append(orderlist: orderlist, questionid: questionid, question: question, description: description)

            }

When i'm running this code , i'm getting the error "Cannot call value of non-function type '[(orderlist: Int, questionid: String, question: String, description: String)]'"
row[4] row [0]row [6]row [7] is returning some values which I need to append in my array

A: Try to use:
animalQuestion.append((orderlist: orderlist, questionid: questionid, question: question, description: description))

And do not forgot:
let orderlist = row[4] as Int

Your code incorrect because of:
1) For appending new objects to array you must to use array-method
animalQuestion.append(<Array object>)
2) In your case Array object is a tuple. So first you need to create a tuple, something like:
let orderTuple = (orderlist, questionid, question, description)

and after that appaned orderTuple to animalQuestion array like:
animalQuestion.append(orderTuple)


Q: Sl4A Selecting running application from notification window I have a SL4A program I have written.  I have one issue before i'm ready to publish it.
For some reason when the app is running,  if I home screen out of the app,  I see it running in the notification area,  but when I select it nothing happens.  However if I click my icon from apps area it will bring the app back up.
Any suggestions?

A: Notifications created by SL4A do nothing; they have no callback and can only alert users. Unfortunately there isn't really any way around this: BeanShell, JRuby and Rhino can make Java API calls (eg., to add the 'open my app when clicked' part) but can't use Contexts (which notifications require), and you could make your own version of the API facade, but then users would be required to install your specific version of x (eg., Python) for Android.
Otherwise all I could think of would be to get tricky with Intents or something and include an activity in the /src of your app to show the notification, though that would likely require learning Java / Android programming meaning you may as well follow through and write the entire app natively.
Sorry, but there really isn't an easy way to do this

A: You stated you wanted to publish it so I am assuming you were implying that in the long run you will be compiling it into a standalone apk?
If so, which package are/will you be using? py4a's method, python27, kivy? From my experiences when you compile to an apk with python27, there is no notification window at the top at all but if you were to compile it using py4a's method it should create a workable notification item for you. Please see the following link for further information: http://code.google.com/p/android-scripting/wiki/SharingScripts
Otherwise ProfSmiles answer is correct but it appears to be a much more complex solution then using the py4a method.
You can also see the python27 project if you would like a more embedded approach, although as mentioned previously it does not have a notification setup by default like py4a.
Kivy's implementation also looks promising but I am unfamiliar with it, it might also be worth looking at further: https://github.com/kivy/python-for-android

A: Well It seems that you can see the notifications started by SL4A "como.googlecode.android_scripting" package with the following command:
This is more like a hack.
dumpsys statusbar | grep "pkg=com.googlecode.android_scripting"

Every notification initiated by SL4A will have an "id". For example the "id=1" is the notification started by SL4A when the server is running. The one you click to stop the server.
With this in mind you can can actually list every notification started by your package and block until the id of your notification disappear.
If so then your next notifications should have an id with 2 or above. Note that this can change if SL4A is stopped or crash. The next time you may get the "id=2" for the (RPC) server notification and then "id=3" and over for your app notifications until you restart your device and so the RPC server notification goes back to "id=1". Knowing this means that you need to keep searchig for new notifications within a loop.
For example in bash and using adb:
while read Info; do echo "$Info" | grep 'pkg=com.googlecode.android_scripting'; done < <(adb shell dumpsys statusbar)

You'll get something like this:
1: StatusBarNotification(pkg=com.googlecode.android_scripting id=2 tag=null score=0 notn=Notification(pri=0 contentView=com.googlecode.android_scripting/0x109008f vibrate=null sound=null defaults=0x0 flags=0x62 kind=[null]) user=UserHandle{0}) # SL4A RPC Notification
7: StatusBarNotification(pkg=com.googlecode.android_scripting id=3 tag=null score=0 notn=Notification(pri=0 contentView=com.googlecode.android_scripting/0x109008f vibrate=null sound=null defaults=0x0 flags=0x10 kind=[null]) user=UserHandle{0}) # My Notification
Let's play with this!
Running:
while read Info; do echo "$Info" | grep "pkg=com.googlecode.android_scripting" | awk '{print $3}' | cut -s -d '=' -f2 ; done < <(adb shell dumpsys statusbar)

Will get you for example:
# Without Using Cut
id=2 # SL4A Notificaion
id=3 # My Notification

Or:
# Using Cut
2 # SL4A Notification
3 # My Notification

Let's get to the action! (An ugly solution)
# Start ADB USB Serial Connection
adb devices

# Activate Wireless ADB (Needs Root) - Not Needed
# adb shell setprop service.adb.tcp.port 5555
# stop adbd
# start adbd

Or:
# Start ADB Wireless
adb connect 192.168.1.3

NotifyCount=0
NotifyList=()

while read Notify; do

   DumpNotify=`echo "$Notify" | grep "pkg=com.googlecode.android_scripting" | awk '{print $3}' | cut -s -d '=' -f2`

   if [ ! -z "$DumpNotify" ] ; then
      NotifyList[$NotifyCount]="$DumpNotify"
      ((NotifyCount++))
   fi

done < <(adb shell dumpsys statusbar)

SL4ARPCNotification="2"
MyScriptNotification="3"

if [[ ${NotifyList[*]} != *"$MyScriptNotification"* ]] ; then
   adb shell am start -a android.intent.action.MUSIC_PLAYER
fi

This should be better in 2 functions with arguments for MyNotification and SL4ARPCNotification variables. That way you can verify from anywhere in the code and divide the job: FunctionX for listing the notifications and FunctionY for comparing the results.
This can easily be done in Pyhon or other interpreters. You need to remember that there's always a notification from SL4A itself. By using Threading in python you can continuously search for new or old notifications without the need to block your program waiting for a change and thus you can continue runninig your script normally.


Q: Values of the synthetic control created by Synth package in R I'm using the Synth package in R. I properly created my dataprep.out and synth(dataprep.out). Following, I created my path.plot and it's very fine.
Now I want to find the values estimated by Synth for my outcome variable for each time period. Where can I find this info, please?
Thanks in advance
I cannot find the values of the outcome variable created by Synth throughout my time periods. The plot created by path.plot shows the trajectory of the synthetic estimator, but not the values estimated.


Q: File Upload Error in Asp.net VB I am trying to add a fileupload control to my aspx page so the user can add pictures, but when I am implementing the code behind on VB the fileuploader controler is not recognized.
I have this on aspx page inside a formview:
<InsertItemTemplate>
    <div id="TaskScreenError">
        Upload a Screenshot of Error:
        <asp:FileUpload ID="ErrorScreen" runat="server"   />
    </div>
<InsertItemTemplate>

And I have the following code on my VB, but it says ErrorScreen is not declared.
Dim filereceived As String = ErrorScreen.PostedFile.FileName
    ' validate the file to ensure it is an image
    Select Case Right(filereceived, 4)
        Case ".jpg", ".tif", ".bmp", ".gif"
        Case Else
            lblErrMsg.Text = "Image is in a format we don't accept, please use jpg, tif, bmp or gif."
            Exit Sub
    End Select
    ...

It might be something really stupid but I cant figure it out what is the problem.
Please help.
Cheers

A: Since your FileUpload control is inside the InsertTemplate, you cannot access the FileUpload control directly. You have to do something like this:
Dim fileUpload As FileUpload = TryCast(YOURFORMVIEWID.FindControl("ErrorScreen"), FileUpload)
If fileUpload Is Nothing Then
    ' Handle if the FileUpload can't be found
Else
    Dim filereceived = fileUpload.PostedFile.FileName
    ' Continue your code here...
End If


Q: image rotation going to wide off of my screen how to keep static or shorten width? Hello guys I was wondering if anyone has a quick fix to my image rotating way to far off my screen and causes my app to have scroll bars and not appealing to the eye maybe have the image just spinning in place to make my formatting issues easier
here is my code
  JS

HTML

A: As markE said set the transform-origin to the center of the image, so something like this:
elem.style.transform-origin = "50% 50%";
elem.style.transform = "rotate("+degrees+"deg)";

You can use -ms- and -webkit- for this in your code too for cross compatability.
Slightly unrelated, I suggest using:
degrees = degrees%360;

instead of your if statement where you wrap from 359 to 1 degrees.
This is because it will work in more general situations, so is less likely to break. For example if you changed the amount of degrees no by +1 but by +10 or -10 it would still wrap correctly between 0 and 360.


Q: Choosing marker size in Matplotlib I am doing a scatter plot with square marker in matplotlib like this one:
.
I want to achieve something like this:

Which means I have to adjust the marker size and the figure size/ratio in such a way that there are no white space between markers. Also there should be a marker per index unit (x and y are both integers) so if y goes from 60 to 100, there should be 40 markers in y direction. At the moment I am tuning it manually. Any idea on what is the best way to achieve this?

A: I found two ways to go about this:
The first is based on this answer. Basically, you determine the number of pixels between the adjacent data-points and use it to set the marker size. The marker size in scatter is given as area.
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')

# initialize a plot to determine the distance between the data points in pixel:
x = [1, 2, 3, 4, 2, 3, 3]
y = [0, 0, 0, 0, 1, 1, 2]
s = 0.0
points = ax.scatter(x,y,s=s,marker='s')
ax.axis([min(x)-1., max(x)+1., min(y)-1., max(y)+1.])

# retrieve the pixel information:
xy_pixels = ax.transData.transform(np.vstack([x,y]).T)
xpix, ypix = xy_pixels.T

# In matplotlib, 0,0 is the lower left corner, whereas it's usually the upper
# right for most image software, so we'll flip the y-coords
width, height = fig.canvas.get_width_height()
ypix = height - ypix

# this assumes that your data-points are equally spaced
s1 = xpix[1]-xpix[0]

points = ax.scatter(x,y,s=s1**2.,marker='s',edgecolors='none')
ax.axis([min(x)-1., max(x)+1., min(y)-1., max(y)+1.])

fig.savefig('test.png', dpi=fig.dpi)

The downside of this first approach is, that the symbols overlap. I wasn't able to find the flaw in the approach. I could manually tweak s1 to
s1 = xpix[1]-xpix[0] - 13.

to give better results, but I couldn't determine a logic behind the 13..
Hence, a second approach based on this answer. Here, individual squares are drawn on the plot and sized accordingly. In a way it's a manual scatter plot (a loop is used to construct the figure), so depending on the data-set it could take a while.
This approach uses patchesinstead of scatter, so be sure to include
from matplotlib.patches import Rectangle

Again, with the same data-points:
x = [1, 2, 3, 4, 2, 3, 3]
y = [0, 0, 0, 0, 1, 1, 2]
z = ['b', 'g', 'r', 'c', 'm', 'y', 'k'] # in your case, this is data
dx = [x[1]-x[0]]*len(x)   # assuming equally spaced data-points

# you can use the colormap like this in your case:
# cmap = plt.cm.hot

fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
ax.axis([min(x)-1., max(x)+1., min(y)-1., max(y)+1.])

for x, y, c, h in zip(x, y, z, dx):
    ax.add_artist(Rectangle(xy=(x-h/2., y-h/2.),
                  color=c,             # or, in your case: color=cmap(c)
                  width=h, height=h))  # Gives a square of area h*h

fig.savefig('test.png')

One comment on the Rectangle: The coordinates are the lower left corner, hence x-h/2.
This approach gives connected rectangles. If I looked closely at the output here, they still seemed to overlap by one pixel - again, I'm not sure this can be helped.


Q: How to sort search results by relevance in javascript I'm building a custom search, as of now if I enter "The R" I get the result list with The Fellow ship of the Ring first, because the phrase "the ring" it's in its .text. I want The Return of the King to be first. Is there a way I can give more relevance to the .name field or sort the match array based on the name .field and the input text?
HTML

      <form class="form-inline position-relative">
        <input id="search" class="form-control form-control-search" type="text" placeholder="Search..." aria-label="Search">
      </form>

JAVASCRIPT
const searchIndex = async searchText => {
 const res = await fetch('/data/index.json');
 const index = await res.json();

  matchList.classList.remove("d-none");
 // Get matches to current text input
 let matches = index.filter(index => {
  const regex = new RegExp(`${searchText}`, 'gi');
  return index.name.match(regex) || index.text.match(regex);
 });

 // Clear when input or matches are empty
 if (searchText.length === 0) {
   clearSearch();
 }

 outputHtml(matches);
};

function clearSearch(){
  matches = [];
  matchList.classList.add("d-none");
}

// Show results in HTML
const outputHtml = matches => {
 if (matches.length > 0) {
  const html = matches.map(function(match){
      return `

${match.name}

            ${match.type}

            Found in ${match.product}

            ${match.text}

`
    }
}).join('');
  matchList.innerHTML = html;
 }
};

index.JSON
 [
  {
    "name": "The Fellowship of the Rings",
    "type": "book",
    "text": "Bilbo reveals that he intends to leave the Shire for one last adventure, and he leaves his inheritance, including the Ring, to his nephew Frodo. Gandalf investigates...",
    "url": "books/the-fellowship-of-the-rings",
    "product": "Books"
  },
  {
    "name": "The Two Towers",
    "type": "book",
    "text": "Awakening from a dream of Gandalf fighting the Balrog in Moria, Frodo Baggins and Samwise Gamgee find themselves lost in the Emyn Muil near Mordor and discover they are being tracked by Gollum, a former bearer of the One Ring.",
    "url": "books/the-two-towers",
    "product": "Books"
  },
  {
    "name": "The Return of the King",
    "type": "book",
    "text": "Gandalf flies in with eagles to rescue the Hobbits, who awaken in Minas Tirith and are reunited with the surviving Fellowship.",
    "url": "books/the-return-of-the-king",
    "product": "Books"
  }
]

A: You could map your data to include relevance points:
const index = await res.json();
const searchTextLowercased = searchText.toLowerCase();

const rankedIndex = index.map(entry => {
    let points = 0;

    if (entry.name.toLowerCase().includes(searchTextLowercased)) {
        points += 2;
    }

    if (entry.text.toLowerCase().includes(searchTextLowercased)) {
        points += 1;
    }

    return {...entry, points};
}).sort((a, b) => b.points - a.points);

This way, you have ranked results in rankedIndex const.
Keep in mind that your code probably needs some refactoring, because you're fetching data on each search. I'm assuming your searchIndex() is called with every key press or something like that.


Q: ttk Button: relief of the button is not taking effect I have button defined as below:
button_style = ttk.Style()
button_style.configure("button_style.TButton", relief=tk.RAISED,
                       width = 20, padding=6, font=('Helvetica', 12) )
self.button = ttk.Button (self.myContainer1, text="Browse", style='button_style.TButton',
                          command = self.browse_file)
self.button.grid(row = 0,column = 3,padx=5, pady=10, ipadx=5, ipady=5)

For some reason the relief effect of the button is not applied. Could somebody help me please?


Q: how to change the size of the file from kilobyte into gigabyte using php i have here a code that saves a file the size is kilobyte but i want a size of a file that have a size into gigabyte but i do not know how to change it.
i need a help from you because im a beginner in the php and i don't know how to change the size of the file and i want to save a video in my database.
here is my code:
       <?php
            function output_file($file, $name, $mime_type='') {
        if(!is_readable($file)) die('File not found or inaccessible!');

        $size = filesize($file);
        $name = rawurldecode($name);
        $known_mime_types=array(
        "pdf" => "application/pdf",
        "txt" => "text/plain",
        "html" => "text/html",
        "htm" => "text/html",
        "exe" => "application/octet-stream",
        "zip" => "application/zip",
        "doc" => "application/msword",
        "xls" => "application/vnd.ms-excel",
        "ppt" => "application/vnd.ms-powerpoint",
        "gif" => "image/gif",
        "png" => "image/png",
        "jpeg"=> "image/jpg",
        "jpg" => "image/jpg",
        "php" => "text/plain"
          );
       if($mime_type=='') {
             $file_extension =
            strtolower(substr(strrchr($file,"."),1));

          if(array_key_exists($file_extension, $known_mime_types)) {
            $mime_type=$known_mime_types[$file_extension];
           } else {
                $mime_type="application/force-download";
           };
             };

            @ob_end_clean();

         if(ini_get('zlib.output_compression'))
         ini_set('zlib.output_compression', 'Off');
             header('Content-Type: ' . $mime_type);
         header('Content-Disposition: attachment; filename="'.$name.'"');
         header("Content-Transfer-Encoding: binary");
         header('Accept-Ranges: bytes');
          header("Cache-control: private");
          header('Pragma: private');
         header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
          if(isset($_SERVER['HTTP_RANGE']){
            list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
          list($range) = explode(",",$range,2);
            list($range, $range_end) = explode("-", $range);
           $range=intval($range);
            if(!$range_end) {
                 $range_end=$size-1;
                       } else {
                       $range_end=intval($range_end);
                }
                    $new_length = $range_end-$range+1;
                         header("HTTP/1.1 206 Partial Content");
                            header("Content-Length: $new_length");
             header("Content-Range: bytes $range-$range_end/$size");
               } else {
                   $new_length=$size;
                        header("Content-Length: ".$size);
                   }
                  $chunksize = 1*(1024*1024);
                    $bytes_send = 0;
                if ($file = fopen($file, 'r') {
                   if(isset($_SERVER['HTTP_RANGE']))
                  fseek($file, $range);

               while(!feof($file) &&
                    (!connection_aborted()) &&
                                 ($bytes_send<$new_length)) {
                   $buffer = fread($file, $chunksize);
                    print($buffer);
                          flush();
                  $bytes_send += strlen($buffer);
                   }
                fclose($file);
                   } else

                  die('Error - can not open file.');
                     die();
                     }
                       set_time_limit(0);
                    $file_path='files/'.$_REQUEST['filename'];
                output_file($file_path, ''.$_REQUEST['filename'].'',
            'text/plain');
             ?>

A: For kilobyte divide it by 1048576. Did you need something more complicated than that?
$sizeInGB = $sizeInKB / 1048576;


Q: MVC3 gives a Blank chart My LoggedUserHome.Controller has this action for chart
 public ActionResult GetGender()
    {

        var AllGender = new List<string>(from c in db.tbl_Profile select c.sex).ToList();
        var Groping = AllGender
           .GroupBy(i => i)
           .Select(i => new { sex = i.Key, CountGet = i.Count() }).ToArray(); //get a count for each

        var key = new Chart(width: 300, height: 300)
            .AddSeries(
            chartType: "pie",
            legend: "Gender Popularity",
            xValue: Groping, xField: "sex",
            yValues: Groping, yFields: "CountGet")
            .Write("gif");
        return null;

    }

and in my view I have given

Thanks to Nexuss ToArray() suggestion I manage to populate the chart by reading the database.. Thanks a lot Nexuzz

A: Simple solution is to try to replace your

in the view with
@{
    var d = new PrimeTrekkerEntities1();
    var AllGender = new List<string>(from c in d.tbl_Profile select c.sex).ToList();
    var Groping = AllGender
        .GroupBy(i => i)
        .Select(i => new { sex = i.Key, Count = i.Count() }); //get a count for each

    var key = new Chart(width: 600, height: 400)
        .AddSeries(
        chartType: "pie",
        legend: "Gender Popularity",
        xValue: Groping, xField: "sex")
        .Write("gif");
}

And "yes" you don't need action GetGender in this case.
More complex solution would be to leave

in the view, but make GetGender() action return chart image URL. So, what you can do in GetGender() is somehow render chart into image file and return response that contains the image's path.
update:
I've updated your example a bit, so it displays data in the chart. Here is what I've got:
@{
    var AllGender = new List<string>() { "Male", "Female", "Male"};
    var Groping = AllGender
        .GroupBy(i => i)
        .Select(i => new { sex = i.Key, Count = i.Count() }).ToArray(); //get a count for each

    var key = new Chart(width: 600, height: 400)
        .AddSeries(
        chartType: "pie",
        legend: "Gender Popularity",
        xValue: Groping, xField: "sex",
        yValues: Groping, yFields: "count")
        .Write("gif");
}

There are two main differences with your example:

*

*Groping is now an array. As far as I understand Chart expects data to be enumerated

*I added yValues and yFields parameters, so chart knows what values to use on Y axis


Q: Xamarin Android load local html file with routing How can I load local html file with routing in Android Webview?
The url looks like this:
file:///android_asset/Content/index.html/#/first-view
file:///android_asset/Content/index.html/#/second-view

I tried with this code but it's not working:
AppWebView.LoadUrl("file:///android_asset/Content/index.html/#/first-view");


Q: Calling base component's methods/features Having Base.vue
<template><div>{{ name }}</div></template>
<script>
  export default {
    data() {
      return {name: 'Example Component'};
    }
  };
</script>

And Extended.vue:
<script>
  import Base from './Base.vue';
  export default {
    extends: Base,
    data() {
      return {name: 'Extended Example Component'};
    }
  };
</script>

Is it possible to reuse data from base one instead of hardcoding Extended Example Component? Some kind of super from OOP? Looking for generic solution involving stuff like mount, methods, computed, etc.
UPDATE
When using OOP we use such approach (Python example):
class Base:
   def __init__(self):
       self.name = 'Example Component'

class Extended(Base):
   def __init__(self):
       super().__init__()
       self.name = f'Extended {self.name}'

This way we reuse self.name field.

A: extends and mixins merge options in a specified way, this is the official way to inherit component functionality. They don't provide full control over the inheritance.
For static data that may change between component definitions (Base and Extended) custom options are commonly used:
export default {
  myName: 'Component',
  data() {
    return { name: this.$options.myName };
  }
}

and
export default {
  extends: Base,
  myName: `Extended ${Base.options.myName}`
}

Notice that name is existing Vue option and shouldn't be used for arbitrary values.
Any reusable functions can be extracted from component definition to separate exports.
For existing components that cannot be modified data and other base component properties can be accessed where possible:
  data() {
    let name;

    name = this.$data.name;
    // or
    name = Base.options.data.call(this).name;

    return { name: `Extended ${name}` };
  }

This approach is not future-proof and not compatible with composition API, as there's no clear distinction between data, etc, and this is unavailable in setup function. An instance can be accessed with getCurrentInstance but it's internal API and can change without notice.

A: The data object is a kind of state for a single component, hence the data object inside a component can only be accessed in that component and not from outside or other components.
For your specific requirement, you can use Vuex. It helps you access the state in multiple components. Simply define a state in the vuex store and then access the state in the component.
If you don't want to use Vuex, then another simple solution is to store the data in localStorage and then access the data in multiple components.

A: You can access your data, from child component. You can do that by this.$parent.nameOfTheDataYouHave.
This cheatsheet can help you with the basics of the component anatomy and lifecycle hooks(mounted,created,etc..).
And last this is the proper way of two-way binding data (parent-child).


Q: I get "IndexError: list index out of range" when installing Pandas in python So, I installed pandas with cmd :

but when I try to import it i get this error:

Traceback (most recent call last):   File
  "C:/Users/Uros/Desktop/fasda.py", line 1, in
      import pandas  ModuleNotFoundError: No module named 'pandas'

and when I try to install it in setting I get this error:

A: As the second screenshot shows, you need to install pandas for your the python interpreter that you use, like this:
C:\Users\Uros\untitled\Scripts\python.exe -m pip install -U pandas


Q: Generate TIE cells with Yosys? I am using Yosys to synthesise my RTL design which includes a couple of literal constants, such as tied output ports as in the following code:
module my_module (
    input a,
    input b,
    output c,
    output d);

    assign c = a & b;
    assign d = 1'b1;
endmodule

In this case, output d will obviously always be a logical one. The flow I am using includes the abc -liberty my_stdcells.lib call to map the combinatorial logic to the standard cells provided by the library, followed by the clean and write_verilog calls.
The cell library I am using also provides TIELO and TIEHI cells, but the synthesised Verilog netlist doesn't include any instances of those cells but instead still shows literal constants like in the example above.
I could probably write a script to post-process the synthesised netlist to replace these literals with TIE* cell instances from the library, but I am wondering if I could get Yosys to do that for me somehow, resulting in something like
TIEHI tiehi_d_inst(.Y(d));

for the assign d = 1'b1 line in the code above.

A: The command you are looking for is hilomap. For example, to map to TIEHI and TIELO cells with Y outputs use something like:
hilomap -hicell TIEHI Y -locell TIELO Y

This will create an individual TIEHI/TIELO cell for each constant bit in the design. Use the option -singleton to only create single TIEHI/TIELO cells with a higher fan-out.


Q: Python Pandas match exact pattern I'm trying to match a pattern with a column of a dataframe
pattern='pgk'
df = pd.DataFrame([['merged_pgk', 10], ['merged_Pgk', 3], ['merged_pgk_stim', 12], ['merged_Scp1', 5]], columns=['condition','count'])

I want the row where pattern is in the column condition.
df[df['condition'].str.lower().str.contains(pattern)]

I tried this but the problem here is that it will return pgk row (what I want) but I got also pgk_stim row (what I don't want)

A: try np.where with str.contains and case=False to ignore the case.
and $ to only match pgk at the end of a string.
df['check'] = np.where(df['condition'].str.contains('pgk$',case=False), True,False)

print(df)

         condition  count  check
0       merged_pgk     10   True
1       merged_Pgk      3   True
2  merged_pgk_stim     12  False
3      merged_Scp1      5  False

A: you can use endswith function
df[df['condition'].str.lower().str.endswith(pattern)]


Q: How to find duplicate items in list<>? I have:
List<string> list = new List<string>() { "a", "a", "b", "b", "r", "t" };

How can I get only "a","b"?
I tried to do like this:
List<string> list = new List<string>() { "a", "a", "b", "b", "r", "t" };
List<string> test_list = new List<string>();

test_list = list.Distinct().ToList();

Now test_list has {"a", "b", "r", "t"}
And then:
test_list = test_list.Except(list).ToList();

So that was my fail point, cause Except() deleted all elements.
Could you help me with solution?

A: Try this
var duplicates = list.GroupBy(a => a).SelectMany(ab => ab.Skip(1).Take(1)).ToList();

A: A simple approach is using Enumerable.GroupBy:
var dups = list.GroupBy(s => s)
               .Where(g => g.Count() > 1)
               .Select(g => g.Key);

A: List<string> list = new List<string>() { "a", "a", "b", "b", "r", "t" };

var dups = list.GroupBy(x => x)
    .Where(x => x.Count() > 1)
    .Select(x => x.Key)
    .ToList();

A: var list = new List<string> { "a", "a", "b", "b", "r", "t" };

var distinct = new HashSet<string>();
var duplicates = new HashSet<string>();

foreach (var s in list)
    if (!distinct.Add(s))
        duplicates.Add(s);

// distinct == { "a", "b", "r", "t" }
// duplicates == { "a", "b" }

A: var duplicates = list.GroupBy(s => s).SelectMany(g => g.Skip(1).Take(1)).ToList();

A: var duplicates = list.GroupBy(a => a).SelectMany(ab => ab.Skip(1).Take(1)).ToList();

It will be more efficient then the one using Where(g => g.Count() > 1) and will return only one element from every group.


Q: WPF GradientBrush? How Many type of gradient brushes are available like LinearGradientBrush, SolidColorBrush?
and when we create a GradientStop how the offset works?
        LinearGradientBrush LGB = new LinearGradientBrush();
        LGB.StartPoint = new Point(0, 0);
        LGB.EndPoint = new Point(0, 1);
        LGB.GradientStops.Add(new GradientStop(Color.FromRgb(255,251,255) , 0));
        LGB.GradientStops.Add(new GradientStop(Color.FromRgb(206,207,222), 1));
        LGB.GradientStops.Add(new GradientStop(Color.FromRgb(0, 247, 0), 2));
        rect.Fill = LGB;

Why the third one "Color.FromRgb(0, 247, 0)" is not reflecting?
Please suggest,where i am wrong?

A: The GradientStop.Offset property is a value which ranges from 0.0 to 1.0. From the MSDN documentation:

A value of 0.0 specifies that the stop is positioned at the beginning of the gradient vector, while a value of 1.0 specifies that the stop is positioned at the end of the gradient vector.

Change your second stop's offset to 0.5 and your third's to 1.0 and it should work.


Q: GWT application generating IE insecure item warning Our service runs over HTTPS and we're currently experimenting with running a compiled GWT-application within it, only client side, no RPC:s.
It is included within an IFRAME, which seems to be recommended (here for example: http://developerlife.com/tutorials/?p=231 under the heading HTTPS and HTTP).
When doing certain operations within the GWT-app, IE it generates an insecure item warning.
http://bagonca.com/insecure_item.png
You may ask yourself why I don't use some nifty Firefox plugin to see what request might be over http. Or why I don't use HTTPWatch in Internet Explorer for the same reason. I have. There are no insecure requests that I can find, anywhere.
What I have read about on the other hand is that Internet Explorer throws this warning for iframes without the src attribute set. And that a potential fix is using src="javascript:false" for any iframe that is populated dynamically.
As I've said, the whole app is included via an IFRAME, and within it GWT itself generates a hidden IFRAME that looks like below.

I've tried hard coding the src attribute above to a blank page that actually exists and is called with HTTPS on the same domain. I've tried the javascript:false; approach. No luck. The app works like a charm, but IE throws the useless, and false warning.
The warning turns up when I do certain actions within the app, not when it is loaded. Actually when dragging and dropping appointments within the http://code.google.com/p/gwt-calendar/ component.
Has anyone tangled with a similar issue before? Any clues?

A:
Any clues?

I'm not sure in this case, but I did some experiments with iframes (on a somewhat similar topic) about a year ago. I would assume, that gwt-calendar tries to communicate with the host page via javascipt's parent reference. AFAIR, that's not allowed, when the host page isn't loaded from the same origin (including protocol).

A: There other snippets of Javascript that can also cause a problem. Please see:
http://blog.httpwatch.com/2009/09/17/even-more-problems-with-the-ie-8-mixed-content-warning/
Also, have a look through the pile of comments on:
http://blog.httpwatch.com/2009/04/23/fixing-the-ie-8-warning-do-you-want-to-view-only-the-webpage-content-that-was-delivered-securely/
Some of the commenters have found and fixed other causes of the warning too.

A: This can happen if you have your app running over HTTPS and are fetching images or some other resource over over plain HTTP. Check if you have image or css paths hardcoded to http://.
For example, if your app if running at https://example.com and you wish to load an image foo.jpg , the html you should be using is:

or (ideally)

and not

Note that the third example fetches the foo.jpg image over http instead of https. Hence it would cause the issue which you are facing.
To avoid such problems, the best practice is either to use ImageResources and relative URLs.


Q: Error retrieving data from a remote database in PHP
How can I solve the problem shown in the table? This happened while I was trying to retrieve data from my database. In my java code, the json array that I try to call is null.
db_connect.php
<?php
class DB_CONNECT{
// constructor
function __construct() {
    // connecting to database
    $this->connect();
}

// destructor
function __destruct() {
    // closing db connection
    $this->close();
}

/**
 * Function to connect with database
 */
function connect() {
    // import database connection variables
    require_once __DIR__ . '/db_config.php';

    // Connecting to mysql database
    $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());

    // Selecing database
    $db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());

    // returing connection cursor
    return $con;
}

/**
 * Function to close db connection
 */
function close() {
    // closing db connection
    mysql_close();
}

}

?>'

retEqp.php
<?php

/*
 * Following code will list all the products
 */

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// get all products from products table
$result = mysql_query("SELECT *FROM facilities_equipments where item_Type='Equipment'") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
    // looping through all results
    // products node
    $response["equipments"] = array();

    while ($row = mysql_fetch_array($result)) {
        // temp user array
        $equipment = array();
        $equipment["item_ID"] = $row["item_ID"];
        $equipment["item_Name"] = $row["item_Name"];

        // push single product into final response array
        array_push($response["equipments"], $equipment);
    }
    // success
    $response["success"] = 1;

    // echoing JSON response
        echo json_encode($response);
    } else {
        // no products found
        $response["success"] = 0;
        $response["message"] = "No products found";

    // echo no users JSON
    echo json_encode($response);
    }
    ?>

A: Replace your code
$con =  mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());

with
$con =  mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());

Turn off all deprecated warnings including them from mysql_*:
error_reporting(E_ALL ^ E_DEPRECATED);


Q: Find Hours Between Startdate and Enddate of different table TimeSheetData timesheetdata = new TimeSheetData();
TimeSheet timeSheet = new TimeSheet();
TimeSheetData timesheetdata = new TimeSheetData();
                        timeSheet.StartDate = thisWeekStart;
                        timeSheet.EndDate = thisWeekEnd;
                        timesheetdata.Date = dt;

                        string HourData = item.Value;
                        string TaskID = item.ID.Split(':')[0];
                        timesheetdata.TaskID = Guid.Parse(TaskID);
                        timesheetdata.TimeSheet = timeSheet;
                        timesheetdata.Hours = Convert.ToDouble(HourData);
                        db.TimesheetData.Add(timesheetdata);
                        db.SaveChanges();

var TMS = db.TimeSheets.Where(t => t.StartDate == thisWeekStart
                                   && t.EndDate == thisWeekEnd).ToList();

My tables are:

*

*Timesheets (Guid, Startdate, Enddate)

*TimeSheetDatas (Guid, hours, Date, Task  GUID, Timesheet Guid)

I want to find hours (TimesheetDatas) between StartDate and EndDate (Timesheets).
 Hours find = var TMS

A: You didn't provide some details but do you want something like that;
var query = from ts in db.TimeSheets
join tsd in db.TimesheetDatas on ts.Guid equals tsd.TimesheetGuid
where ts.StartDate > thisWeekStart && ts.StartDate < thisWeekEnd
select tsd.hour


Q: How to know if email was sent from intent In my app, I'm creating an intenet to send an email... it looks like this
final Intent emailIntent = new Intent(Intent.ACTION_SEND)
                        .putExtra(Intent.EXTRA_EMAIL, new String[]{mBuilder.mEmail})
                        .putExtra(Intent.EXTRA_SUBJECT, mBuilder.mSubject)
                        .putExtra(Intent.EXTRA_TEXT, Html.fromHtml(getBody()))
                        .putExtra(Intent.EXTRA_STREAM, zipUri)
                        .setType("application/zip");
                mBuilder.mContext.startActivity(Intent.createChooser(
                        emailIntent, mBuilder.mContext.getString(R.string.send_using)));

I want to know if it's possible to know if the email was actually sent or not, so I can perform some actions after that happens.
If so, please explain me how and if possible add a code snippet, please.
Thanks in advance.

A:
I want to know if it's possible to know if the email was actually sent or not

No.
First, there is no requirement that the user chooses an email client for this startActivity() request.
Second, there is nothing in the ACTION_SEND protocol that lets the app offering to share the content know whether or not the user did anything with that content.

A: Maybe you could try startActivityForResult() and see whether the resultcode changes depending on what the user did


Q: Asp.net - Starting server with Kestrel on OS X I have not worked with Asp.net before. I'm trying to get an MVC Project running on my machine. I'm running OS X 10.9.3.
I tried following the instructions in this tutorial: http://docs.asp.net/en/latest/tutorials/your-first-mac-aspnet.html
But when I run $ dnx . kestrel in the projects directory I get the following error:
System.InvalidOperationException: Unable to resolve project 'XYZ' from /Users/jeff/Sites/XYZ/XYZ.com
  at Microsoft.Framework.Runtime.ApplicationHostContext..ctor (IServiceProvider serviceProvider, System.String projectDirectory, System.String packagesDirectory, System.String configuration, System.Runtime.Versioning.FrameworkName targetFramework, ICache cache, ICacheContextAccessor cacheContextAccessor, INamedCacheDependencyProvider namedCacheDependencyProvider, IAssemblyLoadContextFactory loadContextFactory, Boolean skipLockFileValidation) [0x00000] in <filename unknown>:0
  at Microsoft.Framework.Runtime.DefaultHost.Initialize (Microsoft.Framework.Runtime.DefaultHostOptions options, IServiceProvider hostServices) [0x00000] in <filename unknown>:0
  at Microsoft.Framework.Runtime.DefaultHost..ctor (Microsoft.Framework.Runtime.DefaultHostOptions options, IServiceProvider hostServices) [0x00000] in <filename unknown>:0
  at Microsoft.Framework.ApplicationHost.Program.Main (System.String[] args) [0x00000] in <filename unknown>:0
  at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
  at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in <filename unknown>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x00000] in <filename unknown>:0
  at Microsoft.Framework.Runtime.Common.EntryPointExecutor.Execute (System.Reflection.Assembly assembly, System.String[] args, IServiceProvider serviceProvider) [0x00000] in <filename unknown>:0
  at dnx.host.Bootstrapper.RunAsync (System.Collections.Generic.List`1 args, IRuntimeEnvironment env, System.Runtime.Versioning.FrameworkName targetFramework) [0x00000] in <filename unknown>:0

What can I try to fix this?

A: It means that dnx cannot find Startup.cs file. Try to run dnx . kestrel inside folder which contains Startup.cs


Q: Can someone explain this css margin behaviour? A friend of mine had a problem with this simple html/ css task: http://jsfiddle.net/kaHzY/6/
The problem was that the .headline 's margin-top was pushing down the #main div although it should directly follow the nav without any space between.
Adding a div .inner with a padding of 1px solved this issue. The .headline still had the margin but was not pushing down the #main div anymore.
I know this behaviour but I cant explain it. How can you explain that, especially to someone who is learning css? Why does it behave like that?
Thanks

A: This is classic collapsing margin behavior.
The people who wrote the CSS spec thought this was a good idea in order to prevent excessive white space from being created by margins.  Without this behavior, it would be a lot more work to control margin/whitespace between block elements.
References:
CSS2 Spec - http://www.w3.org/TR/CSS2/box.html#collapsing-margins
Andy Budd Article - http://andybudd.com/archives/2003/11/no_margin_for_error/
Eric Meyer Article - http://www.complexspiral.com/publications/uncollapsing-margins/
Why Collapsing Margins Are a Good Idea
Collapsing margins are a feature of the CSS Box Model, which forms the basic working unit for the Visual Formatting Model, which allows us to have a rational environment in which to develop web pages.
In designing the CSS specification, the authors had to balance how how rules would be written, for example: margin: 1.0em, and how these rules would work in a CSS formatting engine that needs to layout block of content from top-to-bottom and left-to-right (at least in Western European languages).
Following the train-of-thought from Eric Meyer's article cited above, suppose we have a series of paragraphs with margins styled according to:
p { margin: 1.00em; }

For those of us who used to seeing printed pages with regular spacing between paragraphs, one would expect the space between any two adjacent paragraphs to be 1.00em.  One would also expect the first paragraph to have a 1.00em margin before it and the last paragraph to have a 1.00em margin after it.  This is a reasonable, and perhaps simplified, expectation of how the simple CSS rule for p should behave.
However, for the programmers building the CSS engine that interprets the simple p rule, there is a lot of ambiguity that needs to be resolved.  If one is expecting the printed page interpretation of the CSS rule, then this naturally leads to the collapsing margin behavior.  So the programmers come up with a more complicated rule like: if there are two adjacent p tags with top and bottom margins, merge the margins together.
Now this begs the question, how do you "merge margins together"? min or max of the adjacent top and bottom margins, average of the two? margin of first element always?  And what if you have other block elements other than p's? and if you add a border or background? what next?
Finally, how do you compute all of these margin settings in such a way so that you don't have to iterate through the entire set of HTML elements several times (which would make complicated pages load slowly especially in early generations of browsers)?
In my opinion, collapsing margins offered a solution to a complicated problem that balanced the ease of writing CSS rules for margins, the user expectation of how printed pages are laid out in our typographic heritage, and finally, provided a procedure that could be implemented within the programming environment that browsers exist in.

A: I achieved your desired layout by:

*

*Resetting the default margins and padding on the p tags:
p{
  margin: 0px auto;
  padding: 0px;
 }
Make sure you add this to the top of your CSS.

*Then changed the .headline and .text classes to use padding instead of margin; using your same values.

*Removed the #main .inner CSS entirely.


Q: Overcome VBA InputBox Character Limit The current function I use to collect text InputBox can't accept more than 255 characters apparently, and I need to be able to collect more than that? Is there a parameter or different function I can use to increase this limit?

A: To be pedantic, the Inputbox will let you type up to 255 characters, but it will only return 254 characters.
Beyond that, yes, you'll need to create a simple form with a textbox. Then just make a little "helper function" something like:
Function getBigInput(prompt As String) As String
    frmBigInputBox.Caption = prompt
    frmBigInputBox.Show
    getBigInput = frmBigInputBox.txtStuff.Text
End Function

or something like that...

A: Thanks BradC for the info that. My final code was roughly as follows, I have a button that calls the form that I created and positions it a bit as I was having some issues with the form being in the wrong spot the everytime after the first time I used.
Sub InsertNotesAttempt()
    NoteEntryForm.Show
    With NoteEntryForm
        .Top = 125
        .Left = 125
    End With
End Sub

The userform was a TextBox and two CommandButtons(Cancel and Ok). The code for the buttons was as follows:
Private Sub CancelButton_Click()
    Unload NoteEntryForm
End Sub

Private Sub OkButton_Click()
    Dim UserNotes As String

    UserNotes = NotesInput.Text

    Application.ScreenUpdating = False
    If UserNotes = "" Then
        NoteEntryForm.Hide
        Exit Sub
    End If

    Worksheets("Notes").ListObjects("Notes").ListRows.Add (1)
    Worksheets("Notes").Range("Notes").Cells(1, 1) = Date
    Worksheets("Notes").Range("Notes").Cells(1, 2) = UserNotes
    Worksheets("Notes").Range("Notes").Cells(1, 2).WrapText = True
    ' Crap fix to get the wrap to work. I noticed that after I inserted another row the previous rows
    ' word wrap property would kick in. So I just add in and delete a row to force that behaviour.
    Worksheets("Notes").ListObjects("Notes").ListRows.Add (1)
    Worksheets("Notes").Range("Notes").Item(1).Delete
    NotesInput.Text = vbNullString
    NotesInput.SetFocus ' Retains focus on text entry box instead of command button.
    NoteEntryForm.Hide
    Application.ScreenUpdating = True
End Sub

A: I don't have enough rep to comment, but in the sub form_load for the helper you can add:
me.AutoCenter = True

Outside of that form, you can do it like this:
NoteEntryForm.Show
Forms("NoteEntryForm").AutoCenter = True

My Access forms get all confused when I go from my two extra monitors at work to my one extra monitor at home, and are sometimes lost in the corner.  This AutoCenter has made it into the form properties of every one of my forms.


Q: Proper method to timing how long a sorting algorithm takes (Using Java)
I'm testing sorting arrays to see literally how fast different sorting arrays take.  I want to weed out the erroneous times, so ideally I would like to start a timer, run the sort in a loop of say 100 times, stop the timer, then divide by 100 to get a pretty accurate measure.
The problem is if I were to loop the same array, it'll sort properly the first time, then each sort after, it'll keep sorting the already sorted array, which isn't what I want.
Maybe I'm missing an obvious solution, but is there any way I can make it keep sorting the same initial randomized array?
I thought about reassigning the newly sorted array back to the initial random array each time, but that would mess up my timer..
thanks for any suggestions
what i would like to do:
        startTime = System.nanoTime();
        for(int i=0; i<cntr; i++) {
            sort array
        }
        endTime = System.nanoTime();
        time = (endTime - startTime)/cntr;

A: You can make a copy before you start sorting, and then copy from that stored copy into the array being sorted in each iteration of the loop.
int[] toBeSorted = new int[10000];
// fill the array with data
int[] copied = new int[10000];
System.arrayCopy(toBeSorted, 0, copied, 0, copied.length);
// prepare the timer, but do not start it
for (int = 0 ; i != 100 ; i++) {
    System.arrayCopy(copied, 0, toBeSorted, 0, copied.length);
    // Now the toBeSorted is in its initial state
    // Start the timer
    Arrays.sort(toBeSorted);
    // Stop the timer before the next iteration
}

A: You can use the System.currentTimeMillis() method to get the current time then subtract when the method finishes executing.
long totalRuntime = 0;

for(int i = 0; i < 100; i++)
{
   long startTime = System.currentTimeMillis();
   sortArrays()
   long endTime = System.currentTimeMillis();

   totalRuntime += (endTime - startTime);
}

System.out.println("Algorithm X on average took "
                    + totalRuntime/100 + " milliseconds);

If you want to do this X times just keep a counter for each algorithm and increment. Then you can divide by the total number of runs at the end and compare.

A: Generally you would stop and start the timer in between each run of the algorithm you're testing, adding up the individual times and then dividing by the number of runs. That way any "setup time" isn't included because the timer isn't running during the setup.

A: Go with something like this
new array equals random array,
start timer
sort new array
stop timer
add time to your list of times
repeat until necessary

As long as you copy the original array each time, you will never sort the original one

A: put the sorting algorithm in a function and keep calling the function with the same again and again and passing the array to the function after cloning it using the clone method.
You can call the current time function and print it out every time you run the loop.

A: If you're willing to blow memory, then just make 100 (or however many) copies of the same array before you start timing. If you're not, then time sorting and copying together, and then time just copying to see approximately how much of your sorting + copying time was spent copying.
Also, sidenote: look into using a benchmarking framework like Caliper instead of doing your own "manual" benchmarking. It's easier, and they've solved a lot of problems that you might not even know are going on that could screw up your timings.


Q: Getting graphics object to draw with buffer strategy I've made a JFrame with a canvas on it and I want to draw on that canvas. At a later date the canvas will be updating many times a second so I am using a buffer strategy for this. Here is the code:
package mainPackage;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;

import javax.swing.JFrame;

public class TickPainter {
    //just some presets for a window.
    public static JFrame makeWindow(String title, int width, int height) {
        JFrame mainWindow = new JFrame();
        mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainWindow.setSize(width, height);
        mainWindow.setVisible(true);
        mainWindow.setLocationRelativeTo(null);
        mainWindow.setTitle(title);

        return mainWindow;
    }

    public static void main(String[] args) {

        JFrame mainWindow = makeWindow("Practice", 800, 600);
        Canvas mainCanvas = new Canvas();
        mainWindow.add(mainCanvas);
        mainCanvas.setSize(mainWindow.getWidth(), mainWindow.getHeight());
        mainCanvas.setBackground(Color.white);
        mainCanvas.createBufferStrategy(3);
        BufferStrategy bufferStrat = mainCanvas.getBufferStrategy();

        Graphics g = bufferStrat.getDrawGraphics();
        g.setColor(Color.black);
        g.fillRect(250, 250, 250, 250);
        g.dispose();
        bufferStrat.show();
    }
}

The program does not draw the black rectangle as intended, I feel like I've missed something really obvious here and I just can't see it. At the moment the program just makes a blank white canvas. I feel like part of the issue is that the buffer is just passing the frame with the rectangle faster than I can see, but there is no frame to load after that so I don't know why it's doing this.

A: A BufferStrategy has a number of initial requirements which must be meet before it can be rendered to. Also, because of the nature of how it works, you might need to repeat a paint phases a number of times before it's actually accepted by the hardware layer.
I recommend going through the JavaDocs and tutorial, they provide invaluable examples into how you're suppose to use a BufferStrategy
The following example uses a Canvas as the base component and sets up a rendering loop within a custom Thread.  It's very basic, but shows the basic concepts you'd need to implement...
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                TestCanvas canvas = new TestCanvas();

                JFrame frame = new JFrame();
                frame.add(canvas);
                frame.setTitle("Test");
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);

                canvas.start();
            }
        });
    }

    public class TestCanvas extends Canvas {

        private Thread thread;
        private AtomicBoolean keepRendering = new AtomicBoolean(true);

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        public void stop() {
            if (thread != null) {
                keepRendering.set(false);
                try {
                    thread.join();
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        }

        public void start() {
            if (thread != null) {
                stop();
            }

            keepRendering.set(true);
            thread = new Thread(new Runnable() {
                @Override
                public void run() {

                    createBufferStrategy(3);

                    do {
                        BufferStrategy bs = getBufferStrategy();
                        while (bs == null) {
                            System.out.println("get buffer");
                            bs = getBufferStrategy();
                        }
                        do {
                            // The following loop ensures that the contents of the drawing buffer
                            // are consistent in case the underlying surface was recreated
                            do {
                                // Get a new graphics context every time through the loop
                                // to make sure the strategy is validated
                                System.out.println("draw");
                                Graphics graphics = bs.getDrawGraphics();

                                // Render to graphics
                                // ...
                                graphics.setColor(Color.RED);
                                graphics.fillRect(0, 0, 100, 100);
                                // Dispose the graphics
                                graphics.dispose();

                                // Repeat the rendering if the drawing buffer contents
                                // were restored
                            } while (bs.contentsRestored());

                            System.out.println("show");
                            // Display the buffer
                            bs.show();

                            // Repeat the rendering if the drawing buffer was lost
                        } while (bs.contentsLost());
                        System.out.println("done");
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                        }
                    } while (keepRendering.get());
                }
            });
            thread.start();
        }

    }

}

Remember, the point of BufferStrategy is to give you full control over the painting process, so it works outside the normal painting process generally implemented by AWT and Swing
"At a later date the canvas will be updating many times a second so I am using a buffer strategy for this" - Before going down the "direct to hardware" solution, I'd consider using a Swing Timer and the normal painting process to see how well it works


Q: Async Loop seems to partially parallel I'm trying to implement a function, which slices a file into chunks and then sends them to my backend one after another.
The function has to hash each file & validate if the hash is already known before starting the upload.
The following code is the code part, where my problematic function is called.
        process: async (
          fieldName,
          file,
          metadata,
          load,
          error,
          progress,
          abort,
          transfer,
          options,
        ) => {
          // fieldName is the name of the input field - No direct relevance for us
          // logger.log(`fieldName: ${fieldName}`);

          // Usually Empty - Can be added with Metadata-Plugin
          // logger.log(metadata);

          const source = this.$axios.CancelToken.source();

          const abortProcess = () => {
            // This function is entered if the user has tapped the cancel button
            source.cancel('Operation cancelled by user');

            // Let FilePond know the request has been cancelled
            abort();
          };

          let chunks = [];

          const {
            chunkForce,
            chunkRetryDelays,
            chunkServer,
            chunkSize,
            chunkTransferId,
            chunkUploads,
          } = options;

          // Needed Parameters of file
          const { name, size } = file;

          if (chunkTransferId) {
            /** Here we handle what happens, when Retry-Button is pressed */
            logger.log(`Already defined: ${chunkTransferId}`);
            return { abortProcess };
          }

          this.hashFile(file)
            .then((hash) => {
              logger.log(`File Hashed: ${hash}`);
              if (hash.length === 0) {
                error('Hash not computable');
              }
              return hash;
            })
            .then((hash) => {
              logger.log(`Hash passed through: ${hash}`);
              return this.requestTransferId(file, hash, source.token)
                .then((transferId) => {
                  logger.log(`T-ID receieved: ${transferId}`);
                  return transferId;
                })
                .catch((err) => {
                  error(err);
                });
            })
            .then((transferId) => {
              transfer(transferId);
              logger.log(`T-ID passed through: ${transferId}`);

              // Split File into Chunks to prepare Upload
              chunks = this.splitIntoChunks(file, chunkSize);

              // Filter Chunks - Remove all those which have already been uploaded with success
              const filteredChunks = chunks.filter(
                (chunk) => chunk.status !== ChunkStatus.COMPLETE,
              );

              logger.log(filteredChunks);

              return this.uploadChunks(
                filteredChunks,
                { name, size, transferId },
                progress,
                error,
                source.token,
              ).then(() => transferId);
            })
            .then((transferId) => {
              // Now Everything should be uploaded -> Set Progress to 100% and make item appear finished
              progress(true, size, size);
              load(transferId);
              logger.log(transferId);
            })
            .catch((err) => error(err));

          return { abortProcess };
        },

uploadChunks is where the problem starts.
    async uploadChunks(chunks, options, progress, error, cancelToken) {
      const { name, size, transferId } = options;
      for (let index = 0; index < chunks.length; index += 1) {
        let offset = 0;
        const chunk = chunks[index];
        chunk.status = ChunkStatus.PROCESSING;
        // eslint-disable-next-line no-await-in-loop
        await this.uploadChunk(chunk.chunk, options, offset)
          .then(() => {
            chunk.status = ChunkStatus.COMPLETE;
            offset += chunk.chunk.size;
            progress(true, offset, size);
            logger.log(offset); // This is always chunk.chunk.size, instead of getting bigger
          })
          .catch((err) => {
            chunk.status = ChunkStatus.ERROR;
            error(err);
          });
      }
    },
    uploadChunk(fileChunk, options, offset) {
      const { name, size, transferId } = options;
      const apiURL = `${this.$config.api_url}/filepond/patch?id=${transferId}`;
      return this.$axios.$patch(apiURL, fileChunk, {
        headers: {
          'content-type': 'application/offset+octet-stream',
          'upload-name': name,
          'upload-length': size,
          'upload-offset': offset,
        },
      });
    },

As you can see uploadChunks takes an array of chunks, some options, two functions (progress & error) and a cancelToken (which I currently don't use, since I'm still stuck at this problem)
Each chunk in the array has the form of:
{
  status: 0, // Some Status indicating, if it's completed or not
  chunk: // binary data
}

The Function uploadChunks iterates over the chunk array and should in theory upload one chunk after another and always increment offset after each upload and then call progress. After this it should start the next iteration of the loop, where offset would be bigger than in the call before.
The calls themselves get executed one after another, but every call has the same offset and progress does not get repeatedly called. Instead my progress-bar locks until everything is uploaded and them jumps to 100%, due to the load-call in the first function right at the end.
So the upload itself works fine in the correct order, but all the code after the await this.uploadChunk... doesn't get called after each chunk and blocks somehow.

A: You are setting offset to 0 inside the loop. So offset is always 0. You should move this line:
let offset = 0;
before the for statement.