text:
Q: ActionScript Error: 1120: Access of undefined property myRec on a defined variable I'm trying to write a dollar recognizer in Flash Builder. I'm really new to actionscript and mxml, and I''m getting this error on the line "myRec.addTemplate..." in the code below:
import de.yuv.gestures.Recognizer;

import flash.display.Graphics;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.geom.Point;

var myRec:Recognizer = new Recognizer();

myRec.addTemplate("triangle", new Array(new Point(137,139),new Point(135,141),new Point(133,144),new Point(132,146),new Point(130,149),new Point(128,151),new Point(126,155),new Point(123,160),new Point(120,166),new Point(116,171),new Point(112,177),new Point(107,183),new Point(102,188),new Point(100,191),new Point(95,195),new Point(90,199),new Point(86,203),new Point(82,206),new Point(80,209),new Point(75,213),new Point(73,213),new Point(70,216),new Point(67,219),new Point(64,221),new Point(61,223),new Point(60,225),new Point(62,226),new Point(65,225),new Point(67,226),new Point(74,226),new Point(77,227),new Point(85,229),new Point(91,230),new Point(99,231),new Point(108,232),new Point(116,233),new Point(125,233),new Point(134,234),new Point(145,233),new Point(153,232),new Point(160,233),new Point(170,234),new Point(177,235),new Point(179,236),new Point(186,237),new Point(193,238),new Point(198,239),new Point(200,237),new Point(202,239),new Point(204,238),new Point(206,234),new Point(205,230),new Point(202,222),new Point(197,216),new Point(192,207),new Point(186,198),new Point(179,189),new Point(174,183),new Point(170,178),new Point(164,171),new Point(161,168),new Point(154,160),new Point(148,155),new Point(143,150),new Point(138,148),new Point(136,148)));

It's really confusing me since I've defined myRec just above it. The same code, though, works in Flash Professional, which leads me to believe that I'm missing some import statement or other subtlety that isn't being made clear my this error message.
Any help would be greatly appreciated.
Thanks,
NinjaSteph
Edit (complete error message):
Description Resource    Path    Location    Type
1120: Access of undefined property myRec.   GestureRecognizer.mxml  /GestureRecognizer/src  line 17 Flex Problem
Edit (complete mxml file):
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
           xmlns:s="library://ns.adobe.com/flex/spark"
           xmlns:mx="library://ns.adobe.com/flex/mx"
           minWidth="955" minHeight="600" currentState="Title">
<fx:Script><![CDATA[
    import de.yuv.gestures.Recognizer;

    import flash.display.Graphics;
    import flash.display.Shape;
    import flash.display.Sprite;
    import flash.events.MouseEvent;
    import flash.geom.Point;

    var myRec:Recognizer = new Recognizer();

    myRec.addTemplate("triangle", new Array(new Point(137,139),new Point(135,141),new Point(133,144),new Point(132,146),new Point(130,149),new Point(128,151),new Point(126,155),new Point(123,160),new Point(120,166),new Point(116,171),new Point(112,177),new Point(107,183),new Point(102,188),new Point(100,191),new Point(95,195),new Point(90,199),new Point(86,203),new Point(82,206),new Point(80,209),new Point(75,213),new Point(73,213),new Point(70,216),new Point(67,219),new Point(64,221),new Point(61,223),new Point(60,225),new Point(62,226),new Point(65,225),new Point(67,226),new Point(74,226),new Point(77,227),new Point(85,229),new Point(91,230),new Point(99,231),new Point(108,232),new Point(116,233),new Point(125,233),new Point(134,234),new Point(145,233),new Point(153,232),new Point(160,233),new Point(170,234),new Point(177,235),new Point(179,236),new Point(186,237),new Point(193,238),new Point(198,239),new Point(200,237),new Point(202,239),new Point(204,238),new Point(206,234),new Point(205,230),new Point(202,222),new Point(197,216),new Point(192,207),new Point(186,198),new Point(179,189),new Point(174,183),new Point(170,178),new Point(164,171),new Point(161,168),new Point(154,160),new Point(148,155),new Point(143,150),new Point(138,148),new Point(136,148)));

    var recordedPoints:Array;
    public function hideAllHighlights():void
    {
        for (var i:uint = 0; i < myRec.Templates.length; i++){

            var mc:MovieClip = this["mc_"+myRec.Templates[i].Name];
            trace(mc);
            if (mc)
            {
                mc.visible = false;
            }
        }
    }

    var record:Boolean = false;

    //hideAllHighlights();

    public function handleMouseDown (event:MouseEvent):void
    {
        trace('handleMouseDown:');
        record = true;
        hideAllHighlights();
        recordedPoints = new Array();
        //clear objects from stage that are not circles
        for(var i:int = 0; recPanel.stage.numChildren>i; ){
            if(recPanel.stage.getChildAt(i).name == "circle")
                recPanel.stage.removeChildAt(i);
            else
                i++;
        }
    }

    public function handleMouseUp(event:MouseEvent):void
    {
        trace('handleMouseUp:');
        record = false;
        var myResult = myRec.recognize(recordedPoints);
        trace (myResult.Name);
        trace (myResult.Score);
        resLabel.text = myResult.Name;
        /*var mc:MovieClip = this["mc_"+myResult.Name];
        if (mc){
            mc.visible = true;
        }*/
    }

    public function drawCircle(x:Number, y:Number):void
    {
        var circle:Shape = new Shape;
        circle.name = "circle";
        var radius:Number = 1;
        circle.graphics.beginFill(0x000000);
        circle.graphics.drawCircle(x+recPanel.x, y+recPanel.y, radius);
        recPanel.stage.addChild(circle);
    }

    public function handleMouseMove(event:MouseEvent):void
    {
        if (record){
            trace('handleMouseMove'+event.localX+" "+event.localY);
            recordedPoints.push(new Point(event.localX,event.localY));
            drawCircle(event.localX,event.localY);
        }
    }

    //recPanel.addEventListener ( MouseEvent.MOUSE_DOWN, handleMouseDown );
    //recPanel.addEventListener ( MouseEvent.MOUSE_UP, handleMouseUp );
    //recPanel.addEventListener ( MouseEvent.MOUSE_MOVE, handleMouseMove );

    protected function startBkgd_clickHandler(event:MouseEvent):void
    {
        setCurrentState("RecognizerState");
    }

]]></fx:Script>
<s:states>
    <s:State name="Title"/>
    <s:State name="RecognizerState"/>
</s:states>
<fx:Declarations>
    <!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<s:Label includeIn="Title" fontSize="36" horizontalCenter="0" text="Dollar Gesture Recognizer"
         textAlign="center" verticalAlign="middle" verticalCenter="-30"/>
<s:Label includeIn="Title" fontSize="18" horizontalCenter="0" text=""
         verticalCenter="40"/>
<s:Panel id="recPanel" includeIn="RecognizerState" left="50" width="400" height="400"
         color="#0B333C" fontSize="24" textAlign="center" title="Gesture Recognizer"
         verticalCenter="0" mouseDown="handleMouseDown(event)" mouseMove="handleMouseMove(event)"
         mouseUp="handleMouseUp(event)">
</s:Panel>
<s:Panel id="gesPanel" includeIn="RecognizerState" width="300" height="400" fontSize="24"
         horizontalCenter="0" textAlign="center" title="Available Gestures" verticalCenter="0">
</s:Panel>
<s:Label id="startBkgd" includeIn="Title" x="10" y="10" width="1263" height="591"
         click="startBkgd_clickHandler(event)" />
<s:Panel id="resMeme" includeIn="RecognizerState" right="50" width="400" height="400"
         fontSize="24" title="Resulting Meme" verticalCenter="0">
    <s:Label id="resLabel" x="103" y="165" width="180" text="result" textAlign="center"/>
</s:Panel>

Recognizer class:
package de.yuv.gestures
{
import de.yuv.gestures.Result;
import de.yuv.gestures.Template;

import flash.geom.Point;
import flash.geom.Rectangle;
public class Recognizer {

    public static var NumPoints:int = 64;

    public static var SquareSize:Number = 250.0;
    public static var HalfDiagonal = 0.5 * Math.sqrt(250.0 * 250.0 + 250.0 * 250.0);
    public static var AngleRange = 45.0;
    public static var AnglePrecision = 2.0;
    public static var Phi = 0.5 * (-1.0 + Math.sqrt(5.0)); // Golden Ratio
    public var Templates:Array;

    public function Recognizer(){
            this.Templates = new Array();
    }

    public function recognize(points)
    {
        points = Resample(points, NumPoints);
        points = RotateToZero(points);
        points = ScaleToSquare(points, SquareSize);
        points = TranslateToOrigin(points);

        var b = +Infinity;
        var t;
        for (var i = 0; i < this.Templates.length; i++)
        {
            var d = DistanceAtBestAngle(points, this.Templates[i], -AngleRange, +AngleRange, AnglePrecision);
            if (d < b)
            {
                b = d;
                t = i;
            }
        }
        var score = 1.0 - (b / HalfDiagonal);
        return new Result(this.Templates[t].Name, score);
    };
    //
    // add/delete new templates
    //
    public function addTemplate(name, points)
    {
        this.Templates[this.Templates.length] = new Template(name, points); // append new template
        var num = 0;
        for (var i = 0; i < this.Templates.length; i++)
        {
            if (this.Templates[i].Name == name)
                num++;
        }
        return num;
    }

    // Helper functions

    public static function Resample(points, n)
    {
        var I = PathLength(points) / (n - 1); // interval length
        var D = 0.0;
        var newpoints = new Array(points[0]);
        for (var i = 1; i < points.length; i++)
        {
            var d = Distance(points[i - 1], points[i]);
            if ((D + d) >= I)
            {
                var qx = points[i - 1].x + ((I - D) / d) * (points[i].x - points[i - 1].x);
                var qy = points[i - 1].y + ((I - D) / d) * (points[i].y - points[i - 1].y);
                var q = new Point(qx, qy);
                newpoints[newpoints.length] = q; // append new point 'q'
                points.splice(i, 0, q); // insert 'q' at position i in points s.t. 'q' will be the next i
                D = 0.0;
            }
            else D += d;
        }
        // somtimes we fall a rounding-error short of adding the last point, so add it if so
        if (newpoints.length == n - 1)
        {
            newpoints[newpoints.length] = points[points.length - 1];
        }
        return newpoints;
    }
    public static function RotateToZero(points)
    {
        var c = Centroid(points);
        var theta = Math.atan2(c.y - points[0].y, c.x - points[0].x);
        return RotateBy(points, -theta);
    }

    public static function ScaleToSquare(points, size)
    {
        var B = BoundingBox(points);
        var newpoints = new Array();
        for (var i = 0; i < points.length; i++)
        {
            var qx = points[i].x * (size / B.width);
            var qy = points[i].y * (size / B.height);
            newpoints[newpoints.length] = new Point(qx, qy);
        }
        return newpoints;
    }
    public static function TranslateToOrigin(points)
    {
        var c = Centroid(points);
        var newpoints = new Array();
        for (var i = 0; i < points.length; i++)
        {
            var qx = points[i].x - c.x;
            var qy = points[i].y - c.y;
            newpoints[newpoints.length] = new Point(qx, qy);
        }
        return newpoints;
    }

    public static function DistanceAtBestAngle(points, T, a, b, threshold)
    {
        var x1 = Phi * a + (1.0 - Phi) * b;
        var f1 = DistanceAtAngle(points, T, x1);
        var x2 = (1.0 - Phi) * a + Phi * b;
        var f2 = DistanceAtAngle(points, T, x2);
        while (Math.abs(b - a) > threshold)
        {
            if (f1 < f2)
            {
                b = x2;
                x2 = x1;
                f2 = f1;
                x1 = Phi * a + (1.0 - Phi) * b;
                f1 = DistanceAtAngle(points, T, x1);
            }
            else
            {
                a = x1;
                x1 = x2;
                f1 = f2;
                x2 = (1.0 - Phi) * a + Phi * b;
                f2 = DistanceAtAngle(points, T, x2);
            }
        }
        return Math.min(f1, f2);
    }

    public static function PathLength(points)
    {
        var d = 0.0;
        for (var i = 1; i < points.length; i++)
            d += Distance(points[i - 1], points[i]);
        return d;
    }

    public static function Distance(p1, p2)
    {
        var dx = p2.x - p1.x;
        var dy = p2.y - p1.y;
        return Math.sqrt(dx * dx + dy * dy);
    }
    public static function Centroid(points)
    {
        var x = 0.0, y = 0.0;
        for (var i = 0; i < points.length; i++)
        {
            x += points[i].x;
            y += points[i].y;
        }
        x /= points.length;
        y /= points.length;
        return new Point(x, y);
    }
    public static function RotateBy(points, theta)
    {
        var c = Centroid(points);
        var cos = Math.cos(theta);
        var sin = Math.sin(theta);

        var newpoints = new Array();
        for (var i = 0; i < points.length; i++)
        {
            var qx = (points[i].x - c.x) * cos - (points[i].y - c.y) * sin + c.x
            var qy = (points[i].x - c.x) * sin + (points[i].y - c.y) * cos + c.y;
            newpoints[newpoints.length] = new Point(qx, qy);
        }
        return newpoints;
    }
    public static function BoundingBox(points)
    {
        var minX = +Infinity, maxX = -Infinity, minY = +Infinity, maxY = -Infinity;
        for (var i = 0; i < points.length; i++)
        {
            if (points[i].x < minX)
                minX = points[i].x;
            if (points[i].x > maxX)
                maxX = points[i].x;
            if (points[i].y < minY)
                minY = points[i].y;
            if (points[i].y > maxY)
                maxY = points[i].y;
        }
        return new Rectangle(minX, minY, maxX - minX, maxY - minY);
    }

    public static function DistanceAtAngle(points, T, theta)
    {
        var newpoints = RotateBy(points, theta);
        return PathDistance(newpoints, T.Points);
    }

    public static function PathDistance(pts1, pts2)
    {
        var d = 0.0;
        for (var i = 0; i < pts1.length; i++) // assumes pts1.length == pts2.length
            d += Distance(pts1[i], pts2[i]);
        return d / pts1.length;
    }
}

}

A: Shouldn't this be in some sort of class?
as in:
package
{
    // imports

    public class Main() extends Sprite // extend Sprite if you want to use it as your document class
    {
        public function Main()
        {
            // your code here
        }
    }
}

A: @Amy Blackenship, you are right as I was leaving my code "loose" within my script. Instead of creating a needless class though, I simply put the code within a function that I run when my application starts and that worked. I seems I was just missing something very fundamental about actionscript.
Here's the code for my fix:
    var myRec:Recognizer = new Recognizer();
    public function start():void
    {
        //resImage.source = "assets/omeme.jpg";
        myRec.addTemplate("triangle", new Array(new Point(137,139),new Point(135,141),new Point(133,144),new Point(132,146),new Point(130,149),new Point(128,151),new Point(126,155),new Point(123,160),new Point(120,166),new Point(116,171),new Point(112,177),new Point(107,183),new Point(102,188),new Point(100,191),new Point(95,195),new Point(90,199),new Point(86,203),new Point(82,206),new Point(80,209),new Point(75,213),new Point(73,213),new Point(70,216),new Point(67,219),new Point(64,221),new Point(61,223),new Point(60,225),new Point(62,226),new Point(65,225),new Point(67,226),new Point(74,226),new Point(77,227),new Point(85,229),new Point(91,230),new Point(99,231),new Point(108,232),new Point(116,233),new Point(125,233),new Point(134,234),new Point(145,233),new Point(153,232),new Point(160,233),new Point(170,234),new Point(177,235),new Point(179,236),new Point(186,237),new Point(193,238),new Point(198,239),new Point(200,237),new Point(202,239),new Point(204,238),new Point(206,234),new Point(205,230),new Point(202,222),new Point(197,216),new Point(192,207),new Point(186,198),new Point(179,189),new Point(174,183),new Point(170,178),new Point(164,171),new Point(161,168),new Point(154,160),new Point(148,155),new Point(143,150),new Point(138,148),new Point(136,148)));

Thanks,
NinjaSteph


text:
Q: How to get SCSS variables in js code (nodejs server)? From this blogpost example https://til.hashrocket.com/posts/sxbrscjuqu-share-scss-variables-with-javascript, I tried to get scss variables in my js code and I did not manage to do it.
index.js file
import variables from './variables.scss';
console.log(variables);

variables.scss file
$myvar: 100;

:export {
  myvar: $myvar;
}

webpack.config.js file
module.exports = {
  mode: 'development',
  module: {
    rules: [{
        test: /\.scss$/,
        use: [{
          loader: "style-loader"
        }, {
          loader: 'css-loader'
        }, {
          loader: 'sass-loader'
        }]
    }]
  }
};

dependencies in package.json file
  "dependencies": {
    "css-loader": "^5.0.2",
    "lodash": "^4.17.20",
    "postcss-loader": "^5.0.0",
    "sass": "^1.32.6",
    "sass-loader": "^11.0.1",
    "style-loader": "^2.0.0",
    "webpack": "^5.21.2",
    "webpack-cli": "^4.5.0"
  }

Compilation : npx webpackOutput :

asset main.js 17.2 KiB [compared for emit] (name: main)
runtime modules 937 bytes 4 modules
cacheable modules 9.23 KiB
  modules by path ./src/ 1020 bytes
    ./src/index.js 324 bytes [built] [code generated]
    ./src/variables.scss 371 bytes [built] [code generated]
    ./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js!./src/variables.scss 325 bytes [built] [code generated]
  modules by path ./node_modules/ 8.23 KiB
    ./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js 6.67 KiB [built] [code generated]
    ./node_modules/css-loader/dist/runtime/api.js 1.57 KiB [built] [code generated]
webpack 5.21.2 compiled successfully in 503 ms

In the web console, the object variables is empty and of course, I could not use variables.myvar.
Is there a configuration problem in webpack.config.js ? I tried to simplify it as much as possible. All node_modules are up to date and npm version is 6.14.9.
Thanks for help.

A: I wasn't aware of it but maybe this only works for "css modules". I never tried it without having css-loader configured to be module based. (you can see in my config in this answer that modules are activated)
Please try the following: rename your variables.scss into variables.module.scss
Because by default the css-loader will treat your files as modules or not as modules based on the filename (https://webpack.js.org/loaders/css-loader/#modules).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Having view move remaining view controller's position like Apple's location services notification So here is what I'm trying to do:
I have a navigation controller N that manages a bunch of view controllers. Now depending on a given flag, another view controller B should be shown. The thing is I want B to always sit on top and at the bottom of the navigation controller N.
Any actions that happen in the navigation controller should also be presented in that specific navigation controller and not expand to the area of B.
The layout should basically look like if the navigation controller is only visible
_________
|       |
|       |
|   N   |
|       |
|       |
---------

And this is how it is suppose to look when the flag is set to true
_________
|       |
|       |
|   N   |
|_______|
|   B   |
---------

I'm trying to use View Controller Containment and was able to add B's view to N's hierarchy, but I can't figure out how to resize and reposition N and how to make sure that all new controllers that are loaded from N are contained in N's bounds.
I'm adding B as follows:
let b = BViewController()
presentedViewController?.addChildViewController(BViewController())
presentedViewController?.view.addSubview(b.view)
b.didMove(toParentViewController: presentedViewController!)

Where presentedViewController is defined as
var presentedViewController: UIViewController? {
    var viewController = AppDelegate.instance?.window?.rootViewController
    while(viewController?.presentedViewController != nil) {
        viewController = viewController?.presentedViewController
    }

    return viewController
}

Any pointers how I can achieve this behavior?
Basically the effect I'm trying to achieve is what Apple does with the blue rectangle when an app is currently using location services. The blue rectangle pushes all the other views down.


text:
Q: IF EXIST - Files Without an Extension A working script that moves various files based on file name runs successfully. After the script is done it will check two directories for any lingering files using IF EXIST *.txt. This works great except I've noticed some files with no extension. These were not an issue before and since that cannot be helped due to processes out of my control, I need to amend my script.
My only idea is the following code. Bear with as there are two conditions:
:check1
PUSHD "\\UNC\path1" &&(
DIR /A-D *.
IF %errorlevel% NEQ 0 GOTO check2
) & POPD

:add1
ECHO Add note to the log file

:check2
PUSHD "\\UNC\path2" &&(
DIR /A-D *.
IF %errorlevel% NEQ 0 GOTO laststep
) & POPD

:add2
ECHO Add note to the log file

:laststep
Some other code before exiting

This should run DIR on the path and if files without extensions exist, it will have %errorlevel% zero and move on to the next check. If there are no files present, it will have %errorlevel% not zero (likely 1) and it will append some text to the log before the next check. Check two will do the same.
This seems to be awfully complicated and I am not able to find a "one-liner" solution that is as easy as IF EXIST. I realize I can use *. but that returns directories as well and may result in an incorrect %errorlevel%.
Updated Code
Where I normally set my variables, I also SET the two paths to run DIR against. This way they can be used more easily elsewhere and I bypass the UNC Path error I normally get - reasons for that are unknown to me. The updated file check, used only for files without an extension, is:
DIR %p1% /b /a-d|FIND /v "." && ECHO Found 1 >> %log%
DIR %p2% /b /a-d|FIND /v "." && ECHO Found 2 >> %log%
FINDSTR /I "Found" %log%
IF %errorlevel% EQU 0 GOTO stillthere

:nofiles
Some code
GOTO domore

:stillthere
Some code

:domore
Other code before exit

Thank you for the responses, I've learned from this.

A: Is this what you want to find?
dir /b /a-d |find /v "."

A: @ECHO OFF
SETLOCAL
:check1
PUSHD "u:\path1"
DIR /A-D *. >NUL 2>NUL
IF %errorlevel% EQU 0 ECHO Add note \path1 to the log file
POPD

PUSHD "u:\path2"
DIR /A-D *. >NUL 2>NUL
IF %errorlevel% EQU 0 ECHO Add note \path2 to the log file
POPD

:laststep
:: Some other code before exiting

GOTO :EOF

Your problems include:
Within a block statement (a parenthesised series of statements), the entire block is parsed and then executed. Any %var% within the block will be replaced by that variable's value at the time the block is parsed - before the block is executed - the same thing applies to a FOR ... DO (block).
Hence, IF (something) else (somethingelse) will be executed using the values of %variables% at the time the IF is encountered.
and you are potentially jumping out of a PUSHD/POPD bracket which would mean your POPD won't necessarily restore your starting directory.
(Note that I used u:\ rather than a server to suit my system)

A: You are already using && to verify PUSHD worked. You can do the same with your DIR /-D. I find it makes life easier. Also, you probably want to hide any error message if *. is not found, especially since that is the expected condition. I also hid the display of any files that might be found, but you can certainly get rid of that redirection. You might also want to hide error message if PUSHD fails, but I didn't implement that.
PUSHD "\\UNC\path1" && (
  DIR /A-D *. 1>nul 2>nul && ECHO Add note to the log file
  POPD
)

PUSHD "\\UNC\path2" && (
  DIR /A-D *. 1>nul 2>nul && ECHO Add note to the log file
  POPD
)

ECHO Some other code before exiting


text:
Q: ARM cross compile for x86 error: relocation truncated to fit: R_x86_64_32 against '.rodata", how do I fix this? I'm trying to cross compile a custom OS for x86 hardware on an ARM based system (Debian VM on M1 Mac). To compile I'm using "x86_64-linux-gnu-gcc" and for a linker I'm using "x86_64_linux-gnu-ld".
Note that this does build and compile normally when not on an ARM system. So an x86_64 system will compile and link correctly. I am trying to cross compile this because the ARM version of gcc does not like the x86 assembly boot code that we have (if you think this is the better approach and have tips for handling it this way please let me know).
The error I have comes up when trying to go through the linking process:
Linking for "kernel/kernel.bin"...
main/acpi.o: in function `__rsdp_search_range':
/home/project/kernel/main/acpi.c:63:(.text+0x13b): relocation truncated to fit: R_X86_64_32 against `.rodata'
main/acpi.o: in function `acpi_init':
/home/project/kernel/main/acpi.c:108:(.text+0x290): relocation truncated to fit: R_X86_64_32 against `.rodata'
/home/project/kernel/main/acpi.c:108:(.text+0x295): relocation truncated to fit: R_X86_64_32 against `.rodata'
/home/project/kernel/main/acpi.c:108:(.text+0x29a): relocation truncated to fit: R_X86_64_32 against `.rodata'
/home/project/kernel/main/acpi.c:108:(.text+0x2a4): relocation truncated to fit: R_X86_64_32 against `.rodata'
/home/project/kernel/main/acpi.c:114:(.text+0x327): additional relocation overflows omitted from the output
make[1]: *** [Makefile:34: kernel.bin] Error 1
make[1]: Leaving directory '/home/project/kernel'
make: *** [Makefile:6: all_kernel] Error 2

After trying to search for similar errors, I tried modifying the gcc flags. We already had -mcmodel=large, but i tested with the different variations. I also tested with -fPIC but none of these changes fixed the problem.
gcc flags:
cflags.x86-64   := -march=x86-64 -m64 -mno-red-zone -mcmodel=large -mno-sse3 -mno-ssse3 -mno-sse4.1 -mno-sse4.2 -mno-sse4 -mno-sse4a -mno-3dnow -mno-avx -mno-avx2
cflags.common   := -fno-pie -ffreestanding -fno-builtin -nostdinc -std=c99 -g3 -gdwarf-3 -fno-stack-protector -fsigned-char -Iinclude
cflags.warnings := -Wall -Wredundant-decls -Wundef -Wpointer-arith -Wfloat-equal -Wnested-externs -Wvla -Winline -Wextra -Wno-unused-parameter -Wno-unused-function -Wno-unused-variable -Wno-attributes

linker code:
OUTPUT_FORMAT(elf64-x86-64)

KERNEL_LMA = 0x00100000;
KERNEL_VMA = 0xffff800000000000;

ENTRY(_start)
STARTUP(entry/entry.o)

SECTIONS {
    . = KERNEL_VMA + KERNEL_LMA;

    k_start = .;

    .text : AT(ADDR(.text) - KERNEL_VMA) {
        _code = .;
        *(.multiboot)
        *(.text)
        . = ALIGN(0x1000);
    }

    csd_start = .;
    .csd : AT(ADDR(.csd) - KERNEL_VMA) {
        *(.csd)
        . = ALIGN(0x1000);
    }
    csd_end = .;

    .init :  AT(ADDR(.init) - KERNEL_VMA) {
        kernel_start_init = .;
        *(.init)
        . = ALIGN(0x1000);
        kernel_end_init = .;
    }

    .rodata : AT(ADDR(.rodata) - KERNEL_VMA) {
        _rodata = .;
        *(.rodata)
        . = ALIGN(0x1000);
    }

    .data : AT(ADDR(.data) - KERNEL_VMA) {
        _data = .;
        *(.data)
        . = ALIGN(0x1000);
    }

    _edata = .;

    .bss : AT(ADDR(.bss) - KERNEL_VMA) {
        _bss = .;
        *(.bss)
        *(COMMON)
        . = ALIGN(0x1000);
    }

    _end = .;

    /DISCARD/ : {
        *(.comment)
        *(note.*)
    }
    kernel_phys_off = k_start - KERNEL_LMA;
    kernel_phys_base = k_start - kernel_phys_off;
    kernel_phys_end = _end - kernel_phys_off;
    kernel_page_tables = ((_end - k_start) / 0x80000) + 1; /* XXX might be 0x200000 */
    kernel_text_sectors = ((_end - k_start) / 512) + 1;
}

Edit
Below is the __rsdp_search_range function, I dont necessarily think it is the problem because if I comment out this file, for instance, the error pops up elsewhere.
static rsdp_20_t *__rsdp_search_range(uintptr_t start, uintptr_t end)
{
    uintptr_t rsdp_candidate = start;
    while (rsdp_candidate <= end - sizeof(struct rsdp))
    {
        if (memcmp((void *)rsdp_candidate, rsdp_sig, sizeof(rsdp_sig)) == 0 &&
            __acpi_checksum((uint8_t *)rsdp_candidate, sizeof(rsdp_20_t)) ==
                0)
        {
            return (rsdp_20_t *)rsdp_candidate;
        }
        rsdp_candidate += RSDP_ALIGN;
    }
    return NULL;
}

I did try and remove -fno-pie and got the following error instead: x86_64-linux-gnu-ld: failed to convert GOTPCREL relocation; relink with --no-relax"


text:
Q: create new spring annotation I'm developing an application in Spring which has numerous methods in the controller, and are mapped to various URL using @RequestMapping.
Some of these methods (and hence url) are accessible to some user roles, and not to others. Can I create annotations, and annotate these methods so that only privileged users have access to right methods, while not to the others?
Thanks in advance.

A: I am not sure if creating new annotations is what you really need. You could probably use Spring Security and its annotations. Please take a look here to see if it is what you are looking for.

A: You can use Spring Security and its annotations, restrict access to some methods. This Blog post show some features of annotations used with Spring Security 3.
Have a look at this question and answer, to see how you build your own annotations on top of spring security.
See also the documentation of Spring Security 3.1, Chapter Expression-Based Access Control.


text:
Q: Using a #! comment in ruby running in Ubuntu I am new to programming and am trying to follow an example which uses #! comment in ruby.
I am consistently get the message:
   bash: matz.rb: command not found
I am using this comment:
    #! /usr/bin/env ruby
I have tried it with and without the space after ! as well as with and without the env.
when I use the
    $ which ruby
ruby is in: /usr/bin/ruby
I have also gone into the operating system and changed the permissions on the file matz.rb to rwx for all users w/ no effect.  Am I doing something wrong or do I have my system set up incorrectly?

A: If you're in the same directory as the matz.rb file, be sure to run it as
$ ./matz.rb

and not just
$ matz.rb

Here's a shell session demonstrating this working:
$ ls -la m*
-rwxr-xr-x  1 gareth  gareth  32  8 Jan 08:46 matz.rb
$ cat matz.rb
#!/usr/bin/env ruby
puts "Matz"
$ matz.rb
-bash: matz.rb: command not found
$ ./matz.rb
Matz

A: Your file wasn't created on Windows was it? If it has \r\n line endings, that will upset bash. You can open it with Vim and check:
vi matz.rb
:set ff=unix
:wq

If when you tab-complete the "ff=" part it says dos, then it has the wrong file format. Alternatively, run dos2unix and try to run the file again:
apt-get install sysutils
dos2unix matz.rb

A: It sounds like you're on a Unix/Linux system and just typing matz.rb on the command line. If you're trying to execute a command in the current directory, you need to call it like ./matz.rb. The "./" tells it to look in the current directory rather than just /usr/bin and friends.

A: The /usr/bin/env part is fine. You need to give bash the path to matz.rb when you run it. If you're in the directory with matz.rb, type "./matz.rb". The directory "." means the current directory  - bash doesn't look there by default when running programs (like Windows does).
The env program (/usr/bin/env) searches the executable search path - the PATH environment variable - for the ruby program as if you typed it at the command prompt, and runs that program. The shebang comment doesn't do this. If you want to give your script to other people who might not have ruby installed in the same place as you, then you should use the "#!/usr/bin/env ruby" comment so that it will work as long as they can run ruby by typing "ruby".

A: I failed to see any answer indicating you to change the executable mode of the file, so you might wanna try and do
chmod +x matz.rb

before you go and try doing
./matz.rb

Also it might be better not to attach a .rb extension to the file, such is the case for normal ruby / rails scripts e.g. script/generate, script/console etc.

A: You can use the 'shebang' line with either:
#!/usr/bin/ruby
#!/usr/bin/env ruby

But the script needs to be executable (you indicated it is) and in your shell $PATH.
echo $PATH

Put the script in one of those directories, or modify your path, otherwise specify the full path to it, for example:
export PATH=$PATH:/home/user/bin

or one of these:
./matz.rb
/home/user/bin/matz.rb

You can also run the Ruby interpreter passing the script filename as an argument, and it will be executed. This is particularly useful if you have another version of Ruby installed on your system (say, for testing, like Ruby Enterprise Edition, REE):
/usr/bin/ruby matz.rb
/opt/ree/bin/ruby matz.rb

A: Have you tried the ShaBang as following to directly point to ruby?
#! /usr/bin/ruby

Then you call the script from the commandline as
./matz.rb

Under Unix/Linux systems the dot in front of a command to search for the command in the current directory. If you give a path like /usr/bin/ruby, it will search in the current directory for a directory called usr...
A command without a dot/ in front is searched in locations specified by the path variable of the environment.
A command with a / on the beginning is searched exactly from root following the specified path.
Inside your ShaBang, you want to specify the exact path to the interpreter so "/usr/bin/ruby" is the correct one. On the commandline, where you want your script to be executed, you need to call the script with "./matz.rb" otherwise the bash will search a command like /usr/bin/matz.rb what leads to your errormessage.


text:
Q: Mongo Asynchronous Call I have this Ajax route:
router.get('/getThey', middleware.isLoggedIn, function(req, res){
var array = [];
var followingLength = req.user.they.length -1;

req.user.they.forEach(function(userId, i){
  User.findById(userId, function(err, foundUser){
    foundUser.theySent.forEach(function(theySent, i){
      var foundLength = foundUser.theySent.length -1;

      while(i !== foundLength){
        if(req.user.notifications.indexOf(theySent) === -1){
          req.user.notifications.push(theySent);
          req.user.save();
        }
      }
    });
  });
 });

 res.json(req.user.notifications);
 });

But the code below runs first because the User findById
if(aux === true && i === followingLength){
  res.json(req.user.notifications);
}

What can I do to make findById Synchronous ?

A: findById is specifically designed to take a callback or promise. Since it is making an async call, it will not be sync so you would have to restructure code accordingly.


text:
Q: How to draw a point in 3d coordinates on C# WinForms? I want to have points drawn in runtime in a WinForms application. How do I do that?

A: The simple answer
You need to implement some kind of projective transformation to convert  each Vector3 from (X,Y,Z) coordinates to PointF with (X,Y) coordinates.
On each Paint event, move the origin to the center of the drawing surface and project the 3D points with some math as follows
g.TranslateTransform(ClientSize.Width/2, ClientSize.Height/2);
pixel.X = scale * vector.X / (camera.Z -vector.Z);
pixel.Y = -scale * vector.Y / (camera.Z -vector.Z);
g.DrawEllipse(Pens.Black, pixel.X-2, pixel.Y-2, 4,4);

Where g is the Graphics object passed from the Paint event. The reason for the negative for the Y coordinate is because in WinForms positive Y is downwards, and for 3D graphics it makes sense to objey the right hand rules and have Y pointing upwards. The DrawEllipse method draws a little circle where the point is. Use FillEllipse to fill in the circle instead if you want.

The detailed answer
I have a sample project on GitHub on simple rendering of 3D geometry in Winforms.

There are other parts to the sample you can ignore, but I will explain the process I came up to render simple 3D objects on a WinForms control.

*

*PictureBox is where the target control for the rendering. This is the only requirement for the form. To have Control placed for things to show on. PictureBox is convenient, and it supports double buffering on the get-go.

*Camera is a class that does the rendering. It is responsible for the following tasks.

*

*Reference to the target control and handling the Paint event.

*Handling the math for projecting 3D points into pixels.

*Checks if an object is visible (backface culling).

*Configure the Graphics object before rendering on screen.

*Handling any mouse events if needed.

*Define the 3D viewpoint properties.

A simplified version of my Camera class is below. The things to look into is the Project() methods that take up geometry Vector3 objects and return PointF objects.
using static SingleConstants;

public delegate void CameraPaintHandler(Camera camera, Graphics g);

public class Camera
{
    public event CameraPaintHandler Paint;

    /// <summary>
    /// Initializes a new instance of the <see cref="Camera" /> class.
    /// </summary>
    /// <param name="control">The target control to draw scene.</param>
    /// <param name="fov">
    /// The FOV angle (make zero for orthographic projection).
    /// </param>
    /// <param name="sceneSize">Size of the scene across/</param>
    public Camera(string name, Control control, float fov, float sceneSize = 1f)
    {
        Name = name;
        OnControl = control;
        FOV = fov;
        SceneSize = sceneSize;
        LightPos = new Vector3(0 * sceneSize, 0 * sceneSize / 2, -sceneSize);
        Orientation = Quaternion.Identity;
        Target = Vector3.Zero;
        control.Paint += (s, ev) =>
        {
            Paint?.Invoke(this, ev.Graphics);
        };
    }

    public GraphicsState SetupView(Graphics g, SmoothingMode smoothing = SmoothingMode.AntiAlias)
    {
        var gs = g.Save();
        g.SmoothingMode = smoothing;
        var center = ViewCenter;
        g.TranslateTransform(center.X, center.Y);
        return gs;
    }
    public Point ViewCenter => new Point(
        OnControl.Margin.Left + OnControl.ClientSize.Width/2,
        OnControl.Margin.Top + OnControl.ClientSize.Height/2);
    public string Name { get; set; }
    public Control OnControl { get; }
    public float SceneSize { get; set; }
    public float FOV { get; set; }
    public Quaternion Orientation { get; set; }
    public Vector3 LightPos { get; set; }
    public Vector3 Target { get; set; }
    public int ViewSize
    {
        get => Math.Min(
        OnControl.ClientSize.Width - OnControl.Margin.Left - OnControl.Margin.Right,
        OnControl.ClientSize.Height - OnControl.Margin.Top - OnControl.Margin.Bottom);
    }
    public int ViewHalfSize => ViewSize/2;
    public float Scale => ViewHalfSize/SceneSize;
    public float DrawSize
    {
        get => 2 * (float)Math.Tan(FOV / 2 * Math.PI / 180);
        set
        {
            FOV = 360/pi*Atan(value/2);
        }
    }
    /// <summary>
    /// Get the pixels per model unit scale.
    /// </summary>
    public Vector3 EyePos { get => Target + Vector3.Transform(Vector3.UnitZ * SceneSize / DrawSize, Quaternion.Inverse(Orientation)); }
    public float EyeDistance
    {
        get => SceneSize/DrawSize;
        set
        {
            DrawSize = SceneSize/value;
        }
    }
    public Vector3 RightDir { get => Vector3.TransformNormal(Vector3.UnitX, Matrix4x4.CreateFromQuaternion(Quaternion.Inverse(Orientation))); }
    public Vector3 UpDir { get => Vector3.TransformNormal(Vector3.UnitY, Matrix4x4.CreateFromQuaternion(Quaternion.Inverse(Orientation))); }
    public Vector3 EyeDir { get => Vector3.TransformNormal(Vector3.UnitZ, Matrix4x4.CreateFromQuaternion(Quaternion.Inverse(Orientation))); }

    public PointF Project(Vector3 node)
    {
        float r = 2 * (float)Math.Tan(FOV / 2 * Math.PI / 180);
        int sz = ViewHalfSize;
        float f = sz/r;
        float camDist = SceneSize / r;
        var R = Matrix4x4.CreateFromQuaternion(Orientation);
        return Project(node, f, camDist, R);
    }

    protected PointF Project(Vector3 node, float f, float camDist, Matrix4x4 R)
    {
        var point = Vector3.Transform(node-Target, R);
        return new PointF(
            +f  * point.X / (camDist - point.Z),
            -f  * point.Y / (camDist - point.Z));
    }

    public RectangleF Project(Bounds bounds)
    {
        var nodes = bounds.GetNodes();
        var points = Project(nodes);
        if (points.Length>0) {

            RectangleF box = new RectangleF(points[0], SizeF.Empty);
            for (int i = 1; i < points.Length; i++)
            {
                box.X = Math.Min(box.X, points[i].X);
                box.Y = Math.Min(box.Y, points[i].Y);
                box.Width = Math.Max(box.Width, points[i].X-box.X);
                box.Height = Math.Max(box.Height, points[i].Y-box.Y);
            }
            return box;
        }
        return RectangleF.Empty;
    }

    public PointF[] Project(Triangle triangle) => Project(new[] { triangle.A, triangle.B, triangle.C });
    public PointF[] Project(Polygon polygon) => Project(polygon.Nodes);
    /// <summary>
    /// Projects the specified nodes into a 2D canvas by applied the camera
    /// orientation and projection.
    /// </summary>
    /// <param name="nodes">The nodes to project.</param>
    /// <returns>A list of Gdi points</returns>
    public PointF[] Project(Vector3[] nodes)
    {
        float r = 2 * (float)Math.Tan(FOV / 2 * Math.PI / 180);
        float camDist = SceneSize / r;
        float f = ViewHalfSize/r;
        var R = Matrix4x4.CreateFromQuaternion(Orientation);

        var points = new PointF[nodes.Length];
        for (int i = 0; i < points.Length; i++)
        {
            points[i] = Project(nodes[i], f, camDist, R);
        }

        return points;
    }
    /// <summary>
    /// Uses the arc-ball calculation to find the 3D point corresponding to a
    /// particular pixel on the screen
    /// </summary>
    /// <param name="pixel">The pixel with origin on center of control.</param>
    /// <param name="arcBallFactor"></param>
    public Vector3 UnProject(Point pixel, float arcBallFactor = 1)
    {
        Ray ray = CastRayThroughPixel(pixel);
        Sphere arcBall = new Sphere(Target, arcBallFactor * SceneSize/2);
        var Rt = Matrix4x4.CreateFromQuaternion(Quaternion.Inverse(Orientation));
        bool hit = arcBall.Hit(ray, out var t);
        return Vector3.Transform(ray.GetPointAlong(t), Rt);
    }

    public bool IsVisible(Polygon polygon)
        => polygon.Nodes.Length <3 || IsVisible(polygon.Nodes[0]-Target, polygon.Normal);
    /// <summary>
    /// Determines whether a face is visible.
    /// </summary>
    /// <param name="position">Any position on the face.</param>
    /// <param name="normal">The face normal.</param>
    public bool IsVisible(Vector3 position, Vector3 normal)
    {
        float λ = Vector3.Dot(normal, position - EyePos);

        return λ < 0;
    }

}

*Scene and VisibleObject. The base class for objects to be drawn is called VisibleObject. Everything you see in the screenshot above derives from a VisibleObject. This includes solids, curves and the triad of coordinates. A Scene is just a collection of VisibleObject to be drawn, and it handles the Paint event issued by the Camera. Finally it iterates through the objects and issues the command to be rendered.
public class Scene
{
    readonly List<VisibleObject> drawable;

    public Scene()
    {
        drawable = new List<VisibleObject>();
        Triad = new VisibleTriad("W");
    }
    [Category("Model")]
    public VisibleObject[] Drawable => drawable.ToArray();
    public T AddDrawing<T>(T drawing) where T : VisibleObject
    {
        drawable.Add(drawing);
        return drawing;
    }
    [Category("Model")]
    public VisibleTriad Triad { get; }
    public void Render(Graphics g, Camera camera)
    {
        var state = camera.SetupView(g);

        Triad.Render(g, camera, Pose.Identity);

        foreach (var item in drawable)
        {
            item.Render(g, camera, Pose.Identity);
        }
        Gdi.Style.Clear();
        g.Restore(state);

    }

}

and the base VisibleObject class
public abstract class VisibleObject
{
    public abstract void Render(Graphics g, Camera camera, Pose pose);
}

One point to understand is that the location of each VisibleObject is not contained within.  This is done so multiple copies of the same object can be drawn at various locations on the screen.

*Pose The 3D position and orientation of each object is defined with the Pose class, which contains a Vector3 origin, and a Quaternion orientation.
The main functionality is in the FromLocal() and ToLoca() methods that do the local to world or reverse transformations.
public readonly struct Pose
    : IEquatable<Pose>
{
    readonly (Vector3 position, Quaternion orientation) data;
    public Pose(Quaternion orientation) : this(Vector3.Zero, orientation) { }
    public Pose(Vector3 position) : this(position, Quaternion.Identity) { }
    public Pose(Vector3 position, Quaternion orientation) : this()
    {
        data = (position, orientation);
    }
    public static readonly Pose Identity = new Pose(Vector3.Zero, Quaternion.Identity);
    public static implicit operator Pose(Vector3 posiiton) => new Pose(posiiton);
    public static implicit operator Pose(Quaternion rotation) => new Pose(rotation);
    public Vector3 Position { get => data.position; }
    public Quaternion Orientation { get => data.orientation; }

    public Vector3 FromLocal(Vector3 position)
        => Position +  Vector3.Transform(position, Orientation);
    public Vector3[] FromLocal(Vector3[] positions)
    {
        var R = Matrix4x4.CreateFromQuaternion(Orientation);
        Vector3[] result = new Vector3[positions.Length];
        for (int i = 0; i < result.Length; i++)
        {
            result[i] = Position + Vector3.Transform(positions[i], R);
        }
        return result;
    }
    public Vector3 FromLocalDirection(Vector3 direction)
        => Vector3.Transform(direction, Orientation);
    public Vector3[] FromLocalDirection(Vector3[] directions)
    {
        var R = Matrix4x4.CreateFromQuaternion(Orientation);
        Vector3[] result = new Vector3[directions.Length];
        for (int i = 0; i < result.Length; i++)
        {
            result[i] = Vector3.TransformNormal(directions[i], R);
        }
        return result;
    }
    public Quaternion FromLocal(Quaternion orientation)
        => Quaternion.Multiply(Orientation, orientation);
    public Pose FromLocal(Pose local)
        => new Pose(FromLocal(local.Position), FromLocal(local.Orientation));
    public Vector3 ToLocal(Vector3 position)
        => Vector3.Transform(position-Position, Quaternion.Inverse(Orientation));
    public Vector3[] ToLocal(Vector3[] positions)
    {
        var R = Matrix4x4.CreateFromQuaternion(Quaternion.Inverse(Orientation));
        Vector3[] result = new Vector3[positions.Length];
        for (int i = 0; i < result.Length; i++)
        {
            result[i] = Vector3.Transform(positions[i]-Position, R);
        }
        return result;
    }
    public Vector3 ToLocalDirection(Vector3 direction)
        => Vector3.Transform(direction, Quaternion.Inverse(Orientation));
    public Vector3[] ToLocalDirection(Vector3[] directions)
    {
        var R = Matrix4x4.CreateFromQuaternion(Quaternion.Inverse(Orientation));
        Vector3[] result = new Vector3[directions.Length];
        for (int i = 0; i < result.Length; i++)
        {
            result[i] = Vector3.TransformNormal(directions[i], R);
        }
        return result;
    }
    public Quaternion ToLocal(Quaternion orientation)
        => Quaternion.Multiply(orientation, Quaternion.Inverse(Orientation));
    public Pose ToLocal(Pose pose)
        => new Pose(ToLocal(pose.Position), ToLocal(pose.Orientation));

    #region Algebra
    public static Pose Add(Pose A, Pose B)
    {
        return new Pose(A.data.position+B.data.position, A.data.orientation+B.data.orientation);
    }
    public static Pose Subtract(Pose A, Pose B)
    {
        return new Pose(A.data.position+B.data.position, A.data.orientation-B.data.orientation);
    }

    public static Pose Scale(float factor, Pose A)
    {
        return new Pose(factor*A.data.position, Quaternion.Multiply(A.data.orientation, factor));
    }
    #endregion

    #region Operators
    public static Pose operator +(Pose a, Pose b) => Add(a, b);
    public static Pose operator -(Pose a) => Scale(-1, a);
    public static Pose operator -(Pose a, Pose b) => Subtract(a, b);
    public static Pose operator *(float a, Pose b) => Scale(a, b);
    public static Pose operator *(Pose a, float b) => Scale(b, a);
    public static Pose operator /(Pose a, float b) => Scale(1 / b, a);
    #endregion
}

*Gdi is a graphics library to handle specific sub-tasks such as drawing points on the screen, drawing labels, drawing curves, and various shapes but with a specific style and handing color operations. In addition, it keeps a current Pen and SolidFill object for re-use defining the stroke and fill colors to be used in the low-level Gdi drawing operations. Some details are removed from below:
public static class Gdi
{
    /// <summary>
    /// Converts RGB to HSL
    /// </summary>
    /// <remarks>Takes advantage of whats already built in to .NET by using the Color.GetHue, Color.GetSaturation and Color.GetBrightness methods</remarks>
    /// <param name="color">A Color to convert</param>
    /// <returns>An HSL tuple</returns>
    public static (float H, float S, float L) GetHsl(this Color color)
    {
        var H = color.GetHue() / 360f;
        var L = color.GetBrightness();
        var S = color.GetSaturation();

        return (H, S, L);
    }
    /// <summary>
    /// Converts a color from HSL to RGB
    /// </summary>
    /// <remarks>Adapted from the algorithm in Foley and Van-Dam</remarks>
    /// <param name="hsl">The HSL tuple</param>
    /// <returns>A Color structure containing the equivalent RGB values</returns>
    public static Color GetColor(this (float H, float S, float L);
    public static Style Style { get; } = new Style();

    public static void DrawPoint(this Graphics g, Color color, PointF point, float size = 4f)
    {
        Style.Clear();
        Style.Fill.Color = color;
        g.FillEllipse(Style.Fill, point.X - size/2, point.Y - size/2, size, size);
    }
    public static void DrawLine(this Graphics g, Color color, PointF start, PointF end, float width = 1f)
    {
        Style.Stroke.Color = color;
        Style.Stroke.Width = width;
        g.DrawLine(Style.Stroke, start, end);
    }
    public static void DrawArrow(this Graphics g, Color color, PointF start, PointF end, float width = 1f);
    public static void DrawLabel(this Graphics g, Color color, PointF point, string text, ContentAlignment alignment, int offset = 2);
    public static void DrawPath(this Graphics g, GraphicsPath path, Color color, bool fill = true);

    public static void DrawCircle(this Graphics g, PointF center, float radius, Color color, bool fill = true);
    public static void DrawEllipse(this Graphics g, PointF center, float majorAxis, float minorAxis, float angle, Color color, bool fill = true);
    public static void DrawCurve(this Graphics g, PointF[] points, Color color, bool fill = true);
    public static void DrawClosedCurve(this Graphics g, PointF[] points, Color color, bool fill = true);
    public static void DrawPolygon(this Graphics g, PointF[] points, Color color, bool fill = true);
}

For example to draw a 3D point on the screen at location (100,30) with color Red you would issue code like this from a paint handler with access to a Graphics g object
PointF point = new PointF(100,30);
// Calls extension method `Gdi.DrawPoint()`
g.DrawPoint(Color.Red, point, 4f);

Using the above framework to draw a single point defined by a Vector3 from System.Numerics on the screen you will need the following VisibleObject derived class. The magic happens in the Render() method which uses the supplied Camera to project the 3D point into a pixel location. In addition, it defines a text label to draw next to the point.
    public class VisiblePoint : VisibleObject
    {
        public VisiblePoint(string label, Color color, float size = 4f)
        {
            Label = label;
            Color=color;
            Size=size;
        }

        public Color Color { get; }
        public float Size { get; }
        public string Label { get; }

        public override void Render(Graphics g, Camera camera, Pose pose)
        {
            var pixel = camera.Project(pose.Position);
            g.DrawPoint(Color, pixel, Size);
            if (!string.IsNullOrEmpty(Label))
            {
                g.DrawLabel(Color, pixel, Label, ContentAlignment.BottomRight);
            }
        }
    }


text:
Q: Sort FlexTable Inquiry i use Flex Table to display the data .
now i need ti support that when the user click on the table header the table be sorted according to the column selected .
but i need the sorting not to be slow.
is flex table can support this property ....if yes how can i do it .... if not is there is another way to do it ..? and how can i do it ?
best regards,
Ahmed Shoeib

A: FlexTable is not the good widget to display data, since the 2.1 version you should consider using CellTable
Moreove, since the version 2.2, the CellTable widget supports columns sorting. See the documentation


text:
Q: could I ignore the memory leak information related to " __wcslen_sse2" in valgrind memcheck report I am now using valgrind and memcheck to detect the potential memory leak in my program, and in the report I found the following information:
Invalid read of size 8
     at Ox4310557: __wcslen_sse2 (wcslen-sse2.S:85)
      by myclass:perform_functionality( **.cpp:59)
      by 0x8074656: main (main.cpp:83)
   Address 0x4a46530 is 8 bytes after a block of size 176 alloc'd
      at 0x402B9B4: operator new(unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
     by 0x420B386: std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t>   >::_Rep::_S_create(unsigned int, unsigned int, std::allocator<wchar_t> const&) (in /usr/lib/i386-linux-gnu/libstdc++.so.6.0.16)
     by 0x420C68F: std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >::_Rep::_M_clone(std::allocator<wchar_t> const&, unsigned int) (in /usr/lib/i386-linux-gnu/libstdc++.so.6.0.16)
     by 0x420C7BD: std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t>>::reserve(unsigned int) (in /usr/lib/i386-linux-gnu/libstdc++.so.6.0.16)
  by 0xE29AFF: ???

and
Conditional jump or move depends on uninitialised values(s)
  at 0x4310578:  __wcslen_sse2 (wcslen-sse.s:95)

It is very difficult, however, to figure out where the leak is. It seems the message is related to std::string, but I am not sure.The memory usage summary is as follows:
HEAP SUMMARY:
==2302==     in use at exit: 0 bytes in 0 blocks
==2302==   total heap usage: 87,293 allocs, 87,293 frees, 427,491,963 bytes allocated

So my question is: should I ignore the message related to  __wcslen_sse2? Thanks.
EDIT:
  I found all the message will disappear if I remove the following codes in the function:
std::cout<<"Writing....."<<std::endl;
std::wcout<<imageFileName.c_str()<<std::endl;

This confirms my guess that this kind of message comes from std::wstring. So why calling .c_str() will intriguer these messages? By the way, imageFileName is of class member variable, which is set before using this class.


text:
Q: Replace multiple occurrences of multiple sub-strings in string in jquery I have a small program that is checking for character sequence in a string against array elements, if a sequence is found in the array terms[] than do something. However this only works for the first instance match in the array for me using the below mechanism. How could I make this happen for multiple occurrences?
Example: terms = ['hello', 'world', 'this', 'is', 'me']
string given to program is: hello here is me
the program is asked to replace words that are found in a string that match any of the words in the array with the words red and green respectively, however the program stops at the first occurrence found, that is the result from the currently programmed system is:
'red here is me'

Instead of
'red here green me'

How can I alter the below functionality to give me the 2nd result?
for (var i = 0; i < terms.length && !match; i++) {
    if (string.indexOf(terms[i]) > -1) {
        match = true;
        var newString = '';
        wrapper.css("background", "#a1e4ff");
        var matchString = string.substring(string.indexOf(terms[i]), (string.indexOf(terms[i]) + terms[i].length));

I dont think you understood me, i dont care about css, I care about substring replacement.
Here is my current code
function check(string) {
    var terms = ['one', 'two'];
    var match = false;

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

        if(string.indexOf(terms[i]) > -1) {
            match = true;
            var newString='';
            var matchString = string.substring(string.indexOf(terms[i]), (string.indexOf(terms[i])+terms[i].length));

            switch(matchString) {
                case 'one':
                newString = string.replace(matchString, "three");
                break;
              case 'two':
                newString = string.replace(matchString, "four");
              default:
                alert('no matches');
            }

            $("ul").append("
" + newString + "
");
        }
      }
    }

check('this is a one example string of two');
Currently my program results in this:
    this is a three example string of two
I want to fix my program to result in this:
     this is a three example string of four

A: Use a String#replace with the replacement function, and alternate between the colors:

function replaceWithColor(str, terms) {
  var termsDict = terms.reduce(function(d, t) {
    d[t] = true;
    return d;
  }, Object.create(null));

  var colors = ['red', 'green'];

  var i = 0;

  return str.replace(/\w+/g, function(t) {
    return termsDict[t] ? colors[i++ % 2] : t;
  });
}

var terms = ['hello', 'world', 'is', 'me'];

var str = "hello here this is me";

var result = replaceWithColor(str, terms)

console.log(result);

And an ES6 version that uses Set and arrow functions:

const replaceWithColor = (str, terms) => {
  const termsSet = new Set(terms);

  const colors = ['red', 'green'];

  let i = 0;

  return str.replace(/\w+/g, (t) => termsSet.has(t) ? colors[i++ % 2] : t);
}

var terms = ['hello', 'world', 'is', 'me'];

var str = "hello here this is me";

var result = replaceWithColor(str, terms)

console.log(result);

A:

var terms = ['hello', 'world', 'this', 'is', 'me'];

function check(str) {
  var
   s = str.split(' ');
   out = [],
   redgreen = ['red','green'],
   rgcount = 0;

  s.forEach(function (k, i) {
    if (terms.indexOf(k) >= 0) {
      var color = redgreen[rgcount];
      out.push(''+color+'');
      rgcount = (rgcount + 1) % 2;
    } else out.push(k);
  });
  document.write(out.join(' ')+'
');
}

check('hello here is me');
check('one two there is three four pink yelow there is this what yet there');
check(terms.join(' '));
.red {
  color: red
}
.green {
  color: green;
}


text:
Q: how to make iostat behave like top iostat -xzN 5 | grep "^vg\|^Dev" produces output like:
Device:         rrqm/s   wrqm/s     r/s     w/s   rsec/s   wsec/s avgrq-sz avgqu-sz   await  svctm  %util
vg01-root         0.00     0.00    0.00    0.20     0.00     1.60     8.00     0.00    3.00   3.00   0.06
vg05-vz           0.00     0.00    0.00    0.60     0.00     4.80     8.00     0.01    9.00   9.00   0.54
vg03-vz           0.00     0.00  281.00  128.40  5625.60  1027.20    16.25    42.35  103.54   2.44  99.94
vg02-vz2a         0.00     0.00   28.20   11.40  1416.00   112.00    38.59     0.79   19.84   5.99  23.72
Device:         rrqm/s   wrqm/s     r/s     w/s   rsec/s   wsec/s avgrq-sz avgqu-sz   await  svctm  %util
vg05-vz           0.00     0.00    0.00    8.60     0.00  7876.80   915.91     0.48   55.70   3.40   2.92
vg03-vz           0.00     0.00  308.20   76.20 10376.00  4433.60    38.53    11.50   30.00   2.60 100.00
vg02-vz2a         0.00     0.00   27.80   24.80   604.80   198.40    15.27     0.49    9.39   4.89  25.72
Device:         rrqm/s   wrqm/s     r/s     w/s   rsec/s   wsec/s avgrq-sz avgqu-sz   await  svctm  %util
vg05-vz           0.00     0.00    0.00    1.80     0.00   585.60   325.33     0.01    5.78   4.00   0.72
vg03-vz           0.00     0.00  323.20   49.00  9283.20   497.60    26.28     3.48    9.40   2.69  99.98
vg02-vz2a         0.00     0.00   40.20   55.80  2644.80   483.20    32.58     1.14   11.86   4.12  39.58

I'd like this to display like top i.e. clear screen and start from the top on each iteration.  I'm thinking if there was a way to pipe this through sed/awk/perl/whatever and every time you get ^Dev push a tput clear.
But how?

A: Have you considered iotop instead?
That said, it shouldn't be too hard to hurl some rough Perl.
#!/usr/bin/perl

# Adjust options to taste.
open(IOSTAT, "iostat -d 5 |") || die;

$| = 1;
while(<IOSTAT>) {
    if (/^Dev/) { system "clear"; print; }
    if (/^vg/) { print; }
}

A: Following up on Jeffrey Hantin's response, here's a one-liner version:
S_COLORS=always iostat -hz 5 | perl -pe '/avg/ && system(q[clear])'

A: Just let watch do the work for you:
watch -n<interval> iostat`


text:
Q: How to create this file "/var/run/postgresql/.s.PGSQL.5432"? By mistake, I deleted the .s.PGSQL.5432 file in folder /var/run/postgresql
because of that , I cant able to add server in pgAdmin , Instead i am getting error like below
An error has occurred:

Error connecting to the server: could not connect to server:
No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

please, someone help me to resolve this problem

A: A simple fix would be to restart the PostgreSQL daemon.  It should recreate the socket file on startup.
Reloading the configuration file might also cause the socket file to be recreated.  You can do this from a shell:
pg_ctl reload

Or from an existing PostgreSQL connection that has superuser privileges:
SELECT pg_reload_conf();


text:
Q: Justify inequality involving real numbers Let $a, b, d\in\mathbb{R}^*_+, p\in\mathbb{R}, N\in\mathbb{N}$ with $N\ge 2$ and $p>1, s\in (0, 1), ps<N$.
Suppose that $a\le d^{Np/(N-ps)}$ and $a+b=d$. I am trying to justify the inequality
$$S(a+b)^{(N-ps)/N}\le a,$$
where $S\le\frac{a}{d^{(N-ps)/N}}.$
Could someone please help me with that?
I tried so far by using triangle inequality, multiplying by something, but I haven't been successful.
Any hint will be appreciated.
Thank you in advance!

A: \begin{align}
S(a+b)^{(N-ps)/N}&\le\frac{a}{d^{(N-ps)/N}}\times(a+b)^{(N-ps)/N}&&\left(\because S\le\frac{a}{d^{(N-ps)/N}}\text{ given}\right)\\
&=a&&\left(\because a+b=d\right)
\end{align}


text:
Q: Using python to fill fields on a website, perform some actions on the returned results? A little background - I'm a student, broke and I'd like to travel on the cheapest trains to some nice destinations. Hence this idea was born.
I am comfortable with Python, I have worked with it for its data analysis and machine learning libraries.
Now, I want to be able to use a train ticket booking website to fill the Departure, Arrival, Date, Time, Number of Passengers fields for all destinations offered and find the cheapest train to take. I want to be able to do some actions of the results returned like, for example, choosing the 2nd earliest train while leaving or the 2nd last train while departing. I don't want to automate the booking part, I will do that part myself.
In a nutshell, I just want to automate the part where I input multiple destinations and waste 2 hours of my day trying to find cheap trains.
I have no idea where to start and I looked into some blogs, most of them offered solutions with JavaScript and I have zero knowledge of it. Can I not achieve the above goal with just Python? What libraries will I need for this?


text:
Q: Configure Client Side SSL in Javascript Is it possible to configure a self signed certificate inside of a Javascript app on the client side to verify a remote API?
My issue: I'm building an Office-JS App in Excel and it can only get/post etc to https URLs. My company SSL Cert is giving me errors during startup about "Revocation information unavailable". This doesn't happen in browsers though, only when using the Add-In. Rather then try to make changes company wide SSL, I'd like to configure the WebServer that hosts my JS Files for the Add-In w/ a self signed SSL certificate and have it act as an API proxy. All my requests from Office-JS would be to the same https domain the files are hosted in which would then reach out to other APIs over whatever method but not be constrained by Office-JS policies.
I've been able to generate SSL certs and import them to trusted store and then get via Axios, but I don't want to have to install the cert on each client, I'd like it to be stored inside the JS code that they load (I guess this initial load would have to be over http, then the requests would be https w/ the loaded certs?).
I've read a lot about using https agent in NodeJS but I think that is all server side stuff, I don't really use/understand NodeJS in the server sense, I just use it for NPM, but I use ISS in Visual Studio for Dev and prod I'll probably try and use NGinx as my Webserver on a linux host.
Is this even possible or am I just running myself in circles? Do I need to have the SSL installed into Cert Store on clients?


text:
Q: OpenShift / Docker thin provisioning I've been looking at OpenShift Origin documentation and tutorials for the past two days and I have a few questions if you guys can help me;
For Docker's thin provisioning configuration for production environments using direct-lvm the most common approach (not to say all I encountered) is to use a separate physical drive setup with LVM for the volume group. Is there a problem with using one partitioned hard drive shared between the root system? This comes as some of the machines we use (which are rented) come with large hard drives on the initial configuration, and it's easier to partition one big drive and mirror it than doing this with several, no? Are there disadvantages?
Two machines have been configured with initial disk setup, one has boot + root and swap, where root and swap sit on LVM on a volume group /dev/sda2 and /dev/sda3 is the docker volume group, and the other has boot, root and swap as separate devices and only the remaining space is a volume group. Are both approaches correct or are there considerations to have in mind regarding these setups?

A: Besides the disadvantage that your docker data will share a drive with your operating system there won't be any disadvantages when you partition the drive as you suggested.
Both of your approaches are correct. I'd prefer the variant with two volume groups because it gives you more flexiblility for your OS than plain partitions, but that decision is totally up to you.


text:
Q: xcode 7.3 can not find glances in my watch I updated my Xcode to 7.3, and when I opened my watch apps, I found that my glances can not be show in apple watch, I opened My Watch on my iphone simulator and can not find "show glances" option anymore。。。I created an empty watch project(with glances) and still can not find 'glances' in My Watch
Anybody got idea? Thanks!
Create a new watch project with glances
Can not find glances


text:
Q: Pulling mysql data into a multidimensional array I've checked all kinds of previously answered similar questions and nothing's working.  I have a "Inbox" type application where a person of emailaddress@xyz.com might have 5 messages waiting for them.  They log in and get a screen of those five messages, the sender email, the date sent, and the first 15 chars of the message.
In mysql, I have:  id, emailaddress, senderemail, datesent, fullmessage.
I'm using SELECT * FROM db WHERE emailaddress='emailaddress@xyz.com' to pull out, let's say, 5 new messages. $result equals the mysql query.  mysql_num_rows does a great job of telling me there are 5 rows.  It works fine up to that point.
My problem is that I can't (despite hours of trying) find the right syntax for making this into a multidimensional array so that I can iterate table rows in a for loop and print it all out.  I'm envisioning:

for ($a = 0; $a < $numrows; $a++) {

     the php code would go here and would print the associated sender, date, and message in  cells.

}

Any help would be fantastic.
I'm sure this is not hard but have just not gotten anywhere for most of the afternoon.  Can anyone out there tell me what a simple syntax for doing this would be?

A: Information that comes from the database is in an array when you use mysql_fetch_array() or mysql_fetch_assoc(). So, you can do something like:

<?php
$storage_array = array();
$result = mysql_query("SELECT * FROM db WHERE emailaddress='emailaddress@xyz.com'" or die(mysql_error());

while($data = mysql_fetch_assoc($result))
{
?>

  <?php echo $data['sender'] ?>
  <?php echo $data['date'] ?>
  <?php echo $data['message '] ?>

<?php
  $storage_array[] = $data;
}
?>

You will obviously need to join some tables for messages if they are on different tabels or use LIMIT to only get 5 rows. You will also need to determine your ORDER BY.
You will need to know which loop added your data to $storage_array and remember it starts with $storage_array[0].


text:
Q: jQuery $.fn not working with no errors I've seen this question asked before and googled but to no avail. I'm trying to learn how to create my own function in jQuery but it doesn't do what I'm asking and I'm not receiving any errors. Have I done something wrong here?
Here's the script

For good measure, here's the HTML

Cuisine Types (3/10)

American

Italian

Chinese

Thanks!

A: Not sure with the problem though. but I observed:

*

*

Cuisine Types (3/10)

American

Italian

Chinese

A: Ok! Facepalm! I can't believe I wasted 2 hours on this and everyones time. I spelled javascript wrong and it threw off all the code but no errors. I'm sorry all but thank you for all the feedback!


text:
Q: Getting data from anormal object I'm new in Angular and created a app with Firebase backend (real-time database). I'm getting these type of data:
given data
I want to get the value for Firstname and Lastname, but I don't know how to access it. I've tried something like
    onRowClicked(data: any) {
        let y = data.settings;
        console.log(y);
      }

or something like
    onRowClicked(data: any) {
        let y = data.settings[0].Firstname;
        console.log(y);
      }

But I can't get these value. What do I wrong?
Can you please help me?
I've tried to cast it into array, but that doesn't work. Then I've tried to iterate it via forEach, but then I get the message, that forEach is not a funktion on this type :/


text:
Q: How to consume rules defined in the KIE-Workbench from the another java web application? I don't have previous work experience for the drools and everything. But due to my project requirement I need to use drools KIE-wirkbench rules integration. I know how to define rules inside the KIE but I don't know how to consume those rules inside the other application. Please suggest me some ideas. Thanks in advance.

A: Take a look at https://github.com/krisv/jbpm-evaluation-examples/blob/master/kjar-from-guvnor/src/main/java/org/jbpm/evaluation/EvaluationExampleKJarFromGuvnor.java
While it's a jBPM example, the same code would work for Drools as well.


text:
Q: How to Use v-date-picker with range props from vuetify I already read documentation several time about v-date-picker and I think what I want to use is one of these feature, v-date-picker with range props. But I don't know why I can't seem to implement it in my project. there is several error that I found such as:

*

*[Vue warn]: Error in data(): "TypeError: dateString.split is not a function" I read some answer in here: using-new-date-with-v-date-picker-doesnt-work but it still not solve my problem

*Error in render: "TypeError: dateString.trim is not a function"
this is my current progress:

for information I'm using vuetify: "^1.5.16" for my project. this is the example of my code:
<template>

  <v-date-picker v-model="dates" range></v-date-picker>
  <v-text-field v-model="dateRangeText" label="Date range" prepend-icon="event" readonly></v-text-field>
  model: {{ dates }}

</template>

in fact I just follow the step in Here can someone help me to solve this? I'm confused about this v-date-picker with range props problem.
Just for reference, I already tried this but it still failed:

*

*how-to-display-a-fixed-vuetify-v-date-picker-range
I follow this answer but this is what I got:

I change my dates to: dates: [new Date('2019-09-10').toJSON(), new Date('2019-09-20').toJSON()], and the error is still there. can someone help me to solve this?


text:
Q: Laravel Passport Register the user credentials were incorrect I set up Laravel Passport and currently I am trying to register user with a Post Route. I did create a RegisterController inside Controllers/Api/Auth.
Thus I created a clients table which looks excatly like a users table.
The client gets created if I call the route, but I do not get an access token nor a refresh token.
The route to my controller looks like this (routes/api):
Route::post('register', ['as' => 'register', 'uses' => 'Api\Auth\RegisterController@register']);

My Controller looks like this:
<?php

namespace App\Http\Controllers\Api\Auth;

use App\Client;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Route;
use Laravel\Passport\Client as PClient;

use Illuminate\Http\Request;

class RegisterController extends Controller
{
    private $client;

    public function __construct() {
        $this->client = PClient::find(1);
    }

    public function register(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|min:6|confirmed'
        ]);

        $client_user = Client::create([
            'name' => request('name'),
            'email' => request('email'),
            'password' => bcrypt(request('password'))
        ]);

        $params = [
            'grant_type' => 'password',
            'client_id' => $this->client->id,
            'client_secret' => $this->client->secret,
            'username' => request('email'),
            'password' => request('password'),
            'scope' => '*'
        ];

        $request->request->add($params);
        $proxy = Request::create('oauth/token', 'POST');
        return Route::dispatch($proxy);
    }
}

This is my Client Model:
class Client extends Model implements AuthenticatableContract,
                                      AuthorizableContract,
                                      CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword, HasApiTokens, Notifiable;

    protected $table = 'clients';

    protected $fillable = ['name', 'email', 'password'];

    protected $hidden = ['password', 'remember_token'];

When I am trying to call it with Postman I get this error message:

A: I may be way off basis here but it looks as if you are creating your client with a password of "password" due to your bcrypt('password') call.
Should it not be bcrypt(request('password'))?
This would explain why your credentials are wrong in your request, because they are ; )

A: Ok I fixed it, the post route worked if I used the User Model instead of my Client model, so I guessed that there has to be something different.
After some research I have found out that one needs to add the model, in my case the client model to the providers array inside config/auth.php.
So first one needs to change the api guard like this:
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'passport',
        'provider' => 'clients',
    ],
],

This way to api routes login and register only take action with my clients.
Now you need to a a new provider in this case a clients provider like this.
'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],
    'clients' => [
        'driver' => 'eloquent',
        'model' => App\Client::class
    ],
],

And voila I get an access token + refresh token if  I call the route.


text:
Q: Is it possible to prevent the header("location: url") from being sent to AJAX? I've a html form on a page. The form data is sent via AJAX to a PHP script. Within this PHP script, each of the $_POST's from the inputs are checked conditionally using a variety of if statements. If the condition doesn't meet a specific strlen / other criteria then I echo a message into the AJAX returndata and exit() the PHP script.
Assuming all conditions are met, at the bottom of my PHP script I have applied a url that is built from variables within the PHP script itself and concatenated inside, like so:
header("location: view_topic.php?tid='".$tid."'&page='".$page."'");
The issue:
Since I am generating the url within the PHP script, and am only able to generate it in there, I am having to either use PHP header("location: ...") as a redirect, or having to echo the url, which in turn sends it to the returndata, then use window.location(returndata) in my JavaScript/AJAX.
I've done some homework and have noticed a known issue with the header method, when set is being sent to the AJAX returndata. This means that the entire header location page is being displayed in a tiny invisible div where I display my errors for the above mentioned conditional error messages generated in the PHP script.
The question:
In the below code is my alternative method of setting the window.location(returndata).
Here I am echoing the actual url generated by my PHP variables, which sends it to the returndata. However when submitting the form I am returned to the same page, and the returndata is simply echo'd out from the PHP at the top.
Does anyone know how to prevent the header("location: ..."); from being sent to the AJAX returndata, or have any other solutions on the method below?
Thanks in advance,
Richie.
My AJAX:
$("#topic_form").submit(function(event){
    var formData = new FormData($(this)[0]);
    $.ajax({
    url: 'create_topic_parse.php',
    type: 'POST',
    data: formData,
    async: false,
    cache: false,
    contentType: false,
    processData: false,
        success: function (returndata) {
            if(returndata.indexOf("view_topic") != true){
                $('#message').css("color", "red").html(returndata);
                } else {
                window.location(returndata);
            }
        }
    });
    return false;
});

A: instead of returning html, return json:
{"action": "display","html":"..."}

or
{"action":"redirect","location":"url"}

and change:
    success: function (response) {
        if(response.action == "display"){
            $('#message').css("color", "red").html(response.html);
        } else if (response.action == "redirect") {
            window.location(response.location);
        }
    }

A: I think that, If I understand correctly. You want to use create_topic_parse.php, to generate a URL which you would then like to be redirected to.
Currently the page you want redirecting to, is displaying in a div on your existing page and not redirecting.
I think that in your PHP file, if you echo a meta refresh instead of a header() then this should get you the results you want.
echo "<meta http-equiv=\"refresh\" content=\"0;URL=view_topic.php?tid=".$tid."&page=".$page."\">";

These have always worked as part of the body for me.


text:
Q: BLDC motor control hall effect invalid I am a student EE major working on a control algorithm for a 3 phase sensored BLDC motor. Currently the motor is running well. I'm currently pursuing fault condition safety software for the motor. One possible fault that could occur is an invalid state read in for the hall effect sensors.
If the hall effect sensors read in 000 or 111 that means either one of the hall effect sensor's is shorted (111) or one is disconnected (000). My question derives from how to respond (in my control software) to a condition such as this?
Obviously if a hall effect sensor has gone corrupt (short / disconnected) I need to stop the motor from commutating. However, I'm worried that if this invalid state is caused by a fluke then I would not want to force the motor to stop immediately.
My current thoughts would be to just increment a counter each time an invalid state gets read in, then if 10 invalid reads come in consecutively I would stop the motor for good.
Thoughts? Am I crazy to think that hall effect sensor inputs straight from the motor could randomly be incorrect?
The more I think about this "issue" the more I'm leaning towards trusting the hall effect sensor data absolutely. If a random bit were to flip in the transmission the commutation pattern wouldn't be correct...
Thanks

A: You could implement back-emf as a backup control system to aid detecting fault conditions matching sensor data and rotor position calculated by back-emf, thus being able to detect even those fault conditions producing a "good looking" set of values, and eventually bring the motor to a soft stop using BEMF for rotor position detection.
Another option, if you want to go the fault detection way, is to implement redundancy in your sensors and communication line.
This can be implemented in various ways and probably is the best way to add a functional fault detection that not only detect faults but also enables you to not have to immediately halt the motor.
If both such solutions seems too complicate you probably are in a case were a serious fault detection algorithm is not needed and stopping the motor in case of incoherent data is "just the right solution" so you can fix that cold soldered hall sensor  before finals :-)
As far as fault detection goes is probably more important to focus on current detection.
Have fun! :-)


text:
Q: How to display column names in several languages in SharePoint? I have created a site, installed my language packs, created the term store service and created some terms in multi-language (Persian and English). I then created a site, a new list, and a new managed metadata column on that list. I then used the term sets and it's working perfectly.  I can switch to both Persian and English with no problem and the values of this list are changed as expected.
Despite the fact that the base template is able to switch names when I change the language, it doesn't seem to apply for user defined columns and list names. Is there a way for my user-defined column title (name) to switch language the same way the values can use the term store?

A: The problem is that when you create a column, the name you enter is just a constant string. SharePoint does not do translation based on known words. Internationalization is based on resource files.
And while I have used resource strings with custom list definitions, I wasn't sure if they would work on lists and columns created in the browser. So tried a quick test. I grabbed a resource string ($Resources:core,camlid2;), went to the List Settings of a list, selected a column,  pasted the resource string into the Column name box, and clicked OK. Sure enough, when I returned to the List Settings page, the column name had changed to "Body".
Here are the steps I would take for creating international-able columns through the browser:

*

*Create the column with the name you want as the internal name (ie, no spaces or symbols to avoid _x0020_ and other encoding replacements).

*Edit the column by changing the column name to a resource string that you know if defined in each language you want to support.

A: Here's how to do it programatically:
// Assuming list contains a SPList object
string fieldID = "FieldUniqueID";
list.Fields.Add(fieldID, SPFieldType.Text, false);
list.Fields[fieldID].Title = "$Resources:Example,FieldUniqueID";
list.Fields[fieldID].Update();

Note that you cannot stick "$Resources:Example,FieldNameI18N" right into Fields.Add() because hell breaks loose, since the string in Add() parameters is used for other SP stuff too, special characters get replaced, and so on.

A: I think this MSDN article can help you and show the easy that it is: http://msdn.microsoft.com/en-us/library/office/ff800886(v=office.14).aspx

A: Multilanguage SharePoint Website:

*

*I change the language in the Internet Explorer -> Gearwhell -> Internet Options -> Language to a specific language.

*Then I open the SharePoint Website and modify the columns for example in englisch.

*Then I change the language in the browser again and modify the columns for example in german.

SharePoint seems to save the value interally for the language that is in the settings of the browser.
Now when a users opens the page, depending on his browser language, he sees the Name of the columns in his language.
Requirement is that you have activated the specific languages in the site Settings of the SharePoint page.
This can also be done with Name of the Website, Navigation nodes and list titles.


text:
Q: Regex replacement issues https://www.myregextester.com/?r=6fba8b94
Regex is
(\w(s)\b)

Sample Word
Dress

*

*\1 returns "Dress"

*\2 returns "Dres"

So I figured:

*

*\1 \2 would return "Dress Dres"

But it returns:
"Dress s"

How can I make it return "Dress Dres"

A: You're misreading something in that regex tester. In reality, \1 is equal to ss and \2 is equal to s. This is because you are only matching two characters, \w and s. Even if you added a 1+ quantifier to the \w (i.e. (\w+(s)\b)), you'd still just match Dress and s, since the second capture group is literally just capturing the s.

If you move those capture groups around a bit, you can successfully capture "Dress" and "Dres". A quick side note, you can get the entire regex match with \0 so the nested capture groups are somewhat unnecessary here.
Match: (\w+)s\b
Replace: \0 \1
Output: Dress Dres

A: First, use a + quantifier with \w to match 1 or more word characters (you only match 1 with \w). That is why you get just s and s (see your regex in action capturing ss as Group 1 and s as Group 2).
And use:
(\w+)s\b

With \0 \1 replacement where \0 backreferences the whole match, and the \1 backreferences what was captured with (\w+). See demo here.
Or, if it is Perl, use ((\w+)s)\b and replace with \1 \2 (see demo).
See demo


text:
Q: Concatenating file path I have following paths and I want to concatenate them to make a final path:
path1 = \\ITSUSRAPADCON2\tm1\cons\grm_aspac\user_in\Manual Upload Current Plan\Archive

path2 = Dev Finance GRM CONS ASPAC_GrsSalesAdj.csv_02_11_2021_18_41_03_1862

final path = \\ITSUSRAPADCON2\tm1\cons\grm_aspac\user_in\Manual Upload Current Plan\Archive\ Dev Finance GRM CONS ASPAC_Sales_3069_WI2_2020_GrsSalesAdj.csv_02_11_2021_18_41_03_1862_In.csv

tried this:
final path = path1 + "\\" + path2 + "_In.csv"

gives following error:
FileNotFoundError: [Errno 2] No such file or directory:
 '\\\\ITSUSRAPADCON2\\tm1\\cons\\grm_aspac\\user_in\\Manual Upload Current Plan\\Archive\\ Dev Finance GRM CONS ASPAC_Sales_3069_WI2_2020_GrsSalesAdj.csv_02_11_2021_18_41_03_1862_In.csv'

A: I would recommend using os.path.join() function, like so:
final_path = os.path.join(path1, path2)

This will be safe across operating systems that might use different path directory separators.


text:
Q: Lookup for values and return all matching rows Is there a way to look up for values(sheet2) in  sheet1 and copy all the matching rows to a new sheet (sheet3)?
Sheet1
Name    Hours   Group
Joy     12  AA
Allen   23  AA
Tom 34  AA
Amy 45  AX
Chris   6   AD
Allen   7   FG
Tom 8   GH
Joy     8   JK
Amy 23  UY
Jack    11  AA

Sheet 2 (col A):
Joy
Allen
Amy
Chris

Sheet 3 (expected o/p)
Joy     12  AA
Joy     8   JK
Allen   23  AA
Allen   7   FG
Amy 45  AX
Amy 23  UY
Chris   6   AD

A: What you try is actually filter sheet1 by the names of sheet2
Make use of Advanced Filters to achieve the result of sheet3.
But the restrictions are …

*

*it has to be done in the same sheet (Excel restricts it)
so you need to copy the result to sheet3 after filtering it.

*you need to sort it by name before or after

The following image describes what parameters I used for advanced filter.
(Sorry for the german screenshot, I think you will figure it out.)

Note that you don't necessarily copy the result to another location, but can do a reversible filtering just in place of the original data. Which one to use depends on what you are going to do with that data later.
Also note, that the headlines (like 'Name') of the criteria range have to match the list range. The advanced filter uses them to find the column to filter on.


text:
Q: IValidator.Validate method and adding error message to a custom type I have several server controls that implement the IValidator interface. As such, they have their own Validate() methods that look like this.
public void Validate()
{
  this.IsValid = true;
  if (someConditionFails())
  {
    ErrorMessage = "Condition failed!";
    this.IsValid = false;
  }
}

I understand that these Validate() methods are executed on postback before the load completed event that is executed before the save button's event handler. What I would like to do is pass in a reference to an instance of a custom class that collects all the error messages that I can access from Save button event handler.
In other words, I would like to do something like this:
public void Validate(ref SummaryOfErrorMessages sum)

I guess I can't do this as the signature is different from what the IValidator interface has. The other option I can think of is on Load Completed event, I would iterate through all the validators on page, get the ones with IsValid = false and create my SummaryOfErrorMessages there. Does this sound right? Is there a better way of doing it?

A: I'd iterate through all the validators on the page after validation has been performed and get the summary. You can find all the validators from Page.Validators.
As a warning, please note that validators that only use IValidator and don't inherit from BaseValidator do not support validation groups at all, so it would seem that not inheriting from BaseValidator is somewhat deprecated. I have been bitten by this once.


text:
Q: How can I create global context variables in JBoss? This is a follow-up to a question I posted a while back:  "Can I use a single WAR in multiple environments?".  I was able to create a single-war solution in Tomcat, but now we are migrating our app to JBoss 4.2 and I can't figure out how to set up global environment variables.
In Tomcat 6 this was pretty straightforward:  I simply put the following snippet in tomcat/conf/Catalina/myappname.xml:
<Context ...>
   <Environment name="TARGET_ENV" value="DEV" type="java.lang.String" override="false"/>
</Context>

Then in my app I was able to resolve the environment name with the following:
Context context = (Context) InitialContext().lookup("java:comp/env");
String targetEnvironment = (String) context.lookup("TARGET_ENV");

The problem is that I can't find out where/how to place global variables in JBoss.   I've tried putting the <Environment> tag in the following files to no avail:

*

*server/all/deploy/jboss-web.deployer/context.xml

*server/default/deploy/jboss-web.deployer/context.xml
I know that I can put environment variables  in my app's web.xml but that defeats the purpose of having a unified war  - I'd still need custom .war's for dev, qa and prod.
I'm a JBoss newbie so if there's any additional information that would help just let me know and I'll append to this question.

A: I use somehing similar to PropertiesService for database url, and other environment related things.
Therefore I'm relieved from the burden to provide different environment related atrifacts.


text:
Q: How can I scrape JSON value from key? import requests
from datetime import datetime

gg = []

now = datetime.now()
current_time = now.strftime("%Y-%m-%dT%H:%M:%S")

url = ("https://sportsbook-sm-distribution-api.nsoft.com/api/v1/events?deliveryPlatformId=3&dataFormat=%7B%22default%22:%22object%22,%22events%22:%22array%22,%22outcomes%22:%22object%22%7D&language=%7B%22default%22:%22sr-Latn%22,%22events%22:%22sr-Latn%22,%22sport%22:%22sr-Latn%22,%22category%22:%22sr-Latn%22,%22tournament%22:%22sr-Latn%22,%22team%22:%22sr-Latn%22,%22market%22:%22sr-Latn%22%7D&timezone=Europe%2FBelgrade&company=%7B%7D&companyUuid=4dd61a16-9691-4277-9027-8cd05a647844&filter[sportId]=3&filter[from]={}&sort=categoryPosition,categoryName,tournamentPosition,tournamentName,startsAt&offerTemplate=WEB_OVERVIEW&shortProps=1").format(current_time)

response = requests.get(url)
matches = response.json()
print(matches) #This is my json document

I am trying to scrape odds from betting site. I am pretty new to python and I need some help.
Some kind of "Odd id" is stored in key "b". So basically for every match in this json file, if match contains key "b" with value 2763, i want to scrape value of key "g" and store it in my list "gg"(in key "g" value is odd that i want to scrape). But if match doesn't contains key "b" with value 2763, for that match  I want to append only one time "1.00" to list "gg".
for match in matches:
    mat = matches['data']['events']
    for s in range(len(mat)):
        o = mat[s]['o']
        for element in o:
            h = o[element]['h']
            for x in h:
                if h[x]['b'] == 2763:
                gg.append(h[x]['g'])

With this command i can scrape odds but i don't how to append "1.00" to GG if match doesn't have 'b':2763 (oddid)

A: From what I can understand from your problem. This should be the solution.
   json = {
        'b': 2763,
        'g': 'odd number'
    }

    x = 'b'
    y = 2763
    gg = []

    for key, value in json.items():
        if x == key and y == value:  # if finds b: 2763
            gg.append(json.get('g'))
        elif x == key and y != value:
            gg.append(1.00)
            break

you can reduce the number of lines using comprehension.

A: i haven't verified your code but i'm assuming it works and you understand what it does. what you need is a flag. a flag is just a boolean (True/False), let's name it has_2763. you just have to reset it at each match start
for match in matches:
    mat = matches['data']['events']
    for s in range(len(mat)):
        has_2763 = False
        o = mat[s]['o']
        for element in o:
            h = o[element]['h']
            for x in h:
                if h[x]['b'] == 2763:
                    gg.append(h[x]['g'])
                    has_2763 = True
        if not has_2763:
            gg.append("1.00")


text:
Q: 'Faking' a project reference? I have a solution structure like in Ports And Adapters Architecture or Onion Architecture. My composition root (a web application in this case) and infrastructure libraries only reference the core library.
I can also load infrastructure libraries at runtime using Castle Windsor. However I do not reference these libraries on my composition root so their build output is not copied to the output folder. I guess I need a custom build step but I don't know how I can accomplish this.

A: Use a post build event to copy the assemblies to the output directory. Here is a tutorial you'll be able to get a good feel for it from.
http://eyeung003.blogspot.com/2009/11/visual-studio-post-build-event-to-copy.html?m=1

A: I ended up with setting unreferenced projects' output path same same as the web application's.
..\WebApp\bin

This works well for building the solution inside Visual Studio. For release builds (only building the Website project) I wrote a custom script that builds Web application and other libraries. After those libraries are built, all dll files are copied to WebApp\bin folder inside _PublishedWebsites using a Copy task.