Q:

Blackberry config.xml is different in Worklight build methodologies

I'm building our BB10 environment in Worklight using two different ways.
1- Through Eclipse IDE:
The config.xml in the native folder which has been generated after building the environment contains all the feature that we need in our project.
<?xml version='1.0' encoding='utf-8'?>
<widget id="MobileBanking" version="1.0.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:rim="http://www.blackberry.com/ns/widgets" rim:backButton="exit">
    <name>Mobile Bank</name>
    <author email="support@company.com">company</author>
    <description>
       Mobile Bank
    </description>
    <license href="http://opensource.org/licenses/alphabetical">
    </license>
    <access subdomains="true" uri="file:///store/home" />
    <access subdomains="true" uri="file:///SDCard" />

<!-- start_worklight_host_server do not change this line-->

<access subdomains="true" uri="https://mobile-qa.company.ca" />
  <!-- end_worklight_host_server do not change this line-->

<access subdomains="true" uri="tel://*"/>
<access subdomains="true" uri="http://google.com"/>
<access subdomains="true" uri="http://maps.googleapis.com"/>
<access subdomains="true" uri="http://googleapis.com"/>
<access subdomains="true" uri="http://maps.gstatic.com"/>
<access subdomains="true" uri="http://fonts.gstatic.com"/>
<access subdomains="true" uri="http://csi.gstatic.com"/>
<access subdomains="true" uri="https://www.company.com/*" />

<!-- <access subdomains="true" uri="*" /> -->

<icon src="icon.png" />
<rim:splash src="splash-1024x600.png" />
<rim:splash src="splash-600x1024.png" />
<rim:splash src="splash-1280x768.png" />
<rim:splash src="splash-768x1280.png" />
<content src="webresources/skinLoader.html" />
<rim:permissions>
    <rim:permit>read_device_identifying_information</rim:permit>
    <rim:permit>access_shared</rim:permit>
    <rim:permit>read_geolocation</rim:permit>
    <rim:permit>access_pimdomain_contacts</rim:permit>
    <rim:permit>access_pimdomain_messages</rim:permit>
    <rim:permit>access_location_services</rim:permit>
</rim:permissions>

<preference name="HideKeyboardFormAccessoryBar" value="true"/>
<preference name="Orientation" value="portrait"/>
<preference name="ChildBrowser" value="disable"/>
<preference name="AutoHideSplashScreen" value="false"/>
<preference name="WebSecurity" value="enabled" />

 <feature id="blackberry.invoke" name="blackberry.invoke" value="blackberry.invoke" />

 <feature id="blackberry.app" name="blackberry.app" value="blackberry.app" />

<feature id="com.blackberry.utils" name="com.blackberry.utils" />
<feature id="com.blackberry.pim.lib" name="com.blackberry.pim.lib" />
<feature id="Battery" name="Battery" value="Battery" />
<feature id="Camera" name="Camera" value="Camera" />
<feature id="Contacts" name="Contacts" value="Contacts" />
<feature id="Device" name="Device" value="Device" />
<feature id="Accelerometer" name="Accelerometer" value="Accelerometer" />
<feature id="Compass" name="Compass" value="Compass" />
<feature id="Notification" name="Notification" value="Notification" />
<feature id="org.apache.cordova.file" name="File" value="File" />
<feature id="FileTransfer" name="FileTransfer" value="FileTransfer" />
<feature id="Geolocation" name="Geolocation" value="Geolocation" />
<feature id="Media" name="Media" value="Media" />
<feature id="Capture" name="media-capture" value="Capture" />
<feature id="NetworkStatus" name="NetworkStatus" value="NetworkStatus" />
<feature id="SplashScreen" name="SplashScreen" value="SplashScreen" />
<feature id="Vibration" name="Vibration" value="Vibration" />
 </widget>

2- When I use Ant Worklight Builder, the generated native folder for BB10 contains the following config.xml:
<?xml version='1.0' encoding='utf-8'?>
<widget id="MobileBank" version="1.0.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:rim="http://www.blackberry.com/ns/widgets" rim:backButton="exit">
    <name>MobileBank</name>
    <author email="support@company.com">company</author>
    <description>
       MobileBanking
    </description>
    <license href="http://opensource.org/licenses/alphabetical">
    </license>
    <access subdomains="true" origin="file:///store/home" />
    <access subdomains="true" origin="file:///SDCard" />

    <!-- start_worklight_host_server do not change this line-->
  <access subdomains="true" origin="https://mobile-qa.company.ca" />
  <!-- end_worklight_host_server do not change this line-->

    <access subdomains="true" origin="*" />
    <icon src="icon.png" />
    <rim:splash src="splash-1024x600.png" />
    <rim:splash src="splash-600x1024.png" />
    <rim:splash src="splash-1280x768.png" />
    <rim:splash src="splash-768x1280.png" />
    <content src="webresources/skinLoader.html" />
    <rim:permissions>
        <rim:permit>read_device_identifying_information</rim:permit>
        <rim:permit>access_shared</rim:permit>
        <rim:permit>read_geolocation</rim:permit>
        <rim:permit>access_pimdomain_contacts</rim:permit>
    </rim:permissions>
 </widget>

All the feature tags disappear using Ant builder.
Worklight Ant task version 6.2.0.01.20150329-1923
WebWorks SDK version 2.2.0.15.
I tried Windows and Mac. got same result.
Thank you.

A:

See this blog post: https://developer.ibm.com/mobilefirstplatform/2015/03/05/ootb-support-blackberry-webworks-2-2/
I've created an application with the BlackBerry 10 environment two times: using The WebWorks 1.0 SDK and the WebWorks 2.2 SDK. The difference in config.xml is due to the SDK used.

The Worklight builder will create the first config.xml if your environment variable for WEBWORKS_HOME is pointing to WebWorks 1.0.
The Worklight builder will create the second config.xml if your environment variable for WEBWORKS_HOME is pointing to WebWorks 2.2.

This means that your Studio and Ant .jar file are not of the same version Worklight.
Get the latest iFix from IBM Fix Central; to get the Ant .jar I believe that you will need to extract the Server installation to get it.


Q:

Won an incentive trip in 2013, left employer in 2014, received an earning statement with no cash but a huge tangible bonus listed

This is a crazy one but I hope someone can help point me in the right direction.

I won a trip in 2013 and went on the trip in 2013, the company did NOT list the trip as a bonus in the tax year of 2013
I continued to work for the company for part of 2014 but was off their payroll midyear
The last payroll of 2014 I received an earnings statement that showed earnings that are offset by Social Security Tax, Medicare Tax and a line item under "other" that lists Tangible Bonus. The net effect is that the cash value of the check is zero but my tax liability took a huge bump.
I also found out from people that also went on the trip and still work for the company that no one else was charged with this tax liability.

It is pretty frustrating to suddenly have this tax liability dropped on me. I agree that there should be a tax liability for the trip. I am trying to figure out what game my former employer is playing but I think that they have been classifying the trip as a "business trip" so that winners of the incentive are not taxed. Now suddenly I don't work there and they decided to reclassify only me as having won an incentive trip and therefore hit me with all the taxes.
Is it okay for them to treat me differently than the others for tax purposes?
Can they do this a year after the trip was won and redeemed?
Would the IRS want to know about this fuzzy business trip practice? How would I report it?
Besides now understanding the new level of slime from my former employer is there anything else I should be worried about? Could they do something like this every year just to be annoying?
I really appreciate any thoughts that you have. I live in Illinois.

A:

I had experience working for a company that manufactures stuff and giving products to the employees. The condition was to stay employed for a year after the gift for the company to cover its cost (I think they imputed the tax), otherwise they'd add the cost to the last paycheck (which they did when I left). But they were straight-forward about it and I signed a paper acknowledging it.
However, in your case you didn't get a product (that you could return when leaving if you didn't want to pay), but rather a service. The "winning" trip was definitely supposed to be reported as income to you last year.

Is it okay for them to treat me differently than the others for tax purposes?

Of course not. But it may be that some strings were attached to the winning of the incentive trip (for example, you're required to stay employed for X time for the company to cover the expense). See my example above. Maybe it was buried somewhere in small letters.

Can they do this a year after the trip was won and redeemed?

As I said - in this case this sounds shady. Since it is a service which you cannot return - you should have been taxed on it when receiving it.

Would the IRS want to know about this fuzzy business trip practice? How would I report it?

Here's how you can let them know.

Besides now understanding the new level of slime from my former
  employer is there anything else I should be worried about? Could they
  do something like this every year just to be annoying?

No, once they issued the last paycheck - you're done with them. They cannot issue you more paychecks after you're no longer an employee. In most US States, you are supposed to receive the last paycheck on your last day of work, or in very close proximity (matter of weeks at most).


Q:

Is there a way to run a script on IPython interactively so that it comes afterwards what is already written?

Is there a way to run a script in iPyton with the %run myscript.py so that it will  take into consideration the things I have already entered in the interactive iPython console?
Example:
In [1]: asdf = 18

In [2]:

Then if myscript.py was:
print asdf

And it was ran from iPython like this:
In [2]: %run myscript.py
18

In [3]:

Can this be done?

A:

Try using the %load magic function, available in the IPython Notebook (qtconsole or web version). It allows you to load the contents of a file into a cell, edit them if you want, then run them in the current context.


Q:

Why does this apoc code not work in browser?

I ran CALL apoc.date.parseDefault('1969-07-21 02:56:15', 's') YIELD value in the browser of neo4j. But it does not work.
The error is: There is no procedure with the name apoc.date.parseDefault registered for this database instance. Please ensure you've spelled the procedure name correctly and that the procedure is properly deployed.
I could run CALL apoc.load.json(url) YIELD value or CALL apoc.help("apoc") work without any problem.
(Question originally asked in the comment here)

A:

Since Neo4j 3.1 introduced user-defined functions, several APOC procedures have migrated over, including date parsing. Additionally, these functions support optional parameters, so there is no need for a separate parseDefault() function, it's been dropped since parse() handles it just fine.
Try this instead:
RETURN apoc.date.parse('1969-07-21 02:56:15', 's') as date

You can call functions inline without needing to use CALL or YIELD.
Unfortunately some of the documentation is lagging a bit in reflecting these conversions. While the date/time functions look up-to-date, some of the examples are still referencing the removed procedures rather than referencing current functions.


Q:

How do you add MKPolylines to MKSnapShotter in swift 3?

Is there a way to take a screenshot of mapView and include the polyline? I believe I need to draw CGPoint's on the image that the MKSnapShotter returns, but I am unsure on how to do so.
Current code
      func takeSnapshot(mapView: MKMapView, withCallback: (UIImage?, NSError?) -> ()) {
    let options = MKMapSnapshotOptions()
    options.region = mapView.region
    options.size = mapView.frame.size
    options.scale = UIScreen.main().scale

    let snapshotter = MKMapSnapshotter(options: options)

    snapshotter.start() { snapshot, error in
        guard snapshot != nil else {
            withCallback(nil, error)
            return
        }

        if let image = snapshot?.image{

            withCallback(image, nil)

            for coordinate in self.area {

                image.draw(at:snapshot!.point(for: coordinate))

            }

        }

    }
}

A:

I had the same problem today. After several hours of research, here is how I solve it.
The following codes are in Swift 3.
1. Init your polyline coordinates array
// initial this array with your polyline coordinates
var yourCoordinates = [CLLocationCoordinate2D]()
yourCoorinates.append( coordinate 1 )
yourCoorinates.append( coordinate 2 )
...
// you can use any data structure you like

2. take the snapshot as usual, but set the region based on your coordinates:
func takeSnapShot() {
    let mapSnapshotOptions = MKMapSnapshotOptions()

    // Set the region of the map that is rendered. (by polyline)
    let polyLine = MKPolyline(coordinates: &yourCoordinates, count: yourCoordinates.count)
    let region = MKCoordinateRegionForMapRect(polyLine.boundingMapRect)

    mapSnapshotOptions.region = region

    // Set the scale of the image. We'll just use the scale of the current device, which is 2x scale on Retina screens.
    mapSnapshotOptions.scale = UIScreen.main.scale

    // Set the size of the image output.
    mapSnapshotOptions.size = CGSize(width: IMAGE_VIEW_WIDTH, height: IMAGE_VIEW_HEIGHT)

    // Show buildings and Points of Interest on the snapshot
    mapSnapshotOptions.showsBuildings = true
    mapSnapshotOptions.showsPointsOfInterest = true

    let snapShotter = MKMapSnapshotter(options: mapSnapshotOptions)

    snapShotter.start() { snapshot, error in
        guard let snapshot = snapshot else {
            return
        }
        // Don't just pass snapshot.image, pass snapshot itself!
        self.imageView.image = self.drawLineOnImage(snapshot: snapshot)
    }
}

3. Use snapshot.point() to draw Polylines on Snapshot Image
func drawLineOnImage(snapshot: MKMapSnapshot) -> UIImage {
    let image = snapshot.image

    // for Retina screen
    UIGraphicsBeginImageContextWithOptions(self.imageView.frame.size, true, 0)

    // draw original image into the context
    image.draw(at: CGPoint.zero)

    // get the context for CoreGraphics
    let context = UIGraphicsGetCurrentContext()

    // set stroking width and color of the context
    context!.setLineWidth(2.0)
    context!.setStrokeColor(UIColor.orange.cgColor)

    // Here is the trick :
    // We use addLine() and move() to draw the line, this should be easy to understand.
    // The diificult part is that they both take CGPoint as parameters, and it would be way too complex for us to calculate by ourselves
    // Thus we use snapshot.point() to save the pain.
    context!.move(to: snapshot.point(for: yourCoordinates[0]))
    for i in 0...yourCoordinates.count-1 {
      context!.addLine(to: snapshot.point(for: yourCoordinates[i]))
      context!.move(to: snapshot.point(for: yourCoordinates[i]))
    }

    // apply the stroke to the context
    context!.strokePath()

    // get the image from the graphics context
    let resultImage = UIGraphicsGetImageFromCurrentImageContext()

    // end the graphics context
    UIGraphicsEndImageContext()

    return resultImage!
}

That's it, hope this helps someone.
References

How do I draw on an image in Swift?
MKTileOverlay,MKMapSnapshotter & MKDirections
Creating an MKMapSnapshotter with an MKPolylineRenderer
Render a Map as an Image using MapKit


Q:

Removing part descriptor error on exported Eclipse product

I created an Eclipse product that opens a view. When I launch it through the .product file, everything works fine and the view opens but when I export it and launch it through the new .exe file I get this issue on startup:
!ENTRY org.eclipse.e4.ui.workbench 2 0 2019-03-28 15:48:23.160
!MESSAGE Removing part descriptor with the 'views.myView' id and the 'test myview' description. Points to the invalid 'bundleclass://org.eclipse.ui.workbench/org.eclipse.ui.internal.e4.compatibility.CompatibilityView' class.
Because of this, the view doesn't open on the exported product.I didn't change any of the dependencies so I can't figure out why this appears to be happening.

A:

I had to create a new project from scratch and copy & paste all the folders/files in there. I am still unsure as to what caused the issue.


Q:

Error: Could not find or load main class - path is correct

As you can see in the title, I'm getting the error:
Error: Could not find or load main class Exercise14_11.java
I checked my path and it should be working, when I type java -version in CMD I get the proper output. Which should indicate the system path is set correctly.
I'm opening the CMD from the same folder as where the Exercise14_11.java is located.
But when I typt: java Exercise14_11.java
I get the error:
Error: Could not find or load main class Exercise14_11.java
I've read the answers that has been asked for this error before but it has not really helped.
Hope someone can tell me whats wrong.
PS Here's the program I'm trying to run:
package hsleiden.webcat.exercise14_11;

import java.io.*;
import java.util.*;

public class Exercise14_11 {
    public static void main(String[] args) throws Exception {
        if (args.length != 2){
            System.out.println("Usage: java Exercise14_11 stringTeVerwijderen sourceFile");
        }

        File sourceFile = new File(args[1]);
        if(!sourceFile.exists()){
            System.out.println("Source file " + args[1] + " does not exist");
        }

        Scanner input = new Scanner(sourceFile);
        StringBuilder sb = new StringBuilder();

        while(input.hasNext()){
            String watVervangen = input.nextLine();
            String vervangen = watVervangen.replaceAll(args[0], "");
            sb.append("\r\n" + vervangen);
        }

        input.close();

        PrintWriter output = new PrintWriter(sourceFile);
        output.println(sb.toString());
        output.close();
    }
}

A:

The origin of the problem seems to be that your class belongs to package hsleiden.webcat.exercise14_11, and you are working as it belonged to the default package.  If you sucessfully compiled it, the .class file should be inside a directory C:\...\DDD\hsleiden\webcat\exercise14_11, and be named Exercise14_11.class.  To run it, either

Add directory C:\...\DDD to the classpath, or
Add directory . to the classpath and cd to C:\...\DDD.

Additionally, the java command requires the full class name, so you should use:
java hsleiden.webcat.exercise14_11.Exercise14_11

Please note that when compiling it's correct to use the .java filename extension, but when running it's necessary to use a class name.   These don't have a filename extension, so don't add .java or .class.
For example, if the .class file full path were C:\eclipse\IOPR2\Exercise14_11\bin\hsleiden\webcat\exercise14_11\Exercise14_11.class, then you would need to run it with:
java  -cp C:\eclipse\IOPR2\Exercise14_11\bin  hsleiden.webcat.exercise14_11.Exercise14_11


Q:

Resize WebView defined in Xamarin.Forms Core library on screen rotate event

I have web page defined in the core library as view to fill whole screen:
Content = new WebView
{
    VerticalOptions = LayoutOptions.FillAndExpand,
    HorizontalOptions = LayoutOptions.FillAndExpand,
    Source = "https://google.com",
};

Unfortunately on screen rotate it's not resized (please see below):

How can I make sure that screen is resized on screen rotation.

A:

If it's iOS, then make a custom WebView renderer (http://developer.xamarin.com/guides/cross-platform/xamarin-forms/custom-renderer/):
protected override void OnElementChanged (VisualElementChangedEventArgs e)
{
    base.OnElementChanged(e);

    AutoresizingMask = UIViewAutoresizing.FlexibleDimensions;
    ScalesPageToFit = true;
}

public override void LayoutSubviews()
{
    base.LayoutSubviews();

    NativeView.Bounds = UIKit.UIScreen.MainScreen.Bounds;
}

A:

Please try this solution, it works in iOS 8.4, but not iOS 7.
Xamarin Forms: How to resize the Webview after rotation in iOS


Q:

ASP.NET resources for a C# programmer

Does anyone have any recommendations of resources for learning ASP.NET specifically? I have a good background in web-based programming (PHP/MySQL) and a strong grounding in C# for desktop, winforms and background services, but I have never touched ASP.
I personally prefer online resources, but in lieu of that, books or other resources would be appreciated too (or for other people looking for the same).

A:

You can find a lot of information, tutorials etc. on official ASP.NET site.


Q:

Composite HID gamepad descriptor works on Windows but not on Linux

I am building an USB adapter for an old game controller. So far everything is working fine. My HID descriptor looks like this:
0x05, 0x01,  /* USAGE_PAGE (Generic Desktop)       */
0x09, 0x05,  /* USAGE (Game Pad)                   */
0xa1, 0x01,  /* COLLECTION (Application)           */
0xa1, 0x03,  /*   COLLECTION (Report)              */
0x85, 0x01,  /*     REPORT_ID (1)                  */
0x05, 0x09,  /*     USAGE_PAGE (Button)            */
0x19, 0x01,  /*     USAGE_MINIMUM (Button 1)       */
0x29, 0x0e,  /*     USAGE_MAXIMUM (Button 14)      */
0x15, 0x00,  /*     LOGICAL_MINIMUM (0)            */
0x25, 0x01,  /*     LOGICAL_MAXIMUM (1)            */
0x95, 0x0e,  /*     REPORT_COUNT (14)              */
0x75, 0x01,  /*     REPORT_SIZE (1)                */
0x81, 0x02,  /*     INPUT (Data,Var,Abs)           */
0x95, 0x01,  /*     REPORT_COUNT (1)               */
0x75, 0x02,  /*     REPORT_SIZE (2)                */
0x81, 0x03,  /*     INPUT (Cnst)                   */
0xa1, 0x00,  /*     COLLECTION (Physical)          */
0x05, 0x01,  /*       USAGE_PAGE (Generic Desktop) */
0x09, 0x30,  /*       USAGE (X)                    */
0x09, 0x31,  /*       USAGE (Y)                    */
0x15, 0x00,  /*       LOGICAL_MINIMUM (0)          */
0x25, 0x64,  /*       LOGICAL_MAXIMUM (100)        */
0x75, 0x08,  /*       REPORT_SIZE (8)              */
0x95, 0x02,  /*       REPORT_COUNT (2)             */
0x81, 0x02,  /*       INPUT (Data,Var,Abs)         */
0xc0,        /*     END_COLLECTION                 */
0xc0,        /*   END_COLLECTION                   */
0xc0         /* END_COLLECTION                     */

Now I want to add support for up to 4 of these controllers. If I understand the
HID spec correctly, one way to do this is to repeat the descriptor 4 times, each time with a different report ID. (I know I could probably just have multiple USB interfaces with the HID class, but I'd rather not do it that way; my USB code would get a great deal more complicated.)
When I tried this Linux refused to recognize the device as a gamepad. The HID
driver (hid-generic) is loaded, and the descriptor seems to be parsed correctly, but there is no device file in /dev/input/.
EDIT:
I tested my code on Windows 7, and it looks like this problem is indeed Linux specific. So I am reformulating my original question:
How do I need to modify my HID descriptor, so it works on both Windows and Linux?
When plugging the device in, dmesg reports this:
usb 3-6: new low-speed USB device number 8 using xhci_hcd
usb 3-6: ep 0x81 - rounding interval to 64 microframes, ep desc says 80 microframes
input: XYZ Adapter as /devices/pci0000:00/0000:00:14.0/usb3/3-6/3-6:1.0/0003:16C0:05DC.0009/input/input20
hid-generic 0003:16C0:05DC.0009: input,hidraw4: USB HID v1.01 Gamepad [XYZ Adapter] on usb-0000:00:14.0-6/input0

This is identical to what it says when plugging in the working 1-controller version. The device appears in lsusb, with the correct IDs/descriptors.

A:

After some hours of poking around in debugfs and the kernel sources, I figured it out.
As it turns out the descriptor was fine, the problem was that udev (for whatever reason) decided the create the device file with root-only access. After fixing this, my device now appears as a 56-button 8-axis gamepad, which is not quite what I wanted, but still close enough.


Q:

C Program returning a series of question marks at the end or sometimes, returning nothing

My program is supposed to erase /**/ comments, condense white spaces, and remove line splices of the input.
**edit: scroll down to problem update below.
Here is my code:
#include <stdio.h>

void ass(), f1(), f2(), f3();

int mainRunner();

int a, b;

int main() {
    ass();
    mainRunner();
}

void ass() {
    a = getchar();
    b = getchar();
}

int mainRunner() {
    while ( a != EOF ) {
        f1();
        f2();
        f3();
        putchar(a);
        a = b;
        b = getchar();
    }
}

// Removes Line Splices
void f1() {
    if ((a == '\\') && (b == '\n')) {
        a = getchar();
        b = getchar();
        mainRunner();
    }
}

//Removes Comments in the /*...*/ form
void f2() {
    if ((a == '/') && (b == '*')) {
        while ((a != '*') || (b != '/')) {
            a = b;
            b = getchar();
        }
        a = getchar();
        b = getchar();
        mainRunner();
    }
}

//Condenses White Spaces
void f3() {
    if ((a == ' ') && (b == ' ')) {
        a = b;
        b = getchar();
        mainRunner();
    }
}

When I run the testscript (testscript 1):
a b  c
d             e
f
g

hifealkfja;efa  faekjf;ale   feafaefa

This is returned
a b c
d e
f
g

hifealkfja;efa faekjf;ale feafaefa
????????????????

When I run this testscript (testscript 2):
start linesplice NOW!\
This should be connected with first line.Comment begins here:/*fjelajfal;efjael$
fe;ajfe;fe8/Comment Ends.
Series of 5 spaces between the letters:a     b
Series of 10 spaces between the letters:c          d
Increasing number of spaces between letters from 1 space:e f  g   h    i

Nothing happens and the command line cursor goes to the very left.
I appreciate any feedback, thanks.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Problem Update:
Reduced the issue above by doing what chux suggested. Now I only have the question mark problem. I made a fix so that putchars wouldn't be waiting in the stack and output a whole bunch of EOFs at the end, but why are there still two question marks? Here's my new code:
#include <stdio.h>

void ass();

int mainRunner();

int a, b;

int main() {
    ass();
    mainRunner();
}

void ass() {
    a = getchar();
    b = getchar();
}

int mainRunner() {
    while ( a != EOF ) {
        // Removes Line Splices
        if ((a == '\\') && (b == '\n')) {
            a = getchar();
            b = getchar();
            mainRunner();
        }
        //Removes Comments in the /*...*/ form
        if ((a == '/') && (b == '*')) {
            while ((a != '*') || (b != '/')) {
                a = b;
                b = getchar();
            }
            a = getchar();
            b = getchar();
            mainRunner();
        }
        //Condenses White Spaces
        if ((a == ' ') && (b == ' ')) {
            a = b;
            b = getchar();
            mainRunner();
        }
        if (a == EOF) {
            break;
        }
        else {
            putchar(a);
            a = b;
            b = getchar();
        }
    }
}

When I run the second test script from above (with an asterisk added to end the comment), my program outputs:

start linesplice NOW!This should be connected with first line.Comment
  begins here:Comment Ends. Series of 5 spaces between the letters:a b
  Series of 10 spaces between the letters:c d Increasing number of
  spaces between letters from 1 space:e f g h i ??

Notice the two question marks at the end.
Note: the program works fine for the first test script.

A:

Given OP's first testscript:
The if in f1() is never true.
The if in f2() is never true.
f3() effectively recurses into itself via mainRunner() when multiple space are encountered.  Upon seeing EOF, the recursion stops, and unwinds. mainRunner() performs putchar(a); with EOF in a with each unwinding.

Removing mainRunner(); in f1(), f2(), & f3() may help.
The test code has 1 + 13 + 1 + 2 sequences of 2 spaces.  This causes 17 recursive calls.  Upon unwinding putchar(EOF) is called 16 times creating the '?'.

In OP's 2nd testscript. f2() gets into an infinite loop with
while ((a != '*') || (b != '/')) {
  a = b;
  b = getchar();
}

as there is no escape should getchar() return EOF.


Q:

C# Extension method precedence

I'm a bit confused about how extension methods work.
If I'm reading this correctly http://msdn.microsoft.com/en-us/library/bb383977.aspx and this If an extension method has the same signature as a method in the sealed class, what is the call precedence?.
Then the following should write out "Instance", but instead it writes "Extension method".
interface IFoo
{
}

class Foo : IFoo
{
    public void Say()
    {
        Console.WriteLine("Instance");
    }
}

static class FooExts
{
    public static void Say(this IFoo foo)
    {
        Console.WriteLine("Extension method");
    }
}

class Program
{
    static void Main(string[] args)
    {
        IFoo foo = new Foo();
        foo.Say();
    }
}

Appreciate any help in clarifying the behavior.

A:

The big difference here is that you have defined an extension method for the IFoo interface, and your foo variable is of type IFoo.
If your code was to look like this:
Foo foo = new Foo();
foo.Say()

The Foo.Say() method would be executed, not the extension method.
I wish I could give you a thorough explanation on why this is but I can only cover the basic mechanism. As your variable was of IFoo type and not of Foo, when the compiler tried to determine what methods were available, it looked past any non-interface methods of the Foo class (as it should). However, the extension method Say() was available, so it invoked this.

A:

In your Main,
foo is declared as IFoo. When the compiler looks for a method Say, it finds only the extension method. This is because the instance method is declared in Foo, not in IFoo. The compiler doesn't know that the variable foo happens to contain a instance of Foo; it just looks at the type the variable is declared of.


Q:

Docker info shows containers but docker container ls doesn't

When I run docker info, it shows that I have 18 containers running.
% docker info
Client:
 Debug Mode: false

Server:
 Containers: 18
  Running: 18
  Paused: 0
  Stopped: 0
 Images: 9
...

I want to delete these containers, but when I run docker container ls -a, it shows an empty list. How can I find them?
These containers are not allowing me to delete images.
% docker rmi -f 1e94481e8f30
Error response from daemon: conflict: unable to delete 1e94481e8f30 (cannot be forced) - image is being used by running container 7e9b08a0007b

A:

You are probably running kubernetes.
After stopping kubernetes, to remove all stopped containers and all images without at least one container associated to them:
docker system prune --all


Q:

React rerender on prop change

My problem is when I change a state inside a redux store and based on this state I mount or unmount a component. The Code looks like this:
class Main extends Component {

  render() {
    const { dropdownState } = this.props;
    return (

        <SecondHeadBar />

          <Switch>
            <Route exact path='/' component={withRouter(WebsiteIndex)}/>
            <Route path='/track/:trackid' component={withRouter(MssTrack)}/>
            <Route path='/album/:albumid' component={withRouter(Container.AlbumContainer)}/>
            <Route path='/profile/:userName' component={withRouter(MssUser)}/>
            <Route path='/upload/:albumid' component={withRouter(MssUploadTemplate)}/>
            <Route path='/upload' component={withRouter(MssUploadTemplate)}/>
            <Route path='/admin' component={withRouter(ControlCenter)}/>
            <Route path='/kategorie' component={withRouter(Category)} exact/>
            <Route path='/kategorie/:catName' component={withRouter(Folder)}/>
            <Route path='/notFound' component={withRouter(NotFound)}/>
            <Route path='/meine-eintraege' component={withRouter(Container.MyEntriesContainer)}/>
          </Switch>

        {dropdownState ? <DownloadDropdown /> : ''}

    );
  }
}

function mapStateToProps(state) {
  return {
    dropdownState: state.collection.dropdownState
  };
}

function mapDispatchToProps(dispatch) {
  return {
    dispatch
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(Main);

Whenever the prop dropdownState changes. And the Component DownloadDropdown gets mounted then everything in the Main Component gets rerendered. So the content flashes.

A:

Simplest solution would be to have <DownloadDropdown /> be a container component that is connected to Redux and will always stay mounted although not visible. Then you can utilize a HOC or something that's always mounted and visible (like <SecondHeadBar />) and have it connected to a Redux action creator that toggles DownloadDropdown's visiblity. In other words, isolate Redux to two components, instead of over your entire route tree.
Working example: https://codesandbox.io/s/yw4m7yz8r1 (navigate around the routes and click the 'Download Schedule' link at the top!)
I'm not sure how you are triggering the mount/unmount, but let's stay it's being toggled by a button:
SecondHeadBar.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { handleDropdown } from '../actions';

class SecondHeadBar extends Component {
  state = {...}

  componentDidMount = () => { ... }

  render = () => (

      ...
      <button onClick={this.props.handleDropdown}>Toggle Dropdown</button>
      ...

  )
}

export default connect(null, { handleDropdown })(SecondHeadBar)

DownloadDropdown.js
import React, { Component } from 'react';
import { connect } from 'react-redux';

class DownloadDropdown extends Component {
  state = { ... }

  componentDidMount = () => { ... }

  render = () => (
    this.props.isVisible
      ?
I'm visible!

      : null
  )
}

export default connect(state => ({ isVisible: state.dropdown }))(DownloadDropdown)

actions.js
import { TOGGLE_DROPDOWN } from '../types'

export const handleDropdown = () => ({
  type: TOGGLE_DROPDOWN
})

reducers.js
import { TOGGLE_DOWN } from '../types';

...

const dropdownReducer = (state=false, { type, payload }) => {
  switch(type) {
    case TOGGLE_DROPDOWN: return !state
    default: return state
  }
}

export default = combineReducer({
  ...
  dropdown: dropdownReducer
  ...
})

routes.js
const Main = () => (

    <SecondHeadBar />

      <Switch>
        <Route exact path='/' component={withRouter(WebsiteIndex)}/>
        <Route path='/track/:trackid' component={withRouter(MssTrack)}/>
        <Route path='/album/:albumid' component={withRouter(Container.AlbumContainer)}/>
        <Route path='/profile/:userName' component={withRouter(MssUser)}/>
        <Route path='/upload/:albumid' component={withRouter(MssUploadTemplate)}/>
        <Route path='/upload' component={withRouter(MssUploadTemplate)}/>
        <Route path='/admin' component={withRouter(ControlCenter)}/>
        <Route path='/kategorie' component={withRouter(Category)} exact/>
        <Route path='/kategorie/:catName' component={withRouter(Folder)}/>
        <Route path='/notFound' component={withRouter(NotFound)}/>
        <Route path='/meine-eintraege' component={withRouter(Container.MyEntriesContainer)}/>
      </Switch>

    <DownloadDropdown/>

);

export default Main;

Now, when the user clicks the "Toggle Dropdown" button in <SecondHeadBar/>, it'll update <DownloadDropdown/>'s visibility without affecting your route tree.


Q:

Convert private paid project to free private in Assembla

I have a private project in Assembla with Starter plan, how can i convert this project to free private(non-public) project?
Thanks!

A:

Please go to the Admin tab of your space and check if there's an option to do that directly.
If you will see the statement Remove this space from your Starter Package and convert it into a Free Private space - just click it to convert the space to Free/Private.
Please be aware that all your Professional (paid) tools will be deleted in that case (Messages, Files, StandUp, Milestones, Tickets, Wiki, Time, GitHub, Support, FTP, Webhook, Custom Tabs).
If you will see Remove this space from your Starter Package and convert it into a free public space - then you have an option to convert the space to Free/Public only.
In that case the only option to convert it to Free/Private would be to back up the data in your space (via Admin > Resources tab of your space or Import/Export subtab of your Source/SVN and the Settings page of the Tickets tools) and then create a new Free/Private space and import the dump files there.


Q:

Is it really that expensive to increase FileSystemWatcher.InternalBufferSize?

I'm using a FileSystemWatcher to monitor changes in a folder, but as soon as I have more than a few hundred modifications in a short time, I miss some of them because the internal buffer overflows. So I want to increase the InternalBufferSize (I know it won't really solve the problem, but it will make it less likely to occur), but I see this warning in the documentation:

However, increasing buffer size is expensive, because it comes from
  non-paged memory that cannot be swapped out to disk, so keep the
  buffer as small as possible.

So my question is: does it really matter? Most computers today have at least 1GB of RAM, so it seems to me that if I set the buffer size to 1MB (instead of the default 8KB), it shouldn't really matter if 1MB can't be swapped out to disk. Or am I missing something? I don't know much about low level stuff such as paged/non-paged memory, so I'm not sure what the impact would be...

A:

The memory in which the buffer gets allocated is certainly a precious resource.  Windows will not deal with exhausting the memory pool well, drivers will start to fail at random.  The size of the pool is dynamically set (but can be changed) and depends on the amount of available RAM.
The default buffer size that FSW asks for is 8192 bytes.  Not much on modern machines.  The underlying winapi function will not allow you to ask for more than 64KB.  An entry is the buffer is 12 bytes plus the length of the file path times two.  So worse case is 8192 / (12 + 260*2) = 15 notifications before the buffer runs out.  That should work in most circumstances without much trouble, unless you monitor an entire drive or have very high disk traffic in the directory you are watching.  In which case asking for a bigger buffer is fair.  There is no golden formula, be sure to implement the FileSystemWatcher.Error event so you know that you've got a buffer problem.
In most practical cases you need to deal with the FSW events carefully.  They will be raised while a process still has a lock on a file.  So doing things like opening or copying the file are troublesome.  You deal with that by putting the notifications on a thread-safe queue and use another thread to try to acquire a lock on the file, repeatedly if necessary.  Such a queue is now automatically also a very good way to quickly empty the buffer.  The only thing you've got to watch for now is that the queue doesn't blow up beyond reasonable proportions that will make your program crash with OOM.

A:

Non-paged memory has limited size (update: modern versions of Windows don't have as strict limit as in previous versions, and the amount of memory is now a flexible value that depends on the overall RAM available to Windows) and is very important to kernel-mode inhabitants (device drivers, OS itself). Consuming it without severe control can quickly cause instability in the system and, what is worse, you won't find what has caused this instability.
Also, as comments suggest, it's not the buffer size that matters, but how fast you remove data from the buffer.
In most cases, a filesystem filter driver will do a better job than FileSystemWatcher. The benefits are that you can have any log buffer that you need (as you would create it in whatever memory you need and not be limited by non-paged memory) and also you can handle events as they happen, not after they happen. Also, you can filter requests with finer granularity than FileSystemWatcher lets you.

A:

Consider a consumer producer design to read in the FileSystemWatcher events.
BlockingCollection Overview
If you have some FileSystemWatcher events you don't need to process then quickly dismiss them.
Or if some can process faster than others have a separate collection to keep the total count down.


Q:

Iniciar ponteiro de estrutura com um endereço?

Gostaria de saber se é possível iniciar esse ponteiro tipo estrutura com um endereço, sem precisar apontar para outra variável, ou alocar memória.
typedef struct{

    char nome[20];
    int idade;

}pessoa;

pessoa leonardo;
pessoa *p;

p = &leonardo;
p->idade = 23;
printf("%d", p->idade);

Ou alocando memória.
pessoa *p = malloc(sizeof(pessoa));

A:

Pode:
p = (pessoa*)1234;

Agora, você tem que saber o que vai fazer com isso...


Q:

Why does memory allocated from inside a DLL become invalid after FreeLibrary()?

I had this bug today which turned out to be because I use a string allocated from inside my DLL after calling FreeLibrary().
This is a simple example reproducing the crash. This goes in DLL:
void dllFunc(char **output)
{
    *output = strdup("Hello"); // strdup uses malloc
}

This is in the EXE that loads the DLL:
void exeFunc()
{
    char *output;
    dllFunc(&output);
    std::string s1 = output; // This succeeds.
    FreeLibrary(dll);
    std::string s2 = output; // This crashes with access violation.
}

I read the documentation of FreeLibrary() but I couldn't find anything about memory becoming invalid after it's called.
Edit
I just  realized that I had been using VS2008 toolchain for the DLL while using VS2010 toolchain for the EXE (I was using VS2010 as IDE for both, but you can select the toolchain from the project settings). Setting the toolchain to VS2010 for the DLL as well removed the crash.

A:

If you choose static linking with the MSVCRT (C Runtime) library, you will get the behavior you describe. Same thing also happens if your EXE and DLL are dynamically linked to an MSVCRT DLL, but are  using different versions.  Or if they are matched to the same version, but one is using DEBUG and the other is using RETAIL. In other words, memory is only as good as the lifetime of the MSVCRTxxx.dll used to make the allocation. I just saw your update to your question - yes, mixing and matching the CRT between VS 2008 and 2010 is the exact reason for the crash.
If both your DLL and EXE are dynamically linked to the same version of the MSVCRT DLL, then you share the memory heap and you avoid the problem you are having.
The standard practice is this: If your exported DLL function returns anything that needs to be "freed" or "released" later, then standard practice is to provide an additional function exported out of the DLL to handle de-allocations.
You can configure both the EXE and DLL's C Runtime linkage from the Code-Generation page for the C/C++ project settings in your project.
Picture here: http://imgur.com/uld4KYF.png

A:

This occurs because each Dll creates its own memory heap (which malloc and its C friends, along with new will use internally, generally via HeapAlloc), and when the Dll is freed, so is its heap.
Refer to this MSDN article for more Dll memory caveats. unless you are using a custom memory allocator, shared across all your binaries, you need to keep dynamically allocated memory within the module that created it (unless you can 100% guarantee that the object will not outlive its creator).


Q:

postgres multiple JDBC select statements in batch

How do you issue a single JDBC call to Postgres which includes 2 select statements? The two select statements select from different sets of tables and return two different result sets - so cannot be union-ed. The goal is to ensure that what is read from the database is a consistent snapshot of data in the tables at the instant the selects are issues. If two separate select statements are issued, there is a chance of some data getting updated after the first select and before the second one.
Look like java.sql.Statement's addBatch() and executeBatch() can not be used - this can only be used for updates. Attempting to use it with selects causes a PSQLException with message "A result was returned when none was expected." on executeBatch().

A:

You don't need to jump through any hoops for this. Just BEGIN a transaction in SERIALIZABLE isolation and the two statements will see a consistent view of the data.
See the JDBC tutorial.
There is no other way to ensure two statements see the same data. You could send them together, but unless they're wrapped in a transaction they could still see different data.


Q:

How to use Parcel.readTypedList() along with @Parcelize from kotlin-android-extensions?

I'm running into a problem with implementing Parcelable-based state persistence in a View. Namely, as I need to implement the methods of BaseSavedState like this:
class SavedState : BaseSavedState {
    lateinit var myList: ArrayList<MyParcelable>

    constructor(superState: Parcelable) : super(superState) {}

    private constructor(parcel: Parcel) : super(parcel) {
        val listSize = parcel.readInt()
        val list = ArrayList<MyParcelable>(listSize)
        this.myList = parcel.readTypedList(list, /* needs MyParcelable.CREATOR */ )
    }

    override fun writeToParcel(out: Parcel, flags: Int) {
        super.writeToParcel(out, flags)
        out.writeInt(myList.size())
        out.writeTypedList(myList)
    }

    companion object {
        @JvmField
        val CREATOR: Parcelable.Creator<SavedState> = object : Parcelable.Creator<SavedState> {
            override fun createFromParcel(`in`: Parcel): SavedState {
                return SavedState(`in`)
            }

            override fun newArray(size: Int): Array<SavedState?> {
                return arrayOfNulls(size)
            }
        }
    }
}

However, as you can see, I can't seem to use Parcel.readTypedList() because it needs both the typed list, and the parcelable's CREATOR field!
Classes marked like:
@Parcelize
data class MyParcelable(val someData: String): Parcelable {
}

Do not have CREATORs, in fact, if you try to implement, it says:

'CREATOR' definition is not allowed. Use 'Parceler' companion object instead.

I do not want a Parceler companion object, I need a CREATOR!
I also kinda don't want to write the Parcelable implementation by hand, so I might just make it Serializable and be like "whatever".

Does anyone know by chance how you can use Parcel.readTypedList() with @Parcelize-annotated Kotlin data class?

A:

It's a bug on the Parcelize plugin like you mentioned https://youtrack.jetbrains.com/issue/KT-19853 and it can be solved by either reflection or actually, you can have a proxy class to java as you can access that CREATOR field in java without any problems.
I made a util java class for all creators and then made a kotlin extension referring to that creator
Java
@NonNull
public static Parcelable.Creator<Blah> getBlahCreator() {
    return Blah.CREATOR;
}

Kotlin
val Blah.Companion.CREATOR: Parcelable.Creator<Blah>
 get() = UtilClass.getBlahCreator()

And now I can access Blah.CREATOR anywhere! And those two classes that have all the creators and extensions could be just deleted later after the bug got fixed in the foreseeable future and it'll just work as expected without any edits in the other classes that use the CREATOR
This feels much better to me than the reflection solution! but either way, they are both disgusting and I hope this bug could be fixed soon enough!


Q:

Upgrading laptop from SATA 2 to SATA 3

I'm trying to upgrade my Sony Vaio Fit Laptop with a SATA 3 SSD. My laptop however can only support up to SATA 2. Is there a feasible way of upgrading SATA 2 to SATA 3? I know SATA 3 is backwards compatible but I want to utilize a new SSD to its maximum potential.
Thanks,

A:

Your SATA controller on your laptop is part of the motherboard. Yes, your new SSD will work, but at SATA-II speeds (3 gbps). I have run SSDs in SATA-II ports before and although you do not get the full SATA-III experience (6 gbps), they are still faster and more reliable than traditional hard drives.


Q:

Common JavaScript code that is included on all pages while using RequireJS

How can you use RequireJS, and have some common JavaScript code for all pages? If I have a script tag with datamain in the template (used on all pages), can I then have a require(...) on the other pages that requires what they need? Would this cause problems with the sequence of loading? It would right? I also thought having a second script tag in the template that have all the common code (which is outside of RequireJS) hands. Is that the only approach?

A:

strong text> How can you use RequireJS, and have some common JavaScript code for

all pages?

The answer to this question will help - How does RequireJS work with multiple pages and partial views?

can I then have a require(...) on the other pages that requires what
  they need? Would this cause problems with the sequence of loading? It
  would right?

Nope, this is fine. You can make calls to the same module if you wish and it will only be loaded once. A common example is multiple require calls all needing jquery. You would require it each time to be sure of it's presence, but there is no penalty as RequireJS is smart enough to fetch it just the once.
Edit to answer comment:
Request jQuery and/or jQuery UI as dependencies to either define or require and the callback will execute afterwards:
require(['jquery', 'jquery-ui'], function($) {
    // jQuery is passed in as first argument but as jquery-ui
    // merely augments jQuery we don't need it as the second argument
});

This is the real fundamentals of RequireJS (requiring dependencies and executing code when they're ready) so it might be worth having a detailed read of the documentation (which is superb).
Last thing to note, is that you will need to set a path to jQuery in your paths configuration and I'm not sure if jQuery UI registers itself as a module. If not, you'll need to make use of the shim config option


Q:

Confusion in MATLAB filter roll off

I have the following code in matlab:
L = 10000;
Power = -100;
A = 10^0.5;
Fs = 25e6;
fc1 = 100;
fc2 = 1e3;
fc3 = 10e3;
fc4 = 100e3;
fc5 = 1e6;
a1 = 2*pi*fc1/Fs;
a2 = 2*pi*fc2/Fs;
a3 = 2*pi*fc3/Fs;
a4 = 2*pi*fc4/Fs;
a5 = 2*pi*fc5/Fs;

x = wgn(1,L,Power);
y1 = zeros(1,L);
y2 = zeros(1,L);
y3 = zeros(1,L);
y4 = zeros(1,L);
y5 = zeros(1,L);
y = zeros(1,L);
for i = 2:L,
    y1(i) = (1-a1)*y1(i-1) + a1*x(i);
    y2(i) = (1-a2)*y2(i-1) + a2*x(i)/A;
    y3(i) = (1-a2)*y3(i-1) + a3*x(i)/A^2;
    y4(i) = (1-a2)*y4(i-1) + a4*x(i)/A^3;
    y5(i) = (1-a2)*y5(i-1) + a5*x(i)/A^4;
    y(i) = y1(i) + y2(i) + y3(i) + y4(i) + y5(i);
end
fft1 = fft(y);
fft1 = fft1(1:length(y)/2+1);
psd1 = (1/(Fs*length(y)))*abs(fft1).^2;
psd1(2:end-1) = 2*psd1(2:end-1);
freq = 0:Fs/length(y):Fs/2;
figure(3);
semilogx(freq,10*log10(psd1))
grid on

Ts = 40e-9;
z = tf('z',Ts);
H1 = a1/(1-(1-a1)*z^-1);
H2 = (a2/A)/(1-(1-a2)*z^-1);
H3 = (a3/A^2)/(1-(1-a3)*z^-1);
H4 = (a4/A^3)/(1-(1-a4)*z^-1);
H5 = (a5/A^4)/(1-(1-a5)*z^-1);
H = (H1 + H2 + H3 + H4 + H5);
figure(5);
bode(H),grid

The intent of this code is to model flicker noise, which has 10dB/dec of slope in its power spectral density.
To model that there is a filter whose output is y(i) and input x(i) which is white guassian noise in this case. In the bode plot of the filter (labelled as figure 5) I can see that it has 10dB/dec of roll-off as I intended.
But when I check the output noise (y(i) in this case) power spectral density (labelled as figure 3) I am seeing 20dB/dec of roll-off.
Could someone please explain what I did wrong and why I am not able to get the 10dB roll-off in power spectral density?

A:

Your bode plot uses a transfer function which is the sum of 5 similar subfilters, each using a coefficient ai. In your implementation, you should similarly have 5 subfilters with a regular structure. Howerver, while copying each line you have left some of the coefficients for y3, y4 and y5 to use a2. You should get your expected result by simply substituting the respective a3, a4 and a5 like so:
for i = 2:L,
    y1(i) = (1-a1)*y1(i-1) + a1*x(i);
    y2(i) = (1-a2)*y2(i-1) + a2*x(i)/A;
    y3(i) = (1-a3)*y3(i-1) + a3*x(i)/A^2;
    y4(i) = (1-a4)*y4(i-1) + a4*x(i)/A^3;
    y5(i) = (1-a5)*y5(i-1) + a5*x(i)/A^4;
    y(i) = y1(i) + y2(i) + y3(i) + y4(i) + y5(i);
end


Q:

Calculation of JQuery in while loop

Trying to calculate Break Even Point (BEP) using jquery:

function roundToTwo(num) {
  return +(Math.round(num * 100) / 100);
}
var text = ""
var quantity = 1;
var buy = 0;
var sell = 10;
var bep_pnl = -0.5;
if (buy == 0) {
  buy = roundToTwo(sell - 0.01);
  while (bep_pnl < 0.01) {
    total_amnt_trade = roundToTwo((quantity * buy) + (quantity * sell));
    var brokerage_amnt_buy = ((buy * quantity) * 0.08) / 100;
    if (brokerage_amnt_buy >= 25) {
      var brokerage_buy = 25;
    } else {
      var brokerage_buy = brokerage_amnt_buy;
    }
    var brokerage_amnt_sell = ((sell * quantity) * 0.08) / 100;
    if (brokerage_amnt_sell >= 25) {
      var brokerage_sell = 25;
    } else {
      var brokerage_sell = brokerage_amnt_sell;
    }
    var brokerage = roundToTwo(brokerage_buy + brokerage_sell); //brokerage
    var transaction_charges = roundToTwo((((buy * quantity) + (sell * quantity)) * 0.00325) / 100); //Transaction Charges
    var gst = roundToTwo((((transaction_charges * 18) / 100) + (brokerage * 18) / 100)); //GST

    var total_charges = roundToTwo(brokerage + transaction_charges + gst);
    bep_pnl = roundToTwo(((sell - buy) * quantity) - total_charges);

    text += "
New Buy " + buy + " and profit " + bep_pnl;

    buy = roundToTwo(buy - 0.01);
  }
  var bep = roundToTwo(sell - buy);
  $('#demo').text(bep);
  document.getElementById("testing").innerHTML = text;
}

While running the above codes the result of BEP is 0.04. But it should be 0.

I think it's a technical problem (maybe in while loop) as the formula is correct. (Can be cross-checked in

A:

It's that extra buy = roundToTwo(buy - 0.01); before the while loop expires that's giving the .04 result. You need to decrement buy at the beginning of the loop, not the end. Set buy = sell before it enters the while, then move buy = roundToTwo(buy - 0.01); to the beginning of the loop.
That would give .03 as the result of var bep = roundToTwo(sell - buy);, which is consistent with the output New Buy 9.97 and profit 0.01.


Q:

filter data for current month and 2 months in future

I have following controller code snippet:
public List<User_Stats__c> getSalesReps(){
    Integer regnInt = (regn!=null) ? Integer.valueOf(regn) : -1;
    Sales_Rep=[Select Id, Month__c,Year__c, Rental_Revenue_Goal__c From User_Stats__c where Sales_Rep__c =: OSR and Region__c =: regnInt and District__c =: dist and Sales_Rep__c != null and Rental_Revenue_Goal__c != null ORDER BY Month__c];
    Sales_Rep.sort();
    return Sales_Rep;
}

I want to filter this data only for current month and two months after that. i.e. if the current month is Jan then I want data for Jan, Feb and March. How can I do this?

A:

Something like this should work even when current month is December and the year boundary changes. Untested ;)
Date today = System.today();
Date monthPlus1 = today.addMonths(1), monthPlus2 = today.addMonths(2);

List<User_Stats__c> stats = [Select Id, Month__c,Year__c
    From User_Stats__c
    where (Month__c = :today.month() AND Year__c = :today:year())
        OR (Month__c = :monthPlus1.month() AND Year__c = :monthPlus1.year())
        OR (Month__c = :monthPlus2.month() AND Year__c = :monthPlus2.year())
    ORDER BY Year__c, Month__c];

You'd have to wrap this whole WHERE clause in 1 AND so you can put back the rest of your criteria...

It does look a bit stupid. I guess you could make a Date formula field that would have DATE(Year__c, Month__c, 1) in the definition and then you could use the SOQL date range literals... But the formulas aren't indexed so a full table scan would be needed depending on how selective the other criteria are...
Then again if you'd make this field (either a formula field or something set by simple workflow) your users could benefit a lot from standard date filters in reports ;)


Q:

Javascript document.getElementById("id").value returning null instead of empty string when the element is an empty text box

I have a text box element whose value I am trying to access using document.getElementById("id-name").value. I find that the call is returning a null instead of empty string. The data-type of the returned value is still string. Is null a string value?
<input type="text" value="" id="mytext"> is the textbox whose value I am trying to fetch using var mytextvalue = document.getElementById("mytext").value;

A:

Posting your HTML might help a bit. Instead, you can get the element first and then check if it is null or not and then ask for its value rather than just asking for the value directly without knowing if the element is visible on the HTML or not.
element1 = document.getElementById(id);

if(element1 != null)
{
    //code to set the value variable.
}

A:

fyi, this can happen if you are using the html type="number" attribute on your input tag.  Entering a non-number will clear it before your script knows what's going on.


Q:

html page alignment issue

I am developing an html page on Windows platform. I find when the resolution (or size, in pixels) of browser (display) is larger than the page size, the page will be aligned to the left of the browser, and I want to align the page to the center (middle) of the browser when the page size is smaller than browser.
Any ideas how to implement this and how to find the root cause why aligned to left? The html page is big and not convenient to paste html code here.
thanks in advance,
George

A:

Any ideas how to implement this and

http://dorward.me.uk/www/centre/

how to find the root cause why aligned to left?

… because that is the default.


Q:

Why is setup() executed twice at runtime?

Code:
void setup() {
  Serial.begin(9600);
  Serial.println("hello");
}

void loop() {
}

Output:
hello
hello

Why does hello print twice?

A:

It isn't, it's displaying the previous message from when you didn't have the Serial Monitor open yet, plus the new message caused by the Arduino resetting from the Serial Monitor being opened.
If you put a longer message in there you'll probably see the first line get cut off and then the full line.


Q:

How can I get an item in a specific row in a list from a database?

I have been searching through a lot of questions but they don't ask or answer what I'm looking for, so here is what I'm trying to do.
So far I have an project in witch I added a pre populated database, with a table that contains 6 columns of data, the main xml just displays the list view, I'm using a Adapter, Cursor, SQLiteHelper etc. all works fine and displays my custom itemlist.xml all good, now in every item of the list I display only 3 things (second, fourth and fifth column data) of each record (they all contain 6 coluns like I mention before), I want to be able with a onclickitemlistener to display in a toast the data from the third column for that item, how do I accomplish that? I'm able to get the list item id displayed, so can someone help me here, Thanks
here is som code:
Code from y main activity
public class DBlistActivity extends Activity {

private mediosHelper dbmediosHelper = null;
private Cursor ourCursor = null;
FancyAdapter adapter = null;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ListView myListView = (ListView) findViewById(R.id.mylistView);

    dbmediosHelper = new mediosHelper(this);
    try {
        dbmediosHelper.createDataBase();
} catch (IOException ioe) {
    throw new Error("Unable to create database");
}
try {
    dbmediosHelper.openDataBase();
}catch(SQLException sqle){
    throw sqle;
}
try {
ourCursor = dbmediosHelper.getCursor();
startManagingCursor(ourCursor);
}catch(SQLException sqle){

    throw sqle;

}

adapter = new FancyAdapter(ourCursor);
myListView.setAdapter(adapter);

myListView.setOnItemClickListener(onListClick);

}

class FancyAdapter extends CursorAdapter {
        FancyAdapter(Cursor c) {
                super (DBlistActivity.this, c);
        }
                public void bindView(View row, Context ctxt, Cursor c) {
                    ViewHolder holder = (ViewHolder) row.getTag();
                    holder.populateForm(c, dbmediosHelper);
}
                public View newView(Context ctxt, Cursor c, ViewGroup parent){
                    LayoutInflater inflater = getLayoutInflater();
                    View row = inflater.inflate(R.layout.listitem, parent, false);
                    ViewHolder holder = new ViewHolder(row);
                    row.setTag(holder);
                    return(row);
                }
}

class ViewHolder{
    public TextView nombre=null;
    public TextView estado=null;
    public TextView ciudad=null;
    ViewHolder (View row){
        nombre = (TextView) row.findViewById(R.id.medioName);
        estado = (TextView) row.findViewById(R.id.medioEstado);
        ciudad = (TextView) row.findViewById(R.id.medioCiudad);
    }
    void populateForm(Cursor c, mediosHelper r){
        nombre.setText(r.getName(c));
        estado.setText(r.getEstado(c));
        ciudad.setText(r.getCiudad(c));
    }
}

private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id){
        Toast.makeText(getApplicationContext(), String.valueOf(id), Toast.LENGTH_SHORT) .show();
    }
};

And from my mediosHelper
public Cursor getCursor() {
    SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
    queryBuilder.setTables(TABLE_NAME);
    String[] asColumsToReturn = new String[] { COLUMN_ID, COLUMN_CODE, COLUMN_NAME, COLUMN_URL, COLUMN_ESTADO, COLUMN_CIUDAD};
    Cursor mCursor = queryBuilder.query(myDataBase, asColumsToReturn, null, null, null, null, null);
    return mCursor;
}
public CharSequence getId(Cursor c) {
    return (c.getString(0));
}
public CharSequence getCode(Cursor c) {
    return (c.getString(1));
}
public String getName(Cursor c){
    return(c.getString(2));
}
public String getUrl(Cursor c) {
    return (c.getString(3));
}
public String getEstado(Cursor c) {
    return (c.getString(4));
}
public String getCiudad(Cursor c) {
    return (c.getString(5));
}

A:

you need to get the cursor you used to fill the adapter. once you have that move it to the position you get in the onItemClickedCallback with c.moveToPosition(position). Than you have access to all columns (cursor.getColumnIndex("_id"))
EDIT:
class MyActivity extends Activity implements OnItemClickListener{
FancyAdapter adapter = null;
...

adapter = new FancyAdapter(ourCursor);
myListView.setAdapter(adapter);

myListView.setOnItemClickListener(this);

@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    // TODO Auto-generated method stub
Cursor c = adapter.getCursor();
    c.moveToPosition(position);
    int id = c.getInt(c.getColumnIndex("_id");
}
}


Q:

Low performance in queries using $where even with non-existing collections

I implemented in my code the following sequence on a MongoDB server: 1) query the "entities" collection, 2) update the "entities" collection and 3) query the "csubs" collection. The last one (query on "csubs" collection) uses a $where operator.
I'm running a test which executes the above three-steps sequence hundreds of times per second. As precondition for this test, "csubs" collection is empty (i.e. shows collection doesn't even show it). Thus, intuition says that step 3) should be ultra-fast.
I have done the test both with MongoDB 2.4 and MongoDB 2.6, getting the following results with mongotop ("qatest" is the name of the DB):
MongoDB 2.4.9:
                        ns       total        read       write
           qatest.entities       451ms       189ms       262ms
              qatest.csubs       447ms       447ms         0ms

MongoDB 2.6.10:
                        ns       total        read       write
              qatest.csubs      2315ms      2315ms         0ms
           qatest.entities       121ms        54ms        67ms

Based on this results, I have two questions:

Why is query on "csubs" so slow? I understand that the usage of $where could have a query cost but I have expected that cost to be proportional to the number of documents to process in the target collection. But in this case, the documents number in the collection is 0, given that the collection doesn't exist. Is there any "bootstraping" cost related with $where (e.g. creating a JavaScript VM context to execute the query) associated to the query itself and independent of the collection (and its size) to be queried?
Assuming that such bootstraping cost exist, why is so different from MongoDB 2.4 and MongoDB 2.6? In particular, it gets worse in MongoDB 2.6 (which I understand should be more advanced, from a performance point of view). Has the way in which server JavaScript works changed in MongoDB 2.6?

A:

Finally, it is confirmed that it is due to a "bootstrapping" cost that happens in MongoDB 2.6 but not in MongoDB 2.4. See this ticket in the MongoDB JIRA tracker for more information.


Q:

Convert List stream into single Container

Consider the below WorkExperience class:
public class WorkExperience {
    private int year;
    private List<Skills> skill;

    public WorkExperience(int year, List<Skills> skill) {
        this.year = year;
        this.skill = skill;
    }
    //getter setter
}

public class Skills {
    private String skills;

    public Skills(String skills) {
        this.skills = skills;
    }

    @Override
    public String toString() {
        return "Skills [skills=" + skills + "]";
    }
}

let's say I want to group by my skills by year, this is how we can do groupBy by year:
public static void main(String[] args) {

    List<Skills> skillSet1 = new  ArrayList<>();
    skillSet1.add(new Skills("Skill-1"));
    skillSet1.add(new Skills("Skill-2"));
    skillSet1.add(new Skills("Skill-3"));

    List<Skills> skillSet2 = new  ArrayList<>();
    skillSet2.add(new Skills("Skill-1"));
    skillSet2.add(new Skills("Skill-4"));
    skillSet2.add(new Skills("Skill-2"));

    List<Skills> skillSet3 = new  ArrayList<>();
    skillSet3.add(new Skills("Skill-1"));
    skillSet3.add(new Skills("Skill-9"));
    skillSet3.add(new Skills("Skill-2"));

    List<WorkExperience> workExperienceList = new ArrayList<>();
    workExperienceList.add(new WorkExperience(2017,skillSet1));
    workExperienceList.add(new WorkExperience(2017,skillSet2));
    workExperienceList.add(new WorkExperience(2018,skillSet3));

    Map<Integer, Set<List<Skills>>> collect = workExperienceList.stream().collect(
        Collectors.groupingBy(
            WorkExperience::getYear,
            Collectors.mapping(WorkExperience::getSkill, Collectors.toSet())
        )
    );
}

groupBy is returning: Map<Integer, Set<List<Skills>>>
but what I need is: Map<Integer, Set<Skills>>
How to convert List stream into single Container?

A:

An alternative to flatMapping using Java 8 features only would be
Map<Integer, Set<Skills>> map = workExperienceList.stream()
    .collect(Collectors.toMap(
        WorkExperience::getYear,
        we -> new HashSet<>(we.getSkill()),
        (s1, s2)-> { s1.addAll(s2); return s1; }));

you may optimize this a bit
Map<Integer, Set<Skills>> map = workExperienceList.stream()
    .collect(Collectors.toMap(
        WorkExperience::getYear,
        we -> new HashSet<>(we.getSkill()),
        (s1, s2) -> {
            if(s1.size() > s2.size()) { s1.addAll(s2); return s1; }
            else { s2.addAll(s1); return s2; }
        }));

A:

We can use Collectors.flatMapping  collector added in Java-9. By using flatMapping, we can flatten the intermediate Lists into a single container. flatMapping can be used in the cases where elements of the original stream are convertible to a stream.
workExperienceList.stream().collect(Collectors.groupingBy(
                              WorkExperience::getYear,
                              Collectors.flatMapping(workexp -> workexp.getSkill().stream(),
                                             Collectors.toSet())));

API Note:

The flatMapping() collectors are most useful when used in a multi-level reduction, such as downstream of a groupingBy or partitioningBy.


Q:

Set current PC date and Time as Default in RadDatePicker

In telerik:RadDatePicker the Date is By default Current Date but time is by default 12:00:00 AM, 06-11-14 12:00 AM. I want to set current PC date and Time  as Default in   RadDatePicker

A:

In the Page_Load of your code-behind:
myDatePicker.SelectedDate = DateTime.Now;


Q:

Can the POTUS be the monarch of the UK at the same time?

A tweet on my timeline caught my interest today:

Prince Harry's kids will be Americans. What if one grows up to be president and is in line for the throne at the same time? Brits are playing long-ball here, but it's a smart move. They want America back and this is how they'll do it.
—Greg Pollowitz on Twitter

Is there any legal barrier in either the UK or the USA which stipulate that the President of the United States cannot be the Monarch of the United Kingdom, or vice versa?

A:

I can't speak to requirements for the UK monarchy, but on the US side, it appears to be legally possible for someone in line to the throne to become President.  The only constitutional requirements are:

No Person except a natural born Citizen, or a Citizen of the United States, at the time of the Adoption of this Constitution, shall be eligible to the Office of President; neither shall any Person be eligible to that Office who shall not have attained to the Age of thirty five Years, and been fourteen Years a Resident within the United States. [ref]

and

No person shall be elected to the office of the President more than twice, and no person who has held the office of President, or acted as President, for more than two years of a term to which some other person was elected President shall be elected to the office of the President more than once. [ref]

Obviously, there's no guarantee of being elected, and the nature of the situation practically writes the attack ads from opponents (similar to criticisms of Kennedy about being a Catholic and thus answerable to the Pope).

However, it's a very different story when it comes to actually inheriting the crown while in office.  Article I, Section 9, clause 8 of the Constitution (also called the Emoluments Clause) states

No Title of Nobility shall be granted by the United States: And no Person holding any Office of Profit or Trust under them, shall, without the Consent of the Congress, accept of any present, Emolument, Office, or Title, of any kind whatever, from any King, Prince, or foreign State. [ref]

I think everyone can agree that becoming the King or Queen of the UK would constitute "accepting an Office or Title from a foreign State".  Thus, the POTUS/heir would require Congressional approval to accept the crown.  Without it, they could choose to resign as POTUS or abdicate the crown, but they could not hold both.
The same logic may apply to being named Crown Prince/ess (due to the death or abdication of a prior claimant).  The person in question would still be the heir apparent, but would be unable to receive any of the associated lands or titles until Congress approved or they left office.
It's also worth noting that none of these requirements are unique to the President.  Anyone holding any elected or appointed office in the US would have the same restrictions on taking the crown without Congressional approval.


Q:

Create instance of ActionBar Xamarin Android

Iam using A ActionBar in my app. I have done something like so:-
ActionBar.SetDisplayHomeAsUpEnabled(true);
ActionBar.SetHomeButtonEnabled(true);

But I get a compilation error like:-
A object reference is required for the non-static field, method, or property 'Android.Support.V7.App.ActionBar.SetDisplayHomeAsUpEnabled(bool)'

How can I create a instance of ActionBar as it is a Abstract class?
EDIT:-
With waquaslam's solution I did this:-
public class Homescreen : ActionBarActivity
{

    private DrawerLayout _drawer;
    private MyActionBarDrawerToggle _drawerToggle;
    private ListView _drawerList;
    private static ActionBar ActionBar ;

    private string _drawerTitle;
    private string _title;
    private string[] _planetTitles;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        SupportRequestWindowFeature(WindowCompat.FeatureActionBar);

        SetContentView(Resource.Layout.homescreen);

        _title = _drawerTitle = Title;
        _planetTitles = Resources.GetStringArray(Resource.Array.TitlesArray);
        _drawer = FindViewById<DrawerLayout>(Resource.Id.drawer_layout);
        _drawerList = FindViewById<ListView>(Resource.Id.left_drawer);

        _drawer.SetDrawerShadow(Resource.Drawable.drawer_shadow_dark, (int)GravityFlags.Left);

        _drawerList.Adapter = new ArrayAdapter<string>(this,
            Resource.Layout.drawerlistitem, _planetTitles);
        _drawerList.ItemClick += (sender, args) => SelectItem(args.Position);

        SupportActionBar.SetDisplayHomeAsUpEnabled(true);

        SupportActionBar.SetHomeButtonEnabled(true);

        //DrawerToggle is the animation that happens with the indicator next to the
        //ActionBar icon.
        _drawerToggle = new MyActionBarDrawerToggle(this, _drawer,
                                                  Resource.Drawable.ic_drawer_light,
                                                  Resource.String.DrawerOpen,
                                                  Resource.String.DrawerClose);

        //You can alternatively use _drawer.DrawerClosed here
        _drawerToggle.DrawerClosed += delegate
        {
            ActionBar.Title = _title;
            //InvalidateOptionsMenu();
        };

        //You can alternatively use _drawer.DrawerOpened here
        _drawerToggle.DrawerOpened += delegate
        {
            ActionBar.Title = _drawerTitle;
            // InvalidateOptionsMenu();
        };

        _drawer.SetDrawerListener(_drawerToggle);

        if (null == savedInstanceState)
            SelectItem(0);

    }

Now I get  a NoClassDefinitionFoundError.

A:

If you are using support.V7 then make sure your activity inherits from ActionBarActivity.
In order to get reference of ActionBar in compatibility library, you must need to use the following:
SupportActionBar.SetDisplayHomeAsUpEnabled(true);
SupportActionBar.SetHomeButtonEnabled(true);

For more info, read this in which the example is based on Tabs in actionbar but using support library.


Q:

How to loop through category group and identify those related to entry

Looping through a category group to show links to all the categories. This is an entry page and I want to highlight any categories assigned to the entry. How do I do that? I've tried this so far:
{% set cats = craft.categories.group('events').find() %}
{% for cat in cats %}
    {{ cat.title }}
{% endfor %}

A:

Your solution looks like it's almost there, but it would be making a lot of DB queries as Craft will be querying the database for each category. You can give Craft all the help you can with something like this.
{# First, retrieve all of your events categories #}
{% set cats = craft.categories.group('events').find() %}

{# Get the IDs of all categories related to this entry #}
{% set relatedCats = craft.categories.group('events').relatedTo({sourceElement: entry}).ids() %}

{# Test if the current category ID is in the array of related category IDs #}
{% for cat in cats %}
    {{ cat.title }}
{% endfor %}


Q:

Getting a specific decimal place

I have a money counter that increases over time which I want to animate, I'm using the below extension to run the animation but the issue is that it animates the entire label when I only want the digits that are changing to be animated.
I figured I'd split the digits up and animate each individual digit on its own, the problem is I can't figure how to break down the number and get specific digits.
is there a way I can go about breaking the number down and getting the individual digits or a better way of running the animation on individual numbers?
 func pushTransition(duration:CFTimeInterval) {
    let animation:CATransition = CATransition()
    animation.timingFunction = CAMediaTimingFunction(name:
        kCAMediaTimingFunctionEaseInEaseOut)
    animation.type = kCATransitionPush
    animation.subtype = kCATransitionFromTop
    animation.duration = duration
    self.layer.add(animation, forKey: kCATransitionPush)
}

if let aLabel = self.money{
        aLabel.pushTransition(duration: 0.2)
        aLabel.text = "$\(strRoundDollars)"
        money.sizeToFit()
        }

A:

Firstly, you want to use NumberFormatter rather than simple String interpolation, to make sure you always have the correct number of decimal places  & currency sign, etc. for your locale/currency. Then all you need to do is map the .characters property of the String back into an array of Strings:
let dollars = 123.4
let n = NumberFormatter()
n.numberStyle = .currency
n.locale = Locale.autoupdatingCurrent // or whatever locale you want
if let text = n.string(from: NSNumber(value: dollars)) {
    text // "$123.40"
    let charactersAsStrings = text.characters.map({String($0)})
    charactersAsStrings // ["$", "1", "2", "3", ".", "4", "0"]
}

Many thanks to @Sulthan for pointing out that my first answer using String(format: "$%0.2f", dollars) was shoddy :)


Q:

How to set File Info from a script in Photoshop CS4

I am developing a Photoshop CS4 script and want to set some of the File Info properties on the open document from within the script.
In other words, I want to do the equivalent of choosing File -> File Info and editing some properties, only via the scripting language (Javascript).

A:

OK, I have found it...
// Set copyright info
app.activeDocument.info.author = "Mr Blobby";
app.activeDocument.info.copyrighted = CopyrightedType.COPYRIGHTEDWORK;
app.activeDocument.info.copyrightNotice = "(c) 2009 Mr Blobby Ltd";
app.activeDocument.info.ownerUrl = "http://www.example.com/";

The docs are here...
http://www.adobe.com/devnet/photoshop/pdfs/photoshop_cs4_javascript_ref.pdf


Q:

How to initialise an integer array inside a foreach loop in Codeigniter

I have the following code in the controller of Codeigniter project:
foreach($attendace as $k => $v) {
$id = $v['project_id'];
$result[$id]['project_name'] = $v['project_name'];
$result[$id]['labour'] += $v['no_of_labours'];
$result[$id]['total_time'] += ($v['stop_time']-$v['start_time'])*$v['no_of_labours'];
}

This code gives an error unknown variable labour and total_time. And if I try to initialise these variables as following:
 foreach($attendace as $k => $v) {
    $id = $v['project_id'];
    $result[$id]['labour'] =0;
    $result[$id]['total_time']=0;
    $result[$id]['project_name'] = $v['project_name'];
    $result[$id]['labour'] += $v['no_of_labours'];
    $result[$id]['total_time'] += ($v['stop_time']-$v['start_time'])*$v['no_of_labours'];
    }

Adding $result[$id]['labour'] =0; and $result[$id]['total_time']=0; then the added value that I am getting is wrong. Basically it does not add then.
Hence, could anyone tell me how to get rid of this problem.

A:

You can try this:
if (!isset($result[$id]['labour'])) $result[$id]['labour'] = 0;
if (!isset($result[$id]['total_time'])) $result[$id]['total_time'] = 0;


Q:

Sending email to gmail with CodeIgniter displays "message sent" but there nothing in the inbox?

I'm following this amazing nettusts+ tutorial about sending a email to gmail.
It aparently worked. When I load the page it says: 'Your email was sent, fool.' but then I check my gmail and there's nothing there.
Does CodeIgniter take care of everything? Or I have to install smtp or something in my PC because I'm using localhost (LAMP in Ubuntu)?
Code:

/* SEND EMAIL WITH GMAIL */

class Email extends Controller {

    function __construct()
    {
        parent::Controller();
    }

    function index()
    {
        $config = Array(
            'protocol' => 'smtp',
            'smtp_host' => 'ssl://smtp.googlemail.com',
            'smtp_port' => 465,
            'smtp_user' => 'janoochen@gmail.com',
            'smtp_pass' => '***',
        );

        $this->load->library('email', $config);
        $this->email->set_newline("\r\n");

        $this->email->from('janoochen@gmal.com', 'Alex Chen');
        $this->email->to('janoochen@gmal.com');
        $this->email->subject('This is an email');
        $this->email->message('It is working. Great!');

        if($this->email->send())
        {
            echo 'Your email was sent, fool.';
        }

        else
        {
            show_error($this->email->print_debugger());
        }
    }
}

A:

I don't know if this is it, but in your code you've got @gmal.com instead of @gmail.com


Q:

C/C++ divisions with double and following shift operation

can anybody explain why following code generates different results?
double zaehler = -20;
double teiler = 0.08;
printf("ergebnis = %d \n", ((int) (zaehler/teiler)) << 7 );
printf("ergebnis = %d \n", (int) (-20/0.08) << 7 );

Results:
ergebnis = -31872
ergebnis = -32000

Many thanks ahead

A:

A very small rounding difference, within the range possible for the difference between 64 and 80 bits, could account for the different output. The combination of the truncate to int and shift can magnify a tiny difference. This program:
#include <stdio.h>
int main(){
    double zaehler = -20;
    double teiler = 0.08;
    printf("ergebnis = %d \n", (int) (zaehler/teiler) );
    printf("ergebnis = %d \n", (int) (-20/0.08));
}

prints:
ergebnis = -249
ergebnis = -250

If the division gives an answer even a tiny bit less than 250 the truncation to int will get 249. I suggest rounding instead of truncating.
Eclipse, MinGW:
Info: Internal Builder is used for build
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o main.o "..\\main.cpp"
g++ -o TestCPP.exe main.o


Q:

Regular expression for a (nested) html tags

I have the following text:
lorem

ipsum

lorem ipsum

and I need to make of it four groups (with regural expressions):

lorem

ipsum

lorem ipsum

lorem ipsum

I think I should do it in this way:

 - for paragraphs

 - for a whitespace after

 - for any char before p> (for classes etc.)

.*
 - for any value of paragraph

But now, If I have
Lorem

Ipsum
 I get one group ['
Lorem

Ipsum
']. I understand why but I don't know to improve it because I need to have two groups ['
Lorem
', '
Ipsum
']. How you any ideas?
PS: I use Python with re module.

A:

In re .* is greedy meaning it will match as much text as possible. Add a ? to make text not greedy as so:

.*?

Here is the documentation:
*?, +?, ??

The '*', '+', and '?' qualifiers are all greedy; they match as much text as possible.
Sometimes this behaviour isn’t desired; if the RE <.*> is matched against
'
title
', it will match the entire string, and not just '
'. Adding '?'
after the qualifier makes it perform the match in non-greedy or minimal fashion; as
few characters as possible will be matched. Using .*? in the previous expression will
match only '
'.

Documentation is available here:
https://docs.python.org/2/library/re.html


Q:

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Linq.IQueryable

I have an issue returning some data in my application using the following C# code
[Queryable(AllowedQueryOptions = System.Web.Http.OData.Query.AllowedQueryOptions.Select)]
public override IQueryable<BrokerOutright> Get()
{
 return db.BrokerOutrights.Where(b => b.BidBroker == User.Identity.Name
                                  || b.OfferBroker == User.Identity.Name)
                .Select(x => new
                {
                    x.Id,
                    x.Product,
                    x.Term,
                    (x.AskB=='dev')?x.AskB:null,
                    (x.AskB=='dev')?x.AVol:null
                }
                );
}

The above code threw me following exception

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Linq.IQueryable

May I know a good explicit conversion?

A:

Yes, because you're projecting to an anonymous type:
.Select(x => new
{
    x.Id,
    x.Product,
    x.Term
})

It sounds like you want to use an object initializer for the BrokerOutright type:
.Select(x => new BrokerOutright
{
    Id = x.Id,
    Product = x.Product,
    Term = x.Term
})

Having said that, if db.BrokerOutrights is already an IQueryable<BrokerOutright> you may just want to ditch the Select entirely:
return db.BrokerOutrights
         .Where(b => b.BidBroker == User.Identity.Name ||
                     b.OfferBroker == User.Identity.Name);

If BrokerOutright isn't a type that the LINQ provider knows about, you may need to perform the projection in LINQ to Objects instead using AsEnumerable() - but then you'd have to return an IEnumerable<BrokerOutright> instead of an IQueryable<BrokerOutright>.


Q:

Behat - Check for broken image links

Is there a way to check with Behat, if on the page there is no images with broken / corrupted links ?

A:

I would propose to find all images on the page
$imageElements = $this->getSession()->getPage()->findAll('css','img');
foreach($imageElements as $image){
    $imgUrl = $image->getAttribute('src');
    $this->visit($imgUrl);
    //Here should be assertion of valid img,
    //F.e. if you are using goutte driver check that server response is not 500 or 404
    $this->assertResponseStatusIsNot(404);
}


Q:

Pass cell value to .To and .CC

I send a range of cells from a workbook to Outlook.
I've tweaked just a little bit the following macro from Ron de Bruin http://www.rondebruin.nl/win/s1/outlook/bmail3.htm.
It's like this now (just the part that I've edited):
With Sendrng

    .Parent.Select
    Set rng = ActiveCell
    .Select
    ActiveWorkbook.EnvelopeVisible = True

    With .Parent.MailEnvelope

        With .Item
            .To = ""
            .CC = ""
            .Subject = "XXX"
            '.Attachments.Add ("C:\test.txt")
            .Display
            .Save
            .Close olPromtForSave
        End With

    End With

I want to set .To = "K1" and .CC = "M1:M4". These are cells from the same active workbook. Tweaking a little bit with the cell.Value and for For Each cell In Columns("K") from this link didn't work http://www.rondebruin.nl/win/s1/outlook/bmail5.htm.

A:

Try this:
.To = Range("K1")
For each cel in Range("M1:M4")
    Dim sCC as String
    sCC = sCC & ";" & cel.Value2
Next
.CC = Mid(sCC,2) 'to cut off initial ";"


Q:

Simplifying $2^{30} \mod 3$

I simply cannot seem to get my head around this subject of mathematics. It seems so counter-intuitive to me.
I have a question in my book: Simplify $2^{30}\mod 3$
This is my attempt: $2^{30}\mod 3 = (2\mod 3)^{30}$ (using the laws of congruences).
$2\mod 3$ must be equal to $2$, right? $0\cdot 3 + 2 = 2$ then the rest is "2". Therefore, I concluded that $2^{30}$ is the answer. However, my book says $1$. How can this be? Can anyone explain this to me? It's probably really easy, and I feel kind of stupid for asking, but I simply don't get it.
And also, are there any sites on the internet that provide similar problems with which you can learn the concepts?
Thank you.

A:

Because $2 \equiv -1 \pmod 3$, we have
$$ 2^{30} \equiv (-1)^{30}\equiv 1 \pmod 3.$$


Q:

Iterate Multi-Dimensional Array with Nested Foreach Statement

I think this might be a pretty simple question, but I haven't been able to figure it out yet. If I've got a 2-dimensional array like so:
int[,] array = new int[2,3] { {1, 2, 3}, {4, 5, 6} };

What's the best way to iterate through each dimension of the array with a nested foreach statement?

A:

If you want to iterate over every item in the array as if it were a flattened array, you can just do:
foreach (int i in array) {
    Console.Write(i);
}

which would print

123456

If you want to be able to know the x and y indexes as well, you'll need to do:
for (int x = 0; x < array.GetLength(0); x += 1) {
    for (int y = 0; y < array.GetLength(1); y += 1) {
        Console.Write(array[x, y]);
    }
}

Alternatively you could use a jagged array instead (an array of arrays):
int[][] array = new int[2][] { new int[3] {1, 2, 3}, new int[3] {4, 5, 6} };
foreach (int[] subArray in array) {
    foreach (int i in subArray) {
        Console.Write(i);
    }
}

or
int[][] array = new int[2][] { new int[3] {1, 2, 3}, new int[3] {4, 5, 6} };
for (int j = 0; j < array.Length; j += 1) {
    for (int k = 0; k < array[j].Length; k += 1) {
        Console.Write(array[j][k]);
    }
}

A:

Here's how to visit each element in a 2-dimensional array.  Is this what you were looking for?
for (int i=0;i<array.GetLength(0);i++)
{
    for (int j=0;j<array.GetLength(1);j++)
    {
        int cell = array[i,j];
    }
}

A:

With multidimensional arrays, you can use the same method to iterate through the elements, for example:
int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
foreach (int i in numbers2D)
{
    System.Console.Write("{0} ", i);
}

The output of this example is:
9 99 3 33 5 55

References

MSDN: Using foreach with Arrays

In Java, multidimensional arrays are array of arrays, so the following works:
    int[][] table = {
            { 1, 2, 3 },
            { 4, 5, 6 },
    };
    for (int[] row : table) {
        for (int el : row) {
            System.out.println(el);
        }
    }


Q:

Adding up an attribute inside entity for CoreData ios 10

I have a tableView and that tableview is being populated with data from Coredata. The data breaks down like this.
Entity - Person
Entity - Statement
The statement entity has an attribute called amountOwed and it is of decimal type.
The relationships is that a person can have many statements, but each statement belongs to a single person.
Here is the path of the data that I would like to add up. Person > Statement > AmountOwed.
In the tableView function I have a let that represents the Person entity.
let person = fetchedResultsController.object(at: indexPath)

I know its working because I can print out the persons name like so
print(person.name) // Bob

What I want to be able to do is add up all the amountOwed attributes for each Person inside the Statement entity and display them on a cell.
I have been trying to follow an example of calculated fetches but I seem to not quiet understand how to target my Statements Entities which are linked to each Person entity.
 let fetchRequest = NSFetchRequest<NSDictionary>(entityName:"statement")
            fetchRequest.resultType = .dictionaryResultType

            let sumExpressionDesc = NSExpressionDescription()
            sumExpressionDesc.name = "sumDeals"

            let specialCountExp = NSExpression(forKeyPath: #keyPath(Person.statement[indexPath].amountOwed))

            sumExpressionDesc.expression = NSExpression(forFunction: "sum:", arguments: [specialCountExp])

            sumExpressionDesc.expressionResultsType = .interger32AttributeType

            fetchRequest.propertiesToFetch = [sumExpressionDesc]

            do{
                let results = try coreDataStack.managedContext.fetch(fetchRequest)

                let resultDict = results.first!
                let numDeals = resultDict["sumDeals"]
                print(numDeals!)
            }

            catch let error as NSError{
                print("Count not fetched \(error), \(error.userInfo)")
            }

Do I need to fetch a Statement entity or should I just use the FetchedREsultsController? If I do use my fetchedResultsController does the keypath to the Statement Entity look like this
person[indexPath].statement.amountOwed

A:

You can do that in one line. If the relationship from Person to Statement is called statements, you get the total of the amounts with
let amountTotal = newPerson.value(forKeyPath: "statements.@sum.amount") as? Int64

Change the downcast at the end from Int64 to whatever is appropriate for your amount attribute-- Double or whatever.


Q:

Elegant way to get the first n elements of a SequenceType

Is there an elegant way (think one-liner) to get the first n elements of a SequenceType in Swift?
I could of course write a for-loop that terminates after n elements but that's a little bulky.
Note also that the solution should be able to deal with infinite sequences.

A:

Isn't it exactly what mySequence.prefix(numberOfElements) does?


Q:

Remove value from localStorage in Vuejs

friends
Problem
I have the problem that when I am in the video section watching a particular episode, in the local storage the src of the video that I saw before is stored.
My intention is to eliminate the value of the local storage once it leaves the video section.

Template Video
<template>

          <video
            id="video"
            controls
          ><source :src="videos.video" type="video/mp4"></video>

                video
                {{content}}
                {{state}}
                eps - {{eps}}
                {{Title}}
                <svg class="fill-current opacity-75 h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path d="M12.95 10.707l.707-.707L8 4.343 6.586 5.757 10.828 10l-4.242 4.243L8 15.657l4.95-4.95z"/></svg>

            {{synopsis}}

                 ライウアニミー

</template>

Script
What I have implemented In the mounted property is that if the video exists, it eliminated the obj videos that belongs to the key vuex.
But what I have done does not do anything, when I leave the video section the video object maintains the src of the video.

Mutation
I think what I have to do is create a mutation to clean the localstorage
export const mutations = {
  initialiseStore(state) {
    // Check if the ID exists
    if(localStorage.getItem('store')) {
      // Replace the state object with the stored item
      this.replaceState(
        Object.assign(state, JSON.parse(localStorage.getItem('store')))
      );
    }
  },
  SET_LATEST_DATA(state , payload){
    state.latest = payload;
  },
  SET_VIDEO_ANIME(state , payload){
    state.videos = payload;
  },
  SET_ANIME_ALPHA(state , payload){
    state.animesByAlpha = payload;
  },
  SET_ANIME_GENDER(state , payload){
    state.animesByGender = payload;
  },
  SET_ANIME_SEARCH(state , payload){
    state.searchAnimeList = payload;
  },
  SET_GET_SCHEDULE(state , payload){
    state.schedule = payload;
  },
  SET_MOVIES(state , payload){
    state.movies = payload;
  },
  SET_OVAS(state , payload){
    state.ovas = payload;
  },
  IS_LOADING(state , payload){
    state.isLoading = payload;
  }
};

Action
 GET_ANIME_VIDEO({commit} , info){
    console.log("id: " , info.id , "chapter: " , info.eps)
    A.get(`${API_URL_ENDPOINT.video}` + "/" + `${info.id}` + "/" + `${info.eps}`)
      .then((res) =>{
        console.log("video src = " , res.data)
        commit('SET_VIDEO_ANIME' , res.data);
        commit('IS_LOADING' , false);
      }).catch((err) =>{
      console.error(err);
    });
  },

A:

My Solution
I found the solution, but I do not know if it is the most optimal. But he does the cleaning.
beforeDestroy(){
  const vuex = JSON.parse(localStorage.getItem('vuex'));
  if(vuex.videos){
    localStorage.removeItem(vuex.videos);
  }
}

Actual Problem
When I leave the video session and I want to go see another video, the screen of the previous video remains
My intention is to keep the screen black and the minutes of the video at zero


Q:

Task scheduler stops running C# console application periodically

I have a task scheduler which runs a C# console application every minute. It runs the .application file via a .bat file and does so successfully for a period of time before stopping completely.
Un-installing/re-installing my console application doesn't fix the problem and the task scheduler is showing the batch file as succesfully executing. Also, running the program manually works just fine.
My questions are:

How can I get this task to run again via the task scheduler. I have tried deleting and re-creating the task, uninstalling/reinstalling the applcation.
I have a scheduled backup task occuring around the time the application stops working. Volume shadow copy is not enabled. Could this be impacting my application and why?

A:

Despite the help, I did not manage to isolate the cause of this problem.
I have re-developed my scheduler using Quartz.NET and it's now running as a Windows service.


Q:

Load string that's not quite JSON in Python

I am receiving a response from a service in text format  unfortunately I cannot ask them to send me in JSON format) below is the reponse:
'{message: Successfully sent data for processing, execId: d03c96hg-4098-47b9-9e4b-3cb2c}'

I want to either convert this to dict or json but I am unable to do so, as the string inside the '{ }' does not have single or double quotes.
I have tried using json.loads(), json.dumps(), ast.literal() and also few other methods, but was not able to achieve the desired output.
The output desired is:
{'message': 'Successfully sent data for processing', 'execId' : 'd03c96hg-4098-47b9-9e4b-3cb2c' }

A:

data = '{message: Successfully sent data for processing, execId: d03c96hg-4098-47b9-9e4b-3cb2c}'
// actual string message: Successfully sent data for processing, execId: d03c96hg-4098-47b9-9e4b-3cb2c

    data_str = data[1:-1]
    t_arr = data_str.split(',')
    data_dict = {}
    for data in t_arr :
        temp = data.split(':')
        data_dict[str(temp[0].strip())] = str(temp[1].strip())

    print data_dict


Q:

Рекурсия в регулярных выражениях

Здравствуйте.
Есть регулярное выражение (для примера)

/ \( ( [^)(]+ | (?R) )+ \) /x

(?R) означает рекурсивную ссылку на само регулярное выражение, где можно найти обработчик регулярных выражений, поддерживающих такие рекурсии для Java или Python ?
Стандартные java.util.regex и питоновский regex кажется не имеют поддержки этого механизма.
Регулярное выражение взято здесь.

A:

https://pypi.python.org/pypi/regex
Альтернативный движок для регулярных выражений питона с поддержкой рекурсий.

Java движка кажется не существует в настоящее время.