text:
Q: My solution to this programming challenge is wrong because it outputs the wrong answer for 10/11 test cases. What are those test cases? I am doing this programming challenge which can be found at www.interviewstreet.com (its the first challenge worth 30 points).
When I submitted the solution, I was returned a result which said that the answer was wrong because it only passed 1/11 test cases. However, I feel have tested various cases and do not understand what I am doing wrong. It would be helpful to know what those test cases could be so that I can test my program.
Here is the question (in between the grey lines below):

Quadrant Queries (30 points)
There are N points in the plane. The ith point has coordinates (xi, yi). Perform the following queries:
1) Reflect all points between point i and j both including along the X axis. This query is represented as "X i j"
2) Reflect all points between point i and j both including along the Y axis. This query is represented as "Y i j"
3) Count how many points between point i and j both including lie in each of the 4 quadrants. This query is represented as "C i j"
Input:
The first line contains N, the number of points. N lines follow.
The ith line contains xi and yi separated by a space.
The next line contains Q the number of queries. The next Q lines contain one query each, of one of the above forms.
All indices are 1 indexed.
Output:
Output one line for each query of the type "C i j". The corresponding line contains 4 integers; the number of points having indices in the range [i..j] in the 1st,2nd,3rd and 4th quadrants respectively.
Constraints:
1 <= N <= 100000
1 <= Q <= 100000
You may assume that no point lies on the X or the Y axis.
All (xi,yi) will fit in a 32-bit signed integer
In all queries, 1 <=i <=j <=N
Sample Input:
4
1 1
-1 1
-1 -1
1 -1
5
C 1 4
X 2 4
C 3 4
Y 1 2
C 1 3
Sample Output:
1 1 1 1
1 1 0 0
0 2 0 1
Explanation:
When a query says "X i j", it means that take all the points between indices i and j both including and reflect those points along the X axis. The i and j here have nothing to do with the co-ordinates of the points. They are the indices.  i refers to point i and j refers to point j
'C 1 4' asks you to 'Consider the set of points having index in {1,2,3,4}. Amongst those points, how many of them lie in the 1st,2nd,3rd and 4th quads respectively?'
The answer to this is clearly 1 1 1 1.
Next we reflect the points between indices '2 4' along the X axis. So the new coordinates are :
1 1
-1 -1
-1 1
1 1
Now 'C 3 4' is 'Consider the set of points having index in {3,4}. Amongst those points, how many of them lie in the 1st,2nd,3rd and 4th quads respectively?' Point 3 lies in quadrant 2 and point 4 lies in quadrant 1.
So the answer is 1 1 0 0

I'm coding in PHP and the method for testing is with STDIN and STDOUT.
Any ideas on difficult test cases to test my code with? I don't understand why I am failing 10 / 11 test cases.
Also, here is my code if you're interested:
// The global variable that will be changed
$points = array();

/******** Functions ********/
// This function returns the number of points in each quadrant.
function C($beg, $end) {
    // $quad_count is a local array and not global as this gets reset for every C operation
    $quad_count = array("I" => 0, "II" => 0, "III" => 0, "IV" => 0);

    for($i=$beg; $i<$end+1; $i++) {
        $quad = checkquad($i);
        $quad_count[$quad]++;
    }

    return $quad_count["I"]." ".$quad_count["II"]." ".$quad_count["III"]." ".$quad_count["IV"];
}

// Reflecting over the x-axis means taking the negative value of y for all given points
function X($beg, $end) {
    global $points;

    for($i=$beg; $i<$end+1; $i++) {
        $points[$i]["y"] = -1*($points[$i]["y"]);
    }
}

// Reflecting over the y-axis means taking the negative value of x for all given points
function Y($beg, $end) {
    global $points;

    for($i=$beg; $i<$end+1; $i++) {
        $points[$i]["x"] = -1*($points[$i]["x"]);
    }
}

// Determines which quadrant a given point is in
function checkquad($i) {
    global $points;

    $x = $points[$i]["x"];
    $y = $points[$i]["y"];

    if ($x > 0) {
        if ($y > 0) {
            return "I";
        } else {
            return "IV";
        }
    } else {
        if ($y > 0) {
            return "II";
        } else {
            return "III";
        }
    }
}

// First, retrieve the number of points that will be provided. Make sure to check constraints.
$no_points = intval(fgets(STDIN));
if ($no_points > 100000) {
    fwrite(STDOUT, "The number of points cannot be greater than 100,000!\n");
    exit;
}

// Remember the points are 1 indexed so begin key from 1. Store all provided points in array format.
for($i=1; $i<$no_points+1; $i++) {
    global $points;

    list($x, $y) = explode(" ",fgets(STDIN)); // Get the string returned from the command line and convert to an array
    $points[$i]["x"] = intval($x);
    $points[$i]["y"] = intval($y);
}

// Retrieve the number of operations that will be provied. Make sure to check constraints.
$no_operations = intval(fgets(STDIN));
if($no_operations > 100000) {
    fwrite(STDOUT, "The number of operations cannot be greater than 100,000!\n");
    exit;
}

// Retrieve the operations, determine the type and send to the appropriate functions. Make sure i <= j.
for($i=0; $i<$no_operations; $i++) {
    $operation = explode(" ",fgets(STDIN));
    $type = $operation[0];

    if($operation[1] > $operation[2]) {
        fwrite(STDOUT, "Point j must be further in the sequence than point i!\n");
        exit;
    }

    switch ($type) {
        case "C":
            $output[$i] = C($operation[1], $operation[2]);
            break;
        case "X":
            X($operation[1], $operation[2]);
            break;
        case "Y":
            Y($operation[1], $operation[2]);
            break;
        default:
            $output[$i] = "Sorry, but we do not recognize this operation. Please try again!";
    }
}

// Print the output as a string
foreach($output as $line) {
    fwrite(STDOUT, $line."\n");
}

UPDATE:
I finally found a test case for which my program fails. Now I am trying to determine why. This is a good lesson on testing with large numbers.
10
1 1
1 1
1 1
1 1
1 1
1 1
1 1
1 1
1 1
1 1
12
C 1 10
X 1 3
C 5 5
Y 2 10
C 10 10
C 1 10
X 1 3
C 5 5
Y 2 10
C 10 10
X 3 7
C 9 9
I am going to test this properly by initializing an error array and determining which operations are causing an issue.

A: I discovered a test case that failed and understood why. I am posting this answer here so it's clear to everyone.
I placed a constraint on the program so that j must be greater than i, otherwise an error should be returned. I noticed an error with the following test case:
10
1 1
1 1
1 1
1 1
1 1
1 1
1 1
1 1
1 1
1 1
1
C 2 10
The error returned for the operation C. Essentially the program believed that "2" was greater than "10". The reason for this I discovered was the following:
When using fgets(), a string is returned. If you perform string operations such as explode() or substr() on that line, you are converting the numbers in that initial string into a string again. So this means that the 10 becomes "10" and then after string operations becomes "0".
One solution to this is to use the sscanf() function and basically tell the program to expect a number. Example: for "C 2 10" you could use:
$operation_string = fgets(STDIN);
list($type, $begpoint, $endpoint) = sscanf($operation_string, "%s %d %d");
I submitted the new solution using sscanf() and now have 3/11 test cases passed. It did not check any more test cases because the CPU time limit was exceeded. So, now I have to go back and optimize my algorithm.
Back to work! :)

A: To answer, "What are those test cases?" Try this "solution":
<?php
$postdata = http_build_query(
    array(
        'log' => file_get_contents('php://stdin')
    )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context  = stream_context_create($opts);

file_get_contents('http://myserver/answer.php', false, $context);
?>

On your server:
<?php
$fp = fopen('/tmp/answers.log', 'a');
fputs($fp, $_POST['log']."\n");
fclose($fp);
?>

Edit:
I did that. And came up with this being your main problem (I think):
$operation = explode(" ",fgets(STDIN));

Change that to:
$operation = explode(" ",trim(fgets(STDIN)));

Because otherwise "9" > "41 " due to string comparison. You should make that fix in any place you read a line.

A: As far as I guess, this solution won't work. Even if you solve the Wrong Answer problem, the solution will time out.
I was able to figure out a way for returning the quadrants count in O(1) time.
But not able to make the reflections in lesser time. :(


text:
Q: Excel vba function with dynamic table column as parameter I'm trying to do an excel that counts the number of times that a certain letter appears in a table column.
What I'm trying to do is to create a dynamic table, in which i can always add new lines. Because of that, i need a function that has as a parameter one of the columns, which counts the number of times that another parameter appears.
Example, count the number of "shift" in the "column" (:
Function sumColumnShifts(column As Integer, shift As range) As Integer
    sumColumnShifts = sumDayShifts(ActiveSheet.ListObjects("foo").ListColumns(column).range.Select, shift)
End Function

Public Function sumDayShifts(ByVal Target As range, shift As range) As Variant
    Dim res As Integer
    res = 0
    For Each cell In Target
        If shift.cells(1, 1).Value = cell.Value Then
            res = res + 1
        End If
    Next
    sumDayShifts = res
End Function

The problem here is the function can't find the table, but the table exists.
What am I doing wrong?
Is it the ActiveSheet.ListObjects("foo").ListColumns(column).range.Select?
This is not a range? I can't access this in a function?
Thanks.

A: Can't you just use
=COUNTIF(foo[[#All],[Column1]],"A")

Otherwise,
I would pass the ListObject name and header of column to search along with the search value and use Countif in the function to return the count. You could also alter the function to pass the worksheet as an argument to the function to make it more flexible.
Option Explicit
Public Sub Test()

    Const SEARCH_HEADER As String = "Column1"
    Const SEARCH_VALUE As String = "A"
    Const TABLE_NAME As String = "foo"

    Debug.Print GetCount("foo", SEARCH_HEADER, SEARCH_VALUE)
End Sub

Public Function GetCount(ByVal tableName As String, ByVal searchHeader As String, ByVal searchValue As String) As Variant
    Dim ws As Worksheet, table As ListObject
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    On Error Resume Next
    Set table = ws.ListObjects("foo")
    On Error GoTo 0
    If table Is Nothing Or IsError(Application.Match(table.HeaderRowRange, searchHeader, 0)) Then
        GetCount = CVErr(xlErrNA)
        Exit Function
    End If

    GetCount = Application.WorksheetFunction.CountIf(table.ListColumns(searchHeader).DataBodyRange, searchValue)
End Function

Data:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Execute cycle only for CASE WHEN specific condition If write this
    DECLARE res INTEGER;
    DECLARE loop_res INTEGER;

    BEGIN
        SELECT 0 INTO loop_res;

        FOR i IN 1..5 LOOP
            SELECT loop_res + i INTO loop_res;
        END LOOP;

        SELECT
        case
            WHEN some_variable < 3
                THEN  --some result
            WHEN some_variable  >= 3
                THEN  loop_res
        END
        INTO res;

This works, but here anyway will execute LOOP statement right?
There is possible to execute LOOP statement only in case, if WHEN some_variable   >= 3 ?
I am trying :
        SELECT
        case
            WHEN some_variable  < 3
                THEN   --some result
            WHEN some_variable   >= 3
                THEN
                    FOR i IN 1..5 LOOP
                        SELECT loop_res + i INTO loop_res;
                    END LOOP;
                    loop_res
        END
        INTO res;

gives error syntax error at or near "FOR" at character ...

A: You're trying to mix PL/PgSQL and SQL. They're not really the same thing.
SELECT ... CASE WHEN ... ELSE ... END ..., like you've written is regular SQL. It can't embed PL/PgSQL statements.
PL/PgSQL CASE doesn't appear in a regular SELECT, just by its self as a control structure. It doesn't support INTO since it isn't a SELECT. It's of the form CASE WHEN ... ELSE ... END CASE;
See PL/PgSQL control structures.
You could write:
CASE
    WHEN some_variable < 3 THEN
        res := 0;
    WHEN some_variable >= 3 THEN
        FOR i IN 1..5 LOOP
            loop_res := loop_res + i;
        END LOOP;
        res := loop_res;
END CASE;

which is a PL/PgSQL CASE. The whole approach looks bizarre, but you're only showing dummy code so I can't really say what you're really trying to do. It's pretty unusual that you need to LOOP rather than just using some smarter SQL, but it does happen.
In this case it strikes me as likely that you'd turn out to be able to write a query using unions, with queries (CTEs), and/or generate_series to avoid the need for slow PL/PgSQL looping and control structures.


text:
Q: UIScrollView animation problems I'm using a horizontal UIScrollView that displays photos on the first half of the screen. (Imagine a CGRect (0,0,320,120). The first scrollView is embedded in a second scrollview, which takes all the screen. When I scroll down the page (thus the second scrollView), the first scrollview stop being animated. I programmed a NSTimer to change photo every 3 seconds in the first UIScrollView, but while I'm scrolling the second scrollView, it seems like the animations are being queued. When I release my finger of the screen, there are few photo transitions (i.e: 2 changes if I scrolled without stoping for 6 seconds). In short: how can I make use of blocks (or something else) to continue my animations while I'm scrolling the second scrollView?
My NSTimer (in viewDidLoad):
timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(changePage:) userInfo:nil repeats:YES];

A: Your iOS app has a run loop that continually checks for things like user input. If it is busy detecting touch events, things that are scheduled on that run loop will not get performed. (Similarly, if you block the main thread with e.g. a big server request, you won't get touch events during that time).
Here's how you can get the NSTimer on the right run loop:
First, use timerWithTimeInterval:target:selector:userInfo:repeats: to create a timer not scheduled on a run loop.
Second, use - (void)addTimer:(NSTimer *)aTimer forMode:(NSString *)mode to schedule the timer on a run loop. For the mode argument (the run loop type), use NSRunLoopCommonModes to allow the timer to fire without having to wait on the main run loop.
Note that this same effect exists for e.g. performSelectorAfterDelay if done in the main run loop. It also applies to animation completion blocks. I'm not sure if there's an easy way around the animation completion block problem besides using CoreAnimation.


text:
Q: Export wordpress image ID based off keyword search I would like to know how to go about exporting a load of image ID's based off the image name. For example
'how to dig gold' search may have a load of images like
how to dig gold.mp4001.jpg
how to dig gold.mp4002.jpg
how to dig gold.mp4003.jpg
how to dig gold.mp4004.jpg
how to dig gold.mp4005.jpg

Their wordpress image IDs are along the range of 8322-8326. I would like to run a single command to do this if possible as I will be doing this for hundreds of different keywords. The results should look like the following
how to dig gold-8322
how to dig gold-8323
how to dig gold-8324
how to dig gold-8325
how to dig gold-8326


text:
Q: XML schema attribute errors with type, appearance and syntax I need to validate my XML against the well defined schema. The problem is that I normally receive a lot of errors. Had an extensive look of your examples and everything seems to be alright. The problems are as follows:
Multiple annotations found at this line:
    - s4s-att-not-allowed: Attribute 'type' cannot appear in element 'attribute'.
    - s4s-elt-invalid-content.1: The content of '#AnonType_frominterNodeConnect' is invalid. Element 'attribute' is invalid, misplaced, or
     occurs too often.
    - src-resolve: Cannot resolve the name 'name' to a(n) 'attribute declaration' component.

Here is the example of XML:
<struct>
        <attribute name="sensorReading"/>
        <field name="photo" type="integer"/>
        <field name="solar" type="integer"/>
        <field name="temp" type="real"/>
        <field name="humid" type="real"/>
</struct>

Here is the schema that needs to validate it:
<xs:element name="struct">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="field" minOccurs="0" maxOccurs="unbounded">
                    <xs:complexType>
                        <xs:attribute ref="name" type="xs:string" minOccurs="1" maxOccurs="1"/>
                        <xs:attribute ref="type" type="xs:string" minOccurs="1" maxOccurs="1"/>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
            <xs:attribute ref="name" type="xs:string" minOccurs="1" maxOccurs="1"/>
        </xs:complexType>
</xs:element>

I do not understand why this errors appear. Read somewhere here that attribute needs to be moved at the end of the complex type but this obviously doesn't help much.
Regards to every one that knows where the errors are.

A: A possible XML Schema to validate that XML is this:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="struct">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="attribute">
                    <xs:complexType>
                        <xs:simpleContent>
                            <xs:extension base="xs:string">
                                <xs:attribute name="name" use="required" />
                            </xs:extension>
                        </xs:simpleContent>
                    </xs:complexType>
                </xs:element>
                <xs:element name="field" minOccurs="0" maxOccurs="unbounded">
                    <xs:complexType>
                        <xs:attribute name="name" type="xs:string" use="required" />
                        <xs:attribute name="type" type="xs:string" use="required" />
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

¿Why?

*

*Attributes can't have maxOccurs and minOccurs (they have attribte use=required|optional|prohibited).

*You have in your XML a element named attribute (that's not an attribute, its an element).

*Attribute ref its used to reference things defined in other parts of your XML Schema. If you want to specify the attribute name use the attribute name="x".

As I said in my comment it would be interesting if you read this simple tutorial


text:
Q: Is it a good idea to call finish() after starting a new Activity in Android? Like:
startActivity(intent);
finish();

Without calling finish() explicitly, onDestroy() is not called for the former Activity, and I run out of memory (OutOfMemory Exception).
So, is it a good idea to call finish() explicitly to prevent OutOfMemory Exception?

A: When you start a new activity, the current activity is pushed onto the back stack of the current task. (You can change this behavior via flags and/or the manifest, but this is the default behavior.) When the user presses the back function, the top activity is finished and the stack is popped. The result is that the user sees the app return to the previous activity.
It's perfectly fine to call finish() after starting a new activity. The result will be that the current activity (which is no longer at the top of the stack, since you just started a new one) will be removed from the stack. Then when the user presses Back, it will go to the previous activity on the back stack (or exit your app if the stack is empty).
If you are bouncing back and forth between, say, activities A and B by always starting a new one and never calling finish(), this can cause an OOM exception as the stack fills up with instances of each activity.
You can read more about this in the guide topic Tasks and Back Stack. It also describes how to deal correctly with cycling between activities.

A: Doing this is fine if you don't need an instance of that Activity. So when you press back on the next Activity know that you won't come back to this one but whatever is on the stack below where that Activity was or the home screen if there are no more.
However, I'm not sure this is why you are getting an OOM exception and you should probably figure out where that is coming from instead. If you are using Bitmaps then that could be causing the exception.

A: Alternatively in the manifest you could add android:noHistory="true" to the activity and when you navigate away from the activity it will not add it to the back stack.


text:
Q: Why I can not find the FileInfo? I already add this two :
using System;
using System.IO;

In my code but still can not find the FileInfo Class. When I build my project. Error given below :

'FileInfo' could not be found (are you missing a using directive or an
  assembly reference?)

I tried to use the class with full name System.IO.FileInfo , also Error:

'System.IO.FileInfo' could be not be found (are you missing a using
  directive or an assembly reference?)

It also do not have the File Class in the System.IO namespace
System.IO contains something like Path, BinaryReader/Writer, StreamReader/Writer
I use .Net 4.5 in VS 2012 to develop some Win8 app.
Thanks in advance.

A: As Hans Passant correctly said, System.IO.FileInfo is not available for Windows Store applications. You can see which types are available for the store by looking for the store icon  in the MSDN library listings.

A: As Hans Passant said on comments FileInfo class is not available in a Windows Store Apps.
Apps created with C#/XAML do use the .NET Framework, but only a subset named .NET API for Windows Store Apps. You can access the System.IO on the Windows Store Apps, but you do not have all classes you had on .Net Framework.
Take a look:
http://msdn.microsoft.com/en-us/library/windows/apps/hh454050.aspx
So, you can use the StorageFile class. Take a look at this sample:
http://metroapps.wikispaces.com/File+IO


text:
Q: Flutter: Snackbar does not show up after using barcode_scan plugin In my Flutter app I want to scan some barcodes. After scanning the barcode I want to show a snackbar. The app should run on an Android device.
Unfortunately the snackbar never shows up.
Both functionalities (barcode scanning and showing the snackbar) work fine separately.
During debugging, following happens:

*

*The camera opens

*The barcode is scanned

*The barcode is stored in the variable

*The screen turns black

*The code for the snack bar is executed. The snack bar is not displayed.

*After leaving the method the view/widget on which the snack bar is to be shownn is rendered again.

The barcode scanning is handled by the flutter plugin barcode_scan in version 0.0.3.
Here is the matching code:
final GlobalKey<ScaffoldState> keyScaffold = new GlobalKey<ScaffoldState>();

[...]

@override
Widget build(BuildContext context) {
  return new Scaffold(
    key: keyScaffold,
    [...]
}

Future scan() async {
  String snackBarMessage = "No error";

  try {
    String barcode = await BarcodeScanner.scan();
    setState(() => _barcodeController.text = barcode);
    snackBarMessage = barcode;
  } on PlatformException catch (e) {
    if (e.code == BarcodeScanner.CameraAccessDenied) {
      snackBarMessage = 'The user did not grant the camera permission!';
    } else {
      snackBarMessage = 'Unknown error: $e';
    }
  } on FormatException {
    snackBarMessage =
        'null (User returned using the "back"-button before scanning anything. Result)';
  } catch (e) {
    snackBarMessage = 'Unknown error: $e';
  }

  keyScaffold.currentState.showSnackBar(new SnackBar(
    content: new Text(snackBarMessage),
    duration: new Duration(seconds: 5),
  ));
}

A: On my prototype flutter app (flutter ver. 0.5.1 beta), I use both the snackbar and the barcode_scan plugin (ver. 0.0.4) and the snackbar DOES show up (with the result of the scan as a string). All credits go to Wahib Ul Haq for easier snackbar editing:
Display SnackBar in Flutter
In my case, there are 2 things worth noticing.

*

*I don't use keyScaffold at all. I declare a BuildContext as a variable (I call it scaffoldContext) to hold the body of the Scaffold.

*I declare and initialise a new Scaffold. For its body, I write a Builder. Inside the builder, I initialize scaffoldContext as context for the Builder.
Here's my code for easier understanding:
import 'package:flutter/material.dart';
import 'package:barcode_scan/barcode_scan.dart';
import 'package:flutter/services.dart';
[...]

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      [...],
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  //This is what I meant in note #1.
  BuildContext scaffoldContext;

  String barcode;

  @override
  initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('MyApp'),
      ),
      //This is what I meant in note #2.
      body: Builder(builder: (BuildContext context) {
        scaffoldContext = context;
        return Center(
            child: Column(children: <Widget>[
              ListTile(
              [...]
              ),
              ListTile(
              [...]
              ),
              [...]
            ]

    ));}),

      floatingActionButton: FloatingActionButton(
        mini: true,
        child: Icon(Icons.crop_free), onPressed: fabPressed),
    )};

  void createSnackBar(String message) {
    final snackBar = new SnackBar(content: new Text(message),
        backgroundColor: Colors.black

    );

    Scaffold.of(scaffoldContext).showSnackBar(snackBar);
  }

  void fabPressed() async {
    barcode = "";

    try {
    barcode = await BarcodeScanner.scan();
    setState(() => this.barcode = barcode);

    createSnackBar(barcode);
    }
    on PlatformException catch (e) {
      if (e.code == BarcodeScanner.CameraAccessDenied) {
        setState(() {
          this.barcode = 'The user did not grant the camera permission!';
        });
        } else {
          setState(() => this.barcode = 'Unknown error: $e');
      }
    }
    on FormatException {
      setState(() =>
  this.barcode = 'null (User returned using the "back"-button before scanning anything. Result)');
    }
    catch (e) {
      setState(() => this.barcode = 'Unknown error: $e');
    }
  }
}


text:
Q: How to Redirect permantly to another page after form submission Hello I wanted to know how I can make a protect a page and redirect to other pages after a form submission like.
http://ranksurveys.com/users/signup
they are doing here after u submitted the form u can not access that page again.. and you will auto redirected to http://ranksurveys.com/surveys
I am really curious hope someone can help me!

A: When user submits the form you just put information that form were submitted into the cookies session. Before rendering the form you just check the values in cookie\session and if you found that the form were already submitted just send Location and redirect status code via PHP. You should avoid implementing this in JS because anyone can easily disable Javascript in the browser.
Here is some ugly but fast code exmaples just to explain the concept
 1. Retrieving the form
    /* These are our valid username and passwords */
$user = 'jonny4';
$pass = 'delafoo';

if (isset($_POST['username']) && isset($_POST['password')) {

    if (($_POST['username'] == $user) && ($_POST['password'] == $pass)) {

        if (isset($_POST['rememberme'])) {
            /* Set cookie to last 1 year */
            setcookie('username', $_POST['username'], time()+60*60*24*365, '/account', 'www.example.com');
            setcookie('password', md5($_POST['password']), time()+60*60*24*365, '/account', 'www.example.com');

        } else {
            /* Cookie expires when browser closes */
            setcookie('username', $_POST['username'], false, '/account', 'www.example.com');
            setcookie('password', md5($_POST['password']), false, '/account', 'www.example.com');
        }
        header('Location: index.php');

    } else {
        echo 'Username/Password Invalid';
    }

} else {
    echo 'You must supply a username and password.';
}

*Access cookie and redirect to login if not logged in. I hope you'll understand how to implement an opposite case ;)
/* These are our valid username and passwords */
$user = 'jonny4';
$pass = 'delafoo';
if (isset($_COOKIE[['username']) && isset($_COOKIE['password')) {
if (($_POST['username'] != $user) || ($_POST['password'] != md5($pass))) {
    header('Location: login.html');
} else {
    echo 'Welcome back ' . $_COOKIE['username'];
}

} else {
    header('Location: login.html');
}

A: You can use cookies. Whether it can be use as server side or client side. This can be easily approach with Jquery cookies.
step 1 : add script files
<head>
 <script src="path/to/jquery.js"></script>
 <script src="path/to/jquery.cookie.js"></script>
</head>

step 2: in the protected form page add this script
var isProtected = $.cookie('page-protected');
if(isProtected == 'YES'){
  // We dont need to stay them on current page if they have already submitted the form
  window.location = "http://yoursite.com/your-thanking-page";
}

$.cookie('page-protected', 'NO');

step 3: in the thanking page you should set the cookie YES if the relevant form submitted successfully.
if(formSubmitComplete){
  $.cookie('page-protected', 'YES');
}


text:
Q: Windows Phone 7 EMULATOR Crash Dump or Debugging I want to debug a default application like Internet Explorer on WP7 Emulator. Is there a way to attach it to debugger ? Or how can I access the crash dumps when a crash occurs on WP7 Emulator??

A: You cannot debug system applications with the default toolset available from Microsoft. You can, however, keep track of events that occur in the emulator by enabling the verbose mode (aka to show the console).
To do this, open regedit and go to HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\XDE (for 64bit systems) or HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\XDE (for 32bit systems) and create a new DWORD key, named EnableConsole. Set its value to 0x00000001 (1).
Now, every time the emulator starts, there will be a console window that will show you the system events that are going on.


text:
Q: How to rewrite if file not found under defined folder need to redirect only when file not found under given folder .
my code is
<IfModule mod_rewrite.c>
    RewriteEngine on

    RewriteRule ^(theme|files|images|krishna)(.*)$ Swastik/public/$1$2 [L]

    RewriteRule ^(.*)$ Swastik/library/index.php [L]

</IfModule>

i have to rewrite all request to under Swastik/library/ if file not found in Swastik/public

A: You can use that:
RewriteCond %{DOCUMENT_ROOT}/Swastik/public%{REQUEST_URI} -f
RewriteRule (.*) Swastik/public/$1 [L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* Swastik/library/index.php [L]


text:
Q: Sort Array of Objects Based on Numeric Value I have an array like so:
[
   { Orange: 5 },
   { Red: 575 },
   { Green: 6544 },
   { Blue: 1307 }
]

The desired outcome is:
[
   { Green: 6544 },
   { Blue: 1307 },
   { Red: 575 },
   { Orange: 5 }
]

I've been trying to use the sort operator after looking through Stack Overflow: myArray.sort((a, b) => a.distance - b.distance). However, the issue I'm running into is the key is not standardized. All the examples I'm finding have the same key but i'm trying to sort on a numeric value with non standard keys.
When mapping through the above array, I'm able to access the key like so:
let ungroupedArr = [
   { Orange: 5 },
   { Red: 575 },
   { Green: 6544 },
   { Blue: 1307 }
]

ungroupedArr.map(element => {
   //this is the key
   Object.keys(element)[0]
})

I'm trying to get a more verbose sort solution using the above map style logic (where I have access to each element in the array. However, I've hit a wall and I'm not sure where to go next.
Any idea how I would go about working this out?

A: Using Array#sort and Object#values:

const arr = [ { Orange: 5 }, { Red: 575 }, { Green: 6544 }, { Blue: 1307 } ];

const sorted = arr.sort((a, b) => Object.values(b)[0] - Object.values(a)[0]);

console.log(sorted);


text:
Q: Wireshark merging pcap files I'm trying to merge 15 pcap files using wireshark. The merging is successful.
I'm using the appending function so that the second file is just added to the bottom of the first file. But when this is done, I get a negative value in Time column. How can I change this?

A: This can be done using joincap.
go get -u github.com/assafmo/joincap

To merge 1.pcap and 2.pcap:
joincap 1.pcap 2.pcap > merged.pcap

I wrote joincap to overcome what I believe is bad error handling by mergecap and tcpslice.
For more details go to https://github.com/assafmo/joincap.

A: I'm assuming the time difference between frame 4873 and 4874 is because these packets were from different files.
I would suggest using mergecap to merge the two PCAP files together instead of just concatenating (appending) them like you did. Mergecap merges the packets according to timestamp by default (using the "-a" switch in mergecap would result in a concatenated file like yours).
Another option is to load the two capture files into CapLoader, select all flows, and export them to a new PCAP file (by using drag-and-drop from the PCAP icon).
Finally, if you really want to concatenate/append and NOT have the packets in chronological order, then you just have to right click the packet with the smallest timestamp (for example frame 4874) and select "Set Time Reference". That way all timestamps will be shown as relative to that packet in Wireshark.


text:
Q: Power BI Lower Forecast Minus Putting a Forecast in Power BI and the lower bound drops below zero into minus.
Is there a way to stop the lower bound dropping below zero and even become a bit more of a realistic amount


text:
Q: css text formatting with various styles and sizes I am having trouble determining the best approach to laying out a section of text/textboxes in the following format (image below) without using a table. This content would be located inside a div set to float:right; and would probably have various font sizes and colors.
Any suggestions would be greatly appreciated.

A: I ended up just using a table instead of trying to get fancy with divs and floats.


text:
Q: Is it suggestable to use generics for large amount of data? I'm having let's say thousands of Customer records and I have to show them on a webform. Also, I have one CustomerEntity which has 10 properties. So when I fetch data in using a DataReader and convert it into List<CustomerEntity> I am required to loop through the data two times.
So is the use of generics suggestable in such a scenario? If yes then what will be my applications performance?
For E.g.
In CustomerEntity class, i'm having CustomerId & CustomerName propeties. And i'm getting 100 records from Customer Table
Then for Preparing List i've wrote following code
while (dr.Read())
    {
       // creation of new object of customerEntity
       // code for getting properties of CustomerEntity
       for (var index = 0; index <  MyProperties.Count; index++)
       {
         MyProperty.setValue(CustEntityObject,dr.GetValue(index));
        }
      //adding CustEntity object to List<CustomerEntity>
    }

How can i avoid these two loops. Is their any other mechanism?

A: I'm not really sure how generics ties into data-volume; they are unrelated concepts... it also isn't clear to me why this requires you to read everything twice. But yes: generics are fine when used in volume (why wouldn't they be?). But of course, the best way to find a problem is profiling (either server performance or bandwidth - perhaps more the latter in this case).
Of course the better approach is: don't show thousands of records on a web form; what is the user going to do with that? Use paging, searching, filtering, ajax, etc - every trick imaginable - but don't send thousands of records to the client.

Re the updated question; the loop for setting properties isn't necessarily bad. This is an entirely appropriate inner loop. Before doing anything, profile to see if this is actually a problem. I suspect that sheer bandwidth (between server and client, or server and database) is the biggest issue. If you can prove that this loop is a problem there are things you can do do optimise:

*

*switch to using PropertyDescriptor (rather than PropertyInfo), and use HyperDescriptor to make it a lot faster

*write code with DynamicMethod to do the job - requires some understanding of IL, but very fast

*write a .NET 3.5 / LINQ Expression to do the same and use .Compile() - like the second point, but (IMO) a bit easier

I can add examples for the first and third bullets; I don't really want to write an example for the second, simply because I wouldn't write that code myself that way any more (I'd use the 3rd option where available, else the 1st).

A: It is very difficult what to say the performance will be, but consider these things -

*

*Generics provides type saftey

*If you're going to display 10,000 records in the page, your application will probably be unusable. If records are being paged, consider returning only those records that are actually needed for the page you are on.

*You shouldn't need to loop through the data twice. What are you doing with the data?


text:
Q: Custom view custom attribute not being set without @{} So I've got a custom view with this attribute:
    private var mLabelText: String = "DEFAULT"
    var labelText: String
        set(value) {
            if (mLabelText != value) {
                mLabelText = value
                invalidate()
            }
        }
        get() { return mLabelText }

And defined in attr.xml as
    <declare-styleable name="CustomView">
        <attr name="labelText" format="string"/>
    </declare-styleable>

Now if I try to do this in my layout XML to set the value, it doesnt work (the text still shows 'DEFAULT')
        <CustomView
            ...
            app:text="NewText" />

However, if I do this, it works:
        <CustomView
            ...
            app:text="@{`NewText`}" />

So what gives?
How come views like TextView allow me to do android:text="Text" instead of having to write android:text="@{`Text`}, but my own custom view wont?

A: Mike's comments answer the confusion I had about the different syntaxes.
What I ended up doing ultimately is to inherit the existing android TextView. TextView has a bunch of stuff I needed like font, font size etc, so it was just simpler to inherit rather than re-implement it myself.


text:
Q: String Arrays not working. Compiler not interacting I was learning how to sort arrays with different types of value holders. I tried to sort an array with Strings, but it comes up with the error message, Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
    at SortingArrays.main(SortingArrays.java:50)
There aren't any errors the compiler found, but it comes up with this. The array with numbers worked fine, but the strings didn't. Here is my code.
import java.util.Arrays;
public class SortingArrays {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int[] aryNums;

        aryNums = new int[6];

        aryNums[0] = 7;
        aryNums[1] = 89;
        aryNums[2] = 45;
        aryNums[3] = 234;
        aryNums[4] = 2;
        aryNums[5] = 75;

        Arrays.sort(aryNums);

        int i;

        for (i = 0; i < aryNums.length; i++) {

            System.out.println(aryNums[i]);
        }

        String[] aryStrings;

        aryStrings = new String[5];

        aryStrings[0] = "I have no idea what I'm doing.";
        aryStrings[1] = "Should I know what I'm doing?";
        aryStrings[2] = "I guess not.";
        aryStrings[3] = "There's my boss.";
        aryStrings[4] = "Whoop, he's looking. Hide!";

        Arrays.sort(aryStrings);

        int x;

        for (x = 0; x < aryStrings.length; x++) {

            System.out.println(aryStrings[i]);
        }

    }

}

A: You are getting runtime exception. ArrayIndexOutOfBoundsException means you are trying to access array beyond its capacity with what its defined.
Problem is with this code:
for (x = 0; x < aryStrings.length; x++){
    System.out.println(aryStrings[i]);
                                  ^^
}

You are using i as index instead of x. Here i (after your print statements) would be 6 in your case and your array can hold 5 elements which start with 0 and ends with 5.

A: At the very end of your program:
 System.out.println(aryStrings[i]);

i = 6, of course it out of bounds
What you need is:
System.out.println(aryStrings[x]);

A: i after your first loop is 6.
so here
for (x = 0; x < aryStrings.length; x++){
        System.out.println(aryStrings[i]); // i here is 6 but there are 5 elements in aryStrings
    }

use x in this loop not i

A: As other commenters have said, the problem is with your iterating variable.
But to completely avoid this problem, use a for-each loop.
As Joshua Bloch says in Effective Java, 2nd Edition (Item 46):
// The preferred idiom for iterating over collections and arrays
for (int aryNum : aryNums) {
   System.out.println(aryNum);
}

Or better in Java 8:
Arrays.stream(aryNums).forEach(System.out::println);

A: You're using i instead of x in the second print statement

A: Change the index in x
   System.out.println(aryStrings[x]);

A: As the other answers have stated, by the time you reach your second loop, i is equal to a higher integer than your String array has indices.
Another way to fix your issue is to reset the value of i:
int x;
i = 0;//re-initialize

for (x = 0; x < aryStrings.length; x++) {
    System.out.println(aryStrings[i]);
}

However, this defeats the purpose of your x variable.
As a rule of thumb, I'd keep your incrementer local to your loop to prevent problems like this arising:
//declare x in the loop
for (int x = 0; x < aryStrings.length; x++) {
    System.out.println(aryStrings[x]);
}


text:
Q: How to achieve multiple row criteria in single table mysql> select * from productdetails;
+----------+---------+--------+
| customer | product | is_use |
+----------+---------+--------+
|        1 |       1 |      0 |
|        1 |       2 |      0 |
|        1 |       3 |      1 |
|        2 |       1 |      1 |
|        2 |       2 |      0 |
|        2 |       3 |      1 |
|        3 |       1 |      1 |
|        3 |       2 |      1 |
|        3 |       3 |      1 |
|        4 |       1 |      0 |
|        4 |       2 |      1 |
|        4 |       3 |      1 |
+----------+---------+--------+
12 rows in set (0.00 sec)

How to get the customers for using both product 1 and 2 from the above table

A: In order to know which customers use both products, you'd aggreagte per customer:
select customer
from productdetails
group by customer
having sum(product = 1 and is_use = 1) > 0
   and sum(product = 2 and is_use = 1) > 0
;

A: Solutions using IN(1,2) will find customers who use either product 1 or product 2 (or both).
If you want to find customers who use both product 1 and product 2, you need to test for both simultaneously.
But a WHERE clause naturally applies conditions in the context of only one row at a time.
So you need to get two rows onto one row somehow.
The best way to do this is with a self-join:
SELECT p1.customer
FROM product_detail AS p1
JOIN product_detail AS p2 ON p1.customer = p2.customer
WHERE p1.product = 1 AND p1.is_use = 1
  AND p2.product = 2 AND p2.is_use = 1

A: You can use IN clause:
SELECT customer
FROM   product_detail
WHERE  product IN (1, 2)
AND    is_use = 1;


text:
Q: Generalization of the well known fact about processes with stationary and independent increments It can be easily shown that for the process $X=(X_t)_{t\geq 0}$ which has independent and stationary increments the following holds:
$$
EX_n = nEX_1,
$$
where $n$ is an integer number.
Is this equation true if we replace an integer $n$ by a real number $t$, i.e.
$$
EX_t = t EX_1,
$$
If is it true, how we can prove it?

A: If $(X_t)$ has stationary independent increments the the function $f(t)=EX_t$ satisfies the Cauchy equation $f(t+s)=f(t)+f(s)$. If you assume that the process $(X_t)$ is a measurable process you can show that $f$ is measurable and this implies $f(t)=ct$ for all $t$ where $c$ is a constant. Hence $EX_t=ct$ so $EX_t=tEX_1$.
The equation $f(t+s)=f(t)+f(s)$ comes from $X_{t+s}= (X_{t+s}-X_s) +X_s$


text:
Q: How to select the characters part of string in Visual basic I have some string variables with combinations of numbers and characters. like this:
A12452
BCD23
ESK56003
Using vbscript I want to get the characters and not the numbersfrom these strings. So I should get the following results.
A
BCD
ESK
note: im on VB6 right now.

A: VBA:
Dim i As Long
Dim k As Long

k = Len (MyString)
i = 1
Do Until (i > k) Or (IsNumeric (Mid$ (MyString, i, 1)))
    i = i + 1
Loop

Result = Left$ (MyString, i - 1)

Edit: I just noticed that there might be a bug in this code as Or is not short-circuit in VBA (i.e. the expression following Or is evaluated even if the first expression is true). Probably the correct way of writing the loop would be
Do
    If i > k Then Exit Do
    If IsNumeric (Mid$ (MyString, i, 1)) Then Exit Do
    i = i + 1
Loop


text:
Q: How to create cube with only HTML and CSS?
I have this and I want to make a cube with HTML & CSS only like in the above image. My best try:

.mainDiv{
  position: relative;
  width: 206px;
  height: 190px;
  margin: 0px auto;
  margin-top:100px;
}
.square{
  width:100px;
  height:100px;
  background:#c52329;
  border:solid 2px #FFF;
  float:left;
  transform: skew(180deg,210deg);
  position: absolute;
  top: 43px;
}
.square2{
  width:100px;
  height:100px;
  background:#c52329;
  border:solid 2px #FFF;
  float:left;
  transform: skew(180deg,150deg);
  position: absolute;
  left:102px;
  top: 43px;
}
.square3{
  width:100px;
  height:100px;
  background:#c52329;
  border:solid 2px #FFF;
  float:left;
  transform: skew(180deg,180deg);
  position: absolute;
  left: 51px;
  top: -61px;
}

A: First let me point out that a skew angle should be between -90deg and 90deg, non-inclusive. All of your skews fall way outside this range.
Limiting myself to sensible skew numbers, it turned out to be quite simple:

.mainDiv{
  position: relative;
  width: 206px;
  height: 190px;
  margin: 0px auto;
  margin-top:100px;
}
.tile {
  width:100px;
  height:100px;
  background:#c52329;
  border:solid 2px #FFF;
  position: absolute;
}
.square{
  transform: skewY(30deg);
  top: 43px;
}
.square2{
  transform: skewY(-30deg);
  left:102px;
  top: 43px;
}
.square3{
  height: 58px;
  left: 50px;
  top: -18px;
  transform: skew(60deg, -30deg);
}

Job done. I've also tidied up the huge repetition of styles into a common class for you.

A: Changing the CSS for .square3 should do it:
height: 58px;
left: 50px;
position: absolute;
top: -18px;
transform: skew(240deg, 150deg);
width: 100px;

https://jsfiddle.net/8vuj7peb/26/

A: Use the following css for .square3:
.square3{
  width:110px;
  height:110px;
  background:#c52329;
  float:left;
  transform: rotate(45deg) skew(-15deg, -15deg);
  position: absolute;
  left: 46px;
  top: -42px;
}

A: A single box and 2 pseudos can do this as well.
http://codepen.io/gc-nomade/pen/vGeajp

#square {

  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 5px;
  background: #C52329;
  /*box-shadow: 0 0 5px;*/
  width: 90px;
  height: 150px;
  margin: 5em;
  position: relative;
  transform: skew(30deg) rotate(30deg);
}

#square:before,
#square:after {
  display: inherit;
  align-items: center;
  justify-content: center;
  content: 'before';
  position: absolute;
  top: 0;
  left: 2px;
  right: -2px;
  bottom: 0;
  background: inherit;
  border-radius: inherit;
  box-shadow: inherit;
  transform: translate(100%, -31%) skew(0, -45deg) rotate(0deg);
}
#square:after {
  content: 'after';
  top: -2px;
  left: 0%;
  height: 60%;
  right: 0;
  bottom: 2px;
  transform: translate(50%, -100%) rotate(0deg)skew(-45deg)
}

  boxe

A: According to your HTML, I get this JSFiddle. I just played with transform.

.mainDiv{
  position: relative;
  width: 206px;
  height: 190px;
  margin: 0px auto;
  margin-top:100px;
}
.square{
  width:100px;
  height:100px;
  background:#c52329;
  border:solid 2px #FFF;
  transform: skew(180deg,210deg);
  position: absolute;
  top: 43px;
}
.square2{
  width:100px;
  height:100px;
  background:#c52329;
  border:solid 2px #FFF;
  transform: skew(180deg,150deg);
  position: absolute;
  left:102px;
  top: 43px;
}
.square3{
  width:114px;
  height:100px;
  background:#c52329;
  border:solid 2px #FFF;

transform: rotate(150deg) translate(-40px, -16px) skew(30deg, 0deg);
  position: absolute;
  left: 0px;
  top: -32px;
}

Updated CSS
.square3{
  width:114px;
  height:100px;
  background:#c52329;
  border:solid 2px #FFF;
  transform: rotate(150deg) translate(-40px, -16px) skew(30deg, 0deg);
  position: absolute;
  left: 0px;
  top: -32px;
}

I changed transform CSS with this.

Extra: David Walsh has a cool animated version on an cube. Apart from the fact that it looks kinda cool, by fiddling with the settings you can learn quite a lot about it.

A: You can also achieve a cube with 3d transforms. This will give your cube a more realistic perspective. As if the cube was a real 3d shape like this:

In the following I used one div with 2 pseudo elements :

body {
  perspective: 900px;
  padding-bottom:50%;
}
div {
  position: relative;
  width: 20%;
  padding-bottom: 20%;
  margin: 0 auto;
  transform-style: preserve-3d;
  background: #C52329;
  transform: rotateX(60deg) rotatez(45deg);
}
div:before, div:after {
  content: '';
  position: absolute;
  width: 100%;
  height: 100%;
  transform-origin: -2% -2%;
  background: inherit;
}
div:before {
  top: 104%; left: 0;
  transform: rotateX(-90deg);
}
div:after {
  top: 0; left: 104%;
  transform: rotateY(90deg);
}

CSS 3d cube with 6 faces:
This technique allows you to make a "real cube" with 6 faces:

body{
  perspective-origin:50% -100%;
  perspective: 900px;
  overflow:hidden;
}
h1{position:absolute;font-family:sans-serif;}
.cube {
  position:relative;
  padding-bottom:20%;
  transform-style: preserve-3d;
  transform-origin: 50% 100%;
  transform:rotateY(45deg) rotateX(0);
  transition:transform 3s;
}
.cubeFace {
  position: absolute;
  left:40%;top:0;
  width: 20%;height:100%;
  margin: 0 auto;
  transform-style: inherit;
  background: #C52329;
  box-shadow:inset 0 0 0 5px #fff;
  transform-origin:50% 50%;
  transform: rotateX(90deg);
  backface-visibility:hidden;
}
.face2{
  transform-origin:50% 50%;
  transform: rotatez(90deg) translateX(100%) rotateY(90deg);
}
.cubeFace:before, .cubeFace:after {
  content: '';
  position: absolute;
  width: 100%;
  height: 100%;
  transform-origin:0 0;
  background: inherit;
  box-shadow:inherit;
  backface-visibility:inherit;
}
.cubeFace:before {
  top: 100%; left: 0;
  transform: rotateX(-90deg);
}
.cubeFace:after {
  top: 0; left: 100%;
  transform: rotateY(90deg);
}

body:hover .cube{
  transform:rotateY(405deg) rotateX(360deg);
}

Hover me:

Note that I didn't add the vendor prefixes in the examples. For more info about browser support and what vendor prefixes are needed according to your target audience, see canIuse for 3d transforms.

A: I seen this and thought I would add something I came up with while trying to make some old fashioned abc blocks. Making them into 3d I only had to label the main container with another class to change positions and saved on the code.  I commented the tutorial in the code. Hope this helps someone. :)

/*-------------------------------------------------------------
First we need to create our container for later reference
    -I put this to show in the center of the screen if you wanted to
    copy and paste the code into a document for play.
    -The width is just to give the margin auto something to center on.
    -You really on need the element itself to reference later, but this is prettier
-------------------------------------------------------------*/
.box{
    width: 100px;
    margin: 200px auto;
    text-align: center;
    line-height: 5;
}

/*---------------------------------------------------------------------------
The box-wrapper is our real hero container here. This is where we nail our box together.
    -set this to relative position for child elements to reference to.
    -transform-style is set to preserve-3d because I wanted to keep the look as the text turns with the box. You can also set this to flat, but its not near as cool.
---------------------------------------------------------------------------*/

.box-wrapper{
    position: relative;
    transform-style: preserve-3d;
    -webkit-transform-style: preserve-3d;
}
/*-------------------------------------------------------------------------
Here I am just giving the box its needed dimesions and setting them to absolute so nothing gets any ideas of wandering off.
    -PLEASE NOTE: the border has 2px and our w:98 h:98 making it a total of 100px. (this is important when we translate later)
-------------------------------------------------------------------------*/
.box-wrapper div{
    width: 98px;
    height: 98px;
    position: absolute;
    border: 2px solid black;
    border-radius: 5px;
}

/*----------------------------------------------------------------------
Since our sides are 100px we only need to move our box sides 50px to get the edges to match up without gaps.
    -Meaning "translate" moves to the position relative to your .box-wrapper. (You can play with this code to see it in action, try to take a visible section of the box and take it down 10).
    -Also I use "rotate" y and x to turn our box sheets (.box-wrapper div's)
-----------------------------------------------------------------------*/
.front{
    transform: translateZ(50px) rotateY(0deg);
}
.back{
    transform: translateZ(-50px) rotateY(180deg);
}
.top{
    transform: translateY(-50px) rotateX(90deg);
}
.bottom{
    transform: translateY(50px) rotateX(-90deg);
}

.right{
    transform: translateX(50px) rotateY(90deg);
}
.left{
    transform: translateX(-50px) rotateY(270deg);
}

/*-----------------------------------------------------------------------
Then after all of this we can use our cool box-wrapper to turn this baby
Hope this is helpful! :) Enjoy!
-------------------------------------------------------------------------*/

.box .box-wrapper{
    transform: rotateX(-30deg) rotateY(-40deg);
}
.box .box-wrapper div{
    background-color: yellow;
}
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Bob the box builder</title>
        <link rel="stylesheet" type="text/css" href="boxstyle.css">

Front

Back

Left

Right

Top

Bottom

A: Basically, you want to do 2 transformations:

*

*rotate the rectangle

*squeeze it (skew it)

so basically, you need to do a transform: rotate(x) skew(y, y) and play a bit with size and placing.
here's a little demo I created, based on your own demo:
(I did remove the borders since they felt unneeded to me)

.mainDiv{
  position: relative;
  width: 206px;
  height: 190px;
  margin: 0px auto;
  margin-top:100px;
}
.square{
  width:100px;
  height:100px;
  background:#c52329;
  float:left;
  transform: skew(180deg,210deg);
  position: absolute;
  top: 43px;
}
.square2{
  width:100px;
  height:100px;
  background:#c52329;
  float:left;
  transform: skew(180deg,150deg);
  position: absolute;
  left:102px;
  top: 43px;
}
.square3{
  width:110px;
  height:110px;
  background:#c52329;
  float:left;
  transform: rotate(45deg) skew(-15deg, -15deg);
  position: absolute;
  left: 46px;
  top: -42px;
}

A:       y
      |
      |____ x
     ╱
    z

Imagine a cube from the front side. What you can see? A square that comes out over the screen. So, for the front side, we have:
.front {
  transform : translateZ(50px);
}

for the right side, we have a square that is rotated 90 degrees on Y-Axis and moved on own new Z-Axis:
.right {
  transform : rotateY(90deg) translateZ(50px);
}

for the left side, we have a square that is rotated -90 degrees on Y-Axis and moved on own new Z-Axis:
.right {
  transform : rotateY(-90deg) translateZ(50px);
}

for the top side, we have a square that is rotated 90 degrees on X-Axis and moved on own new Z-Axis:
.right {
  transform : rotateX(90deg) translateZ(50px);
}

for the back side, we have a square that is rotated -180 degrees on Y-Axis and moved on own new Z-Axis:
.right {
  transform : rotateY(-180deg) translateZ(50px);
}

Then, Just package them in a shape container class with transform-style: preserve-3d property:
.cube {
  transform-style: preserve-3d;
}

finally, you can rotate your cube and see the CSS-3D magic.
.cube {
  transform-style: preserve-3d;
  transform: rotateX(-40deg) rotateY(45deg);
}

.cube {
  transform-style: preserve-3d;
  transform: rotateX(-40deg) rotateY(45deg);
}

.side {
  position: absolute;
  width: 100px;
  height: 100px;
  background: #c52329;
  border: solid 3px white;
}

.front {
  transform: translateZ(53px);
}

.top {
  transform: rotateX(90deg) translateZ(53px);
}

.right {
  transform: rotateY(90deg) translateZ(53px);
}

.left {
  transform: rotateY(-90deg) translateZ(53px);
}

.bottom {
  transform: rotateX(-90deg) translateZ(53px);
}

.back {
  transform: rotateY(-180deg) translateZ(53px);
}

It is a full cube. For your approach, you can ignore the back, right, and bottom sides.

Thanks to css-tricks.com


text:
Q: Nodejs creating v8 Context in a separate thread I am using v8 version 3.14.5.9. and that of nodejs is 0.10.17.
In my c++ addon, i start a separate thread and on that i try to create an object whose constructor is :
 class ConstructorRunningOnSeparateThread {
      v8::Persistent<v8::Context> context;
  public:
      ConstructorRunningOnSeparateThread() {
               v8::Locker locker;
        v8::HandleScope handle_scope;//(isolate_);
        v8::Local<v8::ObjectTemplate> globalTemplate = v8::ObjectTemplate::New();
        globalTemplate->Set(v8::String::New("myversion"), v8::FunctionTemplate::New(NodeVersion));
        context_ = v8::Context::New(nullptr, globalTemplate);
        //         ^^^^^-------------------- EXCEPTION HERE

        if (context.IsEmpty()) {
            fprintf(stderr, "Error creating context\n");
        }
      }
}

I am getting an exception at v8::Context::New().
Please help.
Thanks in advace.


text:
Q: Two equivalent definitions of continuity cannot contradict but gets a bit confusing with these two theorem. This is regarding Theorem $18.4$ and Theorem $19.6$   from Topology  by   Munkres.

Theorem 18.4:  Let $$f:A\rightarrow X\times Y$$  be given by the equation $$f(a)=(f_1(a),f_2(a)).$$ Then $f$ is continuous iff $f_1$ and $f_2$ are continuous.
Theorem 19.6:  Let $$f:A\rightarrow \prod_{\alpha \in J} X_{\alpha}$$ br given by $$f(a)=(f_{\alpha}(a)))_{\alpha \in J}.$$ Where $f_{\alpha}:A\rightarrow X_{\alpha}$ for each $\alpha.$ Then $f$ is continuous iff $f_{\alpha}$  is continuous for each $\alpha$ provided the product space $\prod_{\alpha \in J} X_{\alpha}$ is  given product topology.

Now , $18.4$ clearly shows that result holds irrespective of the type of topology when the product is finite.While $19.6$  shows that the results holds only for product topology and not for box topology as illustrated later by example $2$ , when we are taking arbitrary product.
Now, for $19.6$ , let us take an arbitrary open set from $\prod_{\alpha \in J} X_{\alpha}$ , say $U=\prod_{\alpha\in J} U_{\alpha}$ where each $U_{\alpha}$ is open in $X_{\alpha}.$ Now,$a\in f^{-1}(U) \iff a\in \bigcap_{\alpha \in J} \{f_{\alpha}^{-1}(U_{\alpha})\}.$ Now by continuity of each $f_\alpha$ we know each of $f_\alpha^{-1}(U_{\alpha})$ is open in $A$. But since arbitrary intersection of open sets may or may not be open so so the proof similar to $18.4$ does not work here. Later in the example we see that indeed the intersection ends up becoming $\Phi$ for box topology and thus unable to contain any point.
But , had we taken a closed set say, $C=\prod _{\alpha\in J}C_\alpha$ from $\prod_{\alpha \in J} X_{\alpha}$ s.t each $C_{\alpha}$ is closed in $X_{\alpha}$ containing a point $x=(x_{\alpha})_{\alpha}$, then since arbitrary intersection of closed set is again a closed set we would have $f^{-1}(C)=\bigcap_{\alpha \in J} \{f_{\alpha}^{-1}(C_{\alpha})\}$ will be another closed set in $A$.But inverse of a closed set being closed set  implies continuity. But we know our function is not continuous here. So what happened?
In fact , Continuity $\iff$ inverse image of every open set is open $\iff$  inverse of every closed set is closed.
So I'm misunderstanding some point here. Please clarify.
Thank you.

A: There are a lot more closed sets in $\prod_\alpha X_\alpha$ than those that can be written as $\prod_\alpha C_\alpha$ with $C_\alpha \subset X_\alpha$ closed. This even holds for finitely many spaces: The diagonal is closed in $X \times X$ (when $X$ is Hausdorff) but not of this form.
You've only shown $f^{-1}[C]$ closed for a (too limited) subfamily of closed subsets $C$ of the product.


text:
Q: What's a good "mobile" .NET database that supports LINQ? I'm in the process of refactoring an application and I've decided to use a mobile/embedded database.
I've been reading about SQL Server Compact Edition, but I was wondering if any of you knew of any other databases that could be used and don't have huge download sizes, as my current application is about ~2MB (installer). SQLite would be nice, but AFAIK the GSoC implementation of LINQ-to-SQLite is rather buggy at the moment.
Thanks!

A: I have tried out db40 once (not the compact edition) - it is an object database. However, depending on your needs it may be a rather comfortable thing to use. They note that they support linq even for the compact edition:
http://www.db4o.com/s/compactframeworkdb.aspx

A: VistaDB and (as you mentioned) Sql Server Compact Edition are two small options for an embedded database. Sql Server Compact Edition can be used with Linq to SQL or Entity Framework. I believe VistaDB can be used with the Entity Framework.
Also, if you do not require a relational database, you may want to consider db4o. Rob Conery writes about this here.
Hope this helps!

A: I haven't used it myself, but you might want to look at BlackFish. I'm not sure about its Linq support though, but Delphi supports Linq so it may. Another may be Embedded Firebird - again, not sure about the Linq side of things.


text:
Q: How to read and write to SD card? I have an app that can open and edit binary file from external SD card. I want to have possibility to save this file back from where it was opened.
I have added permissions in manifest file and I also ask user for permission.
Thanks to those permissions I can open file and get the data but when I want to save file to external SD card there is an error: java.io.FileNotFoundException: /storage/3834-3433/file.bin: open failed: EACCES (Permission denied).
Here is code for granting permission:
public boolean isStoragePermissionGranted() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    == PackageManager.PERMISSION_GRANTED) {
                return true;
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                return false;
            }
        }
        else {
            return true;
        }
    }

Here is the code for choosing and getting file path:
button.setOnClickListener(v -> {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            startActivityForResult(intent, 200);
        });

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case 200:
                if (resultCode == RESULT_OK) {
                    String filePath = Objects.requireNonNull(data.getData()).getPath();
                    filePathMain = filePath;
                }
                break;
        }
    }

And this is the part of code to save file:
void byteArrayToFile() {
        try (OutputStream out = new FileOutputStream(filePathMain)) {
            out.write(outBytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

I have no idea why it allows me to open file but not to write when I have <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />.
I also had to run this app on the real device because when I run this on emulator there is an error that it can't find the file I choose.
I could really use some help on this. Thank You.

A: Based on @CommonsWare comment I changed from ACTION_GET_CONTENT to ACTION_OPEN_DOCUMENT to get a file Uri.
Also used ContentResolver to read:
InputStream inputStream = getContentResolver().openInputStream(uri);

and write to file:
ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(uri, "w");
FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());

And now it's working properly.


text:
Q: Are the diagonals of the density operator always the probabilities of finding the system in various states? I found lecture notes online that said "Diagonal density matrix elements are the probabilities of finding system in various states." My quantum mechanics textbook doesn't say anything about this, it just says that the probability a state is in $\big|\phi \big>$ can be found from the density operator $\hat \rho=\big|\psi\big>\big<\psi\big|$ by using the projection operator $\hat P_{|\phi>}=\big|\phi\big>\big<\phi\big|$ and taking the trace of the product of the two operators:
$$tr\big(\hat P_{|\phi>}\hat \rho\big)=\big<\phi|\psi \big> \big<\psi|\phi\big>= \big|\big<\phi|\psi \big> \big|^2.$$
I can see that this is the probability, and from what I understand this will always work. However, it seems like just using the diagonal elements is much faster than having to do this math. Is it safe to say that the diagonal elements of the density matrix itself will always give you the probabilities or does it depend on the basis that the matrix is in?


text:
Q: Extension of conformal map and annulus My question is the following : suppose you have a doubly-connected open set $\Omega \subset \mathbb{C}$, that is a domain bounded by 2 non-intersecting circles $C_1$ (the interior) and $C_2$ (the exterior).
This is well known (an exercise in Ahlfors's book) that there exists a conformal mapping $\varphi$ from $\Omega$ to an annulus $A(r) = \{ z \in \mathbb{C}, r< |z| <  1 \}$.
My question is the following : is it possible to extend $\varphi$ to a conformal map from the interior of $C_2$ to $D = \{ z \in \mathbb{C} , |z|<1 \}$? Another way to ask the question is the following : is it possible to find a conformal map from the interior of $C_2$ to $D$, which restricts to a conformal map from $\Omega$ to $A(r)$?

A: As Robert writes, the answer is positive for round circles, which follows from the fact that Möbius transformations map circles to circles (and you can map any circle contained in the unit disc to a circle with its centre at 0).
As Neil mentions, the answer is negative for arbitrary curves. Indeed, this is trivial if the curves in question are not analytic. If the curves are analytic, but not round circles, then you can extend the conformal map across the boundary to a larger annulus by Schwarz reflection, but not to the whole disc - again, because Möbius transformations map circles to circles, and any conformal isomorphism between discs is Möbius!
Finally, to respond to the new version of the question raised in your comment - Suppose that your annulus has modulus M, and let $\psi$ be a conformal map that takes the interior of $C_2$ to the unit disc, normalised in such a way that $\psi^{-1}(0)\notin \Omega$. (This assumption was missing from your question, but without it it is clear that you cannot say anything.)
Consider the annulus $A := 1/\psi(\Omega)$. This is a doubly connected region of modulus M, separating the unit circle from $\infty$. Let $R>1$ be the smallest number such that $A$ omits a point of modulus $R$; wlog this point is $R$ itself. What you are asking for is a lower bound on $R$.
It is well-known that, among all such annuli, the Grötzsch annulus, which is the complement of the closed unit disc and the segment $[R,\infty)$, has the largest modulus, which we denote $M(R)$. (See Ahflors, "Conformal Invariants".) Hence we see that $M(R)\geq M$.
In other words, let $\rho>1$ be such that $M(\rho) = M$. (Such $\rho$ exists because $M$ is clearly monotone and continuous, and tends to $0$ and $R\to 1$ and to $\infty$ as $R\to\infty$.) Then $R\geq \rho$, and hence
$$\psi(\Omega) \subset D(0,1/\rho),$$
which answers your question. Clearly this bound is sharp, by construction.
There are explicit estimates for the modulus of the Grötzsch annulus; see e.g. Ahlfors's book cited above.
Another interpreation of your question can be given when your inner boundary $C_1$ is not a round circle, but a quasicircle. (This is true whenever the curve is smooth.) In this case, you can extend the conformal isomorphism to the round annulus to a map that will in general not be conformal, but at least be quasiconformal, with constants depending on the constants in the quasicircle definition. Quasiconformal maps satisfy some nice properties, so again these will give you some control over the image of your curve.

A: If I understand your question correctly then the answer is negative.  Indeed, $C_2$ could be the the unit circle and $C_1$ could be a square.  Now $\varphi$ has to be a conformal automorphism of $D$, and any such automorphism has the form $\varphi(z)=\lambda(z-\alpha)/(1-\overline{\alpha}z)$ for some $\alpha,\lambda$ with $|\alpha|<1$ and $|\lambda|=1$.  In particular, $\varphi$ is a Mobius map and so sends circles to circles and non-circles to non-circles.  In particular, it does not send $C_1$ to a circle, and so does not send the original region $\Omega$ to an annulus.

A: Yes: if there is a conformal map from $\Omega$ to $A(r)$ that takes $C_1$ to $\{|z|=r\}$ and $C_2$ to $\{|z|=1\}$, then there is a Möbius transformation that does so, and the pole of this function is outside $C_2$ so it does extend.


text:
Q: How to force an edit to readonly property in c# for unit testing I have the following property in my class.
public bool IsUser
{
    get
    {
        return true;
    }
}

I am trying to write a unit test for this one where I have to make IsUser as false.
I am trying to avoid changes in the original property. Is it possible to change just in the unit test.

A: The code that you posted not support any assign operation at all
because you actualy did not store any information you just return logical constant. To support assign operation you must use some class field explicitly as I posted in first example of implicitly - in second.
You may make set method of property protected, than derive test class or mock class with public IsUser property setter in you test assembly from class you want to test.
public bool IsUser
{
     protected set
     {
           _someMemberVariable = value;
     }
     get
     {
           return _someMemberVariable;
     }
}

or just
public bool IsUser
{
     protected set;
     get;
}

This snippet displays property wich can be read from any classes but, can be assigned only from itself or derived types.
_someMemberVariable in this case must be private class field.


text:
Q: OpenSplice with Qt5 Execution Error Creation failed: invalid handle I'm trying to run the tutorial example of OpenSplice using Qt5. I successfully built the program but when I run it I get the following error :

Error in DDS::DomainParticipantFactory::create_participant: Creation
  failed: invalid handle

After many debugging steps I came to the conclusion that my executable doesn't link to my ospl ! I figured that out because when it crashes no ospl-error.log is generated.
I sourced the release file correctly . ./release.com and launched my qtcreator from the same terminal so all the environment variables are correctly set (especially OSPL_URI and OSPL_HOME)
Does anyone have any idea on how to fix this ?

A: I finally managed to solve this problem and thought of sharing the answer.
The problem was that I was including all the DDS libs in my .pro I was including the following libs :
unix:!macx: LIBS += -L$$PWD/../../PrismTech/Vortex_v2/Device/VortexOpenSplice/6.7.1/HDE/x86_64.linux/lib/ -lcmagent -lcmjni -lcmsoap -lcmxml -ldbmsconnect -ldcpsc99 -ldcpsccpp -ldcpsgapi -ldcpsisocpp -ldcpsisocpp2 -ldcpssac -ldcpssacpp -ldcpssaj -lddsconf -lddsconfparser -lddsdatabase -lddshts -lddsi2 -lddsi2e -lddskernel -lddsos -lddsosnet -lddsrmi -lddsrrstorage -lddsserialization -lddsuser -lddsutil -ldurability -lfacecpp -lleveldb-ospl -llzf-ospl -lnetworking -lnwbridge -lrlm913 -lrnr -lsigar-amd64-linux -lsnappy-ospl -lsnetworking -lspliced -lsqlite3-ospl -lstreamsccpp -lstreamsisocpp -lstreamssacpp

INCLUDEPATH += $$PWD/../../PrismTech/Vortex_v2/Device/VortexOpenSplice/6.7.1/HDE/x86_64.linux/include
DEPENDPATH += $$PWD/../../PrismTech/Vortex_v2/Device/VortexOpenSplice/6.7.1/HDE/x86_64.linux/include

I am now using a minimal set of libs that the program requires and now it runs perfectly. Here is what I am using now:
unix:!macx: LIBS += -L$$PWD/../PrismTech/Vortex_v2/Device/VortexOpenSplice/6.7.1/HDE/x86_64.linux/lib/ -lddskernel -ldcpsisocpp

INCLUDEPATH += $$PWD/../PrismTech/Vortex_v2/Device/VortexOpenSplice/6.7.1/HDE/x86_64.linux/include
DEPENDPATH += $$PWD/../PrismTech/Vortex_v2/Device/VortexOpenSplice/6.7.1/HDE/x86_64.linux/include

Actually the error is caused by -ldcpsccpp and -lddshts. By removing those libs the application works perfectly.


text:
Q: Storing a password locally using Java keystore I have a Java program which connects to an external service using a username/password. The password is currently encrypted but hard coded within the Java code itself. I would like to hide this password so that it is read from a location that is not visible. Does the java keystore API's provide this functionality ?
Reading the keystore doc http://docs.oracle.com/javase/tutorial/security/toolsign/index.html seems to be just associated with signing jar files ?
Please suggest if there are other api's which perform functionality I'm trying to implement.

A: If it's encrypted then just store it in a properties file.
At the end of the day if you store it locally then you store it locally, encryption is already the only thing you can do to really make it safe.


text:
Q: Getting Uncaught TypeError: Cannot read properties of undefined (reading 'then') while working with Javascript Promise I declare a window promise where I get a response and stor it in a JS ojbect. The script does not get executed. I am getting an error while working with the Javascript promise:

Cannot read properties of undefined (reading 'then')

window.promise.then(function(response) {
  var jsObject = JSON.parse(response);

  if (jsObject.enableEmailVerificationOnRegistration) {
    alert('hii enable verification tggle is on')
    var signUpClick = document.getElementById("registrationSignUp");
    signUpClick.addEventListener('click', function(e) {
      event.preventDefault();
      var getPdpUrl = window.parent.location.pathname;
      document.getElementById("pdpUrlValue").value = getPdpUrl;
      localStorage.setItem("currentPdpPath", getPdpUrl);
      window.location.href = getPdpUrl;
    });
  }
});


text:
Q: Auth key for private GitHub repo with Paket The paket docs show how to reference a private GitHub repo but the config docs section isn't particularly illuminating on the particulars of how to set up the 'GitHub Auth Key'.
In particular, I am not sure from reading this what I should be using as arguments.
I have tried packet config add-token "http://github.com" [my github personal access token] but get the following error when running paket update:

Paket failed with:
          Could not find hash for https://api.github.com/repos/[my username]/[my private repo]/commits/master

Any pointers would be greatly appreciated!
Michael


text:
Q: C# Swashbuckle SwaggerResponseAttribute I have a WebApi project and I am trying to implement Swagger. I am using Swahbuckle (5.2.1).
In my actual project I have already an attribute for my responses :
[ResponseForApi(HttpStatusCode.OK)]
My problem is I am using Swashbuckle (5.2.1) and I don't want to put an other attribute for my methods. I know how to put responses on Swagger, I can use the 'XML Comments' or the attribute :
[SwaggerResponse(HttpStatusCode.OK)]
My question is : Is there a way to use 'SwaggerResponse' by calling 'ResponseForApi' ?

A: You could do this by wiring up your own IOperationFilter based on ApplySwaggerResponseAttributes -- that's the thing that scans for [SwaggerResponse]. Here's something I whipped up based on the Swashbuckle code
 https://github.com/domaindrivendev/Swashbuckle/blob/master/Swashbuckle.Core/Swagger/Annotations/ApplySwaggerResponseAttributes.cs
public class ApplyResponseTypeAttributes : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        if (apiDescription.GetControllerAndActionAttributes<SwaggerResponseRemoveDefaultsAttribute>().Any())
        {
            operation.responses.Clear();
        }

        // SwaggerResponseAttribute trumps ResponseTypeAttribute
        var swaggerAttributes = apiDescription.GetControllerAndActionAttributes<SwaggerResponseAttribute>();

        if (!swaggerAttributes.Any())
        {
            var responseAttributes = apiDescription.GetControllerAndActionAttributes<ResponseTypeAttribute>().OrderBy(attr => attr.ResponseType.Name);

            foreach (var attr in responseAttributes)
            {
                const string StatusCode = "200";

                operation.responses[StatusCode] = new Response
                {
                    description = InferDescriptionFrom(StatusCode),
                    schema = (attr.ResponseType != null) ? schemaRegistry.GetOrRegister(attr.ResponseType) : null
                };
            }
        }
    }

    private string InferDescriptionFrom(string statusCode)
    {
        HttpStatusCode enumValue;
        if (Enum.TryParse(statusCode, true, out enumValue))
        {
            return enumValue.ToString();
        }
        return null;
    }
}

In your swagger configuration in ./App_Start add the following to register this filter. It's actually pretty interesting putting a breakpoint on this so you can see how Swashbuckle works, it iterates through all your controller's actions.
c.OperationFilter<ApplyResponseTypeAttributes>();


text:
Q: The fundamental theorem of algebra, any real polynomial can be written in factors of degree of $1$ or $2$ Does the theorem that any real polynomial can be written in factors of degree of $1$ or $2$ really only hold only for polynomials with real coefficients. Why doesn't it hold for a polynomial with complex coefficients?
If I understand this theorem correctly, it's meant that it is written only in multiplication between factors (no addition) and that those factors that are multiplied together have the degree either $1$ or $2$, and we can always get any polynomial in that form. Is my understanding correct?

A: Here is what the situation is for real and complex polynomials:

*

*Any real polynomial can be written as the product of real polynomials of degree $1$ or $2$.

*Any complex polynomials can be written as the product of complex polynomials of degree $1$.

And, since any real polynomial is in particular a complex polynomial:

*

*Any real polynomial can be written as the product of complex polynomials of degree $1$.


text:
Q: Automation server can't create object :unsigned activeX control works on the system where its created but not on any other I have created an activeX control (not signed) using VS 2008 and following this link, and converted it into a cab file, which is then placed on the server. When I am accessing the page with the activeX control embedded from the machine in which I created the activeX (which is different from the server), the control is working fine, but if I access the same page on another machine, it shows the infamous error 'Automation server can't create object'
Everywhere I search for this error, I find that it disappears if I place the site in the 'Trusted' zone, and customize the security settings for that zone to
'Enable' for 'Download unsigned activex controls'
'Disable' for 'Only allow approved domains to use activex without prompt'
'Enable' for 'Initialize and script activex controls not marked as safe for scripting'
'Disable' for 'Allow activex filtering'

But, unfortunately, it doesn't work for me. Something I can't understand is that why does it work on the machine I created the activeX, and not in others even though they have the same IE settings Has it got anything to do with the control being registered by Visual Studio at the time of can creation on the machine in which I created the control?
I don't wish to run any registry-changing commands manually, as this should be done by the cab file itself somehow on client machines


text:
Q: Is it possible to process files from a shared network drive with Gulp? I'm trying to run a simple minification process using gulp. I've done this successfully on local source files on my machine, but what I'm trying to do is target the files on a shared network drive. Basically what I'm doing:
gulp.src(_inputPath)
    .pipe(uglify())
    .pipe(gulp.dest(_outputPath));

Where _inputPath and _outputPath are variables set by a config file:
{
    "input": "\\\\drive-name\\home\\project\\js\\*.js",
    "output": "\\\\drive-name\\home\\project\\dist\\"
}

The output of files to the network directory works fine (tested by having the input set to a local directory), but I can't seem to get the input to work. What am I doing wrong?]
EDIT:
I'm able to do the following:
glob('**/*.js', {cwd:_inputPath}, (err, files) => { if (err) throw err; console.log(files) });

And successfully return the files, but trying to use the cwd option in gulp.src doesn't work:
gulp.src('**/*.js', {cwd: _inputPath})


text:
Q: Is it safe to use an American power adapter in India and Australia? I'm going to India and Australia on a business trip in a couple of days and plan to carry only a tablet instead of my trustworthy laptop (which got dunked in the tub by my oldest - don't ask). The adapter states the following:
100-240V~0.65A, 50/60Hz Output 12V===2A
Will it be safe to use the adapter in these countries to charge my device, or do I have to buy new ones there? If the latter, what kind? What else should I take along with me? A surge protector?

A: By the looks of it, the adapter will work as long as you have the "adapter"!
India
230 V
50 Hz

Australia
230 V
50 Hz

source

A: According to this chart, both of those countries use 220-240 Volts at 50 Hz.  Your adapter says that it does support those voltages and cycles.
However, you will need adapters for the shape of the plug so that your plug will fit in the socket.  Most electronics stores carry these fairly cheaply.


text:
Q: Stripe documentation style sidenav with react Does anyone have any ideas how I can achieve the sidenav on the stripe documentation page https://stripe.com/docs The side nav has nested elements. I was wondering how on click of "Payments" on the home page can I open up the payments side nav and its nested list and do a redirect to the payments page. I know that doesn't make sense but if you click the docs page and try you may understand what I am trying to achieve.

A: You can achieve similar behavior with CSS height transition. They appears to be pretty smooth on desktop (60fps is achievable but not through full transition period). If you need more control (for example close other navigation 'ul's when other is opened) you can remove checkbox elements and change label elements to "h2". Then set "onclick" listener on "h2" elements in JS code that will add class (with styles from "input:checked ~ ul") to selected "ul".

:root {
  --liHeight: 1em
}

label {
  cursor: pointer
}

ul {
  opacity: 0;
  height: 0px;
  overflow: hidden;
  transition: 0.3s;
}

ul li {
  height: var(--liHeight);
}

input {
  position: absolute;
  opacity: 0;
}

input:checked ~ ul {
  opacity: 1;
  position: initial;
  height: calc(7 * var(--liHeight));
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

      Item 1

    <input id="item1" type="checkbox"/>

1

1

1

1

1

1

      Item 2

    <input id="item2" type="checkbox"/>

1

1

1

1

1

1

      Item 3

    <input id="item3" type="checkbox"/>

1

1

1

1

1

1

Another solution is to write JS animation, for example using "window.requestAnimationFrame" API, to animate height of "ul" element. (I think that this is what exacly is happening on stripe.com)


text:
Q: Remove folder starting with – (en dash) Don't know how, but I ended up with a folder named –p (en dash, not regular dash)
[test@test work]$ ls -haltr
total 12K
drwxrwxrwx.  2 docker_test docker_test 4.0K Feb 23  2018 –p
drwxrwxrwx. 10 docker_test docker_test 4.0K Oct  9 15:30 ..
drwxrwxrwx.  3 docker_test docker_test 4.0K Oct 11 14:34 .
[test@test work]$ rm –p
rm: cannot remove '–p': Is a directory
[test@test work]$ rmdir –p
rmdir: failed to remove '–p': No such file or directory
[test@test work]$ rm -rf *
[test@test work]$ ls
–p
rm: remove directory '–p'? y
rm: cannot remove '–p': No such file or directory
[test@test work]$ rm -rf -- *p
[test@test work]$ ls
–p
[test@test work]$ rm -rf ./?p
[test@test work]$ ls
–p

Anyone has a clue ?
I also try find but didn't work either
find work/ -name '–p' -delete

I also tried from winscp, rm -rf * but nothing.

A: Try
rm -ri -- *p

Or if you are sure that you run the command in the correct working directory and that you want to remove everything without confirmation, use
rm -rf -- *p

I use option -i (interactive) in combination with -r (recursive) to get a prompt for confirmation and to remove directories with all their contents.
-- separates options from other arguments that may start with -
*p expands to all names that end with p.


text:
Q: 'Cannot Find Module' when using an Image in React I am using React and I am running into an issue importing images in a component.  Now I know how to use the import method, which is fine for some things but in this case the image src is part of an array of objects I need to map over.
So let me start with if I do this directly:   It works just fine.
However if I do this:  or  I get:
react-dom.development.js:11340 Uncaught Error: Cannot find module '../../images/leadinvestigator.jpg'
and if I do this:  I get an invalid token error
here is my component code:
import React from "react"
import "react-responsive-carousel/lib/styles/carousel.min.css"
import { Carousel } from 'react-responsive-carousel'
import './styles.css'

const Crew = () => {
  const crewMembers = [
    {
      image: '../../images/leadinvestigator.jpg',
      name: 'Bryant Richards',
      title: 'Lead Investigator',
      quote: 'In the end, it only matters what you believe'
    }
  ]
  return (
    <Carousel
      showArrows={true}
      infiniteLoop={true}
      showThumbs={false}
      showStatus={false}
      autoPlay={true}
      interval={6100}
    >

      {
        crewMembers ? crewMembers.map(member => (

{member.name}

Designer

                It's freeing to be able to catch up on customized news and not be
                distracted by a social media element on the same site

        )) : null
      }
    </Carousel>
  )
}

export default Crew

A: Try to import your image before put it in the object.
Add on top of your component:
import bryantImage from '../../images/leadinvestigator.jpg'

and then add this image to your object like that:
const crewMembers = [
    {
      image: bryantImage,
      name: 'Bryant Richards',
      title: 'Lead Investigator',
      quote: 'In the end, it only matters what you believe'
    }
  ]


text:
Q: Could not load file or assembly 'HtmlAgilityPack, Version=1.11.7.0? I have F# console project which uses HtmlAgilityPack. It worked and I upgraded version 1.11.7.0. Now it got the following error?

System.IO.FileLoadException
HResult=0x80131040
Message=Could not load file or assembly 'HtmlAgilityPack, Version=1.11.7.0, Culture=neutral, PublicKeyToken=bd319b19eaf3b43a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)


text:
Q: Bootstrap multiple progress bars start meddle

I want to create a progress bar using Bootstrap that looks like the image below (related to the stock market price). There is a middle point (starting price). The lowest price and the highest price are used for the Progress Bar. If each of these two prices is smaller than the starting price, it will be red and if it is bigger than the starting price, it will be green. It is also possible that both prices are greater than the starting price and vice versa.

How can I do that? Or where exactly should I research?
update

.progress-label.left {
  float: left;
  margin-right: 1em;
}

.progress-label.right {
  float: right;
  margin-left: 1em;
}

.price-change {
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
  align-items: center;

}

.price-change .left,
.price-change .right {
  flex: 0 0 3%;
  font-size: .75rem;
}

.price-change .left {
  text-align: left;
}

.price-change .progress {
  margin: 0.25rem;
  flex-grow: 8;
  border-radius: 0;
}

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<!DOCTYPE html>

      210500

      210000

Using Bootstrap I partially built this. But I have to do a lot of calculations to replace progress-bar percentages.

How can I specify the two arrows as well as the middle of it as shown in the figure?


text:
Q: How to display two models on one EmberJS page? What is the basic setup for displaying instances of two different models of two different types on one "page"?
For example, I have two models, say, College and Student. Each is stored in a REST server. On a certain route, I want to pull particular instances of each and display the "name" attribute for each.
Coming from the Rails world, I don't quite understand the Model-View-Controller concept of EmberJS. It seems that in EmberJS, each controller can handle just one model type. So does this mean that a separate controller must be used for each type to be displayed?

A: In ember if you follow the naming convention strictly then your assumption is correct that the best practice is to have a controller per model per view, but in most cases where the requirements are differ you can also diverge from the convention, and to satisfy your needs you could conceptually do something like this:
javascript
var App = Ember.Application.create();

App.IndexRoute = Ember.Route.extend({
  model: function(){
    return Ember.Object.create({post: App.Post.find(1), page: App.Page.find(1)});
  }
});

App.Store = DS.Store.extend({
 revision: 12,
 adapter: 'DS.FixtureAdapter'
});

App.Post = DS.Model.extend({
 title: DS.attr('string'),
 description: DS.attr('string')
});

App.Page = DS.Model.extend({
 title: DS.attr('string'),
 text: DS.attr('string')
});

App.Post.FIXTURES = [
  {
    id: 1,
    title: "My super post",
    description: "Lorem ipsum dolor sit amet..."
  }
];

App.Page.FIXTURES = [
  {
    id: 1,
    title: "My super page",
    text: "Lorem ipsum dolor sit amet..."
  }
];

templates

And here a working jsbin that show's the concept.
Hope it helps

A: This jsbin shows another way to display two models: org model (with attributes "name" and "description") and member model (with just the "name" attribute). The JSBin is set up with a local storage adapter where you can enter in data.
handlebars and html:
  Here are the Orgs:

  {{#each model}}

{{name}} - {{description}}

  {{/each}}

  Here are the Members:
  {{#each member in members}}

{{member.name}}

  {{/each}}

The key is in the controller:
Javascript:
App.OrganizationRoute = Ember.Route.extend({
  model: function() {
    return App.Org.find();
  },
  setupController: function(controller, model) {
    controller.set('members', App.Member.find());
  }
});

(based on this answer)


text:
Q: why am i getting NameError: global name 'spacing' is not defined I'm getting a NameError: global name 'spacing' is not defined for and im not sure why
def main():
    print("Project One\n")
    print("To encrypt message enter: 1")
    print("To decrypt messsge enter: 2\n")
    pick = int(input())
    if pick == 1:
        print("Encrypting!")
        spacing()
    elif pick == 2:
       print("Decrypting!")
    else:
        print("Try again")

if __name__ == '__main__':
    main()

def spacing():
    text = raw_input("Please Enter the message to encrypt: ").upper()
    print(text)
    key = raw_input("Please enter a key to encrypt").upper()
    print(key)
    space_ignore = ""
    j = 0
    for i in range(len(text)):
        if ord(text[i]) == 32:
            space_ignore += " "
        else:
            if j < len(key):
                space_ignore += key[j]
                j += 1
            else:
                j = 0
                space_ignore += key[j]
                j += 1
    print(space_ignore)
    return text, space_ignore

A: Python defines are evaluated in-order relative to other statements. By the time main() runs, spacing() has not yet been defined since control has not yet reached def spacing(): .... Move your if __name__ == 'main': block to below the definition of spacing.

A: Put spacing() definition above main definition and the last thing you need to place is this:
if __name__ == '__main__':
    main()

A: python is a scripting language,would do "line by line" or easy say:from top to end.
make the spacing before main.


text:
Q: Disallow * in php Search I want to suppress Searches on a database from users inputting (for example) P*.
http://www.aircrewremembered.com/DeutscheKreuzGoldDatabase/
I can't work out how to add this to the code I already have. I'm guessing using an array in the line $trimmed = str_replace("\"","'",trim($search)); is the answer, replacing the "\"" with the array, but I can't seem to find the correct way of doing this. I can get it to work if I just replace the \ with *, but then I lose the trimming of the "\" character: does this matter?
// Retrieve query variable and pass through regular expression.
// Test for unacceptable characters such as quotes, percent signs, etc.
// Trim out whitespace.  If ereg expression not passed, produce warning.
$search = @$_GET['q'];
// check if wrapped in quotes
if ( preg_match( '/^(["\']).*\1$/m', $search ) === 1 ) {
   $boolean = FALSE;
}

if ( escape_data($search) ) {
   //trim whitespace and additional disallowed characters from the stored variable
   $trimmed = str_replace("\"","'",trim($search));
   $trimmed = stripslashes(str_ireplace("'","", $trimmed));
   $prehighlight = stripslashes($trimmed);
   $prehighlight = str_ireplace("\"", "", $prehighlight);
   $append = stripslashes(urlencode($trimmed));
} else {
   $trimmed = "";
   $testquery = FALSE;
}

$display = stripslashes($trimmed);

A: You already said it yourself, just use arrays as parameters for str_repace:
http://php.net/manual/en/function.str-replace.php
$trimmed = str_replace( array("\"", "*"), array("'", ""), trim($search) );

Every element in the first array will be replaced with the cioresponding element from the second array.

For future validation and sanitation, you might want to read about this function too:

http://php.net/manual/en/function.filter-var.php

A: use $search=mysql_real_escape_string($search); it will remove all characters from $search which can affect your query.


text:
Q: Como substituir o número de letras de uma palavra por um caractere? Estou fazendo um jogo da forca, vamos supor que eu digite o nome "joão" em uma caixa de text, logo depois aperto um botão e quero que na caixa de "texto 2" apareça "_ _ _ _", então quero que apareçam o mesmo numero de underlines que o numero de letras.

A: Existe um construtor pronto para fazer isto então é muito simples.
using System;

public class Program {
    public static void Main() {
        var texto = "carambola";
        var adivinha = new String('_', texto.Length);
        Console.WriteLine(adivinha);
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Se fizer um laço adicionando strings é mais lento e faz um estrago no garbage collector. Pode não ser importante fazer em um joguinho muito simples, mas se aprende errado em algo simples vai reproduzir em algo que importe mais. Pelo menos poderia usar StringBuilder neste caso, mas também seria um exagero.

A: Você pode usar o string.Length para saber o tamanho da palavra que você possui.
Depois você pode Iterar em cima desse tamanho escrevendo "_"
Exemplor:
for(int i=0; i< string.Legth; i++)
{
  // aqui você pode criar um string igual ao seu exemplo
  novaString += "_";
}

Ou então com foreach
foreach(Char caracter in SuaString)
{
  // aqui você pode criar um string igual ao seu exemplo
  novaString += "_";
}

Ai você pode usar sua novaString para mostrar na tela o exemplo, existem outras formas de fazer, depende de como você vai mostrar esse texto.

A: Além do que já foi respondido anteriormente você pode usar expressão regular 'Regex' com a função replace, substituindo os caracteres.
string txt = "Primeiro Teste";
string forca=   Regex.Replace(txt, "[\\w]", "_");

O resultado é: ________ _____

Se preferir fazer similar a forca basta colocar um espaço após o carácter Undescore:
string txt = "Primeiro Teste";
string teste2 = Regex.Replace(txt, "[\\w]", "_ ");

O resultado é: _ _ _ _ _ _ _ _  _ _ _ _ _