text:
Q: fitting classifier object of type 'int' has no len() I hope you bear with my questions. please let me know if it is unclear. I tried a lot to say any detail. but it may be still unclear. if so please let me know.
We have LDA topic modeling which purpose is to generate a number of topics given a set of documents.
so each document can belong to various topics.
Also, we can evaluate the model we have created. one of the approaches is using classification method like SVM.my goal is to evaluate created model.
I have faced with two kinds of code for making the LDA model.
1.
    # generate LDA model
id2word = corpora.Dictionary(texts)

# Creates the Bag of Word corpus.
mm = [id2word.doc2bow(text) for text in texts]

# Trains the LDA models.
lda = ldamodel.LdaModel(corpus=mm, id2word=id2word, num_topics=10,
                               update_every=1, chunksize=10000, passes=1,gamma_threshold=0.00, minimum_probability=0.00)

this way I can not use Fit_transform
2.
tf_vectorizer = CountVectorizer(max_features=n_features,
                                stop_words='english')
tf = tf_vectorizer.fit_transform(data_samples)

lda = LatentDirichletAllocation(n_topics=n_topics, max_iter=5,
                                learning_method='online',
                                learning_offset=50.,
                                random_state=0)

lda_x=lda.fit_transform(tf)

in the first approach, there is no fit_transform method for LDA model, I do not know why as I don't understand the difference between them.
anyway, I need to pass that LDA model I have created with the first approach to SVM(the reason I put these two approach here I s that I know with the second approach there is no error probably becaz of fit_transform but for some reason I couldnt use that),
this is my final code:
import os
from gensim.models import ldamodel
from nltk.tokenize import RegexpTokenizer
from nltk.stem.porter import PorterStemmer
from gensim import corpora, models
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.pipeline import Pipeline
from sklearn.multiclass import OneVsRestClassifier
from sklearn.svm import LinearSVC

tokenizer = RegexpTokenizer(r'\w+')

# create English stop words list
en_stop = {'a'}

# Create p_stemmer of class PorterStemmer
lines=[]
p_stemmer = PorterStemmer()
lisOfFiles=[x[2] for x in os.walk("data")]

fullPath = [x[0] for x in os.walk("data")]
for j in lisOfFiles[2]:
    with open(os.path.join(fullPath[2],j)) as f:
                    a=f.read()
                    lines.append(a)

for j in lisOfFiles[3]:
    with open(os.path.join(fullPath[3],j)) as f:
                    a=f.read()
                    lines.append(a)

for j in lisOfFiles[4]:
    with open(os.path.join(fullPath[4],j)) as f:
                    a=f.read()
                    lines.append(a)

# compile sample documents into a list
doc_set = lines
# list for tokenized documents in loop
texts = []

# loop through document list
for i in doc_set:
    # clean and tokenize document string
    raw = i.lower()
    tokens = tokenizer.tokenize(raw)

    # remove stop words from tokens
    stopped_tokens = [i for i in tokens if not i in en_stop]

    # stem tokens
    stemmed_tokens = [p_stemmer.stem(i) for i in stopped_tokens]

    # add tokens to list
    texts.append(stemmed_tokens)

# generate LDA model
id2word = corpora.Dictionary(texts)

# Creates the Bag of Word corpus.
mm = [id2word.doc2bow(text) for text in texts]

# Trains the LDA models.
lda = ldamodel.LdaModel(corpus=mm, id2word=id2word, num_topics=10,
                               update_every=1, chunksize=10000, passes=1,gamma_threshold=0.00, minimum_probability=0.00)

# Assigns the topics to the documents in corpus

dictionary = corpora.Dictionary(texts)

# convert tokenized documents into a document-term matrix
corpus = [dictionary.doc2bow(text) for text in texts]

#creating the labels
lda_corpus = lda[mm]
label_y=[]
for i in lda_corpus:
    new_y = []
    for l in i:
        sorted_labels = sorted(i, key=lambda z: z[0], reverse=True)
        if l[1] > 0.005:
            new_y.append(l[0])
        label_y.append(new_y)

classifier = Pipeline([
    ('vectorizer', CountVectorizer(max_df=2,min_df=1)),
    ('tfidf', TfidfTransformer()),
    ('clf', OneVsRestClassifier(LinearSVC()))])
classifier.fit(lda, label_y)

As you see in my code I have used the first approach for some reasons,
but in the last line, it raises an error(object of type int has no len()). It seems it can not accept lda created in this way (I was thinking because in this way I didnt use fit_transform)
how can I fix this error with my code?
many thanks for your patience and help in advance.
this is the full stack error :
/home/saria/tfwithpython3.6/bin/python /home/saria/PycharmProjects/TfidfLDA/test4.py
Using TensorFlow backend.
Traceback (most recent call last):
  File "/home/saria/PycharmProjects/TfidfLDA/test4.py", line 92, in <module>
    classifier.fit(lda, label_y)
  File "/home/saria/tfwithpython3.6/lib/python3.5/site-packages/sklearn/pipeline.py", line 268, in fit
    Xt, fit_params = self._fit(X, y, **fit_params)
  File "/home/saria/tfwithpython3.6/lib/python3.5/site-packages/sklearn/pipeline.py", line 234, in _fit
    Xt = transform.fit_transform(Xt, y, **fit_params_steps[name])
  File "/home/saria/tfwithpython3.6/lib/python3.5/site-packages/sklearn/feature_extraction/text.py", line 839, in fit_transform
    self.fixed_vocabulary_)
  File "/home/saria/tfwithpython3.6/lib/python3.5/site-packages/sklearn/feature_extraction/text.py", line 760, in _count_vocab
    for doc in raw_documents:
  File "/home/saria/tfwithpython3.6/lib/python3.5/site-packages/gensim/models/ldamodel.py", line 1054, in __getitem__
    return self.get_document_topics(bow, eps, self.minimum_phi_value, self.per_word_topics)
  File "/home/saria/tfwithpython3.6/lib/python3.5/site-packages/gensim/models/ldamodel.py", line 922, in get_document_topics
    gamma, phis = self.inference([bow], collect_sstats=per_word_topics)
  File "/home/saria/tfwithpython3.6/lib/python3.5/site-packages/gensim/models/ldamodel.py", line 429, in inference
    if len(doc) > 0 and not isinstance(doc[0][0], six.integer_types + (np.integer,)):
TypeError: object of type 'int' has no len()

Process finished with exit code 1


text:
Q: Formalization of the Proof of the Theorem of the Bijection of Composition of Two Mappings I'm trying to formalize in FOL the proof of the stated theorem.
Assume two mappings $f$,$g$.
With a slight circularity for brevity's sake, let

*

*$B(f): \text{"f is a mapping which is bijective whose codomain is the domain of g"}$,

*$B(g): \text{"g is a mapping which is bijective whose domain is the codomain of f"}$, and

*$B(g\circ f): \\\text{" $g\circ f$ is a composition which is bijective and whose domain is that of f and codomain that of g"}$

Theorem: $\forall f\forall g:B(f)\wedge B(g)\rightarrow B(g\circ f)$
Let $X:=dom(f), Y:=codom(f)=dom(g), Z:=codom(g)$.
We prove with

*

*$I(f): \text{"f is injective"}$

*$S(f): \text{"f is surjective"}$

that the inverse image is unique via injectivity of $f$ and $g$ (conjoined uniqueness of the inverse images if unique images), and via surjectivity of the both
$$
S(g)\leftrightarrow\forall z\in Z\exists y\in Y:g(y)=z
$$
that
$$
S(g)\wedge S(f)\longrightarrow (g\circ f)(x)=g(f(x))=g(y)=z,
$$
unquantified, as taken over from a common verbal proof.
Now we substitute
$$
\forall g(\forall z(\exists y:g(y)=z)\wedge\forall f(\forall y(\exists x:f(x)=y))\longrightarrow \forall z\exists y\exists x: g(y)=z\wedge f(x)=y.
$$
What I can't explain but what seems correct from the standpoint of the verbal proof and the conclusion that it reasonably draws, is whether this transition from the conjunction $$\forall z\exists y:P(y,z)\wedge\forall y\exists x P(x,y)$$ to $$\forall z\exists y\exists z:P(y,z)\wedge P(x,y)$$ is valid. And whether this is an implication or indeed an equivalence.
I am slightly familiar with the propositional logic and the quantification theory  but have no knowledge of the formal proof theory nor model theory. I will gratefully acknowledge all answers regardless of the complexity, as I'm eager to learn. Especially I'll be grateful for any answer that would also draw a link to the particular concept in proof or model theory, as I'm trying to systematize this (plain keywords good enough--just to learn what to look for).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Automatic refresh
* order by their id in a jquery sortable #div I need that, when a #sortable receive an item, it automatic refreshes its own
's order, ordering
s alphabeticly by their id attribute.

A: Firstly; that function you want a clue about.. it doesn't exactly matter.. or rather, the parameters do not, unless you want to do something with the ui or event data.  Receive executes whenever an element is received from another, linked list.  JS has an in-built sort function, and that combined with jquery, and the UI bit, will allow for this to work.
The way to combine it all..  get the element array of li elements using jquery ($('element') returns an array), sort that array using an anonymous function that compares the id values of the a and b variables(of the anonymous function), and execute the sort based on when(and where) the receive event occurs.  I have a working example, but I'd rather like to see you try something before I post it here.  I've explained how to achieve the desired result to the best of my ability without giving away everything.


text:
Q: Jooq: only jooq's logo is logged Problem: Jooq logs only it's logo ("thank you for using jooq"), but does not log the queries as per docs.
Jooq version: 3.10.2 (tried older ones)
logger dependencies:
compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.10.0'
compile group: 'org.apache.logging.log4j', name: 'log4j-to-slf4j', version: '2.10.0'

(tried others (slf-log4j12) as well, without success)
log4j.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration>
    <appender name="stdout" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%m%n" />
        </layout>
    </appender>

    <root>
        <priority value="debug" />
        <appender-ref ref="stdout" />
    </root>
</log4j:configuration>

A: The problem is a result of conflicting dependencies.
If anyone stumbles upon this problem, as an alternative you can implement ExecuteListener as shown here
and call your log statements there.

A: With this log4j2 configuration I have logged jooq queries:
<Configuration>
  ...
  <Loggers>
    ...
    <!-- This disables logging the jooq logo -->
    <AsyncLogger name="org.jooq.Constants" level="warn"/>
    <!-- This enables logging queries -->
    <AsyncLogger name="org.jooq" level="debug"/>
  </Loggers>
</Configuration>


text:
Q: Good loading icon jquery So I just started learning Javascript and jQuery at the same time, and it seems easy.
Now I am making a function that shows a loading image (I made mine on http://www.ajaxload.info/) but I want something that's more cool, like maybe an image that changes every time...
Also, sometimes my loading image appears under other stuff I have no clue why so I am trying to fix that problem, if you have any hints please let me know.
Here is what I have now:
...

...

A: I have done this with my projects, very interesting idea! So here's how i do it.
Of course you can tweak this as you wish and i am sure there are lots of stuff you can do to make it more beautiful but here is what you can do with minimal configuration.
CSS :
.preloader{
    z-index: 1001;  // This is what controls the layer position (the more it's high the more it becomes on top) I put 1001 because i don't use z-indexes more than 1000 but idk about you..
}

HTML :

Javascript (jQuery) :

BTW, for preloaders i use this site : http://preloaders.net/
I am sure you will like it! It's far better than the one you have.
So basically just call the changePreloader() when you want to change it, and well for the first function you know how to use it already :)


text:
Q: increase value to a point, then start decreasing to a point I am making a simple animation in javascript canvas and in order to accomplish the requested result i need to have an object like this:
circle: {
    x: scene_point.x,
    y: scene_point.y,
    vel_x: randomFloat(0.100, 0.500),
    vel_y: randomFloat(0.100, 0.500),
    r: 0,
    r_max: 10,
    trend: 'up'
}

now animation in loop should be like this:

*

*increase value of radius till it get max, increase opacity until circle become fully visible

*when circle has max radius and full opacity, we start to decreasing both values

*when circle radius and opacity again go down to 0, we reset circle and start over.

this is the code i written to accomplish above:
if(circle.trend === 'up' && circle.r < circle.maxR) { // growing, to reach max
    circle.r = parseFloat(circle.r) + parseFloat(circle.decayR);
}
if(circle.trend === 'up' && circle.r >= circle.maxR) { // reached max, starting to decay
    circle.trend = 'down';
}
if(circle.trend === 'down' && circle.r >= 1) { // decaying, to reach min
    circle.r = parseFloat(circle.r) - parseFloat(circle.decayR);
}
if(circle.trend === 'down' && circle.r < 1) { // reached min, reseting
    reset(i);
}

and finally draw object to get proper opacity:
ctx.fillStyle = 'rgba(210, 210, 210, ' + circle.r / circle.maxR + ')';

The question is, is it possible to accomplish above without "trend" logic, its just doesnt seem / feel right. I have to use 4 if conditions and additional "trend" parameter to just go up and down. Maybe there is more friendly way to do it. I am just new to the canvas and animations and i dont know all the tricks yet ;)

A: You could just do:
circle.r += circle.decayR;

if(circle.decayR > 0 && circle.r >= circle.maxR)
  circle.decayR *= -1;

if(circle.decayR < 0 && circle.r < 1)
  reset(i);

Basically, just flip the sign of the decayR.
Working example:

var circle, canvas, ctx;

canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');

function reset() {
  circle = {
    decayR: 1,
    r: 0,
    maxR: 20,
    x: 50 + Math.random() * 50,
    y: 50 + Math.random() * 50
  };
}

function update() {
  circle.r += circle.decayR;

  if (circle.decayR > 0 && circle.r >= circle.maxR)
    circle.decayR *= -1;

  if (circle.decayR < 0 && circle.r < 1)
    reset();

  // clear
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // draw
  ctx.beginPath();
  ctx.arc(circle.x, circle.y, circle.r, 0, Math.PI * 2);
  ctx.closePath();
  ctx.fill();

  requestAnimationFrame(update);
}

reset();

requestAnimationFrame(update);
#canvas {
  width: 200px;
  height: 200px;
  border: solid 1px black;
}
<canvas id="canvas" width="200" height="200"></canvas>

A: I think it can be put shorter like this:
if(circle.trend === 'up'){
  (circle.r >= circle.maxR) ?
    circle.trend = 'down' :
    circle.r += circle.decayR;
}else{
  (circle.r >= 1) ?
    circle.r -= circle.decayR :
    reset(i);
}


text:
Q: Largest smaller value in left subarray for all elements I was solving the question of Longest Increasing Sub-sequence using dynamic programming with O(n^2) as per following pseudocode (Basically we are doing bottom-up approach to get length of largest increasing sub-sequence that ends at index i for all i of given array):
#nums is sequence of numbers like [10,9,2,5,3,7,101,18]
dp=[1]*len(nums) #dp[i] is length of longest increasing sub-sequence ending at element nums[i]
for i in range(len(lst)):
    for j in range(i):
        if nums[i]>nums[j]:
            dp[i]=max(dp[i], dp[j]+)
#max(dp) will give the length of Longest Increasing Sub-sequence

Though I got a different approach for O(nlog(n)) solution for above question, I thought of a modification in above approach that led me to another problem and I couldn't think of if I could solve that problem in better than O(n^2) time.
I thought that if I could know the largest element smaller than nums[i] for all i in [0, len(nums)-1] then I could do something like this (I am not sure if this approach is perfectly okay).
#nums is sequence of numbers like [10,9,2,5,3,7,101,18]

left=[]
#Suppose left is a list of length len(nums) such that left[i] will give largest element smaller than nums[i] in left sub-array for nums (excluding i)
#i.e. for above nums array, left  = [-1,-1,-1,2,2,5,10,10] #I am showing values here for clarity but I can as well store index of largest element smaller than nums[i] for quick access
#No element is left to 10 so left[0]=-1
#No element left to 9 is smaller than 9 so left[1]=-1
#No element left to 2 is smaller than 2 so left[2]=-1
#In array left to 5, 2 is than largest element smaller than 5 so, left[3]=2, and so on

#Now
dp=[1]*len(lst) #dp[i] is length of longest increasing sub-sequence ending at element nums[i]
for i in range(len(lst)):
    if left[i]!=-1:
        dp[i]=max(dp[i], dp[left[i]]+1) #Assuming I am storing indices in array left

Now, my question is not if above approach for the above mentioned problem is correct BUT that how to make the array left in less than O(n^2). If I could get left in less than O(n^2) the it will be worth to check if above approach works (though that's not the intention of asking this question here, I added that to show how I came across above problem). Can left be built in less than O(n^2). For clarity I am adding more input and output below for left (In below examples I will be showing required index in left):
Input: [10,9,2,5,3,7,101,18]
Output: [-1,-1,-1,2,2,3,0,0]

Input: [10,9,8,7,6,8]
Output: [-1,-1,-1,-1,-1,3] #largest element smaller than 8 in left sub-array of 8 is 7 whose index is 3

Input: [0,1,2,3,4,5,6]
Output: [-1,0,1,2,3,4,5] #no element in left sub-array of element 0, so left[0]=-1


text:
Q: Multilevel CTE Expression slows the execution (Reposted with changes) In SQL Server, I have a table-valued function which contains a multi-level CTE as shown in the code here:
CREATE FUNCTION [dbo].[GetDataset_Test]
(@XMLBlock XML, @Id INT)
RETURNS
@tempTable TABLE
            (
                methodID INT,
                [Id] INT,
                SavingMessage varchar(50)
            )
AS
BEGIN

DECLARE @ObjectID INT = 2;
DECLARE @ExchangeRate INT = 2;
DECLARE @Cond INT = 1;

DECLARE @Param1 varchar(50) = 'name1';
DECLARE @Param2 varchar(50) = 'name2';

    WITH CTE AS
    (
        SELECT
            Col1,
            con,
            DiscountLine,
            tempNumber,
            ItemCostExVAT,
            Quantity,
            SomeValue,
            methodID,
            VATAmount,
            SubTypeID,
            Line,
            VATMultiplier,
            ROUND(dbo.GetAmountCustomFunction(COALESCE(Id, AnotherId),  COALESCE(Price, PriceValue)), 2) As [Amount]
        FROM
            dbo.GetObject(@Id, @ObjectID, @ParameterBlock) AS BC

        INNER JOIN
            dbo.fnPrices(@ID, @CurrencyID) BPD ON BPD.Id = BC.productid
    ),
    CTE1 AS
    (
        SELECT
             *,
             CASE WHEN con = 0 THEN Quantity ELSE 1 END AS Quantity
         FROM
             CTE
         WHERE
             1 = SomeValue
    ),
    CTE2 AS
    (
        Select *,
            MIN(CASE WHEN DiscountLine=1 THEN 1 ELSE 20 END) over (PARTITION by tempNumber) As StockControlled,
            SUM(ItemCostExVAT * Quantity) OVER ( PARTITION BY tempNumber ) AS tempCost ,

            ROUND(CASE
                    WHEN methodID = 8 THEN DiscValue
                    WHEN methodID = 2 THEN END ,
                DicsValue,VATAmount),2) AS AmountExVAT

                    From CTE1
   ),
   CTE3
   (
       SELECT
           *,
           ROUND(CASE
                     WHEN SubTypeID = 1 AND Line = 1 THEN  -1 * AmountExVAT
                     ELSE 20
                 END, 2) PriceExVAT
       FROM
           CTE2
   ),
   CTE4
   (
       SELECT
           *,
           ROUND(@ExchangeRate * CASE WHEN @Cond = 1 THEN AmountExVAT * VATMultiplier ELSE 20 END, 2) CashBack
       FROM
           CTE3
   ),
   CTE5
   (
       SELECT
           *,
           dbo.FormatMessage(@Param1, @Param2) AS SavingMessage
       FROM
           CTE4
   )
   INSERT INTO @tempTable
       SELECT
           methodID, [Id], SavingMessage
       FROM
           CTE5

   RETURN
END

In above query because of multi-level CTE and table value parameter I can think that its trying to query recursively and taking more execution time.
I know that we cannot use temporary table as function parameter, is there any alternative of this or can I use temporary table by any way in function?
Or can I make some changes in CTE to improve my T-SQL function query execution time?


text:
Q: Knockout: Remove Array Item from Computed Observable I have a computed variable which contains array. Something like this:
self.MyArray = ko.computed(function() {
    var source = [];
    // Some Logic to Prepare Array
    ...
    ...
    ...

    return source;
});

Now On a button click event, I want to remove Item from self.MyArray. But I could not find any feasible solution for this.
I tried with this:
self.MyArray.remove(currentRow);

But it throws exception:

Uncaught TypeError: self.MyArray.remove is not a function

Sample Fiddle: Fiddle

A: Regular Array
You're returning a regular array, not a knockout observableArray. A standard javascript array does not have a remove function. In the following example, I've used a generic remove function to solve your problem.

var bar = "foo";

self.MyArray = ko.computed(function() {
    var source = [];
    source.push(bar);
    return source;
});

function remove(array, element) {
    const index = array.indexOf(element);

    if (index !== -1) {
        array.splice(index, 1);
    }
}

console.log(self.MyArray()); // ["foo"]

remove(self.MyArray(), bar);

console.log(self.MyArray()); // []
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

Knockout ObservableArray
If you want to use an observableArray instead, you don't need the extra remove function. A knockout observableArray already has one. The example below shows how you can remove it.

var bar = "foo";

self.MyArray = ko.computed(function() {
    var source = ko.observableArray();
    source.push(bar);
    return source;
});

console.log(ko.unwrap(self.MyArray())); // ["foo"]

self.MyArray().remove(bar);

console.log(ko.unwrap(self.MyArray())); // []
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

A: There are several changes required for the code to work. I've listed below the important ones:

*

*The binding for Name input must be two-way to allow the Add button to push the text to the NameList array. You could either use textInput or value binding for this, instead of the text binding.
<input type="text" data-bind="textInput: Name">

*While adding a new item to the array, since it is an observable it must be accessed as self.NameList.push(self.Name());, rather than self.NameList.push(self.Name);.

*Inside the remove function, you can get the index of the source element, and then remove it. Something like:
var idx = self.DataSource().indexOf(selectedData);
self.NameList.splice(idx, 1);

Here's the updated fiddle: http://jsfiddle.net/afmn2keb/7/


text:
Q: Add another stroke to the existing canvas element How to add another stroke with a different color and length into the same circle?
This script use Mootools lib. Can it be converted in pure JavaScript or jQuery?
fiddle: http://jsfiddle.net/xc4xnzcq/1/
Thanks :)
// SVG stuff
var ctx = document.id('counter').getContext('2d');
var circ = Math.PI * 2;
var quart = Math.PI / 2;

ctx.beginPath();
ctx.strokeStyle = '#ff00ab';
ctx.lineCap = 'square';
ctx.closePath();
ctx.fill();
ctx.lineWidth = 10;

var imd = ctx.getImageData(0, 0, 160, 160);

var draw = function(current) {
    ctx.putImageData(imd, 0, 0);
    ctx.beginPath();
    ctx.arc(119, 70, 60, -(quart), ((circ) * current) - quart, false);
    ctx.stroke();
}

var myFx = new Fx({
    duration: 5500,
    transition: 'bounce:out',
    onStep: function(step){
        draw(step / 100);
    }
});

myFx.set = function(now){
    var ret = Fx.prototype.set.call(this, now);
    this.fireEvent('step', now);
    return ret;
};

myFx.start(0, 80);

A: Drawing a second path seems to work fine for me.
// SVG stuff
var ctx = document.id('counter').getContext('2d');
var circ = Math.PI * 2;
var quart = Math.PI / 2;

var imd = ctx.getImageData(0, 0, 160, 160);

var draw = function(current) {
    ctx.putImageData(imd, 0, 0);
    ctx.beginPath();
    ctx.strokeStyle = '#ff00ab';
    ctx.lineCap = 'square';
    ctx.lineWidth = 10;
    ctx.arc(119, 70, 60, -(quart), ((circ) * current) - quart, false);
    ctx.stroke();

    ctx.beginPath();
    ctx.strokeStyle = '#bb00bc';
    ctx.lineCap = 'square';
    ctx.lineWidth = 5;
    ctx.arc(119, 70, 60, -(quart), ((circ) * current) - quart, false);
    ctx.stroke();
}

var myFx = new Fx({
    duration: 5500,
    transition: 'bounce:out',
    onStep: function(step){
        draw(step / 100);
    }
});

myFx.set = function(now){
    var ret = Fx.prototype.set.call(this, now);
    this.fireEvent('step', now);
    return ret;
};

myFx.start(0, 80);


text:
Q: Double vision with the Cardboard - Unity I am trying to create a small android game in unity for the google cardboard, but the problem is that my 5.7 inch phone is too big. The standard profile in the SDK doesn't work with my phone and I see double images.
As far as I know, I need to change the profile using a QR-code or set a default URI in some script. I have created a QR with the
Viewer Profile Generator
and it works great with the standard Cardboard app, but I do not understand how to use it with my program. Syncing the game with the Cardboard app only seems to work with iOS, and changing the DefaultDeviceProfile in the Cardboard.cs doesn't do anything for me.
Thanks.

A: Your phone is running Marshmallow, which has the new runtime permissions model.  Cardboard SDK is not fully up to speed with this model, because it does not prompt the user to add the needed permissions, it just silently fails.  In this case, the needed permission is READ_EXTERNAL_STORAGE, which grants access to the sdcard, where the QR code data is stored.  For now, the best way around this is to make sure that targetSDK = 22 in your project's AndroidManifest (in Assets/Plugins/Android).  For a specific app that is already built, you can activate the "storage" permission in the app's App Info screen.


text:
Q: Multiple Slick Sliders On Same Page with same classes? I'm using Slick js for some carousels on a page. Each carousel has a thumbnail navigation. Everything works great but my issue is I want more than one of these carousels on a page with the same class names. Is this possible, I tried an iteration over the carousels but it was breaking them. I could just setup numerous versions of slick carousels for each carousel but wondering if there is a way to just use the same classes for each of them without causing bugs.
HTML: each carousel setup like this

        Slide One

        Slide Two

        Slide Three

      Slide One Thumbnail

        Slide Two Thumbnail

        Slide Three Thumbnail

jquery:
     $(function () {
        var $videoSlider = $('.video-slider');

        /*INIT*/
        if ($videoSlider.length) {
          $('.slider-for').slick({
            slidesToShow: 1,
            slidesToScroll: 1,
            arrows: false,
            draggable: false,
            fade: true,
            asNavFor: '.slider-nav'
          });

          $('.slider-nav-thumbnails').slick({
            slidesToShow: 3,
            slidesToScroll: 1,
            asNavFor: '.slider-for',
            dots: false,
            arrows: false,
            vertical: true,
            draggable: false,
            centerMode: false,
            focusOnSelect: true,
            responsive: [
              {
                breakpoint: 769,
                settings: {
                  vertical: false
                }
              }
            ]
          });
});

A: I think you just have to modify your code to initialize each slider separately. But that should be consistent with keeping the same classes.
Assuming your .slider-nav-thumbnails is always going to immediately follow your .slider-for, this should work:
$(function () {
    $('.slider-for').each(function(num, elem) {
        elem = $(elem);
        elem.slick({
            slidesToShow: 1,
            slidesToScroll: 1,
            arrows: false,
            draggable: false,
            fade: true,
            asNavFor: '.slider-nav'
        });

        elem.next('.slider-nav-thumbnails').slick({
            slidesToShow: 3,
            slidesToScroll: 1,
            asNavFor: '.slider-for',
            dots: false,
            arrows: false,
            vertical: true,
            draggable: false,
            centerMode: false,
            focusOnSelect: true,
            responsive: [
                {
                    breakpoint: 769,
                    settings: {
                        vertical: false
                    }
                }
            ]
        });
    });
});

A: You can try something like this
$(document).ready(function() {
    var myCarousel = $(".slider-for:not(.slick-initialized)");
    myCarousel.each(function() {
        $(this).slick({});
    });
});


text:
Q: Why TI stopped supporting CC2530ZDK-ZNP-MINI Kits I am planning to buy CC2530ZDK-ZNP-MINI Kit for my project on sensor networks as it has most of the sensors that I need but I found out from the TI website that they are not supporting these kits anymore. Does anybody know why TI stopped supporting them??
Thanks in advance

A: Now they have the CC2530 booster pack for the MSP430 or Stellaris Launchpad. So you will want to use these, because CC2530ZNP mini kit is discouraged for new developments.
http://www.anaren.com/air/cc2530-boosterpack-kit


text:
Q: Writing Unit Test with Spring Data Neo4j I'm facing Difficulty writing unit tests with Spring Data Neo4j.
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = { Application.class })
@WebAppConfiguration
public class SomeRepositoryTest {

    @Autowired
    SomeRepository someRepository;

    @Autowired
    Session session;

    @Test
    public void firstTest() {
        System.out.println(someRepository.findAll());
    }

}

I have no idea how to populate data into database.
For Unit Testing, I've set property of driver to driver=org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver
@ ogm.properties, in order to start Embedded Database.

A: You can populate data using session.query() where you supply a Cypher statement to set up data. Or, if you want a handle to the embedded graph database, this snippet of code will help:
EmbeddedDriver embeddedDriver = (EmbeddedDriver) Components.driver();
GraphDatabaseService databaseService = embeddedDriver.getGraphDatabaseService();


text:
Q: DBGo INSERT INTO via SQL.CommandText I have taken the habit to use SQL.TEXT variable to initialize my queries in order to avoid two statements: SQL.Clear; SQL.Add( ); using DBExpress.
Using dbGo for a new small project, this makes:
SQL.CommandText := 'INSERT INTO LeaveClass (id,name,color,status) VALUES (1,''Joe'',255,''Ok'')';
ExecSql;

This command breaks with a syntax error. But if we use:
SQL.Clear;
SQL.Add( 'INSERT INTO LeaveClass (id,name,color,status) VALUES (1,''Joe'',255,''Ok'')' );
ExecSql;

It works fine! Well I have wasted some time before catching up this problem and find its way around. What errors do I do? May be the dbGo.ADOQUERY.Sql.Clear makes a deep cleaning that the assignment via dbGo.ADOQUERY.SQL.CommandText doesn't. Weird. Any commands?

A: CommandText really only works for SELECT or other operations that return data (recordsets). It's not designed for ExecSQL or INSERT/DELETE type operations.
Simply use ADOQuery.SQL.Text instead:
ADOQuery1.SQL.Text := 'INSERT INTO LeaveClass (id,name,color,status) VALUES (1,''Joe'',255,''Ok'')';
ADOQuery1.ExecSQL;
ADOQuery1.Close;

Setting the Text property directly automatically replaces what was there before, removing the need for Clear.


text:
Q: PostgreSQL custom unique constraint on many to many link table I have a what some might call a pivot table for a many to many relationship. Here are the tables.
users:
 - id
 - name

excursions:
 - id
 - name

excursion_user:
 - user_id
 - excursion_id

I want to add a unique constraint to only allow 1 excursion per user. So the user_id excursion_id pair can only exist once in the table. How would I go about writing this constraint?


text:
Q: Who fixes issue reports of Stack Exchange? There are moderators who apply a "status tag" (also known as red tag) on questions tagged as bugs and feature-request, e.g. (status-completed, status-declined, status-norepro etc.)
Are these moderators also the developers of Stack Exchange issue reporting system?

A:
Are these moderators also the developers of Stack Exchange issue reporting system?

Sometimes, but not always. On every Stack Exchange meta site, any user who is a moderator with a diamond can add/remove the "red tags", however this does not mean that person also works for Stack Exchange. None of the moderators listed in the "moderators" tab of the /Users page of the site is SE employee, as they can't also be a site moderator.
Stack Exchange employees (including developers) might have a diamond on any site, however they'll not be listed as moderators and their role is not to moderate the sites. However, they also have the power to add/remove red tags exactly as the moderators, and they often to this to mark bug as fixed (or declined).
The only people who actually fix the bugs are SE developers, not the site moderators, who don't work for SE and don't have access to the code anyway.
However, site moderators might put a status-completed for example for a bug that was fixed a while ago, and the developer who fixed it forgot to do it themselves. If ordinary user spots a bug report which is clearly fixed, but lacking the completed tag, they can also flag for mod attention and ask for the tag to be added.

A: Meta's slightly unique. There's different sorts of mods here. I'm a community mod. We're a relatively new thing. I handle most sorts of flags I come across but I don't really have any insight over development - so we tend not to handle these.
At the moment, as such we leave those flags for the community managers, developers and other employees.
On other sites or if it's something we can confirm is resolved or won't fix we might, but on MSE chances are it'll need to wait for an employee.


text:
Q: jquery ajax $.post not working IE10 I've tried this two ways.
Way 1
function Login() {
    var email = encodeURIComponent($("#loginemail").val());
    var pass = encodeURIComponent($("#password").val());
    $.ajax({
        url:"/user/login",
        type: "POST",
        data: {email:email, password:pass},
        dataType: "json"
    }).done(LoginDone);
    //$.post("/user/login", {email:email, password:pass}, LoginDone);
}

Way 2
    function Login() {
        var email = encodeURIComponent($("#loginemail").val());
        var pass = encodeURIComponent($("#password").val());
        $.post("/user/login", {email:email, password:pass}, LoginDone);
    }

Both ways work fine on chrome, but for some reason with IE it doesn't send the data {email:email, password:pass} in the POST, or at all.
I've tried both on a local server, and on a live webserver, both with the same results.
Using IE10 here.

A: Can't fix @jQuery bug tracker: AJAX Post on IE10 / Windows 8

A: After deep debuggind I found a workaround for IE10 AJAX POST Bug:
do not use POST with GET.
$.post("Page.aspx?action=edit",a,function(data) {dataRow[0]=data; GoToShowMode(row)});

change to
a.action=edit;
$.post("Page.aspx",a,function(data) {dataRow[0]=data; GoToShowMode(row)});

A: IE-10 does not work data serialize => $(this).serialize()
 $('#formLogin').submit(function () {

        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            cache: false,
            success: function (data) {

                var val1 = "";
                var val2 = "";

                $.map(data, function (item) {
                    val1 = item.success;
                    val2 = item.URL;
                });

                if (data[0].messageCode == "success") {
                    GoGO(data[0].URL);
                }
                else {
                    alert(data[0].message);
                }
            }
        });
        return false;
    });

For this you can use this line on _layOut.chtml before metatag. So, IE-10 works just like IE-9.
  <meta http-equiv="x-ua-compatible" content="IE=9" >

A: Try this: http://code.gishan.net/code/solution-to-ie10-ajax-problem
Works for me. This is a known issue of IE10.

A: I've had the same problem with IE 10 (10.0.9200.16521) on Win7 x64 SP1.
I've solved the problem simply by using a newer version of jQuery (1.9.1 in place of 1.8.3)

A:
data: {email:email, password:pass}

should be
data: {"email":email, "password":pass}

You are passing the value of the variables as the key so if your server-side resource is expecting email it is actually seeing the value of that variable encodeURIComponent($("#loginemail").val()).
This is likely not an IE10 issue, this shouldn't work as written in any browser.
Update
This answer may no longer be applicable due to bug fixes in IE 10.
Please disregard this answer it is wrong and cannot be deleted due to being accepted.


text:
Q: Graph API not returning image/picture for community pages Graph API is not returning image("picture" attribute) for objects corresponding to community pages, which used to be returned earlier. For example this https://graph.facebook.com/178790412179919 does not have picture attribute whereas the corresponding page has an image.
Also the FQL query done on the "albums" connection for some objects does not have a "cover_pid" attribute for an album corresponding to type "profile", which again used to work earlier.
Does anybody know if anything has changed in Graph API corresponding to this in last couple of weeks (I am fairly confident it used to work earlier in the expected way). I looked through Facebook API release notes but could not find any changes corresponding to this. Please let me know if this not appropriate post for this forum.

A: https://developers.facebook.com/docs/reference/api/page/
picture is a connection, not an attribute. So ...
https://graph.facebook.com/178790412179919/picture
And as the docs say: Returns a HTTP 302 with the URL of the user's profile picture.
Kinda goofy? Yes, but it works exactly as the docs say it does. I suspect they implemented it this way so it could easily be used in an <IMG> tag.

A: UPDATE:
It still works via FQL. In your case:
https://api.facebook.com/method/fql.query?query=SELECT+page_id%2C+pic+FROM+page+WHERE+page_id+%3D+178790412179919&format=json

I can confirm that this PREVIOUSLY worked, but NO LONGER works. Facebook have removed the picture connection from Community Pages.
I suspect the reason is that most of these images are pulled from Wikipedia, and there was a licensing / attribution issue.
Unfortunately, Facebook is no longer a reliable source of images for entities (e.g. bands).


text:
Q: Authentication failed to java card Manager after changing Global Platform default key in gpshell I want to change globalplatform  default key for loading applet and secure messaging to card manager.
I could change my gemalto default GP card key using bellow commands successfuly:
mode_211
enable_trace
establish_context
card_connect -readerNumber 1
select -AID A000000018434D00
open_sc -security 1 -keyind 0 -keyver 1 -key 47454d5850524553534f53414d504c45  -keyDerivation visa2 // Open secure channel
put_sc_key -keyver 0 -newkeyver 1 -key 505152535455565758595a5b5c5d5e5f // Put secure channel keys
card_disconnect
release_context

But when i want to make secure channel to card manager by new key, cryptogram which produces in host side doesn't match to card side. The old key doesn't work too.
Commands for authentication to card manager are:
open_sc -security 1 -keyind 0 -keyver 0 -key 505152535455565758595a5b5c5d5e5f  -keyDerivation visa2 // Open secure channel

also i tested
open_sc -security 1 -keyind 0 -keyver 1 -key 505152535455565758595a5b5c5d5e5f  -keyDerivation visa2 // Open secure channel

and
open_sc -security 1 -keyind 1 -keyver 0 -key 505152535455565758595a5b5c5d5e5f  -keyDerivation visa2 // Open secure channel

and
open_sc -security 1 -keyind 1 -keyver 0 -key 505152535455565758595a5b5c5d5e5f  -keyDerivation visa2 // Open secure channel

Also i tested the process by smartcafe smart expert 3.2 (G&D card) and the results are same.
I appreciate if anyone can help me.

A: You need to use:
open_sc -security 1 -key 505152535455565758595a5b5c5d5e5f

As the new key is not diversified (derived) and you must use it directly.
Good luck!

And beware that there is a limit on unsuccessful authentications -- you might lock your card.


text:
Q: RabbitMQ IModel.Dispose hangs For some reason this started happening. Didn't yesterday. My client hangs after channel.BasicPublish returns in channel.Dispose. My connection is not bad, i.e. it's in open state and app is not being shutdown as suggested in https://groups.google.com/forum/?fromgroups=#!topic/rabbitmq-discuss/5nzeEqI5qxw. Both ways behave the same:
using (var channel = _connection.CreateModel()) {
  //use channel here
}

and
var channel = _connection.CreateModel()
//use channel here
channel.Dispose();

A: They have bug 25255 on this issue - link.
For now try using a timeout around this call.
private void DisconnectWithTimeout(IConnection connection, int timeoutMillis)
{
    var task = Task.Run(() => connection.Dispose());

    if (!task.Wait(timeoutMillis))
    {
        //timeout
        throw new TimeoutException("Timeout on connection.Dispose()");
    }
}


text:
Q: iPhone simulator show image with wrong dimensions in xCode5, new a sprite-kit project.
run it with iPhone retina 3.5-inch simulator.
the screen dimensions: 480*320
the spaceship image shows with double size in the simulator.
how to make the image size right.

A: Firstly you can check your images size its correct to that particular dimension which you want after that you deselect the autolayout property in identity inspector then give Scale To Fill property to UIImageView.

A: I had the same problem and it turned out to be the SKScene's Scaling modes Apple reference which determine how the scene's area is mapped to the view that presents it.
SKSceneScaleModeFill,
SKSceneScaleModeAspectFill,
SKSceneScaleModeAspectFit,
SKSceneScaleModeResizeFill

You can also hard code the size in the ViewController to test it:
// Create and configure the scene.
SKScene * scene = [TheGameTableScene sceneWithSize:CGSizeMake(480, 320)]; //skView.bounds.size];
scene.scaleMode = SKSceneScaleModeAspectFill;


text:
Q: Knex cannot connect to LocalDB instance using named pipe I'm attempting to connect to a LocalDB instance through Knex using a named pipe:
np:\\.\pipe\LOCALDB#DBFBFA07\tsql\query
I can connect to it perfectly fine through SSMS & sqlcmd, but whenever I set my Knex config.server property to the named pipe, it says Failed to connect to: np:\\...\query - getaddrinfo ENOTFOUND np:\\...\query
The dev config that I'm using:
development: {
      client: "mssql",
      connection: {
          database: process.env.SQLSERVER_DB,
          user: process.env.SQLSERVER_USER,
          password: process.env.SQLSERVER_PASSWORD,
          server: process.env.SQLSERVER_SERVER
      }
  }

and my .env config:
SQLSERVER_DB=<db_name>
SQLSERVER_USER=<username>
SQLSERVER_PASSWORD=<password>
SQLSERVER_SERVER="np:\\.\pipe\LOCALDB#DBFBFA07\tsql\query"

A: The underlying mssql driver and TDS protocol implementation does not support named pipe connections to LocalDB. See this


text:
Q: Is there a way to checkout git repository, to certain folder with maven? I am attempting to automatize download of repository containing only protocol-buffers (with structure), to "resource" folder for later processing.
I need this kind of functionality, to keep my *.proto files separated from c++ and java code, as they are technically not connected with each other (java application is used for debugging).
My desired effect is to at least checkout repo into project —
My dreamed effect is to get this repo updated every time I run maven.
BR

A: EDIT
After working a lot with such a problem, I found personally that the git submodule might be a solution for you (if you are not using svn).

Okay, so after googling, I have came across this: maven-scm-plugin, which even from description solves my request.
To save time for most people I will paste example of usage, to make it work.
You need to add this to your pom structure:
<project>
    <scm>
        <connection>scm:git:[YOUR_PROJECT_URL]</connection>
    </scm>

    <--! second part -->

    <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-scm-plugin</artifactId>
            <dependencies>
                <dependency>
                    <groupId>org.codehaus.plexus</groupId>
                    <artifactId>plexus-utils</artifactId>
                    <version>2.1</version>
                </dependency>
                <dependency>
                    <groupId>org.apache.maven.scm</groupId>
                    <artifactId>maven-scm-provider-gitexe</artifactId>
                    <version>1.2</version>
                </dependency>
            </dependencies>
            <version>1.0</version>
            <configuration>
                <connectionType>connection</connectionType>
                <!-- YOUR PATH HERE -->
                <checkoutDirectory>src/main/resources/meta</checkoutDirectory>
            </configuration>
            <executions>
                <execution>
                    <id>tag</id>
                    <phase>deploy</phase>
                    <goals>
                        <goal>tag</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
</project>


text:
Q: Can't install Compare plugin in notepad++ I am trying to install compare plugin in notepad++ v7.6.2 32bit
following this tutorial
https://www.youtube.com/watch?v=qvEOX6mSbpo
I did exact same steps, except I realized when I tried to place the DLL in the plugins folder, I didn't find a plugins folder!
so I created one myself and placed the DLL. restarted notepad++ and I can't see the compare plugin at all in plugins

I found this thread here
https://notepad-plus-plus.org/community/topic/17492/plugins-gone/2
apparently, plugins in the new version have to be placed in a subfolder of the plugin name due to organization
so I did that, and still, I can't see the compare plugin

finally, I tried installing from PluginsAdmin (apparently that's what plugin manager is replaced within new notepad++ versions), and it restarts automatically during installation, but i still cannot see compare plugin listed...

what is going on?
Update:
i discovered, thanks to this thread (last post) that based on initial installation selection (which i think i just did default installation whatever options are selected automatically), i found the plugins folder in %APPDATA%

still, placing the dll there didn't help. the plugin won't show up still!

A: Or another fix is to disconnect from your company intranet, connect to the internet via wifi or using your mobile phone usb tethering. Then try to install the plugin, it will work. It's because np++ domain is blocked by your network administrator

A: Finally! I figured out why thanks to this post here:
https://notepad-plus-plus.org/community/topic/17276/cannot-install-plugins-at-all/11
because my machine is company machine, it appears the proxy must be set

Do this in elevated mode (i.e. open notepad++ as administrator)
after that, from pluginAdmin,

install compare plugin, restarted notepad++, and wala! the plugin is showing up finally!!


text:
Q: How can I set Install4j variable from main class? I have a "Download File" action in the "Installer" step of Install4j. This action downloads a file and saves it to the installation directory. All of that works fine. However, the URL of the file to be downloaded is dependent upon user input. How can I set the URL to a variable (from my main class) that I can then use from within the download file action? I have only been able to find a way to get variables in the main class, but not set them. Any ideas?

A: Before your "Download file" action, add a "Set a variable" action. In the action's configuration change the "Script" to return the desired URL string:
// Get some user input from some screen's input field.
String userInput = (String)context.getVariable("sometextbox");

// Call your custom code with user input and return a url
String url = com.mycompany.getDownloadFileUrl(userInput);

// Set it to the runtime variable.
return url;

Set the "Variable" property to a recognizable name.
Then, go back to your "Download file" action and click the arrow that appears if you click within the entry field for "URL".
Click insert runtime variable -> Bound variables and click the variable you created in the earlier step.


text:
Q: Clean up unmentioned intermediate files in Make I have a Makefile that builds a shapefile as an intermediate steps.
.INTERMEDIATE : senate_boundaries.shp
senate_boundaries.shp : Senate\ shape\ files.zip
     unzip -j "$<"

A full shapefile comes with more than just a .shp, but also a .prj file, a .dbf file, and a bunch of others. These files are created when "Senate shape files.zip" is unzipped.
These other files are never an explicit target or dependency.
.INTERMEDIATE : senate_boundaries.prj senate_boundaries.dbf

does not seem to do anything.
How can I tell Make to clean up these other files?

A: You can add something like this to your recipe:
rm -f $(wildcard Senate\shape\*.prj)

But that will only work for that one file and you would have to manually add each extension to get rid of.
so something like this might do the trick:
rm -f $(shell ls Senate\shape\ | grep -v .shp&)

Another option is to unzip into a temp directory and then copy the file you want out and remove the the temp directory.


text:
Q: How to make queries from multiple models in a single view I am working on a school placement system and I have multiple models to query from. First I want to loop through the students' list and check if the two student's ID in the profile and result model match. Then I will check if the student has passed and then place the student.
I am using Django 2.2.1. I did a lot of search but to no avail. Below are some of my codes.
Here is my student model.
class StudentProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    # Extra Fields
    student_ID = models.CharField(max_length=10)
    middle_Name = models.CharField(max_length=50, blank=True)
    gender = models.CharField(max_length=10, choices=STUDENT_GENDER_CHOICES)
    disability = models.CharField(max_length=5, choices=STUDENT_DISABILITY_CHOICES)
    locality = models.CharField(max_length=30, choices=STUDENT_LOCALITY_CHOICES)
    age = models.PositiveIntegerField()
    profile_picture = models.ImageField(upload_to='profile_photos', blank=True, default='profile_photos/default.svg')

    def __str__(self):
        return self.user.username

This is my result upload model
class StudentResultsUpload(models.Model):
    student_ID = models.CharField(max_length=10)
    english = models.PositiveIntegerField()
    mathematics = models.PositiveIntegerField()
    integrated_Science = models.PositiveIntegerField()
    social_Studies = models.PositiveIntegerField()
    basic_Design_Technology = models.PositiveIntegerField()
    home_Economics = models.PositiveIntegerField()
    ghanaian_Language = models.PositiveIntegerField()
    french = models.PositiveIntegerField(blank=True)

This is my school selection model.
NB: I removed the multiple school models and put everything in one model.
class SchoolSelection(models.Model):
    student = models.ForeignKey(User, on_delete=models.CASCADE)

    school_One = models.CharField(max_length=100)
    program_One = models.CharField(max_length=50)
    residential_Status_One = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Two = models.CharField(max_length=100)
    program_Two = models.CharField(max_length=50)
    residential_Status_Two = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Three = models.CharField(max_length=100)
    program_Three = models.CharField(max_length=50)
    residential_Status_Three = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Four = models.CharField(max_length=100)
    program_Four = models.CharField(max_length=50)
    residential_Status_Four = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Five = models.CharField(max_length=100)
    program_Five = models.CharField(max_length=50)
    residential_Status_Five = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

And this is my views.py for placement.
def placement(request):
    profile = StudentProfile.objects.all()
    place = StudentResultsUpload.objects.all()
    schools = SchoolSelection.objects.all()

    placements = []
    for candidate in profile:
        for pl in place:

            if candidate.student_ID == pl.student_ID:
                if (pl.english >= 50 and pl.mathematics >= 50 and pl.integrated_Science >= 50 and pl.social_Studies >= 50):

                    raw_score = (pl.english + pl.mathematics + pl.integrated_Science + pl.social_Studies + pl.basic_Design_Technology + pl.home_Economics)
                    for school in schools:
                        if raw_score >= 480:
                            place_me = school.school_One
                        elif raw_score >= 420:
                            place_me = school.school_Two
                        elif raw_score >= 360:
                            place_me = school.school_Three
                        elif raw_score >= 300:
                            place_me = school.school_Four
                        else:
                            place_me = school.school_Five

                        placements.append({'student': candidate, 'school': place_me})
                    return render(request, 'schools/placement.html', {'place_me': placements})

                else:
                    return HttpResponse("Sorry, you did not qualify for placement.")

Here is my placement.html file

    Placement Here.

{% for placement in place_me %}
    Stdudent ID: {{ placement.student.student_ID }}

    Stdudent username: {{ placement.student.user }}

    Stdudent gender: {{ placement.student.gender }}

    School: {{ placement.school }}

{% endfor %}

But when I run it, it is not iterating properly through all the students in the system. It is only retaining multiple instances of one student but it will pick the schools of other students and display for the one student that it is returning its multiple instances.

A: As Daniel Roseman indicated you should use Foreign Keys to associate different models. A refactoring of your code should be something like the codes below.
The StudentResultsUpload model
class StudentResultsUpload(models.Model):
    student = models.ForeignKey(StudentProfile, on_delete=models.CASCADE, null=True)
    english = models.PositiveIntegerField()
    mathematics = models.PositiveIntegerField()
    integrated_Science = models.PositiveIntegerField()
    social_Studies = models.PositiveIntegerField()
    basic_Design_Technology = models.PositiveIntegerField()
    home_Economics = models.PositiveIntegerField()
    ghanaian_Language = models.PositiveIntegerField()
    french = models.PositiveIntegerField(blank=True)

The SchoolSelectionOne model
class SchoolSelectionOne(models.Model):
    student = models.ForeignKey(StudentProfile, on_delete=models.CASCADE, null=True)
    name_of_School = models.CharField(max_length=100)
    program = models.CharField(max_length=50)
    residential_Status = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES

The placement function
def placement(request):
    profiles = StudentProfile.objects.all()
    uploads = StudentResultsUpload.objects.all()
    school_one = SchoolSelectionOne.objects.all()
    school_two = SchoolSelectionTwo.objects.all()
    school_three = SchoolSelectionThree.objects.all()
    school_four = SchoolSelectionFour.objects.all()
    school_five = SchoolSelectionFive.objects.all()

    profile_dicts = []
    for profile in profiles:
        try:
            upload = [u for u in uploads if u.student.pk == profile.pk][0]
            one = [s for s in school_one if s.student.pk == profile.pk][0]
            two = [s for s in school_two if s.student.pk == profile.pk][0]
            three = [s for s in school_three if s.student.pk == profile.pk][0]
            four = [s for s in school_four if s.student.pk == profile.pk][0]
            five = [s for s in school_five if s.student.pk == profile.pk][0]
        except (AttributeError, IndexError):
            continue

        profile_dicts.append({
            'upload': upload,
            'school_one': one,
            'school_two': two,
            'school_three': three,
            'school_four': four,
            'school_five': five
        })

    place_me_list = []
    for profile in profile_dicts:
        upload = profile['upload']

        if (
                upload.english >= 50 and
                upload.mathematics >= 50 and
                upload.integrated_Science >= 50 and
                upload.social_Studies >= 50
        ):
            raw_score = (
                upload.english +
                upload.mathematics +
                upload.integrated_Science +
                upload.social_Studies +
                upload.basic_Design_Technology +
                upload.home_Economics
            )

            if raw_score >= 480:
                place_me = profile['school_one']
            elif raw_score >= 420:
                place_me = profile['school_two']
            elif raw_score >= 360:
                place_me = profile['school_three']
            elif raw_score >= 300:
                place_me = profile['school_four']
            else:
                place_me = profile['school_five']

            place_me_list.append(place_me)

    return render(request, 'schools/placements.html', {'place_me': place_me_list})

In placement function to avoid using the nested for I firstly found the desired information for each candidate (supposing that each one is associated with schools and upload models) and then I made the calculations.

A: On these two lines
for candidate in profile:
    if profile.student_ID == place.student_ID:

you are indicating you want to use candidate as the variable name inside the loop, so the second line should probably read if candidate.student_ID instead of if profile.student_ID.

A: place is a queryset. so must be iterate it.
try this code:
def placement(request):
    profile = StudentProfile.objects.all()
    place = StudentResultsUpload.objects.all()
    school_one = SchoolSelectionOne.objects.all()
    school_two = SchoolSelectionTwo.objects.all()
    school_three = SchoolSelectionThree.objects.all()
    school_four = SchoolSelectionFour.objects.all()
    school_five = SchoolSelectionFive.objects.all()

    placements = []
    for candidate in profile:
        for pl in place:
            if candidate.student_ID == pl.student_ID:
                if (pl.english >= 50 and pl.mathematics >= 50 and pl.integrated_Science >= 50 and pl.social_Studies >= 50):
                    raw_score = (pl.english + pl.mathematics + pl.integrated_Science + pl.social_Studies + pl.basic_Design_Technology + pl.home_Economics)

                    if raw_score >= 480:
                        place_me = school_one
                    elif raw_score >= 420:
                        place_me = school_two
                    elif raw_score >= 360:
                        place_me = school_three
                    elif raw_score >= 300:
                        place_me = school_four
                    else:
                        place_me = school_five

                    placements.append({'student': candidate, 'school': place_me})
    return render(request, 'schools/placement.html', {'place_me': placements})

placement.html:

        Placement Here.

    {% for placement in place_me %}
        Stdudent Id: {{ placement.student.student_ID }}
        Stdudent middle name: {{ placement.student.middle_Name }}
        Stdudent gender: {{ placement.student.gender }}

        Placements:
            {% for school in placement.school %}
                {{ school }}
            {% endfor %}
    {% endfor %}


text:
Q: Undertstanding NTOP Mail_POP bandwidth data I'm having some trouble understanding the output of Ntop.
I'm receiving high bandwidth warnings for one my (debian) servers from my network provider. Because the server runs only a few low traffic sites, and I couldn't find anything being too busy, I have installed NTOP.
In Ntop I can see there is some weird traffic going on but it is hard too understand.

*

*On trafficStats -> application protocols, I have a high 10gb of Mail_POP traffic. I don't use POP on the server though. Only HTTPS/HTTP and SSH are open.

*On trafficStats -> eth0 report, I find this 10gb under "non-ip traffic", with only 1gb ip traffic.

*On hosts -> traffic, Only the server itself has a little traffic 1.5 gb but the 10gb Mail_POP traffic does not show anywhere.

*Ntop uptime is 6 days but the server itself is first seen yesterday.
Can anyone help to understand these readings? What is Mail_POP What could be causing the high traffic spikes? Do I need to provide more information?

A: Your "huge amounts of Mail_POP traffic" issue is probably related to a bug the existed in some old (circa early-2012) releases of ntop. It was mistakenly categorising HTTPS traffic as POP.
There's a discussion that touches on it here..

Moreover, port 443 is mapped to POP rather than HTTPS..

And some mention of it here too..

.. there was a report back in March of HTTPS traffic being classified as mail_POP.

Can't shed any light on your other issues but my experience with ntop so far indicates it can generally be a bit flaky.


text:
Q: How to check that all functions have a test case? Is there a standard method to check if all functions of all files that are included in a test have a testcase? So if I have script_1.py, script_2.py and script_3.py with corresponding test_script_1.py, test_script_2.py and test_script_3.py, how can I check that every function in script_x.py gets called at least ones by the test scripts?
I wrote the test functions in the format def test<Name_of_function>_<test_condition> so for example the function def sum(a, b) has test functions def testSum_valid_input and def testSum_invalid_input, so I could write a script that gets all the function names from the test scripts and compare that to the functions in the tested scripts, but I am hoping that there is already an easy way to do this.

A: The best way is probably to use a coverage tool. It will tell you how much of your code is called at least one time by a test.


text:
Q: Angular: how to create Form Controls from an array of objects I can't seem to find a solution for this.
I have an array objects, lets say:
productInformation = {
   [
     {labelid: 1, labelname: 'weight', value: 1},
     {labelid: 2, labelname: 'height', value: 5},
     {labelid: 3, labelname: 'width', value: 10},
     {labelid: 4, labelname: 'depth', value: 2}
   ]
}

The objects will not always be predictable.  Sometimes it'll have a only two objects, sometimes all of them, sometimes it'll have others, such as for color, condition, etc.
How can I create form controls with just the array of objects, where the admin can edit the values for each property (except for the id)?  For example, the admin might want to update how much something weighs.
Each time I view a product's details, it will fetch an array of objects, as shown above.
Thank you.

A: Use addControl
  createGroup(productInformation:any[]):FormGroup{
    const form=new FormGroup({})
    productInformation.forEach(x=>{
       form.addControl(x.labelname,new FormControl(x.value))
    })
    return form
  }

//you use
this.form=this.createGroup(this.productInformation)

To manange in .html you should create a function that return a formControl
  getControl(key:string)
  {
    return this.form.get(key) as FormControl
  }

And use in html
<form [formGroup]="form">
  <div *ngFor="let keyvalue of form.controls | keyvalue;let i=index">
    {{ productInformation[i].labelname }}
    <input [formControl]="getControl(productInformation[i].labelname)" />
  </div>
</form>

NOTE: you defined wrong the productInformation  (remove the { }
See a stacktblitz

A: Something like this should work:
product: FormGroup;

constructor(private fb: FormBuilder) {
 this.product.addControl('productInformation', new FormArray([]));
}

setInformation(productInformation){
  const options = this.product.get('productInformation') as FormArray;
  for(let {labelid, labelname, value} of productInformation){
    options.push(this.fb.group({ labelid, labelname, value } as any));
  }
}

You can set labelid without using an input by setValue or patchValue.


text:
Q: Is there any more simple way to get all months and years list between two dates then mine I want to get all months and year in turn in an array between two dates. I want the output like this format: Y-m
I done it. But, I just want to know is there any simple way to get the same result.
There is my code:
public function __construct()
{
    $this->params['start-date'] = date('Y-m-d', strtotime("01-01-2016"));
    $this->params['end-date'] = date('Y-m-d', time());
}

/**
 * @return array
 */
private function _getAllMonths()
{
    $start  = date_parse($this->params["start-date"]);
    $end  = date_parse($this->params["end-date"]);

    $output[] = ['month' => $start["year"]."-0".$start["month"]];
    //loop years
    for($i=(int)$start["year"];$i<=(int)$end["year"];$i++)
    {
        //control months and start year
        $k = $i == $start["year"] ? (int)$start["month"] + 1 : 1;
        //loop months
        for($j=$k;$j<13;$j++)
        {
            if($i==$end["year"] && $j==$end["month"])
                break;
            $output[] = ["month" => $i."-".str_pad($j, 2, "0", STR_PAD_LEFT)];
        }
    }
    return $output;
}

Please explain me how?

A: How about this to get you started
$start = new \DateTime('now');
$end = new \DateTime('now + 3 years');
$interval = new \DateInterval('P1M');
$period = new \DatePeriod($start, $interval, $end);

foreach($period as $date) {
    echo $date->format('Y-m-d H:i:s') . "\n";
}

Not a huge step to adapt it to your needs
PHP Manual Pages

*

*DateTime

*DateInterval

*DatePeriod
If you're doing a lot with dates I recommend a library called Carbon


text:
Q: How to determine mysql.connector cursor type? What is happening in this python code?
If I execute as shown, it prints "MySQLCursor".
If I comment-out "import hashlib", it prints "CMySQLCursor".
I have some code that imports hashlib and some that does not, but I want to consistently detect the cursor type correctly.
What does the "C" mean and what is its origin?
These are the possible cursor types (with or with the C prefix depending on existence of hashlib):

*

*CMySQLCursor

*CMySQLCursorBuffered

*CMySQLCursorRaw

*CMySQLCursorBufferedRaw

*CMySQLCursorDict

*CMySQLCursorBufferedDict

*CMySQLCursorNamedTuple

*CMySQLCursorBufferedNamedTuple

*CMySQLCursorPrepared

import hashlib
import mysql.connector

db = mysql.connector.connect(user='myuser', password='mypass', host='myhost', database='myschema')
cursor = db.cursor()

print (type(cursor).__name__)


text:
Q: How do I prevent the user from clicking a button too often? In a button-click event, I am sending a command to a server. I don't want the server to be flooded with requests, so I want to prevent the user from clicking the button too often.
I've thought about counting how many times the button is clicked, like this:
button.tag := button.tag + 1;
if button.Tag = 5 then
  exit;

But this will not help because I have to set the tag to 0 each time I need to detect the fast clicks, and this will also not help because it will detect the tag number every 5 clicks, whereas I just need to know if the button was clicked repeatedly.
How do I detect fast button clicks without using the button tag?

A: If you want to restrict how often to send commands from your client to the server, disable the button a short while after each click. This will give the user feedback that something is processing. I'm assuming there is no way the server can give feedback when it is ready.
procedure TForm1.Button1Click(Sender: TObject);
begin
  Button1.Enabled := false;
  Timer1.Interval := 500;  // Pick a suitable interval
  Timer1.Enabled := true;
  SendCommand(); // Make call to server
end;

procedure TForm1.Timer1Timer(Sender: TObject);
// Timer1 is disabled at startup
begin
  Button1.Enabled := true;
  Timer1.Enabled := false;
end;

Note: if you are trying to do some load balancing on the server, there must be a way for the clients to know how to restrict the calls. But this is all a backwards way of doing it, the server should be capable of handling this without any restrictions on the clients.

A: You've correctly recognized that merely counting the clicks won't be sufficient. You need to account for the time, too. So use a timer.
When the button is clicked, disable the button and enable a timer. When the timer fires, re-enable the button.
procedure TExampleForm.SendButtonClick(Sender: TObject);
begin
  Assert(SendButton = Sender);
  SendButton.Enabled := False;
  SendButtonTimer.Enabled := True;
  SendCommandToServer(...);
end;

procedure TExampleForm.SendButtonTimerTimer(Sender: TObject);
begin
  Assert(SendButtonTimer = Sender);
  SendButtonTimer.Enabled := False;
  SendButton.Enabled := True;
end;

Set the timer's Interval property to the number of milliseconds that you want the button to remain disabled.
There's no need to count the clicks in this scenario because the implicit limit is one click per timer interval.

A: You could just put some kind of timestamp into the Tag, and check whether enough time has elapsed.
Better yet, derive your own class, (TDontPressMeTooFastButton ;-), and you can do whatever you want, ie.:

*

*track both how much time elapsed since last click and how many "fast clicks" the user attempted

*you could make the button contain the timer component, not leaking this implementation detail into the form
Just about anything, in a much cleaner way than using the .Tag or global/form variables ...


text:
Q: Best practice for only getting parts of the store/state in React component using redux I implemented by using redux thunk that if one component is mounted, that the store is filled by calling an API.
The data which are requested have much more fields than I need in particalur components. So could you please give me a tip what  the best practice would be to get only parts of the data. Because storing a reduced version of the data also (kind of duplication) wouldn't be a good practice, would it?

A: If I understood the question correctly, you can use the selectors

A: You can deconstruct data.
For example, when you connect your component to the redux state.
const mapStateToProps = state => {
    relevantPartOfTheState: state.some.part.of.the.state
}

This is essentially what selectors do.

The data which are requested have much more fields than I need in particalur components

You are not required to save all of it. You can have something like this.
switch (action.type) {
    case RECEIVE_USELESS_DATA:
        return action.payload.onlyRelevantData
}

A: You can either use selectors as mentioned above or somethine like that:
const mapStateToProps = state => {
    relevantPartOfTheState: fetchSliceOfReducer(state)
}

The fetchSliceOfReducer(state) can be a function from inside the reducer file where you take only part of the state. Obviously you have to import the function in your component file and it can be reused for other components. So if your state is something like that
state = {
 value: true,
 name:"Michael"
}

your function would be const fetchSliceOfReducer = state => state.value
Selectors would be more appropriate for a growing app, where as the example above is nice and neat for something smaller


text:
Q: Cmake include path for system and program files I'm wondering if there is a possibility to configure cmake, that it's possible to make a difference if headerfiles are included with #include<...> or #include "..."?
Lets assume that I have a project like this:
src
   foo.h
   foo.c
lib
   foo.h
   foo.c

How can be achieved to add the file src/foo.h by writting #include "foo.h" and if the headerfile is included with #include <foo.h> the file at location lib/foo.h is loaded?
It always load the files from the first include_directories() command
include_directories(src)
include_directories(lib)

EDIT
My current problem inside my project:
I have a file named string.h. Which contains some function for custom text handling. Now I have the problem that if I write #include <string.h> my custom file is loaded, but I expect the system file string.h. I don't want to rename my custom file nor I want to move it inside a folder to include it like #include "custum/string.h"
All I want is:
#include <string.h> // load file from system library
#include "string.h" // load my custom file

I used it inside IDE Keil like this ways, but I don't know if it can be done with cmake

A: Change include order
include_directories(lib)
include_directories(src)

You will need to place your whole code in the src. In this case #include "foo.h" starts search files in the same directory where current file is parsed. #include <foo.h>" starts search in include directories in the order of include_directories.
BTW it is a bad practice to do such things. Your files should be searched first and then lib files. Better way is to do like
include_directories(src)
include_directories(parent_of_lib)

Use #include "foo.h" or #include <foo.h> for your own included files and #include <lib/foo.h> for third-party included files.


text:
Q: how do I get a list of the videos of the Itunes media library on IOS? i want to get a list of all Videos which are in the itunes library, how i get the access to them?
later I want to play them eventually, but not in fullscreen.
i hope you can help me.

A: MPMediaPropertyPredicate *predicate = [MPMediaPropertyPredicate predicateWithValue:@(MPMediaTypeAnyVideo) forProperty:MPMediaItemPropertyMediaType];
MPMediaQuery *movieQuery = [[MPMediaQuery alloc] init];
[movieQuery addFilterPredicate:predicate];

NSArray *allVideos = [movieQuery items];


text:
Q: Will multiple @font-face formats slow download? I'm developing a website and using @font-face for typography (because the exact font required isn't available as a webfont). I used Font Squirrel's @font-face generator to create their recommended formats, which include different formats for maximum cross-browser compatibility, and used their sample CSS:
@font-face {
font-family: 'playfair_displayregular';
src: url('playfair-display-webfont.eot');
src: url('playfair-display-webfont.eot?#iefix') format('embedded-opentype'),
     url('playfair-display-webfont.woff') format('woff'),
     url('playfair-display-webfont.ttf') format('truetype'),
     url('playfair-display-webfont.svg#playfair_displayregular') format('svg');
font-weight: normal;
font-style: normal;

}

My question is, are browsers going to try and download all the different formats, or does each browser just load one for it to use?

A: Under certain circumstances, some browsers will download multiple formats of the same font-face.
A thorough explanation can be found at Bulletproof @font-face syntax, but the gist of it is that FontSquirrel is doing all the hard work for you and their syntax implements the the best syntax and prevents multiple resources from being downloaded.
The article is worth reading and also provides links to more information.


text:
Q: PHP, array manipulation to get keys with all same name I have this array posting to my controller:
Array
(
    [id] => Array
        (
            [0] => 95
            [1] => 69
        )
)

I want:
Array(

    [id] => 95
    [id] => 69
)

As I am using CodeIgniter's $this->db->delete() function and it takes the array key value as the column for the WHERE clause. I have this code at the moment:
foreach($ids as $k => $v){

    $formatIds['id'] = $v;

}

Which just gives me one of the rows and not the rest.
I then tried:
foreach($ids as $k => $v){

    $formatIds['id'][] = $v;

}

But this gives me a MultiDimensional array...

A: The answer to your question is "not possible": array keys must always be unique.
The answer to what you're trying to do is to use where_in():
$names = array(95,69);
$this->db->where_in('id', $names);
$this->db->delete('mytable');


text:
Q: Quantile g-computation I want to perform a time-to-event analysis using qgcomp package. I used qgcomp.cox.boot function and adjusted for confounding factors. However I have encountered some problems.
library("ggplot2")
data("metals", package="qgcomp")

Xnm <-c('arsenic','barium','cadmium','calcium','chromium','copper','iron','lead','magnesium','manganese','mercury','selenium','silver','sodium','zinc')

qc.survfit2 <- qgcomp.cox.boot(Surv(disease_time, disease_state) ~ arsenic+barium+cadmium+calcium+chromium+copper+iron+lead+magnesium+manganese+mercury+selenium+silver+sodium+zinc+ph,expnms=Xnm,data=metals[,c(Xnm, 'disease_time', 'disease_state')], q=4,B=5, MCsize=1000, parallel=TRUE, parplan=TRUE)         #ph is a confounding factor
Error in eval(predvars, data, env) : object 'ph' not found

Then I fixed the code as followed:
qc.survfit2 <- qgcomp.cox.boot(Surv(disease_time, disease_state) ~ arsenic+barium+cadmium+calcium+chromium+copper+iron+lead+magnesium+manganese+mercury+selenium+silver+sodium+zinc+metals$ph,expnms=Xnm,data=metals[,c(Xnm, 'disease_time', 'disease_state')], q=4,B=5, MCsize=1000, parallel=TRUE, parplan=TRUE)

Error in model.frame.default(data = list(id__ = c(2L, 2L, 3L, 3L, 3L,  :
variable lengths differ ('metals$ph')

Can anyone solve this problem? Thanks a lot.
I have googled this quite a lot, however they didn't solve my problem. In the linear model, I can adjust for confounding factors by inputting the variable name directly. However, it did not work in the time-to-event analysis with qgcomp.cox.boot function.

A: Your problem is that you're including ph in your model, but subsetting metals to not include ph. I can see that in the vignette you linked, they do sometimes subset metals, but this is only a matter of convenience to use y~. notation, it's not necessary. So you can either leave metals as is:
library(survival)
library(qgcomp)
data(metals)

Xnm <-c('arsenic','barium','cadmium','calcium','chromium','copper','iron','lead','magnesium','manganese','mercury','selenium','silver','sodium','zinc')

qc.survfit2 <- qgcomp.cox.boot(
  Surv(disease_time, disease_state) ~ arsenic+barium+cadmium+calcium+chromium+copper+iron+lead+magnesium+manganese+mercury+selenium+silver+sodium+zinc+ph,
  expnms=Xnm,
  data=metals,
  q=4,
  B=5,
  MCsize=1000,
  parallel=TRUE,
  parplan=TRUE
)

Or, if you want to use y~. notation, make sure to include ph in your subset:
qc.survfit2 <- qgcomp.cox.boot(
  Surv(disease_time, disease_state) ~ .,
  expnms=Xnm,
  data=metals[,c(Xnm, 'ph', 'disease_time', 'disease_state')],
  q=4,
  B=5,
  MCsize=1000,
  parallel=TRUE,
  parplan=TRUE
)


text:
Q: XDocReport: generated docx document error "Word experienced an error trying to open the file" I am trying to generate a report in .docx format that contains a table in it using XDocReport and freemarker.
I am using a list to print the data inside the table.

The problem is there is no error in java while generating the document, but the generated document cannot be open. The error said
Word experienced an error trying to open the file.

I was expecting the output to be like this:

I am using XDocReport 2.0.2 with Office 2016. Any help is appreciated. Thank You.

A: I guess (without knowing XDocReport) that [#list p.cities ...] should be prefixed with @before-row too. Otherwise when you iterate for the cities, the start-tags of the table row will not be repeated, only the end-tags.

A: So, after a few days of workaround and help from my friend, this issue was finally solved. so here is a change that I made
I added the @before-row tag before [#list p.cities as c] and with only a single @after-row tag. Now, the generated document can be open

A: Right Click on the File. Instead of clicking on "Open" click on "Edit"
That's it, simple.


text:
Q: Worklight 6.2 - Issues with logging I've seen a couple of issues with Worklight 6.2 studio around logging.

*

*If you change the logging config, an extra  line gets added to the server.xml at eclipse startup.

*The dev server doesn't seem to pay attention to the log size limit.

To repro #1

*

*Change your logging configuration.  We set our log level to INFO and upped the size to 400.  This results in the following line in the server.xml file:

<logging consoleLogLevel="INFO" copySystemStreams="false" maxFileSize="400"/>

*

*Shut down and restart eclipse.  As part of the startup process, it adds a 2nd logging line to the end of the server.xml file

<logging consoleLogLevel="AUDIT" copySystemStreams="false"/>
Since this line comes later in the file, it takes precedence over the first line for the server.  For the GUI, it displays the contents of the first line.
For #2, it straight up looks like if you change the maxFileSize option on the logging line, the server just doesn't pay attention to it, and still wraps at the default (20, I believe).  I've made sure there aren't 2 logging lines in the server.xml, restarted the server, etc.
If there is any additional info I can provide to help track these down, please let me know.

A: Concerning the point 2 it is normal, it is a restriction of Liberty Profile: maxFiles and maxFileSize don't apply to the console.log file.
See http://www-01.ibm.com/support/knowledgecenter/SSD28V_8.5.5/com.ibm.websphere.wlp.nd.doc/ae/rwlp_logging.html

A: This appears to be a known defect.
If you are an IBM customer or business partner and require a fix for this issue, you can open a PMR  support ticket and request a Worklight 6.2 iFix to be produced and delivered to you.


text:
Q: How correctly connect to Oracle 12g database in Play Framework? I am new in Play Framework (Scala) and need some advise.
I use Scala 2.12 and Play Framework 2.6.20. I need to use several databases in my project. Right now I connected MySQL database as it says in documentation. How correctly connect project to remote Oracle 12g database?
application.conf:
db {
  mysql.driver = com.mysql.cj.jdbc.Driver
  mysql.url = "jdbc:mysql://host:port/database?characterEncoding=UTF-8"
  mysql.username = "username"
  mysql.password = "password"
}

First of all to lib folder I put ojdbc8.jar file from oracle website.
Then add libraryDependencies += "com.oracle" % "ojdbc8" % "12.1.0.1" code to sbt.build file. Finally I wrote settings to aplication.conf file.
After that step I notice error in terminal:
[error] (*:update) sbt.ResolveException: unresolved dependency: com.oracle#ojdbc8;12.1.0.1: not found
[error] Total time: 6 s, completed 10.11.2018 16:48:30
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=256M; support was removed in 8.0

EDIT:
application.conf:
db {
  mysql.driver = com.mysql.cj.jdbc.Driver
  mysql.url = "jdbc:mysql://@host:@port/@database?characterEncoding=UTF-8"
  mysql.username = "@username"
  mysql.password = "@password"

  oracle.driver = oracle.jdbc.driver.OracleDriver
  oracle.url = "jdbc:oracle:thin:@host:@port/@sid"
  oracle.username = "@username"
  oracle.password = "@password"
}

ERROR:
play.api.UnexpectedException: Unexpected exception[CreationException: Unable to create injector, see the following errors:

1) No implementation for play.api.db.Database was bound.
  while locating play.api.db.Database
    for the 1st parameter of controllers.GetMarkersController.<init>(GetMarkersController.scala:14)
  while locating controllers.GetMarkersController
    for the 7th parameter of router.Routes.<init>(Routes.scala:45)
  at play.api.inject.RoutesProvider$.bindingsFromConfiguration(BuiltinModule.scala:121):
Binding(class router.Routes to self) (via modules: com.google.inject.util.Modules$OverrideModule -> play.api.inject.guice.GuiceableModuleConversions$$anon$1)

GetMarkersController.scala:
package controllers

import javax.inject._

import akka.actor.ActorSystem
import play.api.Configuration
import play.api.mvc.{AbstractController, ControllerComponents}
import play.api.libs.ws._
import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future, Promise}
import services._
import play.api.db.Database

class GetMarkersController @Inject()(db: Database, conf: Configuration, ws: WSClient, cc: ControllerComponents, actorSystem: ActorSystem)(implicit exec: ExecutionContext) extends AbstractController(cc) {
    def getMarkersValues(start_date: String, end_date: String) = Action.async {
        getValues(1.second, start_date: String, end_date: String).map {
            message => Ok(message)
        }
    }

    private def getValues(delayTime: FiniteDuration, start_date: String, end_date: String): Future[String] = {
        val promise: Promise[String] = Promise[String]()
        val service: GetMarkersService = new GetMarkersService(db)
        actorSystem.scheduler.scheduleOnce(delayTime) {
            promise.success(service.get_markers(start_date, end_date))
        }(actorSystem.dispatcher)
        promise.future
    }
}

A: You cannot access Oracle without credentials. You need to have an account with Oracle. Then add something like the following to your build.sbt file
resolvers += "Oracle" at "https://maven.oracle.com"

credentials += Credentials("Oracle", "maven.oracle.com", "username", "password")

More information about accessing the OTN: https://docs.oracle.com/middleware/1213/core/MAVEN/config_maven_repo.htm#MAVEN9012
If you have the hard coded jar, you don't need to include as a dependency. See unmanagedDependencies https://www.scala-sbt.org/1.x/docs/Library-Dependencies.html


text:
Q: My API URL Have backslashes (\x01\x02) causing apache 400 error. How to remove those backslashes from the url I am managing an application that gets requests through API. Some of the requests are having invalid characters.
The Request URL/API looks like:
/up/100.php?f=0&t=n\x01\x02&...

These \x01\x02 causing Apache2 to throw 400 errors.
I can't change/alter the URL. I need to fix my apache to accept and process that URL. I tried mod_rewrite but couldn't found the correct one.
Any Help?
Update and Solution
Now, I found that the request is really a malfunctioned URL. So, what I did to solve the problem? I've created a custom error handling page to sanitize the URL and make it work.

A: Try the following at the top of your .htaccess file:
RewriteEngine On
RewriteCond %{QUERY_STRING} (.*)\\x01\\x02(.*)
RewriteRule ^up\.php$ /$0?%1%2 [R,L]

The double backslash in the CondPattern is necessary to match a single backslash in the query string, since the backslash is used as the escape character in PCRE regex.
The %1 and %2 backreferences match the characters either side of the sequence you want to remove. $0 is just a backreference to the matched URL-path (saves repetition).
HOWEVER, a request of the form /up.php?f=0&t=n\x01\x02&... would not ordinarily trigger a 400 response. The character sequence \x01\x02 in the URL is just a literal character sequence: \, x, 0, 1, etc. (it's not an encoded character in this context).
So, if you are getting a 400 response, it's possible that something else (a mod_security rule perhaps?) is triggering this response - which maybe out of your control?


text:
Q: RE match and searching in python I am using python to scrape data from a text file now when i use
re.match('some pattern',source_string)

i get nothing in return but when i use
re.search('some pattern',source_string)

it returns this
[<_sre.SRE_Match object at 0x25ae238>]
Now this is my problem how do i get to make the string searched that occurs in the file to be returned and what is that gibberish output that i get..please help me

A: That is fine, it returns a match object. To get the string, just get the 0th group:
a = re.search('some pattern',source_string)
print a.group(0)

re.match will try to match the string from the start against your regex whereas re.search will search for the specified regex in the string. You should use re.search in this case.


text:
Q: Why does my UITextView not resize when there is a '\n' character using this function, whenever I have a '\n' character in the text of my UITextView, it doesn't resize text size properly to fit the specified frame size, but when i remove the '\n' character, it works perfect does anyone know why?
extension UITextView{
open override func didMoveToSuperview() {
    var defaultFontSize = CGFloat(44.0)
    self.font = UIFont(name: (self.font?.fontName)!, size: defaultFontSize)
    if (self.contentSize.height > self.frame.size.height) {
        var fontIncrement = CGFloat(1.0)
        while (self.contentSize.height > self.frame.size.height) {
            print(defaultFontSize - fontIncrement)
            self.font = UIFont(name: (self.font?.fontName)!, size: defaultFontSize - fontIncrement)
            fontIncrement += 1.0
        }
    }

 }
}


text:
Q: If a beam of light follows the path $y(x)=y_0\sin(x/y_0)$, what is the index of refraction? An exam question that showed up while I was studying:

A plane wave refracts and follows a ray given by the equation $y=y_0\sin(x/y_0)$ where $y_0$ is a constant. Find the refractive index $n(y)$ and plot it.

I believe I've made a mistake in my calculation.
The wave propagates in the $x$-direction. So we are told the trajectory -- that's simple enough. Let us divide the material into thin sheets of height $dy$. If we zoom in on the path enough, we can use Snell's law to approximate the difference in the angle (between the sheets.) We get that
$$ n(y)\sin(\theta)=n(y+dy)\sin(\theta + d\theta).$$
To be clear, $\theta$ is measured from the $y$-axis. (So $dx/dy=\tan(\theta)$.) We can expand to first order to get that
$$ n(y)\sin(\theta)=n(y)\sin(\theta) + n(y)\cos(\theta)d\theta + n'(y)\sin(\theta)dy $$ whereupon we get (using the chain-rule backwards)
$$-n(\theta)\cos(\theta)=\frac{dn}{d\theta}\sin(\theta)$$
where $n(y)$ has been written $n(\theta).$ (There is no difference.) Now we can separate variables. The equation
$$\frac{dn}{n}=-\frac{d\theta}{\tan(\theta)}$$
yields
$$n(\theta)=\frac{1}{\sin(\theta)}.$$
Now the issue is when I go through the trig identities, that is, replacing $\tan(\theta)$ with $dx/dy$, I get that
$$\tan(\theta)=\frac{1}{\sqrt{1-(y/y_0)^2}}$$ which implies $n(y)=y/y_0.$ I have no idea if this is the right behavior. There is no divergence in $n(y)$ like I imagined there would be and strangely it seems to flip the sign with $y$. But $n(y)$ can never be negative to I am at a loss here.
Edit: I believe the integral should be $$n(\theta)=\frac{1}{|\sin(\theta)|}$$ which takes care of the sign issue.


text:
Q: Log4J file not printing log data In my Selenium framework i am implementing Log4J library to print test execution log but application.log file is not printing any log. could someone please help me to see why or what's wrong i am doing:
I am doing following:
1) I added 1.2.17 log4J dependency to my pom.xml file
2) Added log4j.properties file to "C:\XXX\IdeaProjects\XXX\AG_CEP_Regression_Testing\src\main\resources\log4j.properties
When I execute the script it generates log file but doesn't print the log data but instead, I see following having printed
2019-10-10 11:07:38,039 DEBUG [main] cache:45 - Couldn't find template in cache for "Extent.ftl"("en_GB", UTF-8, parsed); will try to load it.
2019-10-10 11:07:38,042 DEBUG [main] cache:45 - TemplateLoader.findTemplateSource("Extent_en_GB.ftl"): Not found
2019-10-10 11:07:38,043 DEBUG [main] cache:45 - TemplateLoader.findTemplateSource("Extent_en.ftl"): Not found
2019-10-10 11:07:38,044 DEBUG [main] cache:45 - TemplateLoader.findTemplateSource("Extent.ftl"): Found
2019-10-10 11:07:38,045 DEBUG [main] cache:45 - Loading template for "Extent.ftl"("en_GB", UTF-8, parsed) from "jar:file:/C:/XXX/.m2/repository/com/relevantcodes/extentreports/2.41.2/extentreports-2.41.2.jar!/com/relevantcodes/extentreports/view/Extent.ftl"
2019-10-10 11:07:38,314 DEBUG [main] cache:45 - Couldn't find template in cache for "Extent.ftl"("en_GB", UTF-8, parsed); will try to load it.
2019-10-10 11:07:38,315 DEBUG [main] cache:45 - TemplateLoader.findTemplateSource("Extent_en_GB.ftl"): Not found
2019-10-10 11:07:38,315 DEBUG [main] cache:45 - TemplateLoader.findTemplateSource("Extent_en.ftl"): Not found
2019-10-10 11:07:38,315 DEBUG [main] cache:45 - TemplateLoader.findTemplateSource("Extent.ftl"): Found
2019-10-10 11:07:38,316 DEBUG [main] cache:45 - Loading template for "Extent.ftl"("en_GB", UTF-8, parsed) from "jar:file:/C:/XXX/.m2/repository/com/relevantcodes/extentreports/2.41.2/extentreports-2.41.2.jar!/com/relevantcodes/extentreports/view/Extent.ftl"

Here are my log4J.properties file contents:
log4j.rootCategory=debug, console, file
#log4j.logger.freemarker.cache = DEBUG, file, stdout
# Appender which writes to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{MM-dd-yyyy HH:mm:ss} %F %-5p [%t] %c{2} %L - %m%n

# Appender which writes to a file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=application.log

# Defining maximum size of a log file
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ISO8601} %5p [%t] %c{1}:%L - %m%n
log4j.appender.file.Append=true

This is the last bit of work that I need to incorporate into my framework so any help would highly be appreciated.

A: I have tested your configuration and here is my advice (since I managed to make it work on my side):

*

*Fix your properties file since here log4j.rootCategory=debug, console, file you refer to console appender but here log4j.appender.stdout=org.apache.log4j.ConsoleAppender you define stdout appender. So that the line would look like log4j.rootCategory=debug, stdout, file

*Make sure you import porper Logger class where you log your messages. Check that you are using import org.apache.log4j.Logger; but not import java.util.logging.Logger; or whatever else.

*Make sure there are no other log4j configuration files in class path

This is my test code (assuming the property file has been fixed):
import java.util.logging.Logger;

public class TestLogging {

    static final Logger log = Logger.getLogger(TestLogging.class.getName());

    public static void main(String[] args) {
        log.info("Test");
    }

}

Here is console output:
10-10-2019 14:22:29 TestLogging.java INFO  [main] TestLogging 8 - Test

And here is file output:
2019-10-10 14:22:29,447  INFO [main] TestLogging:8 - Test