text:
Q: WaitForSingleObject: do not lock a mutex but check the current state? I'm currently using WaitForSingleObject((HANDLE)handle,INFINITE) function to mutex-lock some parts of my code.
Now I have a situation where I do not want to lock it but just peek, if it is in the locked-state. Using POSIX I can do that with pthread_mutex_trylock() - when it fails, I know there is already a lock on this mutex.
So: how can this be done with WaitforSingleObject()-call? How can I find out if the related mutex is already locked?
I guess it has something to do with the dwMilliseconds parameter, but I don't understand how I can find out if it is locked or just returned because of an other lock...

A: WaitForSingleObject (family of functions) is used for effectively putting a thread to sleep while waiting on various types of Windows handles. Execution of the thread will wait until the function has returned. In the simplest case of using mutex, these functions also request a lock. The thread will keep the mutex locked until you call ReleaseMutex.
dwMilliseconds merely specifies the wait timeout. Normally you should use the constant INFINITE here. You can also pass the value 0  to dwMilliseconds to have the function check the status of the handle and immediately return and continue execution. If it returns WAIT_OBJECT_0 (or equivalent), you have the mutex lock. This is the equivalent to pthread_mutex_trylock.
In case you do specify a timeout, WaitForSingleObject will return a timeout status WAIT_TIMEOUT when it has not gotten the requested handle within the specified time period. In case of WaitForMultipleObjects, you also need to check the result to see which object you got.
Example from MSDN: https://learn.microsoft.com/en-us/windows/win32/sync/using-mutex-objects

A: There is no "peeking" a mutex's current state. Either you lock the mutex or you don't, there is no peek.
pthread_mutex_trylock() always returns immediately and does not block the calling thread whether the mutex is already locked or not. However, if the mutex was not locked and trylock is successful then the lock has been obtained and you must unlock it. You must check the return value to know which is the case.
To replicate the same behavior with WaitForSingleObject(), simply set the timeout to 0 so it exits immediately without blocking. If the mutex is not already locked and the wait is successful, the lock is obtained and you must unlock it. Again, you must check the return value.
Note: there is a subtle but important difference between a pthread mutex and a Win32 mutex. A Win32 mutex is always recursive. When a thread already has a lock to a Win32 mutex, it can safely relock the same mutex without blocking itself. An internal lock count is incremented each time the mutex is relocked, and the thread simply needs to unlock the mutex as many times as it (re)locked in order to release the mutex for other threads to lock. A pthread mutex, on the other hand, is recursive only if the mutex creator explicitly requests it when calling pthread_mutex_init(). So be carefully with your (re)locking to avoid deadlocking your code.


text:
Q: Why is ASPNETDB.mdf created and how do I rid myself of it? My question is stated in the title, to give some background though.
I'm helping a customer use webparts within a ASP.net environment and I don't want them to get attached to this database. I'd like to be able to use the site without it creating this database.
I'm currently researching more into this, but any suggestions on sites to look at or information regarding this will be much appreciated.

A: Most of your configuration is saved in this database.  It's created to hold all the complex data that is necessary for membership and personalization to work.
You can point to a different database if you have one set up, but out of the box, Visual Studio uses this local file for the database.
I believe that web parts relies on having the database available, so you'll need to keep this database, or follow the link above to use a centralized database.
http://msdn.microsoft.com/en-us/library/879kf95c(VS.80).aspx

A: I know this is a very old post, but I had basically the same question, "Why is ASPNETDB.mdf being created?".  Since my site used a SQL database, ASPNETDB.mdf had not previously been present. But then suddenly it appeared and my entire site crashed at the hosting location.  It was a little insidious because everything worked fine in the development environment.
In my case I wanted to get a list of user roles and I had added < roleManager enabled="true" /> in web.config.  I didn't connect at the time that this would create ASPNETDB.mdf. This SO post The Role Manager feature has not been enabled has some good discussion regarding this topic.
But the point is that when I enabled the role manager, the MVC framework automatically created ASPNETDB.mdf, causing my problems at the hosting location.  I found a different way to get the roles without activating the default role manager and my immediate problem was resolved.
I just wanted to add this post in the event someone else was surprised by the sudden appearance of ASPNETDB.mdf.  This is another way it can show up, which is related to the op's question.

A: If the ASPNETDB.mdf is not needed by your application, then you can simply remove it from the "App_Data" folder where this database file is probably located and also remove the line in the web.config file that references to it.
However, this database is needed if you are using membership services as this is the place where all this information will be stored - as it was mentioned in David's answer.
Are you using one of the ASP.NET toolkits for this application? please provide more details in order to help you better.

A: The 'why' is here:

To get the aspnetdb.mdf created on the fly, one can simply Ctrl-F5 to run the web site or web application.  Click "Log In" button to let the ASP.NET Development Server or IIS server process create the aspnetdb.mdf file for you.

But this is a little old I think and things have moved around a bit.  The default connection string is now in the machine.config:

The default connection string is defined in machine.config

I find this incredibly odd and it caught me by surprise when i was iterating thru connection strings.
There is also a lot of talk on the internet that User Instance=true is now deprecated in favor of localdb, but I struggled to find an official line for that.
To make it stop, you can add a "clear" tag to connectionStrings section (I confirmed that this works):
<connectionStrings>
    <clear/>

I'm thinking of removing it from the machine.config.?  Having it in there in the first place seems pretty heavy handed on MS's part.

redpajama_set_name: RedPajamaStackExchange


text:
Q: background-image: url() don't work with localhost I tried to put a background image on my login page from a client-server project.
The client part is made using Spring.
To put that background i did:
 <body style="background-image: url(login_background.jpg)">
I start the client application and access login page but there's no background image.
When i open the login.html page with my browser there's my background image.
EDIT: Resolved: seems like Spring look for html resources in "static" directory. I moved image there and change url to /login_background.jpg.


text:
Q: Printing unicode characters to stdout in python prints wrong glyphs  I want to print a set of Unicode characters to my command prompt terminal. Even when I enforce the encoding to be "UTF-8" the terminal prints some garbage.
$python -c "import sys; print sys.stdout.write(u'\u2044'.encode('UTF-8'))"
ΓüäNone

$python -c "import sys; print sys.stdout.encoding"
cp437

My default terminal encoding is cp437 and I am trying to override that. The expected output here is Fraction slash ( ⁄ )
http://www.fileformat.info/info/unicode/char/2044/index.htm
The same piece of code works flawlessly in my Mac terminal and it uses UTF-8 as default encoding. Is there a way to display this on Windows as well? The font I use on windows command prompt is consolas.
I want my code to work with any Unicode characters, not just this particular example since the input is a web query result and I have no control over it.

A: Python cannot control the encoding used by your terminal; you'll have to change that somewhere else.
In other words, just because you force python to output UTF-8 encoded text to the terminal, does not mean your terminal will magically start to accept that output as UTF-8 as well.
The Mac OS X terminal has already been configured to work with UTF-8.
On Windows, you can switch the console codepage with the chcp command:
chcp 65001

where 65001 is the Windows codepage for UTF-8. See Unicode characters in Windows command line - how?

A: You have to use a UTF-8 code page (cp65001) to expect UTF-8 encoded text to display.
Python 3.3 claims to support code page 65001 (UTF-8) on Windows.
C:\>chcp 65001
Active code page: 65001

C:\>python
Python 3.3.0rc1 (v3.3.0rc1:8bb5c7bc46ba, Aug 25 2012, 13:50:30) [MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print('\u2044')
⁄

Although it is buggy:
>>> print('\u2044')
⁄

>>> print('\u2044'*8)
⁄⁄⁄⁄⁄⁄⁄⁄
��⁄⁄⁄⁄
⁄⁄
��

>>> print('1\u20442 2\u20443 4\u20445')
1⁄2 2⁄3 4⁄5
⁄5


text:
Q: gridview/adapter issue, adding images to gridview first do I have to make my own adapter class to set images in a gridview? its seams ineligent, requires I make a new class each time I make a gridview.
the problem I have having is that I can't make my image appear in my gridview
package joshpike.hsh.hsh_game;

import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class DisplayActivity extends MainActivity
{
    public class ImageAdapter extends BaseAdapter
    {
        private Context mContext;

        // create a new ImageView for each item referenced by the Adapter
        public View getView(int position, View convertView, ViewGroup parent)
        {
            ImageView imageView;
            if (convertView == null)
            {
                // if it's not recycled, initialize some attributes
                imageView = new ImageView(mContext);
                imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(8, 8, 8, 8);
            }
            else
            {
                imageView = (ImageView) convertView;
            }

           imageView.setImageResource(imageArray[position]);
            return imageView;
        }

        private Integer[] imageArray =
        {
            //currentImageView(0, "xh","bottom",0,0), currentImageView(0, "xh","bottom",1,0)
            R.drawable.level_1_bottom, R.drawable.level_1_top
        };

        @Override
        public int getCount()
        {
            return 0;
        }

        @Override
        public Object getItem(int position)
        {
            return null;
        }

        @Override
        public long getItemId(int position)
        {
            return 0;
        }
    }

    // Inflate the menu; this adds items to the action bar if it is present.
    //makes the options menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.display, menu);
        return true;
    }

    //what happens if you select items from the options menu
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId() )
        {
            case R.id.miniMap:

            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    //called when activity is started for first time either for first time or after destroyed
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.display);

        GridView bottomMapGrid = (GridView)findViewById(R.id.bottomMapGrid);

        bottomMapGrid.setAdapter(new ImageAdapter());

        System.out.println("DisplayActivity onCreate done");
    }

A: currently you are passing Null mContext to ImageView Constructor for Creating it. you need to initialize mContext before using it as :
public class ImageAdapter extends BaseAdapter
    {
        private Context mContext;

        public ImageAdapter(Context mContext){
           this.mContext=mContext;  //<<< initialize here
        }
         //....your code here
    }

and from Activity Create ImageAdapter instance by passing Current Activity Context as :
bottomMapGrid.setAdapter(new ImageAdapter(DisplayActivity.this));

A:  @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.display);
        GridView bottomMapGrid = (GridView)findViewById(R.id.bottomMapGrid);
        bottomMapGrid.setAdapter(new ImageAdapter(this));
        System.out.println("DisplayActivity onCreate done");
    }

And Adapter class Use like this

public class ImageAdapter extends BaseAdapter {
  private Context mContext;

  public ImageAdapter(Context c) {
      mContext = c;
  }

  public int getCount() {
      return mThumbIds.length;
  }

  public Object getItem(int position) {
      return null;
  }

  public long getItemId(int position) {
      return 0;
  }

  // create a new ImageView for each item referenced by the Adapter
  public View getView(int position, View convertView, ViewGroup parent) {
      ImageView imageView;
      if (convertView == null) { // if it's not recycled, initialize some
                                  // attributes
          imageView = new ImageView(mContext);
          imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
          imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
          imageView.setPadding(8, 8, 8, 8);

      } else {
          imageView = (ImageView) convertView;
      }

      imageView.setImageResource(mThumbIds[position]);

      return imageView;
  }

  // references to our images
  private Integer[] mThumbIds = { R.drawable.sample_2, R.drawable.sample_3,
          R.drawable.sample_4, R.drawable.sample_5, R.drawable.sample_6,
          R.drawable.sample_7, R.drawable.sample_0, R.drawable.sample_1,
          R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4,
          R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7,
          R.drawable.sample_0, R.drawable.sample_1, R.drawable.sample_2,
          R.drawable.sample_3, R.drawable.sample_4, R.drawable.sample_5,
          R.drawable.sample_6, R.drawable.sample_7 };
}


text:
Q: Magento2 how to fix upgrade UCT tool errors
1. 36  WARNING Extending from class
'Magento\Framework\App\Action\Action'    that is @deprecated on
version '2.4.5' - See    \Magento\Framework\App\ActionInterface

2. Using class 'Magento\Framework\Registry' that is @deprecated on version '2.4.5'

3Using class 'Magento\Framework\Mail\MessageInterface' that is @deprecated on version '2.4.5' - See \Magento\Framework\Mail\MailMessageInterface

4. Call method 'Magento\CatalogInventory\Api\StockRegistryInterface::getStockItem' that is @deprecated on version '2.4.5'

5. Call method 'Magento\Framework\Api\Search\FilterGroupBuilder::create' that is @deprecated on version '2.4.5'

How to fix the Magento upgrade issues in 2.4.5?


text:
Q: Can I render tables and/or charts 'side by side' in an xls report using DynamicJasper? I'm building a reporting application that's using DynamicJasper for exporting data to xls. The reports are pretty dynamic in the sense that the user is able to customize the queries (one or more) that fetch the data. The resulted data can be rendered as a table or as a chart.
Currently the tables and the charts (pngs) are rendered one after the other, in order, in a 'one column' layout. I would need to add support for a 'two column' layout. For example, to be able to have the tables/charts rendered side by side.
I have to mention that I'm using the DynamicReportBuilder.addConcatenatedReport API. No jasper-reports templates are being used.
Are there any solutions to achieve this?

A: No, it is not supported.
It could maybe achieved with sub-reports, but coding is needed. not easy


text:
Q: How to define an interface in C++? I'm working on a C++ class which provides an abstraction of BSD sockets for networking. I want to define an interface ISocket which is implemented by CSocket and MockSocket (the latter for unit testing). I know that I need to define the methods that I want implementing classes to provide as pure virtual, i.e.
class ISocket {
public:
  virtual int Socket(int domain, int type, int protocol) = 0;
};

What I'm worried about is whether a class of type ISocket can be instantiated. My instincts tell me that any class with at least one pure virtual method is an abstract class (i.e. interface) and cannot be instantiated, but I have a niggling worry in the back of my mind that I need to do something about the auto-generated constructors and destructor that the C++ compiler will provide (Effective C++ is both a gift--when you remember everything you read in it--and a curse--when you don't).
Am I doing this correctly, or is there a best practise for defining interfaces in C++ that I'm not following here?

A: In general, you should declare a virtual destructor; otherwise you'll get into undefined behaviour if you try to invoke delete on a pointer-to-interface.  There are no such issues with constructors.
Oh, and you are correct that it is not possible to instantiate an object of a class with a pure-virtual.

A:
My instincts tell me that any class with at least one pure virtual method is an abstract class (i.e. interface) and cannot be instantiated

Your instincts are correct on this one. Types with at least one pure virtual function can't be instantiated and will generate a compiler error.

A: You are doing correct:An abstract class is a class that is designed to be specifically used as a base class. An abstract class contains at least one pure virtual function. You cannot instantiate a virtual class.

A: You are correct in thinking that any class with a pure virtual method is abstract and cannot be instantiated.
Personally I tend to add a protected destructor to most of my interfaces as in many/most cases I don't want the code that uses the interface to be able to destroy it. Alternatively you should add a public virtual destructor (not pure, with an empty body!) so that the object can be deleted via the interface pointer and the correct destructors will be called.


text:
Q: What is the origin of the phrase - "the world over"? The phrase "the world over" was used in an article from The Economist. I'm curious to know its origin.

A: In short, the preposition "over" can sometime occur after its object in a pseudo-adverbial sense. According to the OED*:

In the above senses [In or on all or many parts of; everywhere (or here and there) on the surface of; throughout.] often placed after its object, esp. when this is modified by all or the like (cf. through prep. 4b). Frequently in the world over.

For the corresponding use in reference to time, as in 'all the year over', in which over may be explained adverbially, see sense A. 19b. Even in the present sense, in phrases such as 'all the world over', it is difficult to separate the preposition from the adverb when the associated verb admits of both transitive and intransitive construction: cf. 'you may search London over (= London from end to end) before you find another like it'.

It's been used since at least Middle English:

Wars Alexander (Ashm.) 18 (MED)   Alexsandire..aȝte euyn as his awyn all the werd ouire.

*Note: non-academic networks might not have access to this link.

A: Sir Walter Raleigh, 1614:

And though the City of Dodona was not then built,or (perchance) not so
  ancient as Dedanim himselfe, yet his Posterity might give it that name
  in the memory of their first 23 Parent, as it hapned all the World
  over.

I find a couple of uses that might be earlier, but I suspect they are more modern commentary.


text:
Q: How to resize image in css so it keeps proportions (and be cropped)?
*

*image should have 100% of width (of its container: container is 250px)

*

*image should have fixed height of 150px

*image should keep propotions (so be cropped)

.pic {
    width:100%;
    height:150px;
}

Problem is : it does not keep propotions. I want the image to be cropped to keep proportions.

A: .pic { width: 250px; }
div { overflow:hidden }

This will get you the cropped look you want.

A: To keep the size of the image you should only use width property.
max-width is a good way to avoid over flatted image.
to crop the image you can use clip like:
 clip: rect(0px,60px,200px,0px);
reference
Find below an example with div cropping with only height and width.

.pic {
    width:150px;

}
.center-cropped {
  width: 400px;
  height: 300px;
  background-position: center center;
  background-repeat: no-repeat;
}
#Resize

#Cropped

A: If you don't mind using bleeding-edge stuff, and don't need IE/EDGE support  support right now, you can use a clip-path. Size the width of the img to 100%, then clip to a polygon the shape you want.
Here I use top left (0 0), top right (100% 0), 150 pixels down from top right (100% 150px) and 150 pixels down from top left (0 150px):

.pic {
  width:100%;
  clip-path: polygon(0 0, 100% 0, 100% 150px, 0 150px);
  -webkit-clip-path: polygon(0 0, 100% 0, 100% 150px, 0 150px);
}

Note that current versions of Chrome and Safari require the -webkit- prefix. More details on browser support here: http://caniuse.com/#feat=css-clip-path
Note also that I added a height to the div - without it, the div sizes itself to the height of the resized image, ignoring the crop.

A: Here my solution, your image and 3 more, nicely packed in a flexbox container. Different sizes => equal to, less and greater than 250x150.
Read the comments in the snippet. I think the code meets all your requirements.
Let me know if it doesn't.

/* generic globals */
html, body                  { box-sizing: border-box; height: 100%; width: 100%;
                              margin: 0; padding: 0; border: 0; cursor: default }
*, *:before, *:after        { box-sizing: inherit }

body {
    display: flex; flex-wrap: wrap; /* flexbox container */
    justify-content: center;        /* center content */
    max-width: 82%; margin: 0 auto; /* center on screen */
    background: #fafafa
}

.pic-wrap { /* thumbnail container */
    width: 250px;                   /* as per requirement */
    min-width: 250px;               /* to be inherited by .pic */
    height: 250px;                  /* just for proof, remove when done */
    background: cornflowerblue;     /* ditto?? */
    margin: 4px
}
.pic { /* thumbnail */
    height: 150px;                  /* as per requirement */
    min-height: 150px;              /* for shorter than 150px pics */
    min-width: inherit;             /* for smaller than 250px pics */
    overflow: hidden                /* chop excess */
}
.fit { /* stretcher */
    min-width: inherit;             /* for smaller pics */
    max-width: 100%                 /* no wider than parent width (250px)*/
}
.byline { /* demo */
    width: 100%;
    padding: 5px;
    text-align: center
}

574x710 crop

574x710 crop-fit

250x200 crop

250x150 match

150x150 original

150x150 scale-fit

100x100 original

100x100 scale-fit


text:
Q: bayesian decision making - comparing expected loss The problem is like this:
Suppose that I am considering which country should I invest on, country A and country B, based on their GDP growth rate $\alpha$.
There are two possible choices for each country:
$d_{1A}$ : Invest in country A  and $d_{2A}$ : Do not invest in country A;
$d_{1B}$ : Invest in country B  and $d_{2B}$ : Do not invest in country B.
The loss functions for both countries are the same:
$$
L(d_1,\alpha)=\left\{\begin{matrix}
0 & \alpha > 0.002\\
4 & \alpha \leqslant  0.002
\end{matrix}\right.
$$ and $$
L(d_2,\alpha)=\left\{\begin{matrix}
1 & \alpha > 0.002\\
0 & \alpha \leqslant  0.002
\end{matrix}\right.
$$
Assume that I can only invest on the country, the one will increase its GDP growth more rapidly.
The $\alpha$ of country A is from posterior $\pi_A(\alpha|x)$;The $\alpha$ of country B is from posterior $\pi_B(\alpha|x)$. $\pi_A(\alpha|x)$ and $\pi_B(\alpha|x)$ are known.
And I also calculate the values of the four following expected loss:
$E\left [L(d_{1A},\alpha)  \right ] = \int_{-\infty }^{0.002}{4\cdot \pi_{A}(\alpha|x)}$ and all other $E\left [L(d_{2A},\alpha)  \right ]$,$E\left [L(d_{1B},\alpha)  \right ]$,$E\left [L(d_{2B},\alpha)  \right ]$.
The issue is that how could I use these four "loss" to make a decision that which country is worth investing on? Because $\alpha_A$ and $\alpha_B$ come from different posteriors, so I cannot compare their loss directly.


text:
Q: Windows cmd line: calling SQL directly does not work, but typing out the entire query does I am trying to call an sql file via cmd line. Using -f the command line freezes and nothing moves/is returned.
psql.exe -U someUsername -h localhost -d someDbName -f "C:\Users\Name\Desktop\selectNames.sql"

However, typing out the entire command and using -c does work completely fine.
psql.exe -U someUsername -h localhost -d someDbName -c "Select names from table123;"

How can I use -f to call the selectNames.sql file in cmd line?


text:
Q: Can a UWP app act as a SignalR server? I saw a code sample that makes a WPF app a SignalR server: https://code.msdn.microsoft.com/Using-SignalR-in-WinForms-f1ec847b
Can I make my UWP app a SignalR server? So that other clients can connect to someone running a UWP app on their device?
I tried installing the SignalR NuGet on to my UWP app, but I got an error:
Install-Package : Microsoft.AspNet.SignalR.Core 2.2.1 is not compatible with UAP,Version=v10.0.

At line:1 char:1
+ Install-Package Microsoft.AspNet.SignalR.SelfHost
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand

I am also thinking about running a SignalR server as a service and then connecting the UWP app to it and connecting other clients to the service. Will that work?

A: SignalR uses server APIs that are not available on UWP, so I doubt this will work, despite I have not looked into it in more detail.
But it is in general not a good idea to do that anyway the way UWP apps work. For example, they get suspended when they are not in the foreground, which should never happen to anything that is a server. You can definitely not rely on it to be available permanently. Is there a specific reason you considered a UWP app for doing this?
So your approach by using a (Windows?) service to host SignalR and connecting the UWP app (and possible other UWP apps) to it is the much better and in fact the correct approach. Another option is to host a web application in IIS or any web server you prefer instead of a Windows service, as handling is a bit easier than self-host a web service inside a Windows service.


text:
Q: GNU inline assembly optimisation I am trying to write a small library for highly optimised x86-64 bit operation code and am fiddling with inline asm.
While testing this particular case has caught my attention:
unsigned long test = 0;
unsigned long bsr;

// bit test and set 39th bit
__asm__ ("btsq\t%1, %0 " : "+rm" (test) : "rJ" (39) );

// bit scan reverse (get most significant bit id)
__asm__ ("bsrq\t%1, %0" : "=r" (bsr) : "rm" (test) );

printf("test = %lu, bsr = %d\n", test, bsr);

compiles and runs fine in both gcc and icc, but when I inspect the assembly I get differences
gcc -S -fverbose-asm -std=gnu99 -O3
movq    $0, -8(%rbp)
## InlineAsm Start
btsq    $39, -8(%rbp)
## InlineAsm End
movq    -8(%rbp), %rax
movq    %rax, -16(%rbp)
## InlineAsm Start
bsrq    -16(%rbp), %rdx
## InlineAsm End
movq    -8(%rbp), %rsi
leaq    L_.str(%rip), %rdi
xorb    %al, %al
callq   _printf

I am wondering why so complicated? I am writing high performance code in which the number of instructions is critical. I am especially wondering why gcc makes a copy of my variable test before passing it to the second inline asm?
Same code compiled with icc gives far better results:
    xorl      %esi, %esi                                    # test = 0
    movl      $.L_2__STRING.0, %edi                         # has something to do with printf
    orl       $32832, (%rsp)                                # part of function initiation
    xorl      %eax, %eax                                    # has something to do with printf
    ldmxcsr   (%rsp)                                        # part of function initiation
    btsq      $39, %rsi                                     #106.0
    bsrq      %rsi, %rdx                                    #109.0
    call      printf                                        #111.2

despite the fact that gcc decides to keep my variables on the stack rather then in registers, what I do not understand is why make a copy of test before passing it to the second asm?
If I put test in as an input/output variable in the second asm
__asm__ ("bsrq\t%1, %0" : "=r" (bsr) , "+rm" (test) );
then those lines disappear.
movq    $0, -8(%rbp)
## InlineAsm Start
btsq    $39, -8(%rbp)
## InlineAsm End
## InlineAsm Start
bsrq    -8(%rbp), %rdx
## InlineAsm End
movq    -8(%rbp), %rsi
leaq    L_.str(%rip), %rdi
xorb    %al, %al
callq   _printf

Is this gcc screwed up optimisation or am I missing some vital compiler switches? I do have icc for my production system, but if I decide to distribute the source code at some point then it will have to be able to compile with gcc too.
compilers used:
gcc version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.1.00)
icc Version 12.0.2

A: I've tried your example on Linux like this (making it "evil" by forcing a stack ref/loc for test through using &test in the printf:):#include <stdio.h>
int main(int argc, char **argv)
{
    unsigned long test = 0;
    unsigned long bsr;
// bit test and set 39th bit
    asm ("btsq\t%1, %0 " : "+rm" (test) : "rJ" (39) );
// bit scan reverse (get most significant bit id)
    asm ("bsrq\t%1, %0" : "=r" (bsr) : "rm" (test) );
    printf("test = %lu, bsr = %d, &test = %p\n", test, bsr, &test);
    return 0;
}
and compiled it with various versions of gcc -O3 ... to the following results:

code generated                                                     gcc version
================================================================================
  400630:       48 83 ec 18             sub    $0x18,%rsp          4.7.2,
  400634:       31 c0                   xor    %eax,%eax           4.6.2,
  400636:       bf 50 07 40 00          mov    $0x400750,%edi      4.4.6
  40063b:       48 8d 4c 24 08          lea    0x8(%rsp),%rcx
  400640:       48 0f ba e8 27          bts    $0x27,%rax
  400645:       48 89 44 24 08          mov    %rax,0x8(%rsp)
  40064a:       48 89 c6                mov    %rax,%rsi
  40064d:       48 0f bd d0             bsr    %rax,%rdx
  400651:       31 c0                   xor    %eax,%eax
  400653:       e8 68 fe ff ff          callq  4004c0
[ ... ]
---------------------------------------------------------------------------------
  4004f0:       48 83 ec 18             sub    $0x18,%rsp          4.1
  4004f4:       31 c0                   xor    %eax,%eax
  4004f6:       bf 28 06 40 00          mov    $0x400628,%edi
  4004fb:       48 8d 4c 24 10          lea    0x10(%rsp),%rcx
  400500:       48 c7 44 24 10 00 00 00 00      movq   $0x0,0x10(%rsp)
  400509:       48 0f ba e8 27          bts    $0x27,%rax
  40050e:       48 89 44 24 10          mov    %rax,0x10(%rsp)
  400513:       48 89 c6                mov    %rax,%rsi
  400516:       48 0f bd d0             bsr    %rax,%rdx
  40051a:       31 c0                   xor    %eax,%eax
  40051c:       e8 c7 fe ff ff          callq  4003e8
[ ... ]
---------------------------------------------------------------------------------
  400500:       48 83 ec 08             sub    $0x8,%rsp           3.4.5
  400504:       bf 30 06 40 00          mov    $0x400630,%edi
  400509:       31 c0                   xor    %eax,%eax
  40050b:       48 c7 04 24 00 00 00 00         movq   $0x0,(%rsp)
  400513:       48 89 e1                mov    %rsp,%rcx
  400516:       48 0f ba 2c 24 27       btsq   $0x27,(%rsp)
  40051c:       48 8b 34 24             mov    (%rsp),%rsi
  400520:       48 0f bd 14 24          bsr    (%rsp),%rdx
  400525:       e8 fe fe ff ff          callq  400428
[ ... ]
---------------------------------------------------------------------------------
  4004e0:       48 83 ec 08             sub    $0x8,%rsp           3.2.3
  4004e4:       bf 10 06 40 00          mov    $0x400610,%edi
  4004e9:       31 c0                   xor    %eax,%eax
  4004eb:       48 c7 04 24 00 00 00 00         movq   $0x0,(%rsp)
  4004f3:       48 0f ba 2c 24 27       btsq   $0x27,(%rsp)
  4004f9:       48 8b 34 24             mov    (%rsp),%rsi
  4004fd:       48 89 e1                mov    %rsp,%rcx
  400500:       48 0f bd 14 24          bsr    (%rsp),%rdx
  400505:       e8 ee fe ff ff          callq  4003f8
[ ... ]

and while there's a significant difference in the created code (including whether the bsr acceesses test as register or memory), none of the tested revs recreate the assembly that you've shown. I'd suspect a bug in the 4.2.x version you used on MacOSX, but then I don't have either your testcase nor that specific compiler version available.
Edit: The code above is obviously different in the sense that it forces test into the stack; if that is not done, then all "plain" gcc versions I've tested do a direct pair bts $39, %rsi / bsr %rsi, %rdx.
I have found, though, that clang creates different code there: 140:   50                      push   %rax
 141:   48 c7 04 24 00 00 00 00         movq   $0x0,(%rsp)
 149:   31 f6                   xor    %esi,%esi
 14b:   48 0f ba ee 27          bts    $0x27,%rsi
 150:   48 89 34 24             mov    %rsi,(%rsp)
 154:   48 0f bd d6             bsr    %rsi,%rdx
 158:   bf 00 00 00 00          mov    $0x0,%edi
 15d:   30 c0                   xor    %al,%al
 15f:   e8 00 00 00 00          callq  printf@plt>so the difference seems to be indeed between the code generators of clang/llvm and "gcc proper".


text:
Q: How can I make Tikz pins appear after click \documentclass[xcolor={table},t]{beamer}

\usepackage{pgfplots}
\usepgfplotslibrary{fillbetween}
\usepackage{tikz}

\usetikzlibrary{decorations.pathreplacing,angles,quotes,calligraphy,plotmarks,overlay-beamer-styles}

\tikzset{
    invisible/.style={opacity=0},
    visible on/.style={alt={#1{}{invisible}}},
    alt/.code args={<#1>#2#3}{%
      \alt<#1>{\pgfkeysalso{#2}}{\pgfkeysalso{#3}} % \pgfkeysalso doesn't change the path
    },
  }

\begin{document}

\begin{frame}{Test}

\begin{figure}

\begin{center}

\begin{tikzpicture}

\begin{axis}[
legend style={at={(1.3,0)},draw=none,anchor= south, legend columns=1, font=\tiny,text width=1in, minimum height=0.2in},
ymin=0,ymax=1000,
xlabel = Strain ($\epsilon_{e}$ and $\epsilon_{t}$),
every axis x label/.style=
    {at={(ticklabel cs:0.5)},anchor=near ticklabel},
ylabel = Stress ($F_{t}$ and $F_{e}$),
every axis y label/.style=
    {at={(ticklabel cs:0.5)},rotate=90,anchor=near ticklabel},
xmin=0, xmax=0.4,
xtick={0,0.05,...,0.4},,
x tick label style={rotate=45},
width=0.75\linewidth,
height=0.58\linewidth,
font=\tiny,
axis x line=bottom,
axis y line=left,
]
\begin{scope}[
  every pin edge/.style={<-,>=latex, mark size=3pt},
  every pin/.append style={font=\tiny}
]

\addplot [black,mark = *,mark size=3pt,mark options={fill=black}, only marks] coordinates {(0.012,439) (0.182322,614.4) (0.2,512) (0.29,350)};

    \node [coordinate,pin={[visible on=<2->,pin distance=0.35 in,pin edge={gray,thick}]90:{(5) $F_{t}=F_{ut}*[w*\frac{\epsilon_{t}}{\epsilon_{ut}}^n+(1-w)*(1+\epsilon_{t}-\epsilon_{ut})]$} } ]
        at (axis cs:0.239017,638.115116) {};

    \node[coordinate,pin={[pin distance=0.25 in,pin edge={gray,thick}]90:{(4) $F_{t}=F_{ut}*(\frac{\epsilon_{t}}{\epsilon_{ut}})^n$} } ]
        at (axis cs:0.095,565) {};

\node[inner sep=0pt] (whitehead) at (axis cs:0.03,400)
{\tiny{A}};

\node[inner sep=0pt] (whitehead) at (axis cs:0.18,450)
{\tiny{B}};

%\node[inner sep=0pt] (whitehead) at (axis cs:0.33,350)
%{\tiny{C}};

\node[inner sep=0pt] (whitehead) at (axis cs:0.182322,680)
{\tiny{B'}};

\node[inner sep=0pt] (whitehead) at (axis cs:0.1,160)
{\tiny{Hardening Region}};

\addplot [<->, black, dashed, thick] coordinates {(0.012,439)  (0.012,0)};
\addplot [<->, black,dashed, thick] coordinates {(0.2,512)  (0.2,0)};
\addplot [<->, black, thick] coordinates {(0.012,100)  (0.2,100)};

\addplot [<->, black, dashed, thick] coordinates {(0.29,350)  (0.29,0)};
\addplot [<->, black, thick] coordinates {(0.2,100)  (0.29,100)};

\node[inner sep=0pt] (whitehead) at (axis cs:0.245,160)
{\tiny{Necking}};

    %\node[inner sep=0pt] (whitehead) at (axis cs:0.245,180)
%{\tiny$\begin{aligned} Necking, and \\ Fracture \end{aligned}$};

\node[inner sep=0pt] (whitehead) at (axis cs:0.31,350)
{\tiny{C}};

\end{scope}
\end{axis}
\end{tikzpicture}
\end{center}
\caption{True Stress Strain Match}
\label{Tension_Test}
\end{figure}
\end{frame}
\end{document}

A: TikZ nodes are overlay aware. This means you can delay the complete node, including the text and the pin, with \node<2->
Some other comments about your code

*

*figures are centred by default in beamer. No need to warp them in a center environment. This will only mess with the vertical spacing

*you don't need to define the visible on etc. styles yourself, that's what you load the overlay-beamer-styles library for

*the frame environment is missing. That's a crucial part of beamer. Never use beamer without a frame!

\documentclass[xcolor={table},t]{beamer}

\usepackage{pgfplots}
\usepgfplotslibrary{fillbetween}
\usepackage{tikz}

    \usetikzlibrary{decorations.pathreplacing,angles,quotes,calligraphy,plotmarks,overlay-beamer-styles}

\begin{document}
\begin{frame}
\begin{figure}

%\begin{center}

\begin{tikzpicture}

\begin{axis}[
    %x label style={at=(.50,-0.1)},
    %x label/.style={at={(ticklabel cs:0.5)},anchor=near ticklabel},
    %y label style={at={(current axis.above origin)},anchor=west},
    legend style={at={(1.3,0)},draw=none,anchor= south, legend columns=1, font=\tiny,text width=1in, minimum height=0.2in},
    ymin=0,ymax=1000,
    xlabel = Strain ($\epsilon_{e}$ and $\epsilon_{t}$),
    every axis x label/.style=
        {at={(ticklabel cs:0.5)},anchor=near ticklabel},
    ylabel = Stress ($F_{t}$ and $F_{e}$),
    every axis y label/.style=
        {at={(ticklabel cs:0.5)},rotate=90,anchor=near ticklabel},
    xmin=0, xmax=0.4,
    xtick={0,0.05,...,0.4},,
    x tick label style={rotate=45},
    width=0.75\linewidth,
    height=0.58\linewidth,
    font=\tiny,
    axis x line=bottom,
    axis y line=left,
]
\begin{scope}[
      every pin edge/.style={<-,>=latex, mark size=3pt},
      every pin/.append style={font=\tiny}
    ]

        \node<2-> [coordinate,pin={[pin distance=0.35 in,pin edge={gray,thick}]90:{(5) $F_{t}=F_{ut}*[w*\frac{\epsilon_{t}}{\epsilon_{ut}}^n+(1-w)*(1+\epsilon_{t}-\epsilon_{ut})]$} } ] at (axis cs:0.239017,638.115116) {};

\end{scope}
\end{axis}
\end{tikzpicture}
%\end{center}
\caption{True Stress Strain Match}
\label{Tension_Test}
\end{figure}
\end{frame}
\end{document}

A: I have solved this issue:
visible on=<2-> simply needed to be added to the pin options as follows:
    \node [coordinate,pin={[visible on=<2->,pin distance=0.35 in,pin edge={visible on=<2->,gray,thick}]90:{(5) $F_{t}=F_{ut}*[w*\frac{\epsilon_{t}}{\epsilon_{ut}}^n+(1-w)*(1+\epsilon_{t}-\epsilon_{ut})]$} } ]
        at (axis cs:0.239017,638.115116) {};

Full code:
\documentclass[xcolor={table},t]{beamer}

\usepackage{pgfplots}
\usepgfplotslibrary{fillbetween}
\usepackage{tikz}

\usetikzlibrary{decorations.pathreplacing,angles,quotes,calligraphy,plotmarks,overlay-beamer-styles}

\tikzset{
    invisible/.style={opacity=0},
    visible on/.style={alt={#1{}{invisible}}},
    alt/.code args={<#1>#2#3}{%
      \alt<#1>{\pgfkeysalso{#2}}{\pgfkeysalso{#3}} % \pgfkeysalso doesn't change the path
    },
  }

\begin{document}

\begin{frame}{Test}

\begin{figure}

\begin{center}

\begin{tikzpicture}

\begin{axis}[
    legend style={at={(1.3,0)},draw=none,anchor= south, legend columns=1, font=\tiny,text width=1in, minimum height=0.2in},
    ymin=0,ymax=1000,
    xlabel = Strain ($\epsilon_{e}$ and $\epsilon_{t}$),
    every axis x label/.style=
        {at={(ticklabel cs:0.5)},anchor=near ticklabel},
    ylabel = Stress ($F_{t}$ and $F_{e}$),
    every axis y label/.style=
        {at={(ticklabel cs:0.5)},rotate=90,anchor=near ticklabel},
    xmin=0, xmax=0.4,
    xtick={0,0.05,...,0.4},,
x tick label style={rotate=45},
width=0.75\linewidth,
height=0.58\linewidth,
font=\tiny,
axis x line=bottom,
axis y line=left,
]
\begin{scope}[
      every pin edge/.style={<-,>=latex, mark size=3pt},
      every pin/.append style={font=\tiny}
    ]

\addplot [black,mark = *,mark size=3pt,mark options={fill=black}, only marks] coordinates {(0.012,439) (0.182322,614.4) (0.2,512) (0.29,350)};

%\node[inner sep=0pt] (whitehead) at (axis cs:0.5,250)
    %{\tiny{(1) $\sigma_T=\ln*(1+\epsilon_{eng})$}};

    %\node[inner sep=0pt] (whitehead) at (axis cs:0.12,650)
    %{\tiny{Eq. (1), (2)}};

        \node [coordinate,pin={[visible on=<2->,pin distance=0.35 in,pin edge={visible on=<2->,gray,thick}]90:{(5) $F_{t}=F_{ut}*[w*\frac{\epsilon_{t}}{\epsilon_{ut}}^n+(1-w)*(1+\epsilon_{t}-\epsilon_{ut})]$} } ]
            at (axis cs:0.239017,638.115116) {};

        \node[coordinate,pin={[pin distance=0.25 in,pin edge={gray,thick}]90:{(4) $F_{t}=F_{ut}*(\frac{\epsilon_{t}}{\epsilon_{ut}})^n$} } ]
            at (axis cs:0.095,565) {};

    \node[inner sep=0pt] (whitehead) at (axis cs:0.03,400)
    {\tiny{A}};

    \node[inner sep=0pt] (whitehead) at (axis cs:0.18,450)
    {\tiny{B}};

    %\node[inner sep=0pt] (whitehead) at (axis cs:0.33,350)
    %{\tiny{C}};

    \node[inner sep=0pt] (whitehead) at (axis cs:0.182322,680)
    {\tiny{B'}};

    \node[inner sep=0pt] (whitehead) at (axis cs:0.1,160)
    {\tiny{Hardening Region}};

    \addplot [<->, black, dashed, thick] coordinates {(0.012,439)  (0.012,0)};
    \addplot [<->, black,dashed, thick] coordinates {(0.2,512)  (0.2,0)};
    \addplot [<->, black, thick] coordinates {(0.012,100)  (0.2,100)};

    \addplot [<->, black, dashed, thick] coordinates {(0.29,350)  (0.29,0)};
    \addplot [<->, black, thick] coordinates {(0.2,100)  (0.29,100)};

    \node[inner sep=0pt] (whitehead) at (axis cs:0.245,160)
    {\tiny{Necking}};

        %\node[inner sep=0pt] (whitehead) at (axis cs:0.245,180)
    %{\tiny$\begin{aligned} Necking, and \\ Fracture \end{aligned}$};

    \node[inner sep=0pt] (whitehead) at (axis cs:0.31,350)
    {\tiny{C}};

\end{scope}
\end{axis}
\end{tikzpicture}
\end{center}
\caption{True Stress Strain Match}
\label{Tension_Test}
\end{figure}
\end{frame}
\end{document}


text:
Q: MySQL View with Union Error - "View's SELECT contains a subquery in the FROM clause" I'm getting this error and I don't know how to resolve.  It works fine as a normal query, but I'd like for it to be a view:
CREATE  OR REPLACE VIEW `myTable`.`vw_videos` AS

SELECT DISTINCT theVideos.videoID FROM
    (SELECT video_youtube_id AS videoID FROM videos
    UNION
    SELECT entry_video AS videoID FROM vw_entry_info) AS theVideos
WHERE videoID != "";

I keep getting "View's SELECT contains a subquery in the FROM clause".  Why is this?

A: I think you've just stumbled on: http://bugs.mysql.com/bug.php?id=16757
It's a very annoying "feature" of MySQL which you can work-around by creating separate subviews and referencing them in your latter query.


text:
Q: Simple curiosity about scene graph conception I'm writing a simple 3D engine using OpenGL. I've already implemented a simple scene graph with the following pattern :
ISceneNode
    IMeshSceneNode
         StaticMeshSceneNode
    ICameraSceneNode
         StaticCameraSceneNode
         TrackBallCameraSceneNode
    ILightSceneNode
         PointLightSceneNode

But I wonder if a 'Renderer' (the class which implement the shader program) could be a scene node too (extract the rendering code from MeshSceneNode to the RenderSceneNode). For me it could be a right choice because if I must render several meshes (for example 42 meshes) using the same vertex and fragment shaders it should be usefull to bind and unbind the shader program just one time and not 42 times!
So what do you think about the following schemas :
The first one represent my current conception (for a sake of simplicity I don't represent the 'Light' and 'Camera' scene nodes).

So, here, if I want to render my 3 meshes (with 3 shader programs using the sames shaders) I will bind and unbind 3 times my shader programs for each frame (in the 'render' method of each Mesh node).
Here's the other conception :

As you can see above, this time I'll bind a unique shader program in the render node for all the children nodes. So it could be faster.
What do you think about my idea ?

A: Another way to say what Anton said: if you want to optimize state changes, you don't want nodes in your scene graph to make any draw calls directly. Delegate that to your renderer, which will then be able to build an intermediate representation based on which it can reorder OpenGL calls for optimization.
Defining a clean API for your renderer will also allow you to separate your concerns:

*

*what to draw, vs.

*how to draw it.

Then you could even use double dispatch (like an evolved Visitor Pattern) to make things more generic.


text:
Q: How to collapse and expand a ListItem.Standard? For the app I am developing I would like to have a list with sections that I can collapse or expand. The item in the sections can be clicked and open a DefaultSheet.
So, for example in the "Ubuntu UI toolkit Gallery" in the List Items tab, in "GroupedList", I would like to be able to click on "fruit" and collapse the list, and click again on it and expand the list.
How can I do that? Is that possible? (It is for ListItem.ValueSelector so it might be possible)
Thank you for your help.

A: I think what you need is the ListItem.Expandable SDK component. It was added in the 14.10 SDK Framework which is at the time of writing this answer is a development framework. It provides the capability to collapse and expand the listitem on clicking it.
I would recommend you read the API documentation here to learn more about the component and see how to use it in your application.
Code Sample
Here is a small code sample that creates such a component,
import QtQuick 2.0
import Ubuntu.Components 1.1
import Ubuntu.Components.ListItems 1.0 as ListItem

MainView {
    id: mainView

    width: units.gu(50)
    height: units.gu(75)

    Page {
        title: "Sample Expandable App"

        Column {
            anchors { left: parent.left; right: parent.right }
            clip: true

            Repeater {
                model: 2
                ListItem.Expandable {
                    id: expandingItem1
                    expandedHeight: contentCol1.height + units.gu(1)

                    onClicked: {
                        expanded = !expanded;
                    }

                    Column {
                        id: contentCol1
                        anchors { left: parent.left; right: parent.right }
                        Item {
                            anchors { left: parent.left; right: parent.right}
                            height: expandingItem1.collapsedHeight
                            Label {
                                anchors { left: parent.left; right: parent.right; verticalCenter: parent.verticalCenter}
                                text: "Item " + index
                            }
                        }

                        UbuntuShape {
                            anchors { left: parent.left; right: parent.right }
                            height: index % 2 == 0 ? units.gu(6) : units.gu(18)
                            color: "khaki"
                        }
                    }
                }
            }
        }
    }
}

Clock App Giff
I have attached a gif below where we use in the clock app to set the alarm duration.


text:
Q: Fedora 14 - hulu player does not load in firefox I have a fresh install of fedora 14 (64 bit) on my laptop. I installed the new 64bit flash using instructions from this website. Flash seems to work, I can load videos on youtube and they play just fine. In general, flash seems to work without a problem wherever I go. What I can't do is get the hulu player to load in firefox. It loads fine in Epiphany.
I couldn't get it to load with the standard 32 bit adobe flash either. If I switch to using Gnash, still nothing.
I am running Firefox version 3.6.4. I have adblock plus installed, but it is disabled for hulu.com
What settings do I need to have enabled or disabled for hulu player to load in firefox? Any other suggestions? anything I'm missing?


text:
Q: Set nextVisibleTime in Azure Webjobs SDK I'm using Azure Webjobs to process messages from a queue.
I saw that the Webjobs SDK processes any failed message again after 10 minutes, and it if fails 5 times it moves it to the poison queue (1).
Also I can see the nextVisibleTime of the message in the queue, that is 10 minutes after the insertionTime (2).
I want to use the AzureSDK error handling of the messages but I cannot wait 10 minutes for the message to be processed again.
Is there any way I can set this nextVisibleTime to a few seconds?
Create a .NET WebJob in Azure App Service

If the method fails before completing, the queue message is not deleted; after a 10-minute lease expires, the message is released to be picked up again and processed.

How to use Azure queue storage with the WebJobs SDK
public static void WriteLog([QueueTrigger("logqueue")] string logMessage,
    DateTimeOffset expirationTime,
    DateTimeOffset insertionTime,
    DateTimeOffset nextVisibleTime,

Note: There are similar questions here in StackOverflow but with no answer:

*

*QueueTrigger Attribute Visibility Timeout

*Azure WebJob QueueTrigger Retry Policy

A: In the latest v1.1.0 release, you can now control the visibility timeout by registering your own custom QueueProcessor instances via JobHostConfiguration.Queues.QueueProcessorFactory. This allows you to control advanced message processing behavior globally or per queue/function.
For example, to set the visibility for failed messages, you can override ReleaseMessageAsync as follows:
protected override async Task ReleaseMessageAsync(CloudQueueMessage message, FunctionResult result, TimeSpan visibilityTimeout, CancellationToken cancellationToken)
{
    // demonstrates how visibility timeout for failed messages can be customized
    // the logic here could implement exponential backoff, etc.
    visibilityTimeout = TimeSpan.FromSeconds(message.DequeueCount);

    await base.ReleaseMessageAsync(message, result, visibilityTimeout, cancellationToken);
}

More details can be found in the release notes here.

A: If there is an exception while processing your function, the SDK will put the message back in the queue instantly and the message will be reprocessed. Are you not seeing this behavior?


text:
Q: How to import vault keys and file content of blob into azure functions using logic app I am trying to create logic app in which I am fetching keys from vault and file content from blob into Logic app. Now I want to fetch keys and file content in azure java function inside logic app but I am unable to do so.
I fetched the file content and keys into logic app. Now creating azure java function in logic app to consume the same. Not able to fetch them. Please guide.

A: Hi I'm Wayne Wang from the Microsoft for Founders Hub team!
From my understanding of your question, it seems you possiblely want to do one of the following:

*

*Pass the content and keys to Azure Function written in Java

*Give hint to Azure Function written in Java, let it fetch the keys and contents itself.

For the first possibility, you can implement with as http Post with json or Put with file, but I would not suggest you do it that way.

*

*secrets should not passed as parameters between services

*Post from/to serverless services usually have a size limitation of 100MB (after base64)

For the second one, we have an article about visiting Key Vault using Java console. it also applied to java functions.
https://learn.microsoft.com/en-us/azure/key-vault/secrets/quick-create-java?tabs=azure-cli
and you can also use storage account to deliver file contents between services
https://learn.microsoft.com/en-us/samples/azure-samples/azure-sdk-for-java-storage-blob-upload-download/upload-download-blobs-java/
Communication from Logic Apps to a Function, you can use a http call, or you can use an async message though "Service Bus"  "Storage Queue" "Event Hub" and other stuff. it is a more open topic.
Hope these ideas can help


text:
Q: Фатальная ошибка SDL2
..Проблема чисто техническая

Месяца два назад всё работало, я следовал инструкции первой и второй.
Сейчас, после установки ghc-9.2.5, при добавлении sdl2 в package.yaml > dependencies проекта вылезает длиннющий адрес, и такой вот тип ошибки:
Error: [S-7282]
    Stack failed to execute the build plan.
    While executing the build plan, Stack encountered the following errors:
    <stderr>: commitAndReleaseBuffer: invalid argument (invalid character)

{-PS. Я понимаю что все ошибки возникают из-за элементарных проблем, я точно где-то ступил, надежд в этом году не питаю, но в следующем бросать пройденный путь сквозь рукава не собираюсь. Но я точно помню, что похожая ошибка возникала и при её переустановках-}

A: Проблема оказалась очень забавной, её решение лежало в ручном определении предыдущего, и установленного по умолчанию [в C:\sr\global-project\stack.yaml] lts в stack.yaml > resolver каждого нужного проекта

ох уж этот ghc и lts, голову мне морочат


text:
Q: Firebase realtime database: how can I retrieve 10 records around a specific key after ordered by value? I created a simple leaderboard in my Firebase Realtime Database, using Unity:

Keys correspond to the user name and the values correspond to the user score.
I want to

*

*Retrieve first 20 records

*Retrieve the 5 records around a given user name (upper 2, itself and the lower 2) when ordered by the scores.

I manage to retrieve top 100 scores by the following query:
FirebaseDatabase.DefaultInstance.GetReference (LEADERBOARD_TABLE_CAPTION).Child (leaderboardName).OrderByValue ().LimitToLast (20)

I use LimitToLast because the ordering is done in ascending order.
The result looks like:
1.test31,987
2.test85,975
3.test67,943
4.test94,941
5.test95,940
6.test71,929
7.test16,917
8.test64,911
9.test100,906
10.test42,870
11.test54,863
12.test88,861
13.test5,859
14.test97,844
15.test46,836
16.test26,765
17.test52,764
18.test4,763
19.test70,756
20.test51,742

Then for the second task, I want to retrieve scores around a user name, let say "test100". I want to retrieve such a result (note that test100 does not need to be in top 20):
 7.test16,917
 8.test64,911
 9.test100,906
 10.test42,870
 11.test54,863

I want to run such a query that start at test100 and limit to first 3, then end at test100 limit to last 3, but in ordered by value fashion. There is no such function (I could not manage to find). StartAt and EndAt are always based on the value , but I cannot center my query based on the score 906 (there may be lots of user have score 906).
Even if there is only one 906 still my solution does not work. When I center and get first 2 and last 2 scores around 906, I do not know the ranking of the centering value and I cannot show what is the current ranking of my current user. The most inefficient solution is to retrieve all the scores ordered by value and search for the current user but it is not a solution when I have 10.000 records.
How can I do this?
Best regards,
fercis

A: Firebase Database queries can retrieve items starting at a specific key/value or items ending at a specific key/value. To retrieve the 5 items before a specific key and the five items after a specific key, you will need to use two queries.
leaderboard = FirebaseDatabase.DefaultInstance.GetReference(LEADERBOARD_TABLE_CAPTION).Child(leaderboardName);
var anchorItemKey = "...";
Query itemsBefore = leaderboard.orderByKey().endAt(anchorItemKey).limitToLast(6);
Query itemsAfter = leaderboard.orderByKey().startAt(anchorItemKey).limitToFirst(6);

Each query above will retrieve (up to) 6 items, which is one more than you need. The reason for this is that the query will also retrieve the anchor item itself.
Update: If you want to retrieve the items based on score, around a specific key, you'd use the startAt() method with two parameters:
leaderboard = FirebaseDatabase.DefaultInstance.GetReference(LEADERBOARD_TABLE_CAPTION).Child(leaderboardName);
var anchorItemKey = "...";
var scoreOfAnchorItem = ...;
Query itemsBefore = leaderboard.orderByChild("score").endAt(scoreOfAnchorItem, anchorItemKey).limitToLast(6);
Query itemsAfter = leaderboard.orderByChild("score").startAt(scoreOfAnchorItem, anchorItemKey).limitToFirst(6);

With this variant, Firebase will order the items by score and then return the items around the anchor item's key.


text:
Q: Pandas finding duplicated elements I am running into a weird situation:
df.userid.size # output: 11852
df.userid.nunique() # output: 11851

df[df.duplicated(['userid']) # outputs nothing

Any idea on how I can find the duplicated userid?

A: Most probably you have one NaN in that column.
Demo:
In [24]: df
Out[24]:
     a
0  1.0
1  NaN

In [25]: df.a.nunique()
Out[25]: 1

In [26]: df.a.size
Out[26]: 2

In [27]: df.duplicated('a')
Out[27]:
0    False
1    False
dtype: bool


text:
Q: Windows Scripting Host HTML Application - event on exit? I've created a Windows Scripting Host HTML Application. Is there a way to fire an event when/before the user exits the program? I want to spawn an "Are you sure you want to quit?" prompt.
I got the onbeforeunload event to fire the following script:
window.onbeforeunload = function(e) {
    return 'Dialog text here.';
};

The prompt displays as it should. However the program exits regardless of whether the user clicks OK or Cancel. How do I prevent the program from closing?


text:
Q: Scheme - How do you apply data structures to the combining of 2 Roman Numeral objects (letters & values) to produce a 2-character Roman Numeral? I'm attempting to solve the following problem:

Write a function called form-rn that consumes two Roman-Numeral objects (digit1 and digit2) and produces the two-character Roman-Numeral represented by the values of digit1 and digit2 read from left to right. The string values of digit1 and digit2 must be a single letter (one of I, V, X, L, C, D, or M).
For example:
(form-rn (make-Roman-numeral "C" 100) (make-Roman-numeral "C" 100))

produces (make-Roman-numeral "CC" 200), and
(form-rn (make-Roman-numeral "X" 10) (make-Roman-numeral "L" 50))

produces (make-Roman-numeral "XL" 40).

So far I tried a few things:
(define II (make-Roman-numeral "II" 2))
(define IV (make-Roman-numeral "IV" 4))

This was in an attempt to produce Roman Numeral combinations but I realized that this probably isn't the approach I should be taking.
(make-Roman-numeral 'I 1)
(make-Roman-numeral 'V 5)

I thought maybe if I had to define each Roman numeral separately but its not supposed to be a single character like "I" its supposed to be a combo like "IV"
(define (form-rn digit1 digit2)
  (cond
    [(> digit1 digit2) (+ (Roman-numeral-value digit1) (Roman-numeral-value digit2))]))

I considered making conditions because the question says that if the first symbol is larger than the other, then the two symbols add up but if the second symbol is larger than the first, then the value of the larger symbol subtracts the value of the smaller symbol.

A: You're definitely on the right track with your last attempt! A couple of notes

*

*The question asks you to return a Roman-numeral object from your form-rn function, so you'll need to call make-Roman-numeral from inside it.

*You need to handle the cases in which digit1 is greater than digit2 and the inverse separately.

In order to add the letters together, we can just use string-append. To find the new value, then we can use cond to check which digit is greater. Then, we just need to take the two new values we've calculated and combine them into a new Roman-numeral object.
You can do this like so:
(define (form-rn digit1 digit2)
  (define new-letters (string-append (Roman-numeral-letters digit1) (Roman-numeral-letters digit2)))
  (define new-values
    (let ([value1 (Roman-numeral-value digit1)]
          [value2 (Roman-numeral-value digit2)])
      (cond
        [(> value1 value2)
         (+ value1 value2)]
        [else
         (- value2 value1)])))
  (make-Roman-numeral new-letters new-values))


text:
Q: how to find the average of sales per city? Let's say we have a dataset like this:
 id        sales    city
 12        10000    New york
 13        15000    New york
 14        20000    Tokyo
 15        25000    Tokyo
 16        10000    Istanbul
 17        12000    Istanbul

How I can find the average sales per city?
Using this, I want to create a horizontal bar graph.

A: print(df.groupby('city')['sales'].mean())


text:
Q: Index and match in excel I have two sheets, I want to retrive data from the first sheet according to 3 conditions: Month in row1, conditions in row 2, and operations from column B. Each shown in the table: each location have the same two operations.

In sheet 2, I want to select the month from the list (Data validation, the months are linked from the table) then the data of that month only will be shown. I used the following code:
=INDEX(Sheet1!B1:K6,MATCH((B1= Sheet1!C1:K1)*(E2=Sheet1!C2:K2),0),MATCH(B3,Sheet1!B1:B6,0))

As seen in the picture:

But I get an error that the data is not found even though I am sure it's there. Please guide me what did I do wrong?
UPDATE:
I used another code (This is C3):
=INDEX(Sheet1!C3:K3,MATCH(B1,Sheet1!C1:K1,0),MATCH(C2,Sheet1!C2:K2,0))

It worked, I only change te data range in each cell and the option (H, W, M with month). The weird thing is that it only works for January!!

But when I select Feb or March I get:

I feel confused what is the reason and how to fix it?

A: =INDEX(Sheet1!$A:$K,ROW(),MATCH($D$1,Sheet1!$1:$1,0)+COLUMN()-3)

How it works:
MATCH($D$1,Sheet1!$1:$1,0)

finds the column of the selected month in Sheet1
+COLUMN()-3

offsets from that column to get H, W or M column
ROW()

gives same rows in Sheet1 and destination sheet
INDEX(...)

returns the result

A: Do in Sheet2 C3 :
=INDEX(OFFSET(Sheet1!$C$3:$F$4,MATCH(OFFSET(Sheet2!$A3,IF(Sheet2!$A3="",-1,0),0),Sheet1!$A$3:$A$8,0)-1,MATCH(Sheet2!$B$1,Sheet1!$C$1:$N$1,0)-1),MATCH(Sheet2!$B3,Sheet1!$B$3:$B$4,0),MATCH(C$2,Sheet1!$C$2:$E$2,0))

Idea : use offset to 'determine' the area for OP,CR & H,W,M search. put an If+offset condition to 'shift' the sheet2,columnA reference if it is blank.
Please share if it works/not. ( :


text:
Q: grep or writing for function which is better I'm writing a program to copy from one drive to another drive for this i'm using
fdisk -l > fdiskOutput.txt to check for whether device are present or not.
Then i'm writing the contents of the file into a buffer. And using strstr i'm checking for
entries like /dev/sda2 , /dev/sdb1 and performing the copy operation.
Code is given below:
#include<stdio.h>
main()
{
    char * buff;
    int fileLength=0;
    system("fdisk -l > /fdiskinfo.txt");
    fileLength=GetFileLength("/fdiskinfo.txt");
    buff = malloc(fileLength);
    int fid = open("/fdiskinfo.txt",O_RDONLY);
    read(ifd,buff,fileLength+1);
    if((strstr(buff,"/dev/sda2") !=NULL && (strstr(buff,"/dev/sdb1") != NULL)
    {
         /*do copy operation */
    }
    else
    {
        /* print something went wrong */
    }
        // method 2: using grep command
    {
    if(system("grep '/dev/sda2' /fdiskinfo.txt")==0 && system("grep /dev/sdb1 /fdiskinfo.txt");
    {
        /* copy operation */
    }
 }

A: Better way is  writing the code for checking. Because when you are calling the
system function that time it create the new child process so it will consume the some memory
space for the new child process.
So until the child  ends it stop the execution of the working process. My choice is code
is better than using the system.

A: Why are you doing that?  Just do:
char * target = argv[2]; /* or whichever arg you prefer */
dst = fopen( target, "w" );
if( dst == NULL ) {
  perror( target );
  exit( EXIT_FAILURE );
}

If the partition doesn't exist, the fopen will fail and you'll get a nice error message explaining why.


text:
Q: How to update a single property using PATCH method in Node JS? I want to create a PATCH method to update a single property for my API but there is something I don't understand.

A: You should Clearly post your question, this is what i understand, i hope this will help you if you are using request npm in node.js
var request = require('request');

request.patch(
    //First parameter API to make post request
    'https://example.com/api/users',

    //The second parameter, DATA which has to be sent to API
    { json: {
        name: "paul rudd",
        movies: ["I Love You Man", "Role Models"]
      }
    },

    //The third parameter is a Callback function
    function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body);
            console.log(response.statusCode);
        }
    }
);

for more information read here


text:
Q: Transition kernels of diffusions: kernel properties Question: Suppose $Y_{t,x}$ is an Ito diffusion, i.e. the a.s. unique solution of the SDE
$$
dY_{t, x} = b(Y_{t, x})dt + \sigma(Y_{t, x})dW_t, \qquad Y_{0, x}=x,
$$
with $\sigma, b$ Lipschitz continuous.
We can define the family of "transition functions" $(P_t)_{t\geq0}$ of the process via
$$
P_t: \mathbb{R}^d \times \mathbb{B}(\mathbb{R}^d) \to [0, 1], (x, B) \mapsto \mathbb{P}(Y_t\in B | Y_0=x).
$$
How do we know, that $P_t$ is a transition kernel for each $t$, i.e. that
$$
P_t(\cdot, B): x \mapsto P_t(x, B)
$$
is measurable for all $B\in\mathbb{B}(\mathbb{R}^d)$ and
$$
P_t(x, \cdot): B \mapsto P_t(x, B)
$$
is a probability measure for all $x\in\mathbb{R}^d$? What assumptions do we need for that?
Own effort: I was trying to show the semigroup property of the transition semigroup $(P_tf)(x):=\mathbb{E}[f(Y_{t,x})]$, which can be traced back to the Chapman-Kolmogorov Equation, which in turn only makes sense for transition kernels, i.e. if the defined transition functions have the kernel properties. However, this is often just assumed/stated as for example in [Pavliotis, Stochastic Processes and Applications, p.35]. Is this obvious? I could understand the second part, i.e. that $P_t(x,\cdot)$ is a probability measure, since that might just be a consequence of there being a solution to the SDE for every x?


text:
Q: Is $ \lim_{x\to \infty}\frac{x^2}{x+1} $ equal to $\infty$ or to $1$? What is
$ \lim_{x\to \infty}\frac{x^2}{x+1}$?
When I look at the function's graph, it shows that it goes to $\infty$, but If I solve it by hand it shows that the $\lim \rightarrow 1$
$ \lim_{x\to \infty}\frac{x^2}{x+1} =$ $ \lim_{x\to \infty}\frac{\frac{x^2}{x^2}}{\frac{x}{x^2}+\frac{1}{x^2}} =$ $\lim_{x\to \infty}\frac{1}{\frac{1}{x}+\frac{1}{x^2}}=$$ \lim_{x\to \infty}\frac{1}{0+0} = \ 1$
what is wrong here?

A: The answer is $+\infty$. Note that $\lim_ {x\to\infty}\frac1{\frac1x+\frac1{x^2}}=+\infty$, not $1$.

A: What is wrong is

*

*to write "$\lim_{x\to \infty} \frac{1}{0+0}$": an expression such as $\frac{1}{0+0}$ doesn't make sense.

*to write that "$\lim_{x\to \infty} \frac{1}{0+0}$" is equal to $1$. If there is a way to give a meaning to this limit, it will certainly not be $1$ but rather $+\infty$ or $-\infty$ depending on the sign of the denominator.

*to constantly mix up the two kinds of sentences "the function tends to infinity" and "the limit of the function is equal to infinity".

A: $$\lim_{x \rightarrow \infty} \frac{x^2}{x+1}=\lim_{x \rightarrow \infty} x\cdot \frac{1}{1+\frac1x}=\infty$$

A: You  cannot always reinvent the wheel! It's a  basic result that the limit at infinity of a rational function is the  limit of the ratio of the leading terms of its numerator and denominator.
In other terms, here:
$$\lim_{x\to\infty}\frac{x^2}{x+1}=\lim_{x\to\infty}\frac{x^2}{x}=\lim_{x\to\infty}x.$$

A: Writing the fraction as follows may clear it up:
$$
\frac{x^2}{x+1}
= \frac{x^2-1+1}{x+1}
= \frac{x^2-1}{x+1} + \frac{1}{x+1}
= x-1 + \frac{1}{x+1}
\to \infty
$$

A: Hint: Write $$x\cdot \frac{1}{1+\frac{1}{x}}$$


text:
Q: Cauchy-Schwarz Inequality question Find the number of ordered quadruples $(a,b,c,d)$ of nonnegative real numbers such that
\begin{align*}
a^2 + b^2 + c^2 + d^2 &= 4, \\
(a + b + c + d)(a^3 + b^3 + c^3 + d^3) &= 16.
\end{align*}
I have 21 as my answer since (1,1,1,1), (0,0,0,2), and $(0,0\sqrt{2},\sqrt{2})$ and found all the combinations possible with (0,0,0,2) and $(0,0\sqrt{2},\sqrt{2})$,then adding up all the possible combinations and getting 21. However this answer is incorrect. What did I do wrong?

A: $$a^2 + b^2 + c^2 + d^2 = 4$$
$$(a + b + c + d)(a^3 + b^3 + c^3 + d^3) = 16$$
By the C.S. inequality
$$(a + b + c + d)(a^3 + b^3 + c^3 + d^3) \ge (a^2 + b^2 + c^2 + d^2)^2$$
In this case they are equal, and the equality holds only when:
$$\frac{a}{a^2} = \frac{b}{b^2} = \frac{c}{c^2} = \frac{d}{d^2}$$
$$\implies a = b = c = d = 1$$
Note that if any of $\{a,b,c,d\}$ are $0$, the ratios will not exist. We need to consider them on a case-by-case basis:

*

*One of them, say $a=0$: In this case, $$b=c=d=\frac{2}{\sqrt{3}}$$

*Two of them are zero, say $a=b=0$. Then,
$$b = c = \sqrt{2}$$

*Three of them say $a=b=c=0$. Then $d=2$
Hence the solutions are:
$$\boxed{(a,b,c,d) = (1,1,1,1),\ (0, \frac{2}{\sqrt{3}},\ \frac{2}{\sqrt{3}}, \frac{2}{\sqrt{3}}),\ (0, 0, \sqrt{2}, \sqrt{2}),\ (0,0,0,2)}$$
Number of possibilities:

*

*$(1,1,1,1) \implies ^4C_4 = 1$

*$(0, \frac{2}{\sqrt{3}}, \frac{2}{\sqrt{3}}, \frac{2}{\sqrt{3}}) \implies ^4C_1 = 4$

*$(0, 0, \sqrt{2}, \sqrt{2}) \implies ^4C_2 = 6$

*$(0,0,0,2) \implies ^4C_1 = 4$
Hence the total number of cases seems to be $\boxed{15}$


text:
Q: Ember Data routing/mapping to MySQL database I've been struggling to understand this concept, and I've put a LOT of time into researching  this but I'm getting absolutely nowhere.
I have a MYSQL database at a cheap host (one.com). I've made a table in said database, and now I want my Ember app to fetch all entries from it.
How do I accomplish this? As I understand it, ember-data tries to fetch information from the specific item URL.. but how do I map my database entries with corresponding URLs?
I can't install any software on the server directly as I do not own it. There is support for PHP though. Using PHP I can easily retrieve all database entries and encode them to JSON with the correct formatting requested by ember-data, but I have no idea on what to do next.
www.myurl.com/blog/js/app.js
App = Ember.Application.create();

// data storage -----------------------------------------------------

App.Store = DS.Store.extend({
    revision: 12,
        adapter: DS.RESTAdapter.create({
            url: 'http://www.myurl.com/blog'
        })

});

// routers, routes --------------------------------------------------

App.Router.map(function() {
    this.resource('contact');
    this.resource('items', { path: "/items/" });
    this.resource('item', { path: "/items/:item_id"});
    this.resource('hearts');
    this.resource('tags');
});

App.IndexRoute = Ember.Route.extend({
    redirect: function() {
        this.transitionTo('items');
    }
});

App.ItemsRoute = Ember.Route.extend({
    model: function() {
        return App.Item.find();
    }
});

App.ItemRoute = Ember.Route.extend({
    model: function(params) {
        return App.Item.find(params.item_id);
    }
});

// controllers --------------------------------------------------------

App.ItemsController = Ember.ArrayController.extend({
    // ...
});

App.ItemController = Ember.ObjectController.extend({
    // ...
});

// model -----------------------------------------------------------

App.Item = DS.Model.extend({
    tag: DS.attr('string'),
    title: DS.attr('string'),
    posted: DS.attr('date'),
    updated: DS.attr('date'),
    intro: DS.attr('string'),
    full: DS.attr('string'),
    visible: DS.attr('number')
});

www.myurl.com/blog/items/index.php
$host = "myhost";
$usr = "myuser";
$pwd = "mypwd";
$db= "mydb";

$connect = mysql_connect("$host", "$usr", "$pwd", "$db") or die("errormsg");

mysql_select_db("$db", $connect) or die("errormsg");

$sql = "SELECT * FROM mytable";

$result = mysql_query($sql);

$rows = array();

if(mysql_num_rows($result)){
    while($row=mysql_fetch_assoc($result)) {
        $rows['post'][]=$row;
    }
}

print(json_encode($rows));

mysql_close($db);

A: Seems like you are most of the way there, next step is to give it a try and do some debugging.
Step one: make sure your API is returning JSON the way ember expects. Try something like this from javascript console:
$.getJSON("/items").then( function(response) {
  console.log("response: ", response);
});

Response should be list of items. Is it?
Step two: See if ember-data is able to fetch items using the api. So from console, try:
App.Item.find({}).then( function(items) {
  console.log("item count: ", items.get('length'));
  console.log("items: ", items.getEach('id'));
});


text:
Q: Why use the decorator pattern? Ive done research on this pattern, and Im still not sure why it is 100% better than an alternative which I will describe shortly. I will discuss two ways to implement streams. As far as I am concerned, the decorator pattern and my approach are two sides of the same coin.
I wont describe the decorator pattern here since I will assume that people interested in this answer are already familiar with it.
The alternative is to use lists. Lists are inherently ordered, and seem to do the same thing. Lets say we have an output stream that we wrap in an encryption stream which we wrap in a zip stream.
OutputStream stream = new ZipStream(new EncryptStream(new OutputStream(outputLocation)));
stream.write(data);

The alternative to would be to create an output stream, and add a zipper and encrypter to it.
OutputStream stream = new OutputStream(outputLocation);
stream.add(new EncyrptStream());
stream.add(new ZipStream());
stream.write(data);

The code for OutputStream.write would look something like:
public void write(String data) {
  for(StreamDecorator d : decorators) {
    data = d.doMyThing(data);
  }
  //continue normal write operation
}

am I correct in saying these two approaches are two sides of the same coin? If not, where is the decorator pattern more useful than this approach?

A: It's roughly the same to me. In your list pattern, you'll end up calling :
zipStream.doMyThing(encryptStream.doMyThing(outputStream.doMyThing(data))));

The difference is just that you'll be using a specific method rather than constructors, which might be better in some situations.

A: Your example bypasses a lot of things. If you look at Java's streams, you can see that each of them has a single responsibility. FileOutputStream knows how to write bytes to file, SocketOutputStream knows how to write bytes to socket, etc. They could be used by themselves or with other streams, but they're "terminating", i.e. the bytes are gone outside of your handling.
Your Outputstream.write doesn't describe what the "normal write operation" is, but with your list approach, all the "terminating" streams would need to have a list of StreamDecorators and the same code to iterate them and process the data.
While it's not at all impossible to do this with a list (therefore becoming Chain Of Responsibility), it's a lot simpler to do it as a decorator, since the class needs to do only a single thing.

A: Kayaman mentioned single responsibility, but it's more than that to me.
Decorators nest, which means that at a given level of nesting, there is encapsulation (and subsequently information hiding). This means that code is more resistant to changes, etc.
It might help to look at the coupling in the two designs:

In the Decorator example, the coupling only goes to a single component (the object that the stream wraps). The goal of the decorator is to enhance the object it wraps. It has no idea what that object is, apart from it respecting the type of objects it can wrap (e.g., OutputStream).
In the list (with add()) example, there is more coupling. The stream object needs to know more (and could have more reasons to change, re Single Responsibility). Stream has to worry about failures of any/all of the things it aggregates.
I think if you try to implement your alternative all the way, you'll see that it's not as clean as Decorator. As suggested by another answer, you need
zipStream.doMyThing(encryptStream.doMyThing(outputStream.doMyThing(data))));

which I don't think can be easily coded generally (for an arbitrary number of decorators add()ed to your Stream).
Another point involves types and nesting. Since types/subtypes can be used in the Decorator nesting process, it should prevent illogical nesting. It's not clear that add() respects these typing rules, or it would have to be more restricted.
If you start hard-coding add() rules, you wind up with combined class functions of decorator (see the counter example in https://stackoverflow.com/a/6366543/1168342).

A: Your first alternative is not a "list," it is nested constructors.
Anyways, I think that first alternative makes more sense because you want to encrypt the stream, then zip that.
The second alternative looks like you are adding two streams to a single stream. Where would the data be written in that case? I would think the original OutputSteam.

A: From a functional point of view, as others say, it isn't that different.
But, the Decorator Pattern is better because it is a known thing.  So when you describe your design or document it for others, you can say "and I used the decorator pattern here".  This is much more concise and easier for them to validate than "and I used a List here, where I add the streams to it that I want to get called, and I call them in this order.  This allows me to blah blah blah..."
All of the concepts behind the patterns have been around for decades; by naming them, we can more efficiently communicate about the concepts and our intent.


text:
Q: Linux process data structure According to GNU website the linux shell uses the following data structure for a process :
typedef struct process
{
  struct process *next;       /* next process in pipeline */
  char **argv;                /* for exec */
  pid_t pid;                  /* process ID */
  char completed;             /* true if process has completed */
  char stopped;               /* true if process has stopped */
  int status;                 /* reported status value */
} process;

Why can't the shell use the task_struct  data structure for a process when it is already present in the kernel. Why use a separate data structure ?


text:
Q: Tailwind styles don't work with a conditional I was trying to paint a component with Tailwind, the problem is that if I pass a "color" as a prop to the component, it paints the color that I send it and if not, it paints a default color.The problem is that neither color is displayed.
This is my code:
export default function UIStepBlurp({ ico, number, description, color }) {

    let styleCustomColor = `items-center justify-center pt-2 border-2 rounded-full text-[14px] flex absolute -left-4 bg-white -top-4 h-[33px] w-[33px] border-[${color}]`;
    let styleDefaultColor = "items-center justify-center pt-2 border-2 rounded-full text-[14px] flex absolute -left-4 bg-white -top-4 h-[33px] w-[33px] border-primary";

    return (

            <div className={`${color ? styleCustomColor : styleDefaultColor}`}>{number}
 // here is the conditional.
            <div className="w-20 h-20 mb-[10px] bg-no-repeat bg-contain" style={{ backgroundImage: `url(${ico})` }} />

{description}

    )
}

and this is my code where I send all the props:
 <UIStepBlurp number={1} ico="image" description="Accede al catálogo de cursos." color="#000" />

A: Tailwind won't work when passing variables to Arbitrary Values. You can pass this color into an element's style instead:
export const Example = ({ color }) => (

)

Or if you want to strictly use Tailwind you could create an enum with all the colors you expect to use and then choose color/class with the prop you are passing:
const COLORS = {
  COLOR_A: "border-[#000]",
  COLOR_B: "border-[#fff]",
}

export const Example = ({ color }) => (
   <div className={`class-1 class-2 ${COLORS[color]}`} />
)


text:
Q: Jquery Mobile Issues with Disabling Ajax So I am using jquery mobile for an admin interface for something I am doing. Multiple people will be using this interface in real time. I realized that after a page has been loaded into the DOM, it doesn't change. So if someone changes a value on the server the page will not change unless you manually refresh the browser. This is a problem. So I tried to put this in my head on my HTML
    $(document).bind("mobileinit", function () {
        $.mobile.ajaxEnabled = false;
    });

But to no avail. I think I need to disable ajax or clear out the DOM on every request or something. Does anyone have any idea on why this isn't working or what I am doing wrong?


text:
Q: Read Dynamics 365/CRM from Azure Logic Apps I have an Azure Logic App that is triggered upon a sales/purchase order record being updated in Dynamics 365 (online).
I grab all the sales order fields and then I grab all the sales order line fields and I send them to a Web API app as JSON parameters. Now I need product fields for each sales order line.
I currently send the sales order and sales order lines as separate parameters. I would like to combine the sales order, sales order lines and products into one JSON payload.
I'm having difficulty figuring out how to pull in the product for each sales order line and then combining it all into one JSON payload.
How would I do this?
I've been investigating but so far no luck.


text:
Q: Insert svg into simple form input I am quite new to the simple form gem and I'd like to customize the inputs with SVG add-ons such as an email picture into the input field "Email"
Here is the svg code:
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 24 24" xml:space="preserve" width="24" height="24"><title>email 84</title><g class="nc-icon-wrapper" stroke-linecap="square" stroke-linejoin="miter" stroke-width="2" fill="#111111" stroke="#111111"><polyline data-cap="butt" data-color="color-2" fill="none" stroke-miterlimit="10" points="1,3 12,13 23,3 " stroke-linecap="butt"/> <rect x="1" y="3" fill="none" stroke="#111111" stroke-miterlimit="10" width="22" height="18"/></g></svg>

And here is my simple form code:

Welcome !!

    <%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
      <%= f.error_notification %>

        <%= f.input :first_name, required: true, autofocus: true, placeholder: "First name" %>
         <%= f.input :last_name, required: true, autofocus: true, placeholder: "Last name" %>
        <%= f.input :email, required: true, autofocus: true, placeholder: "Email Address" %>
        <%= f.input :password, required: true, hint: ("#{@minimum_password_length} characters minimum" if @minimum_password_length), placeholder: "Password" %>
        <%= f.input :password_confirmation, required: true, placeholder: "Password" %>

        <%= f.button :submit, "Sign up", class: "btn btn-danger small-btn width-login" %>

    <% end %>

Where should I put the SVG code?
Thanks !!

A: You can put before input tag and into a label tag
<%= f.label(:email) do %>
  # Here is the SVG
  #Edit
  <%= f.input :email, required: true, autofocus: true, placeholder: "Email Address" %>
<% end %>

Edit:
And you should use css like in How to add a SVG icon within an input?


text:
Q: If statement not working in my conditional ternary operator I have the following if statement in PHP:
<?php

    for ($i = 1; $i <= 10; $i++) {
        echo "<option " . $carDoors == $i ? "selected = 'selected'" : "" . " >" . $i ."</option>";
    }

?>

I need the selectlist to be based on the value of $carDoors and if that's the case, I want to echo selected = 'selected'. At the moment I keep getting a fully empty selectbox. What am I doing wrong?

A: The problem of your code is, that the ternary operator ?: has a higher precedence than the concatenation operator .. Your code is therefore evaluated as:
if ($carDoors == $i) {
    echo "<option selected = 'selected'";
} else {
    echo "<option  >" . $i ."</option>";
}

To get your desired output you should use brackets arround your short if:
echo "<option " . ($carDoors == $i ? "selected = 'selected'" : "") . " >" . $i ."</option>";

A list of operator precedence can be found in the official PHP documentation.

A: You can use ? by this way:
<?php

    for ($i = 1; $i <= 10; $i++) {
        $selected = $carDoors == $i ? "selected = 'selected'" : "";
        echo "<option " .  $selected . " >" . $i ."</option>";
    }

?>

or simple insert it into ():
for ($i = 1; $i <= 10; $i++) {
  echo "<option " .  ($carDoors == $i ? "selected = 'selected'" : "") . " >" . $i ."</option>";
}


text:
Q: setInterval triggers function multiple times EDIT: what i mean by fires multiple times, is that newjob() will fire 3 times, every 5 seconds...so in 20 seconds i'll have it 12 times triggered, instead of the 4 times that i would want. so it's triggeres multiple times every 5 seconds, instead of once every 5 seconds.
I have a function that i created using Toastr to display a message on my web application. i'm eventually going to tie it to an ajax request to an API to determine whether or not to display a message, but for now i'm just testing how it looks.
i am setting an interval, but it fires the function inside of it multiple times (usually 3).
$(document).ready(function() {
    setInterval(function () {
        newJob();
    }, 5000);
});

i can't do setInterval( function(e) { } as e is undefined, as there is no event associated with it, on click, i've used e.stopImmediatePropagation(); to have it only fire once.
how can i stop this immediate propagation on set interval if i don't have e?
thank you.
EDIT: full code:
var newJob = function(e) {
    var i = -1;
    var $toastlast;

    var getMessage = function () {
        var msgs = ["There's a new job in the job dispatch queue", "A job pending approval has timed out"];
        i++;
        if (i === msgs.length) {
            i = 0;
        }

        return msgs[i];
    };

    var shortCutFunction = "success"; // 'success' or 'error'

    toastr.options = {
        closeButton: true,
        progressBar: true,
        debug: false,
        positionClass: 'toast-top-full-width',
        onclick: null,
        timeOut: "0",
        extendedTimeOut: "0",
        showDuration: "0",
        hideDuration: "0",
        showEasing: "swing",
        hideEasing: "linear",
        showMethod: "fadeIn",
        hideMethod: "fadeOut",
    };

    toastr.options.onclick = function () {
        window.location.href = "/dispatcher";
    };

    var msg = getMessage();

    $("#toastrOptions").text("Command: toastr["
                    + shortCutFunction
                    + "](\""
                    + msg
                    + "\")\n\ntoastr.options = "
                    + JSON.stringify(toastr.options, null, 2)
    );

    var $toast = toastr[shortCutFunction](msg);

};

$(document).ready(function() {
    setInterval(function () {
        console.log('set interval');
        newJob();
    }, 5000);

});

and this is my index.phtml file:
    <?php
echo $this->headScript()->appendFile($this->basePath() . '/plugins/toastr/toastr.js')
echo $this->headScript()->appendFile($this->basePath().'/js/dispatchernotification.js');
    ?>

all i'm doing is adding the javascript of what i want running to my index.phtml file and the toastr library.
by console.loging inside interval, i get three logs.
here's a fiddle..not sure how to run it though as it's on ready
http://jsfiddle.net/efecarranza/rfvbhr1o/

A: setInterval will continue endlessly. I think you're looking for setTimeout.

A: Make sure to put your setInterval outside of $(document).ready(function() {...}). So it will be like:
<script>

$(document).ready(function() {
    ... some code ...
});

var myInterval;
clearInterval(myInterval);
myInterval = setInterval(function() {
    ... your code is here ...
}, 5000);

</script>

For some reason, if it's within $(document).ready() every time you dynamically bring the same page again it double-sets the setInterval in progression and clearInterval function doesn't help until you actually refresh the browser.

A: setInterval: call a function repeatedly every x milliseconds
setTimeOut: call a function after x milliseconds.
You have two options:
Clear the interval when it isn't necessary anymore:
var intervalId;
$(document).ready(function() {
    intervalId = setInterval(function () {
        newJob();
    }, 5000);
});

// At some other point
clearInterval(intervalId);

Or, the simpler solution in your case, use setTimeout:
$(document).ready(function() {
        setTimeout(function () {
            newJob();
        }, 5000);
    });

A: It would help if you can add a jsfiddle with your code so we can see what's going wrong exactly. It's possible that for whatever reason the setInterval function is being called multiple times. Try adding a console.log statement at the start of that function to check if that's the case.
If it is and you can't figure out why (and neither can we without knowing your code), you could place a check at the start of the function like this:
if (typeof this.installInterval.done == "undefined") {
  /*a bunch of code*/
  this.installInterval.done = true
}

A: May be by mistake you are calling your script twice as I did!
In the code below I have called 'testLoop.js' two times.
<script src="../js/testLoop.js"></script>
<script type="text/javascript" src="../js/testLoop.js"></script>
<script type="text/javascript" src="../js/cube.js"></script>


text:
Q: Why, when I posted a topic with PAHO mqtt, did return-8 appear? Consider:
MQTTAsync_responseOptions sendOptions = MQTTAsync_responseOptions_initializer;
MQTTAsync_message pubMsg = MQTTAsync_message_initializer;
int rc = 0;
char msgSend[48] = {0};
json_object *pValue = NULL;
json_object *pObjectSerPro = NULL;
int waitCount = 0;

if (pLoopCount == NULL)
{
    printf("(%s) This is an empty data.\n", __FUNCTION__);
    return DEAL_ERROR;
}

while(!ConnectedFlag && ++waitCount < WAIT_COUNT)
    ;

if (waitCount >= WAIT_COUNT)
{
    printf("(%s) Failed to wait for the connection.\n", __FUNCTION__);
    return DEAL_ERROR;
}

/*
{
    "loop1_count": 1,
    "loop2_count": 2
}
*/

pObjectSerPro = json_object_new_object();

pValue = json_object_new_int(1);
json_object_object_add(pObjectSerPro, LOOP1_COUNT, pValue);
pValue = json_object_new_int(2);
json_object_object_add(pObjectSerPro, LOOP2_COUNT, pValue);

memset(msgSend, 0, 48);
sprintf(msgSend, "%s", json_object_to_json_string(pObjectSerPro));

json_object_put(pObjectSerPro);

sendOptions.onSuccess = onSend;
sendOptions.context = GlobalClient;
pubMsg.payload = msgSend;
pubMsg.payloadlen = strlen(pubMsg.payload);
pubMsg.qos = 1;
pubMsg.retained = 1;

if ((rc = MQTTAsync_sendMessage(GlobalClient, ORENA_SMARTFIRE_EC_RESPONSE_LOOP_REGISTER, &pubMsg,
                                &sendOptions)) != MQTTASYNC_SUCCESS)
{
    printf("(%s) Failed to start sendMessage, return code %d\n", __FUNCTION__, rc);
    return DEAL_ERROR;
}
return DEAL_OK;

I intend to encapsulate a JSON message ({"loop1_count": 1,"loop2_count": 2}) for publication.
When I changed this code from CHAR msgSend[48] = {0}; to CHAR msgSend[40] = {0};,I encountered a return error code -8, but I looked at the data and said that the problem of returning -8 was due to the version problem. Why?

(#define MQTTASYNC_BAD_STRUCTURE   -8
--Return code: A structure parameter does not have the correct eyecatcher and version number)

A: The guess is that the string length exceeds the array size, memory coverage occurs, and the header of the data to be sent is changed.
The answer comes from the author of PAHO: return error code -8 #902 (GitHub).


text:
Q: HTTP Request Sampler not working I am using windows7 and the latest version of Jmeter. I created a simple HTTP Request Sampler and in the server name I added google.com
When I ran it I got the following error:
2015/11/30 14:15:32 INFO  - jmeter.engine.StandardJMeterEngine: Running the test!
2015/11/30 14:15:32 INFO  - jmeter.samplers.SampleEvent: List of sample_variables: []
2015/11/30 14:15:32 INFO  - jmeter.gui.util.JMeterMenuBar: setRunning(true,*local*)
2015/11/30 14:15:32 INFO  - jmeter.engine.StandardJMeterEngine: Starting ThreadGroup: 1 : Thread Group
2015/11/30 14:15:32 INFO  - jmeter.engine.StandardJMeterEngine: Starting 1 threads for group Thread Group.
2015/11/30 14:15:32 INFO  - jmeter.engine.StandardJMeterEngine: Thread will continue on error
2015/11/30 14:15:32 INFO  - jmeter.threads.ThreadGroup: Starting thread group number 1 threads 1 ramp-up 1 perThread 1000.0 delayedStart=false
2015/11/30 14:15:32 INFO  - jmeter.threads.ThreadGroup: Started thread group number 1
2015/11/30 14:15:32 INFO  - jmeter.engine.StandardJMeterEngine: All thread groups have been started
2015/11/30 14:15:32 INFO  - jmeter.threads.JMeterThread: Thread started: Thread Group 1-1
2015/11/30 14:15:33 INFO  - jmeter.threads.JMeterThread: Thread is done: Thread Group 1-1
2015/11/30 14:15:33 INFO  - jmeter.threads.JMeterThread: Thread finished: Thread Group 1-1
2015/11/30 14:15:33 INFO  - jmeter.engine.StandardJMeterEngine: Notifying test listeners of end of test
2015/11/30 14:15:33 INFO  - jmeter.gui.util.JMeterMenuBar: setRunning(false,*local*)

A: This is normal output of JMeter, it indicates that JMeter started and finished one thread one time.
You can visualize test  results with Listeners, in particular View Results Tree is extremely useful for test script development and debugging.
As you can see at below image:

*

*the request is successful (green triangle)

*google search page is displayed at "Response data" tab

*log viewer contains the same entries as you posted

Don't forget to disable listeners for the actual test execution, they consume a lot of resources. You'll be able to open results file after test run using "Browse" button and perform analysis.
See How to debug your Apache JMeter script article for detailed information on getting to the bottom of JMeter test script problem.


text:
Q: elastislide move one at a time I'd like to move one image at a time with the elastislide plugin put can't figure it out. I read on the plugin comments that you can change line 295 from this: var amount = this.fitCount * this.itemW, val; to this: var amount = this.itemW; but the code has been updated since the post in 2012 and no longer works. Can someone please help me.

A: Update code from :
var amount = this.fitCount * itemSpace;

to
var amount = 1 * itemSpace;

A: The above answer works but you could also use the public method _slideTo to move the carousel/slider to individual slides.


text:
Q: How can you calculate the probability of failure of a product after a given time, given the expected failures per unit time? For example, if a product has an expected failure rate of 1 failure every 10 years of operation, what's the probability that the product fails after 1 year of use? How does this probability change if we ask the same question, but now we are using 2 of the same product in parallel? Thanks!

A: You can use an exponential distribution to model this type of problem. Let $t$ be a random variable with distribution $t \sim \text{Exp}(\lambda)$. Here, $t$ represents the amount of time to failure, and $\lambda$ is the rate parameter, where $E[t] = \frac{1}{\lambda}$. Then, we have the following cumulative distribution function:
$$ P[t < T] = 1 - e^{-\lambda T} . $$
We're given that the expected failure rate is $1$ failure in $10$ years of operation. Interpreting that as the mean time to failure, we have $\lambda = \frac{1}{10}$. Plugging in $\lambda$, we have
$$ P[t < T] = 1 - e^{-\frac{T}{10}} . $$
The probability that the product fails within $T = 1$ year is
$$ P[t < 1] = 1 - e^{-\frac{1}{10}} \approx 9.5 \% . $$
Now, let's say we have $n$ of these products running in parallel, and we can assume that the failure of any one product is independent of the failure of any other products. Let $t_i$ represent the time to failure of the $i$th product, where each $t_i$ is independently and identically distributed the same way as $t$ above.
Probability of at Least One Failure
If we want the probability that at least one of the products fails within time T, we're looking for
$$ P[t_1 < T \cup t_2 < T \cup \ ... \ \cup t_n < T] . $$
This isn't a particularly easy way to frame this calculation - we'd have to calculate the probability of exactly one of them failing, or exactly two of them failing, etc., and we'd have to account for all possible combinations of products. But, there's a way to reframe it that's a lot easier.
The complement of the event that at least one product fails is that none of the products fail. In that case, we have
$$ P[t_1 < T \cup t_2 < T \cup \ ... \ \cup t_n < T] = 1 - P[t_1 > T \cap t_2 > T \cap \ ... \ \cap t_n > T] . $$
Since we assumed these failures were independent, we have
$$ 1 - P[t_1 > T \cap t_2 > T \cap \ ... \ \cap t_n > T] $$
$$ = 1 - P[t_1 > T]* P[t_2 > T]* \ ... \ *P[t_n > T] $$
$$ = 1 - (P[t > T])^n $$
$$ = 1 - (1 - P[t < T])^n $$
$$ = 1 - \left(1 - \left(1 - e^{-\frac{T}{10}} \right) \right)^n $$
$$ = 1 - \left(e^{-\frac{T}{10}} \right)^n $$
$$ = 1 - e^{-\frac{nT}{10}} . $$
When $n = 2$ and $T = 1$, we have
$$ P[t_1 < 1 \cup t_2 < 1] = 1 - e^{-\frac{2*1}{10}} \approx 18.1 \%. $$
Probability of $n$ Failures
Now, if we want to find the probability that all $n$ products fail within time $T$, we want
$$ P[t_1 < T \cap t_2 < T \cap \ ... \ \cap t_n < T] . $$
Again, through independence, we can split this up into individual probabilities and calculate:
$$ P[t_1 < T \cap t_2 < T \cap \ ... \ \cap t_n < T] $$
$$ = P[t_1 < T]*P[t_2 < T]* \ ... \ *P[t_n < T] $$
$$ = (P[t < T])^n $$
$$ = \left(1-e^{-\frac{T}{10}}\right)^n . $$
For $n = 2$ and $T = 1$, we have
$$ P[t_1 < 1 \cap t_2 < 1] = \left(1-e^{-\frac{1}{10}}\right)^2 $$
$$ \approx 0.9 \% . $$