text:
Q: Display Different images per monitor directX 10 I am fairly new to DirectX 10 programming, and I have been trying to do the following with my limited skills (though I have a strong background with OpenGL)
I am trying to display 2 different textured Quads, 1 per monitor.  To do so, I understood that I need a single D3D10 Device, multiple (2) swap chains, and single VertexBuffer
While I think I'm able to create all of those, I'm still pretty unsure how to handle all of them.  Do I need multiple ID3D10RenderTargetView(s) ? How and where should I Use OMSetRenderTargets(...) ?
Other than MSDN, documentation or explaination of those concepts are rather limited, so any help would be very welcome.  Here is some code I have :
Here's the rendering code
for(int i = 0; i < screenNumber; i++){
    //clear scene
    pD3DDevice->ClearRenderTargetView( pRenderTargetView, D3DXCOLOR(0,1,0,0) );

    //fill vertex buffer with vertices
    UINT numVertices = 4;
    vertex* v = NULL;

    //lock vertex buffer for CPU use
    pVertexBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**) &v );

    v[0] = vertex( D3DXVECTOR3(-1,-1,0), D3DXVECTOR4(1,0,0,1), D3DXVECTOR2(0.0f, 1.0f) );
    v[1] = vertex( D3DXVECTOR3(-1,1,0), D3DXVECTOR4(0,1,0,1), D3DXVECTOR2(0.0f, 0.0f) );
    v[2] = vertex( D3DXVECTOR3(1,-1,0), D3DXVECTOR4(0,0,1,1), D3DXVECTOR2(1.0f, 1.0f) );
    v[3] = vertex( D3DXVECTOR3(1,1,0), D3DXVECTOR4(1,1,0,1), D3DXVECTOR2(1.0f, 0.0f) );

    pVertexBuffer->Unmap();

    // Set primitive topology
    pD3DDevice->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP );

    //set texture
    pTextureSR->SetResource( textureSRV[textureIndex] );

    //get technique desc
    D3D10_TECHNIQUE_DESC techDesc;
    pBasicTechnique->GetDesc( &techDesc );

    // This is where you actually use the shader code
    for( UINT p = 0; p < techDesc.Passes; ++p )
    {
        //apply technique
        pBasicTechnique->GetPassByIndex( p )->Apply( 0 );

        //draw
        pD3DDevice->Draw( numVertices, 0 );
    }

    //flip buffers
    pSwapChain[i]->Present(0,0);
}

And here's the code for creating rendering targets, which I am not sure is good
for(int i = 0; i < screenNumber; ++i){

    //try to get the back buffer
    ID3D10Texture2D* pBackBuffer;
    if ( FAILED( pSwapChain[1]->GetBuffer(0, __uuidof(ID3D10Texture2D), (LPVOID*) &pBackBuffer) ) ) return fatalError("Could not get back buffer");

    //try to create render target view
    if ( FAILED( pD3DDevice->CreateRenderTargetView(pBackBuffer, NULL, &pRenderTargetView) ) ) return fatalError("Could not create render target view");

    pBackBuffer->Release();
    pD3DDevice->OMSetRenderTargets(1, &pRenderTargetView, NULL);
}

return true;

}

A: I hope I got the gist of what you wish to do - render different content on two different monitors while using a single graphics card (graphics adapter) which maps its output to those monitors. For that, you're going to need one device (for the single graphics card/adapter) and enumerate just how many outputs there are at the user's machine.
So, in total - that means one device, two outputs, two windows and therefore - two swap chains.
Here's a quick result of my little experiment:

A little introduction
With DirectX 10+, this falls into the DXGI (DirectX Graphics Infrastructure) which manages the common low-level logistics involved with DirectX 10+ development which, as you probably know, dumped the old requirement of enumerating feature sets and the like - requiring every DX10+ capable card to share in on all of the features defined by the API. The only thing that varies is the extent and capability of the card (in other words, lousy performance is preferable to the app crashing and burning). This was all within DirectX 9 in the past, but people at Microsoft decided to pull it out and call it DXGI. Now, we can use DXGI functionality to set up our multi monitor environment.

Do I need multiple ID3D10RenderTargetView(s) ?

Yes, you do need multiple render target views, count depends (like the swap chains and windows) on the number of monitors you have. But, to save you from spewing words, let's write it out as simple as possible and additional information where it's needed:

*

*Enumerate all adapters available on the system.

*For each adapter, enumerate all outputs available (and active) and create a device to accompany it.

*With the enumerated data stored in a suitable structure (think arrays which can quickly relinquish size information), use it to create n windows, swap chains, render target views, depth/stencil textures and their respective views where n is equal to the number of outputs.

*With everything created, for each window you are rendering into, you can define special routines which will use the available geometry (and other) data to output your results - which resolves to what each monitor gets in fullscreen (don't forget to adjust the viewport for every window accordingly).

*Present your data by iterating over every swap chain which is linked to its respective window and swap buffers with Present()

Now, while this is rich in word count, some code is worth a lot more. This is designed to give you a coarse idea of what goes into implementing a simple multimonitor application. So, assumptions are that there is only one adapter ( a rather bold statement nowadays ) and multiple outputs - and no failsafes. I'll leave the fun part to you. Answer to the second question is downstairs...
Do note there's no memory management involved. We assume everything magically gets cleaned up when it is not needed for illustration purposes. Be a good memory citizen.
Getting the adapter
IDXGIAdapter* adapter = NULL;
void GetAdapter() // applicable for multiple ones with little effort
{
    // remember, we assume there's only one adapter (example purposes)
    for( int i = 0; DXGI_ERROR_NOT_FOUND != factory->EnumAdapters( i, &adapter ); ++i )
    {

        // get the description of the adapter, assuming no failure
        DXGI_ADAPTER_DESC adapterDesc;
        HRESULT hr = adapter->GetDesc( &adapterDesc );

        // Getting the outputs active on our adapter
        EnumOutputsOnAdapter();

}

Acquiring the outputs on our adapter
std::vector<IDXGIOutput*> outputArray; // contains outputs per adapter
void EnumOutputsOnAdapter()
{
    IDXGIOutput* output = NULL;
    for(int i = 0; DXGI_ERROR_NOT_FOUND != adapter->EnumOutputs(i, &output); ++i)
    {

        // get the description
        DXGI_OUTPUT_DESC outputDesc;
        HRESULT hr = output->GetDesc( &outputDesc );

        outputArray.push_back( output );
    }

}

Now, I must assume that you're at least aware of the Win32 API considerations, creating window classes, registering with the system, creating windows, etc... Therefore, I will not qualify its creation, only elaborate how it pertains to multiple windows. Also, I will only consider the fullscreen case here, but creating it in windowed mode is more than possible and rather trivial.
Creating the actual windows for our outputs
Since we assume existence of just one adapter, we only consider the enumerated outputs linked to that particular adapter. It would be preferable to organize all window data in neat little structures, but for the purposes of this answer, we'll just shove them into a simple struct and then into yet another std::vector object, and by them I mean handles to respective windows (HWND) and their size (although for our case it's constant).
But still, we have to address the fact that we have one swap chain, one render target view, one depth/stencil view per window. So, why not feed all of that in that little struct which describes each of our windows? Makes sense, right?
struct WindowDataContainer
{
    //Direct3D 10 stuff per window data
    IDXGISwapChain* swapChain;
    ID3D10RenderTargetView* renderTargetView;
    ID3D10DepthStencilView* depthStencilView;

    // window goodies
    HWND hWnd;
    int width;
    int height;
}

Nice. Well, not really. But still... Moving on! Now to create the windows for outputs:
std::vector<WindowDataContainer*> windowsArray;
void CreateWindowsForOutputs()
{
    for( int i = 0; i < outputArray.size(); ++i )
    {

        IDXGIOutput* output = outputArray.at(i);
        DXGI_OUTPUT_DESC outputDesc;
        p_Output->GetDesc( &outputDesc );
        int x = outputDesc.DesktopCoordinates.left;
        int y = outputDesc.DesktopCoordinates.top;
        int width = outputDesc.DesktopCoordinates.right - x;
        int height = outputDesc.DesktopCoordinates.bottom - y;

        // Don't forget to clean this up. And all D3D COM objects.
        WindowDataContainer* window = new WindowDataContainer;

        window->hWnd = CreateWindow( windowClassName,
                                        windowName,
                                        WS_POPUP,
                                        x,
                                        y,
                                        width,
                                        height,
                                        NULL,
                                        0,
                                        instance,
                                        NULL );

        // show the window
        ShowWindow( window->hWnd, SW_SHOWDEFAULT );

        // set width and height
        window->width = width;
        window->height = height;

        // shove it in the std::vector
        windowsArray.push_back( window );

        //if first window, associate it with DXGI so it can jump in
        // when there is something of interest in the message queue
        // think fullscreen mode switches etc. MSDN for more info.
        if(i == 0)
            factory->MakeWindowAssociation( window->hWnd, 0 );

    }
}

Cute, now that's done. Since we only have one adapter and therefore only one device to accompany it, create it as usual. In my case, it's simply a global interface pointer which can be accessed all over the place. We are not going for code of the year here, so why the hell not, eh?
Creating the swap chains, views and the depth/stencil 2D texture
Now, our friendly swap chains... You might be used to actually creating them by invoking the "naked" function D3D10CreateDeviceAndSwapChain(...), but as you know, we've already made our device. We only want one. And multiple swap chains. Well, that's a pickle. Luckily, our DXGIFactory interface has swap chains on its production line which we can receive for free with complementary kegs of rum. Onto the swap chains then, create for every window one:
void CreateSwapChainsAndViews()
{
    for( int i = 0; i < windowsArray.size(); i++ )
    {
        WindowDataContainer* window = windowsArray.at(i);

        // get the dxgi device
        IDXGIDevice* DXGIDevice = NULL;
        device->QueryInterface( IID_IDXGIDevice, ( void** )&DXGIDevice ); // COM stuff, hopefully you are familiar

        // create a swap chain
        DXGI_SWAP_CHAIN_DESC swapChainDesc;

        // fill it in

        HRESULT hr = factory->CreateSwapChain( DXGIDevice, &swapChainDesc, &p_Window->swapChain );
        DXGIDevice->Release();
        DXGIDevice = NULL;

         // get the backbuffer
        ID3D10Texture2D* backBuffer = NULL;
        hr = window->swapChain->GetBuffer( 0, IID_ID3D10Texture2D, ( void** )&backBuffer );

        // get the backbuffer desc
        D3D10_TEXTURE2D_DESC backBufferDesc;
        backBuffer->GetDesc( &backBufferDesc );

        // create the render target view
        D3D10_RENDER_TARGET_VIEW_DESC RTVDesc;

        // fill it in

        device->CreateRenderTargetView( backBuffer, &RTVDesc, &window->renderTargetView );
        backBuffer->Release();
        backBuffer = NULL;

        // Create depth stencil texture
        ID3D10Texture2D* depthStencil = NULL;
        D3D10_TEXTURE2D_DESC descDepth;

        // fill it in

        device->CreateTexture2D( &descDepth, NULL, &depthStencil );

        // Create the depth stencil view
        D3D10_DEPTH_STENCIL_VIEW_DESC descDSV;

        // fill it in

        device->CreateDepthStencilView( depthStencil, &descDSV, &window->depthStencilView );

    }

}

We now have everything we need. All that you need to do is define a function which iterates over all windows and draws different stuff appropriately.

How and where should I Use OMSetRenderTargets(...) ?

In the just mentioned function which iterates over all windows and uses the appropriate render target (courtesy of our per-window data container):
void MultiRender( )
{
    // Clear them all
    for( int i = 0; i < windowsArray.size(); i++ )
    {
        WindowDataContainer* window = windowsArray.at(i);

        // There is the answer to your second question:
        device->OMSetRenderTargets( 1, &window->renderTargetView, window->depthStencilView );

        // Don't forget to adjust the viewport, in fullscreen it's not important...
        D3D10_VIEWPORT Viewport;
        Viewport.TopLeftX = 0;
        Viewport.TopLeftY = 0;
        Viewport.Width = window->width;
        Viewport.Height = window->height;
        Viewport.MinDepth = 0.0f;
        Viewport.MaxDepth = 1.0f;
        device->RSSetViewports( 1, &Viewport );

        // TO DO: AMAZING STUFF PER WINDOW
    }
}

Of course, don't forget to run through all the swap chains and swap buffers per window basis. The code here is just for the purposes of this answer, it requires a bit more work, error checking (failsafes) and contemplation to get it working just the way you like it - in other words - it should give you a simplified overview, not a production solution.
Good luck and happy coding! Sheesh, this is huge.


text:
Q: Instantiation of template classes in C++ with non-basic constructor I have a very simple matrix class with the following constructor:
template <typename Type>
SimpleMatrix<Type>::SimpleMatrix(const int &rows, const int &cols, const Type &val) {
    for (int i = 0; i < rows; i++) {
        vector<Type> col_vec(cols, val);
        mat.push_back(col_vec);
    }
}

Simple as it is, if I try to call it from main.cpp by doing the following:
SimpleMatrix<double> matrix(1,1,0.5);

The compiler throws the well-known error:
Undefined symbols for architecture x86_64:
  "Matrix::SimpleMatrix<double>::SimpleMatrix(int const&, int const&, double const&)", referenced from:
      _main in main.o
  "Matrix::SimpleMatrix<double>::~SimpleMatrix()", referenced from:
      _main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Isn't that the way of using overloaded constructors in this case? I am starting to think this is a red herring and my XCode is playing up!

redpajama_set_name: RedPajamaStackExchange


text:
Q: parsing multiple files flex/bison I am currently working on a flex/bison project.
I need to parse multiple files in one execution, so i made a loop to run YYPARSE() multiple times.
When flex finds a lexical or syntactic error, the parsing of a file stops and the program starts parsing the next file. However, the parsing of that new file doesn't start from the beginning. Indeed, if the parsing stopped at line 8 for file 3 the parsing will start form line 8 in file 4.
How could i solve this problem ?
Thanks in advance.
Here is my main function in my bison.y file:
int main(int argc, char* argv[]){

DIR* dir;

struct dirent *ent;

int val = 0;

    if ((dir = opendir ("../TpCompileHoho")) != NULL)
    {
      // print all the files and directories within directory
      while ((ent = readdir (dir)) != NULL)
      {
        if ((strcmp(ent->d_name,".") != 0) && (strcmp(ent->d_name,"..") != 0) && (strstr(ent->d_name,".txt") != NULL))
        {
                yyin = fopen(ent->d_name,"r");

                yyparse();
        }

      }
      closedir (dir);
    }
    else
    {
      // could not open directory
      perror ("could not open directory");
      return EXIT_FAILURE;
    }

}

A: If you need to discard the rest of the current input and start parsing a new file, you need to call yyrestart(yyin) instead of simply setting yyin to a new value. Setting yyin to a new value works fine only if the previous file was read up to the end-of-file marker.
You should also remember to close the old file. The flex-generated scanner will not do that for you.


text:
Q: comparing the content of two HashMaps with set<> value I have these two objects.
public Map<String, Set<RuleConditionBl>> countryToNonSplittedRules1 = new HashMap<>;
public Map<String, Set<RuleConditionBl>> countryToNonSplittedRules2 = new HashMap<>;

I have a test that compares these two
and even though their content is the same, i get false for
countryToNonSplittedRules1.equals(countryToNonSplittedRules2);
here is an example:

I read this post, so i'm not sure why doesn't this return true
public class RuleConditionBl {

public int weight;
public boolean isAll;
public List<String> countries;
public UserFlag userFlag;

@JsonIgnore
private Range<LocalDate> datesRange;

public String fromDate;
public String toDate;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        RuleConditionBl that = (RuleConditionBl) o;

        if (weight != that.weight) return false;
        if (isAll != that.isAll) return false;
        if (countries != null ? !countries.equals(that.countries) : that.countries != null) return false;
        if (userFlag != that.userFlag) return false;
        return datesRange != null ? datesRange.equals(that.datesRange) : that.datesRange == null;
    }

    @Override
    public int hashCode() {
//        int result = weight;
        int result = 0;
        result = 31 * result + (isAll ? 1 : 0);
        result = 31 * result + (countries != null ? countries.hashCode() : 0);
        result = 31 * result + (userFlag != null ? userFlag.hashCode() : 0);
        result = 31 * result + (datesRange != null ? datesRange.hashCode() : 0);
        return result;
    }

{

A: I have looked a bit at your solution.
Your implementation is correct(ish).
First of all, Range<LocalDate> datesRange should not work if I am not mistaken.
Range is not generic, so it cannot be parameterized with arguments.(Please correct me if im wrong).
I change Range<LocalDate> datesRange to List<LocalDate> datesRange.
So besides that, your code is correct. I think your problem is the key values when you put your objects into countryToNonSplittedRules1 and countryToNonSplittedRules2. The key values has to be the same, otherwise you cannot compare the two maps.
Map<String, Set<RuleConditionBl>> countryToNonSplittedRules1 = new HashMap<>();
Map<String, Set<RuleConditionBl>> countryToNonSplittedRules2 = new HashMap<>();

Set<RuleConditionBl> s1 = new LinkedHashSet<>();
Set<RuleConditionBl> s2 = new LinkedHashSet<>();

//Objects for s1
RuleConditionBl r1 = new RuleConditionBl();
r1.weight = 710;
r1.userFlag = null;
r1.isAll = false;

RuleConditionBl r3 = new RuleConditionBl();
r3.weight = 700;
r3.userFlag = null;
r3.isAll = false;

s1.add(r1);
s1.add(r3);

countryToNonSplittedRules1.put("r1", s1);

//Objects for s2
RuleConditionBl r2 = new RuleConditionBl();
r2.weight = 700;
r2.userFlag = null;
r2.isAll = false;

RuleConditionBl r4 = new RuleConditionBl();
r4.weight = 710;
r4.userFlag = null;
r4.isAll = false;

s2.add(r2);
s2.add(r4);

countryToNonSplittedRules2.put("r1", s2);

System.out.println(countryToNonSplittedRules1.equals(countryToNonSplittedRules2));

Output:
true

The order of the elements in Set does matter. According to the documentation:

Compares the specified object with this set for equality. Returns true
  if the given object is also a set, the two sets have the same size,
  and every member of the given set is contained in this set. This
  ensures that the equals method works properly across different
  implementations of the Set interface.


text:
Q: .sln file opening in Visual Web Developer 2008 Express instead of VS2010 Professional I have Visual Web Developer Express 2008 as well as Visual Studio 2010 Professional Edition. My .sln file always kinds of opens in VS2008 Express and moreover when I right click on solution file and want to set the default program to VS2010 my "Always use the selected program for opening" is greyed out. I've tried everything but the checkbox just remains greyed out. How can I resolve this issue?
Note: For other file types like .csproj etc I am able to set the default program for opening. But for .sln file the "Always use the selected program for opening" is just greyed out.

A: You can open Visual Studio 2010 Pro go to Tools - Options - Environment - General and use Restore File Associations button. After that the sln files should open by default with VS.


text:
Q: Pinterest - Why are my icons not displaying full images? I'm using the Pin it button on a site, but when you use it it only displays a cut off icon of the image. Whereas using the button anywhere else, it will display the full size image.
I'm digged through my code, but can't find a solution.
Can anyone help? It doesn't seem to work with either the Pin it button, or the browser extension.
Here's a link to the site:
http://www.slurp.co.uk/red-wine/chilean-red-wine/18173-casillero-del-diablo-cabernet-sauvignon-2010/
Code:
<iframe src="http://d3io1k5o0zdpqr.cloudfront.net/pinit.html?url=http://www.slurp.co.uk/red-wine/chilean-red-wine/18173-casillero-del-diablo-cabernet-sauvignon-2010/&media=http://www.slurp.co.uk/images/products/small/18173.jpg&layout=horizontal" scrolling="no" frameborder="0" style="border-top-style: none; border-right-style: none; border-bottom-style: none; border-left-style: none; border-width: initial; border-color: initial; border-image: initial; width: 90px; height: 20px; "></iframe>

<script type="text/javascript" src="http://assets.pinterest.com/js/pinit.js"></script>

A: I think you need to style that IFRAME to have a width and height.  These are the settings:
+----------------------+-------+--------+
| Orientation-of-Count | Width | Height |
+----------------------+-------+--------+
| Horizontal           | 90px  | 20px   |
| Vertical             | 43px  | 58px   |
| None                 | 43px  | 20px   |
+----------------------+-------+--------+

Couple other things that you did not ask about, but might want to know:

*

*You need not insert the IFRAME and then use pinit.js.    The function of the pinit.js code is to  replace specially-marked ANCHOR (A) tags in your document with the IFRAME tags pointed at the pinterest CDN (cloudfront.net).  If you are inserting IFRAMEs with the appropriate src attribute, then you don't need pinit.js.

*the query params on the src attribute of that IFRAME need to be encoded.  In particular, the colon and slashes in the url and media params need to be uri-encoded. In Javascript you can use encodeURIComponent() to accomplish this.  I've found that pinterest is sort of picky about the  format of the URLs, and will fail silently if you get something wrong. If you use an media URL that includes spaces or parens, I believe it will fail, even though these are legal characters for HTTP URIs. Likewise for the page URL.

*In case you were wondering:  I don't believe you can eliminate the use of the IFRAME.  I believe pinterest may be looking at the REFERRER, and it may silently reject any pin/create/button requests that have not been referred by cloudfront.net.

A: Please take a look here:
http://business.pinterest.com/widget-builder
We've launched a new set of buttons and widgets that should help.


text:
Q: Window name doesn't match I been facing this problem for a long time and still have yet to solve it. As you can see in the image:

The window's name is something like "-ka" BUT my program clearly named the window as "My Image".
I am now already doing more adavance stuff like splitting of image, etc, but my project supervisor asking me about this, yet I do not know the reason behind it. Can anyone help? Thanks.

A: Just in case anyone have such problem in the future and see this post, The reason was caused by it running in debug mode rather than release mode. Peace.


text:
Q: Matlab failed to load a .NET assembly When I try to load in Matlab my .NET assembly foo.dll by typing:
asm = NET.addAssembly('fullpath\foo.dll');

I get the following error: "Could not load file or assembly 'file:///fullPath\foo.dll' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded. Source: mscorlib HelpLink:"
I've Matlab R2010a and I tried to build the assembly both for .NET framework 4.0 and .NET framework 3.0 with no success.
EDIT
I did several tests and now maybe I've partly discovered the problem. In the above example I was trying to add a private assembly by giving the full path. I then remembered to have also previously registered the same assembly (targeted for .NET 4.0) in the GAC (through the gacutil /i foo.dll command). Hence I removed the assembly from the GAC (gacutil /u foo) and now at least I'm able to add the private assembly targeted for .NET 3.0 but still not if I want to target .NET 4.0.
I presume that before, when I was trying to add a private assembly for .NET 3.0, Matlab was still trying to add the assembly for .NET 4.0 installed in the GAC, because of some conflict.
However, I still do not understand why I cannot use .NET 4.0 .

A: I can't reproduce the error. This is the example I used:
MyClass.cs
using System;
namespace ClassLibraryTest
{
    public class MyClass
    {
        public static double add(double x, double y)
        {
            return x + y;
        }
    }
}

MATLAB
>> NET.addAssembly('C:\path\to\ClassLibraryTest.dll');
>> ClassLibraryTest.MyClass.add(1,2)
ans =
     3

I tried different .NET target frameworks 4.0/3.5/3.0, and they all worked fine. Note that you can't unload an assembly once loaded, and the only way to release the .NET resources is to restart MATLAB...


text:
Q: jQuery check if element has a class beginning with some string I need to loop through some elements in the page and then, for each one, if it had a class beginning with, for example, "C", do something.
$('#dialog li').each(function(){
    if ($(this).hasClass("^C")){
         //do something
    }
}

It may sound silly, but what selector/method should I use on the if clause?

A: Try the Attribute Starts With Selector.  As a bonus, there is no need for the extra if.
$('#dialog li[class^="C"]').each(function() {
    // do something
});

A: I don't think that there is a built-in selector to test for classes starting with a string.
There is a selector to test if an attribute starts with a string, so if you know that your elements only have one class (or always start with the class in question), you could do:
$(this).is("class^='C'")
If, however, you can't guarantee either of the above conditions, you would have to manually split out and test each class defined on the element, as described here.

A: Carefull with $('#dialog li[class^="C"]')! It will only match elements, whose class attribute starts with "C" not ones with a class starting with C. For example it will not match
.
AFAIK what you want is not possible mit jQuery alone. You would need to loop through the classes and check each separatly. Something like:
$('#dialog li').filter(function(){
  var classes = this.className.split(/\s/);
  for (var i = 0, len = classes.length; i < len; i++)
    if (/^C/.test(classes[i])) return true;
  return false;
}).each( ... )

Alternativly you should consider changing your approach, and give all elements an additional class and filter by that. This has the addvantage that it can also be used in CSS:

A: You can try that selector. That will work if there are two or more classes like this "Clown foo doo" and
You can try however something like this $('#dialog li[class*="C"]') in which case will select anything that include the "C" letter, for excample "exCelence foo".
If you are interested in counting how many classes start with "C" no matter of their position (no matter if they are at the beginning, at the and or somewhere in the middle) then you can try something like this:
$('#dialog li[class^="C"]').each(function() {
  var classes = div.attr("class").split(" ");
  var count = 0;
  $.each(classes, function(i, v){ if(v.indexOf('C')!=-1) count++; });
  if (count == 1)   alert("It has one 'C' class");
  if (count>1) alert("It more than one 'C' class");
}

A: Try something like $('#dialog li[class^="C"]')

A: For more elaborate filters than "starts with" you can use the filter() function:
$('#dialog li').filter( function() {
  // return true for every element that matches your condition
  return this.className.match(/^c/) != null;
}).each(function(){
  //do something
}


text:
Q: SQL Select where values IN List string I select data with this query
SELECT * FROM `tbl_post` WHERE cate IN (15)

But only records can be found that The number 15 is the first like : "15,16,18" , "15"
can not be found If the number is 15 in the middle or last like : "14,15,16"

A: MySQL has a specific string function called find_in_set() for the purpose of searching for a value in a comma-separated string:
select * from tbl_post where find_in_set('15', cat) > 0

While this will work for your specific use-case, let me pinpoint that storing delimited list in relational databases is not a good practice, and should be generally avoided. You should have a separate table to store cates, which each value on a separate row.
Recommended reading: Is storing a delimited list in a database column really that bad?

A: Simply using "like" might help -
select * from tbl_post where cate like '15,%' or cate like '%,15,%' or cate
like '%15';

cate like '15,%' : Will get the 15 placed at the beginning
cate like '%,15,%' : Will get the 15 placed in the middle
cate like '%15' : Will get the 15 placed at the end


text:
Q: How to define a iterator in my class I use iterator in C++.It is so good.But I want have a my iterator in my class.how to do?
a simple example
//a simple container
class MyArray
{
public:
    MyArray()
    {
        for(int i=0;i<10;i++)
            data[i] = 0;
    }

    int GetValue(int index)
    {
        if(index>=10 || index<0)
            return -1;
        else
            return data[index];
    }

    bool SetValue(int value, int index)
    {
        if(index>=10 || index<0)
            return false;
        data[index] = value;
    }

    int& operator[](int index)
    {   return data[index]; }

    void ShowData();
protected:
    int data[10];
private:
};

// only test use
void MyArray::ShowData()
{
    std::cout<<"Data : ";
    for(int i =0;i<10;i++)
    {
        std::cout<<data[i]<<" ";
    }
    std::cout<<std::endl;
}

int main()
{
    MyArray array;

    MyArray::iterator it = array.begin();   //how to implementation?

    getchar();
    return 0;
}

A: The C++11 standard defines the requirements for iterators in section 24 of the standard. So, the short answer here is for you to define and implement your iterator and const_iterator class in a manner that meets the requirements for iterators.
The requirements for iterators take up five terse pages in the standard. Obviously, that's not something that can be summarized in a few short paragraphs in a stackoverflow.com answer.
I would suggest that you visit a library or a book store, look for a thorough book on C++, browse it, and see if it provides a good, substantive review of iterators and their requirements. Then try to implement them yourself.


text:
Q: Put a conditional format conversion in a sequence of piped Shell commands How is it possible to add an optional
iconv -f utf-16 -t latin1

inside a sequence of piped commands?
The assumption is that the source file can be either in latin1 or in utf16.
Shell scripts using awk, grep and the like should be able to work on both formats, by adding an optional conversion step.
How could that be done in the most beautiful manner, while respecting the DRY principle (not repeating the other commands)?
EDITED --
Curent sequence of commands looks like:
awk '...' $1 | cut ... | colorize

A: Not exactly efficient, but the following easily sets up conditional commands within a pipeline. The trick is to select from various alternate commands so you always run something:
opt_condtion=true;    #true run extra command, false not to

first_command | ( $opt_condition && ( optional_command || true ) || cat ) | third_command
The ( optional_command || true ) assures the cat does not run if optional_command returns a non-zero exit code as an extra cat would likely hang the pipelined command.
Using full (subshells) allows you a lot of freedom. If the commands get too complex put them in a function to keep the pipeline simple.


text:
Q: A-Frame gltf 2.0 can't set opacity I import a animated gltf 2.0 model in a A-Frame scene.
I want to set its opacity to 0.5. But it doen't work, even I try to modify the value with object3D class.
Hier is the demo project on glitch:
https://glitch.com/edit/#!/animated-gltf-opacity
Thanks for any help.

A: You need to wait until the model is loaded, throw Your code to an event listener:
this.el.addEventListener("model-loaded", (e)=>{//change opacity})

Check it out here.


text:
Q: Nokogiri to_xml without carriage returns I'm currently using the Nokogiri::XML::Builder class to construct an XML document, then calling .to_xml on it.  The resulting string always contains a bunch of spaces, linefeeds and carriage returns in between the nodes, and I can't for the life of me figure out how to get rid of them.  Here's an example:
b = Nokogiri::XML::Builder.new do |xml|
  xml.root do
    xml.text("Value")
  end
end

b.to_xml

This results in the following:
<?xml version="1.0"?>
<root>Value</root>

What I want is this (notice the missing newline):
<?xml version="1.0"?><root>Value</root>

How can this be done?  Thanks in advance!

A: Builder#to_xml by default outputs formatted (i.e. indented) XML. You can use the Nokogiri::XML::Node::SaveOptions to get an almost unformatted result.
b = Nokogiri::XML::Builder.new do |xml|
  xml.root do
    xml.foo do
      xml.text("Value")
    end
  end
end

b.to_xml
# => "<?xml version=\"1.0\"?>\n<root>\n  <foo>Value</foo>\n</root>\n"

b.to_xml(:save_with => Nokogiri::XML::Node::SaveOptions::AS_XML)
# => "<?xml version=\"1.0\"?>\n<root><foo>Value</foo></root>\n"

Now you could either just get rid of the XML header (which is optional anyway) and remove the last newline
b.to_xml(:save_with => Nokogiri::XML::Node::SaveOptions::AS_XML | Nokogiri::XML::Node::SaveOptions::NO_DECLARATION).strip
# => "<root><foo>Value</foo></root>"

Just removing all newlines in the XML is probably a bad idea as newlines can actually be significant (e.g. in <pre> blocks of XHTML). If that is not the case for you (and you are really sure of that) you could just do it.

A: This is not something that Nokogiri is designed to do. The closest you can get is to serialize the root of the document with no newlines or indentation, and then add the PI yourself (if you really need it):
require 'nokogiri'

b = Nokogiri::XML::Builder.new{ |xml| xml.root{ xml.foo "Value" } }
p b.to_xml
#=> "<?xml version=\"1.0\"?>\n<root>\n  <foo>Value</foo>\n</root>\n"

p b.doc.serialize(save_with:0)
#=> "<?xml version=\"1.0\"?>\n<root><foo>Value</foo></root>\n"

flat_root = b.doc.root.serialize(save_with:0)
p flat_root
#=> "<root><foo>Value</foo></root>"

puts %Q{<?xml version="1.0"?>#{flat_root}}
#=> <?xml version="1.0"?><root><foo>Value</foo></root>

Alternatively, you could simply cheat and do:
puts b.doc.serialize(save_with:0).sub("\n","")
#=> <?xml version="1.0"?><root><foo>Value</foo></root>

Note the usage of sub instead of gsub to only replace the first known-present newline.

A: b.to_xml returns a string. You just need to replace the first instance of \n in the string.
require 'nokogiri'

b = Nokogiri::XML::Builder.new do |xml|
  xml.root do
    xml.text("Value")
  end
end

b.to_xml.sub("\n",'')

Probably easier than trying to overload the method.


text:
Q: which is the latest C cross compiler for u-boot2019 and linux kernel? i want to compile u-boot2019,but it is for gcc6.0+.
*** Your GCC is older than 6.0 and is not supported

I can only search for"arm-none-linux-gnueabi-gcc" and "arm-linux-gnueabihf-gcc" for 2014.
Thanks in advance!

A: You can get a version 7.4.1 toolchain from Linaro and a version 8.3.0 one from Arm.
Update: you can now get  a version 7.5.0 toolchain from Linaro, and a version 9.2.1 from Arm.

A: You can use tools/buildman/buildman to fetch a toolchain for you (and also use it) from kernel.org, or you can also get one from https://toolchains.bootlin.com/


text:
Q: Setting specific rows to the value found in a row if differing index I work with a lot of CSV data for my job. I am trying to use Pandas to convert the member 'Email' to populate into the row of their spouses 'PrimaryMemberEmail' column. Here is a sample of what I mean:
import pandas as pd

user_data = {'FirstName':['John','Jane','Bob'],
             'Lastname':['Snack','Snack','Tack'],
             'EmployeeID':['12345','12345S','54321'],
             'Email':['John@issues.com','NaN','Bob@issues.com'],
             'DOB':['09/07/1988','12/25/1990','07/13/1964'],
             'Role':['Employee On Plan','Spouse On Plan','Employee Off Plan'],
             'PrimaryMemberEmail':['NaN','NaN','NaN'],
             'PrimaryMemberEmployeeId':['NaN','12345','NaN']
             }

df = pd.DataFrame(user_data)

I have thousands of rows like this. I need to only populate the 'PrimaryMemberEmail' when the user is a spouse with the 'Email' of their associated primary holders email. So in this case I would want to autopopulate the 'PrimaryMemberEmail' for Jane Snack to be that of her spouse, John Snack, which is 'John@issues.com' I cannot find a good way to do this. currently I am using:
for i in (df['EmployeeId']):
    p = (p + len(df['EmployeeId']) - (len(df['EmployeeId'])-1))
    EEID = df['EmployeeId'].iloc[p]

    if 'S' in EEID:
        df['PrimaryMemberEmail'].iloc[p] = df['Email'].iloc[p-1]

What bothers me is that this only works if my file comes in correctly, like how I showed in the example DataFrame. Also my NaN values do not work with dropna() or other methods, but that is a question for another time.
I am new to python and programming. I am trying to add value to myself in my current health career and I find this all very fascinating. Any help is appreciated.

A: IIUC, map the values and fillna:
df['PrimaryMemberEmail'] = (df['PrimaryMemberEmployeeId']
                            .map(df.set_index('EmployeeID')['PrimaryMemberEmail'])
                            .fillna(df['PrimaryMemberEmail'])
                           )

Alternatively, if you have real NaNs, (not strings), use boolean indexing:
df.loc[df['PrimaryMemberEmployeeId'].notna(),
       'PrimaryMemberEmail'] = df['PrimaryMemberEmployeeId'].map(df.set_index('EmployeeID')['PrimaryMemberEmail'])

output:
  FirstName Lastname EmployeeID         DOB               Role PrimaryMemberEmail PrimaryMemberEmployeeId
0      John     Mack      12345  09/07/1988   Employee On Plan    John@issues.com                     NaN
1      Jane    Snack     12345S  12/25/1990     Spouse On Plan    John@issues.com                   12345
2       Bob     Tack      54321  07/13/1964  Employee Off Plan     Bob@issues.com                     NaN


text:
Q: Java работа с массивом если массив {true, true, true} result = true;
если массив {true, false, true} result = false;
    public static boolean mono(boolean[] data) {
    boolean result = true;
    for (int i = 0; i < data.length; i++) {
        if (data[i] == data[0]) {
            result = true;
        } else {
            result = false;
        }
    }
        return result;
}
public static void main(String[] args) {
    boolean[] a = {true,false,true};
    System.out.println(mono(a));
}

но в моем коде мравнивается последний элемент, что я делаю не так?

A: По-моему тут требуется проверить не равенство элементов массива, а то, что все эти элементы - true. Например так:
public static boolean checkAllTrue(boolean... all) {
    boolean result = all != null && all.length > 0;
    for (int i = 0, j = result ? all.length : 0; i < j && (all[i] || (result = false)); i++);
    return result;
}

A: Проверка на равенство всех элементов массива:
public static boolean mono(boolean[] data) {
    for (int i = 1; i < data.length; i++) {
        if (data[i] != data[i - 1])
            return false;
    }
    return true;
}

public static void main(String[] args) {
     boolean[] a = {true,false,true};
     System.out.println(mono(a));
}

A:  public boolean mono(boolean[] data) {
    boolean result = true;
    for (int i = 0; i < data.length; i++) {
        if (data[i] != data[0]) {
            result = false;
            break;
        }
    }
        return result;
}


text:
Q: Problemas em inserir dados em base de dados Boas, eu estou aqui com um problema pois insiro os dados todos mas não me guarda na base de dados. Alguém aqui sabe qual o problema com os seguintes códigos:

<form action="php/RegistoFederados.php" id="formF" method="post">

Sexo
<select name="sexo" id="sexo" required>
 <option value="">Escolha uma opção</option>
 <option value="M">Masculino</option>
 <option value="F">Feminino</option>
</select>

Nome Completo
<input type="text" class="txtfield" name="nome" placeholder="Nome Completo" required >

Data de Nascimento
<input type="date"  name="dataNasc"  required>

BI ou CC
<input type="text" class="txtfield" name="bi" maxlength="8" placeholder="BI ou CC" required onblur="Vbi()">

Nº licença de Federado
<input type="text" class="txtfield" name="Nfederado" id="nf" onblur="Vfed()" required>

Email
<input type="text" class="email" name="email" placeholder="maratonajomara@gmail.com" required>

Telemovel
<input type="text"  id="tlm" class="txtfield" name="telemovel" maxlength="9" required onblur="Vtlm()">

Morada
<input type="text" class="txtfield" name="morada" required>

Levantamento de dorsais
<select name="localdorsal" id="localS" required>
 <option value="">Escolha uma opção</option>
 <option value="loja">Loja Jomara</option>
 <option value="PUA"> Quiosque do Conhecimento PUA</option>
</select>

Metodo de Pagamento **
<Select name="pagamento" required>
 <option value="">Escolha uma opção</option>
 <option value="Dinheiro">Dinheiro</option>
 <option value="Transferência">Transferência Bancaria</option>
</select>

Equipa
<input type="text" class="txtfield" name="equipa">

Prova
<select name="prova" required>
 <option value="">Escolha uma opção</option>
 <option value="45 km">Meia-Maratona 45 KM</option>
 <option value="70 km">Maratona 70 KM</option>
</select>

Almoço
<select name="almoco" required>
 <option value="">Escolha uma opção</option>
 <option value="1">Sim</option>
 <option value="0">Não</option>
</select>

<input type="submit" class="Sinscricao" value="Submeter Inscrição">

**Nas inscrições se o pagamento for por transferência bancária, deverá ser enviado o comprovativo por e-mail com o nome completo do atleta

</form>

<?php
 $con = mysqli_connect("localhost","root","","jomara");

 $sexo = mysql_real_escape_string($_POST['sexo']);
    $nome = mysql_real_escape_string($_POST['nome']);
 $dataNasc = mysql_real_escape_string($_POST['dataNasc']);
    $bi = mysql_real_escape_string($_POST['bi']);
 $nf = mysql_real_escape_string($_POST['Nfederado']);
    $email = mysql_real_escape_string($_POST['email']);
    $telemovel = mysql_real_escape_string($_POST['telemovel']);
    $morada = mysql_real_escape_string($_POST['morada']);
    $local_dorsal = mysql_real_escape_string($_POST['localdorsal']);
    $pagamento = mysql_real_escape_string($_POST['pagamento']);
    $equipa = mysql_real_escape_string($_POST['equipa']);
    $categoria = mysql_real_escape_string($_POST['categoria']);
    $almoco = mysql_real_escape_string($_POST['almoco']);
    $pago = 0;

 $sql = "INSERT INTO registofederados(sexo,nome,dataNasc,bi,numero_federado,email,telemovel,morada,local_dorsal,pagamento,equipa,categoria,almoco,pago) VALUES('$sexo','$nome','$dataNasc','$bi','$nf','$email', '$telemovel', '$morada', '$local_dorsal', '$pagamento', '$equipa', '$categoria', $almoco, $pago)";

 if(mysqli_query($con, $sql)){
 echo "";
 }
 else{
  echo "";
  header('Location: ../federados.html');
  }
?>

A: Primeiro verifiquem sempre se os dados da base de dados coincidem com os dados do php. Depois verifiquem sempre se os dados que estão no php são os mesmos que os do form na pagina de html. Foi esse o meu problema e estou a responder à minha pergunta para não haver outra pessoa a passar pela burrice que passei.


text:
Q: Tikz : texture cube faces using png image I would like to draw a cube using Tikz with some faces of the cube having a texture on it (texture would be a PNG image)
my current code is at follows :
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{3d,calc}
\tikzset{persp/.style={scale=3.0,x={(-0.8cm,-0.4cm)},y={(0.8cm,-0.4cm)}, z={(0cm,1cm)}},points/.style={fill=white,draw=black,thick}}

\begin{document}
\begin{tikzpicture}[persp]\def\i{-15}
    \pgfmathparse{cos(\i)}\let\ci\pgfmathresult
    \pgfmathparse{sin(\i)}\let\si\pgfmathresult
    \coordinate (Ocube) at (0,0,0);
    \coordinate (Xcube) at (\ci,\si,0);
    \coordinate (Ycube) at (-\si,\ci,0);
    \coordinate (Zcube) at (0,0,1);
    \coordinate (C0) at ($(Ocube)-(Xcube)-(Ycube)-(Zcube)$);
    \coordinate (C1) at ($(Ocube)+(Xcube)-(Ycube)-(Zcube)$);
    \coordinate (C2) at ($(Ocube)-(Xcube)+(Ycube)-(Zcube)$);
    \coordinate (C3) at ($(Ocube)+(Xcube)+(Ycube)-(Zcube)$);
    \coordinate (C4) at ($(Ocube)-(Xcube)-(Ycube)+(Zcube)$);
    \coordinate (C5) at ($(Ocube)+(Xcube)-(Ycube)+(Zcube)$);
    \coordinate (C6) at ($(Ocube)-(Xcube)+(Ycube)+(Zcube)$);
    \coordinate (C7) at ($(Ocube)+(Xcube)+(Ycube)+(Zcube)$);
    \fill[black!20, draw=black, dashed,opacity=0.3] (C0)--(C1)--(C3)--(C2)--cycle;
    \fill[black!20, draw=black, dashed,opacity=0.3] (C0)--(C1)--(C5)--(C4)--cycle;
    \fill[black!20, draw=black, dashed,opacity=0.3] (C0)--(C2)--(C6)--(C4)--cycle;
    \fill[black!20, draw=black, thick,opacity=0.3] (C4)--(C5)--(C7)--(C6)--cycle;
    \fill[black!20, draw=black, thick,opacity=0.3] (C2)--(C3)--(C7)--(C6)--cycle;
    \fill[black!20, draw=black, thick,opacity=0.3] (C1)--(C3)--(C7)--(C5)--cycle;
    \coordinate (Q0) at ($(Ocube)-.8*(Xcube)+(Ycube)-.8*(Zcube)$);
    \coordinate (Q1) at ($(Ocube)+.8*(Xcube)+(Ycube)-.8*(Zcube)$);
    \coordinate (Q2) at ($(Ocube)-.8*(Xcube)+(Ycube)+.8*(Zcube)$);
    \coordinate (Q3) at ($(Ocube)+.8*(Xcube)+(Ycube)+.8*(Zcube)$);
    \fill[white!20, draw=black, thick,opacity=0.3] (Q0)--(Q1)--(Q3)--(Q2)--cycle;
\end{tikzpicture}
\end{document}

On the last line, rather then filling white a color (white!20), I would like to draw the image "face.png". This drawing must be distorded so to fit the face realisticaly.
Could someone help me doing that ?

A: There are several questions on the site which address filling a shape with an image in TikZ, for example:

*

*TikZ: Drawing regular hexagons with pictures inside

*How to clip an external image inside an ellipse
We can adapt those solutions to your 3D shape. We use \clip to restrict to the front square of the cube, then add the image, and finally we draw the border around it.
I've replaced the line:
\fill[white!20, draw=black, thick,opacity=0.3] (Q0)--(Q1)--(Q3)--(Q2)--cycle;

with
\def\frontsquare{(Q0)--(Q1)--(Q3)--(Q2)--cycle}

\begin{scope}
    \clip \frontsquare;
    \node {\includegraphics{grass.jpg}};
\end{scope}

\draw[black, thick] \frontsquare;

First I define \frontsquare to the area you want to fill. The \clip contained in the scope restricts everything else we draw to within that area, until \end{scope}. When I use \includegraphics to add an image, only the part of the image that is within the front square. The \draw command then adds a border.
This is what the resulting cube looks like:

and here's the complete code:
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{3d,calc}
\tikzset{persp/.style={scale=3.0,x={(-0.8cm,-0.4cm)},y={(0.8cm,-0.4cm)}, z={(0cm,1cm)}},points/.style={fill=white,draw=black,thick}}

\begin{document}
\begin{tikzpicture}[persp]\def\i{-15}
    \pgfmathparse{cos(\i)}\let\ci\pgfmathresult
    \pgfmathparse{sin(\i)}\let\si\pgfmathresult
    \coordinate (Ocube) at (0,0,0);
    \coordinate (Xcube) at (\ci,\si,0);
    \coordinate (Ycube) at (-\si,\ci,0);
    \coordinate (Zcube) at (0,0,1);
    \coordinate (C0) at ($(Ocube)-(Xcube)-(Ycube)-(Zcube)$);
    \coordinate (C1) at ($(Ocube)+(Xcube)-(Ycube)-(Zcube)$);
    \coordinate (C2) at ($(Ocube)-(Xcube)+(Ycube)-(Zcube)$);
    \coordinate (C3) at ($(Ocube)+(Xcube)+(Ycube)-(Zcube)$);
    \coordinate (C4) at ($(Ocube)-(Xcube)-(Ycube)+(Zcube)$);
    \coordinate (C5) at ($(Ocube)+(Xcube)-(Ycube)+(Zcube)$);
    \coordinate (C6) at ($(Ocube)-(Xcube)+(Ycube)+(Zcube)$);
    \coordinate (C7) at ($(Ocube)+(Xcube)+(Ycube)+(Zcube)$);
    \fill[black!20, draw=black, dashed,opacity=0.3] (C0)--(C1)--(C3)--(C2)--cycle;
    \fill[black!20, draw=black, dashed,opacity=0.3] (C0)--(C1)--(C5)--(C4)--cycle;
    \fill[black!20, draw=black, dashed,opacity=0.3] (C0)--(C2)--(C6)--(C4)--cycle;
    \fill[black!20, draw=black, thick,opacity=0.3] (C4)--(C5)--(C7)--(C6)--cycle;
    \fill[black!20, draw=black, thick,opacity=0.3] (C2)--(C3)--(C7)--(C6)--cycle;
    \fill[black!20, draw=black, thick,opacity=0.3] (C1)--(C3)--(C7)--(C5)--cycle;
    \coordinate (Q0) at ($(Ocube)-.8*(Xcube)+(Ycube)-.8*(Zcube)$);
    \coordinate (Q1) at ($(Ocube)+.8*(Xcube)+(Ycube)-.8*(Zcube)$);
    \coordinate (Q2) at ($(Ocube)-.8*(Xcube)+(Ycube)+.8*(Zcube)$);
    \coordinate (Q3) at ($(Ocube)+.8*(Xcube)+(Ycube)+.8*(Zcube)$);

    \def\frontsquare{(Q0)--(Q1)--(Q3)--(Q2)--cycle}

    \begin{scope}
        \clip \frontsquare;
        \node {\includegraphics{grass.jpg}};
    \end{scope}

    \draw[black, thick] \frontsquare;
\end{tikzpicture}
\end{document}

A: Not exactly an answer to the question, but it is fun.
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{backgrounds}

\begin{document}
\begin{tikzpicture}
  \draw[yellow,yslant=0.5] (0,0) rectangle (2,2);
  \node[yslant=0.5,anchor=center,opacity=0.3]  at (1,1.5) {\includegraphics[width=2cm,height=2cm]{example-image-a}};
  \draw[magenta,yslant=-0.5] (-2,2) rectangle (0,0);
  \node[yslant=-0.5,anchor=center,opacity=0.3]  at (-1,1.5) {\includegraphics[width=2cm,height=2cm]{example-image-b}};
  \begin{scope}[on background layer]
  \draw[orange,yslant=-0.5] (0,2) rectangle (2,4);
  \node[yslant=-0.5,anchor=center,xshift=0cm,yshift=1cm,opacity=0.3]  at (1,1.5) {\includegraphics[width=2cm,height=2cm]{example-image-b}};
  \draw[green,yslant=0.5,,xshift=-2cm,yshift=2cm] (0,0) rectangle (2,2);
  \node[yslant=0.5,anchor=center,xshift=-2cm,yshift=2cm,opacity=0.3]  at (1,1.5) {\includegraphics[width=2cm,height=2cm]{example-image-a}};
\draw[blue,yslant=-0.5,xslant=1] (-2,0) rectangle (0,2);
\node[yslant=-0.5,anchor=center,xshift=0cm,yshift=2cm,xslant=1,opacity=0.3]  at (-0,-1) {\includegraphics[width=2cm,height=2cm]{example-image-a}};
  \end{scope}
  \draw[red,yslant=-0.5,xslant=1] (-4,2) rectangle (-2,4);
\node[yslant=-0.5,anchor=center,xshift=0cm,yshift=4cm,xslant=1,opacity=0.3]  at (-0,-1) {\includegraphics[width=2cm,height=2cm]{example-image-a}};

\end{tikzpicture}
\end{document}


text:
Q: mongodb query to show subdocument as maindocument and having pagination with it First of all, I have this type of model:
const produkSchema = new mongoose.Schema({
    nama_produk: String,
    etalase: {type: mongoose.Schema.Types.ObjectID, ref: 'kategori'},
    kategori: {type: mongoose.Schema.Types.ObjectID, ref: 'kategori'},
    jenis: {type: mongoose.Schema.Types.ObjectID, ref: 'kategori.jenis'},
    bahan: String,
    warna: String,
    deskripsi: String,
    foto_produk: [String],
    harga: Number,
    link_bukalapak: String,
    link_shopee: String,
    link_tokopedia: String,
    link_lazada: String,
    link_website: String,
    display: {type: Boolean, default: false},
}, {
    weights: {
        nama_produk: 5,
    },
    timestamps: true
})

const tokoSchema = new mongoose.Schema({
    username: {type: String, trim: true},
    password: {type: String, required: true, select: false},
    merek: String,
    listMerek: [{type: mongoose.Schema.Types.ObjectID, ref: 'produk'}],
    deskripsi: String,
    follower: [{type: mongoose.Schema.Types.ObjectID, ref: 'user'}],
    email: {type: String, trim: true, unique: true},
    instagram: String,
    whatsapp: String,
    website: String,
    alamat: String,
    foto_profil: String,
    bukalapak: String,
    shopee: String,
    tokopedia: String,
    fotoktp: String,
    banner: [{
        gambar: {type: String, required: true, trim: true},
        // order: {type: Number, required: true},
    }],
    produk: [produkSchema],
    etalase: [{type: mongoose.Schema.Types.ObjectID, ref: 'kategori'}],
    // etalase: [{
    //     kategori: {type: mongoose.Schema.Types.ObjectID, ref: 'kategori'},
    //     order: {Number}
    // }],
    approve: {type: Number, default: 0}, // 0: pending, 1: reject, 2: approve
    populer: {type: Boolean, default: false},
    gambar_populer: [String],
    pilihan: {type: Boolean, default: false},
}, {timestamps: true});

and I have an endpoint to filter this produkSchema with following code:
exports.filterProduk = (req, res) => {
    const {merek, warna, kategori, jenis, hargaAwal, hargaAkhir, skip, limit} = req.body

    let query = {}
    const $and = []

    if (merek) {
        $and.push({$or: merek.map(id => ({_id: mongoose.Types.ObjectId(id)}))})
    }

    if (warna) {
        $and.push({$or: warna.map(warna => ({"produk.warna": warna}))})
    }

    if (kategori) {
        query["produk.etalase"] = mongoose.Types.ObjectId(kategori)
    }

    if (jenis) {
        $and.push({$or: jenis.map(id => ({"produk.jenis": mongoose.Types.ObjectId(id)}))})
    }

    if (hargaAwal !== '') {
        query["produk.harga"] = {
            $gte: parseInt(hargaAwal),
        }
    }
    if (hargaAkhir !== '') {
        query["produk.harga"] = {
            $lte: parseInt(hargaAkhir)
        }
    }

    if ($and.length > 0) {
        query = {$and, ...query}
    }

    toko.aggregate([
        {$unwind: '$produk'},
        {$match: query},
        {
            $lookup: {
                from: "kategoris",
                as: "produk.etalase",
                let: {pjid: "$produk.jenis"},
                pipeline: [
                    {$unwind: "$jenis"},
                    {$match: {$expr: {$eq: ["$$pjid", "$jenis._id"]}}},
                    {
                        $project: {
                            "jenis._id": 1,
                            "jenis.label": 1
                        }
                    }
                ]
            }
        },
        {$unwind: {path: "$produk.etalase"}},
        {$group: {_id: '$_id', produk: {$push: '$produk'}, foto_profil: {$first: '$foto_profil'}}},
        {$limit: skip + limit},
        {$skip: skip}
    ])
        .then(async data => {
            res.status(200).json({data, prefix: {produk: "uploads/produk", toko: "uploads/toko"}})
        })
}

the actual result is:
[
{_id: blabla,
 foto_profil: "blabla",
 produk:[{nama_produk: "blabla", bahan: "blabla", ...rest ProdukSchema as query}]
},
{_id: blabla,
 foto_profil: "blabla",
 produk:[{nama_produk: "blabla", bahan: "blabla", ...rest ProdukSchema as query}]
},
{_id: blabla,
 foto_profil: "blabla",
 produk:[{nama_produk: "blabla", bahan: "blabla", ...rest ProdukSchema as query}]
}
]

expected:
[
{nama_produk: "blabla", bahan: "blabla", ...rest ProdukSchema as query, foto_profil(from toko schema): "blabla"},
{nama_produk: "blabla", bahan: "blabla", ...rest ProdukSchema as query, foto_profil(from toko schema): "blabla"}
]

and having pagination with this produkSchema (limit and offset)
actually, before this, I already ask for this query at here, but this query will produce a lot of data and need to be paginated,
how do I do this? Should I split my produkSchema to main subdocument? or any query exist for this condition?

A: I am not sure with exact requirement, but I can guess 2 options,

*

*Assuming Variables:

let skip = 0;
let limit = 10;

First Option:

*

*remove $group stage from the end and start after $unwind stage

*$replaceRoot to merge objects produk and foto_profil using $mergeObjects and replace the root

  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: [{ foto_profil: "$foto_profil" }, "$produk"]
      }
    }
  },
  { $skip: skip * limit },
  { $limit: limit }

Playground

Second Option:

*

*remove $group stage from the end and start after $unwind stage

*$group by toko id and produk id, this will group produk and get unique first produk

*$replaceRoot to merge objects produk and foto_profil using $mergeObjects and replace the root

  {
    $group: {
      _id: {
        _id: "$_id",
        produk_id: "$produk._id"
      },
      root: { $first: "$$ROOT" }
    }
  },
  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: [{ foto_profil: "$root.foto_profil" }, "$root.produk"]
      }
    }
  },
  { $skip: skip * limit },
  { $limit: limit }

Playground

A: maybe you can do this after lookup:

*

*$unwind produk (where the produk still on array type, then unwind it).

*$group: { _id: nama_produk, etc... }

*$project ...... or whatever you wanna do with.

so you can get the list of group by nama_produk as an _id.


text:
Q: Using CMake with GNU Make: How can I see the exact commands? I use CMake with GNU Make and would like to see all commands exactly (for example how the compiler is executed, all the flags etc.).
GNU make has --debug, but it does not seem to be that helpful are there any other options? Does CMake provide additional flags in the generated Makefile for debugging purpose?

A: It is convenient to set the option in the CMakeLists.txt file as:
set(CMAKE_VERBOSE_MAKEFILE ON)

A: cmake --build . --verbose
On Linux and with Makefile generation, this is likely just calling make VERBOSE=1 under the hood, but cmake --build can be more portable for your build system, e.g. working across OSes or if you decide to do e.g. Ninja builds later on:
mkdir build
cd build
cmake ..
cmake --build . --verbose

Its documentation also suggests that it is equivalent to VERBOSE=1:

--verbose, -v
Enable verbose output - if supported - including the build commands to be executed.
This option can be omitted if VERBOSE environment variable or CMAKE_VERBOSE_MAKEFILE cached variable is set.

Tested on Cmake 3.22.1, Ubuntu 22.04.

A: If you use the CMake GUI then swap to the advanced view and then the option is called CMAKE_VERBOSE_MAKEFILE.

A: When you run make, add VERBOSE=1 to see the full command output. For example:
cmake .
make VERBOSE=1

Or you can add -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON to the cmake command for permanent verbose command output from the generated Makefiles.
cmake -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON .
make

To reduce some possibly less-interesting output you might like to use the following options. The option CMAKE_RULE_MESSAGES=OFF removes lines like [ 33%] Building C object..., while --no-print-directory tells make to not print out the current directory filtering out lines like make[1]: Entering directory and make[1]: Leaving directory.
cmake -DCMAKE_RULE_MESSAGES:BOOL=OFF -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON .
make --no-print-directory

A: I was trying something similar to ensure the -ggdb flag was present.
Call make in a clean directory and grep the flag you are looking for. Looking for debug rather than ggdb I would just write.
make VERBOSE=1  | grep debug
The -ggdb flag was obscure enough that only the compile commands popped up.

A: CMake 3.14+
CMake now has --verbose to specify verbose build output. This works regardless of your generator.
cd project
cmake -B build/
cmake --build build --verbose

It's worth noting however Xcode may not work with --verbose
Some generators such as Xcode don't support this option currently.

Another option it to use the VERBOSE environment variable.
New in version 3.14.

Activates verbose output from CMake and your build tools of choice when you start to actually build your project.

Note that any given value is ignored. It's just checked for existence.

A: Or simply export VERBOSE environment variable on the shell like this:

export VERBOSE=1

A: cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=TRUE will generate a file with all compilation commands.
This file is required by some LSP to know how to compile a source file out of the box, but it could also help for debugging compilation problems.
The output file is named ${CMAKE_BINARY_DIR}/compile_commands.json.


text:
Q: How to implement Proper Pagination in millions of records in Lucene I have over 10 million Documents in my Lucene Indexes and I need to implement PROPER pagination in my application. Each document is a unique record of a College Candidate. Currently I am showing 5 records per page and providing pagination on the front end for the User.
As soon as the search is performed, 5 records are displayed for Page Number 1. Now there are buttons that takes the User to the First Page, Next Page, Previous Page and Last Page.
Now For example my search query has total hits of 10 million, and when I click on Last Page, I am basically going to Page Number 2000000(2 Million). In the back end I am passing pageNumber*5 as the maxSearch(int) in lucene search Function. This takes so much of time to fetch the results.
Please refer screenshot to see the result on front end
And this is what I am doing on the back end,

My hits are never calculated. The process gets stuck at search. Kindly suggest me a solution to implement correct solution.
P.S. I am Using Lucene 4.0.0.

A: Several approaches might help:
Leave all pagination to Lucene
You can avoid manual loop iteration over hits.ScoreDocs as described in accepted answer in Lucene 4 Pagination question.
Cursors
If performance of Lucene-based pagination approach is not enough, you can try to implement cursors:
Any (found) document has a sort position, for example a tuple (sort field value, docId). Second tuple element eliminates same sort value issue.
So you can pass sorting position to next and previous page and use sort filters instead of iteration.
For example:
In first page we see three documents (sorted by date):
(date: 2017-01-01, docId: 10), (date: 2017-02-02, docId: 3), (date: 2017-02-02, docId: 5).
Second page will start from first (by sort) document with (date >= 2017-02-02 OR (date == 2017-02-02 AND docId > 5).
Also it possible to cache this positions for several pages during search.
Pagination issues on changing index
Pagination usually applies to particular index version (if index updated in middle of user interaction with results pagination may provide bad experience -- document positions may vary due to adding and removing rows or modification the sort field value of existing document).
Sometimes we must provide search results "at moment of search", displaying a "snapshot" of index, but it is very tricky to big indexes.
Cursors that stored at client side (commonly as opaque string) can seriously break pagination when index is updated.
Usually, there are a few queries that provide really huge results and page cursors can be cached by backend using WeakMap over coreCacheKey for this queries.
Special last page handling
If and only if "Last page" is a frequent operation, you can sort results in reverse order and obtain last page documents as a reverse of top reversed results.
Keep in the mind same value issue when implementing a reverse order.


text:
Q: JSException while loading a file in a codemirror based editor using java using setvalue I have a java based application that reads a file and displays the same in a code mirror based editor. The java code reads a file selected by user and converts it into string. The string is then passed to the editor using 'editor.setvalue'. The problem is that any hardcoded string is displayed fine. But if it is read from a file then I get an error
Caused by: netscape.javascript.JSException: SyntaxError: Unexpected EOF

I am able to print the file properly, no issues in that.
This is what I am trying to do in java.
String sb = FileUtils.readFileToString(file);
webengine.executeScript("editor.setValue('" + sb + "');");

"webengine.executescript" is a javafx way of calling a javascript function visible to the html rendered in the webengine.
My code Mirror code.
<form>
    <textarea id="code" name="code">
    </textarea>
</form>
<script>
    var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
        lineNumbers : true,
        matchBrackets : true,
        mode : "text/x-java",
        theme : "theme_value",
        indentUnit : 4,
        gutter: true
    });
</script>

I am not able to understand which all characters are causing this issue.
I tried adding two strings using "+" operator and the added strings were displayed. But, when I insert a newline "\n" between the strings , I start getting the same error.I tried replacing the newline with , but not much of help as they were displayed as it is without breaking the line.

A: The issue is that when calling executeScript if the passed in String into the given Javascript method contains any newline characters or single quotes then that will result in the syntax error.
Quick fix:
    content = content.replace("'", "\\'");
    content = content.replace(System.getProperty("line.separator"), "\\n");
    content = content.replace("\n", "\\n");
    content = content.replace("\r", "\\n");

That way the newlines and single quotes will be preserved in the JavaScript method.


text:
Q: Replication of Docker Containers Please, is there a solution to replication docker container with RF = 2 (Replication factor) on a ring ?
I can't find any paper here https://scholar.google.fr/
Thank you so much for help.
Kind regards.


text:
Q: How to create such buttons with Wordpress? I'm very new to WordPress (tbh, it's my first time working with it). And I need to make a website as my school project using CMS. Creating pages with templates is alright, but I have a lot of troubles with buttons. I found this website, and I can see it using WordPress. I need such buttons as on this page https://movie-chooser.co.ua/random-movie-2/ (they appear when you hover over the image). Is this a default option for buttons in WordPress? If not, is there a plugin for this or what is the way to add them on my images?

A: First Install Elementor plugin https://wordpress.org/plugins/elementor/
and go to page when you add button and open page with elementor
and do drag and drop any element like button, space, text editor etc.

A: You have several ways to achieve that:

*

*Overwritting Wordpress CSS

*Using a plugin

*Create your own shortcode

1 - Overwriting Wordpress CSS
If you manage to display all the elements using wordpress template, and your only issue is to display buttons over the images, then it should only be a matter of CSS
2 - Using a plugin
The idea here is to find a plugin that help you to create/display the informations you need (maybe you'll need to add functionnality to basic post though custom fields or  using a custom post type).
Once you find the right plugin, again if the plugin dosen't directly offert some settings on the design then you'll have to overwrite the plugin's CSS rules to display the elements as you want.
3 - Create your own shortcode
If you're new to Wordpress I wouldn't recommend this method as it is kind of advanced, unless you're comfortable with PHP/HTML/CSS (optionaly JS).
This is the more flexible solution as you can basically control anything, but it will require you to understand some core concepts of Wordpress like WP Query and how custom queries works.
The idea here is to create a shortcode.
THis shortcode refere to a custom made PHP function, in which you can create a custom request to fetch the informations you need to display from Wordpress database, and display it in an HTML structure that you decide.
THen angain, you'll just have to customize it though CSS.
Note : no need to create a whole plugin if you decide to create a shortcode, you can use the template functions.php file for that.


text:
Q: Cordova 3.0.0 - ChildBrowser not working All the cited examples show this as the correct code:
window.plugins.childBrowser.showWebPage( "http://www.someurl.com" );

However, "window.plugins.childBrowser" is null, whilst this is not:
window.plugins.ChildBrowser

Unsurprising perhaps when one considers that this is the last code in childbrowser.js:
cordova.addConstructor(function () {
    if (!window.plugins) {
        window.plugins = {};
    }

    window.plugins.ChildBrowser = new ChildBrowser();
});

(extra information about this under the line below)
However, although the ChildBrowser property in this line has a value:
window.plugins.ChildBrowser.showWebPage( "http://www.someurl.com" );

It still doesn't do anything.
Huh?
ChildBrowser.showWebPage() looks like this btw:
ChildBrowser.prototype.showWebPage = function (url, options) {
    if (!options) {
        options = { showLocationBar: true };
    }

    cordova.exec(onEvent, onError, "ChildBrowser", "showWebPage", [url, options]);
};

ps: Cordova 3.0.0, XCode 4.6.3, ChildBrowser 5.0.0. The official plugin page at https://build.phonegap.com/plugins/480 claims that ChildBrowser 5.0.0 is supported by Cordova 3.0.0

Just to check that window.plugins ref, I ran this loop:
console.log( "loop starts..." );
for ( var propt in window.plugins ) {
    console.log( "propt " + propt );
}
console.log( "loop ends." );

And it produced this:
[Log] loop starts...
[Log] propt ChildBrowser
[Log] loop ends.

A: The official Apache plugin is "InAppBrowser"
Syntax is: 'window.open'
https://github.com/apache/cordova-plugin-inappbrowser/blob/master/doc/index.md


text:
Q: Reactive way of reading YAML with Jackson using Spring boot webflux The yamlObjectMapper in configuration
@Bean
    public ObjectMapper yamlObjectMapper() {
        ObjectMapper yamlObjectMapper = new ObjectMapper(new YAMLFactory().disable(YAMLGenerator.Feature
            .WRITE_DOC_START_MARKER));
        yamlObjectMapper.findAndRegisterModules();
        return yamlObjectMapper;
    }

The Service to parse yaml file
@Service
public class CustomerService {

  @Autowired
  @Qualifier("yamlObjectMapper")
  private ObjectMapper yamlObjectMapper;

  public Customer get() {
    try {
      InputStream inputStream = ResourceUtils.getURL("classpath:/files/test.yaml").openStream();
      return yamlObjectMapper.readValue(inputStream, Customer.class);
    } catch (IOException ex) {
      throw new IllegalStateException(ex);
    }
  }

  @Data
  public static class Customer {
    private String name;
    private String surname;
    private String email;
  }
}

I guess IO operations are blocking, how this can be done using reactive way?

A: I would rather use configuration binding since probably you need to read it once.
package com.vob.webflux.webfilter.controller;

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource(value = "classpath:config.yml", factory= YamlPropertySourceFactory.class)
@Getter
public class YamlFooProperties {
    @Value("${test}")
    private String test;
}

Factory
package com.vob.webflux.webfilter.controller;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.io.IOException;
import java.util.Properties;

public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource)
            throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(encodedResource.getResource());

        Properties properties = factory.getObject();

        return new PropertiesPropertySource(encodedResource.getResource().getFilename(), properties);
    }
}

Source factory from


text:
Q: How did the Saviours know where Rick and the team would be travelling in the Season 6 finale? Negan said he invested a lot to get all of that manpower together at that one specific day, to

 block off the roads, and stop Rick and the team travelling to Hilltop.

But how did the Saviours know that Rick and his team would be going there that day (or even travelling at all for that matter). It's true Daryl, Glenn, Michonne and Rosetta were captured, but nobody at Alexandria could have known that, and would they have known where to look even if they did? So clearly Negan knew that some of the Alexandria team would be venturing out, as I don't think all of those men would've been too happy blocking an empty road all day.
So how did he know?

A: TL;DR:  We don't know for sure, but we can make an educated guess.
The evidence available:

*

*Negan and the Saviors know where Rick's group lives.  When Carol met the pickup truck full of Saviors on the road, not only were they already en route to Alexandria, they also revealed that they had been watching Alexandria very closely for some time.  Tobin told Rick that Carol left in a car with spikes run through it that he had placed outside the gate the day before.  The Saviors in the truck mentioned that they had cars with spikes through them, just like Carol's, outside the gate of Alexandria.

*The Hilltop has no ammunition.  The Saviors know this.  The Saviors had told the Hilltop to bring Gregory's head to their base with the huge satellite dish.  If Negan checked out the base after it was attacked by Rick's group, he would have realized a few things:

*

*Whoever attacked the base had brought a head that looked a hell of a lot like Gregory, so whoever did it was in touch with Hilltop and knew what the Saviors wanted from Hilltop.

*Whoever attacked the base was heavily armed, had plenty of ammunition, and was far more aggressive and skilled than the people at Hilltop.  Clearly, Hilltop had sought help from another group who was based somewhere near Hilltop, but not at the Hilltop.

*The same kind of skill and weaponry went into other confrontations with the Saviors: at the slaughterhouse where Carol and Maggie were taken; at the spot where Carol killed the Saviors in the truck; at the railroad tracks where Daryl, Rosita, Abe, and Eugene fought off the much larger group of Saviors led by Dwight; and  at the other railroad tracks where Daryl killed three Saviors himself.

*Dwight has seen Daryl on three different occasions: in the burned out forest where they first met;  at the railroad tracks where Denise was killed;  and in the woods where Daryl was captured.  Although Daryl was alone and lightly armed on the first occasion, on the two latter occasions he was with other people and well armed.

*If the Saviors were spying on Daryl, Denise, and Rosita just before they killed Denise, they might have realized that Denise had medical training (why else would they have brought an untrained, unarmed, mostly helpless person on a supply run to a pharmacy, if not so that she could tell them which medications to take?).  They killed Denise, so the Saviors may or may not know that Alexandria no longer has a doctor.

*If they had been listening to what was going on in Alexandria as well as watching it, they might have learned that someone in Alexandria needed medical attention and was being taken to the Hilltop.
Taking all of these facts together, Negan would know a number of things:

*

*Rick's people are trained and well armed, but relatively few in number.

*They are probably running low on some supplies, which would explain why they made an unprovoked attack on the Saviors on behalf of the Hilltop.

*They definitely know about the Hilltop (including the doctor who lives there), but might not know about other communities of survivors in the area.

*They have some sort of deal worked out with the Hilltop, and it is pretty easy to figure out the basic idea of that deal:  Hilltop has supplies, but lacks firepower, and is being taxed by the Saviors;  Alexandria has firepower, but lacks something they need (probably some sort of supplies), and isn't being taxed by the Saviors yet.  Thus, the most reasonable assumption would be "Alexandria agreed to get rid of the Saviors in exchange for something that Hilltop has (presumably supplies, possibly other things as well)".

*Rick may well believe that he has already fulfilled most or all of his end of the deal - he and his people have, after all, killed at least 43 Saviors, and this was incredibly easy to do. If Rick does indeed believe he has crushed the Saviors, he would probably head to the Hilltop soon for his payment.

*Even if Rick doesn't think he's already wiped out the Saviors, he doesn't have many places to go.   He's obviously not visiting his grandma in Baltimore, or taking his kids to NYC to see the Statue of Liberty.  If he's leaving Alexandria with a fairly sizable crew, he must have a good reason for it, and there aren't that many possible destinations he could have in mind.  In fact, as far as Negan knows, Hilltop is the only friendly place Rick knows about at the moment (and this is indeed the case, at least for now).

*This all adds up to one thing:  If Rick is leaving Alexandria for anything other than a normal supply run, chances are he's headed for the Hilltop.

The Wildcard:
Having read all of the comics to date, I can assure you that this specific question doesn't really come up in the comics.  There is no elaborate network of roadblocks designed to herd Rick's people towards a specific place.  Instead, Negan just waits on the road between Hilltop and Alexandria and ambushes Rick when his group passes by.  This means that there is no reason to believe that there's a mole in Alexandria in the comic books.
However, there is one person in the comics and the show who is clearly not to be trusted...

 Gregory, the leader of the Hilltop colony.  He is a conniving, sneaky, selfish coward who is only interested in saving his own skin.  All it would take to convince Gregory to spill the beans about Alexandria is a simple threat from Negan.  "Gregory, if you tell us what you know, we'll let you live and keep being the boss of Hilltop.  If you don't tell us what you know, we'll kill you."  That's it.  That's all Gregory would need to be persuaded to sell out Rick and his community.

...

 Granted, Gregory doesn't know exactly when Rick's people will return to the Hilltop, but he does know that Maggie is pregnant and Alexandria doesn't have the neonatal resources that Hilltop has - after all, when she was at the Hilltop, she asked for an ultrasound and some neonatal vitamins.  Gregory knows that Maggie will want an occasional checkup from Hilltop's doctor to see how the pregnancy is progressing.  In other words, he knows that she'll be back sooner than later.

...

 Even if we ignore the Maggie issue, Gregory is aware that Rick's group has another reason to visit Hilltop in the near future:  Hilltop owes Rick payment for rescuing a Hilltop resident from the Saviors and beginning the war against the Saviors.  Again, Gregory knows that Rick's people will be back to Hilltop sooner than later.

A: One thing to consider is that the walking dead universe has pretty much none of the pastimes we have now. A huge outfit like the saviors might very well be waiting for a chance to do something like this.
They caught Daryl and them somewhere between Alexandria and Hilltop. They probably figured they would come looking for them, not necessarily that they would be going to Hilltop. So like Rick's group, I bet they just looked at a map and figured the most obvious paths, set up the roadblocks, and figured it would work out. For all we know, they planned for a lot more than just the ones we saw.
In the end, you might figure that Negan got to where he is not by happenstance. He may have just thought - if some of my men went out and didn't come back when planned, what would I do? I'd probably go out looking. So let's assume that's what they'll do and herd them into our trap.

A: I'm wondering if Rick's group was setup by the Hilltop colony.  Jesus seem's much more like a savior than a hilltop (he's way too cunning).  He was in the RV and could have placed a radio inside(which the saviors have been shown using).  This would have given the saviors real time intel about the situation and planning in the RV.  At the time I wondered if the attack on Gregory was a ruse (he was treated by the hilltop dr) and seemed to make the deal too quickly.  Also, the hilltop dr gave Maggie "vitamins" to take.  Could have been something like warfarin that would cause hemmorage (or about a million other things).  I don't see it being the pickles or tea.  I could speculate that the group in the microwave facility might have been a problem (either going rouge or challenging Negan's authority) and the end game was to use Rick's bunch to deal with them only to be enslaved later.  No, I don't trust Enid either.  I'm probably all wrong and have assumptions based on assumptions but it's fun to think about.

A: Sure they could have just been setting around at roadblocks waiting for Rick to come by, but that could take weeks or months.  Plus after the first or second roadblock they may have just given up and went home.  But because of Maggie it was urgent they get to the Hilltop.  So it seems likely they did have something to do with her getting sick.  If not that is a huge waste of manpower and I can think of lots of other ways for the saviors to get their point across.

A: I think the Saviors have a spy in Alexandria. She was told to get Rick and team to go to Hilltop. Her idea was to give Maggie tainted pickles to make her sick. I have always thought there is something not right with Carl's girlfriend, Enid.

A: They had to know somehow and I think Enid is the most logical answer. It may not have been the pickles she also gave her some tea I believe but I think Enid knew that they would be captured and at least one of them killed. That is why she tried so hard to keep Carl from going since he is actually the only person she has shown a real affection to.
Also story wise it would make more sense that she needed to take Maggie's spot on the wall to communicate with The Saviors, which was the pickles scene, and then later poison her once she got her marching orders.
We know that they already knew where Alexandria is located since the group that ran into Carol was headed there. We also know that it is possible to steal a car that is right by the main gate since Carol did it therefore it should be child's play the get a message to Enid if she is at the gate.

A: My theory of the potential leak from Alexandria is the guy from Hilltop that led Rick's crew to the Savior's base with "Gregory"'s head. He looked uncomfortable from the start with giving information regarding the layout.
I get he had interactions and understood how formidable they would be.. but I think he is kind of overshadowed by the events and Enid shines a bit more from being odd. That being said- I don't know if he went back to Hilltop or opted to stay in Alexandria- perhaps we will know the answer... in six months


text:
Q: Get line numbers from .NET exceptions without .pdb files
Possible Duplicate:
Generating .NET crash dumps automatically
include line numbers in stack trace without pdb?

Currently I have a .NET Windows application and I don't deploy the pdb files with it. If a client gets an exception I display it in nice window with the stack trace so they can email it to me. I am considering deploying the pdb files also so I get line numbers in the stack trace.
Now I am wondering if there is a better way. The pdb files will roughly double the size of my install, which I don't like. Is there a way to catch an exception and maybe create some kind of dump file that the user could sent to me and then I could debug that information and retrieve the line number?
If there's no common easy way to do this then I'll just deploy the pdb files and be done with it.


text:
Q: Printer not reachable in network i've a low-cost printer Samsung i provided to configure in my network.
i gave it a static IP and connected to my AP. i can ping (and use) the printer only if i'm connected to the same AP. why can't i ping this printer from any other pc in the LAN?
the positive thing is that the printer maintained the static IP and every day it's reachable if i'm connected to the same AP.
this AP, in order to work, is connected to another AP that is, in turn, connected to the main switch of the workshop.

A: So, you AP (wireless) is actually a bridge/Extender for another AP, which is connected to the main Switch.
Try looking at the AP Settings to see if certain network segregation is set-up, is the primary AP from your Provider ? because some providers configure their Wireless networks to be split from the LAN network (as is the case with my provider in BE).
Could be as simple as that the AP and LAN are 2 segregated networks.
Can you ping a AP Connected computer from a LAN Attached device ?
regards,

A: What are the ping times when you are not connected to the AP? It doesn't make sense that the AP would be segregated if you are able to ping. If you do an -arp a from a Windows machine after pinging the printer, does the MAC address for the IP of the printer match the MAC of the printer?
If you are able to ping from outside of the AP, and the MAC is correct, I would be curious how you have the printer installed. Is it installed on your machine by IP address?


text:
Q: Disable activities hot corner in Ubuntu GNOME 17.04? How do I disable the activities overview screen from popping up when I hit the top-left corner of my screen in Ubuntu GNOME 17.04?

A: There are many extensions which achieve this purpose, for example:

*

*No Topleft Hot Corner

*Activities Configurator


text:
Q: Noncommutative algebra in Algebraic Geometry. I'm a undergraduate student with an interest on Algebraic Geometry, and I already took 3 courses on Algebra, from Basic Group/Ring Theory to Galois Theory(never studied modules though, only saw one thing or another about it), but I feel the need for a revision(especially Galois Theory, I forgot many things about it), so I'm planning to study algebra again.
But I'd like to double focus on what would be useful for AG, be it Varieties or Schemes(Planning to reach them someday). I already know that Commutative Algebra is vital, but what of noncommutative algebra would be good to know?
Thanks in advance.

A: You don't need any non-commutative algebra at all for basic  algebraic geometry.
For example the two basic references for Algebraic Geometry in the last half-century, Hartshorne's Algebraic Geometry and the thousands of pages of Grothendieck-Dieudonné's monumental EGA, contain (as far as I'm aware) no noncommutative algebra at all.
Even at an expert level, noncommutative algebra is only needed in certain very specialized topics like Brauer groups and $K$-theory of schemes.
The bad (?) news is that you will need a frightening lot of commutative algebra.
Even  proving intuitively obvious  statements  like the fact that the locus cut out by a single equation on a variety reduces its dimension by one requires tough commutative algebra.
Apart from commutative algebra the most useful preparation would be to review the advanced calculus of several variables, especially the notion of differential of a map and the implicit function theorem, and its natural extension: the elementary theory of differential manifolds.


text:
Q: Pandas left join on duplicate keys but without increasing the number of columns I'm trying to combine two different dataframes I've imported in python with pandas. They are the results of some eye-tracking I've done. One of them however contains both the class and method the user has gazed upon, meaning that for every row dataframe1 has dataframe2 has an extra one. Now this doesn't happen in every row so I can't just duplicate the rows, but what I was thinking was to add another row every time the index of dataframe2 had two of the same indices. Kinda like this:
dataframe1 = pd.DataFrame({'index':[1,2,3],'a':['asd','fgh','qwe'],'b':['dsa','hgf','ewq'],'c':['sad','gfh','wqe']})
dataframe1=dataframe1[['index','a','b','c']]
dataframe1
   index    a    b    c
0      1  asd  dsa  sad
1      2  fgh  hgf  gfh
2      3  qwe  ewq  wqe

dataframe2 = pd.DataFrame({'index':[1,1,2,3,3],'d':['zxc','cxz','xzc','zxc','xcz']})
dataframe2=dataframe2[['index','d']]
dataframe2
   index    d
0      1  zxc
1      1  cxz
2      2  xzc
3      3  zxc
4      3  xcz

Expected Result:
index, a, b, c, d
1, asd, dsa, sad, zxc
1, nan, nan, nan, cxz
2, fgh, hgf, gfh, xzc
3, qwe, ewq, wqe, zxc
3, nan, nan, nan, xcz

Any built in functions to use? The values can also just be the values of the previous line with the same index.

A: Use pd.merge with an additional cumcounted column:
u = df2.assign(cnt=df2.groupby('index').cumcount())
v = df.assign(cnt=df.groupby('index').cumcount())

u.merge(v, on=['index', 'cnt'], how='left').drop('cnt', 1)

   index    d    a    b    c
0      1  zxc  asd  dsa  sad
1      1  cxz  NaN  NaN  NaN
2      2  xzc  fgh  hgf  gfh
3      3  zxc  qwe  ewq  wqe
4      3  xcz  NaN  NaN  NaN

Details
We introduce cumulative counts for the duplicate values in "index".
u = df2.assign(cnt=df2.groupby('index').cumcount())
u
   index    d  cnt
0      1  zxc    0
1      1  cxz    1
2      2  xzc    0
3      3  zxc    0
4      3  xcz    1

v = df.assign(cnt=df.groupby('index').cumcount())
v
   index    a    b    c  cnt
0      1  asd  dsa  sad    0
1      2  fgh  hgf  gfh    0
2      3  qwe  ewq  wqe    0

We then force a LEFT JOIN wrt u on "index" and "cnt". This way, NaNs are introduced int the result:
u.merge(v, on=['index', 'cnt'], how='left')

   index    d  cnt    a    b    c
0      1  zxc    0  asd  dsa  sad
1      1  cxz    1  NaN  NaN  NaN
2      2  xzc    0  fgh  hgf  gfh
3      3  zxc    0  qwe  ewq  wqe
4      3  xcz    1  NaN  NaN  NaN

The last step is to delete the temporary "cnt" column.

A: Using merge with mask and duplicated:
df = df2.merge(df1)
cols = ['index','a','b','c']
df[['a','b','c']] = df[cols].mask(df[cols].duplicated())[['a','b','c']]

print(df)
   index    d    a    b    c
0      1  zxc  asd  dsa  sad
1      1  cxz  NaN  NaN  NaN
2      2  xzc  fgh  hgf  gfh
3      3  zxc  qwe  ewq  wqe
4      3  xcz  NaN  NaN  NaN


text:
Q: We are given a class consisting of 4 boys and 4 girls. We are given a class consisting of 4 boys and 4 girls. a committee that consists of a President, a Vice-President and a secretary is to be chosen among the 8 students of the class. Let a denote the number of ways of choosing the committee in such a way that the committee has at least one boy and atleast one one girl. Let b denote the number of ways of choosing the committee in such a way that the number of girls is greater than or equal to that of boys. Then what are the values of a and b?

A: As Simon said in his answer above, $a$ can have two cases:
$a.1:$ 2 boys 1 girl, which yields $\binom{4}{2}\binom{4}{1}$ choices for people and $3!$ arrangements for their positions which yields $6\cdot4\cdot6=144$ possibilities.
$a.2:$ 1 boy 2 girls, which is the same as above and yields  $144$.
Thus $a=288$.
$b$ also has two cases:
$b.1:$ 1 boy 2 girls, which as above, yields $144$.
$b.2:$ 3 girls, which yields $\binom{4}{3}$ to choose the three girls and $3!$ arrangements which gives $4\cdot6$ possibilities $24$.
Thus $b=168$.

A: Case a is either 2 boys 1 girl or 1 boy 2 girls, case b is either 1 boy 2 girls or 3 girls. The numbers are small enough to enumerate the possibilities.

A: I agree with the answer by Linus S and the comments by Simon and Joe Taxpayer.  This is an alternate approach using a generating function that will give the solutions handily  even if the numbers are not "small enough".
We are counting the number of injective functions from the set {President, Vice President, Secretary} into the set {boy1, boy2, boy3, boy4, girl1, girl2, girl3, girl4}. The bivariate exponential generating function:
(1 + x)^4 * (1 + y*x)^4 will count the number of girls that are selected for an arbitrary number of positions.  In this case (since there are 3 positions) we seek   the coefficient of x^3/3! which is:  24 + 144 y + 144 y^2 + 24 y^3.  This tells us that of all 336 possible selections there are 24 with no girls, 144 with exactly one girl, 144 with exactly 2 girls, and 24 with exactly 3 girls.


text:
Q: PowerShell, search specific directories for specific filename I've got a program outputting a filename to the console at the moment.
I want to give it a series of directories to search through (in order) to search through to find that filename and, if it finds it, copy to another directory.
I've got this far:
[string]$fileName = "document12**2013" #** for wildcard chars
[bool]$found = false
Get-ChildItem -Path "C:\Users\Public\Documents" -Recurse | Where-Object { !$PsIsContainer -and GetFileNameWithoutExtension($_.Name) -eq "filename" -and $found = true }

if($found = true){
Copy-Item C:\Users\Public\Documents\ c:\test
}

As it stands I've got two issues. I only know how to look through one directory, and I don't know how to specify the script to copy the particular file I've just found.

A: The Path parameter accepts an array of paths so you can specify more than one. You use the Filter parameter to get the file name you're after and pipe the results to the Copy-Item cmdlet:
Get-ChildItem -Path C:\Users\Public\Documents,$path2,$path3 -Recurse -Filter $fileName |
Copy-Item -Destination $Destination

A: What about wrapping this into a function?
Using Shay's Approach:
function copyfile($path,$fileName,$Destination) {
Get-ChildItem -Path  $path -Recurse -Filter $fileName |
Copy-Item -Destination $Destination
}

$path1=C:\Users\Public\Documents
$path2=C:\Users\Public\Music
$path3=C:\Users\Public\Pictures

copyfile $path1 corporate_policy.docx \\workstation\c$\users\Public\Documents
copyfile $path2 intro_from_ceo.mp3 \\workstation\c$\users\Public\Music
copyfile $path3 corporate_logo.jpg \\workstation\c$\users\Public\Pictures

A: You can do all of this in one pipeline:
$folders = 'C:\path\to\folder_A', 'C:\path\to\folder_B', ...

$folders | Get-ChildItem -Recurse -Filter filename.* |
    ? { -not $_.PSIsContainer } | Copy-Item -Destination 'C:\test\'

Note that you must have a trailing backslash if you're using a folder as the destination in Copy-Item, otherwise the cmdlet will try to replace the folder C:\test with a file C:\test, which will cause an error.


text:
Q: Can you prove a definite integral has no closed form? It is a well known fact that some functions posses no closed form antiderivative yet still they have definite integrals that have a closed form. A classic example is the Gaussian integral $$\int_{-\infty}^\infty e^{-x^2}\mathrm dx=\sqrt\pi$$
Now look at the functions that do not possess anitderivatives in a closed form. We do this because finding the antiderivative is the most trivial way of evaluating a definite integral.
Is it possible to prove that a functions definite integral simply doesn't exist in a closed form?
I imagine to do such a thing one would need to look at the nature of the integrand with respect to many different techniques for evaluating definite integrals. It looks to me that this is an extremely tedious and difficult task however is it possible?
This is similar in a sense to proving that some polynomial equations cannot have a closed form by radicals however radicals and functions considered to be "closed form" are radically different. This means that the mechanics of proof may not be very well understood.
I am specifically talking about Wikipedia's definition for closed form. And if possible the extra work that would be needed if we want to allow special functions. Beta, Gamma, Erf, PolyGamma etc.


text:
Q: Loss is decreasing and accuracy is not improving in siamese network with contrastive loss function # We have 2 inputs, 1 for each picture
left_input = Input(img_size)
right_input = Input(img_size)

# We will use 2 instances of 1 network for this task
convnet = Sequential([
 Conv2D(4,3, input_shape=img_size, padding='same'),
 Activation('relu'),
 MaxPooling2D(),
 Conv2D(4,3, padding='same'),
 Activation('relu'),
 MaxPooling2D(),
 Conv2D(4,3, padding='same'),
 Activation('relu'),
 MaxPooling2D(),
 Conv2D(4,3, padding='same'),
 Activation('relu'),
 Flatten(),
 Dropout(0.3),
 Dense(18),
 Activation('sigmoid')
])
# Connect each 'leg' of the network to each input
# Remember, they have the same weights
encoded_l = convnet(left_input)
encoded_r = convnet(right_input)

# Getting the L1 Distance between the 2 encodings
L1_layer = Lambda(lambda tensor:K.abs(tensor[0] - tensor[1]))

# Add the distance function to the network
L1_distance = L1_layer([encoded_l, encoded_r])

prediction = Dense(1,activation='sigmoid')(L1_distance)
siamese_net = Model(inputs=[left_input,right_input],outputs=prediction)

optimizer = Adam(lr, decay=2.5e-4)

#//TODO: get layerwise learning rates and momentum annealing scheme described in paperworking
siamese_net.compile(loss=tfa.losses.contrastive.contrastive_loss,optimizer=optimizer,metrics=['acc'])

siamese_net.summary()

my accuracy is decreasing eventhough loss value is decreasing?
I have got output like this
Epoch 1/10 6368/6368 [==============================] - 647s 102ms/step - loss: 0.1762 - acc: 0.2134 - val_loss: 0.1590 - val_acc: 0.1784
Epoch 2/10 6368/6368 [==============================] - 1094s 172ms/step - loss: 0.1649 - acc: 0.1881 - val_loss: 0.1548 - val_acc: 0.1784
Epoch 3/10 6368/6368 [==============================] - 1440s 226ms/step - loss: 0.1573 - acc: 0.1779 - val_loss: 0.1515 - val_acc: 0.1790

may i know what is the reason why my accuracy is reducing even though the loss function is reducing?


text:
Q: How disable check constraint on connection java.sql.DriverManager.getConnection("jdbc:ucanaccess:///user/dev/project/project.mdb")
I have this error
Java::NetUcanaccessJdbc::UcanaccessSQLException: integrity constraint violation: NOT NULL check constraint; SYS_CT_10991 table: EMPLOYE column: DATE
I doesn't want control integrity at the connection, what is the property parameter to disable check contrainte at the connection ?
Thank for your help

A: If this exception is thrown at the connection time, it means that the database data are inconsistent with its contraints: ucanaccess is properly building a dbms layer with all integrity contraints but the  creation of one of those constraints fails.
You can't disable it, ucanaccess must create all constraints so that  when you try to insert/update/delete a record, all related  constraints are checked and your db consistent state is preserved.
Why don't you drop the not null constraint  in the database table definition?(you have just to set the "required" property, on the mentioned column, from true to false). It doesn't seem to be taken into account...