text:
Q: SqlAlchemy AmbiguousForeign Keys Error - foreign key attribute is specified THIS IS NOT A DUPLICATE, PLEASE DONT DELETE
My problem is using 2 foreign keys from the same ref table and using back_populates in order to relate them. Docs and previous SO answers say to specify the foreign keys with the 'foreign_keys= ' attribute which is what I have. AND THIS WORKS WHEN REMOVING THE BACK_POPULATES attribute. However I need to be able to access the user schema when looking up the Connections table in one of my api endpoints:
class Connections(db.Model):
    __tablename__ = 'connections'

    id = db.Column(db.Integer, primary_key = True)
    followee_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable = False)
    follower_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable = False)

    followee = db.relationship('User', foreign_keys="Connections.followee_id")
    follower = db.relationship('User', foreign_keys="Connections.follower_id")
    messages = db.relationship('Messages', back_populates = 'connection', cascade = "all, delete")

class User(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key = True)
    name = db.Column(db.String(30), nullable = False)
    email = db.Column(db.String, nullable = False, unique = True)
    password = db.Column(db.String, nullable = False, unique = True)
    phonenumber = db.Column(db.String, nullable = False)
    age = db.Column(db.Date, nullable = False)
    is_admin = db.Column(db.Boolean, nullable = True, default = False)
    connection = db.relationship('Connections', back_populates = 'users', cascade = "all, delete")
    connection = db.relationship('Connections', back_populates = 'users', cascade = "all, delete")

If there's another way to set up the back relationship between Connections and User, please let me know. Any help would be greatly appreaciated however just to reiterate, I have tried the solutions on here that relate to relationships without backref or back_populates


text:
Q: How to use dynamic value of table column in the value of another column on INSERT I'm doing something like the below..
INSERT INTO example_table
            (start_time,
             start_time_type,
             end_time,
             end_time_type,
             duration)
SELECT IF(start_time_type = 'now'
           OR start_time < " . CURRENT_TIME . ", " . CURRENT_TIME . ",
       start_time),
       start_time_type,
       IF(list_in = 'store', 0, ( IF(end_time_type = 'duration',
                                  " . CURRENT_TIME . " + duration * 86400,
                                  end_time
                                  ) )),
       IF(list_in = 'store', '', 'duration'),
       IF(list_in = 'store', end_time - start_time / 86400, duration)
FROM   bulk_listings
WHERE  .....

Now as you can see for the duration, I am wanting to work on the resulting value of the start_time and end_time; however obviously the code below will not work as that will work on the current value of the column I assume and won't use the resulting value I am wanting.
Is there any way to do what I want?

A: You need to create a subquery with your computed values columns:
SELECT start_time, start_time_type, end_time,
       IF(list_in = 'store', '', 'duration'),
       IF(list_in = 'store', end_time - start_time / 86400, duration)
FROM (SELECT IF(start_time_type = 'now'
           OR start_time < " . CURRENT_TIME . ", " . CURRENT_TIME . ",
       start_time) AS start_time,
       start_time_type,
       IF(list_in = 'store', 0, ( IF(end_time_type = 'duration',
                                  " . CURRENT_TIME . " + duration * 86400,
                                  end_time
                                  ) )) AS end_time,
       duration,
       list_in
FROM   bulk_listings
WHERE ...) AS SUBQUERY

redpajama_set_name: RedPajamaStackExchange


text:
Q: VAO and VBO Crashing when drawing I changed my code from DisplayLists to VBOs / VAOs.
But when i run the application it crashes.
It crashes when at the first attempt to draw the VAOs. I'm drawing using no shaders (so it does not cause problems).
There are up to 12 faces (12 * 3 vertices) in one VAO and texture coordinates for those. There are up to 500 000 VAOs.
How i create a face:
tData.add(new float[]{textureX + 0.1249f, textureY+ 0.1249f});
vData.add(new float[]{x, y, z});
tData.add(new float[]{textureX+ 0.1249f, textureY+0.0001f});
vData.add(new float[]{x, y+1, z+1});
tData.add(new float[]{textureX+0.0001f, textureY+0.0001f});
vData.add(new float[]{x+1, y+1, z+1});

Creating the VBO/VAO:
if(vData.isEmpty())
        return;

    int vaoHandle = glGenVertexArrays();
    glBindVertexArray(vaoHandle);

    int vertexDataSize = vData.size() * 3;
    int textureDataSize = tData.size() * 2;
    FloatBuffer vertexData = BufferUtils.createFloatBuffer(vData.size() * 3);
    FloatBuffer textureData = BufferUtils.createFloatBuffer(tData.size() * 2);

    while(!vData.isEmpty())
    {
        vertexData.put(vData.remove(0));
    }
    while(!tData.isEmpty())
    {
        textureData.put(tData.remove(0));
    }

    vertexData.flip();
    textureData.flip();

    int vertexHandle = glGenBuffers();
    glBindBuffer(GL_ARRAY_BUFFER, vertexHandle);
    glBufferData(GL_ARRAY_BUFFER, vertexData, GL_STATIC_DRAW);
    glVertexAttribPointer(0, vertexDataSize, GL_FLOAT, false, 0, 0);

    int textureHandle = glGenBuffers();
    glBindBuffer(GL_ARRAY_BUFFER, textureHandle);
    glBufferData(GL_ARRAY_BUFFER, textureData, GL_STATIC_DRAW);
    glVertexAttribPointer(1, textureDataSize, GL_FLOAT, false, 0, 0);

    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(0);

    renderEngine.vaos.add(new VAO(vaoHandle, (int)((float)vertexDataSize / 3f)));

Rendering the VBO / VAO:
    glUseProgram(0);//TODO:REMOVE
    for(VAO vao : vaos)
    {
        glBindVertexArray(vao.getHandle());
        glEnableVertexAttribArray(0);
        glEnableVertexAttribArray(1);

        System.out.println(vao.getVertices());//correct numeber
        glDrawArrays(GL_TRIANGLES, 0, vao.getVertices());//<-- CRASH at first time called

        glDisableVertexAttribArray(1);
        glDisableVertexAttribArray(0);
    }
    glBindVertexArray(0);

Here's the error:
# A fatal error has been detected by the Java Runtime Environment:
#
#  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x000000000b3fb610, pid=7736, tid=6224
#
# JRE version: Java(TM) SE Runtime Environment (8.0_20-b26) (build 1.8.0_20-b26)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.20-b23 mixed mode windows-amd64 compressed oops)
# Problematic frame:
# C  [ig75icd64.dll+0x8b610]
#
# Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
#
# An error report file with more information is saved as:
# C:\Users\Geosearchef\workspaces\workspaceLWJGL\OrangeJuiceVBO\hs_err_pid7736.log
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.sun.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#

I don't think it's sensefull to post the whole error here.
Do you have any idea why this is happening? I can't find anything about this error concerning VBOs.

A: You do not set the vertex attribute pointers correctly:
int vertexDataSize = vData.size() * 3;
int textureDataSize = tData.size() * 2;
[...]
glVertexAttribPointer(0, vertexDataSize, GL_FLOAT, false, 0, 0);
[...]
glVertexAttribPointer(1, textureDataSize, GL_FLOAT, false, 0, 0);

The size parameter defines the number of elements in the vector of each vertex, and must be in the range of 1 to 4.
YOur code will just generate a GL error - and you should definitively add some error checks, at least for debugging - and leaves the attribute pointer uninitialized.
Another issue here: you use generic vertex attributes 0 and 1, but you don't use shaders. That is not going to work. The spec only guarantees that attribute index 0 will map to the classic glVertex attribute, but attribute 1 might be anything, or not work at all.


text:
Q: When Exactly to Use ArgumentNullException Basically i know how and why we use ArgumentNullException. One thing that is not clear for me yet is when exactly do we need to use it.
Currently i think we need to use it when we write method with parameter and there is a possibility someone who use our code will pass a null parameter. This example is for when we write a library and someone else around the world use the code, or when we work on team.
What if we write code for our own, there is still possibility for null parameter but from the caller method we make sure that the param is never null (we know that it's should not be null since we are the one who write the method). Do we still need to use ArgumentNullException?

A:
(we know that it's should not be null since we are the one who write
  the method).

That sounds like famous last words. As a general rule you want to validate as much of the input at the beginning of every method. It's better to fail with an exact exception before beginning your operation than some mysterious side-effect exception later on.
And I always write my code as if it's going to eventually be a 3rd-party library used by a million people, even if I know only I (or a small group) will use it. There's no reason to be lazy, it's not even saving you anything. Over the long run you will save time in debugging later.


text:
Q: Get error 500 when I try auto-login using selenium I'm trying to create a login bot using selenium and when it logs in it returns a server error, I don't know if it's an internal error or it's because I'm using a bot.
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains

from getpass  import getpass

email= input("Enter your username")
password= getpass("Enter your password: ")

driver=webdriver.Chrome("C:\\Users\\alvar\\env\\ChromeDriver\\chromedriver.exe")
driver.get("https://www.basic-fit.com/on/demandware.store/Sites-BFE-Site/es_ES/Login-Start")

username_textbox = driver.find_element_by_name("email")
username_textbox.send_keys(email)

password_textbox= driver.find_element_by_name('password')
password_textbox.send_keys(password)

login_button = driver.find_element_by_xpath("/html/body/div[1]/div[2]/section[1]/div[2]/form/div[4]/button").submit()

Here's the error

A: You have to click() button, not submit()

When you click then it runs JavaScript which checks login/password.
When you submit then it doesn't click button but it sends form to assigned url <form action="https://www.basic-fit.com/on/demandware.store/Sites-BFE-Site/es_ES/Login-Submit"...> and it makes problem.


text:
Q: How do I intercept mapview panning and zooming (Swift 4) I'm trying to restrict panning and zooming for a mapview, to remain within a predefined max and min camera altitude and the four corners of a bounding box.
The solutions proposed here, allow the user to pan outside the region, and then use regionDidChangeAnimated to pan them back to within the pre-defined bounds.
I'd like to know if it's possible to just never allow the user to pan outside the bounds in the first place. Can I, for example, intercept panning/zooming gestures and decide whether or not to let them continue?
I think I'm looking for something like the following pseudocode:
func blockMapViewPanEvent(_ mapView: MKMapView){
    return mapView.visibleMapRect.isContainedWithin(topLeft, bottomRight)
}

I know that MapBox's Swift SDK achieves this, so I imagine it's possible. Can I do this with plain-old MapKit?
Edit for Clarity:
I want to restrict panning and zooming so the user can pan and zoom as much as they want within a bounding box. For example, if the bounding box is of Germany, I want the user to be able to pan and zoom within Germany, but they should never be able to see Spain, since Spain is outside the bounding box of Germany.
I do not want to disable all user interaction on the map view.

A: If I am understanding you correctly, you want to disable user interaction in the map.
Here are the few options available in map view. These might be helpful for you
mapView.zoomEnabled = false
mapView.scrollEnabled = false
mapView.userInteractionEnabled = false

If you have issues with these you can simply put a transparent view over map view

A: MapKit now makes this possible in iOS 13
You can restrict panning with:
let boundaryRegion = MKCoordinateRegion(...) // the region you want to restrict
let cameraBoundary = CameraBoundary(region: boundaryRegion)
mapView.setCameraBoundary(cameraBoundary: cameraBoundary, animated: true)

And prevent the user zooming outside your region of interest with:
    let zoomRange = CameraZoomRange(minCenterCoordinateDistance: 100,
        maxCenterCoordinateDistance: 500)
    mapView.setCameraZoomRange(zoomRange, animated: true)
There are some limitations that you can best see in the WWDC 2019 video at 2378 seconds.
References

*

*MapKit documentation on "Constraining the Map View"

*class reference for MKMapView.CameraBoundary

*class reference for MKMapView.CameraZoomRange


text:
Q: git filter-branch --tree-filter not deleting the file There is a mistakenly committed file in our git repository. Firstly, I've found which file causes this by running the following command from the How to find/identify large files/commits in Git history?
$ git rev-list --objects --all \
> | git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' \
> | awk '/^blob/ {print substr($0,6)}' \
> | cut --complement --characters=13-40 \
| sort --numeric-sort --key=2 \
> | cut --complement --characters=13-40 \
> | numfmt --field=2 --to=iec-i --suffix=B --padding=7 --round=nearest

Which results 6b82d8f18acd  716MiB MSSender/DebContainer.tar.tgz
Then, I used git filter-branch --tree-filter "rm -f DebContainer.tar.tgz" HEAD --all command from https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History#The-Nuclear-Option:-filter-branch to delete this file in all branches. While processing it creates a gitrewrite folder and creates .git folder back with the same size? What am I possibly doing wrong? Thank you.

A: The procedure for shrinking the repository size after rewriting the history is documented in git filter-branch documentation.
The removed file is still accessible by some references:

*

*references backups created by the filter-branch

*reflog references

So, to shrink the .git folder, you have to get rid of those references:

*

*either by creating a new clone from the rewritten one

*either by deleting the references and garbage-collecting the repo content:
git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d
git -c gc.reflogExpire=now gc --prune=all

NOTE:
Any modified reference need to be force-pushed to the original repository.
And anyone that cloned this repository need to carefully update it's repository (git pull --rebase for each local branch should be the best option)


text:
Q: Cannot Select the whole surface of the tabHeader in WPF dynamically populated tabcontrol
In the above image:

*

*You may note there is a little rectangle box around the tabHeader "title".

*When I click inside the rectangle box, the tab does not get selected.

*When I click outside the box, it does.

Code C#:
public class Lexicon : ObservableCollection<LexiconEntry>
{
    public String leftLanguage  { get; set; }
    public String rightLanguage { get; set; }
    public String name { get; set; }

    public Lexicon(String name, String leftLanguage,String rightLanguage)
    {
        this.leftLanguage = leftLanguage;
        this.rightLanguage = rightLanguage;
        this.name = name;
    }

}

public partial class MainWindow : System.Windows.Window
{
    public List<Lexicon> lexicons;
    public MainWindow()
    {
        InitializeComponent();

        lexicons = new List<Lexicon>();

        lexicons.Add(new Lexicon("foo_title","russian","french"));
        lexicons.Add(new Lexicon("bar_title", "french", "english"));
        lexicons.Add(new Lexicon("baz_title", "russian", "french"));

        TheTabControl.ItemsSource = lexicons;
    }
}

Xaml CODE:
<Window x:Class="InterpreterNotepad.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:toolkit="http://schemas.xceed.com/wpf/xaml/toolkit"
        xmlns:avalonDock="http://schemas.xceed.com/wpf/xaml/avalondock"
        Title="InterpreterNotepad"  WindowStartupLocation="CenterScreen" WindowState="Maximized" x:Name="mainWindow">
        ...
    <DockPanel>
        <Menu DockPanel.Dock="Top">
            ...
        </Menu>
        <TabControl x:Name="TheTabControl">
            <TabControl.ItemTemplate>
                <DataTemplate>
                    <TabItem Header="{Binding name}"/>
                </DataTemplate>
            </TabControl.ItemTemplate>
            <!-- Content -->
            <TabControl.ContentTemplate>
                <DataTemplate>
                    <TextBlock Text="bqr"/>
                </DataTemplate>
            </TabControl.ContentTemplate>
        </TabControl>
    </DockPanel>
</Window>

A:
Got it, Sorry for this newbie question, I'm new to WPF. Using snoop, I saw that my rectangle box was actually a tabItem inside a tabItem!
I thought the dataTemplate described the template to be repeated in the tabControl, while it describes the content of each tabItem.
I Need to put:
        <TabControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}"/>
            </DataTemplate>
        </TabControl.ItemTemplate>

Instead of:
        <TabControl.ItemTemplate>
            <DataTemplate>
                <TabItem Header="{Binding name}"/>
            </DataTemplate>
        </TabControl.ItemTemplate>


text:
Q: PHP Priority Queue Implementation I just finished coding a complex job assignment application where a lot of the work was done using priority queues. When I deployed, however, I discovered the web server ran PHP 5.2.
Has there been an implementation for PHP<5.3 that can server as a drop-in replacement for SPLPriorityQueue?

A: I would have thought it would be quite simple to build one using SPLMaxHeap and a wrapper for each item?
C.

A: I don't know of anything that has the same interface.
But, I'd like to point out that if you don't need the performance characteristics of the heap implementation(small data sets probably don't), it wouldn't be much work to write your own using a regular php array.


text:
Q: Is there a good solutation to display a statistics report on iphone? I am  a new iphone developer and I have a problem when I develop my app. The situation is that I need to display a report with headers both on the vertical and horizontal axes, just like an excel spreadsheet does. Can anyone can help me to figure out a good solution? Better with some code. Any comments are appreciated.

A: If the report is pretty much static and doesn't need to be editable/selectable then you could build a 2x2 grid of UILabel's which contain both your headings and report data and drop it all inside a containing UIView and then put that containing UIView inside a UIScrollView with vertical and horizontal scrolling set.

A: Here's an iOS grid component.  It's API is very similar to UITableView
http://cocoacontrols.com/platforms/ios/controls/dtgridview


text:
Q: Unity: How to stretch UI picture to relative size of canvas without it overstretching? My UI elements in free-aspect ratio screen are perfect but when I change aspect ratios the text and pictures are way too small. I'm using an anchor to the corners for the UI elements; however, if I use the all-direction stretch then it overstretches. How do I prevent overstretching? I want the image to stretch relative to the canvas size while being anchored in a position. How do I do this?

A: First, You need to create an empty GameObject. This object needs to be a child of your canvas. Inside this empty object you'll put all of your GUI objects (Images, Buttons, etc...)
Like this
Next, set the anchor preset to strecth As here
Then you need to write this code (don't forget * 1f after Scale.width and height because if you don't write this the operation Scale.width / Scale.height will be considered as an integer and not a float)
Finally, use these Canvas Settings

A: If the anchors are set properly then it is most likely the Canvas Scaler needs to be changed to "Scale with Screen Size" mode so that it changes to the resolution you put in i.e. X:800, Y:600. If this still doesn't work then you should change text Paragraph to "Best Fit".


text:
Q: Using Ajax on a webApp I'm working on an application and I would like to use Ajax to partially render part of web page instead of full post back. So I use scriptManager and updatepanel but I have an error in JS sys is not defined. I took a look in generated JS code and it seems that no Ajax client side framework has been loaded by scriptmanager, no reference at scriptressource.
I created a website by using vs2010 template to test ajax and all works fine but in web.config I don't found any difference. Is it a known problem?

A: Solution:
After comment and uncomment different part of my code i found that is my objectdatasource which cause the problem... ObjectDataSource use function instance to retrieve business object but since i use class properties as argument of my "select" objectdatasource function i need to define current instance of my page as object instance (1) but when work is finished is also disposed by objectdatasource .... :) i stop disposing process by using event "ObjectDisposing" (2) ...
(1)
protected void OdsRecordObjectCreating(object sender, ObjectDataSourceEventArgs e)
        {
            e.ObjectInstance = this;
        }

(2)
protected void OdsRecordObjectDisposing(object sender, ObjectDataSourceDisposingEventArgs e)
{
    e.Cancel = true;
}

bye !


text:
Q: Select box with default option posting multiple values I was hoping someone could shed some light on a very odd behavior I've encountered. I have a simple select box (single value drop-down) that has a default selected value set on page load. The odd behavior is that if the user changes the value of the select box, it appears both values (the default value and the new selected value) are being sent on postback?!
<select name="selectBox">
    <option value="1" selected>Item 1</option>
    <option value="2">Item 2</option>
    <option value="3">Item 3</option>
</select>

So, if a user selects item 2, on post I'm receiving a value like, "1,2". Obviously, I'd expect just to receive a value of "2". If I debug in firebug, when I select an option, the value being displayed in firebug is the single, selected value as expected. It seems so simple, am I blind? I am using MVC as the framework, if that makes any difference. Your help is greatly appreciated.

A: Add a name attribute to your select element.

The name attribute is used to reference form data after it's
  submitted, and to reference the data using JavaScript on the client
  side. Unlike the id attribute, which must be given a unique value each
  time it's applied to a new form control, a name attribute with a given
  value may be applied to numerous form controls (although in practice
  this approach is only ever seen in use with radio input buttons).
  Note that only form elements which have a name attribute will have their values passed through to the page or script specified in the
  form's action attribute.


text:
Q: Logical expressivity and model classes Consider two logical languages $\mathcal L_1\subseteq\mathcal L_2$. Let the corresponding logics be semantically defined. Suppose that the correspond models depend on the language itself, but there is a meaningful way to convert the models associated with $\mathcal L_1$ into the others and vice versa. How can one compare expressive strength of such two logics if the model classes are not the same? Would one use the model class associated with the larger language?
The example I have in my mind comes from a paper about justification logic by Bryan Renee(pdf). In his paper, we compares a "basic" justification logic with one enhanced by a public announcement operator. The classical semantic way of defining justification logics is to consider extensions of Kripke-models where a function
$$
\mathcal E:\mathcal L\times Jt\to \mathcal P(W)
$$
is added to assign every formula and justification term a set of worlds where this combination is considered admissible. The classic definition about expressive comparison is considering two languages evaluated over the same class of models. But enhancing the language should also change the class of models as a part of the definition depends on it. Naturally, if one considers an extension of the language like Renee does, there is here also a way to convert/extend a model from the lower language to a model concerning the higher language. My confusion arises as how one would compare these logics then, would one use the "larger" model class?  Renee makes no comment on this.


text:
Q: sizeThatFits doesn't work properly on iOS7 and works fine on iOS8 CGSize size = [_textView sizeThatFits:CGSizeMake(300, kTextViewHeight)];

It works different on ios7 and iOS8. In ios8 it gives me the height of the text properly, but in IOS7 it just leaves the height equal to kTextViewHeight. Help me please.

A: use FLT_MAX instead of kTextViewHeight:-
CGSize size = [_textView sizeThatFits:CGSizeMake(width, FLT_MAX)];


text:
Q: Countdown timer does not stop If an answer is given before 10 seconds, I need a stop function. I've tried some ideas but can't find a solution
Here's the updated jsFiddle and my code. Can anyone help, please?
HTML
<canvas id="timer" width="48" height="48"></canvas>

stop

JAVASCRIPT
function sCounter(){
    canvas = document.getElementById('timer');
    num = document.getElementById('num');
    ctx = canvas.getContext('2d');
    fps= 40;

    var total = fps*10; //*second
    for(var i=total;i>=0;i--) {
        var delayed = (function(){
            var step = 1-i/total;
            var left = Math.ceil(i/fps);
            return function() {
                num.innerHTML=left;
                draw_next(step);

                if(left===0){  //if 0
                    //etc...
                }
            };
        })();
        var timer = setTimeout(delayed,-1000/fps*(i-total));
    }
}

function draw_next(step) {
    ctx.clearRect(0,0,48,48);
    ctx.beginPath();
    ctx.arc(24,24,20,Math.PI * (-0.5 + 0),Math.PI * (-0.5 + step*2),false);
    ctx.lineWidth = 8;
    ctx.strokeStyle = "#dedede";
    ctx.stroke();
}

function istop(e) {
    e.preventDefault();
    var timer = null;
    clearTimeout(timer);
    return false;
}

sCounter();

A: You should be putting the timer var on a common scope, seems too that the for loop is activating timers without the previous one has ended, because of that you can't clear them, see de fiddle: http://jsfiddle.net/HQJkz/
    var timer = null

    function sCounter() {
    canvas = document.getElementById('timer');
    num = document.getElementById('num');
    ctx = canvas.getContext('2d');
    fps = 40;

    var total = fps * 10; //*second

    var render = function (left, step, i) {
        num.innerHTML = left;
        draw_next(step);
        if (left)
        if (left === 0) { //if 0
            //etc...
        } else {
            delayed(i - 1);
        }
    };

    var delayed = function (i) {
        var step = 1 - i / total;
        var left = Math.ceil(i / fps);
        var current = function () {
            console.log(left, step);
            render(left, step, i);
        };
        timer = setTimeout(current, -1000 / fps * (i - total));
    }

    delayed(total - 1);
}

And it seems that you where trying to clear the timer after losing it's value. I had to change the istop scope to window because fiddle didn't find it. This should do the trick:
window.istop = function() {
    clearTimeout(timer);
    timer = null;
    return false;
}


text:
Q: Not able to set meta data on a resque-status hash As per the resque-status home page on GitHub I should be able to pass back data from a job. For some reason this does not seem to be working for me. If anyone else has encountered this problem and worked around it I would like to know how.
I am using resque-status with JRuby 1.6.5 in a Rails 3.2.3 application.

Passing back data from the job
You may want to save data from inside the job to access it from outside the job.
A common use-case is web-triggered jobs that create files, later available for download by the user.
A Status is actually just a hash, so inside a job you can do:
status['filename'] = '/myfilename'
Also, all the status setting methods take any number of hash arguments. So you could do:
complete('filename' => '/myfilename')

A: Apparently such functionality is not implemented, as read on
https://github.com/quirkey/resque-status/issues/66
we've found a work around using the function set_status to add the required data to the status hash:
set_status({"my variable" => "my value" })

hope this helps!


text:
Q: Custom form and action attribute in wordpress site I've fallen in the (unknown to me) abyss of the custom forms and custom form handlers in wordpress.
I just need a working contact form without the need of installing any plugin.
I would normally do this with the $_SESSION superglobal (to pass error and success messages) and a post-redirect-get pattern (avoiding double sends with page reloads). The code would look like this
<form class="di-contact" method="post" action="<?php echo get_template_directory_uri() ?>/contact.php" style="width: 50%; margin: 0 auto">

<?php the_title() ?>

<?php _e('Name', 'di-news-blog'); ?>:
<input class="uk-input" type="text" id="di-name"  name="di-name">

<?php _e('E-mail', 'di-news-blog'); ?>:
<input class="uk-input" type="email" id="di-email"  name="di-email">

<?php _e('Message', 'di-news-blog'); ?>:
<textarea class="uk-textarea" id="di-message"  name="di-message"></textarea>

<input type="submit" name="di-submit" value="<?php _e('Submit', 'di-news-blog'); ?>">
</form>

Then i would code something like this in contact.php:
<?php
////////////////////   MAIL PROPERTIES      ///////////////////

$to = get_option('admin_email');
$from = htmlentities($_POST['di-email']);
$subject = __('Message from ','di-news-blog'). get_bloginfo('blogname');

////////////////////////   HEADERS   ////////////////////////

$headers = "From:" . $from . "\r\n";
$headers .= "Reply-To:" . $from . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

////////////////////////   MESSAGE  ////////////////////////

$message = '
You got a message from '  .
htmlentities($_POST['di-name']) . '
';
$message .= '
Email: ' . $from . '
';
$message .= 'Message:
' .
htmlentities($_POST['di-message']);

//////////////////////////////////////////////////////////////
if ( isset( $_POST['di-submit'] ) ) {
if (  ! empty( $_POST['di-email'] ) || ! empty( $_POST['di-email'] ) ||  ! empty( $_POST['di-message'] ) ) {
    mail($to, $subject, $message, $headers);
    $_SESSION['success'] = '
' . __('Message sent succesfully', 'di-news-blog') . '
';

    wp_redirect(get_template_directory_uri() . '/contact'); exit;
} else {
    $_SESSION['error'] = '
' . __('Please enter all the requested data and try again', 'di-news-blog') . '
';

   wp_redirect(get_template_directory_uri() . '/contact'); exit;
  }
}

But nooby me, i just found out wordpress functions like get_option() or __('','') won't work in a page like contact.php, and also the $_SESSION superglobal, i was told i could make it work with something like that in the functions.php file:
// SESSIONS //////
function register_my_session(){
    if( ! session_id() ) {
        session_start();
    }
}

add_action('init', 'register_my_session', 1);

function cyb_session_start() {
    if( ! session_id() ) {
        session_start();
    }
}

function cyb_session_end() {
    session_destroy();
}

add_action( 'init', 'cyb_session_start', 1 );
add_action( 'wp_logout', 'cyb_session_end' );
add_action( 'wp_login', 'cyb_session_end' );

which didn't work.
Sorry my ignorance, but i couldn't find documentation (that i understand, not a nijna php dev) on how this could be achieved.

A: I would send the form POST back to /contact (the contact form page) and handle the form send from there.
To keep the template clean I'd normally create a function in functions.php which you can then call from the template, and I'd create a specific contact page template in the theme called page-contact.php (which will automatically be used for the page with the slug contact). This would be the only template that needs to call the contact form handler function.
You can actually include Wordpress within your own custom (non-template) files so that you can use wordpress functions, but I don't think it's necessary for what you're trying to do.
A very minimal example:
page-contact.php
<?php get_header(); ?>

<?php if(have_posts()) : ?>
<?php while(have_posts()) : the_post(); ?>

<?php the_title(); ?>

<?php the_content(); ?>
<?php contact_form_handler(); ?>

<?php endwhile; ?>

<?php else : ?>
<?php include_once 'templates/no-posts-found.php'; ?>
<?php endif; ?>

<?php get_footer(); ?>

functions.php
function contact_form_handler() {

  /* If this is a postback, handle the contact form */
  if(isset($_POST['message'])) {

    //Try to send the message and set $successful to true or false

    echo ($successful ? "Message sent!" : "An error occurred");

  }

  /* Otherwise display the form itself */
  else {
    include_once 'templates/contact-form.php';
  }
}

templates/contact-form.php
<form method="POST" action="/contact">
  <textarea name="message"></textarea>
  <input type="submit" value="Submit" />
</form>


text:
Q: How to use calc() in tailwind CSS? I have this html:

I have set the .navBar's height to h-7. Now I want to set .content-container's height to 100vh-(h-7).
How can I use calc() to set it?

A: theme()
Use the theme() function to access your Tailwind config values using dot notation.
This can be a useful alternative to @apply when you want to reference a value from your theme configuration for only part of a declaration:
.content-container {
  height: calc(100vh - theme('spacing.7'));
}

A: If you are using v2.x, add mode: 'jit' to your tailwind.config.js (no mode: 'jit' needed in tailwind v3)
module.exports = {
  mode: 'jit',
  ....
};

And use like this: (Without space!)
class="w-[calc(100%+2rem)]"

It will produce:
.w-\[calc\(100\%\+2rem\)\] {
  width: calc(100% + 2rem);
}

We can use the theme variables as well:
h-[calc(100%-theme(space.24))]

Tailwind v3 update
Now we can use an underscore _ instead of whitespaces:
Ref: Handling whitespace


text:
Q: Функция JavaScript для параметризации стринга Ребята помогите мне плиз, хочу чтобы мой output был robin-singh-from-usa.
Пока, что мой output это массив ["robin", "singh", "from", "usa."]
 function string_parameterize(str1) {
  return str1.trim().toLowerCase().split(' ');
 }
 console.log(string_parameterize("Robin Singh from USA."));

A: Осталось объединить полученный массив с помощью функции join

function string_parameterize(str1) {
  return str1.trim().toLowerCase().split(' ').join('-');
}
console.log(string_parameterize("Robin Singh from USA."));


text:
Q: Mongodb timestamps for querying documents I want to fetch all the documents created on D-1 day, i.e. suppose if any record has been created on 4-12-2019 then query should fetch records created on 3-12-2019.
Here is my Model and code:
VENDOR ORDER SCHEMA
const vendorOrderSchema = new mongoose.Schema({
    timesOfIndia:{
        tradeCopies:{
            type:Number,
            deafult:0 },
        subscriptionCopies:{
            type:Number,}
    },
    economicTimes:{
        tradeCopies:{
            type:Number,
            deafult:0
        },
        subscriptionCopies:{
            type:Number,}
    },
    mumbaiMirror:{
        tradeCopies:{
            type:Number,
            deafult:0
        },
        subscriptionCopies:{
            type:Number}
    },
    isApproved:{
        type:Boolean,
        default:false
    },
    vOrderCreator:
    {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required:true
    }
},
{ timestamps: true }
)

const VendorOrder = mongoose.model('VendorOrder',vendorOrderSchema)
module.exports = VendorOrder

Query:
exports.getOrderById = async (req,res,next) =>{
    const vOrderCreator = req.params.id
    const vendorOrder = await VendorOrder.find({vOrderCreator,
                            createdAt: { $gt: new Date(Date.now() - (1000 * 60 * 60 * 24)) }
                         })
    try {
        if (!vendorOrder) {
            const error = new Error('Could not find post.');
            error.statusCode = 404;
            throw error;
        }
        res.status(200).json({ message: 'VendorOrder fetched.', vendorOrder });
    } catch (err) {
        if (!err.statusCode) {
            err.statusCode = 500;
        }

        next(err);
    }}

POSTMAN RESPONSE

{
      "message": "VendorOrder fetched.",
      "vendorOrder": [] // getting this empty array
  }


text:
Q: Window form opacity .. How to control? I have a single form window application now I want to change the form opacity when application runs. Means when application run it will show low opacity form and as time increse it will show complete form with 100 opacity. So how to do that. (should I use timer control to control opacity, if yes then how????)

A: in constructor of the form you can write something like this.
this.Opacity = .1;
timer.Interval = new TimeSpan(0, 0, intervalinminutes);
timer.Tick += ChangeOpacity;
timer.Start();

And then define a method like this
void ChangeOpacity(object sender, EventArgs e)
{
    this.Opacity += .10; //replace.10 with whatever you want
    if(this.Opacity == 1)
        timer.Stop();
}

A: To fade forms in and out, I usually do this:
for(double opacity = 0.0; opacity <= 1.0; opacity += 0.2) {
    DateTime start = DateTime.Now;
    this.Opacity = opacity;

    while(DateTime.Now.Subtract(start).TotalMilliseconds <= 30.0) {
        Application.DoEvents();
    }
}

It's a nice, simple solution if you'll be doing it very infrequently. Otherwise, I would recommend using threads.

A: In the constructor, start the timer control that will call a method at each tick.
timer.Interval = 1000;
timer.Tick += new EventHandler(TimerEventProcessor);
timer.Start();

............
 private static void TimerEventProcessor(Object myObject,
                                            EventArgs myEventArgs)
  {
       if(this.Opacity < 1)
         this.Opacity += .1;
       else
           timer.Stop();
  }

A: For Exit Decreasing Opacity Animation
       ///////\\\\\\ Coded by Error X Tech ///////\\\\\\

 System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
 private void DecreaseOpacity(object sender, EventArgs e)
    {
        if (this.Opacity >= 0.1)
        {
            this.Opacity -= 0.04; //replace 0.04 with whatever you want
        }
        if (this.Opacity <= 0.0)
            timer.Stop();
        if (this.Opacity <= 0.1)
        {
            System.Environment.Exit(1);
            Process.GetCurrentProcess().Kill();
        }
    }

private void Exit_Click(object sender, EventArgs e)
    {

        timer.Interval = 47; //replace 47 with whatever you want
        timer.Tick += DecreaseOpacity;
        timer.Start();
    }

A: In the constructor, set the opacity to 0 and start a timer with an interval of something small like 10 or 100 milliseconds. In the timer_Tick event, you simply need to run this.Opacity += 0.01;
This will make it so that the opacity starts at 0 and increase by .01 every few milliseconds until it's 1 (opacity is a double, when it reaches a value of 1 it's fully opaque)

A: increasing Opacity Animation while Application start
        ///////\\\\\\ Coded by Error X Tech ///////\\\\\\
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
void IncreaseOpacity(object sender, EventArgs e)
    {
        if (this.Opacity <= 1)  //replace 0.88 with whatever you want
        {
            this.Opacity += 0.01;  //replace 0.01 with whatever you want
        }
        if (this.Opacity == 1) //replace 0.88 with whatever you want
            timer.Stop();
    }
private void Form1_Load(object sender, EventArgs e)
    {
        this.Opacity = .01;
        timer.Interval = 10; //replace 10 with whatever you want
        timer.Tick += IncreaseOpacity;
        timer.Start();
     }


text:
Q: How do I add a PictureBox chess piece over the top of a PictureBox chess board so that the position is relative to the chess board? How do I add a PictureBox chess piece over the top of a PictureBox chess board so that the position is relative to the chess board?
PictureBox chessPiece = new PictureBox();
chessPiece.Image = Properties.Resources.PawnBlack;
chessPiece.BackColor = Color.Transparent;
chessPiece.BringToFront();
chessBoard.Controls.Add(chessPiece);
chessPiece.Location = new Point(0, 0);

Can a picture box be added to another picture box or do I need a 3rd element to house both the board and then the pieces?
To be more clear, The picture box/s will show up at the point (0,0) relative to the form not the chess board.

A: You have to add chess piece location relative to the chess board location, so

chessPiece.Location = new Point(chessBoard.Location.X + x, chessBoard.Location.Y + y);
// x,y is chesspiece location relative to the chessboard

PS: Try using tablelayoutpanel instead of picturebox for the chessboard.


text:
Q: In the Poisson process $N,$ find $\operatorname E[2^{N(t)}e^{-\lambda t} \mid N(s) = k]$ and $\operatorname{Var}(N(t) \mid N(s) = k)$.
Consider the Poisson Process $\{N(t); t \geq 0\}$ with intensity $\lambda$. For $0 < s < t$, determine
a) $\operatorname E[2^{N(t)}e^{-\lambda t} \mid N(s) = k]$ (Hint: $\operatorname E[e^{xN(t)}] = e^{-\lambda t(1-e^x)})$
b) $\operatorname{Var}(N(t) \mid N(s) = k).$

This is what I've tried:
Edit: the last implication below was wrong. $\operatorname{E}[2^{N(t)}e^{-\lambda t}\mid N(s)=k]$ doesn't have to be equal to 1.

a) First I calculated $\operatorname E[2^{N(t)}e^{-\lambda t}]{:}$
\begin{align}
& = e^{-\lambda t}E[2^{N(t)}] \\[10pt]
& = e^{-\lambda t}E[e^{\ln(2)N(t)}] \\[10pt]
& = e^{-\lambda t}e^{\lambda t} \text{ using the hint} \\[10pt]
& = 1.
\end{align}
Then, using $\operatorname{E}[X] = \sum_{y} \operatorname{E}[X\mid Y=y]f_Y(y)$:
$\operatorname{E}[2^{N(t)}e^{-\lambda t}] = \sum_{k=0}^{\infty} \operatorname{E}[2^{N(t)}e^{-\lambda t}\mid N(s)=k]e^{-\lambda s}\frac{(\lambda s)^k}{k!}$
$\implies 1 = e^{-\lambda s} \sum_{k=0}^{\infty} \operatorname{E}[2^{N(t)}e^{-\lambda t}\mid N(s)=k]\frac{(\lambda s)^k}{k!}$
$\implies e^{\lambda s} = \sum_{k=0}^{\infty} \operatorname{E}[2^{N(t)}e^{-\lambda t}\mid N(s)=k]\frac{(\lambda s)^k}{k!}$
$\implies \sum_{k=0}^{\infty} \operatorname{E}[2^{N(t)}e^{-\lambda t}\mid N(s)=k]$ should equal 1 because $e^{\lambda s} = \sum_{k=0}^{\infty}\frac{(\lambda s)^k}{k!}$.

On the second try I found $\operatorname{E}[2^{N(t)}e^{-\lambda t}\mid N(s)=k] = 2^k e^{-\lambda s}$ (thanks to Michael Hardy's answer):
\begin{align}
\operatorname{E}[2^{N(t)}e^{-\lambda t}\mid N(s)=k] & = \operatorname{E}[2^{N(t) - N(s) + N(s)}e^{-\lambda t}\mid N(s)=k] \\[10pt]
& =e^{-\lambda t}\operatorname{E}[2^{N(t) - N(s)}\mid N(s)=k]\cdot\operatorname{E}[2^{N(s)}\mid N(s)=k] \\[10pt]
& =e^{-\lambda t}\operatorname{E}[2^{N(t-s)}]\cdot 2^k \\[10pt]
& =2^k e^{-\lambda t}e^{\lambda (t-s)}\\[10pt]
& =2^k e^{-\lambda s}.
\end{align}
Is this correct?
b) $\operatorname{Var}(N(t) \mid N(s) = k)$
\begin{align}
& = \operatorname{Var}(N(t) - N(s) + N(s) \mid N(s) = k) \\
& = \operatorname{Var}(N(t) - N(s) \mid N(s) = k) + \operatorname{Var}(N(s) \mid N(s) = k)\\
& = \operatorname{Var}(N(t) - N(s)) + 0\\
& = \lambda (t-s).
\end{align}
Could this be correct?
Any help or answers would be greatly appreciated.

A: $\newcommand{\v}{\operatorname{var}}$The number of arrivals in the time interval $[0,s]$ and the number of arrivals in the time interval $[s,t]$ are independent.
Therefore
\begin{align}
\v(N(t) \mid N(s)=k) & = \v(N(t)-k\mid N(s)=k) = \v(N(t)-N(s)\mid N(s)=k) \\[10pt]
& = \v(N(t) - N(s)) \text{ by the aforementioned independence} \\[10pt]
& = t-s \text{ since } N(t)-N(s) \sim \operatorname{Poisson}(t-s).
\end{align}
Similarly
\begin{align}
& \operatorname E(2^{N(t)} e^{-\lambda t}\mid N(s)=k) = \operatorname E(2^{(N(t) - N(s)) + k} e^{-\lambda t} \mid N(s)=k) = 2^k e^{-\lambda t} \operatorname E(2^{N(t) - N(s)}),
\end{align}
and then use the hint.


text:
Q: emacs: Automatically open corresponding file in another instance I want something similar to Emacs C++, opening corresponding header file except that I want to
1) Always automatically open the corresponding header; and
2) Do that in another emacs instance (if someone came up with a solution that made all other emacs instances do this, it would be fine also.)
Note that I use emacs in the terminal mode so I can't do https://superuser.com/questions/102163/how-to-split-emacs-over-a-dual-monitor (or at least I do not know how).

A: A simple solution to 2) is to run an emacs instance with
server-mode enabled in the second terminal and command it from the
main emacs instance by using server-eval-at.
To launch the slave, run:
$ emacs --eval '(progn (setq server-name "ff-slave") (server-mode 1))'

Then use the following code to command it:
(require 'server)
(require 'find-file)

(defun command-ff-slave ()
  (interactive)
  (save-excursion
    (let ((b (ff-other-file-name)))
      (if (null b)
          (message "Found no other file")
          (server-eval-at "ff-slave"
                          `(find-file ,b))))))

Calling command-ff-slave from the main emacs instance
should open any related file in a new buffer on the slave server.


text:
Q: Problemas con con estilos al repetir input number en bootstrap 4 Hola estoy teniendo problemas con un input form de números ,resulta que cuando repito todo el div solo me toma estilo a uno solo.

(function ( $ ) {

 $.fn.bootstrapNumber = function( options ) {

  var settings = $.extend({
   upClass: 'default',
   downClass: 'default',
   upText: '+',
   downText: '-',
   center: true
   }, options );

  return this.each(function(e) {
   var self = $(this);
   var clone = self.clone(true, true);

   var min = self.attr('min');
   var max = self.attr('max');
   var step = parseInt(self.attr('step')) || 1;

   function setText(n) {
    if (isNaN(n) || (min && n < min) || (max && n > max)) {
     return false;
    }

    clone.focus().val(n);
    clone.trigger('change');
    return true;
   }

   var group = $("

");
   var down = $("<button type='button'>" + settings.downText + "</button>").attr('class', 'btn btn-' + settings.downClass).click(function() {
    setText(parseInt(clone.val() || clone.attr('value')) - step);
   });
   var up = $("<button type='button'>" + settings.upText + "</button>").attr('class', 'btn btn-' + settings.upClass).click(function() {
    setText(parseInt(clone.val() || clone.attr('value')) + step);
   });
   $("").append(down).appendTo(group);
   clone.appendTo(group);
   if(clone && settings.center) {
    clone.css('text-align', 'center');
   }
   $("").append(up).appendTo(group);

   // remove spins from original
   clone.prop('type', 'text').keydown(function(e) {
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
     (e.keyCode == 65 && e.ctrlKey === true) ||
     (e.keyCode >= 35 && e.keyCode <= 39)) {
     return;
    }
    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
     e.preventDefault();
    }

    var c = String.fromCharCode(e.which);
    var n = parseInt(clone.val() + c);

    if ((min && n < min) || (max && n > max)) {
     e.preventDefault();
    }
   });

   self.replaceWith(group);
  });
 };
} ( jQuery ));

$("[name='checkbox2']").change(function() {
 if(!confirm('Do you wanna cancel me!')) {
  this.checked = true;
 }
});

$('#after').bootstrapNumber();
$('#colorful').bootstrapNumber({
 upClass: 'success',
 downClass: 'danger'
});
.cantidad span{
  margin-right: 0;
  border: initial
}
.cantidad button{
  background: transparent!important;
}
.cantidad .form-group{
  width: 167px
}
.cantidad .input-group{
  border: 1px solid gray;
}
.cantidad .input-group > .form-control{
  border: 1px solid #fff!important;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">

  Cantidad:
  <input id="after" class="form-control" type="number" value="1" min="1" max="10" />

  Cantidad:
  <input id="after" class="form-control" type="number" value="1" min="1" max="10" />

A: Mueve after de id a clase:
$('.after').bootstrapNumber();

<input class="form-control after">


text:
Q: Matlab reading hex values from text file with non hex values interspersed? I have a text file that looks something like this what's pasted below.  Several hex values followed by "xx" followed by hex values.  The pattern repeats ~1M times.  I'm looking for a good way to read out just the hex values ignoring the "xx" values.  Textscan seems interesting, but doesn't support hex.  fscanf is great, but it chokes as soon as it hits the first "xx" in the file.  I wrote a clunky script, which reads everything as a string, omits "xx"s and uses dec2hex, but this is painfully slow (obviously).  Any suggestions?
7F
55
8A
9B
6E
XX
XX
XX
XX
FF
DE
BE
EF
XX
XX
XX
04
88
.
.
.

A: This solution reads 1 million 2-character lines in less than a second on my laptop:
fid = fopen('test.txt');
A   = textscan(fid,'%2c','CommentStyle','XX');
fclose(fid);
A   = hex2dec(A{:});

Note the 'CommentStyle' option that skips those lines that start with XX.


text:
Q: codefirst - model changes commands I am confused about one thing that how and in which order should we execute the commands in project manager console when a new model and modify the existing model requires to update the database.
1) Enable-migrations
2) Add-Migration
3) Update-database

I am presuming that on the base of model changes or new model, we require these commands to be executed in the mentioned order each time. Kindly guide me in this regard. –

A: If you want to enable migration to your project for first time, run
PM> Enable-Migrations

If migration is enabled and you changed your model and want to affect changes to your database run
PM> Add-Migration [migration-name]
PM> Update-Database

There are more useful switches for above commands that you can find at EF Migrations Command Reference.


text:
Q: How can I access midi Info after it arrives at my receiver in Java What I wish to do is write a simple program where whenever I press keys on my external midi controller, an internal receiver accepts the note on messages and somehow allows them to printed as byte information. Ive set up a receiver which is set to my external hardware midi controller's transmitter. I'm not sure how to access the midi information from the receiver after it has arrived there. In terms of research which I have done on the subject, Ive read oracles midi over view and looked at various examples on StackOverFlow. The Oracle article explains connecting the receiver and the transmitter and how to send this info to a synth, but does not cover how to access the Midi Short Messages from the receiver itself without a synth or a sequencer. The StackOverFlow examples have relevant info but I haven't seen anything which explains how to get to extract info from the receiver itself. If someone where to write some example code, and write a detailed explanation, I think it would be a great service to beginners like myself, because it would show how to make the first step in writing code that is compatible with midi i.e. How to receive the midi data in Java and then the first steps in being able to use it. Here is some sample code of what I am already trying.
package receivemidiattempt;

import javax.sound.midi.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class ReceiveMidiAttempt {

public static void main(String[] args)   {

 // My internal receiver which I set up with my own MidiReceiver class   which implements
 // Receiver

 Receiver r = new MidiReceiver ();

   //My Transmitter
   Transmitter trans = null;

   try {
  //Setting up transmitter with the external midi controller
       trans= MidiSystem.getTransmitter();

   }
   catch(MidiUnavailableException e)
   {
       System.out.println("No Midi port Detected");
   }

  //contecting the transmitter to my internal receiver
   trans.setReceiver(r);
   }
   }

Ive got the transmitter and the receiver connected, but am not              sure what to do from here   to extract the midi info from the receiver so I  can print it. The receiver interface only has two methods, close and send, where close closes the receiver and Send sends a message to the receiver itself. Hoping I can find some way to take the midi info arriving at the receiver and store it in a byte variable called midiInfo which i can then print.
Alright Ive messed around with Java for the past hour and Ive almost figured it out. I think what I'm confused about is the way methods work in a class when an object of that class has been instantiated. For example just by putting println(msg) in the method Send() from the class I made which implements receiver, without invoking the method, every time I press a key on my controller a strange message gets printed which looks like a@787fd and changes every time. If i use msg.getLength i can see that every time I press a key the number 3 is printed. This makes sense considering that a Short message has three bytes The status byte, the pitch byte and the velocity byte. What I still can't figure out is how to get java to print the actual bytes. Almost there though!

A: The easiest way to do this would be to use JFugue:
// You'll need some try/catches around this block. This is traditional Java Midi code.
MidiDevice.Info[] infos = MidiSystem.getMidiDeviceInfo();
MidiDevice device = MidiSystem.getMidiDevice(infos[0]); // You'll have to get the right device for your MIDI controller.

// Here comes the JFugue code
MusicTransmitterToParserListener m = new MusicTransmitterToParserListener(device);
m.addParserListener(new ParserListenerAdapter() {
    @Override public void onNotePressed(Note note) {
        System.out.println(note + " pressed");
    }
    @Override public void onNoteReleased(Note note) {
        System.out.println(note + " released");
    }
} );

// Choose either this option:
m.startListening();
...do stuff...
m.stopListening();

// Or choose this option:
m.listenForMillis(5000); // Listen for 5000 milliseconds (5 seconds)


text: Q: Side-by-Side translations So I'm trying to set up a kind of side-by side translation in LATEX and I have tried two minipages as well as two columns and it doesnt quite work the way I want it too. The final goal is something like Spark Notes NoFearShakespeare


text:
Q: Docker build step , requires two arguments docker build -t project1 .
Sending build context to Docker daemon 82.77 MB
Step 1/3 : FROM httpd:2.4
---> a8ea074f4566
Step 2/3 : COPY ./usr/local/apache2/htdocs/
COPY requires at least two arguments


text:
Q: How to find the sum of numbers on a line within a text file? I'm currently trying to use a dictionary to accumulate the sum of all the numbers that are on the line. Each line has an ID number which is the first number on each of the lines.
It is able to ID each line, however it doesn't find the sum, it uses the second value in each line as the sum.
dict = {}
with open ("id_data.txt") as input_file:
  for line in input_file:
    line = line.split()
    ID = int (line[0])
    Sum = int (line[1])

    if ID in dict:
        dict [ID] += Sum
    else:
        dict [ID] = Sum
output_file = open ("id_SUMS.txt", "w")
for ID in sorted (dict):
   output_file.write ("Line ID : " + str (ID))
   output_file.write(", Sum : " + str (dict[ID]))
   output_file.write ("\n")
output_file.close ()
print("file has been updated")

If anyone can help me identify where my program is going wrong and how to fix it, to where it finds the sum of the numbers on the specific line, it would be greatly appreciated.

A: Sum should be:
Sum = sum(int(i) for i in line[1:])


text:
Q: Finding the correct combination in a 2D array after finding the first digit I'm having hard time coding this ... I want to find a certain combination of numbers in a 2D grid. This combination is already known and is stored in an ArrayList. The catch is that the combination can be completed from ANY of the 8 cardinal directions (stored as ints from 0 to 7) like a word search puzzle. I'm trying to find that direction but honestly I'm not sure where to go from here ...
[...] //This is only a part of the bigger code I'm working on

for (i = 0; i < grid.length; ++i){
    for (j = 0; j < grid[i].length; ++j){
        if (grid[i][j] == digits.get(0){   //Here I find the 1st digit of my number

        }
    }
}

Keep in mind that the number entered can be of ANY length and that the direction is only returned IF I get the whole number. I'm so lost literally any advice is appreciated, thanks.

A: for (i = 0; i < grid.length; ++i){
for (j = 0; j < grid[i].length; ++j){
    int gridItemIndex = digits.indexOf( grid[i][j] )
    {
        if( gridItemIndex != -1 )
        {
             // now you are sure grid[i][j] IS IN LIST
             // gridItemIndex tells THE INDEX NUMBER OF grid[i][j] in ArrayList(digits)
        }
    }
}

I hope this gets to close to what you are trying to say??
int gridItemIndex = digits.indexOf( grid[i][j] )
{
    if( gridItemIndex != -1 )
    {
         // now you are sure grid[i][j] IS IN LIST
         // gridItemIndex tells THE INDEX NUMBER OF grid[i][j] in ArrayList(digits)
    }
}

Deals with the case where you are trying to locate the existence and index number of grid[i][j] in digits ArrayList, And please don't -vefy my answer before not even discussing why and the end result of your expected combination is a bit blurry still, would be glad to help

A: I think the problem here is that you don't see the bigger picture. The below is your starting point, cleaned up a bit.
Now what I would do is write a method that checks the table in every direction for the length of your combination. Checking for north is basically doing grid[startingX][startingY--]. If you apply that logic to every direction and account for 'out of bounds'-errors, you will solve it in no time.
//2D array
    int[][] grid = new int[25][25];
    //Your combination
    List<Integer> combination = new ArrayList<>();

    //Loop over the 2D array to find your starting point
    for (int i = 0; i<25; i++) {
        for (int j = 0; j<25; j++) {

            if (grid[i][j] == combination.get(0)) { //If we find the first element of your combination
                //Check in all cardinal directions
                checkDirections(i, j);
            }
        }
    }


text:
Q: Huygens-principle Huygens principle states that every point on the wave front acts as a source. If it is true, then why can't a single source (let's say a bulb) illuminate a whole big room? Why is it dark after some distance from the bulb? According to him it should continue to infinite.
Where am I wrong?

A: Every point on a spherical wave front acts as a source of a new spherical wavelet.  The tangent surface to all of the wavelets becomes the new wavefront. And this process is repeated using the new wavefront to advance (propagate) the wave.
Note that the wavelets are spherical so their amplitude is reduced inversely to their radius as they propagate (as 1/ct or 1/r).  This causes the propagating wavefront's amplitude to be reduced in the same way.
So the spherical wave amplitude becomes lower as it propagates.
Note that if the original wave front was a plane wave there would be no reduction in amplitude as it propagates--the tangent surface is a plane--for why, see www.researchgate.net/publication/316994209 the link is given below.  Essentially in a planar wave there is a one to one correspondence of between points of the successive planar tangent surfaces, with spherical surfaces there is not.  The correspondence is between successive spherical elemental areas which grow in size as the radius increases.
See for Huygens' Principle in general:
http://farside.ph.utexas.edu/teaching/302l/lectures/node150.html
http://hyperphysics.phy-astr.gsu.edu/hbase/phyopt/huygen.html
https://www.physlink.com/education/askexperts/ae471.cfm
See my paper for a mathematical derivation:
https://www.researchgate.net/publication/316994209
or the update update
https://www.researchgate.net/publication/340085346

A:
Why is it dark after some distance from the bulb? According to him it
  should continue to infinite.

That's a great observation! I must have seen Huygen 100 times and never thought of this.
The basic answer is that Huygen's principle is mostly concerning the phase of the waves, in a way. He's talking about how the wave front propagates. This is what you see in the typical diagram consisting of arcs emanating from a point source.
The amplitude of the wave, which corresponds to the illumination in this case, is a function of its spread. This is actually baked into the principle, although you'd never know that from common explanations or diagrams.
A better illustration would have the arcs grow increasingly light as they move away from the source.


text:
Q: Access PCF VCAP_Services from Spring boot Angular App I am trying to deploy an Angular Application as a Jar ( Maven) in Pivotal Cloud foundary. I am trying to access the VCAP_SERVICES varialble in the PCF inside the application.
I was using the process.env.VCAP_SERVICES from the proxy.conf.js.
Since this is deployed and run as a Jar in the PCF, I think the node server is not started and the VCAP_SERVICES variable is not accessible. It was showing as "undefined".  I am looking for any pointers to access the VCAP_SERVICES from angular code. Can someone please help or give link to any blog/tutorials for this. Thank you.


text:
Q: Accessing lazy loaded property in NHibernate ASP.NET MVC3 Razor code I have a Post class:

public class Post
{
    ...
    public virtual IList<Comment> Comments { get; set; }
    ...
}

In mappings I set Comments as a ManyToOne reference. As we know by default it's set as lazy loaded.
In my Razor view script I want to check if post has any comment and if so, add a button that calls an action to get comments for that post via ajax and show them, by injecting html.
When I try to invoke something on Post.Comments in Razor (like Model.Comments.Count()) I recieve an exception saying that Session is not present. I know why that happens - because the lazy loading.
My question is how to handle these kind of situations? What are the 'best practices'?
Two solutions comes to my mind:
1) Set Comments as not lazy loaded - not ok since I get comments via ajax later and for this time I need only the Count of comments
2) Create a ViewModel class that contains information if post has comments or pass this via ViewBag.
What are your suggestions on this?
Thanks,
Bartek

A: Personally, I would go with option 2.
Create a ViewModel, include a property like HasComments and use that in your view instead of trying to evaluate Model.Comments.Count().

A: Why is your session ending so early?
You should keep it open still during render, for times like that.


text:
Q: Solidity contract not working I'm having trouble running my first solidity contract in remix ethereum and through web3 so I'm guessing something is wrong with my contract code:
pragma solidity ^0.4.0;

contract cntrct
{
  uint public aaa;

  function() payable public
  {
    create(msg.value);
  }

  function create(uint _value) internal
  {
    require(_value>0);
    aaa = _value;
  }

  function reader() view public returns(uint)
  {
    return aaa;
  }
}

I succesfully deployed the contract in both remix and web3. However, after sending a transaction to the contract, the aaa variable is still 0. What I want this code to do is update the aaa variable to the last deposited amount so I can read it later by calling the reader function. In remix it does not show any input field for the aaa variable. Also, in MetaMask transactions sent to the contract stay in a pending status even if they're already completed (balances updated in remix and tx in testRPC.)
In node I'm using the following line to try to execute the reader function but I'm unsure if this will work.
contract.methods.reader().call(0, (error, result) => { if(!error){console.log(result);}});

A: There's no reason to store the ether sent in a state variable unless you need to maintain a mapping of balances spread across multiple addresses. The total balance is held in the contract and is accessible with this.balance.
In addition, fallback functions are limited to 2300 gas. You can't write to storage (ie, update a state variable) within that limit. Your variable isn't updated because it's failing. See the second bullet point here for more info.

A: In solidity contract, you can read the value of public filed by calling field as a method. here, aaa()
I have deployed with mist browser under private network and send 10 ether to this contract successfully.


text:
Q: PLS-00103: Encountered the symbol "(" when expecting one of the following I am trying to create a table in Oracle DB and I am getting this error:
PLS-00103: Encountered the symbol "(" when expecting one of the following:
. , @ in <an identifier>
<a double-quoted delimited-identifier> partition subpartition

The create statement is the following:
set echo on
set term on
set pause off
set pages 5000
set serveroutput on size 99999
spool sqlResult.lst

declare
 --
wcont number :=0;

begin

CREATE TABLE schema.TABLE
       (ID NUMBER GENERATED BY DEFAULT AS IDENTITY,
       DOCUMENT1 VARCHAR2(50),
       DOCUMENT2 VARCHAR2(50),
       ID_CLIENT1 NUMBER,
       ID_CLIENT2 NUMBER,
       BDATEO DATE,
       FDATE DATE,
       ID_PROCESS VARCHAR2(100),
       TYPE VARCHAR2(50),
       CONSTRAINT tmp_pk PRIMARY KEY(ID));

wcont:=wcont+ sql%ROWCOUNT;

if  sql%ROWCOUNT > 1
  then
     RAISE_APPLICATION_ERROR(-20010,'ERROR');
  end if;
 --
  commit;
 --
  dbms_output.put_line('SUCCESS');
   --
  exception
       when others then
            rollback;
            dbms_output.put_line(sqlerrm);
end;
/
spool off
exit

I can't see where is the error because the only "(" are after new table name and I think it's mandatory.
Best regards!


text:
Q: Mirroring repository on an offline computer Here is my situation. I have a computer which cannot connect to the network. I have created a repository of it's code on our remote bitbucket instance (using my laptop). What is the easiest way to implement version control in a situation like this?
This is what I was thinking and have done so far.

*

*The master is on the remote bitbucket instance (point A)

*I have cloned master onto an external hard drive (point B)

*I have copied the .git folder from the hard drive onto the target machine (point C) at the root directory of the code (just like in the hard drive clone)

What's the best way to go about making commits? Let's say on the target machine I change some code and commit to that local repo. How can I then sync that with the hard drive repo (so that the local machines commits are latest) and then in turn sync that to master on the remote server?
Am I answering my own question in terms of the strategy of this?

A: You want to use git bundle. Docs and examples below.
https://git-scm.com/docs/git-bundle
https://git-scm.com/book/en/v2/Git-Tools-Bundling

A:
I have copied the .git folder...

This is never a good idea. Remember that any folder that contains a .git folder is itself a repository. To copy that repo, you can just do git clone /path/to/folder.


text:
Q: Viewing an object property's DebuggerDisplay Say I have the following two classes:
[DebuggerDisplay("Test={Test}")]
class Class1
{
    public string Test;
}

[DebuggerDisplay("obj={obj}")]
class Class2
{
    public Class1 obj;
}

class Program
{
    public static void Main(string[] args)
    {
        var c1 = new Class1() { Test = "test" };
        var c2 = new Class2() { obj = c1 };
    }
}

Is it possible to enable the debugger display of Class2 to show the debugger display of Class1? I.e., I would like hovering over c2 to reveal obj="test".

A: you can write in this style for your goal:
[DebuggerDisplay("{ToString()}")]
class Class1
{
    public string Test;
    public override string ToString()
    {
        return "Test=" + Test;
    }
}

[DebuggerDisplay("{ToString()}")]
class Class2
{
    public Class1 obj;
    public override string ToString()
    {
        return "obj=" + obj;
    }
}

internal class Program
{
    public static void Main(string[] args)
    {
        var c1 = new Class1() {Test = "test"};
        var c2 = new Class2() {obj = c1};
    }
}


text:
Q: Yahoo Finance API / URL not working: Python fix for Pandas DataReader Yahoo Finance URL has not been accessible using the Pandas DataReader's "yahoo" method since 16 May 2017. I have yet to test this fix-yahoo-finance: https://pypi.python.org/pypi/fix-yahoo-finance that was posted just yesterday, with the statement: "Yahoo! finance has decommissioned their historical data API".
EDIT August 2, 2017: I have since followed the steps in https://pypi.python.org/pypi/fix-yahoo-finance to: $ pip3 install fix_yahoo_finance --upgrade --no-cache-dir, upgraded pandas_datareader to work with "fix-yahoo-finance 0.0.6", and amended codes:
from pandas_datareader import data as pdr
import fix_yahoo_finance

data = pdr.get_data_yahoo('AAPL', start='2017-04-23', end='2017-05-24')

Note that the order of the last 2 data columns are 'Adj Close' and 'Volume' ie. not the previous format. For my purpose, they are simply reset to the original format:
cols = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close']
data.reindex(columns=cols)

A: I would recommend using Quandl. I'm not sure if Yahoo is going to be reliable after their acquisition.
In Quandl if you have multiple symbols you have to loop. Read the docs and do something like this:
    import quandl as qdl
    start_date = '2016-01-01'
    end_date = '2017-05-22'
    for symbol in symbols:

        quandldata = qdl.get_table("WIKI/PRICES",qopts={"columns":["date", "adj_close"]},
        ticker=symbol, date = {'gte': start_date,'lte' : end_date})
        # specify that the quandldata df has index col = 'date'
        quandldata = quandldata.set_index(["date"], drop=True)
        # rename col adj close to the respective symbol to prevent clash w/ same name for all cols
        quandldata = quandldata.rename(columns={'adj_close': symbol})
        df = df.join(quandldata)

A: import pandas_datareader.data as pdweb
from pandas_datareader import data as pdr
import fix_yahoo_finance # must pip install first
data = pdr.get_data_yahoo('SPY','2017-05-20','2017-05-23')
data = pdr.get_data_yahoo(['SPY','QQQ'],'2017-05-01','2017-05-23', as_panel=False,group_by = 'ticker')

A: I have followed the steps in https://pypi.python.org/pypi/fix-yahoo-finance to: $ pip3 install fix_yahoo_finance --upgrade --no-cache-dir and also upgraded pandas_datareader to be sure.
The "fix-yahoo-finance 0.0.6" worked well, for example BHP.AX:
from pandas_datareader import data as pdr
import fix_yahoo_finance

data = pdr.get_data_yahoo('BHP.AX', start='2017-04-23', end='2017-05-24')

Note that the order of the last 2 data columns are 'Adj Close' and 'Volume' ie. not the previous format. For my purpose, they are reset to the original format:
cols = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close']
data.reindex(columns=cols)

A: I like user3443068 answer as it's simple.
I also would suggest looking at using Google as your source as the yahoo instance is probably going to go through many deprecated versions given where the company's going.
def get_ret(tickers_ls, start_dt, end_dt):
        #create dataframe
        df_ret=pd.DataFrame()

        #get prices for all tickers
        for tk in tickers:
            p = wb.DataReader(tk, "google", start_date, end_date).Close
            df_ret_tmp = p.to_frame()['Close'].reset_index()
            df_ret_tmp['Ticker']=tk
        ## append
            df_ret=df_ret.append(df_ret_tmp)

        #pivot and get into single dataframe
        pivoted = df_ret.pivot(index='Date', columns='Ticker')
        pivoted.columns = pivoted.columns.droplevel(0)

        return pivoted


text:
Q: Proving $A$ is similar to $B$ when $\operatorname{adj} A$ is similar to $\operatorname{adj} B$ $A,B$ are two $6 \times 6$ real matrices and $A$ is invertible. I need to prove that if $\operatorname{adj} A$ is similar to $\operatorname{adj} B$ then $A$ is similar to $B$.
$\operatorname{adj}A = M^{-1}(\operatorname{adj}B) M$ but can't think of a direction to the solution?

A: Hint: use the relations
\begin{align}
A\operatorname{adj}A&=\det(A)I,\tag{1}\\
B\operatorname{adj}B&=\det(B)I\tag{2}
\end{align}
to prove first that $\det A=\det B$.
One way to do that: prove that
$$
\det A\ne 0\implies \det\operatorname{adj}A\ne 0\implies
\det\operatorname{adj}B\ne 0\implies \det B\ne 0.
$$
Then take the determinant of boths side in (1) and (2).


text:
Q: localStorage assignment vs. setItem() One of the first results from a Google search says that this syntax is to be used for localStorage:
localStorage.lastname="Smith";

MDN uses .setItem() and .getItem(), I suppose so that if the browser doesn't support localStorage, then you can add it using the technique defined there.
But since my program is only running on iOS, I guess my question is:
Is it ok to use
localStorage.lastname="Smith";

instead of:
window.localStorage.setItem("lastname","Smith");

A: Though both methods are valid JavaScript,
localStorage.lastName = "Smith";

assigning a value directly like above to a key can sometimes result in property conflicts.
window.localStorage.setItem("lastname","Smith");

On the other hand is a better practice to get into. MDN and most other resources recommend this method when working with Local-storage.


text:
Q: Using 'await' but still receiving this error: A second operation started... Use 'await' to ensure that When the user session ends, a popup shows up in my application and when the user clicks "Stay in the system", the RefreshTheUserSession action of the Account controller is evoked.
public async Task<ActionResult> RefreshTheUserSession(string UserId)//this will be called from the ajax timeout
{
      AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
      var myuser = await UserManager.FindByIdAsync(UserId);

      if (myuser != null)
      {
          await SignInManager.SignInAsync(myuser, false, false);
      }

        return null;
 }

Here is the AuthenticationManager property of the Account controller that comes by default by MVC application.
private IAuthenticationManager AuthenticationManager
 {
     get
     {
         return HttpContext.GetOwinContext().Authentication;
     }
 }

However, when the RefreshTheUserSession action is executed, I receive the following error:

A second operation started on this context before a previous asynchronous operation completed. Use 'await' to ensure that any asynchronous operations have completed before calling another method on this context. Any instance members are not guaranteed to be thread safe.

It recommends me to use await and I am using await. I have no idea why this is happening. Any ideas or leads?


text:
Q: Is there a way to upload, rename, then download a file in HTML? Is there any HTML and JavaScript code to have a user upload a file, then the code will rename it, and automatically download it to the user's computer? I would be doing this on repl, not on a server I have if that helps.
I will convert a .zip file to a .mcpack file and back.

A: To write and download files with JavaScript, use object URLS, Blobs, and  elements. To upload, use <input> type "file".
Example:

f. onchange=function () {
  oy.href=URL.createObjectURL(f.files[0])
  oy.download="yo new name new game here.html"
  oy.click()
  oy.href=""
};
<input type="file" id=f>


text:
Q: Problem with opacity in IE8 I try to solve a problem that appears in IE8. Html is very simple:

When I set (using jQuery) opacity of "#source" element with "0" in IE I can see the background of #overlay, not #imgcontainer > div, but why?
There is a javascript code:
$(function(){
    $("#source").css({
        opacity: "0",
    });
    $("#overlay").css({
        width: $(window).width(),
        height: $(window).height(),
        display: "block",
        opacity: "0.6"
    });

    $("#imgcontainer").css({
        zIndex: 2,
        position: "fixed",
        opacity: "1",
        left: "0",
        right: "0",
        top: "100px",
        display: "block"
    });
});

You can try live example on jsFiddle.
UPD:
After some experiments I found the solution. It's really html\css issue, so I made some refactoring of code and remove jQuery tag. Imagine we have such html murk up:

and the css styles:
body {
    background-color: #c8c8c8;
}

#d1 {
    background-color: #6c0922;
    width: 500px;
    border: 1px solid black;
    filter: alpha(opacity = 100);
}

#d2 {
    background-color: #146122;
    width: 350px;
    margin: 20px auto;
    border: 1px solid black;
}

#d3 {
    background-color: #0080c0;
    height: 100px;
    margin: 10px 65px;
    filter: alpha(opacity = 0);
    zoom: 1;
}

At first look all is ok, we expect that #d3 become transparent and we can see #d2 background(dark green). But not so simple in IE7\8. In IE we can see body!(grey) background through #d2 and #d1. All magic in #d1 you guessed it. When we remove filter: alpha(opacity = 100); all work correctly.
You can ask - but why you set opacity = 1 to the element which is non-transparent now? I don't know :). May be in some reason you should use this behavior. Very interesting and unexpected behavior.
You can play with this example in jsFiddle.

A: I had the same issue.  I did a lot of searching and reading and found IE8 doesn't use the css for opacity other browsers use.  Here is my CSS that I used for IE8:
#loading-div-background {
    display:none;
    position:absolute;
    top:0;
    left:0;
    background:gray;
    width:100%;
    height:100%;
    /* Next 2 lines IE8 */
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=75)";
    filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=75);
}

However, it still didn't work with position:fixed, but once I put in position:absolute it started working.

A: IE8 doesn't support the CSS attribute opacity you have to use an MS filter instead:
    opacity: "0",
    filter: alpha(opacity = 50); /*change value to suit your needs*/

That's not all though. This only works when the element is positioned, thankfully you have that already so it will work. For future reference if you don't have any position set, you can add zoom: 1 to the selector and it will work in IE :)


text:
Q: Reading 1/n chunk of text input at one time using InputStream in Java I want to read a text file and insert   tag every 1/n chunk of text. For example, if the text is d
 Hello world
 my name is hello kitty
 I am bored

and if n = 3, I want the output to be like:
<Tile> Hello World </Tile>
<Tile> my name is ... </Tile>
<Tile> I am bored </Tile>

I want the length of the characters in each tile approximately the same. So I want I did was this:
   int tileSize = 5;
   File file = new File(inputDir + filename);
   BufferedFileWriter bw = new BufferedFileWriter(new FileWriter(outputDir + filename);
   long totalLength = file.length();
   int tileLength = (int)(totalLength/(double)tileSize);
   byte[] b = new byte[tileLength];
   InputStream in = new FileInputStream(file);
   while(in.read(b) != -1) {
          bw.write("<TILE>" + Charset.defaultCharset().decode(ByteBuffer.wrap(b)) + "</TILE>");
   }
   bw.close();

I am doing this for multiple files (ex, 150 files), but this operation is somehow extremely slow. Something seems to be very inefficient. Could you give me any guidance in what might have caused this code to be slow or any better suggestion? Thanks!


text: Q: Need some hints and clarification to Problem 9, Section 46 in Munkres Topology The problem is shown in the image below. I solved part (a) and part (b). For part (c), I know why the map $Q$ is continuous, but I need some hints about how to prove that $G$ is continuous. Besides, I am not sure why the image of the map $G$ lies in $C(X,Y)$ (in part (b)). This is true if $g$ is a continuous map. However, showing that $g$ is continuous is what I ultimately need to do in part (c), and if I don't know that the image of the map $G$ lies in $C(X,Y)$, I can't use Theorem 46.11 to say that "$g$ is continuous because $G$ is continuous". This seems to be a circular argument to me. It would be of great help if someone can explain these things clearly to me.


text:
Q: Properly joining in Hibernate I have the following problem with Hibernate:
I have got two classes:
1) Sprawozdanie
   <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                                   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
 <class name="com.mg.shared.Sprawozdanie" table="sprawozdania">
  <id column="spr_id" name="id" type="int">
    <generator class="increment"/>
  </id>
  <property column="spr_od" generated="never" lazy="false" name="Od" type="date"/>
  <property column="spr_do" generated="never" lazy="false" name="Do" type="date"/>
  <property column="spr_typ_okresu" generated="never" lazy="false"
   name="TypOkresu" type="string"/>
  <property column="spr_kurs" generated="never" lazy="false" name="Kurs" type="float"/>
  <property column="spr_dsp_nazwa" generated="never" lazy="false"
   name="NazwaDysponenta" type="string"/>
  <property column="spr_dsp_adres" generated="never" lazy="false"
   name="AdresDysponenta" type="string"/>
  <property column="spr_dsp_regon" generated="never" lazy="false"
   name="RegonDysponenta" type="string"/>
  <property column="spr_dsp_wojew_kod" generated="never" lazy="false"
   name="KodWojDysponenta" type="string"/>
  <property column="spr_dsp_wojew_nazwa" generated="never" lazy="false"
   name="NazwaWojDysponenta" type="string"/>
  <property column="spr_dsp_powiat_kod" generated="never" lazy="false"
   name="KodPowiatDysponenta" type="string"/>
  <property column="spr_dsp_powiat_nazwa" generated="never" lazy="false"
   name="NazwaPowiatDysponenta" type="string"/>
  <property column="spr_dsp_gmina_kod" generated="never" lazy="false"
   name="KodGminaDysponenta" type="string"/>
  <property column="spr_dsp_gmina_nazwa" generated="never" lazy="false"
   name="NazwaGminaDysponenta" type="string"/>
  <property column="spr_dsp_typ_gminy_kod" generated="never"
   lazy="false" name="KodTypGmDysponenta" type="string"/>
  <property column="spr_dsp_typ_gminy_nazwa" generated="never"
   lazy="false" name="NazwaTypGmDysponenta" type="string"/>
  <property column="spr_dsp_zwiazek_jst_kod" generated="never"
   lazy="false" name="KodZwJTSDysponenta" type="string"/>
  <property column="spr_dsp_typ_zwt_kod" generated="never" lazy="false"
   name="KodTypZwDysponenta" type="string"/>
  <property column="spr_dsp_instytucja_nadrzedna" generated="never"
   lazy="false" name="InstytucjaNadrzednaDysponenta" type="string"/>
  <property column="spr_dsp_nazwa_waluty" generated="never" lazy="false"
   name="NazwaWalutyDysponenta" type="string"/>
  <property column="spr_dsp_symbol_waluty" generated="never"
   lazy="false" name="SymbolWalutyDysponenta" type="string"/>
  <property column="spr_stan" generated="never" lazy="false" name="Stan" type="string"/>
  <property column="spr_data_utworzenia" generated="never" lazy="false"
   name="DataUtworyenia" type="date"/>
  <property column="spr_data_zaakceptowania" generated="never"
   lazy="false" name="DataYaakceptowania" type="date"/>
  <property column="spr_data_zatwierdzenia" generated="never"
   lazy="false" name="DataYatwierdyenia" type="date"/>
  <property column="spr_data_odrzucenia" generated="never" lazy="false"
   name="DataOdryucenia" type="date"/>
   <property column="spr_data_edycji" generated="never" lazy="false"
   name="DataEdycji" type="date"/>
  <many-to-one class="com.mg.spr.shared.User" column="spr_uz_login"
   lazy="false" name="Uzytkownik" update="false"/>
  <many-to-one class="com.mg.spr.shared.Officer" column="spr_dsp_id"
   lazy="false" name="Dysponent" update="false"/>
  <many-to-one class="com.mg.spr.shared.TypSprawozdania" column="spr_typ_spr_nazwa"
   lazy="false" name="TypSpr" update="false"/>
  <set name="PozycjeSprawozdania" table="pozycje_sprawozdan" cascade="all" lazy="false" >
   <key column="pspr_spr_id"  not-null="true" update="true"/>
   <one-to-many class="com.mg.shared.PozycjaSprawozdania" />
   </set>
 </class>
</hibernate-mapping>

2) PozycjaSprawozdania
    <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                                   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
 <class name="com.mg.shared.PozycjaSprawozdania" table="pozycje_sprawozdan">
  <id column="pspr_id" name="id" type="int">
    <generator class="increment"/>
  </id>
  <property column="pspr_nr_tabeli" generated="never" lazy="false" name="NrTabeli" type="int"/>
  <property column="pspr_nr_wiersza" generated="never" lazy="false" name="NrWiersza" type="int"/>
  <property column="pspr_dzi_kod" generated="never" lazy="false"
   name="DzialKod" type="string"/>
  <property column="pspr_roz_kod" generated="never" lazy="false"
   name="RozdzialKod" type="string"/>
  <property column="pspr_par_kod" generated="never" lazy="false"
   name="ParagrafKod" type="string"/>
  <property column="pspr_par_typ" generated="never" lazy="false"
   name="ParagrafTyp" type="string"/>
  <property column="pspr_zad_kod" generated="never" lazy="false"
   name="ZadanieKod" type="string"/>
  <property column="pspr_zfin_kod" generated="never" lazy="false"
   name="ZrodloFinansowaniaKod" type="string"/>
  <property column="pspr_dzi_nazwa" generated="never" lazy="false"
   name="DzialNazwa" type="string"/>
  <property column="pspr_roz_nazwa" generated="never" lazy="false"
   name="RozdzialNazwa" type="string"/>
  <property column="pspr_par_nazwa" generated="never" lazy="false"
   name="ParagrafNazwa" type="string"/>
  <property column="pspr_zad_nazwa" generated="never" lazy="false"
   name="ZadanieNazwa" type="string"/>
  <property column="pspr_zfin_nazwa" generated="never" lazy="false"
   name="ZrodloFinansowaniaNazwa" type="string"/>
  <property column="pspr_kolumna_01" generated="never" lazy="false"
   name="Kolumna01" type="string"/>
  <property column="pspr_kolumna_02" generated="never" lazy="false"
   name="Kolumna02" type="string"/>
  <property column="pspr_kolumna_03" generated="never" lazy="false"
   name="Kolumna03" type="string"/>
  <property column="pspr_kolumna_04" generated="never" lazy="false"
   name="Kolumna04" type="string"/>
  <property column="pspr_kolumna_05" generated="never" lazy="false"
   name="Kolumna05" type="string"/>
  <property column="pspr_kolumna_06" generated="never" lazy="false"
   name="Kolumna06" type="string"/>
  <property column="pspr_kolumna_07" generated="never" lazy="false"
   name="Kolumna07" type="string"/>
  <property column="pspr_kolumna_08" generated="never" lazy="false"
   name="Kolumna08" type="string"/>
  <property column="pspr_kolumna_09" generated="never" lazy="false"
   name="Kolumna09" type="string"/>
  <property column="pspr_kolumna_10" generated="never" lazy="false"
   name="Kolumna10" type="string"/>
  <property column="pspr_kolumna_11" generated="never" lazy="false"
   name="Kolumna11" type="string"/>
  <property column="pspr_kolumna_12" generated="never" lazy="false"
   name="Kolumna12" type="string"/>
  <property column="pspr_kolumna_13" generated="never" lazy="false"
   name="Kolumna13" type="string"/>
  <property column="pspr_kolumna_14" generated="never" lazy="false"
   name="Kolumna14" type="string"/>
  <property column="pspr_kolumna_15" generated="never" lazy="false"
   name="Kolumna15" type="string"/>
  <property column="pspr_kolumna_16" generated="never" lazy="false"
   name="Kolumna16" type="string"/>
  <property column="pspr_kolumna_17" generated="never" lazy="false"
   name="Kolumna17" type="string"/>
  <property column="pspr_kolumna_18" generated="never" lazy="false"
   name="Kolumna18" type="string"/>
  <property column="pspr_kolumna_19" generated="never" lazy="false"
   name="Kolumna19" type="string"/>
  <property column="pspr_kolumna_20" generated="never" lazy="false"
   name="Kolumna20" type="string"/>
  <property column="pspr_kolumna_21" generated="never" lazy="false"
   name="Kolumna21" type="string"/>
  <property column="pspr_kolumna_22" generated="never" lazy="false"
   name="Kolumna22" type="string"/>
  <property column="pspr_kolumna_23" generated="never" lazy="false"
   name="Kolumna23" type="string"/>
  <property column="pspr_kolumna_24" generated="never" lazy="false"
   name="Kolumna24" type="string"/>
  <property column="pspr_kolumna_25" generated="never" lazy="false"
   name="Kolumna25" type="string"/>
  <property column="pspr_kolumna_26" generated="never" lazy="false"
   name="Kolumna26" type="string"/>
  <property column="pspr_kolumna_27" generated="never" lazy="false"
   name="Kolumna27" type="string"/>
  <property column="pspr_kolumna_28" generated="never" lazy="false"
   name="Kolumna28" type="string"/>
  <property column="pspr_kolumna_29" generated="never" lazy="false"
   name="Kolumna29" type="string"/>
  <property column="pspr_kolumna_30" generated="never" lazy="false"
   name="Kolumna30" type="string"/>

  <many-to-one class="com.mg.shared.Sprawozdanie" column="pspr_spr_id"
   lazy="false" name="Sprawozdanie" update="false" insert="false"/>

 </class>
</hibernate-mapping>

I use a Jasperreports to generate reports. Some of data is in Sprawozdanie and some is in PozycjaSprawozdania. When I am using this query:
listOfData = session.createQuery("Select spr from Sprawozdanie spr left join fetch spr.PozycjeSprawozdania").list();

I recive this error:
51142 [btpool0-2] ERROR org.hibernate.LazyInitializationException - failed to lazily initialize a collection, no session or session was closed

A: I was getting the same error a while back on my project. Turned out that in one of the entities I had forgotten to assign an annotation. In your case that would be in the XML mapping, did you miss a relationship mapping somewhere? Also, try changing the fetch type on all the relationships to eager to see if the problem goes away. if the problem does go away, change the relationships back to lazy one by one till something breaks.


text:
Q: Evernote oAuth error php (oauth ) while I am trying to run PHP SDK for evernote it gives following error
The PHP OAuth Extension is not installed !!
any help??
I am able to successfully create note using EDAMTest.php but it doesn't ask for credentials so if any one use that code every note comes in my account..

A: Oh and (shameless auto-promo) you could also use a ready-to-use vagrant box : laurent.sarrazin.io/2014/04/a-vagrant-box-for-the-evernote-php-sdk.html

A: Maybe you need to install oauth?
I'm sorry, I don't use Evernote extension, so I don't know what is EDAMTest.php..
Try to use this solution(if you use Windows) or find a way set up OAUTH for linux.

A: It means that the oauth extension is not loaded.
I'd say that you did not configure the extension in the cli php.ini.
Find the location of the php.ini by doing this :
php -i | grep 'Configuration File'

Add the oauth extension at the end of the file.
That should now work.


text:
Q: browsers send Options instead of Post after changing http header /*set the response header*/
    Form responseHeaders = (Form) getResponse().getAttributes().get("org.restlet.http.headers");
    if (responseHeaders == null) {
        responseHeaders = new Form();
        responseHeaders.add("Access-Control-Allow-Origin", "*");
        responseHeaders.add("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE");
        getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);
    }

I added this in my restlet 2.0 code to allow for cross domain access, this does make the first GET to work on page load, but when I try to do POST later(with backbone model.save()), browser sends Options with a null entity instead.
It does send the right POST if I did not add the code above
This happens on Opera, Firefox, and Chrome (works fine if I start chrome with --disable-web-security), so i assume it is still a browser security issue, could anyone provide explanations on why this would happen and what might be the fix?

A: From What is the HTTP OPTIONS method?

This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.

I have fought several times with CORS issues and I have always solved them with the method of try and error my suggestion for your case is add OPTIONS to your Allow Methods :
"Access-Control-Allow-Methods": "POST, GET, PUT, DELETE, OPTIONS"

And make your server to respond to OPTIONS request with an *, in Sinatra is like this:
options "/*" do
  "*"
end

Update
For the new issue explained in the comment about the error header field Content-Type is not allowed by Access-Control-Allow-Headers.
Try to add another CORS header:
"Access-Control-Allow-Headers": "origin, x-requested-with, content-type"

A: Thanks for fguillen's advice, have some googling I found the way that would work
/*set the response header*/
    Form responseHeaders = (Form) getResponse().getAttributes().get("org.restlet.http.headers");
    if (responseHeaders == null) {
        responseHeaders = new Form();
        responseHeaders.add("Access-Control-Allow-Origin", "*");
        responseHeaders.add("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
        responseHeaders.add("Access-Control-Allow-Headers", "Content-Type");
        getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);
    }

so this is the right code to inject for cors in Restlet 2.0
do not miss responseHeaders.add("Access-Control-Allow-Headers", "Content-Type"); at least when you are dealing with backbone

A: Slightly off topic but I thought it might be useful for somebody and save time.
I was having CORS issues with uwsgi server and backbone. This is part of my uwsgi.ini file which seem  to work for POSTing.
[uwsgi]
add-header = Access-Control-Allow-Origin: *
add-header = Access-Control-Allow-Headers: origin, x-requested-with, content-type
add-header = Access-Control-Allow-Methods: POST,GET,PUT,OPTIONS,DELETE
add-header = Content-Type: application/json; charset=UTF-8
add-header = Accept: application/json

As mentioned by fguillen server needs to reply '*' for OPTIONS request.

A: Below code can be used to resolve cross domain issue in Restlet 2.0
Form responseHeaders = (Form) getResponse().getAttributes().get("org.restlet.http.headers");
if (responseHeaders == null) {
    responseHeaders = new Form();
    getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);
}
responseHeaders.add("Access-Control-Allow-Origin", "*");
responseHeaders.add("Access-Control-Allow-Methods", "GET,DELETE,PUT,POST,OPTIONS");
responseHeaders.add("Access-Control-Allow-Headers", "Content-Type");
responseHeaders.add("Access-Control-Allow-Credentials", "false");
responseHeaders.add("Access-Control-Max-Age", "60");

A: Perhaps this link could give you some hints about how CORS works and its support in Restlet with the CorsFilter:

*

*Understanding and using CORS - https://templth.wordpress.com/2014/11/12/understanding-and-using-cors/
Hope it helps you,
Thierry

A: On a different content the code give below works for Restlet 2.1 upwards.
import org.restlet.engine.header.Header;

private static final String HEADERS_KEY = "org.restlet.http.headers";

@SuppressWarnings("unchecked")

static Series<Header> getMessageHeaders(Message message) {

ConcurrentMap<String, Object> attrs = message.getAttributes();

Series<Header> headers = (Series<Header>) attrs.get(HEADERS_KEY);

if (headers == null) {

         headers = new Series<Header>(Header.class);

     Series<Header> prev = (Series<Header>)

          attrs.putIfAbsent(HEADERS_KEY, headers);

    if (prev != null) { headers = prev; }

     }

   return headers;

}
//The JSON Query "GET"
@Get("json")

 public Representation toJson()

  {

   getMessageHeaders(getResponse()).add("Access-Control-Allow-Origin", "*");

   getMessageHeaders(getResponse()).add("Access-Control-Allow-Methods", "POST,GET,OPTIONS");

   getMessageHeaders(getResponse()).add("Access-Control-Allow-Headers", "x-requested-with,Content-Type");

   getMessageHeaders(getResponse()).add("Access-Control-Allow-Credentials", "true");

   getMessageHeaders(getResponse()).add("Access-Control-Max-Age", "60");

  return get();
}