text:
Q: How to use the callback method with a c++ directshow sample grabber I have a sample grabber hooked into my directshow graph, based on this example http://msdn.microsoft.com/en-us/library/dd407288(VS.85).aspx the problem is that it uses one shot and buffers.  I want to continuously grab samples, and i'd rather have a callback than i guess polling for the samples.
How do use the SetCallback method?
SetCallback(ISampleGrabberCB *pCallback, long WhichMethodToCallback)

how do I point pCallback to my own method?

A: I come from a c# background, and thought that at some level i could just pass a reference to a method.  This doesn't seem to be case.  Instead it requires you create a class the implements its interface that defines the method that it will call.  You then pass an instance of the class to the filter in the SetCallback method.  Certainly seems long winded in comparison to a delegate or lambda expression
Here is an example of a class implementing ISampleGrabberCB
class SampleGrabberCallback : public ISampleGrabberCB
{
public:
    // Fake referance counting.
    STDMETHODIMP_(ULONG) AddRef() { return 1; }
    STDMETHODIMP_(ULONG) Release() { return 2; }

    STDMETHODIMP QueryInterface(REFIID riid, void **ppvObject)
    {
        if (NULL == ppvObject) return E_POINTER;
        if (riid == __uuidof(IUnknown))
        {
            *ppvObject = static_cast<IUnknown*>(this);
             return S_OK;
        }
        if (riid == __uuidof(ISampleGrabberCB))
        {
            *ppvObject = static_cast<ISampleGrabberCB*>(this);
             return S_OK;
        }
        return E_NOTIMPL;
    }

    STDMETHODIMP SampleCB(double Time, IMediaSample *pSample)
    {
        return E_NOTIMPL;
    }

    STDMETHODIMP BufferCB(double Time, BYTE *pBuffer, long BufferLen)
    {
        return E_NOTIMPL;
    }
};


text:
Q: Adding multiple levels in game created with JSON For one of my school projects, I have to create a game with Javascript. My Javascript experience is very minimal, and therefore I'm really stuck on how to create multiple levels within my game. With JSON, I load blocks for Mario to walk on:
createBlocks: function () {
        console.log('game -> createBlocks');

        $.getJSON('js/boxes.json', function (data) {

            data.boxes.level1.forEach(function (blockData) {

                this.stage.removeChild(this.block.el);

                var block = new Block(blockData);
                this.block.push(block);
                this.stage.addChild(block.el);

            }.bind(this));
        }.bind(this));
    }

With the function "createStars" the game loads another JSON. My goal is to have the game switch to another level with every 5 stars being collected. What is the best way to create this with JSON?
My JSON file for the blocks are created as follow:
{
"boxes": {
    "level1": [
        {
            "x": 0,
            "y": 115,
            "width": 25,
            "height": 25
        },
        {
            "x": 25,
            "y": 115,
            "width": 25,
            "height": 25
        }
    ],
    "level2": [
        {
            "x": 0,
            "y": 95,
            "width": 25,
            "height": 25
        }
    ]
}
}

Please let me know if you need my complete code to answer my question? I can also give a link to the game as it currently is hosted on my own site: http://school.carlavanloon.com/cp/
Furthermore, I'd like the game to stop the time after collecting 20 stars. This will then be the end time for the user of the game.
Many thanks in advance for your reply. And please let me know if I need to give any additional information.

A: Instead of making your json file around "boxes" you should design the json structure top down,
first load game json, which contains level objects - which contain boxes arrays etc. ie. something like this
var json = {
    "game_data": {
    "some_global_settings" : {"game_speed": 30, "theme": "dark"},
    "level1": {
        "boxes": [
         {
            "x": 0,
            "y": 115,
            "width": 25,
            "height": 25
         },
         {
            "x": 25,
            "y": 115,
            "width": 25,
            "height": 25
         }
        ],
        "stars": [
         {
            "x": 0,
            "y": 50,
            "width": 25,
            "height": 25
         },
         {
            "x": 125,
            "y": 120,
            "width": 25,
            "height": 25
         }
        ],
        "player_position" : {"x": 0,"y": 50},
        "victory_condition" : {"stars_required" : 5, "time_limit" : "10min"}
       },
       "level2": {"same structure as above with different data" : 1}

    }
    }

and then make a level builder function which picks a level object and creates everything in it. To reload a new level, check the number of stars remaining, if its 0, call your createLevel(gamelevel) with n+1 for building the next level.
below is pseudo code sample.
Every time user collects a star, you will check if it was the last star required, and if so, increment the level counter and call level builder function which could be something like this
function buildLevel( levelNr ) {
    var gdata = json.game_data["level"+levelNr];
    //check if next level exists in game_data object
    if (!gdata) {
        finishGame();
        return false;
    }

    //next level data exists, so build whats in it
    //clear level from previous stuff
    clearLevel();//perhaps replace canvas with new one

    createBoxes( gdata.boxes);
    createStars( gdata.stars);
    createPlayer( gdata.player_position);

    //everything is ready, add listeners / timers etc, and start the game
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to using oracledataadapter with transaction? I use a method to gettable using a Select statiments.When i use a select statiment using a link database i got error (ORA-01453 SET TRANSATION must be first statement of transation.)
I know solition but i cant use Transaction methot with Oracledataadapter.
I want to use Commit() ... Rollback().
This is my code:
private System.Data.DataTable GetDataTable_(string SqlStatement, bool fromProcCall)
        {

            OracleConnection Con = new OracleConnection();
            try
            {
                Con = Connection();
                OpenConnection(Con, fromProcCall);

                //-----------------------------------------
                DateTime startTime = DateTime.Now;
                //-----------------------------------------
                DataSet ds = new DataSet();

                OracleDataAdapter sda = new OracleDataAdapter(SqlStatement, Con);
                sda.Fill(ds, "tbl1");
                //-----------------------------------------
                if (!fromProcCall)
                    DurationOfIfsAction = DateTime.Now.Subtract(startTime).Milliseconds;
                else
                    DurationOfFirstIfsAction = DateTime.Now.Subtract(startTime).Milliseconds;
                //-----------------------------------------

                CloseConnection(Con);
                return ds.Tables[0];
            }
            catch (Exception ex)
            {
                if (Con != null)
                {
                    try
                    {
                        CloseConnection(Con);
                    }
                    catch (Exception) { }
                }
                throw new Exception("ERROR[" + ex.Message + "]");
            }
        }

A: Basically, you could do something like this:
oraConn = new OracleConnection("CONNECTION STRING");
oraConn.Open();

//Command with transaction
OracleCommand oraCom = oraConn.CreateCommand();
oraCom.CommandText = "INSERT QUERY";
oraCom.Transaction = oraCom.Connection.BeginTransaction(IsolationLevel.ReadCommitted);

//Execute
if (oraCom.Connection.State == ConnectionState.Closed)
{
      oraCom.Connection.Open();
}

oraCom.ExecuteNonQuery();

//Commit / Rollback
oraCom.Transaction.Commit(); // or oraCom.Transaction.Rollback();

To use this with DataAdapter, the concept is the same: Create the transaction setting the DataAdapter.SelectCommand.Transaction and then you can control with Commit() and Rollback().


text:
Q: Wordpress Advanced Search - Remember what was picked I'm creating a Wordpress Advanced form where on the home page the user has 3 fields to select from, then they hit submit and it goes to another page.
However when it gets to that page it shows the results but the same fields on that page don't remember what was selected.
Is there a way to achieve this, so it remembers and continues to remember until they leave that page?
I've been researching it but not even sure what to search for?...
EDIT
Been asked to add my code to help explain it;
<form method="post" class="form_search" action="<?php bloginfo('url');?>/job-search/" >
<label>
    Job Title/Keywords
    <input type="text" name="s" class="search_job_title" placeholder="e.g. Truck Driver">
</label>
<label>
    Sector
    <select name="job-sector">
        <option disabled selected value> -- select an option -- </option>
        <?php
            $terms = get_terms( 'job-sector' );
            if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
                foreach ( $terms as $term ) {
                    echo '<option>' . $term->name . '</option>';
                }
            }
            ?>
    </select>
</label>
<label>
    Location
    <input type="text" name="job-location" class="search_job_location" placeholder="e.g. Manchester">
</label>
<label>
    <input type="submit" class="search_submit" value="Search">
    <!-- <input type="hidden" name="post_type" value="jobs-board"> -->
</label>
</form>

A: You need to add POST variables to the form:
<form method="post" class="form_search" action="<?php bloginfo('url');?>/job-search/" >
<label>
    Job Title/Keywords
    <input type="text" name="s" class="search_job_title" placeholder="e.g. Truck Driver" value="<?php echo isset($_POST["s"])?esc_attr($_POST["s"]):'';?>" >
</label>
<label>
    Sector
    <select name="job-sector">
        <option disabled selected value> -- select an option -- </option>
        <?php
            $terms = get_terms( 'job-sector' );
            if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
                foreach ( $terms as $term ) {
                    echo '<option value="' . $term->name . '"
                    '.(isset($_POST["job-sector"]) and urldecode($_POST["job-sector"])==$term->name)?'selected':''.'>' . $term->name . '</option>';
                }
            }
            ?>
    </select>
</label>
<label>
    Location
    <input type="text" name="job-location" class="search_job_location" placeholder="e.g. Manchester" value="<?php echo isset($_POST["job-location"])?esc_attr($_POST["job-location"]):'';?>">
</label>
<label>
    <input type="submit" class="search_submit" value="Search">
    <!-- <input type="hidden" name="post_type" value="jobs-board"> -->
</label>
</form>


text:
Q: VB stand alone application or ASP web application I have experience developing software and web applications and I have decided to do some freelance work on the side. Well, I met with my first client and they are requesting a relatively simple, custom system that (without being long winded) tracks client's paperwork as it progresses through the business's different manual processes. It is a small business that has about 10 employees, but all of the employees will interact with the client's paperwork, therefore everyone would need access to the new system. When I say 'track' I literally mean that the employees will 'check as complete' on a simple page the increases a progress bar at different stages for the paperwork. Now I am %110 capable of coding the custom system that meets their needs, but I am unsure about how I should go about doing it.
The information that is being tracked in the new system and stored in the DB is confidential information that they are very protective of. My main question is how should I be developing this to be as secure as I can?
-They have their own server in house, so should I develop an application (VB and SQL) for the server and require employees to log on remotely to use it? Can more than one person access/use the application at a time?
-Or should I develop a web application (ASP.Net/VB and SQL) that is only accessible on their network to their employees? They plan to expand offices, could they set up a VPN to access the site?
I'm leaning towards a web application, but I have not done too much in term of security. Basically I'm looking for pros and cons for either option or any suggestions on what I should.
PS, stackoverflow is awesome! Long time user, first time poster!

A: If you want to develop using vb & sql you have to consider that:

*

*You need to have real ip

*Your system will communicate threw certain port and you have to handle the security measure for letting certain port opened in your server.

*You should have good knowledge in network programming

If you want to develop using asp.net you have to consider that:

*

*in case only office employees will use the system, you can develop against users in Active Directory and for outside users with username and password with SSL connection or vpn

for preventing more than one person access the file you can simply add column 'locked' in case file is being used.

A: Well im not a web fan (I suck) ive seen too many security issues go with it...i.e Lulzsec, but i do very much love VB apps.
So I would definetely recommend a VB app connected to a MSSQL database (coz it's easy to configure and havent seen any security exploits yet),my Chinese friend told me there is a way to access MySQL free databases.Now, allow remote access but make sure your Windows Firewall is also configured properly do look at all angles of security.
If I remember well there is an option in MSSQL to specify the IP addresses or is it MAC addresses that can access the DB so maybe input all of the 10 employees' IP addresses assuming they are static,if they are dynamic (DHCP) don't bother. And ask them to make the IP address of the server where you will host the DB on static.
If only 10 employees use the DB then limit the connections to 10. For now develop this when it comes to VPN you can make a Remote version of the App im sure that will come later right now focus on the basics. Also use Dotfuscator when you are publishing the app I heard it is very good.N also im suggesting the document/work order is received at the reception so that user will check in the document with specifics...if they are passing on the work order to the next user they should select the user and then THAT user may enter some sort of verification code unique to the user...im sure you can envision the rest from here. Now do I also get a cut from this?lol

A: I've been doing the same for years now, and I always take the website side, this days I go width ASP.NET MVC 4, it's easier, everything in their place and extremely easier to test and maintain.
The web application has a very big advantage to any standalone windows application, you deploy and upgrade only one application instead to maintain all the different versions once you start deploying windows apps, and they are harder to debug once you start to having different machines with different versions and so on...
so, Web or Win app = Web app, always!
All you need is a server that run IIS and set it up for using Active Directory (Visual Studio has that project already, simply create an ASP.NET MVC and choose the "intranet" template), it will set up everything for you, and all you need later is tweak the Active Directory connection string.
I also use a self-signed SSL to protect data between client and server, as I also make the apps available outside the office without VPN needed, as long as they login with their secure AD credentials.
And... audit everything into a secondary database, every action performed by a user since they login until they logout, every view, update or creating data witch .NET makes it simple if you create your Logging method to simple log messages and Stack messages on errors.
This will greatly benefit your employer and you when something goes wrong.

A: I would say to go with web application. Advantage using web application is, if they want to expand bussiness .. same can you do with you WebApp. But choose .Net over VB, going with latest techonology will help you resolve current challanges.


text:
Q: WebView loading page Android My app begins by loading a webpage as a WebView on onCreate. Should I extend this into a new thread since it may hang for a bit? Or at least a way to show that the page is still loading. It will display as white for a few seconds occasionally.
Also, is there a way to prevent the page from reloading on orientation change?

A: the webview handles threading itself, so you don't need to worry about that.
you can register callbacks for when the page starts and finishes loading. it's up to you to put up a progress bar, or whatever you want. see WebChromeClient.onProgressChanged() for details. here's a good post that gives some details.
you can add something to your manifest to tell the system you don't care about orientation changes. add the following to your activity definition,
android:configChanges="orientation"

the other option is to lock your app into one orientation or the other,
android:screenOrientation="portait"

A: Ad 1.
I have not (and should not) do that in separate thread.
WebView progress bar - Android WebView progress bar
Ad 2. you can block orientation changing by adding android:screenOrientation="portait" or "landscape" to declaration of your Activity in manifest.

A: You should use Progress Dialog. Show dialog till load the web page to the WebView.
public final class MyWebview extends Activity {

 private static final int DIALOG2_KEY = 1;
 private ProgressDialog pd = null;
 private static final String  AmitBlog="YOUR URL";
 private WebView webView;
 @Override
 protected void onCreate(Bundle icicle) {
  super.onCreate(icicle);
  setContentView(R.layout.main);
  pd = new ProgressDialog(this);
  webView = (WebView) findViewById(R.id.webview);
  webView.setWebViewClient(new HelpClient());
  webView.getSettings().setBuiltInZoomControls(true);

  /** Showing Dialog Here */
  showDialog(DIALOG2_KEY);
 }

 @Override
 protected void onResume() {
                super.onResume();
  LoadView();
 }

 private void LoadView()
 {
  webView.loadUrl(AmitBlog);
 }

 /** Its very important while navigation hardware back button if we navigate to another link .Its like a Stack pop of all the pages you visited in WebView */
 @Override
 public boolean onKeyDown(int keyCode, KeyEvent event) {
  if (keyCode == KeyEvent.KEYCODE_BACK) {
   if (webView.canGoBack()) {
    webView.goBack();
    return true;
   }
  }
  return super.onKeyDown(keyCode, event);
 }

/** WebViewClient is used to open other web link to the same Activity. */

  private final class HelpClient extends WebViewClient {
  @Override
  public void onPageFinished(WebView view, String url) {
   setTitle(view.getTitle());

   /** Dismissing Dialog Here after page load*/
   dismissDialog(DIALOG2_KEY);
  }

  @Override
  public boolean shouldOverrideUrlLoading(WebView view, String url) {
   if (url.startsWith("file")) {
    return false;
   } else{
    view.loadUrl(url);
    return true;
   }
  }
 }

 @Override
 protected Dialog onCreateDialog(int id) {
  switch (id)
  {
  case DIALOG2_KEY:
  {
   pd.setMessage(getResources().getString(R.string.Loading));
   pd.setIndeterminate(true);
   pd.setCancelable(false);
   return pd;
  }
  }
  return null;
 }
}


text:
Q: Using Ising model to find the equilbrium situation time dependant I'm very new to python so my code may be messy. I was trying to do this physics homework, using the Ising model, where an array of 16x16 is set with a spin value (-1 or 1) for each cell. Then, using mcmove(config,iT), the equilibrium situation is found for a given temperature, using calcMag(config). The program also computes the total magnetization for each situation.
My problem is that I have achieved the animation of the different arrays (using matplotlib.animation.ArtistAnimation), but I would like to animate the magnetization too. My ultimate goal would be to have the six subplots animated and with every frame syncronized: the array for each temperature and its magnetization value at the same frame for the three temperatures.
Here's my code (the previous definitions can be skipped, I think my problem is inside the loop when plotting the magnetization):
import numpy as np
from numpy.random import rand
import matplotlib.pyplot as plt
import matplotlib.animation as animation

def initialstate(N):
    '''Generates a random spin configuration for initial conditions'''
    state=2*np.random.randint(2,size=(N,N))-1
    return state

def mcmove(config,beta):
    '''Monte Carlo move using Metropolis algorithm'''
    for i in range(N):
        for j in range(N):
            #select random spin for NxN system
            a=np.random.randint(0,N)
            b=np.random.randint(0,N)
            s=config[a,b]
            #calculate energy cost of this new configuration (the % is for calculation of periodic boundary conditions)
            nb=config[(a+1)%N,b] + config[a,(b+1)%N]+config[(a-1)%N,b]+config[a,(b-1)%N]
            cost = 2*s*nb
            #flip spin or not, depending on the cost and its Boltzmann factor
            ## (acceptance probability is given by Boltzmann factor with beta=1/kBT)
            if cost<0:
                s*=-1
            elif rand() < np.exp(-cost*beta):
                s*=-1
            config[a,b]=s
    return config

def calcEnergy(config):
    '''Energy of a given configuration'''
    energy = 0
    for i in range(len(config)):
        for j in range(len(config)):
            S = config[i,j]
            nb=config[(i+1)%N,j]+config[i,(j+1)%N] + config[(i-1)%N,j] + config[i,(j-1)%N]
            energy += -nb*S
    return energy/4.

def calcMag(config):
    '''Magnetization of a given configuration'''
    mag = np.sum(config)
    return mag

nt = 64         # number of temperature points
N = 16           # size of the lattice, NxX
eqSteps = 10    # number of MC sweeps for equilibration

n1= 1.0/(eqSteps*N*N)
Magnetization = np.zeros(eqSteps)

n=0

tem='Temperature = '

c=0
f=0
id=1

images1 = []
images2 = []
images3 = []
#images4 = []
#images5 = []
#images6 = []

fig = plt.figure()
ax1 = fig.add_subplot(2,3,1)
ax2 = fig.add_subplot(2,3,2)
ax3 = fig.add_subplot(2,3,3)
ax4 = fig.add_subplot(2,3,4)
ax5 = fig.add_subplot(2,3,5)
ax6 = fig.add_subplot(2,3,6)

list=[[0.5, ax1, images1, ax4],
      [1.5, ax2, images2, ax5],
      [3.0, ax3, images3, ax6]]

for T, c, p, g in list:

    E1 = M1 = E2 = M2 = 0

    config = initialstate(N)
    iT = 1.0/T
    iT2 = iT*iT

    print ("Simulation at temperature T=",T)
    titles = tem + str(T)

    for i in range(eqSteps):   # equilibrate
        mcmove(config,iT)      # Monte Carlo moves

        im = c.imshow(config, animated=True)
        c.set_title(titles)
        p.append([im])

        Mag = calcMag(config)
        M1 = M1 + Mag
        Magnetization[i]  = n1*M1

        g.plot(i, abs(Magnetization[i]),'.',color="#348ABD")
        g.set_title('Magnetization')

ani = animation.ArtistAnimation(fig, images1, interval=50, blit=True, repeat_delay=0)
ani = animation.ArtistAnimation(fig, images2, interval=50, blit=True, repeat_delay=0)
ani = animation.ArtistAnimation(fig, images3, interval=50, blit=True, repeat_delay=0)

THANK YOU SO MUCH in advance.
About more trivial things I would also like some help in:

*

*Can I remove the axis from the arrays?

*Can I have the same axis for the magnetization plots for every frame?

*How do I put xlabels and ylabels on the magnetization plots?

*Can I put a label in the figure that updates with every frame? I want this for enumarating them


text:
Q: How do I get the clipboard to work in CentOS inside VirtualBox on Windows? I have CentOS 7.3.1611 running with XFCE inside Oracle VirtualBox 5.1.16 on Windows 8.1. The other questions are for older versions or the guest/host are switched. I set Devices > Shared Clipboard > Bidirectional, but nothing I copy in Windows is pasteable in CentOS, and nothing I copy in CentOS is pasteable in Windows.
I used Vagrant to create the box. vagrant init centos/7; vagrant up
==> default: Checking for guest additions in VM...
    default: No guest additions were detected on the base box for this VM! Guest
    default: additions are required for forwarded ports, shared folders, host only
    default: networking, and more. If SSH fails on this machine, please install
    default: the guest additions and repackage the box to continue.
    default:
    default: This is not an error message; everything may continue to work properly,

I also manually added an optical drive and loaded VBoxGuestAdditions.iso from the VirtualBox folder, restarted, manually mount the CDROM, and manually ran the script, but:
[vagrant@localhost ~]$ sudo mount /dev/sr0/ /mnt
mount: /dev/sr0 is write-protected, mounting read-only
[vagrant@localhost ~]$ cd /mnt
[vagrant@localhost mnt]$ sudo ./autorun.sh
Linux guest additions installer not found -- try to start them manually.
[vagrant@localhost mnt]$ ls
32Bit  AUTORUN.INF  cert  runasroot.sh            VBoxSolarisAdditions.pkg        VBoxWindowsAdditions.exe
64Bit  autorun.sh   OS2   VBoxLinuxAdditions.run  VBoxWindowsAdditions-amd64.exe  VBoxWindowsAdditions-x86.exe

So now I don't know how to get the clipboard to work.

Here is the log from running VBoxLinuxAdditions.run.
[vagrant@localhost mnt]$ sudo ./VBoxLinuxAdditions.run
Verifying archive integrity... All good.
Uncompressing VirtualBox 5.1.16 Guest Additions for Linux...........
VirtualBox Guest Additions installer
Removing installed version 5.1.16 of VirtualBox Guest Additions...
Copying additional installer modules ...
Installing additional modules ...
vboxadd.sh: Building Guest Additions kernel modules.
Failed to set up service vboxadd, please check the log file
/var/log/VBoxGuestAdditions.log for details.
[vagrant@localhost mnt]$ cat /var/log/VBoxGuestAdditions.log

vboxadd.sh: failed: Look at /var/log/vboxadd-install.log to find out what went wrong.
vboxadd.sh: failed: Please check that you have gcc, make, the header files for your Linux kernel and possibly perl installed..
[vagrant@localhost mnt]$ cat /var/log/vboxadd-install.log
/tmp/vbox.0/Makefile.include.header:97: *** Error: unable to find the sources of your current Linux kernel. Specify KERN_DIR=<directory> and run Make again.  Stop.
Creating user for the Guest Additions.
Creating udev rule for the Guest Additions kernel module.
[vagrant@localhost mnt]$ gcc
gcc: fatal error: no input files
compilation terminated.
[vagrant@localhost mnt]$

A: I don't think you'll be able to get clipboard sharing to work without the additions installed.  Can you manually run the VBoxLinuxAdditions.run file and see if it will either install or give you a proper error?


text:
Q: something to play a VOB file as a screen saver back to my touchscreen jukebox question, i thought of another way to do it if the software exists, is there something out there that will play a VOB file as a screen saver?  that would do everything that i need it to do right there.

A: Use Video Screensaver. It's free and works with any file that Windows Media Player can play ( tried a .vob file, played well)


text:
Q: Predicting cutoff in python using scikit-learn As I'm using python for the first time for data mining, I'm facing problems to tune the parameters and get the best parameter values (cutoff, classwt, sampsize). I'm trying to find the cutoff values for different classes using random forest in scikit learn. I'm using the following code
def cutoff_predict(rf,trainArr,cutoff):
   return (rf.predict_prob(trainArr)[:,1]>cutoff).astype(int)

score=[]
def custom_f1(cutoff):
    def f1_cutoff(rf,trainArr,y):
        ypred=cutoff_predict(rf,trainArr,cutoff)
        return sklearn.metrics.f1_score(Actualres,results)
    return f1_cutoff
for cutoff in np.arange(0.1,0.9,0.1):
    rf = RandomForestClassifier(n_estimators=100) #Random forest generation for Classification
    rf.fit(trainArr, trainRes) #Fit the random forest model
validated=cross_val_score(rf,trainArr,trainRes,cv=10,scoring=custom_f1(cutoff))
    score.append(validated)

But I'm getting the following error.
    IndexError                                Traceback (most recent call last)
<ipython-input-14-f8b808ce9a4d> in <module>()
     94     rf = RandomForestClassifier(n_estimators=100) #Random forest generation for Classification
     95     rf.fit(trainArr, trainRes) #Fit the random forest model
---> 96     validated=cross_val_score(rf,trainArr,trainRes,cv=10,scoring=custom_f1(cutoff))
     97     score.append(validated)

C:\Python27\Anaconda\lib\site-packages\sklearn\cross_validation.pyc in cross_val_score(estimator, X, y, scoring, cv, n_jobs, verbose, fit_params, pre_dispatch)
   1350     X, y = indexable(X, y)
   1351
-> 1352     cv = _check_cv(cv, X, y, classifier=is_classifier(estimator))
   1353     scorer = check_scoring(estimator, scoring=scoring)
   1354     # We clone the estimator to make sure that all the folds are

C:\Python27\Anaconda\lib\site-packages\sklearn\cross_validation.pyc in _check_cv(cv, X, y, classifier, warn_mask)
   1604         if classifier:
   1605             if type_of_target(y) in ['binary', 'multiclass']:
-> 1606                 cv = StratifiedKFold(y, cv, indices=needs_indices)
   1607             else:
   1608                 cv = KFold(_num_samples(y), cv, indices=needs_indices)

C:\Python27\Anaconda\lib\site-packages\sklearn\cross_validation.pyc in __init__(self, y, n_folds, indices, shuffle, random_state)
    432         for test_fold_idx, per_label_splits in enumerate(zip(*per_label_cvs)):
    433             for label, (_, test_split) in zip(unique_labels, per_label_splits):
--> 434                 label_test_folds = test_folds[y == label]
    435                 # the test split can be too big because we used
    436                 # KFold(max(c, self.n_folds), self.n_folds) instead of

IndexError: too many indices for array

What could be the problem here? Also: In 'R' we have option to tune 'cutoff' parameter(cutoff = 1/(number of classes)). Is there a similar parameter in random forest(scikit learn package) to tune in python?


text:
Q: Appending a row to the table jQuery I'm trying to append a row using jQuery, but the row is not appending.

Here is the HTML code:

          Course Name

          Institution Name

          Start Date

          End Date

          Percentage or CGPA

I'm trying to append rows to the table at the click of a button, but the rows are not appending. The rows appended fine until I appended the variable newRowField.
$('#edu_table').append(newRowField);

A: Your string has unescaped quotes in all of the value="" cases. You can save yourself a lot of trouble by using single quotes for the string, and double quotes for the HTML inside:
var newRowField = '
<input type="text" name="course_name_' + count + '" id="course_name_' + count + '" value="">	' +
  '	<input type="text" name="college_name_' + count + '" id="college_name_' + count + '" value="">	' +
  '	<input type="text" name="start_dt_' + count + '" id="start_dt_' + count + '" value="">	' +
  '	<input type="text" name="end_dt_' + count + '" id="end_dt_' + count + '" value="">	' +
  '	<input type="text" name="cgpa_' + count + '" id="cgpa_' + count + '" value="">
';


text:
Q: Android: MapOverlay - Current location I am currently creating an Android application, that shows the user its current location on Google Maps. I currently have it working so brings up the location, zoomed in.
However, I want the location to be pin-pointed. I have attempted to try and follow the HelloMapView tutorial, but have been having difficulty. How do I modify what the tutorial is saying, to make the Overlay, show the current location?
Also, I have been getting an error, with the getDrawable part of the following:
Drawable drawable = ((Object) this.getResources()).getDrawable(R.drawable.androidmarker);
ItemizedOverlay itemizedoverlay = new ItemizedOverlay(drawable, this);

Also, whereabouts do I paste this:
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);

Thank you.


text:
Q: How to modify captions of windows created by visual studio project wizard I have craeted a Visual C++ project using studio 2010 wizard in which I have added things like FileView, ClassView, PropertiesWindow, OutputWindow etc, with the help of wizard. Now I am interested in changing the default captions/names of one of these items let's say FileView. The FileView has a resource string "IDS_FILE_VIEW" associated with it with value "File View" which is displayed as a caption of the FileView window. If I change the value of above mentioned string in the resources it does not change that caption and still shows "File View" as a caption. Could anyone suggest me that how can I customize captions and other features of such common windows created through studio wizards?
Thanks a lot.

A: You don't say, but I assume from the "IDS" that you are using the MFC libraries.
In MFC, the resource strings like IDS_FILE_VIEW are defined and used by the designer but it is quite possible to override them. Changing the IDS_FILE_VIEW resource's value will indeed change what is displayed when that resource is used, but you may have (inadvertently) prevented that resource being used where you expect.
I would check through your project files to see where this and related names appear and verify that there are no inconsistencies.
HtH
Ruth


text:
Q: Why Uri used in MediaPlayer static method create() throws java.lang.IllegalArgumentException? The problem is that when we use a uri to get the instance of Mediaplayer class using Mediaplayer.create(Context, uri) it throws exception as of below :
 java.lang.IllegalArgumentException

The above exception occurs when we have path of music files is in Url Encoded form (i.e,path : storage/sdcard/song%20music%20file.mp3) the path is of phone storage and not the url of song on internet.
Uri uri = Uri.parse(path);
//the below line creates the problem.
mediaplayer = Mediaplayer.create(context, uri);

while in other cases of path of the files it works like charm why this problem occurs and if there is any way of resolving this problem how can we do this ? Any suggestion,help will be appreciated.

A: You can use code like below to solve the issue :
Uri myUri = Uri.parse(Uri.encode(path));
//then use myUri like
mediaplayer = Mediaplayer.create(context, myUri);


text:
Q: find specific pattern in string and remove it I want to remove xxxx-xxxx in string.

*

*String data = "help text 2015-2016 dummy string";
Need output:  help text dummy string

*String data = "abcd 2057-3827 any string";
Need output: abcd any string

A: The following code should work:
String regexp = "[^\\s]{4}-[^\\s]{4}\\s";
String str = "help text 2015-2016 dummy string";
System.out.println(str.replaceFirst(regexp, ""));

If xxxx-xxxx is always a number, then you can use:
String r = "[0-9]{4}-[0-9]{4}\\s";


text:
Q: Getting out of a recursive loop in Python I have the following code, which results in Python "quitting unexpectedly":
def profile_videos_sort_and_filter(profile, sort, filter, uncredited_videos, list_of_credits=[]):
    """Given a sort and filter, this will order the credits and return a credit_set."""
    if filter == 'user' or filter == 'all':
        if filter == 'user':
            credit_set = profile.videocredit_set.filter(video__uploaded_by=profile)
        if filter == 'all':
            credit_set = profile.videocredit_set.all()

        if sort == 'alphabetical':
            credit_set = conform_videos_and_credits(credit_set, uncredited_videos, sort)
        if sort == 'newest':
            credit_set = conform_videos_and_credits(credit_set, uncredited_videos, sort)
        if sort =='position':
            credit_set = credit_set.order_by('position')
            list_of_credits = position_credit_set(profile, credit_set, filter, uncredited_videos)

    elif filter == 'others':
        credit_set = profile.videocredit_set.exclude(video__uploaded_by=profile)
        if sort == 'alphabetical':
            credit_set = credit_set.order_by('video__title')
        if sort == 'newest':
            credit_set = credit_set.order_by('video__uploaded_at')
        if sort == 'position':
            credit_set = credit_set.order_by('position')
            list_of_credits = position_credit_set(profile, credit_set, filter, uncredited_videos)

    #### THIS IS THE PART THAT CAUSES THE ERROR ###
    else:
        ### if none of the above, call the function, passing default parameters ###
        profile_videos_sort_and_filter(profile, uncredited_videos=uncredited_videos,
                                        sort='position', filter='newest')

    return credit_set, list_of_credits

How would I change the final else clause to be valid? Thank you.

A: Add a condition for sort='position' and/or filter='newest'.

A: Where do you handle filter=='newest'? The code will loop forever unless you add an elif filter=='newest' and do something on that case.


text:
Q: Plot two dimensional array with "for" loop I have Python classes on University, however I'm not into the programming stuff and I have a problem with one exercise.
We've got to create an array that looks like this:

While having the list of x (from 1.0 to 10.0, as see in the array) and formulas for y1 and y2 which are: y1=sin(x) and y2=sin(x)*2.7^(-x).
My code looks like this:
x=[1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0]
y1=[]
y2=[]
for i in x:
    l=math.sin(i)
    l=round(l, 5)
    y1.append(l)
for o in x:
    o=math.sin(o)*(pow(2.7, -o))
    o=round(o, 6)
    y2.append(o)

Can you help me how to get that three lists into one that looks like on the photo?

A: import math

# You don't have to use one-liners of course, I just wanted the code to be shorter.
x = [i*0.5 for i in range(2, 21)]
y1 = [round(math.sin(i), 5) for i in x]
y2 = [round(math.sin(i)*pow(2.7, -i), 6) for i in x]
print(f'{"x":10} | {"y1":10} | {"y2":10}')  # print with spaces
print('_'*36) # underline
for l1, l2, l3 in zip(x, y1, y2):
    print(f'{l1:10} | {l2:10} | {l3:10}')

Output:
x          | y1         | y2
____________________________________
       1.0 |    0.84147 |   0.311656
       1.5 |    0.99749 |   0.224836
       2.0 |     0.9093 |   0.124732
       2.5 |    0.59847 |   0.049961
       3.0 |    0.14112 |    0.00717
       3.5 |   -0.35078 |  -0.010846
       4.0 |    -0.7568 |  -0.014241
       4.5 |   -0.97753 |  -0.011194
       5.0 |   -0.95892 |  -0.006683
       5.5 |   -0.70554 |  -0.002992
       6.0 |   -0.27942 |  -0.000721
       6.5 |    0.21512 |   0.000338
       7.0 |    0.65699 |   0.000628
       7.5 |      0.938 |   0.000546
       8.0 |    0.98936 |    0.00035
       8.5 |    0.79849 |   0.000172
       9.0 |    0.41212 |    5.4e-05
       9.5 |   -0.07515 |     -6e-06
      10.0 |   -0.54402 |   -2.6e-05

A: First of all, welcome to StackOverflow!
Essentially, what you need to do is go through your x list (the structures declared with square brackets in Python are lists, not arrays ) and, for each element, calculate either of those sine formulae you presented.
Getting the numbers
You were on the right track, but you are missing a couple of things:

*

*you forgot import the math module (or you omitted that line in your snippet).

*to get an output on your console, you need to print your lists, x, y1 and y2. Just add three prints at the end of your script, like this:

# the print function will output everything you give it, separated by a space
print("x:", x)
print("y1:", y1)
print("y2:", y2)

Now, your script should output the following:
x: [1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0]
y1: [0.84147, 0.99749, 0.9093, 0.59847, 0.14112, -0.35078, -0.7568, -0.97753, -0.95892, -0.70554, -0.27942, 0.21512, 0.65699, 0.938, 0.98936, 0.79849, 0.41212, -0.07515, -0.54402]
y2: [0.311656, 0.224836, 0.124732, 0.049961, 0.00717, -0.010846, -0.014241, -0.011194, -0.006683, -0.002992, -0.000721, 0.000338, 0.000628, 0.000546, 0.00035, 0.000172, 5.4e-05, -6e-06, -2.6e-0
5]

Some other notes:

*

*you don't need to change iteration variable names for each for loop.

*you don't need to use the pow function. Python has the ** syntax, which behaves like the usual ^ (which has another meaning in this language already). So you could rewrite pow(2.7, -o) to 2.7**(-o).

*if you are not constrained to using for loops, you could also use the very handy map function. It applies a function over a given list, which is exactly what you're trying to achieve. You could "just" write:

# not doing round to be shorter
y1 = list(map(lambda i: math.sin(i), x))
y2 = list(map(lambda i: math.sin(i)*2.7**(-i), x))

*

*alternatively, list comprehensions exist and are also very neat and would fit here well:

y1 = [math.sin(i) for i in x]
y2 = [math.sin(i)*2.7**(-i) for i in x]

Printing them in a table
Python has rather powerful string formatting, which makes printing these lists as tables pretty simple :D
The full code is as follows:
# Construct the header
header = f"| {'x':10} | {'y1':10} | {'y2':10} |"
# enough dashes to underline the whole header
line = "-" * len(header)
print(header)
print(line)

# Iterate through the three lists and print them with appropriate
# spacing and decimal places
for ix, iy1, iy2 in zip(x, y1, y2):
    print(f"| {ix:10.5f} | {iy1:10.5f} | {iy2:10.5f} |")

print("-" * len(header))  # print new dash line

I'm making use of f-strings, which makes formatting strings really easy. You just put an f before the opening quotes and then you can insert variables inside curly brackets. Additionally, you can tell Python how wide you want the inserted string to be, which is what those 10s following the columns are. You can also specify how many decimal places you want, in case you're printing floats, which is done by adding those .5f (format float with 5 decimal places with a . as separator) after the width.
Finally, the zip function allows you to iterate multiple things at the same time. In this case, I used it to go through all three lists at the same time to print each of their values on the same lines.
Final output
| x          | y1         | y2         |
----------------------------------------
|    1.00000 |    0.84147 |    0.31166 |
|    1.50000 |    0.99749 |    0.22484 |
|    2.00000 |    0.90930 |    0.12473 |
|    2.50000 |    0.59847 |    0.04996 |
|    3.00000 |    0.14112 |    0.00717 |
|    3.50000 |   -0.35078 |   -0.01085 |
|    4.00000 |   -0.75680 |   -0.01424 |
|    4.50000 |   -0.97753 |   -0.01119 |
|    5.00000 |   -0.95892 |   -0.00668 |
|    5.50000 |   -0.70554 |   -0.00299 |
|    6.00000 |   -0.27942 |   -0.00072 |
|    6.50000 |    0.21512 |    0.00034 |
|    7.00000 |    0.65699 |    0.00063 |
|    7.50000 |    0.93800 |    0.00055 |
|    8.00000 |    0.98936 |    0.00035 |
|    8.50000 |    0.79849 |    0.00017 |
|    9.00000 |    0.41212 |    0.00005 |
|    9.50000 |   -0.07515 |   -0.00001 |
|   10.00000 |   -0.54402 |   -0.00003 |
----------------------------------------

I hope this helps you, and feel free to ask questions in the comments!


text:
Q: How in Firestore show only documents that belong to a specific uid? What I'm trying to achieve is to only show the documents that match request.auth.uid. I've seen these examples on a lot of website but none of them seems to work for me. No matter what article I read I see these examples there but none of them seems to work for me. I have a (posts) collection with bunch of documents with auto-generated (ids).

// I cannot attach more than 2 images it gives me formatting error that's why.
https://i.stack.imgur.com/M84P5.png
https://i.stack.imgur.com/hbBii.png
https://i.stack.imgur.com/lm4HH.png

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /posts/{postId} {
      allow read: if request.auth.uid == resource.data.userId;    // This doesn't work
    }
  }
}

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /posts/{postId} {
      allow read: if request.auth.uid == postId;    // This also doesn't work
    }
  }
}

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /posts/{postId} {
      allow read: if request.auth.uid != null;     // even though this works fine but it is general.
    }
  }
}

Below I've shared my code.
class App extends React.Component {
  constructor() {
    super();
    this.state = { social: [], loggedIn: "false" };
  }

  componentDidMount = () => {
    firestore.collection("posts").onSnapshot((snapshot) => {
      const social = snapshot.docs.map((doc) => {
        return { id: doc.id, ...doc.data() };
      });
      this.setState({
        social
      });
    });
  };

//   clickHandle(id, likes) {
//     firestore
//       .collection("posts")
//       .doc(id)
//       .update({ likes: likes + 1 });
//   }

  handleCreate() {
    var obj = { title: "Never Ever GIve Up" };
    firestore.collection("posts").add(obj);
  }

  handleDelete(id) {
    firestore.collection("posts").doc(id).delete();
  }

  handleLogin() {
    var provider = new firebase.auth.GoogleAuthProvider();
    auth.signInWithPopup(provider).then((result) => {
      console.log(result);
    });
  }

  handleLogout() {
    firebase.auth().onAuthStateChanged((user) => {
      auth.signOut();
    });
  }

  render() {
    return (

        <button onClick={this.handleLogin.bind(this)}>Login to Google</button>
        <button onClick={this.handleLogout.bind(this)}> Logout from Google</button>
        {this.state.social.map((obj) => {
          return (

{obj.title}

          );
        })}

        <button id="create" onClick={this.handleCreate.bind(this)}>
          Create
        </button>

    );
  }
}
ReactDOM.render(<App />, document.querySelector("#root"));

A: The problem is that Firestore security rules are not filters.  Please read that documentation carefully, and also this blog.
Your query is asking for all documents in the posts collection.  However, your rules do not allow that.  The rules will not filter the documents that match the rules.  Instead, your client app needs to filter for the documents that the user should be able to read, and your rules need to validate that filter.
If you want to require the userId field to be the same as the authenticated user ID for the purpose of reading the document, your query needs to add a filter to ensure they aren't asking for anything more than they have permission to read:
firestore.collection("posts").where("userId", "==", uid)

Where uid is the user ID that you got from the Firebase Auth SDK.
Then your rules can check to see that the filter is correct:
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /posts/{postId} {
      allow read: if request.auth.uid == resource.data.userId;
    }
  }
}

A: I bet you're doing something funky with your requests.
resource.data will return the attributes of the document accessed. In your first example, this will work if the document at path posts/{post_id} has the attribute userId, and the userId attribute matches the uid of the incoming request context. I would verify the structure of each document in the posts collection to check that it matches.
The first example should work, I would double-check the user id matches of the sender. Check the "Authentication" tab of your Firebase console. (In the document shown, looks like the userId is the id of another post, which might indicate some misbehavior?)
The second example won't work because the document doesn't have a postId attribute.


text:
Q: What is the function in R to calculate p-value for KS test if I only know the D value and sample size? I am doing a one sample KS test.  I have the D value and sample size.  Is there a function in R to calculate the p-value? I cannot use ks.test because I only have D value and sample size.

A: The test statistic has an approximate kolmogorov distribution under the null hypothesis. Look to see whether there's an R function to compute that. If not, you can write your own. The CDF of the kolmogorv distribution is
$$ P(K\leq x)=\frac{\sqrt{2\pi}}{x}\sum_{k=1}^\infty e^{-(2k-1)^2\pi^2/(8x^2)} $$
so for a given value of $D$ the approximate $p$-value is
$$ 1 - \frac{\sqrt{2\pi}}{D}\sum_{k=1}^\infty e^{-(2k-1)^2\pi^2/(8D^2)} $$


text: Q: Problem Configuring Swagger openAPI 3.0 Authentication with firestore I am using the swagger openAPI for retrieving data of firestore. I wanted to apply security from swagger not from firestore and when i do this and perform GET request UI displays the data stored on firestore and not display the unauthenticated message.


text:
Q: PrototypeJS to jQuery | document.viewport I'm trying to convert some prototype code to jQuery.
I have these calls that I don't know the how to convert:
document.viewport.getHeight();
document.viewport.getScrollOffsets().top

Question
What's the equality for the above code in jQuery?
If there is none, what is the vanilla way of doing it?

A: In modern browsers:
document.documentElement.clientHeight
document.documentElement.scrollTop

In jQuery:
$(window).height();
$(window).scrollTop();

A: jQuery way
Window height:
$(window).height();

Scroll top:
$(window).scrollTop();

Vanilla javascript way:
Window height
var winHeight = 0;
if (document.body && document.body.offsetWidth) {
    winHeight = document.body.offsetHeight;
}
if (document.compatMode=='CSS1Compat' && document.documentElement && document.documentElement.offsetHeight) {
    winHeight = document.documentElement.offsetHeight;
}
if (window.innerHeight) {
    winHeight = window.innerHeight;
}

Scroll offset:
var scrollY = window.pageYOffset;


text:
Q: Ruby on Rails - possible error in naming convention throughout a route I am making a login route and added this to the routes.rb resources :sign_in
I made a controller like this:
class Mobile::Sign_inController < ApplicationController
  layout "mobile/application"

  def get
    respond_to do |format|
      format.html
    end

  end

  def index
    respond_to do |format|
      format.html
    end
  end

end

and it seems to get routed correctly, but my view file which is located here:
/app/views/mobile/sign_in.html.haml

which just has 1  line for test purposes:
%strong{:class => "code", :id => "message"} Hello Signin!

But when I go to the url: http://m.cmply.local:8800/signin in the browser, the screen is totally white with nothing rendered in the browser.
Any idea why this happens and how to fix it?
Thanks!

A: A few problems here:

*

*Your controller name should be SignInsController, not Sign_inController. Consider changing your name to UserSessionsController or similar, since that better reflects the resource it represents. You can still specify an alternate name for the URL (such as sign_in).

*Why is your controller namespaced under Mobile? Your routes given don't reflect that, but you don't seem to have provided them all. The route should probably be under a scope:
scope :module => "mobile" do
  resource :sign_in
end

*Since there is only "one" sign in, it should have its route declared resource :sign_in, and probably even resource :sign_in, :only => [:new, :create, :destroy], depending on what you want. This means that the index action no longer exists, and you probably want to replace it with the new action`.

*There is no get action by default for RESTful resources, I'm not sure what you meant it to be, but it should be something else.


text:
Q: I need help with PWM filter capacitor current calculation PWM filter capacitor current calculation.
I am trying to select the capacitor for the PWM filter shown below. That being the case,  I need to calculate the total current (fundamental + harmonics) flowing through the capacitor C1. The RMS phase to phase voltage amplitude of the harmonics and fundamental are shown in the table.
L1 = L2 = L3 = 200 uH C1 = C2 = C3 = 300 uF switching frequency = 2Khz
@ 60.1 Hz from the table below, we can see that the phase-to-phase voltage is 439.3 volts. Therefore, the phase to neutral voltage is 439.3/1.73 = 254 volts. So, the current flowing through C1 is 28 amps.  jWL = .074 ohms and 1/jWC = 11.46 ohms. Are my calculations correct?
Similarly, @1880 Hz the current through C1 is 22 amps.
So, if you sum up all the currents, one will get 121 amps flowing through C1. Is this correct?


text:
Q: Why AES-128 performance is not %40 better than AES-256 I am making performance tests over AES-128 and AES-256. But my results are around %20. I am using Intel Core 2 Duo 800 MHz. 2.60 GHz. 6 MB Cache Memory T9500 CPU and Linux Mint 17.2 Rosa Xfce Os. Is there a problem with my testing? Any help would be appreciated.
My testing code is here:
Headings;
// g++ -g3 -ggdb -O0 -DDEBUG -I/usr/include/cryptopp AESCBC128.cpp -o AESCBC128.exe -lcryptopp -lpthread
// g++ -g -O2 -DNDEBUG -I/usr/include/cryptopp AESCBC128.cpp -o AESCBC128.exe -lcryptopp -lpthread
  #include "osrng.h"
   using CryptoPP::AutoSeededRandomPool;
   #include <iostream>
   using std::cout;
   using std::cerr;
   using std::endl;
   #include <string>
   using std::string;
   #include <cstdlib>
   using std::exit;
   #include "cryptlib.h"
   using CryptoPP::Exception;
   #include "hex.h"
   using CryptoPP::HexEncoder;
   using CryptoPP::HexDecoder;
   #include "filters.h"
   using CryptoPP::StringSink;
   using CryptoPP::StringSource;
   using CryptoPP::StreamTransformationFilter;
   #include "aes.h"
   using CryptoPP::AES;
   #include "ccm.h"
   using CryptoPP::CBC_Mode;
   #include "assert.h"
   #include<sstream>
   const double CLOCK_TICKS_PER_SECOND = 1000000.0;

And my code (for AES-256);
 int main(int argc, char* argv[]){
 AutoSeededRandomPool prng;

 byte key[AES::MAX_KEYLENGTH];
 prng.GenerateBlock(key, sizeof(key));

 byte iv[AES::BLOCKSIZE];
 prng.GenerateBlock(iv, sizeof(iv));

 CBC_Mode< AES >::Encryption e;
 e.SetKeyWithIV(key, sizeof(key), iv);

And my code (for AES-128);
 int main(int argc, char* argv[]){
 AutoSeededRandomPool prng;

 byte key[AES::DEFAULT_KEYLENGTH];
 prng.GenerateBlock(key, sizeof(key));

 byte iv[AES::BLOCKSIZE];
 prng.GenerateBlock(iv, sizeof(iv));

 CBC_Mode< AES >::Encryption e;
 e.SetKeyWithIV(key, sizeof(key), iv);

I use crypto++ test data rijndael.dat as plianText (1020 bytes). It is like;
std::string plain = "000102030405060708090A0B0C0D....

My testing code;
clock_t startTime, finishTime;
std::string plain, cipher, encoded, recovered;
startTime = clock();
for ( int i = 0; i < 200000; i++ )
{
    // clean up for next round
    cipher = "";

try
{

// The StreamTransformationFilter removes
//  padding as required.
StringSource s(plain, true,
    new StreamTransformationFilter(e,
        new StringSink(cipher)
    ) // StreamTransformationFilter
); // StringSource
 }
  catch(const CryptoPP::Exception& e)
   {
      cerr << e.what() << endl;
      exit(1);
    }
 } // end-for
  // save current time just after finishing the encryption loop
   finishTime = clock();

And I am keeping results with;
 double executionTimeInSec = double( finishTime - startTime ) / CLOCK_TICKS_PER_SECOND;

 std::cout << "Encryption loop execution time: " << executionTimeInSec * 1000.0 << " microseconds." << std::endl;

 std::cout << "Plain text size: " << plain.size() << " bytes." << std::endl;

 double data_rate_MiBps = ((double)plain.size() / 1048576) / ((double)executionTimeInSec) ;

 std::cout << "Encryption/decryption loop execution time MB/S: " << data_rate_MiBps << " MB/S." << std::endl;
  return 0;
 }

Finally my results are here;
AES-128/CBC ----------
           2037.41 encryption loop execution time (microseconds)
           0.083 microseconds for Key Setup and IV
           95.48 Encrypiton loop execution time (MIB/Seconds)
AES-256/CBC ----------
           2470.86 encryption loop execution time (microseconds)
           0.092 microseconds for Key Setup and IV
           78.72 Encrypiton loop execution time (MIB/Seconds)


text:
Q: I need to take answers of many participant attending and record answers but not working #made a program but not working :(
num_ques=int(input('Enter Number of Questions: '))#take input number of questions
num_parts=int(input('Enter Number of Participants: '))#take input of number of person answering
n =1
m= 1
num_parts=int(num_parts)
part=[]

while num_parts>=m:
    while num_ques>=n:
        part.append(input(f'Enter Ans{n}: '))
        f=open('data1.txt','w')
        f.write(str(part))
        f.close()
        n=n+1
    m=m+1

why the while loop is not running for all the number of participants,i.e num_parts>=m


text:
Q: Are structs and enums really Objects, or are they just convertible to Objects? From the MSDN:

In cases where it is necessary for a value type to behave like an
  object, a wrapper that makes the value type look like a reference
  object is allocated on the heap, and the value type's value is copied
  into it. The wrapper is marked so the system knows that it contains a
  value type. This process is known as boxing, and the reverse process
  is known as unboxing. Boxing and unboxing allow any type to be treated
  as an object.

It seems to me that value types are treated completely different from reference types, even though they inherit from a reference type (both Object and ValueType). Am I right?

A: By definition, YES.
That is how it is defined by the specifications!

C# has a unified type system. All C# types, including primitive types
  such as int and double, inherit from a single root object type. Thus,
  all types share a set of common operations, and values of any type can
  be stored, transported, and operated upon in a consistent manner.
  Furthermore, C# supports both user-defined reference types and value
  types, allowing dynamic allocation of objects as well as in-line
  storage of lightweight structures.

Are they implemented differently?  Yes, but they are still System.Objects.
Anywhere in the specifications, in which they refer to objects or System.Objects, you can be quite certain that it refers to all types.
What would you expect as the output for the following code?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StackOverflowConsole
{
   public class EmptyClass
   {
   }

   public class ReferenceStuff : EmptyClass
   {
      object a;
   }

   public class TypeStuff : EmptyClass
   {
      int a;
   }

   class Test
   {
      static void Main()
      {
         ReferenceStuff r = new ReferenceStuff();
         TypeStuff t = new TypeStuff();

         if (r is EmptyClass)
         {
           Console.WriteLine("r is an EmptyClass");
         }
         if (t is EmptyClass)
         {
            Console.WriteLine("t is an EmptyClass");
         }
      }
   }
}

Not surprisingly, the output is:
r is an EmptyClass
t is an EmptyClass

Why?  Because they are both EmptyClass objects.  EmptyClass doesn't contribute anything that object doesn't, but both r and t are of type EmptyClass nonetheless.


text:
Q: How to implement 2D FFT using C or glsl for converting image to frequency space and back I currently have a naive kernal convolution that cannot be seperable causing high load on the system at large kernal sizes.
I have started looking into Fast Fourier Transform, and as far as I can tell the result of a kernal convolution is the same as the multiplication of the FFT of both the image and the kernal.
Could someone please help me to learn how to implement a 2D FFT.
This is for a project for simulating lens blur.


text:
Q: Q: Verificação de login SQL ALCHEMY Pendente Estou criando um login para dar acesso a ferramenta que estou  começando a criar, o banco de dados é o SQL Server
A estrutura do projeto é essa:
├── Project
│   ├── Controllers
│   │   ├── __init__.py
│   │   └── Mapping_Login
│   │       ├── __init__.py
│   │       └── Mapping_login.py
│   ├── __init__.py
│   ├── Models
│   │   ├── Conexao
│   │   │   ├── conexao.py
│   │   │   ├── conexao.pyc
│   │   │   ├── __init__.py
│   │   │
│   │   ├── __init__.py
│   │   └── sing_in
│   │       ├── __init__.py
│   │       └── register.py
│   └── View
│       ├── __init__.py
│       ├── static_routes.py
│       ├── view_acept_reg.py
│       ├── view_index_page.py
│       └── view_register.py
├── run.py
├── static
│   ├── index.css
│   ├── main.css
│   ├── main.js
│   ├── user_login.png
│   └── util.css
└── templates
    └── printer
       ├── Acept.html
       ├── index.html
       ├── Register.html
       └── TelaInicial.html

Criei um mapeamento da base de dados com SQLALCHEMY para fazer o CRUD
class mapping_log:
    def __init__(self):
        metadata = MetaData()
        self.table = Table('login',metadata,
            Column('id',Integer, primary_key = True),
            Column('usuario',String),
            Column('Senha',String))

    def login(self, Usuario,senha):
         selecionar = self.table.select().where(self.table.c.usuario
                         == Usuario and self.table.c.Senha == senha)
         conn = __engine__()
         usuarios = conn.execute(selecionar)
         print(usuarios)
         return usuarios
    def insert(self,key_value):
         inserir = self.table.insert()
         conn = __engine__()
         conn.execute(inserir,
              usuario = key_value.get('usuario'),
              Senha = key_value.get('Senha')
          )
    def deletar(self, id ):
        deletar_User =  self.table.delete().where(self.table.c.id ==
        id)
        conn = __engine__()
        conn.execute(deletar_User)

Criei Rotas para a parte de login defini o "def" como teste e estou pegando do template o login e senha do 'usuario', porém estou com dificuldade em validar o mesmo verificando se existe e permitindo o acesso
 # -*- coding utf-8 -*-

 from flask import  render_template, abort,
      render_template_string,url_for,Blueprint,request
 from Project.Controllers.Mapping_Login.Mapping_login import
      mapping_log
 from Project import app

 login_db = mapping_log()

 app_router = Blueprint('app',__name__, url_prefix='/index')
 @app_router.route('/')
      def hellou():
          return render_template('printer/index.html')

 @app_router.route('/initi', methods=['GET', 'POST'])
       def teste():
           usuario = request.form.get('login')
           senha = request.form.get ('password')
           usuarios =  login_db.login(usuario,senha)
           print(usuarios,"pasou aqui ")
           return render_template('printer/TelaInicial.html')

  app.register_blueprint(app_router)

Eu não sei aonde eu possa estar errando para que essa validação não de certo, ele passa para "TelaInicial.html" com qualquer coisa que eu digite nos campos Login e senha!


text:
Q: Long-running Process with Responsive Form - Performance Improvements So, I'm working on a library for my internal applications that interacts with our PostgreSQL database (amongst many other things).  One requirement at the moment is that this library can dump data from the database to a file.  I have something working, but I've been trying to improve its performance as much as possible.  This is what I'm currently looking at:
Using COPYReader As NpgsqlCopyTextReader = CType(CIADB.DBConnection.BeginTextExport(COPYSQL), NpgsqlCopyTextReader)
    With COPYReader
        Dim stopWatch As New Stopwatch
        Dim ts As TimeSpan
        Dim elapsedTime As String

        ' ** FIRST ATTEMPT
        stopWatch.Start()
        Dim BufferText As String = .ReadLine

        Do While Not BufferText Is Nothing
            CurrentPosition += 1
            OutputFile.WriteLine(BufferText)

            If Not UpdateForm Is Nothing Then
                UpdateForm.UpdateProgress(Convert.ToInt32((CurrentPosition / MaxRecords) * 100))
            End If

            BufferText = .ReadLine
        Loop

        OutputFile.Flush()
        OutputFile.Close()

        stopWatch.Stop()
        ts = stopWatch.Elapsed
        elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10)

        ' ** FIRST ATTEMPT RESULTS
        ' ** Records Retrieved: 65358
        ' ** Time To Complete: 2:12.07
        ' ** Lines Written: 65358
        ' ** File Size: 8,166 KB

        ' ** SECOND ATTEMPT
        stopWatch.Start()

        Using TestOutputFile As New IO.StreamWriter(DestinationFile.FullName.Replace(".TXT", "_TEST.TXT"), False)
            TestOutputFile.Write(.ReadToEndAsync.Result)
        End Using

        stopWatch.Stop()
        ts = stopWatch.Elapsed
        elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10)

        ' ** SECOND ATTEMPT
        ' ** Records Retrieved: 65358
        ' ** Time To Complete: 1:04.01
        ' ** Lines Written: 65358
        ' ** File Size: 8,102 KB
    End With
End Using

I've run multiple tests of each method and come up with pretty much the same results.  FIRST ATTEMPT takes about twice as long as SECOND ATTEMPT
Obviously, the UpdateForm.UpdateProgress method used in FIRST ATTEMPT (used to keep the form responsive and show the current progress of the export) is going to cause the process to take longer because of the form updating and such involved, not to mention the line-by-line writing to the file. This is pretty much exactly why I was looking at reducing the number of extra calls by doing a full dump in one line of code.  The problem is that if I use the "one-liner", the form is completely unresponsive until the process is complete.
I've tried moving the code for the "all-in-one-shot" dump from the SECOND ATTEMPT into a separate Async method, but I'm extremely unfamiliar with async methods in general, so I'm (obviously) not doing it right:
Private Async Sub OutputToFile(ByVal COPYReader As NpgsqlCopyTextReader, ByVal DestinationFile As IO.FileInfo)
    ' ** METHOD 3
    Using TestOutputFile As New IO.StreamWriter(DestinationFile.FullName.Replace(".TXT", "_TEST.TXT"), False)
        Await TestOutputFile.WriteAsync(COPYReader.ReadToEndAsync.Result)
    End Using

    ' ** METHOD 3 RESULTS
    ' ** Records Retrieved: 65358
    ' ** Time To Complete: 0:15.07
    ' ** Lines Written: 34
    ' ** File Size: 4 KB
End Sub

One other thing to mention: I tried moving all of this to a BackgroundWorker, but I was getting some strange behavior when I tried to call my UpdateForm.UpdateProgress method which caused the application to completely skip the actual dumping process.  I've currently given up on trying to get this onto a separate thread, but I'm still open to other suggestions.  This is actually one of the smaller tables that I'm dumping, so I'm not looking forward to what one of the bigger ones will do.
Just for the sake of completeness, here's the UpdateForm class that I've implemented in my library for reusability across other applications:
Imports System.Windows.Forms

Namespace Common
    Public Class FormHandler
        Implements IDisposable

        Public Property ApplicationForm As Form
        Public Property ApplicationStatusLabel As Label
        Public Property ApplicationToolStripLabel As ToolStripStatusLabel
        Public Property ApplicationProgressBar As ProgressBar

        Private LabelVisibleState As Boolean = True
        Private ProgressBarVisibleState As Boolean = True
        Private CurrentStatusText As String
        Private CurrentProgress As Integer

        Public Sub New(ByVal AppForm As Form)
            ApplicationForm = AppForm
        End Sub

        Public Sub New(ByVal StatusLabel As Label, ByVal Progress As ProgressBar)
            ApplicationStatusLabel = StatusLabel
            ApplicationToolStripLabel = Nothing
            ApplicationProgressBar = Progress
            ApplicationForm = ApplicationProgressBar.Parent.FindForm

            LabelVisibleState = StatusLabel.Visible
            ProgressBarVisibleState = Progress.Visible

            With ApplicationProgressBar
                .Minimum = 0
                .Maximum = 100
                .Value = 0
                .Visible = True
            End With

            With ApplicationStatusLabel
                .Visible = True
                .Text = ""
            End With
        End Sub

        Public Sub New(ByVal StatusLabel As ToolStripStatusLabel, ByVal Progress As ProgressBar)
            ApplicationToolStripLabel = StatusLabel
            ApplicationStatusLabel = Nothing
            ApplicationProgressBar = Progress
            ApplicationForm = ApplicationProgressBar.Parent.FindForm

            LabelVisibleState = StatusLabel.Visible
            ProgressBarVisibleState = Progress.Visible

            With ApplicationProgressBar
                .Minimum = 0
                .Maximum = 100
                .Value = 0
                .Visible = True
            End With

            With ApplicationToolStripLabel
                .Visible = True
                .Text = ""
            End With
        End Sub

        Public Sub New(ByVal AppForm As Form, ByVal StatusLabel As Label, ByVal Progress As ProgressBar)
            ApplicationForm = AppForm
            ApplicationStatusLabel = StatusLabel
            ApplicationToolStripLabel = Nothing
            ApplicationProgressBar = Progress

            LabelVisibleState = StatusLabel.Visible
            ProgressBarVisibleState = Progress.Visible

            With ApplicationProgressBar
                .Minimum = 0
                .Maximum = 100
                .Value = 0
                .Visible = True
            End With

            With ApplicationStatusLabel
                .Visible = True
                .Text = ""
            End With
        End Sub

        Public Sub New(ByVal AppForm As Form, ByVal StatusLabel As ToolStripStatusLabel, ByVal Progress As ProgressBar)
            ApplicationForm = AppForm
            ApplicationToolStripLabel = StatusLabel
            ApplicationStatusLabel = Nothing
            ApplicationProgressBar = Progress

            LabelVisibleState = StatusLabel.Visible
            ProgressBarVisibleState = Progress.Visible

            With ApplicationProgressBar
                .Minimum = 0
                .Maximum = 100
                .Value = 0
                .Visible = True
            End With

            With ApplicationToolStripLabel
                .Visible = True
                .Text = ""
            End With
        End Sub

        Friend Sub UpdateProgress(ByVal StatusText As String, ByVal CurrentPosition As Integer, ByVal MaxValue As Integer)
            CurrentStatusText = StatusText
            CurrentProgress = Convert.ToInt32((CurrentPosition / MaxValue) * 100)
            UpdateStatus()
        End Sub

        Friend Sub UpdateProgress(ByVal StatusText As String, ByVal PercentComplete As Decimal)
            CurrentStatusText = StatusText
            CurrentProgress = Convert.ToInt32(PercentComplete)
            UpdateStatus()
        End Sub

        Friend Sub UpdateProgress(ByVal StatusText As String)
            CurrentStatusText = StatusText
            CurrentProgress = 0
            UpdateStatus()
        End Sub

        Friend Sub UpdateProgress(ByVal PercentComplete As Decimal)
            CurrentProgress = Convert.ToInt32(PercentComplete)
            UpdateStatus()
        End Sub

        Friend Sub UpdateProgress(ByVal CurrentPosition As Integer, ByVal MaxValue As Integer)
            CurrentProgress = Convert.ToInt32((CurrentPosition / MaxValue) * 100)
            UpdateStatus()
        End Sub

        Friend Sub ResetProgressUpdate()
            CurrentStatusText = ""
            CurrentProgress = 0
            UpdateStatus()
        End Sub

        Private Sub UpdateStatus()
            If Not ApplicationForm Is Nothing Then
                If ApplicationForm.InvokeRequired Then
                    Dim UpdateInvoker As New MethodInvoker(AddressOf UpdateStatus)

                    Try
                        ApplicationForm.Invoke(UpdateInvoker)
                    Catch ex As Exception
                        Dim InvokeError As New ErrorHandler(ex)

                        InvokeError.LogException()
                    End Try
                Else
                    UpdateApplicationProgress(CurrentStatusText)
                End If
            End If
        End Sub

        Friend Sub UpdateApplicationProgress(ByVal ProgressText As String)
            If Not ApplicationForm Is Nothing Then
                With ApplicationForm
                    If Not ProgressText Is Nothing Then
                        If Not ApplicationStatusLabel Is Nothing Then
                            ApplicationStatusLabel.Text = ProgressText
                        End If

                        If Not ApplicationToolStripLabel Is Nothing Then
                            ApplicationToolStripLabel.Text = ProgressText
                        End If
                    End If

                    If Not ApplicationProgressBar Is Nothing Then
                        ApplicationProgressBar.Value = CurrentProgress
                    End If
                End With

                ApplicationForm.Refresh()
                Application.DoEvents()
            End If
        End Sub

        Public Sub Dispose() Implements IDisposable.Dispose
            If Not ApplicationForm Is Nothing Then
                ApplicationForm.Dispose()
            End If

            If Not ApplicationStatusLabel Is Nothing Then
                ApplicationStatusLabel.Visible = LabelVisibleState
                ApplicationStatusLabel.Dispose()
            End If

            If Not ApplicationToolStripLabel Is Nothing Then
                ApplicationToolStripLabel.Visible = LabelVisibleState
                ApplicationToolStripLabel.Dispose()
            End If

            If Not ApplicationProgressBar Is Nothing Then
                ApplicationProgressBar.Visible = ProgressBarVisibleState
                ApplicationProgressBar.Dispose()
            End If
        End Sub
    End Class
End Namespace

EDIT
Per the suggestion in the comments from @the_lotus, I modified my FIRST ATTEMPT slightly to check the value of the current progress (I declared a CurrentProgress variable as an Integer), and it dramatically improved the time taken:
' ** FOURTH ATTEMPT
Using COPYReader As NpgsqlCopyTextReader = CType(CIADB.DBConnection.BeginTextExport(COPYSQL), NpgsqlCopyTextReader)
    With COPYReader
        Dim stopWatch As New Stopwatch
        Dim ts As TimeSpan
        Dim elapsedTime As String
        Dim CurrentProgress As Integer = 0

        stopWatch.Start()
        Dim BufferText As String = .ReadLine

        Do While Not BufferText Is Nothing
            CurrentPosition += 1
            OutputFile.WriteLine(BufferText)

            ' ** Checks to see if the value of the ProgressBar will actually
            ' ** be changed by the CurrentPosition before making a call to
            ' ** UpdateProgress.  If the value doesn't change, don't waste
            ' ** the call
            If Convert.ToInt32((CurrentPosition / MaxRecords) * 100) <> CurrentProgress Then
                CurrentProgress = Convert.ToInt32((CurrentPosition / MaxRecords) * 100)

                If Not UpdateForm Is Nothing Then
                    UpdateForm.UpdateProgress(CurrentProgress)
                End If
            End If

            BufferText = .ReadLine
        Loop

        OutputFile.Flush()
        OutputFile.Close()

        stopWatch.Stop()
        ts = stopWatch.Elapsed
        elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10)
    End With
End Using
' ** FOURTH ATTEMPT RESULTS
' ** Records Retrieved: 65358
' ** Time To Complete: 0:47.45
' ** Lines Written: 65358
' ** File Size: 8,166 KB

Of course, the form is a "little" less responsive than if I were making the call on every record, but I'm thinking it's worth the trade-off.

EDIT #2
So that I could minimize the amount of code I'd have to retype (read: "copy/paste") each time I use the UpdateProgress method, I've moved the test for changed values over there and it seems to be operating with the same performance improvements.  Again, for the sake of completeness, here's the code for the two private methods involved in doing the actual progress/status update:
Private Sub UpdateStatus()
    If Not ApplicationForm Is Nothing Then
        If ApplicationForm.InvokeRequired Then
            Dim UpdateInvoker As New MethodInvoker(AddressOf UpdateStatus)

            Try
                ApplicationForm.Invoke(UpdateInvoker)
            Catch ex As Exception
                Dim InvokeError As New ErrorHandler(ex)

                InvokeError.LogException()
            End Try
        Else
            UpdateApplicationProgress()
        End If
    End If
End Sub

Private Sub UpdateApplicationProgress()
    Dim Changed As Boolean = False

    If Not ApplicationForm Is Nothing Then
        With ApplicationForm
            If Not CurrentStatusText Is Nothing Then
                If Not ApplicationStatusLabel Is Nothing Then
                    If ApplicationStatusLabel.Text <> CurrentStatusText Then
                        Changed = True
                        ApplicationStatusLabel.Text = CurrentStatusText
                    End If
                End If

                If Not ApplicationToolStripLabel Is Nothing Then
                    If ApplicationToolStripLabel.Text <> CurrentStatusText Then
                        Changed = True
                        ApplicationToolStripLabel.Text = CurrentStatusText
                    End If
                End If
            End If

            If Not ApplicationProgressBar Is Nothing Then
                If ApplicationProgressBar.Value <> CurrentProgress Then
                    Changed = True
                    ApplicationProgressBar.Value = CurrentProgress
                End If
            End If
        End With

        If Changed Then
            ApplicationForm.Refresh()
        End If

        Application.DoEvents()
    End If
End Sub

Doing it this way also came with the added benefit of returning some of the responsiveness to the form that was previously lost.  I hope at least some of this code and information is helpful to someone out there.

A: You don't need to call UpdateProgress on each call. It's not necessary when the percentage didn't even move. Try to do a small check and only update the percentage when needed.
It's also possible that the second attempt is faster because it doesn't go to the database. The data could be cached.


text:
Q: Angular 1 fix Ng-Model disable value When putting ng-model the value of the input dispairs
ex
<input type="text"  name="" ng-model='myInput' value="gooo">

The goo doesn't appear, even if I use ng-value instead of value
<input type="text"  name="" ng-model='myInput' ng-value="gooo">

It doesn't appear as well if i removed ng-model it appears
Can I use it this way without using data binding

A: You should use the model in order to bind the value instead of ng-value.
$scope.myInput = "goo".
Then in html code just put ng-model, it will bind the correct value for you.

A: Since you said ng-value="gooo", angular tries to find gooo variable inside scope. If you directly want to set ng-model value using ng-value, you should have been wrap in '(single quote).
<input type="text"  name="" ng-model='myInput' ng-value="'gooo'">

You can also set the value of gooo inside respective controller, like $scope.myInput = 'gooo'


text:
Q: What is the simplest way to dynamically load routes in angular? I am building an angular app and what i'm trying to accomplish is have an array of objects where i would keep the basic info about each module (the url, the controller name) so i would have a single service for the initialization, and it would get called on each route with a different url to fetch the server data with ajax calls so i have the corresponding data available in each controller by the time it is loaded.
Back with a pretty error:
modules = [{
  name: Scan,
  url: packing/scan,
  controllerName : packer
}];

var Application = angular.module('ReporterApplication', ['ngRoute', 'ngSanitize', 'ui.select']);

/**
 * Handles the initialization by fetching server data on module run
 */

Application.service('Initialize', ['$http', function($http)
{

    this.serverData = function(route)
    {
        return $http.get(route + '.action')
            .then(function(response)
            {
                return response.data;
            });

    };

}])

Application.config(['$routeProvider', '$interpolateProvider',

    function($routeProvider, $interpolateProvider) {

        $interpolateProvider.startSymbol('<%');
        $interpolateProvider.endSymbol('%>');

        for (var i=0; i < 1; i++) {
            var index = i; // for some weird reason i is 1 by the time initData is run
            $routeProvider.when('/' + modules[i].url + '.html', {
                templateUrl: modules[i].url + '.html',
                controller: modules[i].name + 'Controller' + ' as ' + modules[i].controllerName,
                resolve: {
                  initData : ['Initialize', function(Initialize) {
                    return Initialize.serverData('/' + modules[index].url)
                  }]
                }

            })
        };   etc more code

scan.js
Application.controller('ScanController', ['$scope', '$http', 'initData', function($scope, $http, initData) {

    var packer = this;

    packer.initData = initData;
    packer.packedToday = initData.ordersPackedToday; etc more code

And this throws me
Error: [$injector:unpr] Unknown provider: initDataProvider <- initData <- ScanController
Update: Solved that one, but now it seems that controller doesn't load data
Update: Solved that too. Everything seems to work, and im the best :D


text:
Q: How do I add text in the center of a radial chart and/or align the dataLabels to the end of the bars? The code for the simple radial chart I have so far: https://jsfiddle.net/du4jxzwn/20/
       series: {
            dataLabels: {
                enabled: true,
                align: 'right',
                color: '#FFFFFF',
                x: -10,
                rotation: '270',
            },
            pointPadding: 0.025,
            groupPadding: 0
        }

I want the text to align to the end of the bar. I also want to add some text in the center of the chart, as shown here. Is there any way to do this using Javascript?

A: Inside the series if you save the point as an object you can edit the dataLabels parameter there and align it.
  series: [{
    data: [{
      x: 0,
      y: 29.9,
      dataLabels: {
        enabled: true,
        allowOverlap: true,
        format: 'Financal',
        color: '#000',
        rotation: '280',
        x: 2,
        y: 15
      }
    }, {
      x: 1,
      y: 71.5
    }, {
      x: 2,
      y: 106.4
    }]
  }]

You can also edit points via events like here and execute the update method on them to change something e.g. the value.
events: {
  load: function() {

    let chart = this,
      series = chart.series[0],
      point = series.data[0],
      dataLabel = point.dataLabel;

    console.log(point);

    point.update({
      y: 33,
    })
  },
},

Demo: https://jsfiddle.net/BlackLabel/kjfn5pvc/1/