text:
Q: How to use multible routes in MVC I have a website that need a departmentID for all sites, so i rewrote the default route to the following:
routes.MapRoute(
            name: "Main",
            url: "{deptID}/{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", deptID = "", id = UrlParameter.Optional }
        );

It works fine when you for example use the following URL:
http://domain/2/Home/Index
or just simply:
http://domain/2
My problem is that when i go to "http://domain/" i get an error because i dont have specified the departmentID.
How can i add a second route which will fire when you just go to the domain.
I have tried to add the following:
routes.MapRoute(
            name: "Start",
            url: "/",
            defaults: new { controller = "Department", action = "Select"}
        );

Which doesnt work since you cant just put "/" as an URL.
I have also tried to add the default route and then just change the defaults object:
            routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Department", action = "Select", id = UrlParameter.Optional }
        );

This doesnt work either.

A: You have to modify your code as below
  public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
          name: "Department",
          url: "{deptID}/{controller}/{action}",
          defaults: new { controller = "Department", action = "Index"}
      );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

    }

Output

Let me know if the above code still not worked for you.


text:
Q: Why can't I build to simulator on XCode 12 This is a somewhat peculiar.
I think this is related to XCode 12, but I made some simultaneous project changes, so it may be that. It seems that I can meaningfully deploy the project to devices running ios 13 or ios 14 successfully, project runs fine, but when I try to deploy to the simulator, it can't copy some stuff into the target. I've looked at many related questions in various forums and haven't seen this addressed specifically.
    CopySwiftLibs /Users/seanl/Library/Developer/Xcode/DerivedData/PROJNAME-dmjlgigvatannqerrubxabptwsnp/Build/Products/Debug-iphonesimulator/appname.app (in target 'APPNAME' from project 'PROJNAME')
cd /Users/seanl/development/Projdir
export CODESIGN_ALLOCATE\=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate
export DEVELOPER_DIR\=/Applications/Xcode.app/Contents/Developer
export SDKROOT\=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk
builtin-swiftStdLibTool --copy --verbose --sign - --scan-executable /Users/seanl/Library/Developer/Xcode/DerivedData/PROJNAME-dmjlgigvatannqerrubxabptwsnp/Build/Products/Debug-iphonesimulator/APPNAME.app/APPNAME --scan-folder /Users/seanl/Library/Developer/Xcode/DerivedData/PROJNAME-dmjlgigvatannqerrubxabptwsnp/Build/Products/Debug-iphonesimulator/APPNAME.app/Frameworks --scan-folder /Users/seanl/Library/Developer/Xcode/DerivedData/PROJNAME-dmjlgigvatannqerrubxabptwsnp/Build/Products/Debug-iphonesimulator/APPNAME.app/PlugIns --scan-folder /Users/seanl/Library/Developer/Xcode/DerivedData/PROJNAME-dmjlgigvatannqerrubxabptwsnp/Build/Products/Debug-iphonesimulator/WhirlyGlobeMaplyComponent.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk/System/Library/Frameworks/iAd.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk/System/Library/Frameworks/AdSupport.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk/System/Library/Frameworks/CoreMotion.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk/System/Library/Frameworks/GLKit.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk/System/Library/Frameworks/Photos.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk/System/Library/Frameworks/WebKit.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk/System/Library/Frameworks/ImageIO.framework --scan-folder /Users/seanl/development/Projdir/Firebase/FirebaseAnalytics/GoogleAppMeasurement.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk/System/Library/Frameworks/AVKit.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk/System/Library/Frameworks/CoreMedia.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk/System/Library/Frameworks/AVFoundation.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk/System/Library/Frameworks/MobileCoreServices.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk/System/Library/Frameworks/ExternalAccessory.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk/System/Library/Frameworks/AddressBook.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk/System/Library/Frameworks/AddressBookUI.framework --scan-folder /Users/seanl/Library/Developer/Xcode/DerivedData/PROJNAME-dmjlgigvatannqerrubxabptwsnp/Build/Products/Debug-iphonesimulator/WhirlyGlobeMaplyComponent.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk/System/Library/Frameworks/MapKit.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk/System/Library/Frameworks/MessageUI.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk/System/Library/Frameworks/CoreLocation.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk/System/Library/Frameworks/SystemConfiguration.framework --scan-folder /Users/seanl/development/Projdir/Firebase/FirebaseAnalytics/FirebaseAnalytics.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk/System/Library/Frameworks/CFNetwork.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk/System/Library/Frameworks/CoreText.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk/System/Library/Frameworks/CoreGraphics.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk/System/Library/Frameworks/OpenGLES.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk/System/Library/Frameworks/Security.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk/System/Library/Frameworks/StoreKit.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk/System/Library/Frameworks/QuartzCore.framework --scan-folder /Users/seanl/development/Projdir/Firebase/FirebaseAnalytics/FIRAnalyticsConnector.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk/System/Library/Frameworks/UIKit.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.0.sdk/System/Library/Frameworks/Foundation.framework --platform iphonesimulator --toolchain /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain --destination /Users/seanl/Library/Developer/Xcode/DerivedData/PROJNAME-dmjlgigvatannqerrubxabptwsnp/Build/Products/Debug-iphonesimulator/APPNAME.app/Frameworks --strip-bitcode --strip-bitcode-tool /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/bitcode_strip --emit-dependency-info /Users/seanl/Library/Developer/Xcode/DerivedData/PROJNAME-dmjlgigvatannqerrubxabptwsnp/Build/Intermediates.noindex/PROJNAME.build/Debug-iphonesimulator/APPNAME.build/SwiftStdLibToolInputDependencies.dep

always results in:
    error: Build input file cannot be found: '/Users/seanl/Library/Developer/Xcode/DerivedData/PROJNAME-dmjlgigvatannqerrubxabptwsnp/Build/Products/Debug-iphonesimulator/APPNAME.app/APPNAME' (in target 'APPNAME' from project 'PROJNAME')

As I said, this is only building to the simulator, device works fine. One interesting point is that it's not using swift, and yet there's a copySwiftLibs call , though maybe that's a generic library copy.
I've scoured the net for ideas, any thoughts?
Thanks in advance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: c++ deleting non-existing pointers class C {

public:
    std::vector<C*> list;
    int value;

    C(int value,  C* parent)
    {
        this->value = value;

        if(parent)
        {
            parent->registerChild(this);
        }
    }

    void registerChild(C* child)
    {
        this->list.push_back(child);
    }

    ~C()
    {
        for(std::vector<C*>::iterator it = list.begin(); it != list.end(); ++it)
        {
            if( (*it))
            {
                delete (*it);
            }
        }
    }
};

This is for a GUI project. A child class that has a parent, must notify parent class of it so that when the parent class gets deleted, all of its children should be deleted too.
C* main = new C(100, 0);

C* child1 = new C(250, main);
C* child2 = new C(450, main);

delete main;

^ everything works as expected - main is deleted along with child1 and child2.
C* main = new C(100, 0);

C* child1 = new C(250, main);
C* child2 = new C(450, main);

delete child1;

delete main; // windows error

If I decided to get rid of child1 first and then sometime later decided to delete main, I get a windows error that is traced back to vector loop where apparently delete tries to delete a now non-existent pointer.
I would have thought that if( (*it)) would return false for a pointer that doesn't exist anymore.
What can I do here?
EDIT:
This appears to work flawlessly
class C {

    typedef std::vector<C*> cList;

public:
    std::vector<C*> list;
    int value;
    C* parent;

    C(int value,  C* parent)
    {
        this->value = value;
        this->parent = parent;

        if(parent)
        {
            parent->registerChild(this);
        }
    }

    void registerChild(C* child)
    {
        this->list.push_back(child);
    }

    void removeChild(C* child)
    {
        cList::iterator it = std::find(list.begin(), list.end(), child);

        if(it != list.end())
        {
            list.erase(it);
        }
    }

    ~C()
    {
        if(this->parent)
        {
            // this child is being removed - notify parent and remove this from its child_list
            this->parent->removeChild(this);
        }

        cList::iterator it = list.begin();

        while(it != list.end())
        {
            delete (*it);

            // find a new beginning
            it = list.begin();
        };
    }
};

A: When you call delete main, it will call delete on its children. child1 is one of them. So you are calling delete on the same memory address twice. And that is undefined behaviour.

I would have thought that if( (*it)) would return false for a pointer that doesn't exist anymore.

No, there is no mechanism for one pointer to know that the object it points to has been deleted via another pointer.

What can I do here?

Make sure only one entity is responsible for managing dynamically allocated objects.

A: It is a semi-widely missconception that a pointer is set to NULL when the memory it points to is deleted. It is not. Also, it is safe to delete NULL so checking whether a pointer is not NULL before deleting it is not necessary (off topic...).

A: There's nothing magic about pointers. They are just (generally speaking) integers of machine word width which can be used to refer to specific memory addresses. There's no magic that  NULLs that integer when the memory area it mentions is no longer owned by your program.
It's a bad idea to deal with raw pointers like this. People are too easily confused by who is responsible for managing the memory pointed to.
Look into std::unique_ptr and std::shared_ptr (http://en.cppreference.com/w/cpp/memory).
Consider keeping the parent pointer as a member of the class, adding a deregister member function. Then in the destructor of the class, have the object deregister itself from the parent. You'll need to change how you manage the child window list.
Also, the names of your class member variables really should be more descriptive. list doesn't tell us much. Consider a name like children or child_list.


text:
Q: nested filter array method The purpose of this code is to filter items by color. The filtered is value is not updating to the items that match the color. The filterData function is suppose to filter through the products and then filter through the colors in the array and return the products that are of that color
state = {
    filtered:this.props.products,
    color:[],
    size:'all',
    price:'all',
    type:'all'
}

change = (e) => {
    let value = e.target.value;
    let name = e.target.name;
    this.setState({
        [name]:[...this.state.color,value]
    }, () => {
        this.filterData();
    })
}

filterData = () => {
    if (this.state.color) {
        var newData = this.props.products.filter(product => {
            return this.state.color.filter(c => {
                return c === product.colors
            })
        })
    }
    this.setState({
        filtered:newData
    })
}

render() {
    let list = this.state.filtered.map(product => {
        return(

                <Link to = {{ pathname: '/'+product.product_id}}>

                </Link>

{product.title}

${product.price}.00

        )
    })

A: Try changing your filter function, like this:
filterData = () => {
  var newData = this.propts.products;

  if(this.state.color) {
      newData = this.props.products.filter(product => {
        return product.colors.some(color => {
          return this.state.color.includes(color);
        });
      })
  }

  this.setState({
      filtered:newData
  })
}

Besides fixing the issue of comparing arrays directly, this functions returns true only when at least on of the color of a product is in the list of colors selected by the user.
Of course that you have to account the fact that newData is only defined when this.state.color is set so you should do something about it (I fixed it by assigning a default value).
Update: BTW, your code is awful, you should take some time to format your code accordingly so it is readable.

A: I think this can be simplified a fair bit. It's hard to tell for sure without seeing what the actually data structure of an item in the color array and what a product looks like. This new filterData method should fix it. This is what I am imagining the data looks like:
this.state.color = ["red","blue","green","purple", ...];

this.state.products = [
    {name: "product1", price: 10, color: "orange"},
    {name: "product2", price: 20, color: "red"},
    ...
]

You can also utilize some ES6 features to make your code cleaner and more readable. A big issue is you defined newData within your "if(this.state.color)" block so will always be undefined when it hits "this.setState".
First you should filter the products, and the condition in the filter being if the products color is within the color array. You can achieve this by using "indexOf" and checking if the index is greater than -1. -1 means it does not exist in the array, anything greater is the color's index position, meaning it exists.
filterData = () => {
    if(this.state.color){
        let { color } = this.state;
        let { products } = this.props;
        let newData = products.filter(product => {
            if(color.indexOf(product.colors) > -1)
                return product;
        }
        this.setState({filtered: newData})
    }
}

Based on the example data I provided above, only product2 would be returned since it's color ("red") is included in the color array.
Hope this helps!


text:
Q: I don't understand useCallback I need to change the checkbox checked status, but useCallback re-renders component a lot of times. I don't understand how it works. I've read a lot of materials about it.
const AppealsList = () => {
  const [isFiltered, setFiltered] = React.useState(false);
  console.log('rerender');

  const changeCheckBox = useCallback(() => {
    setFiltered(!isFiltered);
  }, [isFiltered]);

  return (

        <input
          checked={isFiltered}
          className={classNames('appeals__input')}
          type="checkbox"
          readOnly={true}
        />

  );
};

Amount of re-renders:

A: This is because you have written your callback with a dependency on isFiltered so it will change every time you click.  It works best when it does not depend on the very state that the callback is changing.
To create a toggle function that does not constantly change, have it call setState with a function so that it can compute new state from previous state, taking advantage of functional state updates offered by useState:
const changeCheckbox = useCallback(() => {
    setFiltered(currentValue => !currentValue);
}, []); // look no dependencies!

You can read about functional state updates (deriving new state from current state) here: https://reactjs.org/docs/hooks-reference.html#functional-updates

If the new state is computed using the previous state, you can pass a function to setState. The function will receive the previous value, and return an updated value.

A: setCallback is used to memoize functions so if you have heavy functions that require a lot of processing you don't have to processes the same inputs twice. For example if you had a function that adds two numbers and you give it 4 and 3 then it runs the function and memorizes that when you input 4 and 3 into the function the result is 7. So next time it is passed 4 and 3 instead of processing the result it uses the memorized result.
While useCallBack is used to memorize functions, useEffect is used to prevent unnecessary rerenders. I think in this case you are wanting to use the useEffect Hook?


text:
Q: TYPO3 7: override or remove page template from within extension controller I want my calendar extension to return XML and iCal output while avoiding the need of any additional TypoScript (additional page or typeNum). For this purpose I created a dedicated export controller. The correct XML extension template is being loaded but wrapped in the regular HTML page template.
Here's what I tried in ExportController->listAction(). The following line does what I hoped it would as there is no HTML <head> section in the output:
$GLOBALS['TSFE']->config['config']['disableAllHeaderCode'] = 1;

With the following line instead the page is still being parsed completely although I can see the changes in the f:debug output of $GLOBALS['TSFE']->tmpl->setup:
$GLOBALS['TSFE']->tmpl->setup['page.']['10.']['file'] = 'path/to/empty/templatefile.xml';

I even went further and tried to override all template settings from my TypoScript ($GLOBALS['TSFE']->tmpl->setup['page.']['10.']['file.']['stdWrap.']['cObject.']['default.']) – with the same result.
While, when setting $GLOBALS['TSFE']->tmpl->setup = null;, some of the page content is gone: all the output after the extension's XML template and above it all the content elements – but that part of the template is still there.
Additionally – and unsuccessfully – I tried this:
$this->objectManager->get(\TYPO3\CMS\Core\Page\PageRenderer::class)->setTemplateFile('path/to/empty/templatefile.xml');

Is there any non-TypoScript way to achieve what I want?

A: The action template file gets resolved before your controller action gets called. The only way that I know of, is to override methods on the controller such as setViewConfiguration and programatically add an additional template root path - but this is not necessarily compatible with your use case. It requires that the template object not specify a template path and filename, it must only specify a template name and a (set of) template root paths.
Your use case looks like the file path and filename get set in TS, in which case, no, you cannot override this outside of TS.
Sometimes, accepting you need to use TS for some things is just the easier way. It's how TYPO3 was designed, after all.


text:
Q: Unintentional Two Master Branches Git I had written some code in Xcode that I knew I wasn't going to be using, but wanted to keep in git just in case. I committed and pushed this, and then tried to undo this via
git reset HEAD^
I probably should have just used my tried and true method of hard resets. But now I have the following:
   A origin /master undoing head
     |
   origin master 1 /head 1 master messed up commit
     |
     |    GOLDEN COMMIT **I WANT TO BE HERE**
     |
     |
     |
     |
      \
        master (a really old commit !)
     |
     |
     |
     |

All I want to do is get back to the golden commit. But I have this master branch that is an old commit, and every time I pull nothing happens. What is going on !? My project is now corrupted and I can't open it

A: If you really want a given commit, and don't care about losing local changes, force a checkout:
$ git checkout -f golden_commit

That will update your local files (those which were tracked at the time of commit) no matter what.
git reset only modifies your local repo. It does not touch what you have pushed elsewhere. Get your local repo to look like you want it first, and don't try pushing or pulling before you have that.
Once your local repo is fine, you can discard the really old master in your remote (if you don't think anyone else is using it) with git checkout master -f && git push origin master -f. The old master in your remote will eventually get lost.


text:
Q: Where it is better to make a request (react) First request return for me two lists: list1, list2.
So i need render list1 immediately. But for list2 i need to check from second request and then display him. Where better place to do that?
p.s. now i am doing that in componentDidMount in item of list2. isChecking - set true when request is ending and give result.
const Container = (props) =>

    {props.list1.map(item => <Item {...item} />)}
    {props.list2.map(item => <Item {...item} check={true}/>)}

;

class Item extends React.Component {
    componentDidMount() {
      if (check) {
        this.props.checkRequest();
      }
    }

    render() {
      if (this.props.check && !this.props.isChecking) {
        return ;
      }

      return
{item.name}
;
    }
}

A: If you don't need the checking logic for the list1 you can directly map it without using Item component for it, like this:
const Container = (props) =>

    {props.list1.map(item =>
{item.name}
)} // <------- no Item component here
    {props.list2.map(item => <Item {...item} check={true}/>)}

;

class Item extends React.Component {
    componentDidMount() {
      if (check) {
        this.props.checkRequest();
      }
    }

    render() {
      if (this.props.check && !this.props.isChecking) {
        return ;
      }

      return
{item.name}
;
    }
}


text:
Q: How to recover toric invariants tropically? My excuses in advance in case my question is too vague (which is mainly due to the fact that I'm not really familiar with tropical/toric geometry, but at least I still believe that the content of the question is non-empty).
I'd like to understand better the relationships between tropical and toric geometry. (The naive intersection of the two fields is of course due to the appearance of similar combinatorial structures in form of fans/polyhedra used in building the respective geometries).
More precisely, I'd like to know now the following question: Suppose we are given a (nice) toric variety. Can we recover its "invariants/properties" in terms of an associated tropical variety?
(The naive way would of course be to look at the tropical variety attached to the underlying combinatorial structures of the toric variety.)
In fact, I'm most interested in describing the Todd class of a (nice) toric variety tropically.
I'd be very happy about any kind of related pointers towards the literature or (philosophical) explanations.
(Again, I'm sorry in case my question is completely off-track.)
Thanks a lot in advance!

A: One has to be precise when one talks about the tropicalization of a toric variety.  Usually, one takes tropicalizations of subvarieties of an algebraic torus.  To get around this constraint, there is a notion of extended tropicalization of subvarieties of a toric variety.  Although I haven't checked the definitions, the extended tropicalization of a toric variety should contain exactly the same information as the fan.
The question should perhaps go the other way.  There are lots of recipes for reading geometric invariants of toric variety from the fan which is a combinatorial object.  Given a subvariety of a toric variety, can one read off geometric invariants of the subvariety from the tropicalization.  The case of the toric variety is the prototypical example, but maybe other varieties act like toric varieties in this sense.


text:
Q: Pulseaudio Virtual Sink to Virtual Source I am trying to create both a virtual speaker and a virtual microphone to direct the output from one software to the input of another software, but I am running in dead ends trying to figure out how to use PulseAudio in such a way, most posts I have found are not helping me at all with my problem. Can someone please help me?
Basically:
Virtual Speaker ---> Virtual Microphone

A: Pulseaudio automatically creates a monitor source for any audio playback sink
on my system Pulseaudio card Profile is set to Analog Stereo Output instead of Analog Stereo Duplex for input+output. checking available sinks with 'pactl list short sinks' responds
0   alsa_output.pci-0000_04_06.0.analog-stereo  module-alsa-card.c  s32le 2ch 48000Hz   IDLE

and for 'pactl list short sources'
0   alsa_output.pci-0000_04_06.0.analog-stereo.monitor  module-alsa-card.c  s32le 2ch 48000Hz   IDLE

audio playing to alsa_output.pci-0000_04_06.0.analog-stereo can be recorded from alsa_output.pci-0000_04_06.0.analog-stereo.monitor
in Pulseaudio Volume Control GUI, monitor sources are not visible as input devices by default in pulseaudio -t 4
dropdown menu at bottom right of window 'Show' is usually set to show only 'Hardware input devices' change this to 'All input devices' to make monitor sources visible


text:
Q: cURL php download and upload without save in the middle I have a situation where I need to move files from one location to another.  Using cURL, it is simple to download the files and then upload them using the sweet at symbol i.e. "file_box"=>"@/path/to/myfile.jpg"  What I'm looking to do now is bypass the saving step in the middle and just "stream" the file from one to the other.  Is this possible?

A: Sure, you can do that.  I'm not sure you can use cURL for the POST though.  You'd have to look into its methods to see if it will let you callback for the next chunk of data.
http://curl.haxx.se/libcurl/php/examples/callbacks.html
$ch = curl_init();
curl_set_opt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
curl_set_opt($ch, CURLOPT_WRITEFUNCTION, 'read_body');

function read_header($ch, $data) {
    // Ok, so the header is going to come in here.
    // I assume you will need data, such as MIME type and what not.
    print_r($data);
    return strlen($data); //This means that we handled it, so cURL will keep processing
}

function read_body($ch, $data) {
    // This is where the body of the content will be, in chunks.
    // This function will be called multiple times.
    print_r($data);
    return strlen($data); //Again, if we don't do this, cURL will cancel.
}

Now for the sending part, it seems you will have to implement HTTP yourself with fsockopen.  See here for more information:  PHP How To Send Raw HTTP Packet

A: I m actually working with a similar problem now. and as far as my experience, you will have to open a file handle, and save the data to local before being able to upload it to another server.
I know what you mean by streaming, as you want to stream/pipe the file you are downloading to PUT or POST to another server.
I dont think streaming is possible with Php curl. You need save the file locally. then open it and upload it.
I have done a similar job with Java, with that you are actually using streams, so that might work but I havent tried it.


text:
Q: Macro arguments HEX and DEC According to that guide: enter link description here
i wrote:
#define DEBUG
#ifdef DEBUG
 #define DEBUG_PRINT(x)  Serial.print (x)
 #define DEBUG_PRINTLN(x)  Serial.println (x)
 #define DEBUG_PRINT_HEX(x)  Serial.print (x, HEX)
 #define DEBUG_PRINT_DEC(x)  Serial.print (x, DEC)
#else
 #define DEBUG_PRINT(x)
 #define DEBUG_PRINTLN(x)
 #define DEBUG_PRINT_HEX(x)
 #define DEBUG_PRINT_DEC(x)
#endif

if i call a function:
uint32_t versiondata;
DEBUG_PRINT_HEX((versiondata>>24) & 0xFF, HEX);
DEBUG_PRINT_DEC((versiondata>>16) & 0xFF, DEC);
uint8_t uidLength;
DEBUG_PRINT_DEC(uidLength, DEC);

the compiler give me:
error: macro "DEBUG_PRINT_DEC" passed 2 arguments, but takes just 1
error: macro "DEBUG_PRINT_HEX" passed 2 arguments, but takes just 1
Someone can explain me why does not works?

A: Look at the error message. You had defined this macro:
#define DEBUG_PRINT_HEX(x)

This macro want one argument: the x
And you call the macro with two arguments:
DEBUG_PRINT_HEX((versiondata>>24) & 0xFF, HEX);

1 argument: (versiondata>>24) & 0xFF
2 argument: HEX
Just call the macro like this:
DEBUG_PRINT_HEX((versiondata>>24) & 0xFF);


text:
Q: AOP with Spring 3 using Annotations I am trying to get Aspect working with Spring 3 and annotations.
@Aspect
public class AttributeAspect {

  @Pointcut("@annotation(com.mak.selective.annotation.Attribute)")
  public void process(){
    System.out.println("Inside Process ....");
  }

  @Around("process()")
  public void processAttribute(){
    System.out.println("Inside Actual Aspect ..");
  }
}

XML:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans                 http://www.springframework.org/schema/beans/spring-beans.xsd       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 <aop:aspectj-autoproxy proxy-target-class="false" />
<context:component-scan base-package="com.mak.selective.annotation.*" />
<bean name="attribute" class="com.mak.selective.annotation.AttributeAspect"/>
</beans>

MY Test to test the Aspect:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/springcontext/*.xml")
public class AttributeTest {

@Attribute(tableName = "firstTable", columnName = "New Column")
private void getAttribute() {
    System.out.println("Inside Attribute call...");
}

@Test
public void testAttributeAspect() {
    getAttribute();
}

}
With this code i can only see "Inside Attribute call..." but nothing from Aspect.
Please guide.

Got this working by making a new Object (Component) and injected to the Junit test class.

A: Good to see that you got it working from XML, but you could have also done it from annotations.
The issue is that the @Aspect annotation is not a Spring stereotype, so the scanner is not registering the aspect as a Spring Bean.  Just add either @Service or @Component above or below @Aspect and it will be registered.
Also, either directly name the bean (e.g., @Service("myNamedService")) or have it implement an interface (e.g., public class AttributeAspect implements IAspect {), as per standard Spring design.

A: You need to use real AspectJ if you want to intercept invocations of methods within the same bean form where it is invoked. (What you have done, should work if the method testAttributeAspect() is located in an other bean.)

How to do real AspectJ?

Using the AspectJ compiler and weaver enables use of the full AspectJ language, and is discussed in Section 7.8, "Using AspectJ with Spring applications".

@See Spring Reference

A: A few things:
Firstly, when you do around advice you need to write the advice method like this:
@Around(...)
public void aroundAdviceMethod(ProceedingJoinPoint pjp) throws Throwable {
    try {
        System.out.println("before...");
        pjp.proceed();
    }
    finally {
        System.out.println("After...");
    }
}

But also (and this at least applies when you're using proxies, not entirely sure in your case), the method you're putting advice on needs to be public (yours isn't), spring managed (via @Component or otherwise) and called external from the class so the proxy can take effect (also not the case in your example). So you need something like this:
@Component
public class SomeClass {
    @Attribute
    public void someMethodCall() {
        System.out.println("In method call");
    }
}

public class SomeUnitTest {
    @Autowired SomeClass someClass;
    @Test
    public void testAspect() {
        someClass.someMethodCall();
    }
}


text:
Q: Make Datetime Timezone Aware From UTC Offset and DST Bit I am currently battling the cruel beast that is timezone localization in my django application, and having some trouble... I want to make naive datetimes timezone aware, based on a location. I have a database of zip codes that have the UTC offset in hours, as well as a 0 or 1 depending on if the zip codes adhere to DST. How might I use this data to accurately apply a timezone to my datetimes? Ideally the datetime would respond to changes in DST, rather than just always simply following the UTC offset.

A: With pytz it's not hard to convert the datetimes as you describe; the only complication is getting tzinfo instances corresponding to the time zone descriptions in your database.
The problem is that real timezones are more complicated than just offset + DST. For example, different regions adopted DST at different points in history, and different regions in the world can make the DST switch at different points in the year.
If your usage is only for the US, and only concerns future (not historical) dates, then there are a couple options that should yield accurate results (though note the caveat below):

*

*Just create your own concrete tzinfo subclass that uses the offset and DST flag from your database. For example, the Python documentation gives sample code for "a complete implementation of current DST rules for major US time zones."

*Map from the offset / DST to the corresponding pytz tzinfo object. Since there are only a handful of possible combinations in the US, just figure out which timezone name corresponds and use that.
TZ_MAP = {
    ...
    (-5, 1): pytz.timezone('US/Eastern')
    ...
}

tz = TZ_MAP[(offset, is_dst)]

Once you have the tzinfo instance the conversion is simple, but note that dealing with DST involves inherent ambiguities. For example, when the clock is turned back at 2am, all the times between 1am and 2am occur twice in the local timezone. Assuming you don't know which one you actually mean, you can either pick one arbitrarily, or raise an exception.
# with no is_dst argument, pytz will guess if there is ambiguity
aware_dt = tz.localize(naive_dst)

# with is_dst=None, pytz will raise an exception if there is ambiguity
aware_dt = tz.localize(naive_dst, is_dst=None)


text:
Q: XLSX XML cell formatting works in LibreOffice but not MS Excel I modified data tables xlsx export to generate tables with my custom styles. Primarily for the background colors. Mine is a mess, but it works. It generates the xlsx file and in LibreOffice it looks exactly like it should. But in Excel, the cells with Style #3 (FFAAAA) are not filled with solid yellow background but with a dotted gray background.
The ones with red or white background just work fine everywhere.
The whole xml was reverse engineered from other exports.
Any idea what Excel expects to be different?
<?xml version="1.0" encoding="UTF-8"?>

A: It seems excel always overwrites the second  with patternType="gray125".
I just keep
<fill>
   <patternFill patternType="gray125">
   <fgColor rgb="FFffffff" />
   <bgColor rgb="FFffffff" />
   </patternFill>
</fill>

as second , regardless if i actually use it in any style and add the  i need after this. Now it works in Libre Office Calc and MS Excel.
I hope that helps others aswell.


text:
Q: View PDF in IE6 I am trying to open a PDF document to display within IE6. I am using the following snippet:
response.ContentType = healthMedia.MediaKey.MimeType;
response.ClearHeaders();

response.AddHeader("Content-Disposition", "inline; filename=" + mediaKeyId);

int contentLength = healthMedia.Content.Length;
response.AppendHeader("content-length", Convert.ToString(contentLength));
response.OutputStream.Write(healthMedia.Content, 0, contentLength);

healthMedia.MediaKey.MimeType; is equal to 'application/pdf'
This brings up the Save dialog. If I comment out Response.ClearHeaders(); I get a new window to popup but it's contents is a bunch of jibberish (random encoding text).
How can I get IE6 to open the PDF correctly?
-Nick

A: Have you tried Response.End() and also Response.Buffer = true? You may also need to set a caching policy.

A: In case it helps, here's a method I've used before to render in-browser PDFs...

A: Use response.BinaryWrite() instead of response.OutputStream.Write()


text:
Q: How can I add a derived column to my Yii model? In Yii, I need to add a "derived" column to any resultset from my model. The column doesn't actually exist in the database table.
For example, say I have an Activity model. There are only two types of Activities: (1) Income, or (2) Expense.
If I want to add a column called income_total or expense_total (depending on what type of activity is being accessed), how would I do that?
Here's a working example of an Activity model in Ruby on Rails (I'm basically wondering how to do the same thing, but in Yii):
class Activity < ActiveRecord::Base

  attr_accessible :name, :effective_at, :amount, :category
  scope :incomes,  :conditions => { :category => 'Income'  }
  scope :expenses, :conditions => { :category => 'Expense' }

  def self.incomes_total
    incomes.sum :amount
  end

  def self.expenses_total
    expenses.sum :amount
  end

end

Update 2012-07-01:
The answer provided by Leonardo points to the use of Virtual Attributes, this adds an attribute to each "row" of the resultset that I'm retrieving from the database.
If the Activity model has a BELONGS_TO relationship with Parent, a Parent View may look like the following:

<?php echo $parent->name; ?>

  <?php foreach($portfolio->activities as $activity): ?>

      <?php echo CHtml::link($activity->name, array('activity/view', 'id' => $activity->id)); ?>
      <?php echo $activity->amount; ?>
      <?php echo $activity->incomes_total; ?>

  <?php endforeach; ?>

However, it doesn't make sense for this Virtual Attribute to be accessed within the foreach() loop.
These Virtual Attributes that I want provide one "aggregated" value for the whole resultset, so I want to be able access it using $parent->activities->incomes_total, like so:

<?php echo $parent->name; ?>

<?php echo $parent->activities->incomes_total; ?>

  <?php foreach($portfolio->activities as $activity): ?>

      <?php echo CHtml::link($activity->name, array('activity/view', 'id' => $activity->id)); ?>
      <?php echo $activity->amount; ?>

  <?php endforeach; ?>

What do I need to do within the Activity model code to achieve this, or should I be thinking about this a different way?

A: I believe it is pretty similar to Ruby. PHP has magic methods, which in Yii is implemented by CComponent (base class of many including CActiveRecord).
In short you can do this within your model
   class Activity extends CActiveRecord {
     public function getIncome_Total() {
       // ...
     }
   }

And, to access it from controller
$activity = Activity::model->findByPk(1);
$income_total = $activity->income_total;

A: I don't know how this can be done within the model.
Although it is more processing, an option or workaround is to add another foreach() loop to the View like so:
$incomes_total = 0;
foreach($parent->activities as $activity)
  $incomes_total += $activity->amount;
echo $incomes_total;

A: As I posted in the other answer You can simply use a stat relation. Specify a STAT relation in Parent model as
'incomes_total'=>array(self::STAT, 'Activity', 'parent_id','select'=>'SUM(amount)','condition'=>"incomes_total.category='Income'")

Similiarly
'expense_total'=>array(self::STAT, 'Activity', 'parent_id','select'=>'SUM(amount)','condition'=>"incomes_total.category='Expense'")

NOTE: Change the attribute names parent_id and amount as in your model


text:
Q: Summing columns and rows How do I add up rows and columns.
The last column Sum needs to be the sum of the rows R0+R1+R2.
The last row needs to be the sum of these columns.
import pandas as pd
# initialize list of lists
data = [['AP',16,20,78], ['AP+', 10,14,55], ['SP',32,26,90],['Total',0, 0, 0]]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Type', 'R0', 'R1', 'R2'])

The result:
    Type  R0  R1  R2  Sum
0     AP  16  20  78  NaN
1    AP+  10  14  55  NaN
2     SP  32  26  90  NaN
3  Total   0   0   0  NaN

A: Let us try .iloc position selection
df.iloc[-1,1:]=df.iloc[:-1,1:].sum()
df['Sum']=df.iloc[:,1:].sum(axis=1)
df
    Type  R0  R1   R2  Sum
0     AP  16  20   78  114
1    AP+  10  14   55   79
2     SP  32  26   90  148
3  Total  58  60  223  341

A: In general it may be better practice to specify column names:
import pandas as pd
# initialize list of lists
data = [['AP',16,20,78], ['AP+', 10,14,55], ['SP',32,26,90],['Total',0, 0, 0]]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Type', 'R0', 'R1', 'R2'])

# List columns
cols_to_sum=['R0', 'R1', 'R2']

# Access last row and sum columns-wise
df.loc[df.index[-1], cols_to_sum] = df[cols_to_sum].sum(axis=0)

# Create 'Sum' column summing row-wise
df['Sum']=df[cols_to_sum].sum(axis=1)

df

    Type  R0  R1   R2  Sum
0     AP  16  20   78  114
1    AP+  10  14   55   79
2     SP  32  26   90  148
3  Total  58  60  223  341


text:
Q: Is there a variable or an option to add custom build.prop options while compiling AOSP I've been looking for this quest all over but couldn't find one. So decided to ask it myself.
So I'm compiling an AOSP ROM for my phone. And I'm willing to add 2 additional parameters to build.prop which will be generated.
Currently I'm doing it manually. Is there an option to do it automatically.
Like the is this variable called "PRODUCT_BUILD_PROP_OVERRIDES" and it has the option to override build description and fingerprint.
And my question is, will I be able to add the below two lines in a similar way.
persist.camera.eis.enable=1
persist.camera.HAL3.enabled=1
Kindly let me know if you guys have any idea on how to do it...!
Thanks in advance

A: In you device.mk:
PRODUCT_PROPERTY_OVERRIDES += \
    persist.camera.eis.enable=1 \
    persist.camera.HAL3.enabled=1


text:
Q: Error in spring when using scoped-proxy beans I am getting an error in spring when trying to use session scoped beans, the error is:
HTTP Status 500 - Error creating bean with name 'scopedTarget.usuarioAutenticado': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

My configuration is:
web.xml:
<servlet>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            WEB-INF/applicationContext*.xml
        </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <url-pattern>/sys/*</url-pattern>
</servlet-mapping>
<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

And the bean:
<bean id="usuarioAutenticado" class="com.wi.security.UsuarioAutenticado" scope="session">
    <aop:scoped-proxy/>
</bean>

I have been searching about this issue and all I have found is to add the following lines to web.xml:
<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

This solves the issue, but the side effect is that all my @Scheduled annotated methods are running twice, I think that is because spring is creating two contexts.
Reading Spring docs it says:

DispatcherServlet, RequestContextListener and RequestContextFilter all do exactly
  the same thing, namely bind the HTTP request object to the Thread that is servicing that request. This
  makes beans that are request- and session-scoped available further down the call chain.

So, I don't understand why is not working with just the DispatcherServlet configuration.
Hope someone can help me to find a solution, I am new to spring.
Thanks in advance.

A: Got it!
I was setting in my web.xml the contextConfigLocation:
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>WEB-INF/applicationContext*.xml</param-value>
</context-param>

and then setting it again in servlet configuration:
<servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/applicationContext*.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

the solution was to remove the servlet param-value:
<servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value/>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>


text:
Q: Can I convert the floating part of a double into an integer (without using string conversions)? Example:  If I have 7.2828, I just want to get the 2828 as an integer.

A: If d is the original value, just do the following.
((int)(d * 10000)) % 10000

A: Decimal is your friend...
Convert your number to a decimal and then do this.
       decimal d = (decimal)7.2828;
       int val = decimal.GetBits(d - decimal.Truncate(d))[0];

the neat thing about a decimal is that it stores the val as an int, and then just stores a decimal point position.

A: In C++, use double modf(double, double *):
double value;
double fractional_part;
double integer_part= modf(value, &fractional_part);
int fractional_part_as_integer= fractional_part * 10000; // insert appropriate scale here.

A: I don't think you can. Most CPUs cannot represent 7.2828 as a double (IBM mainframes being the exception). The reason is that they represent doubles as a sum of powers of 2. The "7" part is easy: 1+2+4. The fracational bit is harder: 0.25+0.0.03125+0,0009765625..... - an infinite sequence. For practical reasons, this sequence is truncated. And the resulting double will be close to 7.2828. Perhaps 7.282800000000001245. This probably won't fit into an (32 bits) integer.


text:
Q: MaaS fails commisioning node After having setup MaaS (DHCP configured), I am able to PXE boot a node but get a lot of warnings like "Temporary failure to resolve proxy" with Xenial after it reaches its login screen. Then it shuts down and gets enlisted in MaaS gui.  I configure ipmi and then commission the node (no shutdown and ssh allowed) which causes it to boot up. Again, it has the same warnings/errors and waits on login.
After a while commissioning has failed in MaaS gui, when I click on the node it has the following summary.
Output of lldpd error file: lot of errors on failure to fetch .. Temporary failure resolving proxy.
I have set proxy in the MaaS server gui such that apt-get works correctly and I can import images. Also having IP forwarding enabled I thought I was good.
Is this upstream DNS related - i set it from the etc/resolv.conf file. Did not seem to matter.
System Details:
Ubuntu Version: 16.04 (4.4.0-22-generic)
MaaS:"version": "2.0.0", "subversion": "beta6+bzr5073"
I have 2 systems. One is configured as MaaS server and has 2 nics, on gets dhcp and has external access the other on private network which maas manages. I have a second node that connects to this private network and gets dhcp from the MaaS.
The primary network interface (maas -external network) Behind Corp net
auto ens2f1
iface ens2f1 inet dhcp

MaaS Managed private network
auto ens2f2
iface ens2f2 inet static
    address 192.168.1.10
    netmask 255.255.255.0
    iptables -t nat -A POSTROUTING -o ens2f1 -j MASQUERADE
    iptables -A FORWARD -i ens2f1 -o ens2f2 -m state --state RELATED,ESTABLISHED -j ACCEPT
    iptables -A FORWARD -i ens2f2 -o ens2f1 -j ACCEPT

The new node pxe-boots and its BMC gets IP 192.168.1.191 and node itself gets 192.168.1.192.


text:
Q: Join 3 tables, sum qty from 2 different tables and Group By material name I am having below Tables
1. Material Unit:
id | Unit_name
1  | Nos.
2  | lts

2. Material Table:
id | Material_name
1  | bricks
2  | Cement

3. Grn Table:
id | material_id | qty | unit
1  | 1           | 100 |   1
2  | 2           | 500 |   1
3  | 2           | 100 |   1
4  | 1           | 200 |   1

4. Consumption table:
id | material_id | qty | unit
1  | 1           | 50  |   1
2  | 2           | 100 |   1

Results expected is as below:
Material Name | Unit | Total Qty | Total Consumed Qty | Stock
Bricks        | Nos. | 300       | 50                 | 250
Cement        | Nos. | 600       | 100                | 500

So on above results Total Qty is to be fetched from Grn Table and Total Consumed Qty from Consumption Table and Stock is difference of both and should be Group By Material Name.
Below query where getting results for only Total Quantity and need your help to get the consumed quantity also.
I am new to SQL and did tried but stuck at this point and need help.
Select sm.material_name as 'Material Name', mu.unit_name as 'Unit Name' , sum(g.qty) as 'Total Qty' from grn g
JOIN material_table.sm ON g.material_id = sm.id
JOIN material_unit.mu ON g.unit = mu.id

GROUP by material_name

A: Select sm.material_name as 'Material_Name', --mu.unit_name as 'Unit Name' ,
 sum(g.qty) as 'Total_Qty', sum(co.total_consumed_qty) as 'Tot_Con_Qty',
 sum(g.qty) - sum(co.total_consumed_qty) as stock
from grn g
JOIN material_table sm ON g.material_id = sm.id
JOIN material_unit mu ON g.unit = mu.id
JOIN consumption co ON co.material_id = g.material_id
GROUP by material_name

Is this what are you expecting? Please check the column names in the query and try.


text:
Q: jQueryUI draggable to sortable "over" event not fired Here's my story - I have a draggable list of items that is connected to sortable list via
connectToSortable   : ".cell-wrapper",

Problem is, jQuery UI doesn't fire "over" event when draggable is over sortable. It does create a placeholder in cell, though. Is there a way I can run my code when my draggable item is over the sortable item? Thanks.


text:
Q: What's the meaning of "it was a tidy bow"? I found this expression in a news article:

When Vermont's first coronavirus case was detected last month, it took two state health workers a day to track down 13 people who came into contact with that single patient. They put them under quarantine and started monitoring for symptoms. No one else became sick.
"It was a tidy bow," recalled Daniel Daltry, one of the two health officers who did the work.
Within days, new cases were "coming in like dominoes," Daltry said. By late March, his team was racing on a single day to trace the contacts of 12 patients, when an additional 30 cases landed on their desk.

I tried but couldn't find any dictionary entry or good explanation for the phrase. I guess, from the context, it could mean something manageable or doable, but otherwise I have no clue.
This is my first post on this forum. Any help would be appreciated.

A: My guess is that it's an allusion to putting a tidy bow on a present: that is to say, they got everything "wrapped up" (finished) nicely.
I can find very few references to this phrase outside of literal tidy bows, but one similar (but not identical) usage is here, in which the writer seemingly uses it to refer to getting their task (in this case, a poem) done:

In their haste to put a tidy bow at the end of the poem, the poet wraps it up with a cliché.

All that said, I've never personally heard anyone use this phrase before.


text:
Q: How to reverse a given Boolean value in a list? I'm trying to solve the Lights Out puzzle. I use a two-dimensional list of Boolean values, such as [[True, True, True], [True, True, True], [True, True, True]], to represent the condition of a light.
I want to reverse the boolean value at a given location such as (1,1), and I code as:
class LightsOutPuzzle(object):

    def __init__(self, board):
        self.board = board

    def get_board(self):
        return self.board

    def perform_move(self, row, col):
        self.board[row][col] = not self.board[row][col]
        print(self.board)
        return LightsOutPuzzle(self.board)

I call perform_move(1,1) on
[[False, False, False], [False, False, False], [False, False, False]]

but the result is:
[[False, True, False], [False, True, False], [False, True, False]]

which makes me confused. Could you please tell me what's wrong with it? What is the right way to do this task?
Thanks a lot for helping!
I'm using this function to generate new boards:
def create_puzzle(rows, cols):
    c = []
    r = []
    for x in range(cols):
        c.append(False)
    for y in range(rows):
        r.append(c)
    return LightsOutPuzzle(r)

Does it cause the problem?
Thank you sooooo much for your replies!!! QWQ

A: The probe statement i saw in your code is in function def create_puzzle(rows, cols)
def create_puzzle(rows, cols):
c = []
r = []

for x in range(cols):
    c.append(False)    #Statement1

for y in range(rows):
    r.append(c)        #Statement2

return LightsOutPuzzle(r)

Statement1 : Appends elements to list #[False, False, False]
Suppose id(c) is 0x1000
Statement2 : This statement will append Same List (c) to your rowList
result (reference id) : [0x1000, 0x1000, 0x1000]
So your row will have reference to same List, This is the reason when you make change in one of the columns List it is reflecting in all other columns Lists as well
Change your create_puzzle
def create_puzzle(rows, cols):
     myBoard = [[False]*cols for i in range(rows)]
     return LightsOutPuzzle(myBoard )

A: you can do it inside the init method itself then change the perform_move method,
try this
class LightsOutPuzzle(object):

def __init__(self, board):
    self.board = board
    board = [not i for i in board]
    print(board)

def get_board(self):
    return self.board

def perform_move(self, row, col):
    self.board[row][col] = not self.board[row][col]
    print(self.board)
    return LightsOutPuzzle(self.board)

def main():
    LightsOutPuzzle([False, False, False])

if __name__ == '__main__':
    main()


text:
Q: Alias with two Fields using JOOQ i have a nasty SQl that i want transform in JOOQ
Here are the Query:
  SELECT
    SUM(dpr.dpr_bruttopraemie_prt + dpr.dpr_sofortrabatt_prt)
    , MAX(TO_NUMBER(DP1.dp_wert))
      FROM deckungen deck, deckungspraemien dpr,
        (SELECT dp.dp_id, dp.dp_wert
              FROM  textbausteine txb, druckparameter dp
              WHERE  dp.dp_txb_id = txb.txb_id
              ) DP1
      WHERE DP1.dp_id = :druckparameter_id;

As you can see, i need to make alias from a select with two Fields.
dp.dp_id, dp.dp_wert

that im going to used it on some other parts.
How i can i get it done?
i've seen
.asField()

Funktion but it only make alias for one column.
PS: The actual Query are a lot more complicated. So i wrote a simpler one.
With hoping that it's satisfied the SQL ORACLE Dialect.

A: I'm assuming that you're using the code generator, so you have generated objects available for your tables like DECKUNGEN. I'm also assuming you're using these static imports:
import static org.jooq.impl.DSL.*;                  // The jOOQ API
import static com.example.myapp.generated.Tables.*; // Your generated tables

You can then write:
Deckungen deck = DECKUNGEN.as("deck");
Deckungspraemien dpr = DECKUNGSPRAEMIEN.as("dpr");
Textbausteine txb = TEXTBAUSTEINE.as("txb");
Druckparameter dp = DRUCKPARAMETER.as("dp");

Table<?> dp1 = table(
    select(dp.DP_ID, dp.DP_WERT)
   .from(txb, dp)
   .where(dp.DP_TXB_ID.eq(txb.TXB_ID))
).as("dp1");

Record2<BigDecimal, BigDecimal> result =
using(configuration)
  .select(
     sum(dpr.DPR_BRUTTOPRAEMIE_PRT.plus(dpr.DPR_SOFORTRABATT_PRT)),
     max(field("to_number({0})", BigDecimal.class, dp1.field(dp.DP_WERT))))
  .from(deck, dpr, dp1)
  .where(dp1.field(dp.DP_ID).eq(druckparameterId))
  .fetchOne();

Some explanations

*

*jOOQ currently doesn't have a built-in TO_NUMBER() function, but you can easily roll your own using DSL.field(String) and similar overloads. For more detail, refer to the manual's section about plain SQL

*A derived table can be created most easily by using the DSL.table(Select) operator.

*Columns from a derived table can be dereferenced using Table.field() methods, in particular the Table.field(Field), which tries to find a field by the same name as the argument field, retaining the argument field's type information.

Side-note
I don't think your query is correct as you're simply creating cartesian products between your tables deck, dpr, and dp1. Specifically, the SUM() is quite likely to be wrong, whereas MAX() is simply calculated inefficiently.


text:
Q: Babel polyfill includes all polyfills no matter which targets are set I am using Babel 7.1 together with rollup (v0.67). This is my rollup config:
{
  input: 'src/svg.js',
  output: {
    file: 'dist/myBundle.js',
    name: 'myBundle',
    sourceMap: true,
    format: 'iife'
  },
  plugins: [
    resolve({browser: true}),
    commonjs(),
    babel({
      include: 'src/**',
      runtimeHelpers: true,
      babelrc: false,
      presets: [["@babel/preset-env", {
        modules: false,
        targets: {
          firefox: "63"
        },
        useBuiltIns: "usage"
      }]],
      plugins: [["@babel/plugin-transform-runtime", {
        corejs: false,
        helpers: true,
        regenerator: true,
        useESModules: true
      }]]
    })
  ]
}

I want to polyfill older browsers. According to the docs, I need to include babel-polyfill in my entry point which I did. Now babel should include only the polyfills needed (because of useBuiltIns: "usage"). However, even when specifying the newest Browsers as target, I get the full load of code into my bundle (10000 lines of code).
What I tried:

*

*I tried useBuiltIns: "entry" which fixes it for newer browsers but its not what I want (it just includes all polyfills which are potentially needed by the browser no matter if they are actually used in the code).

*change the order of the rollup plugins

*not include the babel-polyfill import

I have no idea why this is happening. It would be great if someone could solve this issue. Its driving me crazy!
And if someone knows as a bonus why no sourcemap is generated I dont mind getting an answer for that, too

A: Hey I made a repo which explores a good babel/rollup setup utilising preset-env and useBuiltIns 'usage'.
// Rollup plugins
import babel from 'rollup-plugin-babel';
import commonjs from 'rollup-plugin-commonjs';
import resolve from 'rollup-plugin-node-resolve';

export default {
    input : 'main.js',
    output : {
        file : 'app.js',
        format : 'iife',
        name : 'PROJECT'
    },
    plugins : [
        resolve(),
        babel({
            exclude : 'node_modules/**',
            presets : [[
                '@babel/env', {
                    useBuiltIns : 'usage'
                }
            ]],
            plugins : [
                '@babel/plugin-transform-runtime'
            ],
            runtimeHelpers : true
        }),
        commonjs()
    ]
};

Take a look https://github.com/matt3224/rollup-babel7
If you can figure out how to reduce the output further submit a PR


text:
Q: What would be the space complexity of reassigning an array again and again in a loop (Python)? I am working on a problem for which I created a solution, and I was wondering what the complexity of the program would be. We are given an array of digits and our task is to encrypt this array. The encryption follows pascal triangle scheme. That is adjacent elements of array are added and the right most digit of each addition is passed to next step. We need to do this until there are only two elements left in the array.
example:-
[1, 2, 5, 6]
[3, 7, 1]
[0, 8]
we need to return string "08".
Code:
def getEncryptedNum(nums):

    while (len(nums) > 2):
        crr_level = []
        for i in range(len(nums) - 1):
            encrypt = (nums[i] + nums[i+1])%10
            crr_level.append(encrypt)
        nums = crr_level

    return str(nums[0]) + "" + str(nums[1]) + ""

According to me the time complexity would be O(n^2) but I am conflicted on the space complexity. I hope someone can help me out regarding that.

A: The space complexity will just be linear. The line
nums = crr_level

causes the previous nums array to be released (except the first one because it may still has a reference in caller). So you will have at most in memory:

*

*the original list if it has a reference in caller

*the current (temporary) nums list

*the (next temporary) crr_level list

less than 3 times the original list.

BTW it would be more Pythonic to build the new list that way:
while (len(nums) > 2):
    nums = [(nums[i] + nums[i+1])%10 for i in range(len(nums) - 1)]

It has the same complexity, but building a list as a comprehension is more efficient that repeatedly adding one element at a time


text:
Q: MySQL does not honor a varchar column size change I have a MySQL instance running under Windows 8.1(dev machine).  I have a table defined with one of the columns as varchar(50).  I need to change it to varchar(100).  When I do this in mysql workbench, the change is made and everything looks good.  Problem is that when I run the .net app that uses the database, if I send data with more that 50 characters I get a column too long error.  Even after stoping/starting the database.
Am i missing something obvious?


text:
Q: Rendering custom nested html in Vue.js I'm moving a site from AngularJS 1.x that relies heavily on the $compile service (which is no longer available in Angular 2.x.  In the application I have a directive that looks something like this <myDir elemId="someRestEndPointID"></myDir>
and does the following:
1) A http call is made and the response returns a string that contains a directive <myDir elemId="someRestEndPointID"></myDir>
2) A call is made to the server to for /someRestEndPointID
3) Angular gets the content and renders and looks for another <myDir> tag
4) the process is repeated (recursive)
I have not yet found something that does this for our new framework Vue.js.  Is there a similar feature or library that would achieve this logic in Vue.js?

A: That seems like a convoluted way to work and I wouldn't follow that pattern. Why not create a component that takes an endpoint as a property <your-component endpoint="https://example.org/"></your-component> and then component will do the call inside the create method?
<template>

    {{content}}

</template>


text:
Q: Wait & Signal order If the following pieces of code execute in the order in which I have put them, can I be sure that thread 1 is awoken first by thread 3, later followed by thread 2?
main:
sem_init(&x,0,0);

thread 1:
sem_wait(&x);

thread 2:
sem_wait(&x);

thread 3:
sem_post(&x);

A: There is no reason to make such an assumption. It depends on when thread 1 and thread 2 are invoquing sem_wait(), i.e., on what they do before and how the scheduler gives them CPU for running. If you want that thread 1 be awoken before thread 2, you need another semaphore:
main:
sem_init(&x,0,0);
sem_init(&y,0,0);

thread 1:
sem_wait(&x);
sem_post(&y);

thread 2:
sem_wait(&y);

thread 3:
sem_post(&x);


text:
Q: How to use Xcode in Ubuntu 18.04? I'm using react-native to build an app and Xcode is not supported on Ubuntu. So, I can't develop ios apps. Is there any way around so that I could run an ios simulator without having a Mac?
I found articles where they suggested to use a virtual box but I think it's not efficient to develop apps on a virtual box(just an intuition). Hackintosh is not an option for me. So, Is there any other way to run an ios simulator?

A: Xcode is a proprietary software available only Apple based Macs.
If you want to you Xcode for developing iOS Apps, then you need a mac. Alternatively, you can also develop iOS apps using xamarin, phonegap and react using a ubuntu based machine.
You cannot for sure run Apple simulator on Ubuntu, you just can't. If you want something outside Apple's hardware you should try a Hackintosh, it's not big deal but in the end, for put your app on the Apple store you still need a regular Apple hardware.

A: The only solution I can think of is to install VMWare or any other VT then install OSX on a VM.
It works pretty good for testing.


text:
Q: Read local JSON file and return determinate keys for each object within it, into an array I'm trying to access a local JSON file which stores nodeIDs as objects and longitude,latitude, adjacent nodeIDs as their values.
Example: [{"33583379": {"lat": 40.7046387, "lon": -74.0167729, "adj": ["33583379", "1659428533"]}, "33583380": {"lat": 40.7043271, "lon": -74.0169624, "adj": ["33583379", "33583381"]}, etc.}]
I'm trying to return just the Object name, "lat" and "long" values of each object and save them into arrays like this:
[33583379, -73.984293,40.729468],
  [33583380, -73.987752,40.732017]
I have tried using Object.keys(data[0]) but returns all the object names and I can't find a way to retrieve it one by one in the same for loop.
Any help is appreciated. Spent hours trying to figure it out but I was only able to access the JSON but not the actual key values I need and formatting them into an array. PS: My project is in React.

A: You can access a json file by using require('location-of-json') . You can extract the lat,long details in a for..in loop and push the values into an array .
a=require('./test.json')
data=[]

for(var i in this.a[0]){
  console.log(new Array(this.a[0][i].lat,this.a[0][i].lon))
  this.data.push(new Array(this.a[0][i].lat,this.a[0][i].lon))
}

I have implemented the above in react . Please check : https://stackblitz.com/edit/react-nphzxn


text:
Q: Why JS saves difference date in storage? I have variable formValuesChanged that contains the following data:

Then I save this data to storage:
sessionStorage.setItem("filters", JSON.stringify(formValuesChanged));

Then if explore session storage I see this object but with different date:
{ classNumber: 2
  classSuffix: 5772436057100
  date: "2018-09-23T21:07:47.043Z"
  teacher: 25203
  type: "teacher"
}

Why does JS save wrong date?

A: There is no date type in the JSON format, it is a bit of a pain but if you want to store a date in a string format you will need to parse it when you read it back.
let obj = JSON.parse(sessionStorage.getItem("filters"));
let objWithDate = { ...obj, date: new Date(obj.date) };


text:
Q: Getting compilation error iterating a HashMap in JAVA Iterate a HashMap
I am trying to execute the following code in visual studio code on my M1 Macbook Air machine. But getting these errors. Although the code executes in online IDE.
/Library/Java/JavaVirtualMachines/jdk-15.0.1.jdk/Contents/Home/bin/java --enable-preview -XX:+ShowCodeDetailsInExceptionMessages -Dfile.encoding=UTF-8 -cp "/Users/shoumik/Library/Application Support/Code/User/workspaceStorage/c7518cbb3ce46c96e642c654a9524389/redhat.java/jdt_ws/jdt.ls-java-project/bin" Test
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method entrySet() from the type Map<String,Integer> refers to the missing type Set
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.swing.text.html.parser.Entity;

class Test {
    public static void main(String[] args) {
        Map<String, Integer> hm = new HashMap<String, Integer>();
        hm.put("abc", 123);
        hm.put("def",321);
        hm.put("ghi",33);

        Iterator<Entry<String,Integer>> hmIterator = hm.entrySet().iterator();

        while(hmIterator.hasNext()) {
            Entry<String,Integer> entries = hmIterator.next();
            System.out.println("Key is" + entries.getKey());
            System.out.println("Value is " + entries.getValue());
        }
    }
}


text:
Q: Parse the List of objects in AWS Connect AWS lambda returns the below List. How can I parse the List in AWS Connect?
In AWS Connect, if lambda returns a single attribute (customerId) I can parse that value in
Connect using $.External.customerId and was able to play that CustomerId.
If Lamda returns the below List, I was accessing in connect as: $.External.list.CustomerId
and it fails. No errors n Cloudwatch Logs. Any idea how to parse the below list in Connect?
AWS lambda returns the below List. How can I parse the List in AWS Connect?
In AWS Connect, if lambda returns a single attribute (customerId) I can parse that value in
Connect using $.External.customerId and was able to play that CustomerId.
If Lamda returns the below List, I was accessing in connect as: $.External.list.CustomerId
and it fails. No errors n Cloudwatch Logs. Any idea how to parse the below list in Connect?
{
  "list": [
    {
      "CustomerId": 224455,
      "CustName": "John"
    },
    {
      "CustomerId": 334455,
      "CustName": "Peter"
    }
  ]
}

{
  "list": [
    {
      "CustomerId": 224455,
      "CustName": "John"
    },
    {
      "CustomerId": 334455,
      "CustName": "Peter"
    }
  ]
}

I should be able to parse in Connect as: $.External.list.customerId
and $.External.list.custName

A: You will need to specify the index for the element you are accessing in the list.
$.External.list[0].customerId
This is using JSONPaths
https://support.smartbear.com/alertsite/docs/monitors/api/endpoint/jsonpath.html


text:
Q: Why do we care about equivalence relations? I understand that equivalence relations can group elements of a set to a class that share similar properties. I think it's really cool that we can partition a set using equivalence relations. I'm also someone who doesn't do math for its applications but for its beauty. However...

Why do we care about equivalence relations?

For a specific equivalence relation reflexivity, symmetry, transitivity are always immediate (at least from what I have seen). You can e.g. define modulo with equivalence relations. Suppose you have never even heard of the equivalence relations, though. You could still define modulo without a problem.
Example: Just today, we've defined connected components of a graph using equivalence relations in class. Why would you want to do that? Why not use standard graph theory language? I don't see the reason for using equivalence relations to introduce connected components - what exactly is it that we gain by introducing equivalence classes?
So in summary, I kind of lack a motivation for equivalence relations and would appreciate examples that could enlighten me on that.

A: Equivalence relations are a way to describe objects that are effectively the same in a given context.
If for some problem you find the solution $x \equiv 1 \pmod 6$, then you immediately know that the solution set is $\{6k+1 : k\in\Bbb Z\}$, and it's conceptually much cleaner and more intuitive to refer to the equivalence relation than to some theorem on modular arithmetic.
Keeping with the integers modulo $6$, imagine an infinite graph with vertices labelled with integers, and $uv \in E$ if $u \equiv v \pmod 6$. Then there will be six connected components, each corresponding to an equivalence class. If you zoom out far enough, then each of these components looks like a single object, and it is more interesting to look at how these objects relate to each other than to look at the infinitely many (but effectively the same) possible details.

A: In the context of the connected components of a graph, the idea isn't very interesting, because the picture for connected components of a graph is already so clear and easy to understand geometrically.
But one of the principal techniques of mathematics is to find the underlying structure in one context, and then try to make an abstract model of it that might apply in other contexts as well.  By doing this, we understand the connections between the two contexts, and we can sometimes solve difficult problems in one context by applying tools imported from some other context.
We don't formulate the idea of a partition or an equivalence relation because we want to study the connected components of graphs.  For that it's unnecessary, because graph components are simple.
But that simplicity makes graph theory a good place to start understanding the idea of an equivalence relation, so that when you happen across it in a different context, where it might be more useful, you can recognize it and say "oh, we can model this with an equivalence relation, which means that it partitions the structure into components, and I already know some theorems about how that will work and some techniques I can use."
And you have a language for talking about these things, which can be applied in many different situations, so that when you say "consider the equivalence classes of (something) under (some relation)" you and the people you are talking to instantly get an idea of what is going on: these classes are disjoint, every object is in exactly one class, and so on, just like the components of a graph.
Examples

*

*What are fractions?  They are notations of the form $\frac ab$, where $a$ and $b$ are integers, and $b$ is not zero.  What are the rational numbers?  Just fractions?  No, they are the equivalence classes of fractions under the relation that says $\frac ab \equiv \frac cd$ if $ad=bc$, because for example $\frac 36$ and $\frac8{16}$ are the same rational number. Okay, big deal, we already know all about rational numbers.  But having identified the process, we can now apply it to all sorts of things more complicated than the integers.  Can we do the same construction for, say, polynomials?  (We can!)  Are the results useful and interesting?  (They are!)

*We can relate the complex numbers to polynomials by defining each complex number as a part of a partition induced on the set of polynomials by a certain equivalence relation.  By using different equivalence relations we can define different systems analogous to the complex numbers and use them to study properties of polynomials.

*Mathematics has a structure called a group, which is a model of a way in which a thing can have symmetry.  There is an important "quotient" operation on a group which arises when you consider certain symmetries to be "equivalent"; the quotient is a group that describes the symmetries of the resulting equivalence classes.

*This is a very specific example:  Consider some geometric object which has an even number of symmetries.  Then the object must have at least one symmetry which is an "involution": this means that if you perform the symmetry exactly twice, the object is back in its original position.  Objects without involutions must have an odd number of symmetries!  (An example is a table-saw blade with 37 teeth.)  I hope this is not obvious!  But it is very easy to show if you consider the right equivalence relation on the symmetries.

*An important technique in physics is to analyze the symmetries of the universe itself.  For example, the laws of conservation of momentum and energy are consequences of certain symmetries of space-time.  The abstract structure of spaces with these symmetries is often best understood as a particular quotient group.

*This "quotient" idea applies in other situations too.  Many kinds of mathematical structures are best understood as quotients, in this sense.  For example, in topology we often view a circle as being a quotient of a line segment, under the equivalence relation that says that the two endpoints are equivalent.  When we want to deal with a Möbius strip, we often formulate it as a certain quotient of a rectangle, where the equivalence relation makes certain points on the edge of the rectangle equivalent.  Many related objects, much weirder than the Möbius strip, can be dealt with similarly.
We don't study the identification between partitions and equivalence relations just because it is cool.  It is also useful in understanding other things.  Partitions and equivalence relations pop up everywhere.  Sometimes the partition is obvious, but the equivalence relation is easier to understand; then it is helpful to reinterpret the partition as an equivalence relation.  Sometimes it is useful to go in the other direction instead.

A: An equivalence relation is a very basic kind of structure that occurs all through different areas of mathematics.  You've mentioned two examples: modular arithmetic and connected components of graphs.  There are many others.  Yes, it would be possible to develop each one by itself without using the term "equivalence relation".  But mathematicians are supremely lazy: they don't like to duplicate effort.  And once you have the concept of equivalence relation, all you have to do is recognize that something is an equivalence relation and a whole set of tools is automatically available without further effort.

A: Although pretty much everything that needs to be said has already been addressed (much of it in MJD's excellent answer), I thought I'd share an excerpt from Princeton's Companion to Mathematics that was very helpful to me when I first encountered equivalence relations, equivalence classes, and all that jazz.

There are many situations in mathematics where one wishes to regard different objects as "essentially the same," and to help us make this idea precise there is a very important class of relations known as equivalence relations. Here are two examples. First, in elementary geometry one sometimes cares about shapes but
  not about sizes. Two shapes are said to be similar if one can be transformed into the other by a combination of reflections, rotations, translations, and enlargements. (See the similar shapes in the figure below.)

The relation "is similar to" is an equivalence relation. Second, when doing arithmetic modulo $m$, one does not wish to distinguish between two whole numbers that differ by a multiple of $m$: in this case one says that the numbers are congruent (mod $m$); the relation "is congruent (mod $m$) to" is another equivalence relation.
What exactly is it that these two relations have in common? The answer is that they both take a set (in the first case the set of all geometrical shapes, and in the second the set of all whole numbers) and split it into parts, called equivalence classes, where each part consists of objects that one wishes to regard as essentially the same. In the first example, a typical equivalence class is the set of all shapes that are similar to some given shape; in the second, it is the set of all integers that leave a given remainder when you divide by $m$ (for example, if $m=7$ then one of the equivalence classes is the set $\{\ldots,-16,-9,-2,5,12,19,\ldots\}$).
An alternative definition of what it means for a relation $\sim$, defined on a set $A$, to be an equivalence relation is that it has the following three properties. First, it is reflexive, which means that $x\sim x$ for ever $x$ in $A$. Second, it is symmetric, which means that if $x$ and $y$ are elements of $A$ and $x\sim y$, then it must also be the case that $y\sim x$. Third, it is transitive, meaning that if $x$, $y$, and $z$ are elements of $A$ such that $x\sim y$ and $y\sim z$, then it must be the case that $x\sim z$. (To get a feel for these properties, it may help if you satisfy yourself that the relations "is similar to" and "is congruent (mod $m$) to" both have all three properties, while the relation "$<$," defined on the positive integers, is transitive but neither reflexive nor symmetric.)
One of the main uses of equivalence relations is to make precise the notion of "quotient" constructions [as alluded to in MJD's answer].

A: There are a lot of great answers in here, but I thought I would include an important equivalence relation that arises in linear algebra.

If $A$ and $B$ are $n \times n$ matrices (over a field $F$), we say that $A$ and $B$ are similar and we write $A \sim B$ if there exists an invertible matrix $P$ such that $A = P^{-1}BP$.

When two matrices are similar, they represent the same linear transformation though possibly using different bases. If $A$ and $B$ are similar, then they represent the same underlying linear transformation and so $A$ and $B$ have the same rank, eigenvalues, determinant, trace, minimal polynomial, etc.
So why might we care about this? Well it can make computations easy for one. If you are presented with a matrix, you can determine what the underlying linear transformation is and there is often an "optimal" basis to represent that linear transformation that makes the corresponding matrix as simple as possible (i.e. lots of zeros). You can then use that particular matrix to do all of the computations you have in mind and save your self some time.

A: Equivalence relations are important because of the fundamental theorem of equivalence relations which shows every equivalence relation is a partition of the set and vice versa. Because partitioning is a very common idea in both pure and applied mathematics equivalence relations occur naturally but have the added benefit of allowing you to exploit the transitive, reflexive and symmetric properties of the relation.
I would also point out that "standard graph theory language" as you called it is to use equivalence relations. Very few theorems in mathematics are given the title "fundamental" and they show up in algebraic settings, logic, and even cutting and pasting surfaces together. It's very powerful and widely applicable modelling tool which is why they're ubiquitous in higher mathematics.

A: One common constructions of the real numbers involve equivalence relations:

The equivalence classes of Cauchy sequences of rationals under $\approx$, where for any sequences $f,g \in \mathbb{N} \to \mathbb{Q}$ we have $f \approx g$ iff $f(n)-g(n) \to 0$ as $n \to \infty$.

Furthermore, this is the only way to obtain a completion of a metric space in general.
But there are also many nice examples of equivalence relations in graph theory and topology:

*

*Existence of a cycle containing given edges in an undirected graph. Each equivalence class forms the edges of a 2-connected component.

*Existence of a cycle containing given vertices in a directed graph. The equivalence classes are called strongly connected components.

*The isomorphism between given finite graphs. A major open problem is whether the Graph Isomorphism Problem (to decide whether the given pair of graphs are isomorphic) is in P or NP-complete or neither.

*Whether given closed directed curves in the plane can be continuously deformed from one to the other without crossing the origin. The equivalence classes are exactly those determined by the winding number around the origin.

*Whether given non-self-intersecting closed curves in 3-dimensional space can be continuously deformed from one to the other without self-intersection. It turns out that this is equivalent to the equivalence relation on the knot diagrams under Reidemeister moves.

A: One thing I haven't seen mentioned yet: Equivalence relations give us a tool for removing distinctions we are not interested in, so that the ones we are studying are all that remain.
For example, in topology it is very common to construct a new topological space by gluing existing ones together. MJD touches on this, but didn't show the power. Look at a square sheet. I would like to glue the two sides together:

How do you do that in topology? By equivalence relation! If $S = [0,1]\times[0,1]$ is the square, then I define $$(x_0,y_0) \sim (x_1, y_1) \iff y_0 = y_1 \text { and } (x_0 = x_1 \text{ or } |x_0 - x_1| = 1)$$
Points in the middle or top and bottom of the square are equivalent to only themselves, but points on the LH side is equivalent to points on the RH side at the same height. I drop to the set of equivalence classes $S/\sim$, and note that it has been proven that topologies are compatible with any equivalence relation, and I'm done! Just by putting together that equivalence relation, I've defined a cylinder complete with topology. But that isn't the end. With just a little twist, I get something different:
$$(x_0,y_0) \sim (x_1, y_1) \iff (x_0,y_0) = (x_1,y_1)\text{ or } (|x_0 - x_1| = 1 \text{ and } y_0 = 1 - y_1)$$
Now the space of equivalence classes is the Möbius strip, completely defined as a topological space by that little bit.
In the original square I had distinctions that were not desirable (LH side vs RH side). So I created an equivalence relation that ignored those distinctions. By passing to the equivalence classes, I have now gotten rid of the unwanted distinctions while keeping what is useful.
I can also glue the top and bottom sides together:

*

*if both top and bottom are glued straight and right and left are glued straight, you get the torus.

*if the top and bottom are glued straight, but the right and left are glued twisted, you get the Klein bottle.

*If both top and bottom and right and left are glued with twists, you get the projective plane.

And if you just make all boundary points equivalent to each other, then the entire boundary collapses to a single point, and you get the sphere.
This is just a tiny taste of the power of this technique. Every compact surface without boundary can be built by cutting a bunch of holes in a sphere, and then to each hole, either glue a torus with a single hole in it (gluing the borders of the two holes together), or else glue the border of a Möbius strip to the border of the hole.
Similar examples can be found in any field of mathematics. I was originally going to use building the tangent space in differential geometry, but switched to surfaces as being more accessible.
Equivalence relations are one of the most powerful tools in the mathematician's tool box. You will find them used everywhere.

A: One instance in math where the notion of an equivalence relation is particularly useful, and makes the axioms of an equivalence relation seem natural, is considering a set modulo some equivalence relation.
It is also useful when you have some sets with some type of structure (groups, rings, topological spaces) and you want some way to think of them as being the same. We usually do this by defining an appropriate 'structure preserving function' between them and intuitively these functions should satisfy the axioms of an equivalence relation. Otherwise, what use would it be to have 3, say topological spaces, A,B,C such that we regard A and B as the same B and C as the same but not A and C as the same.
In short an equivalence relation is a nice way to make precise the manner in which we can regard two things as the same (even if they are not "equal"). For the laymen example suppose I am talking about all the shoes I own, but I don't want to talk about distinct shoes, I just want to talk about all the pairs of shoes I own. My blue nike that goes on my left foot is not actually the same shoe as my blue nike that goes on my right foot, but if I consider my shoes modulo the equivalence relation that they belong to the same pair - both of my blue nikes just became the same shoe. In essence I can talk about, or prove things about, both shoes by just considering one of them. Because modulo the equivalence relation, they are "equal".
Edit: added after original post.
Also, something I noticed as I was advancing into higher more abstract mathematics (which I am still doing!) was a common theme of certain math concepts. We love to take some normal concept such as 'equality' or 'distance' and say 'what are the properties that are inherent to distance' or 'what are the properties that are inherent to the notion of equality'. If you sit down and brainstorm for each, you will likely come up with the axioms for a metric space in the distance case, and the axioms of an equivalence relation in the equality case. Then, mathematicians love to say 'what happens in the more general setting where more general objects obey these properties?'. In this sense, the "motivation" would be more along the lines of curiosity. Then, if the theory is turning out to be fruitful and producing interesting results, that further motivates the study of this new 'generalized' notion. I actually haven't studied graph theory, so I can speak to much about your example regarding connected components, but my hunch is that using the equivalence relation is 'just general enough' in the sense that, by avoiding using an equivalence relation you could, at some point, be limiting your self by not being general enough or get wacky results because things are too general. Me personally, everything I study is algebraic - and equivalence relations are imperative. They help to study smaller algebraic structures without forgetting the old structure it came from - and again help make precise what it means for two algebraic structures to be equal.

A: We care about equivalence relations specially because one of the goals of mathematics in general is to classify objects, and, when you have an heuristically point of view, you can synthesize it in an abstract formulation, which will be useful to classify objects. For example, this notion of equivalence is useful to classify the "equivalence classes" modulo some fixed integer, but also is useful to determine the stalk of a sheave, and, as the underlying process is the same, you can relate equivalence classes of everything via functions or even functors. And, in some context, to prove the properties is not quite easy, for example, when you are trying to give a group structure to rational points over an elliptic curve, the associativity is a little bit difficult. That's the reason why we care about equivalence relations: classify.

A: Equivalence relations help generalize/relax the notion of equality, whereby you consider to be 'equal' (under the equivalence relation) elements that are in the same equivalence class. Equivalence relations are also used to construct quotient spaces (eg. in ring theory, in topology), which are ubiquitous in math (eg. the real numbers are a quotient space, the rational numbers are a quotient space; even the integers are a quotient space!).

A: There are even equivalence relations in Euclid, including congruence of triangles and similarity of triangles, as well as several theorems which give you conditions for checking congruence and similarity.
There's even a passage early in Euclid where he lists the properties of "equality", but when you see how these properties are used in Euclid then you see that these properties are actually being used (in modern language) as the definition of equivalence relations.

A: Equivalence relations generalize the concept of equality to different contexts. Suppose you are arranging your books. You decide to put the books with the same colour in the same bookshelf. In this scenario, you only care about what colour (assuming a book can be assigned a single colour without any ambiguity) a book is. So a blue science fiction novel and a blue book on abstract algebra are no different. They're both blue books.
Here, we have defined :
Book X ~ Book Y iff they have the same colour.

A: As mentioned in this answer, we care about equivalence relations because an equivalence relation $\sim$ on a set $X$ naturally determines a corresponding partition $P$ of $X$. But this raises the obvious next question: Why do we care about partitions?
Often (but not always) when studying a particular set $X$, we need to consider the elements $x \in X$, but not the elements $y \in x \in X$. A partition $P$ of $X$ achieves the same thing. We do not need to concern ourselves with the underlying elements of a given $p \in P$. We can use these elements $x \in p \in P$ if we want to, but they don't get in the way.
This property is the reason partitions are so important. And the fact that $X$ is the disjoint union of the sets $p \in P$ (by definition of partition) is the reason this property applies. Formally, it is the universal property of the coproduct, which is the disjoint union in the category of sets. Informally, the disjoint union is the "most general" way to combine a collection of sets $p \in P$ to get a set $X$. No information about the elements of the sets $p \in P$ is relevant, only the sets $p$ themselves. Contrast this to the case of a standard (non-disjoint) union, in which the result depends on whether or not the sets involved have common elements.
So the partition is a tool for "zooming out" from the elements $x \in X$ in a way that allows us to no longer worry about those original elements at all, and instead focus only on a larger scale structure on $X$, namely $P$.