text:
Q: Lightbox not working in Opencart i just downloaded Lightbox and created a new folder in my OPENCART 2.0.3.1 "jquery" folder (which already existed because of some other scripts).
Its located in "catalog/view/javascript/jquery/lightbox"
I then downloaded the header.tpl from "catalog/view/theme/default/template/common" and pasted this line
<link href="catalog/view/javascript/jquery/lightbox/dist/css/lightbox.css" rel="stylesheet">

between
 and <?php } ?> as the second last row. Its in  tag.
And the other one

right under some other  was located. Its in the  tag.
I then uploaded everything and i cannot get it working with the given code
Image #1

Any ideas?
URL: http://www.kwigx.com/test
Whole header.tpl:
<!DOCTYPE html>

<html dir="<?php echo $direction; ?>" lang="<?php echo $lang; ?>">

<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php echo $title; ?></title>
<base href="<?php echo $base; ?>" />
<?php if ($description) { ?>
<meta name="description" content="<?php echo $description; ?>" />
<?php } ?>
<?php if ($keywords) { ?>
<meta name="keywords" content= "<?php echo $keywords; ?>" />
<?php } ?>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<?php if ($icon) { ?>
<link href="<?php echo $icon; ?>" rel="icon" />
<?php } ?>
<?php foreach ($links as $link) { ?>
<link href="<?php echo $link['href']; ?>" rel="<?php echo $link['rel']; ?>" />
<?php } ?>

<link href="catalog/view/javascript/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen" />

<link href="catalog/view/javascript/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
<link href="//fonts.googleapis.com/css?family=Open+Sans:400,400i,300,700" rel="stylesheet" type="text/css" />
<link href="catalog/view/theme/default/stylesheet/stylesheet.css" rel="stylesheet">
<link href="catalog/view/javascript/jquery/lightbox/dist/css/lightbox.css" rel="stylesheet">
<?php foreach ($styles as $style) { ?>
<link href="<?php echo $style['href']; ?>" type="text/css" rel="<?php echo $style['rel']; ?>" media="<?php echo $style['media']; ?>" />
<?php } ?>

<?php foreach ($scripts as $script) { ?>

<?php } ?>
<?php echo $google_analytics; ?>

<body class="<?php echo $class; ?>">

    <?php echo $currency; ?>
    <?php echo $language; ?>

<a href="<?php echo $contact; ?>"> <?php echo $telephone; ?>

<a href="<?php echo $account; ?>" title="<?php echo $text_account; ?>" class="dropdown-toggle" data-toggle="dropdown"> <?php echo $text_account; ?>

            <?php if ($logged) { ?>

<a href="<?php echo $account; ?>"><?php echo $text_account; ?>

<a href="<?php echo $order; ?>"><?php echo $text_order; ?>

<a href="<?php echo $transaction; ?>"><?php echo $text_transaction; ?>

<a href="<?php echo $download; ?>"><?php echo $text_download; ?>

<a href="<?php echo $logout; ?>"><?php echo $text_logout; ?>

            <?php } else { ?>

<a href="<?php echo $register; ?>"><?php echo $text_register; ?>

<a href="<?php echo $login; ?>"><?php echo $text_login; ?>

            <?php } ?>

<a href="<?php echo $wishlist; ?>" id="wishlist-total" title="<?php echo $text_wishlist; ?>"> <?php echo $text_wishlist; ?>

<a href="<?php echo $shopping_cart; ?>" title="<?php echo $text_shopping_cart; ?>"> <?php echo $text_shopping_cart; ?>

<a href="<?php echo $checkout; ?>" title="<?php echo $text_checkout; ?>"> <?php echo $text_checkout; ?>

          <?php if ($logo) { ?>
          <a href="<?php echo $home; ?>"><img src="<?php echo $logo; ?>" title="<?php echo $name; ?>" alt="<?php echo $name; ?>" class="img-responsive" />
          <?php } else { ?>

<a href="<?php echo $home; ?>"><?php echo $name; ?>

          <?php } ?>

<?php echo $search; ?>

<?php echo $cart; ?>

<?php if ($categories) { ?>

<?php echo $text_category; ?>
      <button type="button" class="btn btn-navbar navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"></button>

        <?php foreach ($categories as $category) { ?>
        <?php if ($category['children']) { ?>

<a href="<?php echo $category['href']; ?>" class="dropdown-toggle" data-toggle="dropdown"><?php echo $category['name']; ?>

              <?php foreach (array_chunk($category['children'], ceil(count($category['children']) / $category['column'])) as $children) { ?>

                <?php foreach ($children as $child) { ?>

<a href="<?php echo $child['href']; ?>"><?php echo $child['name']; ?>

                <?php } ?>

              <?php } ?>

            <a href="<?php echo $category['href']; ?>" class="see-all"><?php echo $text_all; ?> <?php echo $category['name']; ?>

        <?php } else { ?>

<a href="<?php echo $category['href']; ?>"><?php echo $category['name']; ?>

        <?php } ?>
        <?php } ?>

<?php } ?>

A: It is because you (as you also say in the question), included two times the css file but not the .js file (dist/js/lightbox.js).
Remove the second
<link href="catalog/view/javascript/jquery/lightbox/dist/css/lightbox.css" rel="stylesheet">

And replace it by

That shouls make it work, check the console and see that the resources are present there.

EDIT, after you fixed that typo
The js file is mentioned in the PHP if statement <?php if ($categories) { ?> and therefor likely not included in the page. Put the line

One line  below, so after <?php } ?> and it should work.


text:
Q: Excel, Differences within Day for Multiple Dates Im currently facing a problem trying to find variations in a Database as follows:
>   Date   | Hour | Place 1 | Place 2 | Place 3 ... Place K (about 50)
>-------------------------------------------------------------
>1-1-2013  |  1   |  654    |  842    |  326    ...   842
>1-1-2013  |  2   |  847    |  247    |  625    ...   874
>1-1-2013  |  3   |  648    |  321    |  547    ...   624
>   ...    | ...  |  ...    |  ...    |  ...    ...   ...
>1-1-2013  |  24  |  748    |  654    |  548    ...   743
>2-1-2013  |  1   |  648    |  548    |  624    ...   845
>2-1-2013  |  2   |  654    |  348    |  247    ...   254
>   ...    |  ... |  ...    |   ...   |  ...    ...   ...

Dates as Day/Month/Year
What I need is a way to find the difference between the max and min value for each day for each place.
Either in one formula or using an aux sheet.
Im guessing some sort of Max(If and Min(If but I haven't been able to figure it out.
After getting those differences I need to know which are the top 5 biggest ones per day. (I know how to get the top 1, but I have no idea how to get the other 4).
Any help would be appreciated.

A: =MAX(IF($A$2:$A$26281=$A2,C$2:C$26281,""))-MIN(IF($A$2:$A$26281=$A2,C$2:C$26281,""))

Will find the difference between the smallest and largest value for a given place on a given day. Enter as an array formula by confirming with ctrl+shift+enter. Assuming your data starts at A1 and doesn't have any blank rows or columns, you can enter this formula for Place 1, autofill over to Place k, then autofill down. It will probably take forever to calculate.
You can use LARGE() to find the top five biggest values from that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Given a cubic fourfold is it possible to extend an isometry on the primitive cohomology to a complete marking? Let $X$ be a (smooth) cubic fourfold and $F$ its Fano variety of lines.
It is known that $F$ is an hyperkähler fourfold. Let $(L,u)$ be an abstract lattice with a distinguished element $u$ isomorphic to $(H^4(X,\mathbb{Z}),h^2)$ , where $h^2$ is the class of a hyperplane section of $X$. We recall that a complete marking of $X$ is an isometry $H^4(X,\mathbb{Z}) \to L$ which sends $h^2$ to $u$. Moreover, let $(L',u')$ an abstract lattice, with a distinguished element $u'$, isomorphic to the pair $(H^2(F,\mathbb{Z}),g)$, where $g$ is again the class of a hyperplane section of $F$. It is known that the Abel-Jacobi map induces an isometry
$$
H^4(X,\mathbb{Z})_{pr} \to H^2(F,\mathbb{Z})_{pr}(-1)
$$
and also we may identify the primitive part of $L'$ (i.e. the orthogonal complement of $u'$ in $L'$) with the lattice $L_0(-1)$, where $L_0$ is the orthogonal complement of $u$ in $L$. Now, let $(F,\psi)$ be a complete marking of $F$,  i.e. an isometry
$$
\psi \colon H^2(F,\mathbb{Z}) \to L' \text{ s.t. } g \mapsto u'
$$
which clearly induces an isometry
$$
\phi_0 \colon H^4(X,\mathbb{Z})_{pr} \to L_0.
$$
My questions are:

*

*Is it possible to extend $\phi_0$ to a complete marking $\phi$ of $X$, i.e. an isometry $\phi \colon H^4(X,\mathbb{Z}) \to L$, with $\phi(h^2)=u$?

*How is justified the existence of a complete marking for a cubic fourfold and for the variety of lines of a cubic fourfold?

*If we start from a complete marking of a cubic fourfold, is it possible to "extend" this to a complete marking for its variety of lines?


text:
Q: Current (e.g., ca. 2016 / MMa 10 / WP 4+) best practices for embedding interactive content in WordPress? My strategy, in the past, has been to embed interactive CDF files into my WordPress blog for student's to use (Much like the Wolfram Demonstration Project).
As many know 1) the 'Plug in' architecture of modern web browsers is evolving (see Google Chrome and no CDF support for example), 2) the 'official' WRI CDF plugin no longer works, 3) thankfully, there is Mathematica Toolbox for WP but I continue to have trouble getting it to format correctly and show CDFs properly in Safari / Mac OS  (e.g., CDF Failures, More CDF Failures, Mathematica Toolbox) and, finally,
4) WRI is advocating that we move this sort of stuff to the cloud™.
I suppose I'm all for the 'cloud™', but I'm getting really really tired of refactoring my work from various incarnations of webMathematica to embedded CDF and now to wolframcloud.com / WolframAPI. Furthermore, I venture that I have to make sure our college gives even more money to WRI to support this cloud stuff.
Using the WolframAPI for interactive stuff really doesn't seem to cut it (at least in my attempts) because the dynamic content keeps being sent back to be evaluated, etc, so you get crappy response.
Looking through the entirety of WRI's web, SE and the Internets-writ-large, I can't find a good "ok- look- here's how to do nice interactive / dynamic content with WordPress".
So I ask of you all, does anyone have suggestions for us WordPress-bound folk? Or am I thinking of this whole cloud/API thing the wrong way?
NB - @bobthechemist has asked a similar/related question here: How to design CloudObjects with reasonable CloudCredit costs


text:
Q: jquery widget help given:
jquery 1.3.2
jquery ui 1.7.2
I found the following jquery snippet but am having problems with it.
    $(document).ready(function() {
        $.widget("ui.hello", {
            options: {
                foo: "bar",
                baz: "quux"
            },
            _init: function() {
                var text = this.options.text;
                this.element.innerHTML("hello " + this.options.foo + " and " + this.options.baz);
            }
        });

        $("#thing").hello({ foo: "WORLD!" });
    });

Here's the problem:
this.options.baz); is undefined shouldn't it be using the default?
source:
http://blog.citrusbyte.com/2010/09/16/jquery-widgets-bringing-sanity/

A: this probably does not refer to the widget due to call context when the _init function is called. Try removing the this. and just refer to options like so:
this.element.innerHTML("hello " + options.foo + " and " + options.baz);

A: Here's what i ended up doing:
   <script type="text/javascript">
        $(document).ready(function() {
            $.widget("ui.hello", {

                _init: function() {
                    var text = this.options.text;
                    alert(this.options.baz);
                }
            });

            $.extend($.ui.hello, {
                defaults: {
                    baz: "whatever"
                }
            });
            $("#thing").hello({ foo: "WORLD!" });
        });
    </script>


text:
Q: Redux-Thunk Error: Actions must be plain objects. Use custom middleware for async actions I have a songbook app with firebase as a backend and struggling with an
Error: Actions must be plain objects. Use custom middleware for async actions.
Action creator
export const createAction = (type, payload) => ({ type, payload });

songs.action.js
import { getSongsAndDocuments } from '../../utils/firebase/firebase.utils';

export const fetchSongsStart = () => {
    createAction(SONGS_ACTION_TYPES.FETCH_SONGS_START);
};

export const fetchSongsSuccess = songs => {
    createAction(SONGS_ACTION_TYPES.FETCH_SONGS_SUCCESS, songs)
};

export const fetchSongsFailed = error => {
    createAction(SONGS_ACTION_TYPES.FETCH_SONGS_FAILED, error);
};

export const fetchSongsAsync = () => {
    return async dispatch => {
        dispatch(fetchSongsStart());

        try {
            const songs = await getSongsAndDocuments();
            dispatch(fetchSongsSuccess(songs));
        } catch (error) {
            dispatch(fetchSongsFailed(error));
        }
    };
};

Songbook.jsx
const dispatch = useDispatch();

useEffect(() => {
        dispatch(fetchSongsAsync());
    }, []);

store.js
import { compose, createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';

import { rootReducer } from './root-reducer';

const middleWares = [thunk];

const composeEnhancer =
    (process.env.NODE_ENV !== 'production' && window && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) ||
    compose;

const composedEnhancers = composeEnhancer(applyMiddleware(...middleWares));

export const store = createStore(rootReducer, undefined, composedEnhancers);

A: You have to return the result of calling createAction function in your action creator functions that is:
return createAction(SONGS_ACTION_TYPES.FETCH_SONGS_START);

instead of:
createAction(SONGS_ACTION_TYPES.FETCH_SONGS_START);


text:
Q: Localized string values for the size strings KB, MB, GB etc.? Where is this strins resources is stored on the Windows?
I need to show size corectly on native language of installed Windows.

A: Strings are very specific to the application that is using it. There are no generic string resouce in windows that an application can use. Of course you can write a program to search the resource in the windows folder to see which resource dll has the string that you are looking for and then use that resource dll in your application, but that is unadvisable. The reason being that, any new update of the windows that brings in resource dll changes can break your application.
As the other poster advises, you are better of writing your own resource dll and localize it in the languages that you want to support your application.

A: This is possible with disk quota library which is available since Windows XP:
function FindStringResourceEx(AInstance: HINST; AStringID: UINT; ALangID: UINT): PWideChar;
var
  Res: HRSRC;
  LoadedRes: HGLOBAL;
  I: Integer;
begin
  Result := nil;
  Res := FindResourceEx(AInstance, RT_STRING, MAKEINTRESOURCE(AStringID div 16 + 1), ALangID);
  if Res <> 0 then begin
    LoadedRes := LoadResource(AInstance, Res);
    if LoadedRes <> 0 then
    try
      Result := PChar(LockResource(LoadedRes));
      if Assigned(Result) then
      try
        for I := 0 to (AStringID and 15) - 1 do
          Inc(Result, PWord(Result)^ + 1);
      finally
        UnlockResource(THandle(Result));
      end;
    finally
      FreeResource(LoadedRes);
    end;
  end;
end;

function GetSizeStrings(out sBytes, sKB, sMB, sGB, sTB, sPB, sEB: string): Boolean;
var
  hLib: HMODULE;
  sRes: string;
  I: Integer;
  SL: TStringList;
begin
  Result := False;
  hLib := LoadLibrary('dskquoui.dll');
  if hLib > 0 then
  try
    SL := TStringList.Create;
    try
      sRes := FindStringResourceEx(hLib, 14472, MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL));
      Result := sRes <> '';
      if Result then begin
        sRes := sRes.Remove(0, 1);
        I := sRes.IndexOf(#$B);
        if I > -1 then
          sRes := sRes.Remove(I);
        SL.Delimiter := #2;
        SL.DelimitedText := sRes;
        sBytes := SL[0]; // bytes
        sKB    := SL[1]; // KB
        sMB    := SL[2]; // MB
        sGB    := SL[3]; // GB
        sTB    := SL[4]; // TB
        sPB    := SL[5]; // PB
        sEB    := SL[6]; // EB
      end;
    finally
      SL.Free;
    end;
  finally
    FreeLibrary(hLib);
  end;
  if not Result then begin
    sBytes := 'bytes';
    sKB    := 'KB';
    sMB    := 'MB';
    sGB    := 'GB';
    sTB    := 'TB';
    sPB    := 'PB';
    sEB    := 'EB';
  end;
end;


text:
Q: Emacs 26.3 on Fedora 31; run on Xming; scrollbars on the left Reading the Emacs manual on the GNU website, I found these two variables to set.  I put them in the .emacs file.  If I forget the quote on left, it fails to parse and I get an uncustomized emacs, so I'm sure the code is being evaluated.  I'm very rusty on Emacs LISP and have tried both 'left and "left" and neither work.
It's of secondary importance but having the scrollbar end when the file ends is typical and I think scroll-bar-adjust-thumb-portion should make that happen, instead of the default behavior of allowing you to scroll down to complete empty screen on the bottom.
I don't see any other scrollbar customizations in my config except for ctrl-z and alt-z for scrolling a line, and setting colors in in custom-set-faces.
(setq scroll-bar-mode 'left)
(setq scroll-bar-adjust-thumb-portion nil)

A: Use the function set-scroll-bar-mode, setq isn't enough for this particular variable.  Alternatively, use customize.  Note that this info is in the docs for scroll-bar-mode.
(set-scroll-bar-mode 'left)


text:
Q: Rspec / CapyBara how to expect record not to be saved I am testing a scenario with CapyBara where I expect the record NOT to be valid.
Given "the customer is not an athlete" do
  @customer = create(:athlete, :shop=> @shop, :first_name=>"Birglend", :last_name=>"Firglingham", :email=>"birglendfirglingham@gmail.com")
end

Then "I should not see that the customer is an athlete" do
  expect(page).not_to have_css('.athlete-row')
end

But before it can get to the "Then", I get an "ActiveRecord::RecordNotSaved" exception. This is caused by a before_save callback that I have to check if the customer is an athlete. If they're not an athlete, the method returns false and I do not want the record to be saved.e.g.
before_save :check_athlete_status

def check_athlete_status
 #return false unless self is an athlete
end

But I have a feeling this is not the correct way because this is an expected scenario and should not be throwing exceptions. How do I handle this?

A: You're trying to mix what a model test and a feature test do here.
There are a couple ways to test this.
I am going to drop the Given/Then syntax because I don't have any experience using that gem.
1) A model spec:
RSpec.describe Athlete, type: :model do
  context 'with invalid status' do
    let(:athlete) { FactoryGirl.build(:athlete, :shop=> @shop, :first_name=>"Birglend", :last_name=>"Firglingham", :email=>"birglendfirglingham@gmail.com") }

    it "raises an exception" do
      expect { athlete.save }.to raise_exception(ActiveRecord::RecordNotSaved)
    end
  end
end

2) You can also change the feature test to do whatever your Given is doing via the interface:
feature 'Admin creates athlete' do
  given(:athlete) { FactoryGirl.build(:athlete, :shop=> @shop, :first_name=>"Birglend", :last_name=>"Firglingham", :email=>"birglendfirglingham@gmail.com") }

  scenario 'with invalid status' do
    # We're testing that your custom callback stops saving the record.
    visit '/athletes/new'
    select @shop.title, from: 'Shop'
    fill_in 'First name', with: 'Birglend'
    fill_in 'Last name', with: 'Firglingham'
    fill_in 'Email', with: 'birglendfirglingham@gmail.com'
    select 'Not an athlete' from: 'Status'
    click_button 'Create Athlete'
    expect(page).to have_content 'There was an error creating the athlete'

    # I'd argue that these next lines, what you're trying to test, really shouldn't be tested here. What you should be testing is that the form provides feedback that the athlete record wasn't created.
    click_link 'Athletes'
    expect(page).not_to have_css('.athlete-row')
  end
end

I don't know what your interface is supposed to be doing, so I just made something up above. Hope that helps you go down the right path.

A: I think you should just use validations rather than a before_save.  You generally want to avoid before and after create/save callbacks unless you really need them.  That said you can expect the call to raise an exception if that is the desired behavior.


text:
Q: npm packaging without an entry point I plan to publish a JavaScript library as an npm package and I have a question regarding packages entry points and best practices: what would be the best practice when a package doesn't expose a single entry point?

*

*Explicitly declare exports without main

*Declare exports with main that would point to an index.js that would throw some helpful error message explaining how to consume the lib

My lib only is only compatible with node > 14 and we use the exports property to leverage subpath exports (as it's shipped both as ESM/CJS module format)
As declared, the library doesn't expose a single entry point and is meant to be consumed by importing a default export from a specific file. So the consumer would use the following semantics to import:
// ESM
import Foo from 'my-lib/path/filename1';

// CJS
const Foo = require('my-lib/path/filename1');


text:
Q: Hibernate/Spring - Rollback a transaction within a transaction Given this example code:
public class MyServiceImpl implements MyService {
    @Transactional
    public void myTransactionalMethod() {
        List<Item> itemList = itemService.findItems();
        for (Item anItem : itemList) {
            try {
                processItem(anItem);
            catch (Exception e) {
                // dont rollback here
                // rollback just one item
            }
        }

    }

    @Transactional
    public void processItem(Item anItem) {
        anItem.setSomething(new Something);
        anItem.applyBehaviour();
        itemService.save(anItem);
    }
}

Here is what I want to achieve:

*

*Only processItem(anItem); should rollback if exception occurs inside it.

*If exception occurs, myTransactionalMethod should continue, that means the for-each should end.

*If exception occurs inside myTransactionalMethod but not in processItem(anItem), myTransactionalMethod should rollback completely.

Is there a solution that doesn't involve managing transactions manually (without annotations)?.
Edit: I was thinking of using @Transactional(PROPAGATION=REQUIRES_NEW), don't know if it will work within the same bean though.

A: This is a common misunderstanding. Spring Transactions are implemented through proxies. Proxies are a wrapper around your class. You are accessing the processItem method from the same class, i.e. you don't go through the proxy, so you don't get any transactions. I explained the mechanism in this answer some years ago.
Solution: you need two separate Spring beans if you want nested transactions, both of them must be proxied by @Transactional.

A: It looks like a case for NESTED transaction. NESTED transaction starts a subtransaction with in the outer transaction with savepoint, allowing it rollback to that savepoint. Since it is a nested transactions they committed at the end of outer transation.
    public class MyServiceImpl implements MyService {
    @Transactional
    public void myTransactionalMethod() {
        List<Item> itemList = itemService.findItems();
        for (Item anItem : itemList) {
            try {
               // If you want to call this method directly configure your transaction use to aspectJ for transaction handling or refactor the code. Refer - [http://stackoverflow.com/questions/3423972/spring-transaction-method-call-by-the-method-within-the-same-class-does-not-wo][1]
                processItem(anItem);
            catch (Exception e) {
                // dont rollback here
                // rollback just one item
            }
        }

    }

    @Transactional(PROPAGATION = PROPAGATION.NESTED)
    // Throw some runtime exception to rollback or some checkedException with rollbackFor attribute set in the above annotation
    public void processItem(Item anItem) {
        anItem.setSomething(new Something);
        anItem.applyBehaviour();
        itemService.save(anItem);
    }
  }

Note that, I have not yet tried this below code see if that helps. You might have to tweak it, if needed. In fact I would love to give this code a try myself sometime soon.


text:
Q: How do I disable a system device programmatically? I am looking for way to disable a system device (either USB or internal) in C#.NET given either the PID & VID or the device name.
After searching I found Hardware Helper Library for C# on CodeProject.
But I need something that will work on XP, Vista & Windows 7 (both x86 and x64 operating systems)...the project I linked only works with XP and Vista x86...even when running the application with administrator privileges.
Does anyone know of a solution that would work on all operating systems?

A: Looks like there were two things in drf's version that were giving you trouble.   Your x64 problem was caused by SP_DEVINFO_DATA having a uint where an IntPtr was needed.   The second is that the SetupDiGetDevicePropertyW function is Vista+ and won't run on XP.
Here's a version with those two issues corrected.   I tested as x86 and AnyCPU on XPx86 and Win7X64.
public static class DisableHardware
{
    const uint DIF_PROPERTYCHANGE = 0x12;
    const uint DICS_ENABLE = 1;
    const uint DICS_DISABLE = 2;  // disable device
    const uint DICS_FLAG_GLOBAL = 1; // not profile-specific
    const uint DIGCF_ALLCLASSES = 4;
    const uint DIGCF_PRESENT = 2;
    const uint ERROR_INVALID_DATA = 13;
    const uint ERROR_NO_MORE_ITEMS = 259;
    const uint ERROR_ELEMENT_NOT_FOUND = 1168;

    static DEVPROPKEY DEVPKEY_Device_DeviceDesc;
    static DEVPROPKEY DEVPKEY_Device_HardwareIds;

    [StructLayout(LayoutKind.Sequential)]
    struct SP_CLASSINSTALL_HEADER
    {
        public UInt32 cbSize;
        public UInt32 InstallFunction;
    }

    [StructLayout(LayoutKind.Sequential)]
    struct SP_PROPCHANGE_PARAMS
    {
        public SP_CLASSINSTALL_HEADER ClassInstallHeader;
        public UInt32 StateChange;
        public UInt32 Scope;
        public UInt32 HwProfile;
    }

    [StructLayout(LayoutKind.Sequential)]
    struct SP_DEVINFO_DATA
    {
        public UInt32 cbSize;
        public Guid classGuid;
        public UInt32 devInst;
        public IntPtr reserved;     // CHANGE #1 - was UInt32
    }

    [StructLayout(LayoutKind.Sequential)]
    struct DEVPROPKEY
    {
        public Guid fmtid;
        public UInt32 pid;
    }

    [DllImport("setupapi.dll", SetLastError = true)]
    static extern IntPtr SetupDiGetClassDevsW(
        [In] ref Guid ClassGuid,
        [MarshalAs(UnmanagedType.LPWStr)]
string Enumerator,
        IntPtr parent,
        UInt32 flags);

    [DllImport("setupapi.dll", SetLastError = true)]
    static extern bool SetupDiDestroyDeviceInfoList(IntPtr handle);

    [DllImport("setupapi.dll", SetLastError = true)]
    static extern bool SetupDiEnumDeviceInfo(IntPtr deviceInfoSet,
        UInt32 memberIndex,
        [Out] out SP_DEVINFO_DATA deviceInfoData);

    [DllImport("setupapi.dll", SetLastError = true)]
    static extern bool SetupDiSetClassInstallParams(
        IntPtr deviceInfoSet,
        [In] ref SP_DEVINFO_DATA deviceInfoData,
        [In] ref SP_PROPCHANGE_PARAMS classInstallParams,
        UInt32 ClassInstallParamsSize);

    [DllImport("setupapi.dll", SetLastError = true)]
    static extern bool SetupDiChangeState(
        IntPtr deviceInfoSet,
        [In] ref SP_DEVINFO_DATA deviceInfoData);

    [DllImport("setupapi.dll", SetLastError = true)]
    static extern bool SetupDiGetDevicePropertyW(
            IntPtr deviceInfoSet,
            [In] ref SP_DEVINFO_DATA DeviceInfoData,
            [In] ref DEVPROPKEY propertyKey,
            [Out] out UInt32 propertyType,
            IntPtr propertyBuffer,
            UInt32 propertyBufferSize,
            out UInt32 requiredSize,
            UInt32 flags);

    [DllImport("setupapi.dll", SetLastError = true)]
    static extern bool SetupDiGetDeviceRegistryPropertyW(
      IntPtr DeviceInfoSet,
      [In] ref SP_DEVINFO_DATA  DeviceInfoData,
      UInt32 Property,
      [Out] out UInt32  PropertyRegDataType,
      IntPtr PropertyBuffer,
      UInt32 PropertyBufferSize,
      [In,Out] ref UInt32 RequiredSize
    );

    static DisableHardware()
    {
        DisableHardware.DEVPKEY_Device_DeviceDesc = new DEVPROPKEY();
        DEVPKEY_Device_DeviceDesc.fmtid = new Guid(
                0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67,
                0xd1, 0x46, 0xa8, 0x50, 0xe0);
        DEVPKEY_Device_DeviceDesc.pid = 2;

        DEVPKEY_Device_HardwareIds = new DEVPROPKEY();
        DEVPKEY_Device_HardwareIds.fmtid = new Guid(
            0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67,
            0xd1, 0x46, 0xa8, 0x50, 0xe0);
        DEVPKEY_Device_HardwareIds.pid = 3;
    }

    public static void DisableDevice(Func<string, bool> filter, bool disable = true)
    {
        IntPtr info = IntPtr.Zero;
        Guid NullGuid = Guid.Empty;
        try
        {
            info = SetupDiGetClassDevsW(
                ref NullGuid,
                null,
                IntPtr.Zero,
                DIGCF_ALLCLASSES);
            CheckError("SetupDiGetClassDevs");

            SP_DEVINFO_DATA devdata = new SP_DEVINFO_DATA();
            devdata.cbSize = (UInt32)Marshal.SizeOf(devdata);

            // Get first device matching device criterion.
            for (uint i = 0; ; i++)
            {
                SetupDiEnumDeviceInfo(info,
                    i,
                    out devdata);
                // if no items match filter, throw
                if (Marshal.GetLastWin32Error() == ERROR_NO_MORE_ITEMS)
                    CheckError("No device found matching filter.", 0xcffff);
                CheckError("SetupDiEnumDeviceInfo");

                string devicepath = GetStringPropertyForDevice(info,
                                           devdata, 1); // SPDRP_HARDWAREID

                // Uncomment to print name/path
                //Console.WriteLine(GetStringPropertyForDevice(info,
                //                         devdata, DEVPKEY_Device_DeviceDesc));
                //Console.WriteLine("   {0}", devicepath);
                if (devicepath != null && filter(devicepath)) break;

            }

            SP_CLASSINSTALL_HEADER header = new SP_CLASSINSTALL_HEADER();
            header.cbSize = (UInt32)Marshal.SizeOf(header);
            header.InstallFunction = DIF_PROPERTYCHANGE;

            SP_PROPCHANGE_PARAMS propchangeparams = new SP_PROPCHANGE_PARAMS();
            propchangeparams.ClassInstallHeader = header;
            propchangeparams.StateChange = disable ? DICS_DISABLE : DICS_ENABLE;
            propchangeparams.Scope = DICS_FLAG_GLOBAL;
            propchangeparams.HwProfile = 0;

            SetupDiSetClassInstallParams(info,
                ref devdata,
                ref propchangeparams,
                (UInt32)Marshal.SizeOf(propchangeparams));
            CheckError("SetupDiSetClassInstallParams");

            SetupDiChangeState(
                info,
                ref devdata);
            CheckError("SetupDiChangeState");
        }
        finally
        {
            if (info != IntPtr.Zero)
                SetupDiDestroyDeviceInfoList(info);
        }
    }
    private static void CheckError(string message, int lasterror = -1)
    {

        int code = lasterror == -1 ? Marshal.GetLastWin32Error() : lasterror;
        if (code != 0)
            throw new ApplicationException(
                String.Format("Error disabling hardware device (Code {0}): {1}",
                    code, message));
    }

    private static string GetStringPropertyForDevice(IntPtr info, SP_DEVINFO_DATA devdata,
        uint propId)
    {
        uint proptype, outsize;
        IntPtr buffer = IntPtr.Zero;
        try
        {
            uint buflen = 512;
            buffer = Marshal.AllocHGlobal((int)buflen);
            outsize=0;
            // CHANGE #2 - Use this instead of SetupDiGetDeviceProperty
            SetupDiGetDeviceRegistryPropertyW(
                info,
                ref devdata,
                propId,
                out proptype,
                buffer,
                buflen,
                ref outsize);
            byte[] lbuffer = new byte[outsize];
            Marshal.Copy(buffer, lbuffer, 0, (int)outsize);
            int errcode = Marshal.GetLastWin32Error();
            if (errcode == ERROR_INVALID_DATA) return null;
            CheckError("SetupDiGetDeviceProperty", errcode);
            return Encoding.Unicode.GetString(lbuffer);
        }
        finally
        {
            if (buffer != IntPtr.Zero)
                Marshal.FreeHGlobal(buffer);
        }
    }

}

A: I've built upon the XP-compatible answer and improved it a bit by adding a SafeDeviceInformationSetHandle class and performing some general code cleanup/refactoring, and am adding it here for posterity:
using System;
using System.Text;
using System.Security;
using System.ComponentModel;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;

public static class SetupApi
{
    private const string SETUPAPI = "setupapi.dll";
    private const int ERROR_INVALID_DATA = 13;
    private const int ERROR_INSUFFICIENT_BUFFER = 122;

    private class SafeDeviceInformationSetHandle : SafeHandleMinusOneIsInvalid
    {
        private SafeDeviceInformationSetHandle() : base(true)
        { }

        private SafeDeviceInformationSetHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHandle)
        {
            SetHandle(preexistingHandle);
        }

        [SecurityCritical]
        protected override bool ReleaseHandle()
        {
            return SetupDiDestroyDeviceInfoList(handle);
        }
    }

    #region Enumerations

    [Flags]
    private enum DIGCF : uint
    {
        DEFAULT         = 0x00000001,
        PRESENT         = 0x00000002,
        ALLCLASSES      = 0x00000004,
        PROFILE         = 0x00000008,
        DEVICEINTERFACE = 0x00000010
    }

    private enum SPDRP : uint
    {
        /// <summary>
        /// DeviceDesc (R/W)
        /// </summary>
        DEVICEDESC = 0x00000000,

        /// <summary>
        /// HardwareID (R/W)
        /// </summary>
        HARDWAREID = 0x00000001,

        /// <summary>
        /// CompatibleIDs (R/W)
        /// </summary>
        COMPATIBLEIDS = 0x00000002,

        /// <summary>
        /// unused
        /// </summary>
        UNUSED0 = 0x00000003,

        /// <summary>
        /// Service (R/W)
        /// </summary>
        SERVICE = 0x00000004,

        /// <summary>
        /// unused
        /// </summary>
        UNUSED1 = 0x00000005,

        /// <summary>
        /// unused
        /// </summary>
        UNUSED2 = 0x00000006,

        /// <summary>
        /// Class (R--tied to ClassGUID)
        /// </summary>
        CLASS = 0x00000007,

        /// <summary>
        /// ClassGUID (R/W)
        /// </summary>
        CLASSGUID = 0x00000008,

        /// <summary>
        /// Driver (R/W)
        /// </summary>
        DRIVER = 0x00000009,

        /// <summary>
        /// ConfigFlags (R/W)
        /// </summary>
        CONFIGFLAGS = 0x0000000A,

        /// <summary>
        /// Mfg (R/W)
        /// </summary>
        MFG = 0x0000000B,

        /// <summary>
        /// FriendlyName (R/W)
        /// </summary>
        FRIENDLYNAME = 0x0000000C,

        /// <summary>
        /// LocationInformation (R/W)
        /// </summary>
        LOCATION_INFORMATION = 0x0000000D,

        /// <summary>
        /// PhysicalDeviceObjectName (R)
        /// </summary>
        PHYSICAL_DEVICE_OBJECT_NAME = 0x0000000E,

        /// <summary>
        /// Capabilities (R)
        /// </summary>
        CAPABILITIES = 0x0000000F,

        /// <summary>
        /// UiNumber (R)
        /// </summary>
        UI_NUMBER = 0x00000010,

        /// <summary>
        /// UpperFilters (R/W)
        /// </summary>
        UPPERFILTERS = 0x00000011,

        /// <summary>
        /// LowerFilters (R/W)
        /// </summary>
        LOWERFILTERS = 0x00000012,

        /// <summary>
        /// BusTypeGUID (R)
        /// </summary>
        BUSTYPEGUID = 0x00000013,

        /// <summary>
        /// LegacyBusType (R)
        /// </summary>
        LEGACYBUSTYPE = 0x00000014,

        /// <summary>
        /// BusNumber (R)
        /// </summary>
        BUSNUMBER = 0x00000015,

        /// <summary>
        /// Enumerator Name (R)
        /// </summary>
        ENUMERATOR_NAME = 0x00000016,

        /// <summary>
        /// Security (R/W, binary form)
        /// </summary>
        SECURITY = 0x00000017,

        /// <summary>
        /// Security (W, SDS form)
        /// </summary>
        SECURITY_SDS = 0x00000018,

        /// <summary>
        /// Device Type (R/W)
        /// </summary>
        DEVTYPE = 0x00000019,

        /// <summary>
        /// Device is exclusive-access (R/W)
        /// </summary>
        EXCLUSIVE = 0x0000001A,

        /// <summary>
        /// Device Characteristics (R/W)
        /// </summary>
        CHARACTERISTICS = 0x0000001B,

        /// <summary>
        /// Device Address (R)
        /// </summary>
        ADDRESS = 0x0000001C,

        /// <summary>
        /// UiNumberDescFormat (R/W)
        /// </summary>
        UI_NUMBER_DESC_FORMAT = 0X0000001D,

        /// <summary>
        /// Device Power Data (R)
        /// </summary>
        DEVICE_POWER_DATA = 0x0000001E,

        /// <summary>
        /// Removal Policy (R)
        /// </summary>
        REMOVAL_POLICY = 0x0000001F,

        /// <summary>
        /// Hardware Removal Policy (R)
        /// </summary>
        REMOVAL_POLICY_HW_DEFAULT = 0x00000020,

        /// <summary>
        /// Removal Policy Override (RW)
        /// </summary>
        REMOVAL_POLICY_OVERRIDE = 0x00000021,

        /// <summary>
        /// Device Install State (R)
        /// </summary>
        INSTALL_STATE = 0x00000022,

        /// <summary>
        /// Device Location Paths (R)
        /// </summary>
        LOCATION_PATHS = 0x00000023,
    }

    private enum DIF : uint
    {
        SELECTDEVICE                   = 0x00000001,
        INSTALLDEVICE                  = 0x00000002,
        ASSIGNRESOURCES                = 0x00000003,
        PROPERTIES                     = 0x00000004,
        REMOVE                         = 0x00000005,
        FIRSTTIMESETUP                 = 0x00000006,
        FOUNDDEVICE                    = 0x00000007,
        SELECTCLASSDRIVERS             = 0x00000008,
        VALIDATECLASSDRIVERS           = 0x00000009,
        INSTALLCLASSDRIVERS            = 0x0000000A,
        CALCDISKSPACE                  = 0x0000000B,
        DESTROYPRIVATEDATA             = 0x0000000C,
        VALIDATEDRIVER                 = 0x0000000D,
        DETECT                         = 0x0000000F,
        INSTALLWIZARD                  = 0x00000010,
        DESTROYWIZARDDATA              = 0x00000011,
        PROPERTYCHANGE                 = 0x00000012,
        ENABLECLASS                    = 0x00000013,
        DETECTVERIFY                   = 0x00000014,
        INSTALLDEVICEFILES             = 0x00000015,
        UNREMOVE                       = 0x00000016,
        SELECTBESTCOMPATDRV            = 0x00000017,
        ALLOW_INSTALL                  = 0x00000018,
        REGISTERDEVICE                 = 0x00000019,
        NEWDEVICEWIZARD_PRESELECT      = 0x0000001A,
        NEWDEVICEWIZARD_SELECT         = 0x0000001B,
        NEWDEVICEWIZARD_PREANALYZE     = 0x0000001C,
        NEWDEVICEWIZARD_POSTANALYZE    = 0x0000001D,
        NEWDEVICEWIZARD_FINISHINSTALL  = 0x0000001E,
        UNUSED1                        = 0x0000001F,
        INSTALLINTERFACES              = 0x00000020,
        DETECTCANCEL                   = 0x00000021,
        REGISTER_COINSTALLERS          = 0x00000022,
        ADDPROPERTYPAGE_ADVANCED       = 0x00000023,
        ADDPROPERTYPAGE_BASIC          = 0x00000024,
        RESERVED1                      = 0x00000025,
        TROUBLESHOOTER                 = 0x00000026,
        POWERMESSAGEWAKE               = 0x00000027,
        ADDREMOTEPROPERTYPAGE_ADVANCED = 0x00000028,
        UPDATEDRIVER_UI                = 0x00000029,
        FINISHINSTALL_ACTION           = 0x0000002A,
        RESERVED2                      = 0x00000030,
    }

    private enum DICS : uint
    {
        ENABLE     = 0x00000001,
        DISABLE    = 0x00000002,
        PROPCHANGE = 0x00000003,
        START      = 0x00000004,
        STOP       = 0x00000005,
    }

    [Flags]
    private enum DICS_FLAG : uint
    {
        GLOBAL          = 0x00000001,
        CONFIGSPECIFIC  = 0x00000002,
        CONFIGGENERAL   = 0x00000004,
    }

    #endregion

    #region Structures

    [StructLayout(LayoutKind.Sequential)]
    private struct SP_DEVINFO_DATA
    {
        public UInt32 cbSize;
        public Guid ClassGuid;
        public UInt32 DevInst;
        public IntPtr Reserved;
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct SP_CLASSINSTALL_HEADER
    {
        public UInt32 cbSize;
        public DIF InstallFunction;
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct SP_PROPCHANGE_PARAMS
    {
        public SP_CLASSINSTALL_HEADER ClassInstallHeader;
        public DICS StateChange;
        public DICS_FLAG Scope;
        public UInt32 HwProfile;
    }

    #endregion

    #region P/Invoke Functions

    [DllImport(SETUPAPI, SetLastError = true, CharSet = CharSet.Unicode)]
    private static extern SafeDeviceInformationSetHandle SetupDiGetClassDevs(
        [In] ref Guid ClassGuid,
        [In] string Enumerator,
        IntPtr hwndParent,
        DIGCF Flags
    );

    [DllImport(SETUPAPI, SetLastError = true)]
    [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
    private static extern bool SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet);

    [DllImport(SETUPAPI, SetLastError = true)]
    private static extern bool SetupDiEnumDeviceInfo(
        SafeDeviceInformationSetHandle DeviceInfoSet,
        UInt32 MemberIndex,
        ref SP_DEVINFO_DATA DeviceInfoData
    );

    [DllImport(SETUPAPI, SetLastError = true)]
    private static extern bool SetupDiSetClassInstallParams(
        SafeDeviceInformationSetHandle DeviceInfoSet,
        [In] ref SP_DEVINFO_DATA deviceInfoData,
        [In] ref SP_PROPCHANGE_PARAMS classInstallParams,
        UInt32 ClassInstallParamsSize
    );

    [DllImport(SETUPAPI, SetLastError = true)]
    private static extern bool SetupDiChangeState(
        SafeDeviceInformationSetHandle DeviceInfoSet,
        [In, Out] ref SP_DEVINFO_DATA DeviceInfoData
    );

    [DllImport(SETUPAPI, SetLastError = true, CharSet = CharSet.Unicode)]
    private static extern bool SetupDiGetDeviceRegistryProperty(
        SafeDeviceInformationSetHandle DeviceInfoSet,
        [In] ref SP_DEVINFO_DATA DeviceInfoData,
        SPDRP Property,
        out RegistryValueKind PropertyRegDataType,
        [Out] byte[] PropertyBuffer,
        UInt32 PropertyBufferSize,
        out UInt32 RequiredSize
    );

    #endregion

    private static void CheckWin32CallSuccess(bool success)
    {
        if (!success)
        {
            throw new Win32Exception();
        }
    }

    private static string GetStringPropertyForDevice(SafeDeviceInformationSetHandle infoSet, ref SP_DEVINFO_DATA devInfo, SPDRP property)
    {
        RegistryValueKind regType;
        UInt32 requiredSize;

        if (!SetupDiGetDeviceRegistryProperty(infoSet, ref devInfo, property, out regType, null, 0, out requiredSize))
        {
            switch (Marshal.GetLastWin32Error())
            {
                case ERROR_INSUFFICIENT_BUFFER:
                    break;
                case ERROR_INVALID_DATA:
                    return string.Empty;
                default:
                    throw new Win32Exception();
            }
        }

        byte[] propertyBuffer = new byte[requiredSize];
        CheckWin32CallSuccess(SetupDiGetDeviceRegistryProperty(infoSet, ref devInfo, property, out regType, propertyBuffer, (uint)propertyBuffer.Length, out requiredSize));

        return Encoding.Unicode.GetString(propertyBuffer);
    }

    public static void EnableDevice(Func<string, bool> hardwareIdFilter, bool enable)
    {
        Guid nullGuid = Guid.Empty;
        using (SafeDeviceInformationSetHandle infoSet = SetupDiGetClassDevs(ref nullGuid, null, IntPtr.Zero, DIGCF.ALLCLASSES))
        {
            CheckWin32CallSuccess(!infoSet.IsInvalid);

            SP_DEVINFO_DATA devInfo = new SP_DEVINFO_DATA();
            devInfo.cbSize = (UInt32) Marshal.SizeOf(devInfo);

            for (uint index = 0; ; ++index)
            {
                CheckWin32CallSuccess(SetupDiEnumDeviceInfo(infoSet, index, ref devInfo));

                string hardwareId = GetStringPropertyForDevice(infoSet, ref devInfo, SPDRP.HARDWAREID);

                if ((!string.IsNullOrEmpty(hardwareId)) && (hardwareIdFilter(hardwareId)))
                {
                    break;
                }
            }

            SP_CLASSINSTALL_HEADER classinstallHeader = new SP_CLASSINSTALL_HEADER();
            classinstallHeader.cbSize = (UInt32) Marshal.SizeOf(classinstallHeader);
            classinstallHeader.InstallFunction = DIF.PROPERTYCHANGE;

            SP_PROPCHANGE_PARAMS propchangeParams = new SP_PROPCHANGE_PARAMS
                                                        {
                                                            ClassInstallHeader = classinstallHeader,
                                                            StateChange = enable ? DICS.ENABLE : DICS.DISABLE,
                                                            Scope = DICS_FLAG.GLOBAL,
                                                            HwProfile = 0,
                                                        };

            CheckWin32CallSuccess(SetupDiSetClassInstallParams(infoSet, ref devInfo, ref propchangeParams, (UInt32)Marshal.SizeOf(propchangeParams)));

            CheckWin32CallSuccess(SetupDiChangeState(infoSet, ref devInfo));
        }
    }
}

A: It can be done using P/Invoke methods on the Windows Setup API.  The API functions have been in Windows since W2K.  The API calls may require administrative rights.  Below is some rough code for using these APIs to disable (as well as enable) devices in C#, which allow invoking:
  DisableDevice(
        n => n.ToUpperInvariant().Contains("VID_3F20&PID_8A1D"),
        true); // true disables the device, false enables it

The first parameter is a filter that is passed the hardware ID.  This disables or enables the first device matching the provided filter.  There is no effect if the device is already in the target state.
The code follows.
public static class DisableHardware {
const uint DIF_PROPERTYCHANGE = 0x12;
const uint DICS_ENABLE = 1;
const uint DICS_DISABLE = 2;  // disable device
const uint DICS_FLAG_GLOBAL = 1; // not profile-specific
const uint DIGCF_ALLCLASSES = 4;
const uint DIGCF_PRESENT = 2;
const uint ERROR_NO_MORE_ITEMS = 259;
const uint ERROR_ELEMENT_NOT_FOUND = 1168;

static DEVPROPKEY DEVPKEY_Device_DeviceDesc;
static DEVPROPKEY DEVPKEY_Device_HardwareIds;

[StructLayout(LayoutKind.Sequential)]
struct SP_CLASSINSTALL_HEADER
{
    public UInt32 cbSize;
    public UInt32 InstallFunction;
}

[StructLayout(LayoutKind.Sequential)]
struct SP_PROPCHANGE_PARAMS
{
    public SP_CLASSINSTALL_HEADER ClassInstallHeader;
    public UInt32 StateChange;
    public UInt32 Scope;
    public UInt32 HwProfile;
}

[StructLayout(LayoutKind.Sequential)]
struct SP_DEVINFO_DATA
{
    public UInt32 cbSize;
    public Guid classGuid;
    public UInt32 devInst;
    public UInt32 reserved;
}

[StructLayout(LayoutKind.Sequential)]
struct DEVPROPKEY
{
    public Guid fmtid;
    public UInt32 pid;
}

[DllImport("setupapi.dll", SetLastError = true)]
static extern IntPtr SetupDiGetClassDevsW(
    [In] ref Guid ClassGuid,
    [MarshalAs(UnmanagedType.LPWStr)]
    string Enumerator,
    IntPtr parent,
    UInt32 flags);

[DllImport("setupapi.dll", SetLastError = true)]
static extern bool SetupDiDestroyDeviceInfoList(IntPtr handle);

[DllImport("setupapi.dll", SetLastError = true)]
static extern bool SetupDiEnumDeviceInfo(IntPtr deviceInfoSet,
    UInt32 memberIndex,
    [Out] out SP_DEVINFO_DATA deviceInfoData);

[DllImport("setupapi.dll", SetLastError = true)]
static extern bool SetupDiSetClassInstallParams(
    IntPtr deviceInfoSet,
    [In] ref SP_DEVINFO_DATA deviceInfoData,
    [In] ref SP_PROPCHANGE_PARAMS classInstallParams,
    UInt32 ClassInstallParamsSize);

[DllImport("setupapi.dll", SetLastError = true)]
static extern bool SetupDiChangeState(
    IntPtr deviceInfoSet,
    [In] ref SP_DEVINFO_DATA deviceInfoData);

[DllImport("setupapi.dll", SetLastError = true)]
static extern bool SetupDiGetDevicePropertyW(
        IntPtr deviceInfoSet,
        [In] ref SP_DEVINFO_DATA DeviceInfoData,
        [In] ref DEVPROPKEY propertyKey,
        [Out] out UInt32 propertyType,
        IntPtr propertyBuffer,
        UInt32 propertyBufferSize,
        out UInt32 requiredSize,
        UInt32 flags);

static DisableHardware()
{
    DisableHardware.DEVPKEY_Device_DeviceDesc = new DEVPROPKEY();
    DEVPKEY_Device_DeviceDesc.fmtid = new Guid(
            0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67,
            0xd1, 0x46, 0xa8, 0x50, 0xe0);
    DEVPKEY_Device_DeviceDesc.pid = 2;

    DEVPKEY_Device_HardwareIds = new DEVPROPKEY();
    DEVPKEY_Device_HardwareIds.fmtid = new Guid(
        0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67,
        0xd1, 0x46, 0xa8, 0x50, 0xe0);
    DEVPKEY_Device_HardwareIds.pid = 3;
}

public static void DisableDevice(Func<string, bool> filter, bool disable = true)
{
    IntPtr info = IntPtr.Zero;
    Guid NullGuid = Guid.Empty;
    try
    {
        info = SetupDiGetClassDevsW(
            ref NullGuid,
            null,
            IntPtr.Zero,
            DIGCF_ALLCLASSES);
        CheckError("SetupDiGetClassDevs");

        SP_DEVINFO_DATA devdata = new SP_DEVINFO_DATA();
        devdata.cbSize = (UInt32)Marshal.SizeOf(devdata);

        // Get first device matching device criterion.
        for (uint i = 0; ; i++)
        {
            SetupDiEnumDeviceInfo(info,
                i,
                out devdata);
            // if no items match filter, throw
            if (Marshal.GetLastWin32Error() == ERROR_NO_MORE_ITEMS)
                CheckError("No device found matching filter.", 0xcffff);
            CheckError("SetupDiEnumDeviceInfo");

            string devicepath = GetStringPropertyForDevice(info,
                                       devdata, DEVPKEY_Device_HardwareIds);
            // Uncomment to print name/path
            //Console.WriteLine(GetStringPropertyForDevice(info,
            //                         devdata, DEVPKEY_Device_DeviceDesc));
            //Console.WriteLine("   {0}", devicepath);
            if (devicepath != null && filter(devicepath)) break;

        }

        SP_CLASSINSTALL_HEADER header = new SP_CLASSINSTALL_HEADER();
        header.cbSize = (UInt32)Marshal.SizeOf(header);
        header.InstallFunction = DIF_PROPERTYCHANGE;

        SP_PROPCHANGE_PARAMS propchangeparams = new SP_PROPCHANGE_PARAMS();
        propchangeparams.ClassInstallHeader = header;
        propchangeparams.StateChange = disable ? DICS_DISABLE : DICS_ENABLE;
        propchangeparams.Scope = DICS_FLAG_GLOBAL;
        propchangeparams.HwProfile = 0;

        SetupDiSetClassInstallParams(info,
            ref devdata,
            ref propchangeparams,
            (UInt32)Marshal.SizeOf(propchangeparams));
        CheckError("SetupDiSetClassInstallParams");

        SetupDiChangeState(
            info,
            ref devdata);
        CheckError("SetupDiChangeState");
    }
    finally
    {
        if (info != IntPtr.Zero)
            SetupDiDestroyDeviceInfoList(info);
    }
}
private static void CheckError(string message, int lasterror = -1)
{

    int code = lasterror == -1 ? Marshal.GetLastWin32Error() : lasterror;
    if (code != 0)
        throw new ApplicationException(
            String.Format("Error disabling hardware device (Code {0}): {1}",
                code, message));
}

private static string GetStringPropertyForDevice(IntPtr info, SP_DEVINFO_DATA devdata,
    DEVPROPKEY key)
{
    uint proptype, outsize;
    IntPtr buffer = IntPtr.Zero;
    try
    {
        uint buflen = 512;
        buffer = Marshal.AllocHGlobal((int)buflen);
        SetupDiGetDevicePropertyW(
            info,
            ref devdata,
            ref key,
            out proptype,
            buffer,
            buflen,
            out outsize,
            0);
        byte[] lbuffer = new byte[outsize];
        Marshal.Copy(buffer, lbuffer, 0, (int)outsize);
        int errcode = Marshal.GetLastWin32Error();
        if (errcode == ERROR_ELEMENT_NOT_FOUND) return null;
        CheckError("SetupDiGetDeviceProperty", errcode);
        return Encoding.Unicode.GetString(lbuffer);
    }
    finally
    {
        if (buffer != IntPtr.Zero)
            Marshal.FreeHGlobal(buffer);
    }
}
}

A: I managed to solve this Problem using DevManView.exe (freeware):

*

*Download DevManView.exe and put the .exe file somewhere:
http://www.nirsoft.net/utils/device_manager_view.html

*Go to your Device Manager and search for the Name of the device you want to enable/disable.

*In C#, create and start a new process for disabling the device (using the name of the device you found in the device manager).
Process devManViewProc = new Process();
devManViewProc.StartInfo.FileName = @"<path to DevManView.exe>\DevManView.exe";
devManViewProc.StartInfo.Arguments = "/disable \"<name of the device>\"";
devManViewProc.Start();
devManViewProc.WaitForExit();

*And enable it again.
devManViewProc.StartInfo.Arguments = "/enable \"<name of the device>\"";
devManViewProc.Start();
devManViewProc.WaitForExit();

A: I'm using devcon.exe to solve this issue.
with the following code:
public class DevconHelper
{
    private readonly ILogger logger;
    public DevconHelper(ILogger logger)
    {
        this.logger = logger;
    }

    readonly static string devconPath = @"devcon\" + (Environment.Is64BitOperatingSystem ? "x64" : "x86") + @"\devcon.exe";
    readonly static Regex parseHwidsOutput = new Regex(@"(?<id>[^\n]+)\n {4}Name: (?<name>[^\n]+)\n {4}Hardware IDs:\n(?<hwids>(?: {8}[^\n]+\n?)+)");
    readonly static Regex parseEnableDisableOutput = new Regex(@"(\d+) device\(s\) (are enabled|disabled)\.");

    public async Task<IEnumerable<Device>> GetDevicesAsync(string filterString = "*")
    {
        logger.Trace("GetDevicesAsync");
        using (var listDevicesProcess = Process.Start(new ProcessStartInfo(devconPath, "hwids " + filterString) { RedirectStandardOutput = true, UseShellExecute = false }))
        {
            var content = await listDevicesProcess.StandardOutput.ReadToEndAsync();

            var matches = parseHwidsOutput.Matches(content.Replace(Environment.NewLine, "\n")); //Regex is based on \n
            logger.Trace("GetDevicesAsync process output: {Content}, parsed {NumberOfMatches}, devconPath: {DevconPath}", content, matches.Count, devconPath);
            return matches.OfType<Match>().Select(match =>
            {
                var id = match.Groups["id"].Value;
                var name = match.Groups["name"].Value;
                var hwids = match.Groups["hwids"].Value.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries).Select(line => line.Trim());
                return new Device() { Id = id, Name = name, HardwareIds = hwids.ToArray() };
            });
        }
    }

    public async Task<bool> EnableAsync(Device device)
    {
        logger.Trace("EnableAsync");
        using (var disableProcess = Process.Start(new ProcessStartInfo(devconPath, "enable " + device.HardwareIds.First()) { RedirectStandardOutput = true, UseShellExecute = false }))
        {
            var content = await disableProcess.StandardOutput.ReadToEndAsync();
            var lastLine = content.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).Last();
            logger.Trace("EnableAsync process output: {Content}, LastLine: {LastLine}", content, lastLine);
            return parseEnableDisableOutput.IsMatch(lastLine);
        }
    }

    public async Task<bool> DisableAsync(Device device)
    {
        logger.Trace("DisableAsync");
        using (var disableProcess = Process.Start(new ProcessStartInfo(devconPath, "disable " + device.HardwareIds.First()) { RedirectStandardOutput = true, UseShellExecute = false }))
        {
            var content = await disableProcess.StandardOutput.ReadToEndAsync();
            var lastLine = content.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).Last();
            logger.Trace("DisableAsync process output: {Content}, LastLine: {LastLine}", content, lastLine);
            return parseEnableDisableOutput.IsMatch(lastLine);
        }
    }

    public class Device
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string[] HardwareIds { get; set; }
    }
}

Then you can use it like this.
var devices = await devconHelper.GetDevicesAsync();
var device = devices.FirstOrDefault(x => x.Name == Settings.GPSDeviceName);
if (device != null)
{
    logger.Trace("Found the device!");
    logger.Info("Disabling the device!");
    if (await devconHelper.DisableAsync(device))
    {
        logger.Info("GPS device has been disabled!");
    }
    else
    {
        logger.Warn("Failed to disable the device!");
    }
    await Task.Delay(1000);
    logger.Info("Enabling device!");
    if (await devconHelper.EnableAsync(device))
    {
        logger.Info("Device has been enabled!");
    }
    else
    {
        logger.Fatal("Failed to enable the device!");
    }
}
else
{
    logger.Warn("Could not find the device!");
}

This has been tested on windows 10 and 8.1 and works as intended!

A: It can be done using P/Invoke methods on the Windows Setup API. The API functions have been in Windows since W2K. The API calls may require administrative rights. Below is some rough code for using these APIs to disable (as well as enable) devices in C#, which allow invoking:
DisableDevice(
    n => n.ToUpperInvariant().Contains("VID_3F20&PID_8A1D"),
    true); // true disables the device, false enables it

This works on Windows 10 on Dell inspi 15.


text:
Q: android how to save date in sqlite I am retrieving date from datepicker and passing its value in main activity and setting this date in a textView. Well textview shows the correct date which has been picked from datepicker but when I saves this date by pulling from date textview, database entry always shows the current(today's) date. Please find my code below
//Database code
public long insertcontact(String date)
    {
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd");
        Date ddate = new Date();
initialValues.put(KEY_DATE, dateFormat.format(ddate));
return db.insert(DATABASE_TABLE, null, initialValues);
}

A: Mistake:
You are trying to put new Date() value which returns the current date and time.
Date ddate = new Date();
initialValues.put(KEY_DATE, dateFormat.format(ddate));

Solution:
I assume you are passing selected date in insertcontact(String date) as a parameter, which is actually a correct date.
Date ddate = new Date();
initialValues.put(KEY_DATE, dateFormat.format(date));


text:
Q: Cursor not showing up in UITextView Can anyone think of a reason that the blinking cursor would not show up in a UITextView? I have a custom control that is just a subclass of UIView and it has a UITextView in it, but the cursor doesn't appear when it gets focus. The keyboard appears, and the text appears as you type, but there is no cursor, and I can't figure out why.
Any thoughts?...

A: You might be setting improperly a contentSize and/or frame for the component so it is too small to be visible or the control is out of the screen. Please go in Simulator to Debug->Color Blended Layers to see whether those values are set correctly.
EDIT:
With new Xcodes (probably introduced in Xcode 6) you can debug this kind of issues by clicking "Debug View Hierarchy" (it is one of the icons on the bottom bar)

A: The textfield is showing the cursor but you are not able to see the color, just because the tint color of your text field is set to default most probably as in my case it was.
Just select you textField in storyboard and Select the link color of your wish. Refer to the image attached.

A: I changed the tint color of all of my UITextViews and the cursor started showing on the next build.

A: You may have changed the tint color in your custom UITextView. If the tint color is the same as the background color (normally white), then it will appear invisible.

A: Simple workaround seems to work by introducing a delay and then calling firstResponder, like so:
-(void)begin{

    [self performSelector:@selector(first) withObject:nil afterDelay:0.01f];
}
-(void)first{

    [tf becomeFirstResponder];
}

A: In my case, I called becomeFirstResponder in a viewDidLoad method. I moved the call into viewDidAppear and it worked for me.

A: a working crutch for me:
   DispatchQueue.main.async {

      self.textView.becomeFirstResponder()
      self.textView.insertText(" ")
      self.textView.deleteBackward()
 }

A: The solution above did not work in my case. The issue in my case is that the UIView that acts as the cursor has isOpaque set to false when the UITableViewCell's selectionStyle is anything but none. This seems to only occur under a race condition I haven't gotten to the bottom of yet.
FWIW here's how I debugged this:

*

*select your UITextFieldView

*open the Debug View Hierarchy. You should see the UIView that would represent the cursor in the correct position, but it does not appear in the UI.

*right click the cursor's UIView and select "Print Description...". The description indicates OPAQUE=NO
Unfortunately, the UITextSelectionView class that owns this UIView is private and therefore there is no non-hacky way to programmatically update isOpaque.
This doesn't seem to be an issue in every implementation, however, here's the relationship between my views.
My text view delegate
extension FooViewController: UITextViewDelegate {
    private func updateSelection(selectedIndex indexPath: IndexPath) {
        if let oldSelected = self.table.indexPathForSelectedRow {
            tableDelegate.tableView(table, didDeselectRowAt: oldSelected)
        }
        tableDelegate.tableView(table, didSelectRowAt: indexPath)
    }

    func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
        guard let rowCell = getParentCell(forTextView: textView), // loops through table row cells
            !rowCell.isSelected,
            let indexPath = self.table.indexPath(for: rowCell)
            else { return true }

        updateSelection(selectedIndex: indexPath)
        return false
    }

and my table delegate:
class TableViewDelegate: NSObject, UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.selectRow(at: indexPath, animated: false, scrollPosition: UITableView.ScrollPosition.none)
    }
}

A: For me, the problem was caused by embedding a UITextField in a UIToolbar. Once I had replaced the container for a simple UIView, the cursor worked again.

A: For me it wasn't the tintColor, it was caused by overriding caretRect method. Removing this method solved my case
open override func caretRect(for position: UITextPosition) -> CGRect {
       return CGRect.zero
   }


text:
Q: Jquery/Ajax call with timer I have a php page that echos out rows from a database. I want to call it via jquery/ajax every 30 seconds. But I also want to be able to call the page at any time so that if I add a record via the form, once the form submits I want the page via called to ajax to update the results right away. Can anyone point me in the right direction or provide some base code so I can try to figure this out? Still very new to jquery/ajax.

A: If you want to set something on a timer, you can use JavaScript's setTimeout or setInterval methods:
setTimeout ( expression, timeout );
setInterval ( expression, interval );

Where expression is a function and timeout and interval are integers in milliseconds. setTimeout runs the timer once and runs the expression once whereas setInterval will run the expression every time the interval passes.
So in your case it would work something like this:
setInterval(function() {
    //call $.ajax here
}, 5000); //5 seconds

As far as the Ajax goes, see jQuery's ajax() method. If you run an interval, there is nothing stopping you from calling the same ajax() from other places in your code.

If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:
setInterval() returns an integer which is the ID of the interval.
var id = setInterval(function() {
    //call $.ajax here
}, 30000); // 30 seconds

If you store that ID in a variable, you can then call clearInterval(id) which will stop the progression.
Then you can reinstantiate the setInterval() call after you've completed your ajax form submission.


text:
Q: Does IBM Dataworks support CSV delimiters? Does the IBM DataWorks Data Load API support CSV files as input source?

A: The answer is yes. To accomplish this, you have provide the structure of the file in the request payload.  This is explained in the API documentation Creating a Data Load Activity.  This an excerpt of the documentation:

Within the columns array, specify the columns to provision data
  from. If Analytics for Hadoop, Amazon S3, or SoftLayer Object Storage
  is the source, you must specify the columns. If you specify columns,
  only the columns that you specify are provisioned to the target...

The Data Load application included in DataWorks is provided just as an example and assumes the input file has 2 columns, the first being an INTEGER and the second one a VARCHAR.
Note: This question was answered on dW Answers by user emalaga.


text:
Q: Valor normal dentro de una función en Javascript Actualmente tengo el siguiente código:
// CONFIG ////////////////
var initialBetAmount = 100; // apuesta realizada
var betColor = 2;    // 1 o 2
var multiplicador = 10; // multiplicador de martingala dual
//////////////////////////

function bet()
{
    return //si lo elimino sigue dandome error undefined
    var bet = document.getElementById("bet-input");
    bet.value = initialBetAmount;
}

¿Qué puede fallar? Tanto si tengo el return como sino, me devuelve valor undefined.
Si esas lineas las pongo fuera del function, funcionan bien y me ponen el valor que yo quiera en el espacio.
¿Alguna idea?

A: Para completar lo que tienes, tu código debería quedar así:
Recuerda que debes tener un elemento html que tenga el id "bet-input". Define la variable bet2 fuera de la función, de la otra manera sólo puedes acceder al objeto dentro de la función.

    // CONFIG ////////////////
        var initialBetAmount = 100; // apuesta realizada
        var betColor = 2;    // 1 o 2
        var multiplicador = 10; // multiplicador de martingala dual
        //////////////////////////
        var bet2 = document.getElementById("bet-input");
        function bet()
         {

           bet2.value = initialBetAmount;
           return bet2.value;
         }

         var valor = bet();// valor contendrá el resultado de la función bet.
console.log(valor);

javascriptjs

A: Hice la prueba de tu codigo y no sale undefined

// CONFIG ////////////////
    var initialBetAmount = 100; // apuesta realizada
    var betColor = 2;    // 1 o 2
    var multiplicador = 10; // multiplicador de martingala dual
    //////////////////////////

    function bet()
     {
       var bet = document.getElementById("bet-input");
       bet.value = initialBetAmount;
       return bet.value;
     }

     var valor = bet();// valor contendrá el resultado de la función bet.
console.log("no sale undefined",valor);


text:
Q: Incorrect diffInMonths laravel Carbon between Feb 1 and Mar 1 I found a weird result when I use diffInMonths of laravel Carbon. Can anyone explain for me why it works like this. Is it a bug? And how to get it correct.
$d1 = new Carbon('2018-02-01');
$d2 = new Carbon('2018-03-01');
dd($d1->diffInMonths($d2));

Output was: 0 (Expected: 1)
BUT
$d1 = new Carbon('2018-02-02');
$d2 = new Carbon('2018-03-02');
dd($d1->diffInMonths($d2));

Output was: 1
My setting timezone is "Asia/Ho_Chi_Minh" (GMT +7). PHP Version 7.0.22. OS: Ubuntu Server 16.04
This weird result happends only between February 1 and March 1, other months result as expected.
I also try date_diff instead of Carbon
$d1 = new \DateTime('2018-02-01');
$d2 = new \DateTime('2018-03-01');
$diff = date_diff($d1,$d2);
dump($diff->m);
dump($diff->d);
die;

It returns months: 0, and days: 28 (Not month: 1, days: 0 as expected)
So the problem may be from PHP not from Carbon.

A: Very peculiar behaviour:
$jan = new Illuminate\Support\Carbon("2022-01-01");
$feb = new Illuminate\Support\Carbon("2022-02-01");
$mar = new Illuminate\Support\Carbon("2022-03-01");

$feb->diffInMonths($mar); // 0
$feb->floatDiffInMonths($mar); // 1.0

$jan->diffInMonths($mar); // 1
$jan->floatDiffInMonths($mar); // 2.0

Solution
Use intval on floatDiffInMonths:
intval($feb->floatDiffInMonths($mar)); // 1
intval($jan->floatDiffInMonths($mar)); // 2

A: You should set timezone in Carbon,
 Now it works:
   Carbon::now(new \DateTimeZone('Asia/Ho_Chi_Minh'));
    $d1 = new Carbon('2018-02-01');
    $d2 = new Carbon('2018-03-01');
    dd($d1->diffInMonths($d2));

A: The code you provided should work. Although you can try alternative of Carbon. Try DateTime

$d1 = new DateTime('2018-02-01');
$d2 = new DateTime('2018-03-01');
$diff = date_diff($d1,$d2);
dd($diff->m);

A: I think setting the timezone to UTC should solve this. I had the same problem when the timezone was set to Europe/Zurich:
>>> $last = new \Carbon\Carbon('2019-02-01');
=> Carbon\Carbon @1548975600 {#2381
     date: 2019-02-01 00:00:00.0 Europe/Zurich (+01:00),
   }
>>> $now = (\Carbon\Carbon::now())->day(1)->setTime(0, 0, 0);
=> Carbon\Carbon @1551394800 {#2371
     date: 2019-03-01 00:00:00.0 Europe/Zurich (+01:00),
   }
>>> $now->diffInMonths($last)
=> 0

After changing the timezone to UTC:
>>> $last = new \Carbon\Carbon('2019-02-01', 'UTC');
=> Carbon\Carbon @1548979200 {#2380
     date: 2019-02-01 00:00:00.0 UTC (+00:00),
   }
>>> $now = (\Carbon\Carbon::now('UTC'))->day(1)->setTime(0, 0, 0);
=> Carbon\Carbon @1551398400 {#2394
     date: 2019-03-01 00:00:00.0 UTC (+00:00),
   }
>>> $now->diffInMonths($last)
=> 1

A: I encountered the same thing, but the above methods doesn't work for me. So I write this and it works perfectly fine.
$prevMonth = Carbon::parse("01-02-2019");
$thisMonth = Carbon::parse("01-03-2019");
$part1 = ($prevMonth->format('Y') * 12) + $prevMonth->format('m');
$part2 = ($thisMonth->format('Y') * 12) + $thisMonth->format('m');
$diff = abs($part1 - $part2); // To make the result always positive abs()

Result:-
1 // with abs()
-1 // without abs()

A: The same story, finally wrote my own function for calculating month difference:
function month_diff(\Carbon\Carbon $date1, \Carbon\Carbon $date2){
$ts1 = $date1->startOfDay()->getTimestamp();
$ts2 = $date2->startOfDay()->getTimestamp();

$year1 = intval(date('Y', $ts1));
$year2 = intval(date('Y', $ts2));

$month1 = intval(date('m', $ts1));
$month2 = intval(date('m', $ts2));

$day1 = intval(date('d', $ts1));
$day2 = intval(date('d', $ts2));

$res = (($year2 - $year1) * 12) + ($month2 - $month1) - (($day2 >= $day1) ? 0 : 1);

return $res >= 0 ? $res : 0; }

here, pay attention to the days of the month too, also may take time into account too.


text:
Q: Clojure - placeholder in sql commands I want to have an update function. So there are 6 params for this func.
(defn update-user-profile [id email slogan title twitter web_site]
  (sql/with-connection
   db
   (sql/do-commands "update users SET email=? slogan=?
                    title=? twitter=? web_site=? WHERE id=?"id,email,slogan...

This is what i want. Is it possible or OK in Clojure?
p.s i know there is a sql/update-values. But each time i try this, i get an error like wrong number of arguments(7) which is i dont understand.
edit : i solved my question with idiomatic way. thank you again.


text:
Q: SQL to retrieve last 3 records if they match a certain criteria I'm looking for the following
TBL_TRANSACTION
(
  ACCOUNT ID
  TRANSACTION_DETAILS
  TRANSACTION_DATE
  TRANSACTION_TYPE
)

ACC_ID TRANS_DTLS TRANS_DATE TRANS_TYPE
1001   Petrol     01-Sept-2015 Cash
1001   Petrol     01-July-2015 Cash
1001   Fruit      01-May-2015 Cash
1001   Biscuits   01-Feb-2015 Cash
1002   Cereal     01-Sept-2015 Cash
1002   Soft Drinks 01-July-2015 Card
1002   Water      01-May-2015 Cash
1002   Water      01-Feb-2015 Card
1003   Milk       01-Sept-2015 Card
1003   Petrol     01-July-2015 Cash
1003   Cereal     01-May-2015 Cash
1003   Biscuits   01-Feb-2015 Cash

Basically, I want to be able to pull back the records of the account IF the last 3 transactions have ALL been paid for by Cash.
Regarding the data above, Account 1001 would be returned as the last 3 transactions have all been Cash, where are 1002 and 1003 would not as at least 1 of the last 3 transactions are card payments.

A: You didn't tag your RDBMS, so for ANSI-SQL you can use ROW_NUMBER() :
SELECT tr.* FROM tbl_transaction tr
INNER JOIN(
    SELECT t.acc_id FROM (
        SELECT t.acc_id,t.trans_type,
               ROW_NUMBER() OVER(PARTITION BY t.acc_id ORDER BY t.trans_date DESC) as rnk
        FROM tbl_transaction t) tt
    WHERE tt.rnk < 4 and t.trans_type = 'Cash'
    GROUP BY tt.acc_id having count(*) = 3) s
 ON(t.acc_id = s.acc_id)

A: with cte as
( select ACCOUNT_ID
       , TRANSACTION_DETAILS
       , TRANSACTION_DATE
       , TRANSACTION_TYPE
       , row_number() over (partition by ACCOUNT_ID order by TRANSACTION_DATE desc) as rn
  from TBL_TRANSACTION
)

select cm.*
from cte cm
where cm.rn <= 3
-- and cm.TRANSACTION_TYPE = 'cash'
and cm.ACCOUNT_ID not in ( select cx.ACCOUNT_ID
                           from cte cx
                           where rn <= 3
                           and TRANSACTION_TYPE <> 'cash' )

A: You can get the last three accounts using row_number(). You can get the last three cash account using row_number() as well, with a different partitioning clause.  If the values are the same for the first three, then the last three are cash.
select t.*
from (select t.*,
             sum(case when seqnum = seqnum_type then 1 else 0 end) over (partition by acc_id) as num_in_sequence
      from (select t.*,
                   row_number() over (partition by acc_id order by transaction_date desc) as seqnum,
                   row_number() over (partition by acc_id, trans_type order by transaction_date desc) as seqnum_type
            from tbl_transaction t
           ) t
      where trans_type = 'cash'
     )
where num_in_sequence >= 3 and seqnum <= 3;

Another method compares the transaction types for the last three records:
select t.*
from (select t.*,
             min(trans_type) over (partition by acc_d) as min_trans_type,
             max(trans_type) over (partition by acc_d) as max_trans_type
      from (select t.*,
                   row_number() over (partition by acc_id order by transaction_date desc) as seqnum
            from tbl_transaction t
           ) t
      where seqnum <= 3
     )
where min_trans_type = 'cash' and max_trans_type = 'cash';


text:
Q: I am getting this error after installing jsonwebtokens in my react application enter image description here
this is the error i am getting in the console!
There is no other error i am receiving and i am clueless about where should i look at to resolve this error
Edit1:
I just realized that I am getting this error when i import anything from jsonwebtoken for example:
import jwt from 'jsonwebtoken'

I also get these 3 error messages in my terminal:
ERROR in ./node_modules/jsonwebtoken/sign.js 18:4-21
Module not found: Error: Can't resolve 'crypto' in 'C:\Users\pc user\Desktop\PokerSocketio\client\node_modules\jsonwebtoken'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
        - install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "crypto": false }

ERROR in ./node_modules/jsonwebtoken/verify.js 13:4-21
Module not found: Error: Can't resolve 'crypto' in 'C:\Users\pc user\Desktop\PokerSocketio\client\node_modules\jsonwebtoken'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
        - install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "crypto": false }

ERROR in ./node_modules/jwa/index.js 3:13-30
Module not found: Error: Can't resolve 'crypto' in 'C:\Users\pc user\Desktop\PokerSocketio\client\node_modules\jwa'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
        - install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "crypto": false }

webpack compiled with 3 errors


text:
Q: Efficient way to implement multiple dispatch for many similar functions I am writing some software that involves a library of various functional forms of a quantity. I want to leverage Julia's multiple dispatch, but want to know if there's a more efficient way to implement this procedure.
Consider, for example, a library that contains the following two functions
function firstfunction(x::Float64)
    return 2*x
end

function secondfunction(x::Float64)
    return x^2
end

I would also like to implement multiple dispatch methods that can apply these functional forms to an vector of values, or an array of vectors (matrix). I could do this as follows
function firstfunction(x::Float64)
    return 2*x
end

function firstfunction(xs::Vector{Float64})
    f = similar(xs)
    for i = 1:size(xs, 1)
        f[i] = 2*xs[i]
    end
    return f
end

function firstfunction(xss::Matrix{Float64})
    f = similar(xss)
    for i = 1:size(xss, 1)
        for j = 1:size(xss, 2)
            f[i, j] = 2*xss[i, j]
    end
    return f
end

function secondfunction(x::Float64)
    return x^2
end

function secondfunction(xs::Vector{Float64})
    f = similar(xs)
    for i = 1:size(xs, 1)
        f[i] = xs[i]^2
    end
    return f
end

function secondfunction(xss::Matrix{Float64})
    f = similar(xss)
    for i = 1:size(xss, 1)
        for j = 1:size(xss, 2)
            f[i, j] = xss[i, j]^2
    end
    return f
end

But since all three versions of the function use the same kernel, and the actions of the various dispatches are the same across all functional forms, I'd like to know if there's a more efficient way to write this such that defining a new function for the library (e.g thirdfunction) only involves explicitly writing the kernel function, rather than having to type out 2*n essentially identical functions for n functional forms in the library.

A: Just do:
function thirdfunction(x::Union{Number, Array{<:Number}})
    return x.^0.5
end

This is the beauty of multiple-dispatch in Julia:
julia> thirdfunction(4)
2.0

julia> thirdfunction([4,9])
2-element Array{Float64,1}:
 2.0
 3.0

julia> thirdfunction([4 9; 16 25])
2×2 Array{Float64,2}:
 2.0  3.0
 4.0  5.0

Note that however in your case it might make sense to have only a single representation of a function and let the user decide to vectorize it using the dot operator (.).
function fourthfunction(x::Real)
    min(x, 5)
end

And now the user just needs to add a dot when needed:
julia> fourthfunction(4)
4

julia> fourthfunction.([4,9])
2-element Array{Int64,1}:
 4
 5

julia> fourthfunction.([4 9; 16 25])
2×2 Array{Int64,2}:
 4  5
 5  5

Since vectorizing in Julia is so easy you should consider this design whenever possible,

A: You should not use type annotations if they are not required for safety or multiple dispatch. E.g. it is unlikely that firstfunction should only work for Float64, probably it should work for all numbers, therefore write
function firstfunction(x::Real) # or just firstfunction(x)
    return 2*x
end

There is no performance penalty for defining functions more general.
Back to the topic:
For applying a function to a matrix / vector, etc. the simplest way is to use broadcasting:
A = rand(10, 10) # 10x10 matrix
B = firstfunction.(A) # apply element-wise

If you want to define the way how to apply another function by yourself, you can use functions as input parameters, e.g.:
thirdfunction(f, x) = f(f(x))


text:
Q: Empty IP address after run container in host mode I want to create docker container with host mode, using java library
https://github.com/spotify/docker-client
In my container exist my application which after run should open port 20202 from container to next using. So my code to do that is
Map<String, List<PortBinding>> portBindings = Maps.newHashMap();
portBindings.put("20202", Lists.newArrayList(PortBinding.of("localhost", "20202")));
        HostConfig hostConfig = HostConfig.builder()
        .networkMode("host")
        .portBindings(portBindings)
        .build();
ContainerConfig config = ContainerConfig.builder()
        .hostConfig(hostConfig)
        .image("myImage")
        .exposedPorts("20202")
        .cmd("myProg", "arg1", "arg2"))
        .build();
DefaultDockerClient.fromEnv().build();
client.pull(config.image());
ContainerCreation creation = client.createContainer(config);
client.startContainer(creation.id());
ContainerInfo info = client.inspectContainer(creation.id());

I see in log how my image is pulling, from local registry, but when my main program try run command in created container I get below exception

org.apache.http.client.ClientProtocolException: URI does not specify a valid host name: http://:20202

After when my program run this container I checked manual from command line if container exist, and if port is open localy on 127.0.0.1:20202 and it is ok,

*

*container exist and is running (I see them after docker ps)

*Port is open and listening I check using netstat -altp --->
tcp        0      0 127.0.0.1:20202  0.0.0.0:*  LISTEN      23839/myProg

*I can use my program just use 127.0.0.1:20202
I saw that problem is when in my main program try get information about host from ContainerInfo using below method
ContainerInfo info = client.inspectContainer(creation.id());
String host = info.networkSettings().ipAddress(); // host is empty

So question is, how put to ContainerInfo information about localhost or 127.0.0.1 when I set host mode in HostConfig ?
Why this is not happend automatic ?

A: Port bindings are ignored when you have host mode, because your code is responsible for choosing the port and binding to it. Docker is just patching your through to the host network. So whether you pass port mapping or not, it will not used in host mode
Also when you run a container is NetworkMode there is no IP assigned to container as such. You need to use the host IP
$ docker run -d --network host alpine sleep 900
804006d7f917637ee615d877558da7fae5b01a03af713c773098d0ef563d06c2

$ docker inspect 804006d7f917637ee615d877558da7fae5b01a03af713c773098d0ef563d06c2 | grep IPA
  "SecondaryIPAddresses": null,
  "IPAddress": "",
  "IPAMConfig": null,
  "IPAddress": "",

As you can see from above, then container never gets an ip in host mode


text:
Q: source ~/.bash_profile error I am trying to fix the bash profile but it constantly says:
source ~/.bash_profile
/Users/KirSo/.bash_profile:160: command not found: bind
\[\e]2;\u@\h\a[\[\e[37;44;1m\]\t\[\e[0m\]]\[\033[0;31m\] (master) \[\e[32m\]\W\[\e[0m\]\n\[\e[0;31m\]\[\e[0;49;34m\]//\[\033[0;31m\] ♥ \[\e[0m\]

checked the line 160 which says:
 bind "set completion-ignore-case on"

Although with adjust the line, restarting the terminal it still drops the same error.

A: Considering the path inside the question, You are probably running CygWin or something similar. Check the $PATH variable and Your env variables. You might have accidently changed the paths in which bash is looking for binaries (such as /bin). Also, on some versions of Linux (dont know about CygWin, sorry :<), there are other bash config files, namely ~/.bashrc /etc/bash.bashrc /etc/profile. The names may vary, depending on the distribution and implementation. Check If those contain code that overrides Your $PATH variable.


text:
Q: React-Router  changing url but not refreshing/loading component? I'm a little stuck and having read a dozen others solutions mine still doesn't seem to work. My Links from react router change the url fine, but doesn't load any different component, unless I do a manual refresh. I also added withRouter to all my components with Routes/Links but still no go. Here is the code
StreamList.js
import {
  connect
} from 'react-redux';
import {
  fetchStreams
} from '../../actions';
import React, {
  Component
} from 'react';
import streams from '../../apis/streams';
import {
  Link,
  withRouter
} from 'react-router-dom';

class StreamList extends Component {
  componentDidMount() {
    this.props.fetchStreams();
  }

  renderAdmin(stream) {
    if (stream.userId === this.props.currentUserId) {
      return ( <
        div className = 'right floated content' >
        <
        button className = 'ui button primary' > Edit < /button> <
        button className = 'ui button negative' > Delete < /button> <
        /div>
      )
    }
  }

  renderList() {
    return this.props.streams.map(stream => {
      return ( <
        div className = 'item'
        key = {
          stream.id
        } > {
          this.renderAdmin(stream)
        } <
        i className = 'large middle aligned icon camera' / >
        <
        div className = 'content' > {
          stream.title
        } <
        div className = 'description' > {
          streams.description
        } <
        /div> <
        /div> <
        /div>
      )
    })
  }

  renderCreate(stream) {
    if (this.props.isSignedIn) {
      return ( <
        div style = {
          {
            textAlign: 'right'
          }
        } >
        <
        Link to = "/streams/new"
        className = "ui button primary" >
        Create Stream <
        /Link> <
        /div>
      );
    }
  }

  render() {
    return ( <
      div >
      <
      h2 > Streams:
 <
      div className = 'ui celled list' > {
        this.renderList()
      } <
      /div> {
        this.renderCreate()
      } <
      /div>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    streams: Object.values(state.streams),
    currentUserId: state.auth.userId,
    isSignedIn: state.auth.isSignedIn
  };
};

export default withRouter(connect(mapStateToProps, {
  fetchStreams
})(StreamList));

App.js
import React from 'react';
import { BrowserRouter, Route } from 'react-router-dom';
import StreamCreate from './streams/StreamCreate';
import StreamDelete from './streams/StreamDelete';
import StreamEdit from './streams/StreamEdit';
import StreamList from './streams/StreamList';
import StreamShow from './streams/StreamShow';
import Header from './Header';

export default function App() {
    return (

            <BrowserRouter>

                    <Route path='/' exact component={StreamList} />
                    <Route path='/streams/new' component={StreamCreate} />
                    <Route path='/streams/edit' component={StreamEdit} />
                    <Route path='/streams/delete' component={StreamDelete} />
                    <Route path='/streams/show' component={StreamShow} />

            </BrowserRouter>

    )
}

Header.js (nav)
import React from 'react';
import { Link, withRouter } from 'react-router-dom';
import GoogleAuth from './streams/GoogleAuth';

export default withRouter(function Header() {
  return (

        <Link to='/' className='item'>
            Twatch
        </Link>

            <Link to='/' className='item'>
                All Streams
            </Link>
            <GoogleAuth />

  )
});


text:
Q: Bash script grabbing specific lines of top Is it possible to grap specific lines of top within a bash script?
the following command works within command shell, but this does not work within a bash script, i also tried grep
echo "             " `top | awk 'NR==7'`
echo "             " `top | awk 'NR==8'`

(i also tried this without the back ticks but it produces the same blank text)

A: With GNU top, I think the simplest way to do what you want is
top -n 1 -b | sed -n '7,17 p'

sed selects only the 7th to the 17th line from top output.

A: I suspect the differences you are observing are due to the interactive nature of top.  Consider passing command line parameters to top to disable the interactive aspect of it.  For example, on MAC, here's a command to take a single sample ( and return) with the top 5 processes:
top -l 1 -n 5

If you want to use awk to select specific lines, let's say 7 through 17 inclusive, try this:
top -l 1 | awk 'NR >= 7 && NR <= 17'


text:
Q: Take specific data from database with nodejs Hello i have some routes and i am receiving data from database
   router.get('/', expressAsyncHandler(async (req,res) => {
            const products = await Product.find({})
            res.json(products)
   }))

With this route i get all the products from mongoDB
I want to get all products with the same category so i begin to try a new route
   router.get('/roundBall', expressAsyncHandler(async (req,res) => {
            const products = await Product.find({})
            const roundball= products._category == 'Rounded'
            res.json(products)
   }))

But it's not working, in my local host i am getting false in the screen. Can anyone help me with this problem?

A: Currently, all the products are getting retrieved from mongoDB. Then the attempt to filter by category in node.js is incorrect.
One way to fix the problem is to correct how the filtering is done at node.js side:
roundball should be created by using Array.filter, this way.
        const roundball= products.filter( product => product._category === 'Rounded')

However, it will be more efficient to query mongoDB only for products corresponding to the desired category:
        const roundball = await Product.find({_category: 'Rounded'})

This way, less data needs to transit between mongodb and node.js.

A: products._category == 'Rounded' is a comparasion so it will always return true of false. What you need to do is map over the elements and compare each element's category with 'Rounded'.


text:
Q: Does qemu-monitor-command support external snapshot? I made an external snapshot for 'myvm'. But when I tried to list snapshot info for 'myvm' through qemu-monitor-command --hmp myvm 'info snapshots'. There was nothing shown. However, I got correct snapshot info by using snapshot-list myvm. I am not clear if qemu-monitor-command support external snapshot?
Compiled against library: libvirt 0.10.2
Using library: libvirt 0.10.2
Using API: QEMU 0.10.2
Running hypervisor: QEMU 2.3.0

Any help is appreciated.

A: The 'info snapshots' monitor command you are invoking only reports on qcow2 internal snapshots (ie snapshot data stored inside the original qcow2 file). So if you created external snapshots (using qcow2 backing file feature), this will not be reported via 'info snapshots'.


text:
Q: Get product price after applied Catalog Price Rule I have created a catalog price rule in Magento adminarea.
For ex. Product A's price is 100 and after applying the catalog price rule, its price becoming 80.
I am trying to fetch the price 80 programmatically but the below code is returning original price only i.e. 100.
$product->getPrice();
$product->getFinalPrice();

A: I got the discounted price by below code:
$price = $product->getPriceInfo()->getPrice('final_price')->getAmount()->getValue();

A: You can get the discounted price after applying the rule as follows:
   $discounted_price = Mage::getModel('catalogrule/rule')->calcProductPriceRule($product
   ->setStoreId(1)
   ->setCustomerGroupId($grup),
   $product->getPrice()
   );

A: The best way to get Price after a catalog Price rule is applied to it is by
calling

\Magento\CatalogRule\Model\Rule::calcProductPriceRule(Product
$product,$price);

You can create object of Rule class in constructor and then call calcProductPriceRule appropriately in your logic to get the currect price when you fail to get it with getFinalPrice func.


text:
Q: Is wifi connection between iphone and any other electronic device possible Is it possible to connect an iPhone with any electronic devices through Wi-Fi, and receive signals from it. I'm currently looking into a sample app with UDPEcho, but it is for Mac.

A: For 20$ a month for 2GB Verizon offers creating a hotspot. At&t does not


text:
Q: How to selectively populate waterline associations via query param in sails.js By default, sails will populate all relationships within a model when it's corresponding API route is hit. Does anyone know if it's possible to toggle this functionality? If I'm working with a one-to-many association, I may not want to populate the association when doing a listing of all items for performance reasons. But when viewing a single item, it would be nice to complete the population.
For example, say one ticket can have many comments. I don't care about the comments when fetching a case listing but would be important when viewing a specific case. I took a guess at how it could function but it fails:
localhost:1337/tickets?populate=false

Update
I implemented the above functionality within balderdashy/sails#1695. The only change is that you selectively choose which associations to populate using:
localhost:1337/tickets?populate=[]          // Don't populate anything
localhost:1337/tickets?populate=[comments]  // Only populate comments

This would override whatever is defined for populate within your blueprint config.

A: You just need to separate your assosiactions via comma, just like this:
localhost:1337/tickets?populate=comments,owner&SOME_OTHER_PARAMS


text:
Q: Search a city using google map I'm using a google map to show location in find search box (from that link) which is working fine:
angular.module('ui.bootstrap.demo').controller('TypeaheadCtrl',function($scope, $http) {

$scope.getLocation = function(val) {
   return $http.get('//maps.googleapis.com/maps/api/geocode/json', {
    params: {
    address: val,
    sensor: false
   }
}).then(function(response){
return response.data.results.map(function(item){
return item.formatted_address;
});
});
};

Asynchronous results

Model: {{asyncSelected | json}}

<input type="text" ng-model="asyncSelected" placeholder="Locations loaded via $http" uib-typeahead="address for address in getLocation($viewValue)"     typeahead-loading="loadingLocations" typeahead-no-results="noResults" class="form-control">

   No Results Found

I would like to know if possible to show my custom city near the search entry ?
Let's say I have bbCity, aaCity, ccCity and when a user types bb, her/him gets the nearest one (bbCity).
Thanks

A: I don't know if it's a right way but I solved it by adding the answer from this link.
angular.module('ui.bootstrap.demo').controller('TypeaheadCtrl',function($scope, $http) {

 // Predefined areas
    var predefinedLocations = [[48,68435270497298,4,39454410970211, 'city 1'],[48,33375503137806,5,616522543132305, 'city 2']];
$scope.getLocation = function(val) {
    return $http.get('//maps.googleapis.com/maps/api/geocode/json', {
      params: {
                address: val,
                sensor: false
      }
    }).then(function(response){
        return response.data.results.map(function(item){
             // Hold distances
                var distances = [];

                    var start = new google.maps.LatLng(item.geometry.location.lat, item.geometry.location.lng);

                    for (var i = 0; i < predefinedLocations.length; i++)
                    {
                        var point = new google.maps.LatLng(predefinedLocations[i][0],predefinedLocations[i][1]);

                        var distance = google.maps.geometry.spherical.computeDistanceBetween(start, point);
                        distances.push(distance);
                    }

                    var firstElement = distances[0];
                var index = 0;
                for (var i = 1; i < distances.length; i++)
                {
                    if(distances[i] < firstElement)
                    {
                        firstElement = distances[i];
                        index = i;
                    }
                }

                    return predefinedLocations[index][2];
    });
  });
};