text:
Q: Help setting up a Java build environment I'm at my wit's end.  I'm spending more time working on getting my build to work rather than actually developing software.  I'm currently working on large-scale Java web application based on Tomcat 6.
Currently the code-base is about 25k LOC (although that's not quite representative because some of that is autogenerated for web services -- but the take away is that it's big) and I've been working exclusively with eclipse to do everything from debugging, to build path management to building.  In the past, eclipse has always been more than enough, but I've never worked on a project this large before.
The first problem I had was when I started adding GWT content.  It worked ok, but the build process was a bit hacky: I had to manually compile and then copy the js output into the appropriate directory and debugging was a nightmare (I realize some of those problems are just GWT and the way it works...).  Now, the issue I'm running into is attempting to work on the project on a Windows machine (I had been working on a Mac, and will continue to work from a Mac from time to time).  Eclipse added the Mac OS JVM libraries to the build path which, of course, Windows can't find.
I asked a question about working in two different environments and most of the answers pertained to using a build tool like Ant+Ivy or Maven.  I've started investigating Maven and attempting to get my project to use it, but it's just been one headache after another and I haven't even begun to try to actually execute/debug my application in Tomcat through eclipse.  The most frustrating part of all of this is it, to me, seems like these build tools are exceptionally complex (and to be fair, incredibly flexible) but, at least initially, make life even more difficult while you try to figure out how to simply compile a Java file.
So all of that to say, does anybody have suggestions for how to simplify this scenario?  Dependency management would be nice, but I don't mind hunting down the JARs myself.  The biggest thing I need is something that will just get out of my way and let me work on what I'm actually trying to work on, not spend hours debugging my typos in an xml file used by the build system.
Thanks in advance

A: I agree.  You don't need Maven; you don't need Ivy.  Start with Ant.
Here's a relatively generic Ant build.xml.  Customize it as you wish.
<?xml version="1.0" encoding="UTF-8"?>
<project name="xslt-converter" basedir="." default="package">

    <property name="version" value="1.6"/>
    <property name="haltonfailure" value="no"/>

    <property name="out" value="out"/>

    <property name="production.src" value="src"/>
    <property name="production.lib" value="lib"/>
    <property name="production.resources" value="config"/>
    <property name="production.classes" value="${out}/production/${ant.project.name}"/>

    <property name="test.src" value="test"/>
    <property name="test.lib" value="lib"/>
    <property name="test.resources" value="config"/>
    <property name="test.classes" value="${out}/test/${ant.project.name}"/>

    <property name="exploded" value="out/exploded/${ant.project.name}"/>
    <property name="exploded.classes" value="${exploded}/WEB-INF/classes"/>
    <property name="exploded.lib" value="${exploded}/WEB-INF/lib"/>

    <property name="reports.out" value="${out}/reports"/>
    <property name="junit.out" value="${reports.out}/junit"/>
    <property name="testng.out" value="${reports.out}/testng"/>

    <path id="production.class.path">
        <pathelement location="${production.classes}"/>
        <pathelement location="${production.resources}"/>
        <fileset dir="${production.lib}">
            <include name="**/*.jar"/>
            <exclude name="**/junit*.jar"/>
            <exclude name="**/*test*.jar"/>
        </fileset>
    </path>

    <path id="test.class.path">
        <path refid="production.class.path"/>
        <pathelement location="${test.classes}"/>
        <pathelement location="${test.resources}"/>
        <fileset dir="${test.lib}">
            <include name="**/junit*.jar"/>
            <include name="**/*test*.jar"/>
        </fileset>
    </path>

    <path id="testng.class.path">
        <fileset dir="${test.lib}">
            <include name="**/testng*.jar"/>
        </fileset>
    </path>

    <available file="${out}" property="outputExists"/>

    <target name="clean" description="remove all generated artifacts" if="outputExists">
        <delete dir="${out}" includeEmptyDirs="true"/>
        <delete dir="${reports.out}" includeEmptyDirs="true"/>
    </target>

    <target name="create" description="create the output directories" unless="outputExists">
        <mkdir dir="${production.classes}"/>
        <mkdir dir="${test.classes}"/>
        <mkdir dir="${reports.out}"/>
        <mkdir dir="${junit.out}"/>
        <mkdir dir="${testng.out}"/>
        <mkdir dir="${exploded.classes}"/>
        <mkdir dir="${exploded.lib}"/>
    </target>

    <target name="compile" description="compile all .java source files" depends="create">
        <!-- Debug output
                <property name="production.class.path" refid="production.class.path"/>
                <echo message="${production.class.path}"/>
        -->
        <javac srcdir="src" destdir="${out}/production/${ant.project.name}" debug="on" source="${version}">
            <classpath refid="production.class.path"/>
            <include name="**/*.java"/>
            <exclude name="**/*Test.java"/>
        </javac>
        <javac srcdir="${test.src}" destdir="${out}/test/${ant.project.name}" debug="on" source="${version}">
            <classpath refid="test.class.path"/>
            <include name="**/*Test.java"/>
        </javac>
    </target>

    <target name="junit-test" description="run all junit tests" depends="compile">
        <!-- Debug output
                <property name="test.class.path" refid="test.class.path"/>
                <echo message="${test.class.path}"/>
        -->
        <junit printsummary="yes" haltonfailure="${haltonfailure}">
            <classpath refid="test.class.path"/>
            <formatter type="xml"/>
            <batchtest fork="yes" todir="${junit.out}">
                <fileset dir="${test.src}">
                    <include name="**/*Test.java"/>
                </fileset>
            </batchtest>
        </junit>
        <junitreport todir="${junit.out}">
            <fileset dir="${junit.out}">
                <include name="TEST-*.xml"/>
            </fileset>
            <report todir="${junit.out}" format="frames"/>
        </junitreport>
    </target>

    <taskdef resource="testngtasks" classpathref="testng.class.path"/>
    <target name="testng-test" description="run all testng tests" depends="compile">
        <!-- Debug output
                <property name="test.class.path" refid="test.class.path"/>
                <echo message="${test.class.path}"/>
        -->
        <testng classpathref="test.class.path" outputDir="${testng.out}" haltOnFailure="${haltonfailure}" verbose="2" parallel="methods" threadcount="50">
            <classfileset dir="${out}/test/${ant.project.name}" includes="**/*.class"/>
        </testng>
    </target>

    <target name="exploded" description="create exploded deployment" depends="testng-test">
        <copy todir="${exploded.classes}">
            <fileset dir="${production.classes}"/>
        </copy>
        <copy todir="${exploded.lib}">
            <fileset dir="${production.lib}"/>
        </copy>
    </target>

    <target name="package" description="create package file" depends="exploded">
        <jar destfile="${out}/${ant.project.name}.jar" basedir="${production.classes}" includes="**/*.class"/>
    </target>

</project>

A: while maven may be a bit daunting at first glance, i think it really is a pretty nice tool.  yes, it does have it's warts, but all in all i think it's one of the best choices for java.  the "thing" you really need to get about maven is that everything is based on convention.  if you do everything the conventional maven way, then your maven pom is generally very small and everything "just works".  and there is plenty of getting started info out there to show you what the "maven convention" is.  (and yes, you usually can do things your own way, but it's usually not worth it unless you are stuck w/ an existing project which would be difficult to re-organize).

A: There are alternatives to Ant/Ivy or Maven XML that might be worth a gander.  They use a real programming language instead of an XML DSL.

*

*http://buildr.apache.org/ (Ruby based)

*http://www.gradle.org/index.php (Groovy based)

A: One simplification you can use when working solely in Eclipse is to let Eclipse take care of the compilation.   A given project can have its own simple Ant script, which packages up whatever is need from bin into a jar.


text:
Q: How to load balance requests using header value in IBM web server plugin? We are using IBM Web Server plugin to load balance in a cluster of web servers. So far we are routing the requests based on URLs. We now need to route a set of requests using combination of URL and a header value. How can this be done?

A: You simply cannot -- the WAS WebServer Plugin only considers the host, URL, and session affinity.  Are you trying to select an alternate cluster, or just a specific backend server?
Either way, the only viable option is to manipulate the URL or session cookie and use the normal routing.

redpajama_set_name: RedPajamaStackExchange


text:
Q: NuGet creates read-only folders for packages without access I am using Windows 10 with Visual Studio Community 2017. I am creating Xamarin.Forms project and right after that I am updating NuGet packages, but I see Access denied error for some NuGetpackage folders. NuGet creates these folders in c:/users/username/.nuget/packages with read-only attribute and after that it has no access to them - access denied.
Even I cannot access or manipulate these folders via File explorer, but I am with administrator account and there is no another Windows account.
I am using Visual Studio as Administrator, but I can't update/restore packages or clear NuGet cache.

A: In my case i have suppress the folder Cache at C:\Users\user_name\AppData\Local\Xamarin.Android for resolve this problem


text:
Q: Analogue clock position sensing I want to control an analogue clock movement with a microcontroller. A Lavet motor is used to advance the hands.
The issue is detecting where the hands are. I noticed that some radio controlled clocks move the hands to midnight before moving them to the correct time.
What mechanism do they use to detect midnight position?

A: According to this forum, it has a IR-LED detector and tiny hole.

A: I know it's a little late, but I have been pondering the same thing, and searching the internet for ideas. Although what I was really looking for was validation of my own idea.
I have a cheap alarm clock that I bought for exactly this purpose. It operates from a 1.5V AA cell, and has a Lavet mechanism internally. My idea is to set the alarm to 12:00 and detect the alarm switch activation (which you can hear clicking on when you move the hands to 12:00).
So, once I disconnect the driver board from the coil and control the hands with an Arduino, I can detect 12:00 by monitoring the alarm switch. Therefore I know the hands are in a known position.
Probably cheaper and easier to find than the clock modules with optical sensors, albeit slightly less accurate at pinpointing 12:00 precisely.

A: I opened up a broken one and it is indeed an optical sensor. Sorry about the focus.
Sensor is the thing hanging over the top most cog.


text:
Q: Alamofire returns nil always in request Usually Alamofire working nice with simple urls like:
"http://somesite.com/folder/file.json"
But when I use:
"http://somesite.com/folder/(jsonName.text).json
it always give me a nil... jsonName is a TextField as well...
That's the whole Controller:
import UIKit
import CoreLocation
import Alamofire
import SwiftyJSON
import CoreData

typealias CompletionHandler = (obj:AnyObject?, error:Bool?) -> Void

 class LoginViewController: UIViewController, UITabBarControllerDelegate, UITextFieldDelegate, NSURLConnectionDelegate {

    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

    @IBOutlet weak var wePrepareQuestLabel: UILabel!

    @IBOutlet weak var downQuestProgres: UIActivityIndicatorView!

    @IBOutlet weak var doNotCloseAppLabel: UILabel!

    @IBOutlet weak var loginBgImage: UIImageView!

    @IBOutlet weak var EmptyCodeError: UILabel!

    @IBOutlet weak var loginTabBarItem: UITabBarItem!

    @IBOutlet weak var QuestCodeTextField: UITextField!

    @IBOutlet weak var loginTextFieldImage: UIImageView!

    @IBOutlet weak var downloaded: UIButton!

    @IBOutlet weak var createQuestButton: UIButton!

    @IBAction func createQuest(sender: UIButton) {

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewControllerWithIdentifier("WebViewController") as! UIViewController
        self.presentViewController(vc, animated: true, completion: nil)

    }

    let Path: String = ""

    @IBAction func QuestFetchButton(button: UIButton) {

         if QuestCodeTextField.text.isEmpty {

       EmptyCodeError.hidden = false
        }

         else if IJReachability.isConnectedToNetwork() {

        }
        else
        {
            QuestCodeTextField.hidden = true
            button.hidden = true
            EmptyCodeError.hidden = true
            createQuestButton.hidden = true
            doNotCloseAppLabel.hidden = false
            wePrepareQuestLabel.hidden = false
            loginTextFieldImage.hidden = true
            downQuestProgres.hidden = false
            self.downloaded.hidden = false

//            questDownloadSaveJSON()

            var objThisVC = LoginViewController()
            objThisVC.callAndGetResponse { (obj, error) -> Void in

                if (obj != nil) {
                    self.setUpDataInCoreData(obj)
                    print("ALL DIE")
                    self.performSegueWithIdentifier("QuestsListViewController", sender: nil)
                }
                else {
                    println("Response nil!!")
                }
            }

        }
        }

    var file:NSFileHandle?
    var pathURL: NSURL
        {
            let folder = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
            let path = folder.stringByAppendingPathComponent("\(QuestCodeTextField.text).json")
            let url = NSURL(fileURLWithPath: path)

            return url!

    }

    var code: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()

      QuestCodeTextField.text = code

        self.QuestCodeTextField.delegate = self;

    }

    func setUpDataInCoreData(obj:AnyObject?){

        println("Web Serviece Response \(obj)")

        let dirEvent = obj as! NSDictionary
        var aryEvent = dirEvent.valueForKey("events") as! NSArray

        var indexEvent : Int = 0;

        for (dirContent) in aryEvent
        {
            // Create Event Instance
            var newItem: Events = NSEntityDescription.insertNewObjectForEntityForName("Events", inManagedObjectContext: self.appDelegate.cdh.backgroundContext!) as! Events

            newItem.title = dirContent.valueForKey("title") as! String
            newItem.indexID = String(indexEvent++) as String

            println(newItem.title)
            println(newItem.indexID)

            var indexContent : Int = 0;
            var aryContent = dirContent.valueForKey("content") as! NSArray

            for (dirContentDetail) in aryContent{

                var contentEntity: Content = NSEntityDescription.insertNewObjectForEntityForName("Content", inManagedObjectContext: self.appDelegate.cdh.backgroundContext!) as! Content

                contentEntity.content_type = dirContentDetail.valueForKey("content_type") as! String
                contentEntity.visible = dirContentDetail.valueForKey("visible") as! Bool
                contentEntity.indexID = String(indexContent++) as String

                println(contentEntity.content_type)
                println(contentEntity.visible)

                if contentEntity.content_type == "text"{

                    contentEntity.data_type = dirContentDetail.valueForKey("data") as! String

                }
                else if contentEntity.content_type == "image" || contentEntity.content_type == "audio" || contentEntity.content_type == "video" || contentEntity.content_type == "choice" {

                    contentEntity.data_type  = ""
                    if (dirContentDetail.valueForKey("data") != nil && dirContentDetail.valueForKey("data")?.count>0 )
                    {

                        var indexImage : Int = 0;

                        var aryDTImages = dirContentDetail.valueForKey("data") as! NSArray

                        if aryDTImages.count > 0 {
                            for strContentDetail in aryDTImages as! [String]{

                                var objDtImg : DataTypeImage = NSEntityDescription.insertNewObjectForEntityForName("DataTypeImage", inManagedObjectContext: self.appDelegate.cdh.backgroundContext!) as! DataTypeImage

                                var strURL : NSString = NSString(string: strContentDetail)

                                objDtImg.urlString = strURL as String
                                objDtImg.indexID = String(indexImage++) as String
                                objDtImg.dtImages = contentEntity

                                // her have to set image to content
                                contentEntity.content = newItem
                            }
                        }

                    }
                }

                // here have to set entity to content
                contentEntity.content=newItem

            }// this is the end of content for loop

        }// end of aryEvent

        // here to save statement
        self.appDelegate.cdh.saveContext(self.appDelegate.cdh.backgroundContext!)

//        self.table.reloadData()

    }

    func callAndGetResponse(complitionHandler : CompletionHandler){
        complitionHandler(obj: nil, error: true)

        Alamofire.request(.GET, "http://g57732cr.bget.ru/\(QuestCodeTextField.text).json").responseJSON() {
            (_, _, data, error) in

            if error == nil {
                complitionHandler(obj: data, error: false)
            }
            else{
                complitionHandler(obj: nil, error: true)
                  self.performSegueWithIdentifier("QuestsListViewController", sender: nil)
            }

            // Fetch all data from Core Data
            //self.fetchAllData()
        }

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // Hide keyboard by tap on the rest of the view
    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {

        view.endEditing(true)

    }

    //ReturnButton hides keyboard
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        self.view.endEditing(true)
        return false
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if (segue.identifier == "QuestsListViewController"){
            var destination = segue.destinationViewController as! UINavigationController
             let VC = destination.topViewController as! QuestListViewController
         VC.questCode = self.QuestCodeTextField.text

        }
    }

}


text:
Q: Entity Framework how to prevent loading tree when child entity returns I have a complicated tree structure of my entites, and if i try to access a entity of tree, EF generate very large query with many JOIN's to other one-level childs.
And if i try to return child entity from its DbContext as parent abstract entity,  EF still generating big query. Lazy loading is on.
How can i return child entity without joining another one-level childs?
Db Structure
Parent class declaration:
public abstract partial class Document : Basics.AccountableGradInfoDbObject
{
    protected Document ()
    {
        ...
    }
    ...
}

Child class declaration:
 public partial class ChildDocumentOne: Document
{
    public ChildDocumentOne()
    {
        ...
    }
    ...
}

What i try to do:
      public static Document GetDocumentById(this MyDbContext ctxt, int docId) //trying to get child entity by PK and return it as parent abstract class
    {
        ...
        switch (docStr.DocumentKind) //entity type found
        {
            case "DocumentOne":
                return MyDbContext.DocumentOneSet.FirstOrDefault(x => x.Id == docId); // getting entity from stecified dbcontext

As result, generates linq containing about 1500 lines and joining all childs.


text:
Q: Getting error while executing visual C++ GUI Program I'm getting error,
error C1113: #using failed on 'c:\program files\reference assemblies\microsoft\framework\.netframework\v4.0\system.core.dll'

When Executing following code...
MyForm.cpp
#include "Myform.h"

using namespace GUI;

[STAThreadAttribute]
int main(){

    MyForm fm;
    fm.ShowDialog();
    return 0;
}

MyForm.h
 private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
                 this->Close();
                 }


text:
Q: how to delete a user in a mysql server based on search results?
I have a datagrid control with a list of names that it retrieves from a MySql database. I can search through them until i have one result. I want to be able to Display a groupbox control when the number of results is equal to 1. Also, in the groupbox i have a button that when clicked will delete this user from the server and their information from the mysql table called "employee". when the user is deleted i'll display a confirmation message in a messagebox, and reload the table with the updated list. so far the only two problems i have are showing the groupbox when the results are equal to 1 and deleting the user from the sql server based on the name of the search result.  im using vb.net in visual basic 2010 express on windows 7 laptop. Thanks!
EDIT1:
Heres my code so far, please suggest how i can apply your answers to it. Thanks!
Private Sub TextBox1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyUp
    'Search Function.
    Dim sqlsearch1 As MySqlCommand = New MySqlCommand("SELECT * FROM employee where name LIKE '%?name%' GROUP BY name;", con)
    Dim sqlsearch2 As MySqlCommand = New MySqlCommand("SELECT * FROM employee where title LIKE '%?title%' GROUP BY title;", con)
    sqlsearch1.Parameters.AddWithValue("?name", TextBox1.Text)
    sqlsearch2.Parameters.AddWithValue("?title", TextBox1.Text)

    If RadioName.Checked = True Then
        con.Open()

        Dim table As DataTable
        For Each table In ds.Tables
        Next
        ' Clear all rows of each table.
        ds.Clear()

        ' display results in Datagrid1.
        DataAdapter1.SelectCommand = sqlsearch1
        DataAdapter1.Fill(ds, "stratos")
        DataGrid1.DataSource = ds
        DataGrid1.DataMember = "stratos"
        con.Close()
    Else
    End If

    If RadioTitle.Checked = True Then
        con.Open()

        Dim table As DataTable
        For Each table In ds.Tables
        Next
        ' Clear all rows of each table.
        ds.Clear()

        ' display results in Datagrid1.
        DataAdapter1.SelectCommand = sqlsearch2
        DataAdapter1.Fill(ds, "stratos")
        DataGrid1.DataSource = ds
        DataGrid1.DataMember = "stratos"
        con.Close()
    Else
    End If
End Sub

A: for deleting, you can simply issue a delete statement and pass it a parameter, namely name.
DELETE FROM MyTable WHERE MyName = @Name
Im not sure what you need the group box for.

A: If you are doing something like
 Set recBooks = con.Execute("SELECT * FROM Admin WHERE Name like 'hey' ;")

recbooks.count will return the number of records.
And for deleting, just run the query
  DELETE FROM Admin WHERE Name = {0}

when the button is clicked, and reload the datagrid using datagrid.refresh()


text:
Q: Is it possible to wrap integer and call it like integer? I want to make the int in IDictionary<int, Driver> a little less obscure about its meaning, so I thought maybe wrapping it would be a good idea. The outcome would be something like IDictionary<finishPosition, Driver>.
Preferably, finishPosition should be assignable like this finishPosition = 1.
I do not know if this is possible and how.

A: You could use a struct with an implicit conversion.
public struct FinishPosition {
    public readonly int Position;

    public FinishPosition(int position) {
        this.Position = position;
    }

    public static implicit operator FinishPosition(int position) {
        return new FinishPosition(position);
    }
}

// ...

Dictionary<FinishPosition, Driver> dict = new Dictionary<FinishPosition, Driver>();
Driver bob = new Driver();

// The following two lines are effectively equivalent
dict[new FinishPosition(7)] = bob;
dict[7] = bob;

// So are these two
bob = dict[7];
bob = dict[new FinishPosition(7)]

A: Absolutely, just use this using directive:
using FinishPosition = System.Int32;
at the top of your source file, and write the code just as you have in your example.
If you use the using directive like this, FinishPosition is an int and other files will see it as an int - there is no new type FinishPosition defined (thanks for configurator in the comments).

A: You could use an enum:
enum Position { Finish, Some, Other }

IDictionary<Position, Driver> lookup = ...;

Driver d = lookup[Position.Finish];

A: In my opinion, it is good to use AbstractDataType pattern anywhere where a general value is used with specific intents (this case has been made by many others with examples like Percentage, ReadonlyString, ConnectionString, etc.)
Note, I personally think that having implicit conversions to and from them sort of hollows the whole thing out (by having an implicit conversion, there is no more compiler guarantee that generic values are being used with specific intent at the right place).
Here is a sample that should inspire you to have it your way: you can still choose the level of convenience/verbosity you prefer. It show two approaches:

*

*_byInt indexes a dictionary by PseudoInt

*_byEnum indexes a dictionary by an Enum : int type

Notes

*

*if you #define IMPLICIT_CONVERSIONS you will get implicit conversions to the base index type (so to int or to the enum)

*this extrapolates to all value types, including user defined ones (try it with your XYZCoord struct :))

*have a look overhere if you really wanted conversions to and from Enum types
Without further ado:
#define IMPLICIT_CONVERSIONS
using System.Collections.Generic;

namespace NS
{
    public enum PositionEnum : int { Begin = 0, Normal = 1, End = 99 }

    public struct Pseudo<T> where T : struct
    {
        public T Value;
        public Pseudo(T value) { Value = value; }
#if IMPLICIT_CONVERSIONS
        public static implicit operator T(Pseudo<T> pi)  { return pi.Value; }
        public static implicit operator Pseudo<T>(T ni)  { return new Pseudo<T>(ni); }
#endif
    }

    static class Program
    {
        private static Pseudo<T> AsPseudo<T>(this T value) where T : struct
        {
            return new Pseudo<T>(value);
        }

        private static readonly IDictionary<Pseudo<int>, string> _byInt =
            new Dictionary<Pseudo<int>, string>()
                {   { 0,  "aap" },
                    { 1,  "noot" },
                    { 99, "mies" },
                };

        private static readonly IDictionary<Pseudo<PositionEnum>, string> _byEnum =
            new Dictionary<Pseudo<PositionEnum>, string>()
                {   { PositionEnum.Begin,  "aap" },
                    { PositionEnum.Normal, "noot" },
                    { PositionEnum.End,    "mies" },
                };

        public static void Main(string[] args)
        {
            string s;
            s = _byInt[0];
            s = _byEnum[PositionEnum.Normal];
        }
    }
}

A: I just adapted the RichEnum generic baseclass in the question I linked before [1]
I'd say I prefer this method because it really seems the most flexible in the long run. The only downside I can think of, really, is that the RichEnum type cannot be a value type anymore.
Head over to see what I mean (includes a fully running sample again):
[1] Can we define implicit conversions of enums in c#?


text:
Q: Regular Expression to split "/n" I want to split the /n from my string in Java. For example, I have one String field which has 2 lines space ( /n).  I have to find out lines ( wherever mopre than one lines is coming) and should replace with one line spaces.
"This is Test Message

  thanks
  Zubair
"

From the above example, there are more spaces between "This is Test Message" and "thanks". So i want to reduce as only one line instead of 2 lines.How to do that?

A: str.replaceAll("(\\r\\n?|\\n){3,}", "$1$1");

What this does is replace three or more line terminators (\r, \n or \r\n) with two line terminators so any double blank lines are replaced with a single blank line, if I understand what you want correctly.

A: I don't know how to use regex, but you can use a StringTokenizer:
String reduceToOneLine(String input){
    // Note that this means both \r and \n are tokens, not that they have to appear together.
    StringTokenizer tokenizer = new StringTokenizer(input, "\r\n");
    StringBuffer output = new StringBuffer();
    while(tokenizer.hasMoreTokens()){
        output.append(tokenizer.nextToken());
    }
    return output.toString();
}

This splits the string on line breaks, then adds each line to a new string (the tokenizer treats multiples of its delimiter as one, so you'll be left with just one line break between lines).


text:
Q: Offset secondary axis in matplotlib I'm trying to bring together to different plot settings in matplotlib. I found nice examples for each of them in the matplotlib example gallery/documentation and stack but I couldn't find anything on my specific problem.
So what I know so far is, how to add one or more axes with offset y-axis for plotting different data with respect to the same x-axis, by using ax.twinx(). The third y-axis is called parasite axis in the example Parasite  axis demo. However, if you want to add an additional axis which is just a scaled version of the existing one, you can use ax.secondary_yaxis(), as shown in the Secondary axis demo. There is no additional data to be plotted.
What I could not achieve so far is a secondary y-axis which is offset from the original one. This can be very helpful to make plots more readable across scientific communities. For instance, while some scientists use frequency as reference for the electromagnetic spectrum, others use the wavelength or the wavenumber. Afsar [1] used a very convenient axis labeling which includes all the three variables in the same plot:

I would like to the something similar, just on the y-axis instead of the x-axis. Is there a way to offset the secondary axis from the primary axis? I tried a few parameters but couldn't figure it out.
Thank you for any help!
[1] Afsar, Mohammed Nurul. "Precision Millimeter-Wave Measurements of Complex Refractive Index, Complex Dielectric Permittivity, and Loss Tangent of Common Polymers." IEEE Transactions on Instrumentation and Measurement IM–36, no. 2 (June 1987): 530–36. https://doi.org/10.1109/TIM.1987.6312733.
[1]:

A: A complete example.  The third-to-last line is the relevant one.
import matplotlib.pyplot as plt
import numpy as np
import datetime

dates = [datetime.datetime(2018, 1, 1) + datetime.timedelta(hours=k * 6)
         for k in range(240)]
temperature = np.random.randn(len(dates)) * 4 + 6.7
fig, ax = plt.subplots(constrained_layout=True)

ax.plot(dates, temperature)
ax.set_ylabel(r'$T\ [^oC]$')
plt.xticks(rotation=70)

def date2yday(x):
    """Convert matplotlib datenum to days since 2018-01-01."""
    y = x - mdates.date2num(datetime.datetime(2018, 1, 1))
    return y

def yday2date(x):
    """Return a matplotlib datenum for *x* days after 2018-01-01."""
    y = x + mdates.date2num(datetime.datetime(2018, 1, 1))
    return y

secax_x = ax.secondary_xaxis('top', functions=(date2yday, yday2date))
secax_x.set_xlabel('yday [2018]')

def celsius_to_fahrenheit(x):
    return x * 1.8 + 32

def fahrenheit_to_celsius(x):
    return (x - 32) / 1.8

secax_y = ax.secondary_yaxis(
    'right', functions=(celsius_to_fahrenheit, fahrenheit_to_celsius))
secax_y.set_ylabel(r'$T\ [^oF]$')

def celsius_to_anomaly(x):
    return (x - np.mean(temperature))

def anomaly_to_celsius(x):
    return (x + np.mean(temperature))

# document use of a float for the position:
secax_y2 = ax.secondary_yaxis(
    1.2, functions=(celsius_to_anomaly, anomaly_to_celsius))
secax_y2.set_ylabel(r'$T - \overline{T}\ [^oC]$')

plt.show()

A: Here is another approach, although maybe it's more of a hack:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

@FuncFormatter
def twin1_formatter(x, pos):
    return f'{x/np.pi*180:.0f}'

@FuncFormatter
def twin2_formatter(x, pos):
    return f'{x/np.pi:.1f} $\pi$'

data = np.arange(0, 2*np.pi, 0.1)

fig, ax = plt.subplots()

twin1 = ax.twiny()
twin1.spines['top'].set_position(('axes', 1.2))
twin1.set_xlabel('Degrees')
twin1.xaxis.set_major_formatter(FuncFormatter(twin1_formatter))

twin2 = ax.twiny()
twin2.set_xlabel('Pies')
twin2.xaxis.set_major_formatter(FuncFormatter(twin2_formatter))
twin2.xaxis.set_ticks(np.array([0, 1/2, 1, 3/2, 2])*np.pi)

ax.plot(data, np.sin(data))
ax.set_xlabel('Radians')
twin1.set_xlim(ax.get_xlim())
twin2.set_xlim(ax.get_xlim())
fig.show()


text:
Q: Getting AC potential in PCB GND I'm using IRM-30-12 for power supply for my PCB. This SMPS doesn't have an earthing connection pin as it has Class 2 isolation protection.There is an AC potential is generated at the circuit GND which is initially found out by using a tester.
When I'm connecting the earthing pin(The earthing of the supply is left open as I'm using a plastic enclosure)directly to the circuit GND the AC potential is no longer exists. Is it the correct approach?
My question is
1. What might be the cause of the generated AC potential?
2. As I have gone through some possible solutions I have found the following LINK;

I have connected the circuit ground to a metal and again connected the earthing wire to the metal. What impact will it have on my PCB?

A:
What might be the cause of the generated AC potential?

To meet EMI limits on the output DC voltage of an unearthed power supply, usually a capacitor is placed between one of the DC output lines and the AC rectified bus voltage on the primary. It isn't perfect but it does the job. See this example here of the internal working of a wall-wart: -

Picture taken from here.
And, the impact of adding this capacitor is that it couples the input AC voltage to the output DC terminals but in a safe way so as not to risk electrocution but, if you looked at the DC output your would see a voltage waveform at the same frequency as the AC power. Of course shorting the DC output to "real" ground will remove this safely.

What impact will it have on my PCB?

Probably no impact but, the devil is in the detail and we have no detailed knowledge of what your circuit is or how you have precisely impemented the grounding.


text:
Q: Docker container can't run jacoco agent with Java 12 I'm trying to run java docker image with my spring boot app. I want to use it for API testing and I want to collect code coverage as well. However I'm not able to make jacocoagent run inside docker container. Am I doing something wrong? Am I missing some setting somewhere? Regular bootJar runs smoothly when I don't add agent. Moreover I'm able to execute the same command without problem outside of docker env. So it doesn't seem to be a java bug.
Here is my docker-compose file:
version: '3.7'
services:
  bootJarTestApi:
    image: openjdk:12.0.1-jdk-oracle
    environment:
      - "JAVA_TOOL_OPTIONS=-javaagent:/jacoco-agent/jacocoagent.jar=destfile=/jacoco-report/apiDockerTest.exec,output=file"
    ports:
      - 2020:2020
      - 2021:2021
    volumes:
      - "./build/libs/bootJar.jar:/bootJar.jar"
      - "./build/libs/jacoco-agent/jacocoagent.jar:/jacoco-agent/jacocoagent.jar"
      - "./build/jacoco/:/jacoco-report/"
    entrypoint: ["java", "-jar",
#                 "-javaagent:/jacoco-agent/jacocoagent.jar=destfile=/jacoco-report/apiDockerTest.exec,output=file",
                 "-Dspring.profiles.active=dev",
                 "/bootJar.jar"]

When I try to run it, docker says:
bootJarTestApi_1  | Picked up JAVA_TOOL_OPTIONS: -javaagent:/jacoco-agent/jacocoagent.jar=destfile=/jacoco-report/apiDockerTest.exec,output=file
bootJarTestApi_1  | FATAL ERROR in native method: processing of -javaagent failed
bootJarTestApi_1  | mmap failed for CEN and END part of zip file
bootJarTestApi_1  | Unexpected error (103) returned by AddToSystemClassLoaderSearch
bootJarTestApi_1  | Unable to add /jacoco-agent/jacocoagent.jar to system class path - the system class loader does not define the appendToClassPathForInstrumentation method or the method failed
bootJarTestApi_1  | #
bootJarTestApi_1  | # A fatal error has been detected by the Java Runtime Environment:
bootJarTestApi_1  | #
bootJarTestApi_1  | #  SIGSEGV (0xb) at pc=0x00007f85d2728b07, pid=1, tid=7
bootJarTestApi_1  | #
bootJarTestApi_1  | # JRE version: OpenJDK Runtime Environment (12.0.1+12) (build 12.0.1+12)
bootJarTestApi_1  | # Java VM: OpenJDK 64-Bit Server VM (12.0.1+12, mixed mode, sharing, tiered, compressed oops, g1 gc, linux-amd64)
bootJarTestApi_1  | # Problematic frame:
bootJarTestApi_1  | # C  [libc.so.6+0x37b07]  abort+0x297
bootJarTestApi_1  | #
bootJarTestApi_1  | # Core dump will be written. Default location: Core dumps may be processed with "/usr/lib/systemd/systemd-coredump %P %u %g %s %t %c %h %e" (or dumping to //core.1)
bootJarTestApi_1  | #
bootJarTestApi_1  | # An error report file with more information is saved as:
bootJarTestApi_1  | # //hs_err_pid1.log
bootJarTestApi_1  | #
bootJarTestApi_1  | # If you would like to submit a bug report, please visit:
bootJarTestApi_1  | #   http://bugreport.java.com/bugreport/crash.jsp
bootJarTestApi_1  | #
bootJarTestApi_1  |
bootJarTestApi_1  | [error occurred during error reporting (), id 0xb, SIGSEGV (0xb) at pc=0x00007f85d2728b07]

A: Looks like the key line in error message is

mmap failed for CEN and END part of zip file

search of this line in Google shows that it is always related to filesystem access, but can be caused by many things - from wrong OS configuration up to strange behaviors of some filesystems and bugs in JVM. And so I think that this is unrelated to particular agent, i.e. unrelated to JaCoCo agent, and you should be able to reproduce the same with any other agent.
You can try

*

*to use volume not for an agent file, but for directory;

*to not use volume at all for agent and put it directly into image.


text:
Q: how to handle exception where one of the model is having error. Model[9] in the view i have one model in that there are 10 classes. im getting error at Model[9]. how to handle null exception at Model[9].
error
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

  @Model[9].status

N-7 NEW ST SR @Model[9].deviceid.ToUpper().Substring(11, 5)

                        @if (@Model[9].status.ToUpper() == "CLOSE")
                        {

                        }
                        else
                        {

                        }


text:
Q: Identifying a PDE from an old notebook A friend of mine ran across the following PDE in some notes from an old friend of theirs:
$$
\theta \frac{d^2\theta}{dt^2} + \delta\frac{d\theta}{dt} + \frac{dL}{d\alpha}(\rho_1-\rho_2)\alpha = \frac{dR}{dB}S_2B\,.
$$
The $L$ here might be a different character, it's garbled in the writing.
I like a good math mystery so I did some poking around for it but couldn't find anything. They indicated it might have something to do with balancing things that wobble, possibly rockets. Any ideas?


text:
Q: Draw a triangle with 3 sides given I want to draw a triangle with only the 3 sides length. (In C# Winforms)
Example: S1(3), S2(4), S3(5) with SN(x) as the length of each side.
I've tried to do this and the result is not a right triangle but it looks like it.
For the first side i just draw it like a line. and after i triy to find the angle with Pythagore and the same for the second one, but i realised that if i enter (5,4,3) it's something else.I'm just try to understand how can i find coordinates of a triangle with only the length of the sides.
  Point a = new Point(0, 0);
  Point b = new Point(s1, 0);

  double y = (Math.Pow(s1, 2) + Math.Pow(s3, 2) - Math.Pow(s2, 2)) / (2 * s1);
  double x = Math.Sqrt(Math.Pow(s3, 2) - Math.Pow(y, 2));

  Point c = new Point((int)x, (int)y);
  e.Graphics.DrawLine(Pens.Black, a, b);
  e.Graphics.DrawLine(Pens.Black, b, c);
  e.Graphics.DrawLine(Pens.Black, c, a);

That's the result:

Can someone help me? because I think I don't understand how can I do this.

A: This is more a math problem. At point A you have the sides s1, s3 with opposing side s2. The cosine formula then gives
2*s1*s3*cos(alpha) = s1^2+s3^2-s2^2.

Now the cosine is the projection of the angle to the horizontal axis, so you should have
x = s3*cos(alpha) = (s1^2+s3^2-s2^2)/(2*s1)

and correspondingly
y = sqrt(s3^2-x^2).

For the test side lengths 3,4,5 this would give
x = (3^2 + (5^2-4^2))/(2*3) = 3
y = sqrt(5^2-3^2) = 4

producing the points for the rectangular triangle.


text:
Q: Data set for storing objects in java Let's say I have multiple Objects to be stored:
Person ------------ Employee ------------ Sales Engineer
  |                    |
Customer          Field Engineer

So: Person, Customer, Employee, Sales Engineer, Field Engineer.
I need to keep track of all of these...what is the best way to store them? In an ArrayList? A custom ArrayList?
The way they are stored also may affect future expansion - in the future, these objects might be generated by fields from an SQL Server. (Also, this is an Android App - so that could be a factor.)

A: You'll want a List<Person>.  Your diagram suggests inheritance, so you'll want to have a collection of the super class and let polymorphism do the rest.
Your code can do this:
List<Person> people = new ArrayList<Person>();
// Any class that extends person can be added
people.add(new Customer());
people.add(new FieldEngineer());
for (Person person : people) {
    System.out.println(person);
}

Your design as expressed won't allow Engineers to be Customers, or Sales engineers to go into the Field, but that's the curse of inheritance in cases like yours.
A better design, if you need the flexibility, might be to keep the Person class and assign a Person a Role in decorator fashion.
A decorator would add behavior using composition rather than inheritance, like this:
public class Customer {

    private Person person;

    public Customer(Person p) { this.person = p; }

    public void buyIt() { // do something customer like here }
}

public class FieldEngineer {

    private Person person;

    public FieldEngineer(Person p) { this.person = p; }

    public void fixIt() { // do something field engineer like here }
}

A: Use a heterogenous list -- in java you can use generics like this List <Person>

A: If you are uncertain about how you will need to access objects in the future you may find that a HashTable <Person> affords a wide degree of flexibility.
Since it uses key-value pairs you can retrieve a specific object quickly and the .keys() method offers a means to traverse the entire set iteratively if you find that necessary.

A: I am assuming all of the objects are a part of a set?
Ideally, the Person should have a get/setCustomer and the Employee should have a get/setFieldEngineer and then the structure should be something like:
class CustomerRelationship{
    public Employee employee;
    public SalesEngineer salesEngineer;
    public Person customer;
}

If the objects are not parts of a set, but are a list of Object, then you might want to reconsider your design. Or you could use instanceof everywhere ( bad ).


text:
Q: Athena Query bucket location I have setup crawler table for CUR reports. Now while setting up Athena table for querying, it is asking for S3 location to store query results. Can I give same location as S3 bucket that has been created to store parquet CUR files?
Please suggest.


text: Q: Angular 2 multiselect dropdown in angular 4 configuration in systemjs.config.js file I want to use angular2-multiselect-dropdown plug in for angular 4 application. I want to know how to configure the same in systemjs.config.js


text:
Q: Why does Tensorflow 2.4.1 not find my GPU? I'm having trouble using my GPU with tensorflow.
I pip installed tensorflow-gpu 2.4.1
I also installed CUDA 11.2 and cudnn 11.2, following the procedure from: https://docs.nvidia.com/deeplearning/cudnn/install-guide/index.html#installwindows , also checking that all paths are fine and the libraries are at the correct place.
However, when  I run tf.config.experimental.list_physical_devices('GPU') on my Jupyter Notebook, it doesn't find my GPU.
I also run tf.test.is_built_with_cuda(), which is returning True.
So is the problem that my GPU isn't supporting the current version of CUDA or cudnn? My GPU is "NVIDIA GeForce 605"

A: NVIDIA GeForce 605 card based on Fermi 2.0 architecture and I can see only Ampere,Turing, Volta, Pascal, Maxwell and Kepler are supported for CUDA 11.x.
As per @talonmies, GeForce 605 card never had supported for Tensorflow.
You can refer this for NVIDIA GPU cards with CUDA architectures are supported for Tensorflow.
For GPUs with unsupported CUDA architectures to use different versions of the NVIDIA libraries, you can refer Linux build from source guide.
Finally, you can also refer tested built configurations for Windows and linux.


text:
Q: .h and .m files in Objective-c I'm on a quest for knowledge today.
I'm working on some code for work, and after review I had a complete Brain Fart and can't remember why we do something with the .h and .m files in objective-c

*

*I was wondering why do we import files and declare method names in the .h files? (I know it has to do with processing, but can't remember the details)

*Why do we sometimes import files directly into the .m file and not in the .h files in some cases.

*When you declared a method in the .h file are you doing this because the class and/or libraries you are using don't perform a function you need them too?

*Is there ever a case where you declared a method that doesn't exist in any of your libraries or your .h file in your .m file?

Thanks everyone I hope that all made sense.

A: *

*Because the .h file is the class's public interface

*Because putting the imports into the .m file makes them private and keeps the dependencies out of the .h file (prevents excessive dependency importing and potential circularities)

*You're doing it to publicly state that you provide that service

*You shouldn't, if it doesn't exist you can't use it (though you may declare things that you hope will exist and check before you actually try to use them)

Bonus extra for 2. In your .h file you should endeavour to have the minimum number of imports possible (just the superclass and any protocols you publicly implement) and use @class for everything else. This minimises the dependency implications.

A: *

*It's used to separate between the public and private parts of a class. The .m file is the implementation. It is where all the logic goes, all the data is processed and stored, etc... The .h file is the interface of that class. It's literally like an API for your own class. It tells other classes how to use it and how to interface with it.

*You import a class when you reference it in a file. If you reference something (i.e. a property) in the interface then you import it in the .h. If you only reference it in the implementation then you import it in the .m.

*Any methods declared in the .h are there so that other classes know that they can run it. i.e. they are public methods. Try and remove a declaration and then call that method. You'll get a warning.

*No, this wouldn't make sense. Unless you were part way through writing your program and declared it for testing purposes.


text:
Q: PHP - Combining Multiple Items Into One I am attempting to create an end-user page where I present different servers that are available to check-out.  A server at any given time can have either an "Available" status or a "Reserved" status.  I'm using a MySQL backend.  This is how I am doing my query:
SELECT *, COUNT(CASE WHEN Status = 'Available' THEN 1 ELSE NULL END) AS Amount
FROM products GROUP BY id

This is the result I get:
id,Server_Type,Status,Amount
1,BL460,Available,1
2,BL460,Available,1
3,BL460,Reserved,0
4,BL460,Reserved,0
5,BL460,Reserved,0
6,DL360,Available,1
7,DL360,Reserved,0
8,DL360,Reserved,0

Where Reserved is equal to 0, and Available is equal to 1.  I only want the end-user to be able to checkout a server in Available status.
To the question:  What I want to do in the page is present the list of servers on the page in this way, where Available is equal to the amount:
BL460 - Amount: 2
DL360 - Amount: 1

How can I achieve this format in PHP?

A: Another option is a crosstab query -
SELECT `Status`,
SUM(IF(`Server_Type` = 'BL460' AND `Status` = 'Available', `Amount`, 0)) AS `BL460`,
SUM(IF(`Server_Type` = 'DL360' AND `Status` = 'Available', `Amount`, 0)) AS `DL360`
FROM `products`
GROUP BY `Status`

Your table would look like this -
Status    |    BL460    |    DL360    |
Available |        2    |        1    |
Reserved  |        0    |        0    |

Here is an EXAMPLE
Even better would be to flip things around -
SELECT `server_type`,
SUM(IF(`status` = 'Available', 1, 0)) AS `Available`,
SUM(IF(`status` = 'Reserved', 1, 0)) AS `Reserved`
FROM `servers`
GROUP BY `server_type`;

Which would result in a table that looks like this (based on data in the fiddle) -
server_type    |    Available    |    Reserved
BL460          |            3    |           1
DL360          |            1    |           2

Here is that EXAMPLE
Here I could continue to add servers to the table without having to worry about adding them to the query as you would have to do in the first query. If you add an additional status you would have to change the query.
Note in both cases there is no need for an Amount column as the status is the item counted. By placing the load on the database server it makes it much easier to output the HTML as you are just going row bu row as you normally would.

A: Well, that would probably be easier if you do it directly in your SQL query:
SELECT Server_Type, COUNT(*) AS Count FROM products WHERE Status = 'Available' GROUP BY Server_Type

This should give you exactly the table you want.
If you want to do it in PHP, the easiest solution would probably be to loop through your SQL result and count the number of available servers per Server_Type in an associative array where the Server_Type is your array key:
$amounts = array();

foreach($sql_result as $entry) {
    if($entry['Amount'] == 1) {
        if(isset($amounts[$entry['Server_Type']])) {
            $amounts[$entry['Server_Type']]++;
        } else {
            $amounts[$entry['Server_Type']] = 1;
        }
    }
}

echo $amounts;

Edit: in order to print the values as described in the question, you could use the following code snippet:
foreach($amounts as $name=>$amount) {
    echo $name + " - Amount: " + $amount + "<br>";
}


text:
Q: Push ViewController inside View that was presented with hero animation The title pretty much says it all. I have a ViewController which I present like this:
let communityVC = self.storyboard?.instantiateViewController(withIdentifier: "CommunityVC") as! CommunityViewController
communityVC.hero.modalAnimationType = .zoomSlide(direction: .right)
let addButtonHeroID = "addWishButtonID"
self.addButton.heroID = addButtonHeroID
communityVC.homeButton.heroID = addButtonHeroID
self.present(communityVC, animated: true, completion: nil)

The thing is that insice comunityVC I would like to push another ViewController. Is that somehow possible? I couldnt really find a Swift solution that is working.

A: You need to present communityVC after embedding the UINavigationController, then you can push the view controller inside communityVC, so you can push ViewController by using navigationController?.pushViewController(vc, animated: true) from communityV
    let communityVC = self.storyboard?.instantiateViewController(withIdentifier: "CommunityVC") as! CommunityViewController
    let navController = UINavigationController(rootViewController: communityVC)
    communityVC.hero.modalAnimationType = .zoomSlide(direction: .right)
    let addButtonHeroID = "addWishButtonID"
    self.addButton.heroID = addButtonHeroID
    communityVC.homeButton.heroID = addButtonHeroID
    self.present(navController, animated: true, completion: nil)


text:
Q: Shifting from OpenCV GUI to Tkinter Form I have this code that performs the mouse functions using eyes and other facial gestures with opencv and dlib. I am running this code using a button click from a tkinter window. When this code starts to run, that tkinter window freezes (i.e, I cannot click any other button from that).
Is there a way that I can make the frame used by opencv a Top level, like top level frames in tkinter so that it doesn't freezes any other frames, or how can I replace opencv frame with Tkinter toplevel frame.
P.S: I have been on it for two days, literally tried anything I can find on the internet and can't seem to find a solution.
    _, frame = vid.read()
frame = cv2.flip(frame, 1)
frame = imutils.resize(frame, width=cam_w, height=cam_h)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

This is the part where changes will be made I guess. Full code is shared below.
from imutils import face_utils
from utils import *
import numpy as np
import pyautogui as pag
import imutils
import dlib
import cv2

# Thresholds and consecutive frame length for triggering the mouse action.
MOUTH_AR_THRESH = 0.3
MOUTH_AR_CONSECUTIVE_FRAMES = 3
EYE_AR_THRESH = 0.20
EYE_AR_CONSECUTIVE_FRAMES = 5
WINK_AR_DIFF_THRESH = 0.001
WINK_AR_CLOSE_THRESH = 0.2
WINK_CONSECUTIVE_FRAMES = 4

# Initialize the frame counters for each action as well as
# booleans used to indicate if action is performed or not
MOUTH_COUNTER = 0
EYE_COUNTER = 0
WINK_COUNTER = 0
INPUT_MODE = False
EYE_CLICK = False
LEFT_WINK = False
RIGHT_WINK = False
SCROLL_MODE = False
ANCHOR_POINT = (0, 0)
WHITE_COLOR = (255, 255, 255)
YELLOW_COLOR = (0, 255, 255)
RED_COLOR = (0, 0, 255)
GREEN_COLOR = (0, 255, 0)
BLUE_COLOR = (255, 0, 0)
BLACK_COLOR = (0, 0, 0)

# Initialize Dlib's face detector (HOG-based) and then create
# the facial landmark predictor
shape_predictor = "model/shape_predictor_68_face_landmarks.dat"
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(shape_predictor)

# Grab the indexes of the facial landmarks for the left and
# right eye, nose and mouth respectively
(lStart, lEnd) = face_utils.FACIAL_LANDMARKS_IDXS["left_eye"]
(rStart, rEnd) = face_utils.FACIAL_LANDMARKS_IDXS["right_eye"]
(nStart, nEnd) = face_utils.FACIAL_LANDMARKS_IDXS["nose"]
(mStart, mEnd) = face_utils.FACIAL_LANDMARKS_IDXS["mouth"]

# Video capture
vid = cv2.VideoCapture(0)
resolution_w = 1366
resolution_h = 768
cam_w = 640
cam_h = 480
unit_w = resolution_w / cam_w
unit_h = resolution_h / cam_h

while True:
    # Grab the frame from the threaded video file stream, resize
    # it, and convert it to grayscale
    # channels)
    _, frame = vid.read()
    frame = cv2.flip(frame, 1)
    frame = imutils.resize(frame, width=cam_w, height=cam_h)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Detect faces in the grayscale frame
    rects = detector(gray, 0)

    # Loop over the face detections
    if len(rects) > 0:
        rect = rects[0]
    else:
        cv2.imshow("Frame", frame)
        key = cv2.waitKey(1) & 0xFF
        continue

    # Determine the facial landmarks for the face region, then
    # convert the facial landmark (x, y)-coordinates to a NumPy
    # array
    shape = predictor(gray, rect)
    shape = face_utils.shape_to_np(shape)

    # Extract the left and right eye coordinates, then use the
    # coordinates to compute the eye aspect ratio for both eyes
    mouth = shape[mStart:mEnd]
    leftEye = shape[lStart:lEnd]
    rightEye = shape[rStart:rEnd]
    nose = shape[nStart:nEnd]

    # Because I flipped the frame, left is right, right is left.
    temp = leftEye
    leftEye = rightEye
    rightEye = temp

    # Average the mouth aspect ratio together for both eyes
    mar = mouth_aspect_ratio(mouth)
    leftEAR = eye_aspect_ratio(leftEye)
    rightEAR = eye_aspect_ratio(rightEye)
    ear = (leftEAR + rightEAR) / 2.0
    diff_ear = np.abs(leftEAR - rightEAR)

    nose_point = (nose[3, 0], nose[3, 1])

    # Compute the convex hull for the left and right eye, then
    # visualize each of the eyes
    mouthHull = cv2.convexHull(mouth)
    leftEyeHull = cv2.convexHull(leftEye)
    rightEyeHull = cv2.convexHull(rightEye)
    cv2.drawContours(frame, [mouthHull], -1, YELLOW_COLOR, 1)
    cv2.drawContours(frame, [leftEyeHull], -1, YELLOW_COLOR, 1)
    cv2.drawContours(frame, [rightEyeHull], -1, YELLOW_COLOR, 1)

    for (x, y) in np.concatenate((mouth, leftEye, rightEye), axis=0):
        cv2.circle(frame, (x, y), 2, GREEN_COLOR, -1)

    # Check to see if the eye aspect ratio is below the blink
    # threshold, and if so, increment the blink frame counter
    if diff_ear > WINK_AR_DIFF_THRESH:

        if leftEAR < rightEAR:
            if leftEAR < EYE_AR_THRESH:
                WINK_COUNTER += 1

                if WINK_COUNTER > WINK_CONSECUTIVE_FRAMES:
                    pag.click(button='left')

                    WINK_COUNTER = 0

        elif leftEAR > rightEAR:
            if rightEAR < EYE_AR_THRESH:
                WINK_COUNTER += 1

                if WINK_COUNTER > WINK_CONSECUTIVE_FRAMES:
                    pag.click(button='right')

                    WINK_COUNTER = 0
        else:
            WINK_COUNTER = 0
    else:
        if ear <= EYE_AR_THRESH:
            EYE_COUNTER += 1

            if EYE_COUNTER > EYE_AR_CONSECUTIVE_FRAMES:
                SCROLL_MODE = not SCROLL_MODE
                # INPUT_MODE = not INPUT_MODE
                EYE_COUNTER = 0

                # nose point to draw a bounding box around it

        else:
            EYE_COUNTER = 0
            WINK_COUNTER = 0

    if mar > MOUTH_AR_THRESH:
        MOUTH_COUNTER += 1

        if MOUTH_COUNTER >= MOUTH_AR_CONSECUTIVE_FRAMES:
            # if the alarm is not on, turn it on
            INPUT_MODE = not INPUT_MODE
            # SCROLL_MODE = not SCROLL_MODE
            MOUTH_COUNTER = 0
            ANCHOR_POINT = nose_point

    else:
        MOUTH_COUNTER = 0

    if INPUT_MODE:
        cv2.putText(frame, "READING INPUT!", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, RED_COLOR, 2)
        x, y = ANCHOR_POINT
        nx, ny = nose_point
        w, h = 60, 35
        multiple = 1
        cv2.rectangle(frame, (x - w, y - h), (x + w, y + h), GREEN_COLOR, 2)
        cv2.line(frame, ANCHOR_POINT, nose_point, BLUE_COLOR, 2)

        dir = direction(nose_point, ANCHOR_POINT, w, h)
        cv2.putText(frame, dir.upper(), (10, 90), cv2.FONT_HERSHEY_SIMPLEX, 0.7, RED_COLOR, 2)
        drag = 18
        if dir == 'right':
            pag.moveRel(drag, 0)
        elif dir == 'left':
            pag.moveRel(-drag, 0)
        elif dir == 'up':
            if SCROLL_MODE:
                pag.scroll(40)
            else:
                pag.moveRel(0, -drag)
        elif dir == 'down':
            if SCROLL_MODE:
                pag.scroll(-40)
            else:
                pag.moveRel(0, drag)

    if SCROLL_MODE:
        cv2.putText(frame, 'SCROLL MODE IS ON!', (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.7, RED_COLOR, 2)

    # Show the frame
    cv2.imshow("Frame", frame)
    key = cv2.waitKey(1) & 0xFF

    # If the `Esc` key was pressed, break from the loop
    if key == 27:
        break

# Do a bit of cleanup
cv2.destroyAllWindows()
vid.release()


text:
Q: How do I use ASMifier on inner classes? I am trying to get an ASMified version of an inner class in java. My command looks something like this java -classpath "asm-all-3.3.1.jar:myjar.jar" org.objectweb.asm.util.ASMifierClassVisitor path/to/my/class$inner.class But it seems to only return the ASMified version of the outer class, what am I doing wrong here?

A: You get to the problem when you try
echo path/to/my/outer$inner.class

which will print
path/to/my/outer.class

Your shell interprets $inner as as variable reference and since you likely have no such variable defined in your environment, it will substitute it with an empty text, which in this case leads to the path and name of the outer class.
Which demonstrates why silently doing the wrong thing is worse than failing with an error message (or exception).
When you prepend the dollar sign with a backslash, i.e. path/to/my/outer\$inner.class, it will be interpreted as a literal $ and work. Or lead to other errors, as the other answer mentions, your ASM version is really old and may have problems parsing newer class files.

A: How about using an ASM version more recent than from 2008, maybe one which can also handle classes more recent than Java 6? I am suggesting these:

*

*https://search.maven.org/artifact/org.ow2.asm/asm/9.2/jar

*https://search.maven.org/artifact/org.ow2.asm/asm-util/9.2/jar
I quickly tried something like this (Git Bash on Windows 10):
java -cp "asm-9.2.jar;asm-util-9.2.jar" org.objectweb.asm.util.ASMifier MyClass\$MyInnerClass.class

In Cmd.exe it would be:
java -cp asm-9.2.jar;asm-util-9.2.jar org.objectweb.asm.util.ASMifier MyClass$MyInnerClass.class

Both variants work nicely.


text:
Q: XSL FO: How to determine page break? I've a situation where I have 2 block-containers - if they are short enough, the should be on one page, separated by a line.
But if not, then the 2. block-container has to start on the next page and there should be NO line between them.
How can I do that (because I don't know how I can check if inside a flow is a page-break)? Is there any param I can use to check in FO, if the block starts after a page-break ore something else?
Thanks for any help !!
Frangoo

A: You could set the following attribute in the second block container
keep-together.within-page="always"

With this the XSL-FO processor will make sure, that the whole block will remain on the same page. So it would look something like this:
<fo:block keep-together.within-page="always"> <!-- any other attribute as necessary -->
    ...
</fo:block>


text:
Q: Replace and Split Multiple \n I have the following string that I want to split on the "\n" but I need to remove/replace all of the occurances of multiple "\n\n";
Here is my sample string:
"\n01:05 PM\n901\nNew York Mets \n\n\n\n\n\n\n\n\n \n+125\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"

So that I end up with an array like
1:05 PM
901
New York Mets
+125
I've tried,
 string adjRow = row.InnerText.Replace("\n", "");

Is there a single Regex Pattern that will work?
Added the following and seems to work.
    RegexOptions options = RegexOptions.None;
                    Regex regex = new Regex("[\n]{2,}", options);
                    string adjRow = regex.Replace(tempRow, "\n");

Here is the result,

"\n01:05 PM\n901\nNew York Mets \n \n+128\n \nOv\n8½\n-113\no\n"


text:
Q: How exactly do i preform basic operations involving complement sets when the universal set equals N (Natural Numbers)? If A = {2,4,6,8,10}  B = {1,3,5,7,9} X or U = N {1,2,3,...}
Find:

*

*Ac ∩ Bc

*Ac - Bc

*(A ∩ B)c
Since the compliment set of A is all the elements of the Universal set that are non-existent in A, and the Universal set in this example is equal to natural numbers (infinite), how do i list all the numbers, is there a specific way to do this or do i just write it as Ac = {1,3,5,7,9,11,..}
Thanks,

A: In general, you can use set-builder notation.  For instance, the complement of $\{3,4,5\}$ can be written
$$ \{ x \in \mathbb{N} \mid x < 3\} \cup \{x \in \mathbb{N} \mid x > 5 \} \enspace. $$
There are many variations on this notation, but the main idea is to define a set by the properties satisfied by its elements.  These properties are specified by formulae like $x \leq 10$ or $x = 2n+1$ for $n \in \mathbb{N}$ (to specify odd natural numbers).


text:
Q: How to rotate canvas bitmap without cut? I am new to android,
I want to rotate a canvas bitmap without cut.
I used the below code, but when I rotate the image it cuts off a portion from the bitmap.
 float px = iv_photo.getWidth()/2;
 float py = iv_photo.getHeight()/2;
 matrix.postTranslate(-canvas.getWidth()/2, -canvas.getHeight()/2);
 matrix.postRotate(90);
 matrix.postTranslate(px, py);
 canvas.drawBitmap(bitmap, matrix, paint);


text:
Q: Why does "Watchdog: BUG: Soft lockup CPU" errors occur when running openstack containers in docker I just deployed openstack using kolla and kolla-ansible stable/pike version. I deployed on one control node and one compute node. Both nodes are Dell PowerEdge 2950 servers that are running Centos 7. The deployment It worked but while I try to use the horizon dashboard, the control node is very slow and locks up and the terminal outputs the following:
Message from syslogd@openstackcontroller at Nov  7 21:46:39 ...
 kernel:NMI watchdog: BUG: soft lockup - CPU#1 stuck for 23s! [runc:[2:INIT]:10527]

Message from syslogd@openstackcontroller at Nov  7 21:46:39 ...
 kernel:NMI watchdog: BUG: soft lockup - CPU#4 stuck for 23s! [fluentd:5005]

Message from syslogd@openstackcontroller at Nov  7 21:46:39 ...
 kernel:NMI watchdog: BUG: soft lockup - CPU#8 stuck for 23s! [keepalived:10664]

Message from syslogd@openstackcontroller at Nov  7 21:46:39 ...
 kernel:NMI watchdog: BUG: soft lockup - CPU#15 stuck for 23s! [java:5604]

Message from syslogd@openstackcontroller at Nov  7 21:46:39 ...
 kernel:NMI watchdog: BUG: soft lockup - CPU#5 stuck for 23s! [neutron-openvsw:3101]

Message from syslogd@openstackcontroller at Nov  7 21:46:39 ...
 kernel:NMI watchdog: BUG: soft lockup - CPU#3 stuck for 23s! [cinder-schedule:3193]

Message from syslogd@openstackcontroller at Nov  7 21:46:39 ...
 kernel:NMI watchdog: BUG: soft lockup - CPU#7 stuck for 23s! [java:6186]

Message from syslogd@openstackcontroller at Nov  7 21:46:39 ...
 kernel:NMI watchdog: BUG: soft lockup - CPU#11 stuck for 23s! [docker-containe:6601]

Message from syslogd@openstackcontroller at Nov  7 21:46:39 ...
 kernel:NMI watchdog: BUG: soft lockup - CPU#12 stuck for 22s! [keepalived:4295]

Message from syslogd@openstackcontroller at Nov  7 21:46:39 ...
 kernel:NMI watchdog: BUG: soft lockup - CPU#10 stuck for 22s! [keepalived:10666]

Message from syslogd@openstackcontroller at Nov  7 21:46:39 ...
 kernel:NMI watchdog: BUG: soft lockup - CPU#9 stuck for 22s! [gmain:939]

Message from syslogd@openstackcontroller at Nov  7 21:46:39 ...
 kernel:NMI watchdog: BUG: soft lockup - CPU#13 stuck for 22s! [node:3261]

Message from syslogd@openstackcontroller at Nov  7 21:46:39 ...
 kernel:NMI watchdog: BUG: soft lockup - CPU#6 stuck for 22s! [neutron-l3-agen:5071]

Message from syslogd@openstackcontroller at Nov  7 21:46:39 ...
 kernel:NMI watchdog: BUG: soft lockup - CPU#14 stuck for 22s! [irqbalance:898]

Whenever I stop all the docker containers that are running on the control node it seems to not have any more CPU lockup errors but as soon as I start up all the docker containers again that are running openstack services on the control node it starts to run very slow again and the lockup errors start again


text:
Q: Akka-Java is throwing DeadLetterException on ask-await I have a driver/main class in file like this. (Basically I'm trying to mix STORM & AKKA). In TenderEventSpout2 class, I am trying to send and receive message to/from an actor.
public class TenderEventSpout2 extends BaseRichSpout {
        ActorSystemHandle actorSystemHandle;
        ActorSystem _system;
        ActorRef eventSpoutActor;
        Future<Object> future;
        Timeout timeout;
        String result;

    @Override
    public void open(Map map, TopologyContext topologyContext, SpoutOutputCollector spoutOutputCollector) {
        //String[] message = {"WATCH_DIR"};
        timeout = new Timeout(Duration.create(60, "seconds"));
        List<Object> messageList = new ArrayList<Object>();

        messageList.add("WATCH_DIR");

        messageList.add(this.inputDirName);

        actorSystemHandle = new ActorSystemHandle();
        _system = actorSystemHandle.getActorSystem();
        eventSpoutActor = _system.actorOf(Props.create(EventSpoutActor.class));

        future = Patterns.ask(eventSpoutActor, messageList, timeout);

    }

    @Override
    public void nextTuple() {
        String result = null;
        try{
            result = (String) Await.result(future, timeout.duration());
        }
        catch(Exception e){
            e.printStackTrace();
        }
}

My Actor is:
public class EventSpoutActor extends UntypedActor {
public ConcurrentLinkedQueue<String> eventQueue = new ConcurrentLinkedQueue<>();
Inbox inbox;
@Override
public void onReceive(Object message){// throws IOException {
    if (message instanceof List<?>) {
        System.out.println(((List<Object>)message).get(0)+"*******************");
        if(((List<Object>)message).get(0).equals("WATCH_DIR")){
            final List<Object> msg = (List<Object>)message;
            Thread fileWatcher = new Thread(new Runnable(){

                @Override
                public void run() {

                        System.out.println(msg.get(1)+"*******************");
                        try {

                            String result = "Hello";
                            System.out.println("Before Sending Message *******************");
                            getSender().tell(result, getSelf());
                            }
                        catch (Exception e) {
                            getSender().tell(new akka.actor.Status.Failure(e), getSelf());
                            throw e;
                            }

                }
            });
            fileWatcher.setDaemon(true);
            fileWatcher.start();
            System.out.println("Started file watcher");
        }
    }
    else{
        System.out.println("Unhandled !!");
        unhandled(message);
    }
}

}
I'm able to send message to my EventSpoutActor. But facing problem with receiving messages. Why is that?? I get the following message printed in console:
[EventProcessorActorSystem-akka.actor.default-dispatcher-3]
[akka://EventProcessorActorSystem/deadLetters] Message [java.lang.String]
from Actor[akka://EventProcessorActorSystem/user/$a#-1284357486] to
Actor[akka://EventProcessorActorSystem/deadLetters] was not delivered. [1]
dead letters encountered.
This logging can be turned off or adjusted with configuration settings
'akka.log-dead-letters' and 'akka.log-dead-letters-during-shutdown'.

A: So, I found out why the messages were not delivered.
 getSender().tell(result, getSelf());

This line which is supposed to send the messages to the sender, lost it's context data, when it is used inside Thread code:
 Thread fileWatcher = new Thread(new Runnable(){

            @Override
            public void run() {

                    System.out.println(msg.get(1)+"*******************");
                    try {

                        String result = "Hello";
                        System.out.println("Before Sending Message *******************");
                        getSender().tell(result, getSelf());

When I moved the "tell" code outside the thread, it worked.


text:
Q: PHP foreach loop returning extra I have a php script below that I am hoping would return all the values of a sql table. It does  do this but also returns a number and value after each of the expected lines
    $condition = "usernames = '$user'  AND password = '$pass' ";
    $result = mysql_query("SELECT * FROM userbase WHERE $condition")  ;

    $row = mysql_fetch_array($result)  ;

    foreach ($row as $k => $v) {
        echo "$k / $v <br>";
        };

    ?>

The results look like this
      0 / Mick Lathrope
      name / Mick Lathrope
      1 / op
      jobtitle / op
      2 / 07998 783 989
      phone / 07998 783 989
      3 / mwl707
      usernames / mwl707
      4 / testpass
      password / testpass

All the data is there that i need But why am I also getting a number list ?
Any help please ?

A: Use
$row = mysql_fetch_array($result, MYSQL_ASSOC) ;

to index only by column name

A: because you have used mysql_fetch_array.
If you want only columns then use mysql-fetch-assoc

A: *

*drop mysql_* for PDO or mysqli;

*you want to use mysql_fetch_assoc to get just keys and no number indexes.

A: According to this you have to specify the result type you want, otherwise you get both:
 MYSQL_ASSOC or MYSQL_NUM,
Example:
while ($row = mysql_fetch_array($result, MYSQL_NUM)){...}


text:
Q: Is it possible to remove a FieldSet and then re-Add it again? How? I got a screen that is shown according to what the costumer wants. So it depends on costumers needs.
The problem is, I have to remove 3 FieldSets when I click on "Clean Fields" button. To re-add them later when costumer clicks on "Search" button.
But when I try to remove, it says "Cannot set the FieldSet's form to null" as an IllegalArgumentException. Do you guys have any idea to help me out?
ps: If is there any Brazilians, maybe I can explain it in Portuguese.
public boolean onCleanClick() {
    this.form.remove(fsResult1);
    this.form.remove(fsResult2);
    this.form.remove(fsSubmits);
    this.profile1.setValue("0");
    this.profile2.setValue("0");
    return true;
}

public boolean onComparaPerfisClick(){
            fsSubmits.setShowBorder(false);
            fsSubmits.setColumns(2);
            fsSubmits.add(submitProfile1);
            fsSubmits.add(submitProfile2);

            form.add(fsSubmits, 2);

            fsResult1.add(processProfile1);
            fsResult1.setShowBorder(false);
            fsResult2.add(processProfile2);
            fsResult2.setShowBorder(false);

            form.add(fsResult1);
            form.add(fsResult2);

}

A: I finally could do it.
I didn't find a way to remove a fieldSet from a form, instead of it, i added the fieldset on form without a thing
when i needed i added stuff, and when i clicked on clear button, i removed stuff from fieldset, and nothing from the form


text:
Q: It takes 1 1/2 minutes to log off when I log off it takes a minute and a half because it says "session 2 has a stop order", I have no idea where it came from and how to correct it, I am fairly new to Ubuntu. thanks

A: I have got the same Problem. It occurred after clean install Ubuntu 16.04. I have looked several hours for any information and tried several things. Nothing helped. It was really annoying. In Ubuntu 15.10 the shutdown was: switch and off in less than 1 sec. Now it took at least 1,30 sec. Finally I figured out, after lots of troubleshooting, that (after disable the Ubuntu boot splash screen) a certain stop-job was running that made the shutdown slow. (Thanks to Alex!) Then I got this error report: "a stop job is running for make remote cups printers available locally" Then I tried this:
sudo systemctl stop cups-browsed.service
sudo systemctl disable cups-browsed.service

and to verify:
sudo systemctl status cups-browsed
sudo systemctl is-enabled cups-browsed

and it finally worked! Shutdown was now as good and fast as ever. (you can find this troubleshooting on: "The Annoying Cups Browsed" at the ec-cwang´s Blog!)
This might be important for those this solution is not helpful: How to find out your running stop jobs, just look up: "How do I disable the boot splash screen" on Ask Ubuntu. Then, if you start Ubuntu you get the typical Linux running command signs. If you shut Ubuntu down, mention the output. It shows you at the end what kind of stop job slows down your shutdown procedure.


text:
Q: How to perform update of nested data in a document I want to update specific field in my document. can someone please help me on this
 var q = {
            _id: mongoskin.helper.toObjectID(req.params._id)
        };
     db.collection.findOne(q., function(err, result) {
                    if (err) return next(err);
                 if (!result) {
                    return res.status(400).send({
                        error: "data not found"
                    });
                } else {
                       var fields = req.body;
                        db.collection.update(q,
                        {
                        $set: fields
                    }, function(err, result) {
                            console.log("err", err)
                            if (err) return next(err);
                            return res.send({
                                status: "success",
                                data: result
                            });
                        });
                    }

                })

Data in db is like this
[ {
            "_id": "59b631cd709fef7c4caf5dee",
            "name": "ddfdd",
            "home": {
                "a1": "f",
                "a2": "cc",
                "a3": "ccc",
                "a4": "gfr"
            },
            "about": {
                "a5": "fgfffgf",
                "a6": "fgfg",
                "a7": "werr"
},contact:{
          a8:"hfjdfh"
          a9:"hyyd"
     }
},{
            "_id": "4546565756756",
            "name": "dde",
            "home": {
                "a1": "ff",
                "a2": "cfrc",
                "a3": "ccdec",
                "a4": "gfetr"
            },
            "about": {
                "a5": "feeeffgf",
                "a6": "tyu",
                "a7": "ert"
},contact:{
          a8:"frt"
          a9:"rty"
     }
},.....]

this is just an example i have more than 250 fields in json data, i tried using split(',') it works but i dont need lengthy code/line.
i have updated my db data please check


text:
Q: Interpreting C# stack traces I have a C# stack trace that contains lines like this:
at MyNamespace.WCFService.<DispatchWork>b__4(Task`1 t)
at MyNamespace.TestMethods.<RunTestCode>d__0.MoveNext()
at MyNamespace.ServiceProxy.<CallService>d__4a.MoveNext()

What does b__4, d__0, and d__4a mean?
What's the difference between b__ and d__? Can there be any other characters (besides d and b)?
What's the stuff after __?

A: These names are automatically generated by the compiler for temp variables, yield instructions, lambdas and ...
There are only two cases which you can see these names, one of them is what compiler generates and the other is when someone chooses to obfuscate his assembly. Obfuscated assemblies have names like these for their methods and classes as well.
See this for more detailed info about what compiler does when generating names (pointed out in the comments).


text:
Q: Adding a duplicate number I'm currently experiencing the following problem.
If you have a look at the below test case:
    declare @Count  int
    ,       @id     int =   777

    declare @table table
    (   id  int identity primary key
    ,   JCid    int
    ,   line    int
    ,   udf     float   )

    insert into @table (jcid,line,udf)
    values
    (777,1,1),
    (777,2,2.1),
    (777,3,2.2),
    (777,4,2),
    (777,5,3)

    select
        @Count  =   count(left(L.udf,1))
    from    @table L
    where   L.jcid  = @id
    group by left(L.udf,1)
    having count(left(L.udf,1))>1

    select  @Count

When I run this, I get the desired results of 3, however upon developing the below trigger, I can't get the count to work out correctly:
create trigger kv_trg_JobLineNumberUpdate_AW on _btblJCTxLines
after insert, update
as

declare @LineNum            float
,       @OldLine            float
,       @id                 int
,       @Count              int
,       @Err                nvarchar(500)

set @Err                =   '--------------------------';
set @Err                =   @Err    +   @Err    +   CHAR(10);
set @Err                =   @Err    +   CHAR(10);
set @Err                =   @Err    +   'You are not allowed to change this Line Number!';

select
    @LineNum    =   iLineID
,   @OldLine    =   isnull(ufJCTxCMLineNumber,0)
,   @id         =   iJCMasterID
from    inserted

select
    @Count  =   count(left(L.ufJCTxCMLineNumber,1))
from    _btblJCTxLines L
join    inserted i on left(L.ufJCTxCMLineNumber,1) = left(i.ufJCTxCMLineNumber,1)
where   L.iJCMasterID   = @id
group by left(L.ufJCTxCMLineNumber,1)
having count(left(L.ufJCTxCMLineNumber,1))>1

begin
    if  @OldLine    =   0
        begin
            if @Count   >=  2
                begin
                    update  _btblJCTxLines
                        set ufJCTxCMLineNumber      =   cast(@LineNum as varchar)+'.'+cast(@Count as varchar)
                    from    _btblJCTxLines  L
                    join    inserted on L.idJCTxLines   =   inserted.idJCTxLines
                end
            else
                begin
                    update  _btblJCTxLines
                        set ufJCTxCMLineNumber      =   @LineNum
                    from    _btblJCTxLines  L
                    join    inserted on L.idJCTxLines   =   inserted.idJCTxLines
                end
        end
    else
        begin
            select
                @OldLine        =   deleted.ufJCTxCMLineNumber
            ,   @LineNum        =   inserted.ufJCTxCMLineNumber
            from    inserted, deleted

                if  (@OldLine <> @LineNum)
                    begin
                        raiserror(@Err, 16, 1)
                        rollback tran
                        return;
                    end
        end
end
go

The ufJCTxCMLineNumber field is the duplicate number I'm looking for.
This triggers main purpose is to ensure that the ufJCTxCMLineNumber field never has duplicates.
What happens is, a user inserts a new line, when they add a new line above any current line, I want the ufJCTxCMLineNumber field to be updated to 3.1 depending on how many duplicates there is.
How would I go about getting the correct count?
Follow this link for Sample Data.


text:
Q: How can I use Math Ceiling RoundUp How to determine even odd number I need to print data from a DataGridView on both sides of a preprinted form but:

*

*Each side has different arrangement for that info.

*Each side can only hold info from tree rows, so:

*1st, 2nd and 3rd row go on side 1;

*4th, 5th and 6th row go on side 2;

*7th, 8th and 9th row go on side 1;

*10th, 11th and 12th  go on side 2; and so on.

I will select which group to print.
I'm planning to do it this way:

*

*((row.Index) +1) / 3,

*round it up, with no decimals, to get an integer, (like in the above excel
image),

*MOD that integer by 2, (like in the above excel image).

If the result of that MOD by 2 is 1, then it will print Side 1 arrangement,
if the result of that MOD by 2 is 0, then it will print Side 2 arrangement.

*

*How do I do it in C#? I'm using VS2010 Express Edition. Also, I
wanted to use System.Math.Ceiling but I get a Namespace, decimal,
double-precision and floating-point number warnings or errors.

A: I don't see that you need to use anything like that:
int zeroBasedRow = row - 1;
int side = ((zeroBasedRow / 3) % 2) + 1;

Test code:
using System;

class Test
{
    static void Main(string[] args)
    {
        for (int row = 1; row <= 12; row++)
        {
            int zeroBasedRow = row - 1;
            int side = ((zeroBasedRow / 3) % 2) + 1;
            Console.WriteLine("Row {0} goes on side {1}", row, side);
        }
    }
}

Output:
Row 1 goes on side 1
Row 2 goes on side 1
Row 3 goes on side 1
Row 4 goes on side 2
Row 5 goes on side 2
Row 6 goes on side 2
Row 7 goes on side 1
Row 8 goes on side 1
Row 9 goes on side 1
Row 10 goes on side 2
Row 11 goes on side 2
Row 12 goes on side 2


text:
Q: Linux Mint Boot problem (on specific hardware) I am having a Lenovo Thinkpad SL400c laptop running on c2d(64 bit) processor. The problem is, Linux Mint doesn't boot in this laptop but boots well in other laptops( I tried it in dell inspiron and compaq ones)and desktop. I tried all versions (from Linux mint 7 till 10 and both 32 and 64 bit versions)
What actually happens is that, the BIOS loads the CD (doesn't even asks "press any key to boot from CD" as it asks for Windows) and abruptly results in a blank screen. It remains blank even for hours. But Opensuse, Ubuntu, and even open solaris all run fine on this system. Don't know why it resists only Linux mint.

A: I'd bet it is simply because the distro's liveCD isn't equipped with the video drivers for your graphics card. Another reason might be that it uses some odd bootloader options.
In any case, you'd best report this upstream.


text:
Q: How to use one instance of emacs as the default text editor? [Linux] What I would like to achieve

*

*one instance of emacs

*if i open any text file from nautilus, it should open in the current emacs instance

*if i close emacs, it shouldn't really close it, just hide it

What I have currently

*

*I set emacs23 to start at startup

*I have (start-server) in my init

*I leave emacs open

*I have emacsclient as the default texteditor

Issues I encountered while trying to achieve what I wanted

*

*emacs gives the following error if i quit emacs and try to start it again

File error: Cannot bind server socket, address already in use

Things I tried

*

*emacs wiki

*stackoverflow

*emacs fu
Update: I tried again with the stackoverflow link, and now most of it is working.
However, something I would like to be able to do is to reload the init file, so that I can make changes to my init file without restarting the computer. Any ideas?
Also, if the server is running and I have emacs false-closed (see emacs fu link), how can i start it again without loading a file? eg what would the equivalent of running emacs23 be, as this doesn't work (see error written above)

A: I start emacs with emacs --daemon so that emacs starts in a daemonized mode. Then I would set EDITOR to emacsclient -t -a emacs -nw which opens a new terminal emacs frame attached to your emacs daemon, with a "no window" version of emacs used as an alternate if there isn't an emacs-server running. For opening emacs windows in the GUI I the editor command is emacsclient -n -c -a emacs.
It's also possible to run more than one emacs instance on a single machine, if you don't want to have buffers from one project be intermingled with buffers from another project. See my my post on the subject.

A: *

*remove (start-server) from .emacs

*use emacsclient "$@" -a "" to start emacs whether it is running or not

If you save emacsclient "$@" -a "" as a script e.g. in editor file then editor -c creates a new frame, editor -t opens new frame in the terminal, and editor FILE visits FILE in an existing frame. It starts emacs server if it is not running.

A:
However, something I would like to be
  able to do is to reload the init file,
  so that I can make changes to my init
  file without restarting the computer.

Reading through the methods behind the daemon-effect you're looking for, none of them seem to preclude simply loading your init file and issuing an eval-buffer call after edits are made.

Also, if the server is running and I
  have emacs false-closed (see emacs fu
  link), how can i start it again
  without loading a file?

Running emacsclient (rather than emacs23) should do the trick, I would think.

A: Hmm, not sure about running emacs as a client, but I frequently revise and apply changes to my .emacs file, without closing emacs.
Simple edit the file (within or outside of emacs, it doesn't matter which).  The M-x load-file, emacs will ask you for the file's path and name, which is easy if it's ~/.emacs.
Type the path and filename then RET and emacs will reload with your changes.  Any buffers you had open will still be there.


text:
Q: Display lins from text.file to array c# I am trying to read lines from txt file into array and display it into a text box.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack != true)
    {
        blogPostTextBox.Text ="";
        string blogFilePath = Server.MapPath("~") + "/Blogs.txt";
        string[] blogMessageArray = File.ReadAllLines(blogFilePath);

        // this for loop code does not work..I think..
        for (int i = 0; i < blogMessageArray.Length; i++)
        {
            string[] fileLineArray = blogMessageArray[i].Split(' ');
            blogPostTextBox.Text = blogMessageArray[i] + System.Environment.New Line.ToString();
        }
    }
}

My text file contains several line and I am trying to split each line to array and display all lines into a text box using a for loop or while loop.

A: UPDATE:
For ASP.Net
var items =File.ReadAllLines(blogFilePath).SelectMany(line => line.Split()).Where(x=>!string.IsNullOrEmpty(x));
blogPostTextBox.Text=string.Join(Environment.NewLine, items)

and as a side note, it is better to use Path.Combine when you build path from multiple strings
string blogFilePath = Path.Combine( Server.MapPath("~") , "Blogs.txt");

also if (IsPostBack != true) is valid but you can do as
if (!IsPostBack)

Winform
If the Multiline property of the text box control is set to true, you can use TextBoxBase.Lines Property
blogPostTextBox.Lines =File.ReadAllLines(blogFilePath);

if you need to split each line and set as textbox text then
blogPostTextBox.Lines = File.ReadAllLines(blogFilePath).SelectMany(line => line.Split()).ToArray();

A: You have to set TextMode="MultiLine" in your TextBox(default value is SingleLine), then you could build the text with Linq in this way:
var allLinesText = blogMessageArray
     .SelectMany(line => line.Split().Select(word => word.Trim()))
     .Where(word => !string.IsNullOrEmpty(word));
blogPostTextBox.Text = string.Join(Environment.NewLine, allLinesText);

A: You need to append each line to the textbox. What you are doing above is overwriting the contents of the textbox with each new line.
string[] blogMessageArray = File.ReadAllLines("");
blogPostTextBox.Text = "";
foreach (string message in blogMessageArray)
{
    blogPostTextBox.Text += message + Environment.NewLine;
}

Although rather than read in all the lines, and then write out all the lines, why don't you just write out all the text to the textbox?
blogPostTextBox.Text = File.ReadAllText();

A: Though you could do this in a loop, you really don't need to (or want to)
Replace your loop with with built in dot net methods that actually do what your need.
See String.Join()

public static string Join(
    string separator,
    params string[] value
)

This will combine all of the elements of blogMessageArray with your specified separator
('\n' in your case, HTML does not need "\r\n")
Then just assign this to the property blogPostTextBox.Tex


text:
Q: get hidden field value in JavaScript / jQuery from updatepanel I am sure this must have been covered but I can't find the anwser. I have an asp:hidden field in an asp:update panel that I need to get the value of in a JavaScript/jQuery. I can't seem to get it the normal way, document.getElementById('<% =controlid.ClientID %>').value;
It must be something to do with ajax or something but I can't figure it out.
Any advice would be great.

A: in jQuery : (updatepanel or not).
$('#<%= controlid.ClientID %>').val()

A: From what you're describing, it sounds like you and ASP are server-side coding the output Javascript, right?  (I have JS experience, but little ASP, so bear with me for guessing with only a few tutorials on UpdatePanels ...)
Based on that note, here's what I think you're seeing:

*

*Your ASP.net writes out the ID of the ClientID field into the Javascript you wrote.  (If you're lucky)

*Your Javascript looks for the field matching the client's ID number, but not the actual client ID field.

So, instead of your output Javascript being, "document.getElementById('ClientID').value" which it may need to be on the client side, your output Javascript is, "document.getElementByID('234234234').value".
I've added a comment to your question above that basically asks, "Do you output a field whose ID is equal to the client's ID, and you're looking for the value of that field?"

A: Try Something different today:
$("input[id$=hfContainerHeight]").val()

<input id="hfContainerHeight" type="hidden" value="100" runat="server" />

+1 For Royi answer...


text:
Q: PhpStorm/Symfony - navigate to twig file I need help getting PhpStorm to correctly navigate to my twig files. E.g, in my controller, I have:
return $this->render('user/schedule.html.twig');

If I hit command and click on the user/schedule.html.twig, it SUPPOSED to take me directly to my file (living in the project root under templates/user/schedule.html.twig).  However, instead PhpStorm says:

Cannot find declaration to go to

I believe this needs to be configured in the Symfony Twig plugin, under "Preferences -> Lang & Frameworks -> Symfony -> Twig/Template", but I cannot seem to find the right setup to make this work. Any advice please?

A: you need to explicitly enable the symfony Plugin for the project


text:
Q: Laravel Retrieve related model through pivot table So i'm a bit confused with this situation, I have the current relations:
User hasmany Favourite
favourites references to a Recipe model
favourites is a pivot table but when I retrieve the favourites for a given user like:

$user->favourites

i get the favourite with the pivot data, but I want to get the fields of the recipe
Recipe.php:
public function favourites()
{
    return $this->hasMany('App\Favourite');
}

User.php:
public function favourites()
{
    return $this->hasMany('App\Favourite');
}

Favourite.php:
public function user()
{
    return $this->belongsTo('App\User','user_id');
}

public function recipes()
{
    return $this->belongsTo('App\Recipe','recipe_id');
}

EDIT : there was no problem at all, just needed to call:
@foreach($user->favourites as $favourite)
    {{ $favourite->recipe->name }}
@endforeach

A: You need to set your relation to Has Many Through instead of just has Many.
https://laravel.com/docs/5.2/eloquent-relationships#has-many-through
Recipe.php:
public function favourites()
{
    return $this->hasManyThrough('App\Favourite', 'App\User');
}

User.php:
public function favourites()
{
    return $this->hasManyThrough('App\Favourite', 'App\Receipe');
}

Favourite.php:
public function user()
{
    return $this->hasManyThrough('App\User','App\Receipe');
}


text:
Q: PostGIS raster MapAlgebra callback optimization I'm trying to speed up an ST_MapAlgebra callback function that essentially takes a raster with four bands, checks each band for values less than a given number, and where the check is true, return the fourth band.
This is my messy function:
create or replace function
callback_fn(pixel float[], pos integer[], variadic userargs text[])
  returns float
  language plpgsql
  immutable
as $$
  declare
    roaddist float;
    protected_area float;
    citydist float;
    return_val float;
  begin

    citydist := pixel[1][1][1];
    roaddist := pixel[2][1][1];
    protected_area := pixel[3][1][1];
    return_val := pixel[4][1][1];

    if protected_area = 1 then return null;
    end if;
    if citydist <= 2000 then return return_val;
    elsif roaddist <= 500 then return return_val;
    else return null;
    end if;
  end;
$$;

So from what I understand, the function above will go through every pixel and either return the "return_val" or it will return NULL. So what I end up with is basically a single band raster with excluded areas removed.
This is exactly what I want, but I was hoping to run this faster. Is there a way to run multiple pixels simultaneously instead of going through each one individually? I'm confused why ST_Reclass can run so quickly to reclassify a whole raster while ST_MapAlgebra seems to take so much longer when (in my mind, at least) the functions are doing similar things - checking the values of a raster and where true, change value, otherwise set null.  Is there a way to use ST_Reclass in a callback function to speed up this process?
Additionally, is there a good source for documentation on writing PostGIS raster callback functions? I have been googling a lot over the last few days and have found extremely meager examples.

A: I think to achieve what you want, you'd
1) use ST_Reclass to reclassify your citydist, roaddist .. http://postgis.net/docs/RT_ST_Reclass.html
2) Convert those to geometry with ST_Polygon - http://postgis.net/docs/RT_ST_Polygon.html
3) Then use ST_Clip with your final- http://postgis.net/docs/RT_ST_Clip.html  (setting crop to false)

A: Or
1) ST_Reclass() to get bands of 1 and NULL
2) ST_Intersection(ST_Intersection(ST_Intersection(band1, band2, 'BAND2'), band3, 'BAND2'), band4, 'BAND2')
I guess any call to some standard API function will always be faster than a custom ST_MapAlgebra() function. Also anything which is raster only should be faster than any conversion to vector. Every case can be solve in many ways and all require test and probing.
ST_ReClass() is faster because it has access to low level code and memory that ST_MapAlgebra() can't have access to. ST_MapAlgebra() also has the overhead of having to call a high level function for each pixel.


text:
Q: Struts2 jQuery plugin - submit button I have Struts 2 jQuery plugin submit button, when click the button its not firing the action class as Struts submit button. I need to keep the same page after click the button.Please look into below code difference.
Struts submit button - Working good:
<s:form action="product!list" id="searchForm" theme="simple" method="Post">
     <s:submit action="product" method="list" value="Find" />
</s:form>

Converting Struts submit to Struts-jQuery submit submit button - Not Working good:
<s:form action="product!list" id="searchForm" theme="simple" method="Post" >
     <sj:submit />
</s:form>

if using only form action <sj:submit/> , the page the refreshing and working as Struts tag, but it should not be.

A: In order <sj:submit> to work properly targets attribute must be set to some value and form must have id attribute.
<s:form action="product!list" id="searchForm">
  <sj:submit targets="results"/>
</s:form>

A: You should include <sj:head/> tag in the body of the <head>. This tag links JQuery and stylesheet on the page and other initial things, without it Ajax call has not made and as a result page refreshes. See examples of submitting tag SubmitTag:

<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="sj" uri="/struts-jquery-tags"%>
<html>
  <head>
    <sj:head/>
  </head>
  <body>
    <s:form id="form" action="AjaxTest">
      <input type="textbox" name="data">
      <sj:submit value="Submit Form" />
    </s:form>
  </body>
</html>