Q:

Problems retrieving the Global Profile settings (shown in the Nvidia Control Panel) with NVAPI SDK

I want to use NVIDIA's NVAPI SDK to retrieve all the settings exposed in the NVIDIA Control Panel's 3D Settings' Global profile.

The reference documentation is here: NVAPI Driver Settings (DRS) APIs
Source
Here is what I have so far, mostly basing myself on samples I've found around the web:
#include <Windows.h>
#include <string>
#include "nvapi.h"
#include "NvApiDriverSettings.h"

NvDRSSessionHandle _session;
NvDRSProfileHandle _profile;

int main()
{
    if (NvAPI_Initialize() != NVAPI_OK)
        throw std::runtime_error("NvAPI: NvAPI can't be initialized");

    if (NvAPI_DRS_CreateSession(&_session) != NVAPI_OK)
        throw std::runtime_error("NvAPI: Can't create NvAPI session");
    if (NvAPI_DRS_LoadSettings(_session) != NVAPI_OK)
        throw std::runtime_error("NvAPI: Can't load system settings");

    if (NvAPI_DRS_GetCurrentGlobalProfile(_session, &_profile) != NVAPI_OK)
        throw std::runtime_error("NvAPI: Can't get global profile");

    NVDRS_PROFILE profileInformation = {0};
    profileInformation.version = NVDRS_PROFILE_VER;
    if (NvAPI_DRS_GetProfileInfo(_session, _profile, &profileInformation) != NVAPI_OK)
        throw std::runtime_error("NvAPI: Can't get current global profile information");

    if(profileInformation.numOfSettings> 0)
    {
        NVDRS_SETTING* setArray = new NVDRS_SETTING[profileInformation.numOfSettings];
        NvU32 numSetRead = profileInformation.numOfSettings,i;
        setArray[0].version = NVDRS_SETTING_VER;
        if (NvAPI_DRS_EnumSettings(_session, _profile, 0, &numSetRead, setArray) != NVAPI_OK)
            throw std::runtime_error("NvAPI: Can't get profile setting enum");

        for(i=0; i<numSetRead; i++)
        {
            if(setArray[i].settingLocation!=NVDRS_CURRENT_PROFILE_LOCATION)
            {
                continue;
            }
            NvAPI_DRS_GetSettingNameFromId(setArray[i].settingId, &setArray[i].settingName);
            wprintf(L"Setting Name: %s\n", setArray[i].settingName);
            printf("Setting ID: %X\n", setArray[i].settingId);
            printf("Predefined? : %d\n", setArray[i].isCurrentPredefined);
            switch(setArray[i].settingType)
            {
            case NVDRS_DWORD_TYPE:
                printf("Setting Value: %X\n", setArray[i].u32CurrentValue);
                break;
            case NVDRS_BINARY_TYPE:
                {
                    unsigned int len;
                    printf("Setting Binary (length=%d) :", setArray[i].binaryCurrentValue.valueLength);
                    for(len=0; len<setArray[i].binaryCurrentValue.valueLength; len++)
                    {
                        printf(" %02x", setArray[i].binaryCurrentValue.valueData[len]);
                    }
                    printf("\n");
                }
                break;
            case NVDRS_WSTRING_TYPE:
                wprintf(L"Setting Value: %s\n", setArray[i].wszCurrentValue);
                break;
            }
        }
    }
    printf("\n");
    // Clean up
    NvAPI_DRS_DestroySession(_session);
    _session = 0;
    return 0;
}

Console Output
This is the output I am currently getting:
Setting Name: Vertical Sync Tear Control
Setting ID: 5A375C
Predefined? : 0
Setting Value: 96861077
Setting Name: Vertical Sync
Setting ID: A879CF
Predefined? : 0
Setting Value: 8416747
Setting Name: ??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
Setting ID: 80303A19
Predefined? : 1
Setting Value: 1
Setting Name: ??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
Setting ID: 80857A28
Predefined? : 1
Setting Value: 1
Setting Name: ??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
Setting ID: 809D5F60
Predefined? : 1
Setting Value: 1

Problem
Some Setting names are not displayed correctly (???...), and most seem to be missing (Ambient Occlusion, Anisotropy, Power management, etc.).
Am I getting the wrong profile or is it perhaps initialized incorrectly?
Related Questions
Some questions:

Is there a fundamental difference between NvAPI_DRS_GetCurrentGlobalProfile and NvAPI_DRS_GetBaseProfile? They seem to have to do the same thing.
Does the Current Global Profile actually correspond to the global parameters I see when I open the NVIDIA Control Panel?

A:

Your array has uninitialized memory
NVDRS_SETTING* setArray = new NVDRS_SETTING[profileInformation.numOfSettings];

and that means you can find any sort of data in it (hence the invalid strings you're printing).
Either consider zero-initializing it
NVDRS_SETTING*setArray = new NVDRS_SETTING[profileInformation.numOfSettings];
// Remember `setArray` is a pointer
memset(setArray, 0, sizeof(*setArray) * profileInformation.numOfSettings);

or use a std::vector which, in this case, will zero-initialize your structs as well (although having an explicit constructor to do the job would have made things easier and more reliable).
Finally consider skipping invalid entries, you might want to skip invalid named entries as well (that you can now detect reliably)
if (setArray[i].settingName[0] == 0x00)
  continue;

Is there a fundamental difference between NvAPI_DRS_GetCurrentGlobalProfile and NvAPI_DRS_GetBaseProfile? They seem to have to do the same thing.

From the NVAPI guide

The Base Profile is a profile that always exists and is not associated with a specific
  application. The settings in the Base Profile are applied to all processes on the system
  automatically.
A profile with no applications is called a Global Profile. The settings from a Global
  Profile are applied to all processes on the system, but only if that profile is selected to be
  the Current Global Profile in the system.

so in your case it might be, but not if you set a different current global profile (cfr. NvAPI_DRS_SetCurrentGlobalProfile).

Does the Current Global Profile actually correspond to the global parameters I see when I open the NVIDIA Control Panel?

Mostly, many other advanced settings are hidden in the control panel but accessible via code and/or other advanced tools. An even deeper layer could be dabbling with undocumented functions but you might break a lot of things if you don't know what you're doing.


Q:

Regular expression for an SQL query

I'm looking for a regular expression for the below SQL query.
Select * from data where url like '%?%<alphabet>'

Where the

alphabet

can be any alphabet(a-z).
Thanks in advance

A:

While RegEx is not supported in SQL Server you may try using the pattern matching feature of the LIKE keyword.
Pattern matching in search conditions
SELECT * FROM data WHERE url LIKE '%[a-z]'


Q:

Is it excessive to own server hardware?

Since there is a large pool of passionate developers in this community, I would like to gather your opinions on this matter - do you think it is excessive, or advantageous, to purchase and operate actual server hardware at home to spice your own development and learning efforts?
Back in 2003/4 when I jumped into the development line, I felt servers only belonged to the data centre, and did not believe in the pricing of servers for home use; consumer computing power was already pretty solid (back then), and similarly-speced PCs could be had for a fraction of the cost. Having assembled my own PCs since i was a school kid, I viewed the activity of obtaining second-hand components to build a new PC as an easy task. It was straightforward to prepare a PC that would act as a dedicated Windows 2003 server for my development tests. But for over three years now, I have been operating on real servers, albeit low-end models. I ended up in this state due to a number of factors.

Stability. Server hardware built to work properly together. Tested to run server operating systems. Hardware that I assemble together may or may not work due to all those funny instances of unexpected incompatibilities. And unfortunately I ran into those situations more often than I should, like having to figure out why the PC won't boot up because I have the RAM modules plugged in a particular order, or by simple use of a particular DVD drive. I have not seen a single BSOD for my servers.
Durability. I leave my servers running 24x7 and for years have (thankfully) not experienced any failure in server hardware. In contrast my PCs are just cursed with rapid failure rates. Even my vendor-purchased laptops eventually sport funny problems one way or another (especially with power supply units).
Warranty. I may have warranty for individual PC parts, but the warranty for the computer as a whole is against myself. If something were to fail, I myself was the person to call up for help. And call myself I did several times. With the server however, I call techsupport and get them to replace parts.
Capacity. Virtualization is truly a wonderful thing. Makes setting up single-purpose machines so much easier to manage. I directly loaded my first server to the max with 4GB RAM and happily ran a variety of virtual machines, simulating the multi-server/workstation environments I needed. Now my new server has capacity for 24GB RAM to afford the bigger scenarios I am looking to experiment with (e.g. AD domains, BizTalk server group, TFS group, etc).

All in all, with cranky DIYs I spent more time troubleshooting hardware problems than working on actual development issues. When I threw in the money to purchase real servers there was an instant drop in hardware problems in my life. I would probably have bought a vendor-built workstation too if only I could find a configuration that suited my development needs.
Now, some of my tech friends who are passionate with their work also operate their own servers at home. The thing is, most other folks/colleagues get rather surprised that I would actually spend cash for this category of machines. Some would classify me as insane. Have I truly gone overboard?
UPDATE - Clarification on server usage
The base server (Windows Server 2008) serves basic IIS 7/ASP.NET, SQL Server 2008, and Subversion services. But the largest role it plays is hosting a variety of virtual machines in Hyper-V. I am not a developer who is merely told to whack out application code against a single database and check it into some version control repository then go home without worrying how the application and implementation works out in a production environment. As a solutions integrator, I have to get an understanding of the client/customer environment and think of the big-picture solution that includes infrastructure and deployment concerns. Software application development, while being my primary role, is but a part of the solution.
I frequently find myself having to experiment and discover if certain suggestions or approaches would work for a given environment, and have had to prepare virtual servers like a forest of domains (controllers), web servers, database servers, BizTalk server groups, Team Foundation server, etc to conduct my analysis and solidify my recommendations. These virtual machines work as my personal POCs. The scenarios I face continue to grow larger, and I definitely do not see how I can get to learn how to handle these situations without a base platform that allows me to virtualise and simulate them.

A:

I think having some familiarity with server hardware makes you a more rounded technologist, so go for it. There are elements to a "proper" server you generally don't build into a home built system, like hot swappable drives and PSUs, remote access cards (like a Dell DRAC) etc.
Even if server admin isn't your main job function, as your career progresses you may increasingly become involved in buying hardware and assessing quotes from vendors. The extra knowledge can certainly come in useful there.

A:

If you're looking only to learn, and that too as a programmer and not a network or server engineer I do agree that spending on a professional server setup is overkill. You'll be done with the novelty in the first few weeks and then it will just sit there on your lap like a beached whale.
Do you have any specific needs that cannot be served by a regular computer with server software installed?

A:

Running data-centre level hardware would be over the top - you don't need hot swappable drives and the like and they'd be a waste of money, but certainly if you're serious about your own development work then running a low end SME level server is a good move for the security and convenience it gives you.
Myself I run my own Consultancy/Development (the accepted answer) business, and I run a small network to support that.  I run a HP SME server with 250GB RAID, 4Gb RAM, Windows 2003.  It's on 24/7 and does everything you'd expect a server to be doing in any small business.  The main network connects to the Internet by a good quality SME level ADSL account.
In addition I run a Linux server on similar hardware that is connected to the Internet by another ADSL account (just a basic cheap business account) on a separate phone line.  This gives me backup in the case of ADSL issues (does happen occasionally that one goes down and the other stays up) but also means I can run a low level internet server for showing things to clients on a dedicated and isolated line - obviously not production quality but good enough for testing (I have a couple of dedicated servers co-hosted elsewhere running client sites, but they can't be extensively used for non-production purposes obviously and having the hardware in-house means I can adjust the configuration more easily)
It's really a question of tuning what your requirements are to the hardware to support that - just like deploying any hardware into a client actually.  As a developer you'll want security and convenience just the same as any small business, but equally you need good ROI - no point in spending $1000 on additional server gold-plating when that would buy you a 30" monitor for example.  Just pretend you have a critical but understanding business partner (of the Joel level of coder-focus) who you have to justify your expenditure too and be honest with yourself over what you need - with a sprinkling of indulgence.
EDIT in response to reading some other comments about not needing server hardware for your own personal development use:  Point you have to ask is what happens when your alternative suffers a hardware failure?  I suggest that having a separate server makes it more likely you can recover from a catastrophic failure more quickly: that's likely to happen less often anyway, your more likely to have backups, and the restore is likely to be simpler.
Even if you're just messing around with personal development loosing work and having to restore complex configurations both takes time and is a demoralising pain to do.  You should value your own time at a reasonable $/h rate even when its just fun stuff and factor in that against the cost of a basic server and associated backup regime - with hardware prices at the level they are it's really a no-brainer.


Q:

How to print a string from an actual printer on Cocoa Touch

I want to send a string to a printer from an iPad using code.
The trouble is, I want to connect to the printer using wifi, and then send a string to it for printing. But I don't know how to connect to the printer, and how to send the string, hope someone can help me. Thanks.
The printer and the iPad are in the same local area off-line, I want to use the socket to transfer the content that I want to print through the IP address of the printer.

A:

If the printer is configured as an AirPrinter then it's fairly easy using UIPrintInteractionController.


Q:

Spring SpEL logical operators

In Spring expression language (SpEL) each textual relational operator has a symbolic equivalent. For example, eq can be written as ==, and lt can be written as < (source here).
The logical operators, however, don't have a symbolic equivalent - at least as far as I can tell. I have to use and and or, the expected notation of & and | is just not there (for some reason not is different, it has the ! equivalent).
Any idea if & and | are available, or if it is possible to extend Spring to support them?

A:

You have to take a look at org.springframework.expression.spel.standard.Tokenizer in method process() where you will realize |, &, || and && are not supported. Adding this would require to subclass the Tokenizer and also to subclass the org.springframework.expression.spel.standard.InternalSpelExpressionParser because in its .doParseExpression()` method the Tokenizer is instantiated directly... Source of Spring 3.1 version was taken by me.


Q:

Count delimiter in a file in windows

I have a bunch of files that contains thousands of records.The structure of each file is same.
Each record is on a separate line and has multiple fields separated by a delimiter '|'.
Each row should have 36 fields, but the problem is some of these rows has <>35 fields, i.e. <>35 '|' characters.
Can someone please suggest a way in windows, by which I can identify the row. (Like record with delimiters <>35 should be written to bad file).

A:

@ECHO Off
SETLOCAL
:: Looking for exactly 36 fields - no empty fields
FOR /f "delims=" %%a IN (q25936461.txt) DO (
 SET good=Y
 FOR /f "tokens=1,30*delims=|" %%m IN ("%%a") DO (
  IF "%%o" equ "" (SET "good=") ELSE (
   FOR /f "tokens=1,6,7delims=|" %%p IN ("%%o") DO (
    IF "%%r" neq "" SET "good="
    IF "%%q" equ "" SET "good="
   )
  )
 )
 IF NOT DEFINED good ECHO(%%a
)
ECHO ========== method 1 done =============
:: Looking for exactly 36 fields - allow empty fields
FOR /f "delims=" %%a IN (q25936461.txt) DO (
 SET good=Y
 SET "line=%%a"
 SET /a count=0
 CALL :analyse
 IF NOT DEFINED good ECHO %%a
)
ECHO ========== method 2 done =============

GOTO :EOF
:analyse
SET "linem=%line:*|=%"
IF "%linem%" neq "%line%" SET /a count+=1&SET "line=%linem%"&GOTO analyse
IF %count% neq 35 SET "good="
GOTO :eof

Here's two methods. Testing is your problem....


Q:

How can I undo an edit in Gmail's compose field?

How can I undo an edit in Gmail's compose field?
For example, I write a draft email, select the entire text and remove it, how can I undo my remove action to get the text back?

A:

@JinaneK was on the correct path suggesting to used Ctrl+Z. You will need to install a keyboard that has Ctrl key such as Hacker's Keyboard if your keyboard app does not have it.
After you delete a text, open Hacker's Keyboard (if it was not already opened), press Ctrl (you will see an indication on the key that it is activated, on my phone, the indication was a blue line), then press on Z. You can even use it to redo by using Ctrl+Y
Disclaimer: I am just a user of the app.


Q:

Detect when user changes tabs

How do I detect when the user changes tabs in Access? In VBA hopefully, and not as an Office Add-In.

A:

Forms and Reports are Access objects that have Activate/Deactivate events that can trigger VBA when a they get/lose the focus. Clicking on the "Net Worth Summary" in your image would fire MainMenu's Form_Deactivate() and NetWorthSummary's Report_Activate() events. Tables and queries don't have events like this that you can trap, just forms and reports.


Q:

how add the scene in particular region in android gaming using andengine?

I am new to game development.am using and-engine to develop the game.am create the scene like fall of object randomly from top of the screen use code below.
    TimerHandler spriteTimerHandler;
    float mEffectSpawnDelay = 3f;

    spriteTimerHandler = new TimerHandler(mEffectSpawnDelay, true,
    new ITimerCallback() {

        @Override
        public void onTimePassed(TimerHandler pTimerHandler) {
            Random rand = new Random();

            int y = (int) (resourcesManager.camera.getHeight() + resourcesManager.ball2.getHeight());
            int minx = (int) (resourcesManager.ball1.getHeight());
            int maxx = (int) (resourcesManager.camera.getWidth() - resourcesManager.ball2.getWidth());
            int rangex = maxx- minx;
            int x = rand.nextInt(rangex) + minx;

            Sprite target = new Sprite(x, y, resourcesManager.ball2.deepCopy(),vbom);
            attachChild(target);

            int minDuration = 4;
            int maxDuration = 8;
            int rangeDuration = maxDuration - minDuration;
            int actualDuration = rand.nextInt(rangeDuration) + minDuration;

            MoveYModifier mod = new MoveYModifier(actualDuration, target.getY(),-target.getHeight());
            target.registerEntityModifier(mod.deepCopy());

            TargetsToBeAdded.add(target);
        }
    });

    registerUpdateHandler(spriteTimerHandler);

from this code the object comes from the top of the screen but it comes all over the width.I want to set fall of the object from half of the screen to till end of the screen.Can any one know please help me to solve this issue.

A:

int minx = (int) (resourcesManager.camera.getWidth() / 2);


Q:

Select next row programmatically

How can I select the next row programmatically in iOS?
I have a nextButton on my view, and I want myTable to select the next row after clicking my nextButton.
[myTable selectRowAtIndexPath: ??????
                 animated:YES
           scrollPosition:UITableViewScrollPositionMiddle];

is my code is correct?

A:

Create a variable with your current index of the table
long currentindex;

Create index path and select row as your code :
currentindex = currentindex +1;
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:currentindex inSection:0];
[myTable selectRowAtIndexPath: indexPath
                 animated:YES
           scrollPosition:UITableViewScrollPositionMiddle];


Q:

android.view.ViewRootImpl$CalledFromWrongThreadException : Only the original thread that created a view hierarchy can touch its views

I'm developing an Android application and I'm using Eclipse as IDE and my database is     MySQL. I have the follow problem. When I try to take datas from the database through the AsynTask I have the error that I show below.
android.view.ViewRootImpl$CalledFromWrongThreadException:
Only the original thread that created a view hierarchy
can touch its views

Activity:
@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);
   asyn=new MyAsyncTask();

   tvtexto=(TextView)findViewById(R.id.tvtextoMa);
   context = getApplicationContext();
   eventos = new ArrayList<Eventos>();
   eventosAdapter = new EventosAdapter(context, R.layout.filae, eventos);
   eventos=new ArrayList<Eventos>();
   asyn.execute();
   listView = (ListView)findViewById(R.id.ListView01Ma);
}

AsyncTask:
public class MyAsyncTask extends AsyncTask<Void, Void, Void>
{
   @Override
   protected Void doInBackground(Void... arg0)
   {
      eventos=(ArrayList<Eventos>) BDEventos.getDatosEventos();
      for(Eventos n:eventos){
         eventosAdapter.add(n);
      }
      eventosAdapter.notifyDataSetChanged();
      listView.setAdapter(eventosAdapter);
      return null;
   }
}

A:

Updating ui from background thread is not possible. `doInbackground is invoked on the background thread. Ui should be updated on the ui thread.
Get your data form data base in doInbackground return result and update ui accordingly in onPostExecute.
eventosAdapter.notifyDataSetChanged();
listView.setAdapter(eventosAdapter);

SHould be in onPostExecute


Q:

HTML5 Canvas Ellipse Outline Becomes Distorted As Transformed

When I transform an HTML5 canvas context and draw an ellipse, as the transform becomes larger the ellipse outline becomes completely distorted. Below is some sample code and the results I see in both Firefox and Chrome.
<body>
    <canvas id="myCanvas" width=900 height=900></canvas>
    <script>
        var canvas = document.getElementById("myCanvas");
        var ctx = canvas.getContext("2d");
        ctx.fillStyle = "rgba(0, 51, 255, 0.5)";
        ctx.lineWidth = 2;
        ctx.beginPath();
        ctx.transform(1, 0, 0, 1, -16776544, -16776916);
        ctx.ellipse(16776994, 16777316, 400, 400, 0, 0, 2 * Math.PI);
        ctx.stroke();
        ctx.fill();
    </script>
</body>

Chrome Results
Firefox Results
Is there a way to fix the distortion, or is it somewhere documented that there are limits on canvas transformation?

A:

This is due to the limited precision of floating point numbers. There is not much you can do about it but to avoid really big and really small numbers.
With a pixel size of 0.1mm you are addressing a pixel that is near one mile from the origin (that's a very big screen).
I am not sure if the canvas rendering uses 32bit floats (thinking it does from your example and I know that webGL definitely uses floats) you need to do the transformations in javascript as it uses doubles 64bit which will give you a screen 9 orders (approx) greater (screen now size of the sun)
eg
var x = 16776544;
var y = 16776916;
var x1 = 16776234;
var y1 = 16776446;
ctx.setTransform(1,0,0,1,0,0);
x -= x1; // apply transform using doubles
y -= y1;
ctx.ellipse(x,y,100,100,0,0,Math.PI*2);


Q:

React Router v4 - Error: React.Children.only expected to receive a single React element child

I'm using react router v4 in a very simple app. I've tried to follow the documentation but I have a weird error when my app try to launch.
The error says: error: React.Children.only expected to receive a single React element child
The weird thing is that I have only one component in my ReactDOM.render function.
Here's some snippets on my code:
index.js:
ReactDOM.render(
  <App />,
  document.getElementById('root')
);

app.js (I hide all the obvious component imports):
import { BrowserRouter as Router, Route } from 'react-router-dom'

class App extends Component {
  render() {
    return (
      <Router>

          <Route path='/'>

              <SearchBar/>
              <AddMovieButton/>

            <SearchResultsList/>
          </Route>
          <Route exact path='/new'>
            <AddMovieForm/>
          </Route>

      </Router>
    );
  }
}

export default App;

I can't really understand why this is not working, and why I have that error.

A:

You can have an only one child element inside a Route. If you want to have multiple, wrap them with a div as follows.
<Route path="/">

      <SearchBar />
      <AddMovieButton />

    <SearchResultsList />

</Route>;


Q:

Recovering a monoidal category from its category of monoids

What kind of additional properties and/or structures one needs to impose on the category
of (commutative or noncommutative) monoids of some monoidal category
so that one can recover the original monoidal category from this data?
What kind of additional properties and/or structures one needs to impose on a category
to ensure that it is the category of monoids of some monoidal category?
The example I have in mind is the category of (commutative or noncommutative) C*-algebras (or von Neumann algebras).
Can we obtain one of these categories as the category of monoids of some monoidal category?

A:

Here is a characterization of categories of commutative monoids.  I don't know the answer in the non-commutative case.
Let C be a category.  Then C is the category of commutative monoids in some symmetric monoidal category if and only if C has finite coproducts.
For suppose that C = CMon(M) for some symmetrical monoidal category M = (M, @, I).  Then one can show that the tensor product @ of M also defines a tensor product on C --- and that this is, in fact, binary coproduct in C.  (Example: if M is the category of abelian groups then C is the category of commutative rings, and the tensor product of commutative rings is the coproduct.)  Similarly, the unit object I of M is a commutative monoid in a unique way, and is in fact the initial object of C.  So C has finite coproducts.
Conversely, suppose that C has finite coproducts.  Then (+, 0) defines a symmetric monoidal structure on C, and with respect to this structure, every object of C is a commutative monoid in a unique way.  Thus, C = CMon(C).


Q:

Delete records from corresponding table

I have two tables in the database as shown in the screenshot...
Please note that LicenceType in the second table is behaving as GroupId in order to classify group of records.
According to business logic (client's requirement) some of the records are saved in tbCompanyAgent as shown in the first table.
Now if we remove data from tbLicence on the basis of LicenceType (Group Id)
then all the corresponding data should be removed from tbCompanyAghent.
For doing so, I have written below query
DELETE FROM tbLicence WHERE LicenceType = @LicenceType

DELETE FROM tbCompanyAgent

SELECT * FROM tbCompanyAgent INNER JOIN tbLicence ON tbCompanyAgent.LicenceNumber = tbLicence.LicenceNumber
    OR tbCompanyAgent.LicenceNumber = tbLicence.StateIssuedLicenseNumber
    OR tbLicence.LicenceType = @LicenceType

but it doesn't do as required. Please help !!!

A:

      Delete from tbCompanyAgent
      where LicenceNumber in (select distinct LicenceNumber
      from tbLicence where LicenceType= @LicenceType)

      Delete from tbLicence where LicenceType = @LicenceType


Q:

Car Dealer Management Software

For learning purposes Im thinking of Creating a management software for car dealers, but before I get into the designing/planning stage im gathering requirements. Would anyone be able to add something to my current req list?
Here is what I have so far

Different logins (Admin, Mechanic, Car Cleaner)
Possibility to Add used and new cars to th system
When Car is sold move it to sold section with all the details
Possibility to book a viewing/test drive
Check current stock
Reports such as, best selling cars by make

Thanks in advance

A:

The requirements looks good for a basic CRUD app , don't forget to add the update section for users and cars, and maybe you want to add a view system for the cars filtering by type or brand or price, make the app secure .


Q:

Add dupli_extrude_cursor to Extrude dropdown box

There are two items that are not in the UI, but just available by a hotkey. Dupli Extrude and Dupli Extrude Rotate.
I want them to be visually available in the Extrude dropdown box in the tool shelf in the Tools panel. So I added them to the submenu for it, which is in the space_view3d-py file, the class VIEW3D_MT_edit_mesh_extrude. And there I am stuck.
The operator is mesh.dupli_extrude_cursor. With a flag to tell if the target object rotates randomly or not. And this flag is the trouble maker here. I can add a normal button that way:
        col.operator("mesh.dupli_extrude_cursor" , icon='DUPLI_EXTRUDE',  text = " DupliExtrude    ").rotate_source = False
        col.operator("mesh.dupli_extrude_cursor", icon='DUPLI_EXTRUDE_ROTATE', text = " DupliExRotate  ").rotate_source = True

But when I do the same in the dropdown box menu then the whole Blender menu vanishes. VS marks me the whole code red then. I also tried to include the flag with the operator. But then Blender doesn't find it and gives a missing srna error in the console. I cannot leave the flag away, that's what separates the tools. And also curious, the dropdown box entry does not show the hotkey for it.
What's the right way to put those two items into the dropdown box?
class VIEW3D_MT_edit_mesh_extrude(Menu):
    bl_label = "Extrude"

    _extrude_funcs = {
        'VERT': lambda layout:
            layout.operator("mesh.extrude_vertices_move", text="Vertices Only"),
        'EDGE': lambda layout:
            layout.operator("mesh.extrude_edges_move", text="Edges Only"),
        'FACE': lambda layout:
            layout.operator("mesh.extrude_faces_move", text="Individual Faces"),
        'REGION': lambda layout:
            layout.operator("view3d.edit_mesh_extrude_move_normal", text="Region"),
        'REGION_VERT_NORMAL': lambda layout:
            layout.operator("view3d.edit_mesh_extrude_move_shrink_fatten", text="Region (Vertex Normals)"),
        'DUPLI_EXTRUDE': lambda layout:
            layout.operator("mesh.dupli_extrude_cursor(rotate_source = False)", text = "DupliExtrude"), # does not work, Blender does not find the operator
        'DUPLI_EX_ROTATE': lambda layout:
            layout.operator("mesh.dupli_extrude_cursor", text="Dupli Extrude Rotate").rotate_source = True,  # does not work, Blender Menu vanishes

    }

EDIT: I could of course add two helper classes. It works. See this example. But i am not a happy bunny with this solution. I want to add the operators in the way the other operators in this dropdown box are added too. There should be a solution.
class VIEW3D_MT_edit_mesh_extrude_dupli(bpy.types.Operator):
    """Duplicate or Extrude to Cursor"""      # blender will use this as a tooltip for menu items and buttons.
    bl_idname = "mesh.dupli_extrude_cursor_norotate"        # unique identifier for buttons and menu items to reference.
    bl_label = "Duplicate or Extrude to Cursor"         # display name in the interface.
    bl_options = {'REGISTER', 'UNDO'}  # enable undo for the operator.

    def execute(self, context):        # execute() is called by blender when running the operator.
        bpy.ops.mesh.dupli_extrude_cursor('INVOKE_DEFAULT', rotate_source = False)
        return {'FINISHED'}

class VIEW3D_MT_edit_mesh_extrude_dupli_rotate(bpy.types.Operator):
    """Duplicate or Extrude to Cursor Rotated"""      # blender will use this as a tooltip for menu items and buttons.
    bl_idname = "mesh.dupli_extrude_cursor_rotate"        # unique identifier for buttons and menu items to reference.
    bl_label = "Duplicate or Extrude to Cursor Rotated"         # display name in the interface.
    bl_options = {'REGISTER', 'UNDO'}  # enable undo for the operator.

    def execute(self, context):        # execute() is called by blender when running the operator.
        bpy.ops.mesh.dupli_extrude_cursor('INVOKE_DEFAULT', rotate_source = True)
        return {'FINISHED'}

class VIEW3D_MT_edit_mesh_extrude(Menu):
    bl_label = "Extrude"

    _extrude_funcs = {
        'VERT': lambda layout:
            layout.operator("mesh.extrude_vertices_move", text="Vertices Only"),
        'EDGE': lambda layout:
            layout.operator("mesh.extrude_edges_move", text="Edges Only"),
        'FACE': lambda layout:
            layout.operator("mesh.extrude_faces_move", text="Individual Faces"),
        'INDIVIDUAL': lambda layout:
            layout.operator("view3d.edit_mesh_extrude_individual_move", text="Individual"),
        'REGION_VERT_NORMAL': lambda layout:
            layout.operator("view3d.edit_mesh_extrude_move_shrink_fatten", text="Region (Vertex Normals)"),
        'DUPLI_EXTRUDE': lambda layout:
            layout.operator("mesh.dupli_extrude_cursor_norotate", text="Dupli Extrude"),
        'DUPLI_EX_ROTATE': lambda layout:
            layout.operator("mesh.dupli_extrude_cursor_rotate", text="Dupli Extrude Rotate")
    }

    @staticmethod
    def extrude_options(context):
        mesh = context.object.data
        select_mode = context.tool_settings.mesh_select_mode

        menu = []
        if mesh.total_face_sel:
            menu += ['INDIVIDUAL', 'REGION_VERT_NORMAL', 'FACE']
        if mesh.total_edge_sel and (select_mode[0] or select_mode[1]):
            menu += ['EDGE']
        if mesh.total_vert_sel and select_mode[0]:
            menu += ['VERT', 'DUPLI_EXTRUDE', 'DUPLI_EX_ROTATE']

        # should never get here
        return menu

    def draw(self, context):
        layout = self.layout
        layout.operator_context = 'INVOKE_REGION_WIN'

        for menu_id in self.extrude_options(context):
            self._extrude_funcs[menu_id](layout)

A:

Can quite simply ap(pre)pend those operators to the menu
import bpy
def draw_dupli_extrude(self, context):
    col = self.layout
    col.operator_context = 'INVOKE_REGION_WIN'
    col.operator("mesh.dupli_extrude_cursor" ,  text="DupliExtrude").rotate_source = False
    col.operator("mesh.dupli_extrude_cursor", text="DupliExRotate").rotate_source = True
# prepend to menu
bpy.types.VIEW3D_MT_edit_mesh_extrude.prepend(draw_dupli_extrude)

NOTE: The operators are kind of useless in the menu as that's where the mouse is to invoke... which could be why they are not there in the first place.
Always look at system console for errors, as in your sample code there are no icons for
icon='DUPLI_EXTRUDE'
icon='DUPLI_EXTRUDE_ROTATE'

which will lead to a TypeError.


Q:

Solving $\sin(t+am)=a$ where $-1 \le m \le 1$

What theory or algorithm would I need to research to solve equations such as $\sin(t+am)=a$ (knowing that $-1 \le m \le 1$) for the value of $a$?
My equations may become more complex but have similar properties (and always the constraint on the range of the $m$ variables), such as $\sin(t+\sin(th+am_1)m_2)=a$.
I've played with Wolfram Alpha enough to verify that these functions stay monotonic with $t$ but still can't figure out how to solve them analytically in the real domain.
EDIT: Here is a piece of music using almost exclusively equations like this to directly calculate the time domain audio samples: http://soundcloud.com/full-synthetic/sunshine It's not the greatest but every synth is on that form.

A:

The bisection technique is also viable, and offers a large benefit over newton's iteration: It guarantees a solution.


Q:

Adding custom keyboard layout to Xubuntu 13.10

I'm trying to add workman-p layout to xubuntu. It comes with several otions to install. There are files for xorg, xmodmap, and *.kmap files.
From this article I found out that you need to add keymaps to /etc/X11/xkb/symbols/, and that all the layout files should be there, but I didn't even have the directory. So I added it, copied the files there but it didn't help in any way. I guess xfce doesn't use this folder in 13.10.
I had some success with xmodmap but it just changed my layout and turned off the switching to Russian I have set up.
I need a way to add layout so that it can be switched in a normal way i.e. the settings menu.

A:

The Xkb directory is located at /usr/share/X11/xkb
Besides, it's not XFCE that uses the directory, it's Xkb, a part of Xorg.
To create a new layout just create a file in symbols/ (eg asdf). After that you can switch to the newly created layout with setxkbmap asdf
Next step would be to register the layout, see the files rules/base.xml and rules/evdev.xml.
After registering you can switch to it other than by calling setxkbmap directly: most desktop environments honor those files and all keyboard layouts you see in keyboard settings are actually from those XML files.


Q:

Python tkinter button returns to black while pressed

I'm using Tkinter and I've noticed that  my buttons become black while mouse button is held down irrespective of what color I have stated when declaring the button.
Does anyone know if this can be controlled?
Kind regards,¨
Daniel

A:

You're looking for the activebackground and activeforeground properties.
Read more about them here.


Q:

Can I transfer a profile to a new Nintendo Switch?

I plan this summer to buy another Nintendo Switch so I can play on the bus (And my SO can play at work too)
But my profile is already on the Nintendo Switch I have; Can I transfer it to another Nintendo Switch?

A:

At this time you can transfer a Nintendo Account between consoles by deactivating the first and then setting the new console as the active one. Digital purchases can only be played on the active console for a given account so you and your SO will not be able to share a single digital purchase. Most importantly your saved games will NOT transfer — saves on SD cards are encrypted by unique hardware not account.
More information on Nintendo's Support site: How to Transfer Digital Games Between Nintendo Switch Consoles.
That said, Nintendo has made many promises about their upcoming Online Services, including theories and hints at the possibility of saved game syncing. The optimists are hoping for something like Sony's PlayStation Plus subscription service, for both save and purchase syncing between multiple pieces of hardware, though that might be too much to hope for.


Q:

non-template std::reference_wrapper assignment operator and template constructor

In the C++ 20 Standard the constructor of the class template std::reference_wrapper is a template.
template<class U>
constexpr reference_wrapper(U&&) noexcept(see below );

while the assignment operator is not a template
constexpr reference_wrapper& operator=(const reference_wrapper& x) noexcept;

What is the reason that this difference (template and non-template) between these special member functions exists?
On the other hand, I tried the following progarm using Visual C++ 2019.
#include <iostream>
#include <functional>

struct A
{
    void f() const { std::cout << "A::f()\n"; }
    virtual void g() const { std::cout << "A::g()\n"; }
};

struct B : A
{
    void f() const { std::cout << "B::f()\n"; }
    void g() const override { std::cout << "B::g()\n"; }
};

int main()
{
    B b;

    std::reference_wrapper<A> r( b );

    r.get().f();
    r.get().g();

    r = std::reference_wrapper<B>( b );
}

and the compiler did not issue an error message relative to the assignment operator.
Is it a bug of the compiler or have I missed something?

A:

If std::reference_wrapper<T> had a single constructor accepting T&, then it would lead to bugs like std::reference_wrapper<const T> being able to bind to temporaries of type T. So, originally there were two constructors (other than the copy constructor): one taking T&, and another taking T&&, which was defined as deleted, ensuring that a compile error would occur.
However, it was pointed out that this is not really what we want: it would be better if std::reference_wrapper<T> would have no constructor at all that accepts an rvalue of type T, as opposed to a deleted constructor. This is LWG 2993. (You'll notice that this issue is mentioned at the bottom of the cppreference page.) Thus, the constructor was changed to a template that is SFINAE-disabled as appropriate.
Once these issues are solved for the constructor, the assignment operator only needs to have a single overload taking reference_wrapper. The conversion issues will be handled by the constructor logic when the compiler forms the implicit conversion sequence.


Q:

convolution of audio signal

I'm using audiorecorder to record sound and do some processing in pseudorealtime on android phone.
i'm facing a problem between FFT and convolution of audio signal:
I perform FFT on a known signal(a sine waveform), and i correctly always find the single tone contained in it, by using the FFT.
Now i want to do the same thing by using a convolution (it's an exercise): I perform 5000 convolutions of that signal by using 5000 filters. Each filter is a sine waveform on a different frequency between 0 and 5000 Hz.
Then, i search the peak for each convolution output. By this way i should find the maximum peak when i'm using the  filter with the same tone contained on the signal.
Infact with a tone of 2kHz i can find the max with the 2kHz filter.
The problem is that when i receive a 4kHz tone, i find the max on the convolution with the 4200Hz filter (while the FFT instead always works fine)
Is it matematically possible?
what is the problem in my convolution?
This is the convolution function that i wrote:
 //i do the convolution and return the max
 //IN is the array with the signal
 //DATASIZE is the size of the array IN
 //KERNEL is the filter containing the sine at the selected frequency

 int convolveAndGetPeak(short[] in,int dataSize, double[] kernel) {
        //per non rischiare l'overflow, il kernel deve avere un ampiezza massima pari a 1/10 del max
        int i, j, k;
        int kernelSize=kernel.length;
        int tmpSignalAfterFilter=0;
        double out;

        // convolution from out[0] to out[kernelSize-2]
        //iniziamo
        for(i=0; i < kernelSize - 1; ++i)
        {
            out = 0; // init to 0 before sum

            for(j = i, k = 0; j >= 0; --j, ++k)
                out += in[j] * kernel[k];

            if (Math.abs((int) out)>tmpSignalAfterFilter ){
                tmpSignalAfterFilter=Math.abs((int) out);
            }
        }

        // start convolution from out[kernelSize-1] to out[dataSize-1] (last)
        //iniziamo da dove eravamo arrivati
        for( ; i < dataSize; ++i)
        {
            out = 0;  // initialize to 0 before accumulate

            for(j = i, k = 0; k < kernelSize; --j, ++k)
                out += in[j] * kernel[k];

            if (Math.abs((int) out)>tmpSignalAfterFilter ){
                tmpSignalAfterFilter=Math.abs((int) out);
            }

        }

        return tmpSignalAfterFilter;
    }

the  kernel, used as filter, is generated this way:
 //curFreq is the frequency of the filter in Hz
 //kernelSamplesSize is the desired length of the filter (number of samples), for time precision reasons i'm using 20 samples length.
 //sampleRate is the sampling frequency

 double[] generateKernel(int curFreq,int kernelSamplesSize,int sampleRate){
    double[] curKernel= new double[kernelSamplesSize] ;

    for (int kernelIndex=0;kernelIndex<curKernel.length;kernelIndex++){
        curKernel[kernelIndex]=Math.sin( (double)kernelIndex * ((double)(2*Math.PI) * (double)curFreq / (double)sampleRate));    //the part that makes this a sine wave....
    }
    return curKernel;

 }

if you want to try a convolution, the data contained in the IN array is the following:
http://www.tr3ma.com/Dati/signal.txt
Note1: the sampling frequency is 44100Hz
Note2: the tone contained in the signal is a single 4kHz tone (even if the convolution has the max peak with a 4200Hz filter.
EDIT: I also repeated the test on a excel sheet. the result is the same (of course, i'm using the same algorithm) and the algorithms seems to me to be correct...
this is the excel sheet i prepared, if you prefer to work on excel: http://www.tr3ma.com/Dati/convolutions.xlsm

A:

it seems all correct, apart the number of samples of the kernel (the filter).
Increasing the size of the filter the result is more accurate.
I don't know how to calculate the bandwidth of this filter but it seems clear to me that it's a matter of filter bandwidth. So, the filter bandwidth depends also on the number of samples of the filter used in the convolution, with reference to the sampling frequency(and may be also with reference to the tone frequency). Unfortunately i can not increase too much the number of samples of my filter since otherwise the phone can not perform the filtering in realtime.
Note: i need the convolution cause i need to identify the precise moment when the tone was fired.
EDIT: i made a compare between filter with 20 samples and filter with 40 samples.
I don't know the formula to obtain the fitler bandwidth but it's clear, in the following image, the difference between the 2 filters.
EDIT2: FEW DAYS AFTER POSTING THE SOLUTION I FOUND HOW TO CALCULATE THE BANDWIDTH OF SUCH FILTER: IT'S JUST THE INVERSE OF THE FILTER DURATION. SO IN EXAMPLE A KERNEL OF 40 SAMPLES AT 44100KhZ HAS A DURATION OF ABOUT 907uS, THEN THE FILTER BANDWIDTH, WITH THIS KERNEL AND A WINDOW OF THE SAME LENGTH IS 1/907uS= 1,1KhZ

(source: tr3ma.com)


Q:

parse form (POST) data to create a multidimensional hash

I have a form which is used to submit data about multiple people. There are multiple properties for each person, and I'm grouping them like the following:
<input type=hidden name="person1[firstname]" value='Sam'/>
<input type=hidden name="person1[lastname]" value='Higgins'/>

<input type=hidden name="person2[firstname]" value='Jiminy'/>
<input type=hidden name="person2[lastname]" value='Cricket'/>

...etc

When I do the following:
my %hash = params;
die Dumper \%hash;

I get:
VAR1 = {
          'person1[firstname]' => 'Sam',
          'person1[lastname]' => 'Higgins',
          'person2[firstname]' => 'Jiminy',
          'person2[lastname]' => 'Cricket',
};

When I was expecting something like:
VAR1 = {
          'person1' => { firstname => 'Sam', lastname => 'Higgens' },
          'person2' => { firstname => 'Jiminy', lastname => 'Cricket' },
};

Is there a way to get the above, or am I doing it wrong in my HTML?
Edit
I've also tried with empty brackets at the end:
<input type=hidden name="person1[firstname][]" value='Sam'/>

but that just gave:
'person1[firstname][]' => 'Sam',

A:

To answer the question more wholly than providing a link:
I went with a solution that uses jQuery, specifically using a plugin (https://github.com/marioizquierdo/jquery.serializeJSON), to send the data asynchronously (AJAX) and using Dancers from_json method which creates a hashref of the JSON string.
I emphasise string because the function offered by the serializeJSON plugin creates a JSON object, and this Dancer does not convert to the proper structure. Therefore you need to use JSON.stringify() to create a json string, which Dancer does accept :)
Below is the code:
Example HTML:
<input type=hidden name="person1[firstname]" value='Sam'/>
<input type=hidden name="person1[lastname]" value='Higgins'/>

JS (jQuery):
var formData = $(this).serializeJSON();
console.log(formData);
$.ajax({
     'url': '/your_url',
     'type': 'POST',
     'data': JSON.stringify(formData),
     'success': function(res){
         console.log(res);
   }
 });

Perl (Dancer):
post '/your_url' => sub {
    my $json = request->body;
    use Data::Dumper;
    my $hashref = {};
    $hashref = from_json($json);
    die Dumper \$hashref->{person1}->{name}; # 'Sam'
}

Thanks to all who helped!


Q:

JavaFX 8 wrong SplitPane's diviser positions

I use a splitPane with 4 Nodes inside without size limits. But when I try to split it, it doesn't work.
Code Used
m_Split.setDividerPosition(0, 0.25);
m_Split.setDividerPosition(1, 0.5);
m_Split.setDividerPosition(2, 0.75);
double tab[] = m_Split.getDividerPositions();
for(int i=0; i < tab.length; i++)
{
    System.out.println("i=" + i + "  pos=" + tab[i]);
}

The code is in a function started with Platform.runLater(new Runnable) and the run() function.
Output
i= 0  pos=0.2505854800936768
i= 1  pos=0.5
i= 2  pos=0.7505854800936768

But with others position values
i=0  pos=0.2997658079625293
i=1  pos=0.5
i=2  pos=1.0

with 0.3, 0.6 and 1.0
and
i=0  pos=0.5
i=1  pos=0.5
i=2  pos=1.0

with 0.5, 1.0 and 1.0 values
I use Java 1.8 and Java FX 8
Thanks

A:

You have not given a full example to reproduce your problem so we can only guess. The likeliest reason for the issue you describe is that you have added children to the split pane and they have maximum/minimum sizes which are not compatible with your divider constraints. The javadoc states (emphasis mine):

Setting the divider position greater than the node's maximum size position will result in the divider being set at the node's maximum size position. Setting the divider position less than the node's minimum size position will result in the divider being set at the node's minimum size position. Therefore the value set in setDividerPosition(int, double) and setDividerPositions(double...) may not be the same as the value returned by getDividerPositions().


Q:

C++ operating on "packed" arrays

Suppose that I have two, for example, float arrays a and b, an int key array k and a template mySortByKey function of my own, operating on a single array, something like
template<class T>
mySortByKey(int *k, T *a)

Is there a possibility (for example, using zip iterators and tuples of some sorts) to enable mySort operating simultaneously on a and b, so that they can be simultaneously ordered according to the key k?

A:

I don't think you can do that. However, you can accomplish something similar by the use of a helper array of indices.
int keys[ARRAY_SIZE];
float a[ARRAY_SIZE];
float b[ARRAY_SIZE];

// Fill up the contents of keys, a, and b

// Create an array of indices.
int indices[ARRAY_SIZE];
for ( int i = 0; i < ARRAY_SIZE; ++i )
   indices[i] = i;

// Sort the indices using keys.
mySortByKey(keys, indices);

// Now access the arrays a and b indirectly, using the sorted array
// of indices as an intermediate object.
for ( int i = 0; i < ARRAY_SIZE; ++i )
{
   float fa = a[indices[i]];
   float fb = b[indices[i]];
}


Q:

trying to update or insert records into an external excel worksheet using SQL query

I am trying to insert or update an external worksheet using SQL with VBA. Below the full function code.
The error happen when I try to open the recordset within the loop passing the sql select query.
Any help would be appreciated. I know that the connection string works as I am using it on other code.
The SQL string looks like this:
select top 1 VALUENAME FROM [TradingTotals$] WHERE LOWER(VALUENAME)= LOWER('Trading') AND VALUEDATE =29/05/2020 AND CLOSINGMONTH = 'May' ORDER BY VALUEDATE DESC)

Full Function code
Public Function InsertClosingMonthTotals(ByVal CollOfTradeLogTotObj As Collection) As Boolean

   Dim IsSuccess As Boolean
   Dim Item As TradeLogTotalsObj
   Dim Sql As String
   Dim SqlSelect As String
   Dim ConnDbString As String

   Dim TotalRecords As Long

   Dim Name As String
   Dim Value As Variant
   Dim Trading As Variant
   Dim LongShort As Variant
   Dim Therms As Variant
   Dim Valdate As Date
   Dim ClosingMonth As String

   ClosingMonth = Helper.FormatValue(Date, formatTypes.AsMonthlongOnly)

   Set Glob_Conn = New ADODB.Connection
   Set Glob_RecSet = New ADODB.Recordset

   ' Client-side cursor for correct return of record count
   Glob_RecSet.CursorLocation = adUseClient

   'Get Connection string according to the database server type
   ConnDbString = Helper.GetConnectionString(ServerTypes.Excel, Glob_FilePathForDataInput)

   'if the connection is closed then open it
   If (Glob_Conn.State = 0) Then
      Glob_Conn.Open (ConnDbString)
   End If

   For Each Item In CollOfTradeLogTotObj
      Name = Item.Name
      Value = Helper.FormatValue(Item.Value, AsNumber)
      LongShort = Helper.FormatValue(Item.LongShort, AsDecimalThreeDigits)
      Therms = Helper.FormatValue(Item.Therms, AsDecimalThreeDigits)
      Valdate = Helper.FormatValue(Item.dateTime, AsDateDisplay)

      SqlSelect = "select top 1 VALUENAME FROM [" & Glob_SheetNameTotalBooks & "$]" & _
      " WHERE LOWER(VALUENAME)= LOWER(" & "'" & Name & "'" & ")" & " AND VALUEDATE =" & Valdate & _
      " AND CLOSINGMONTH = " & "'" & ClosingMonth & "'" & _
      " ORDER BY VALUEDATE DESC)"

      Debug.Print ("SQL SELECT " & SqlSelect)
      Debug.Print ("*************************************************************")

      'open the record set
      If (Glob_RecSet.State <> 1) Then
     ' ******* ERROR ON LINE BELOW ON OPEN **********
      Glob_RecSet.Open SqlSelect, Glob_Conn, adOpenForwardOnly, adLockOptimistic
      End If

      TotalRecords = Glob_RecSet.RecordCount
      If (TotalRecords > 0) Then
      Sql = "UPDATE TradingTotals SET VALUENAME =" & "'" & Name & "'" & _
      ",VALUEDATE =" & Valdate & _
      ",VALUE =" & Value & _
      ",LONGSHORT =" & LongShort & _
      ",THERMS =" & Therms & _
      ",CLOSINGMONTH =" & "'" & ClosingMonth & "'" & _
      "  WHERE LOWER(VALUENAME) = LOWER(" & Name & ") AND VALUEDATE = " & Valdate & " AND CLOSINGMONTH =" & ClosingMonth
      Else
      Sql = "INSERT INTO " & Glob_SheetNameTotalBooks & " (VALUENAME,VALUEDATE,VALUE, LONGSHORT, THERMS, CLOSINGMONTH )" & _
      " VALUES (" & "'" & Name & "'" & "," & Valdate & "," & Value & "," & LongShort & "," & Therms & "," & ClosingMonth & ")"
      End If

      Debug.Print ("SQL INSERT " & Sql)
      Debug.Print ("*************************************************************")

      Glob_Conn.Execute Sql

   Next Item

 'cleanup
   Helper.CloseConnectionObjects Glob_RecSet, Glob_Conn

   InsertClosingMonthTotals = IsSuccess
End Function

EDIT
this query works
SQL SELECT select TOP 1 VALUENAME FROM [TradingTotals$] WHERE LOWER(VALUENAME) ='Trading'

and seems that the issue is with LOWER() ; does anyone know if LOWER() cannot be used in excel queries?
EDIT 2
it seems that is just a matter of "properly" writing the query in Excel; this one below works. In the previous one tehre also was an extra ")" at the end of teh query
SQL SELECT select top 1 VALUENAME FROM [TradingTotals$] WHERE VALUENAME= 'Trading' AND VALUEDATE ='29/05/2020' AND CLOSINGMONTH = 'May' ORDER BY VALUEDATE DESC

I am trying now to use LOWER() again
EDIT 3
LOWER() dos not work, at least in the way I am using  it in VBA;
SQL SELECT select top 1 VALUENAME FROM [TradingTotals$] WHERE LOWER(VALUENAME)='Trading' And ValueDate =  '29/05/2020' AND CLOSINGMONTH = 'May' ORDER BY VALUEDATE DESC

I also tried double quotes for literals

A:

So at the end there were different issues but mostly due with incorrect query syntax as I am writing SQL as when querying SQL server; not yet up to speed with excel query syntax.
Thanks to all who added useful comments, I am unaware on how to accept an answer from a comment so I am posting this as an answer but no credit to me at all; all credit to the great folks that added comments here.
I am now facing other issues with the insert.. basically even if I pass numbers as long and dates it get stored in excel as general. Even if I format the columns in the spreadsheet as date and number, it get reverted again to general?? but I am opening a new question for this issue


Q:

How to show a textbox, button, etc in a Java Applet?

How can I show common GUI elements such as :

Textbox
Button
Radios/Dropdowns
Labels

etc in a java applet which would be run from a web browser?

A:

This applet tutorial starts from the beginning, and covers GUI components.
There are plenty of other applet tutorials around of course, almost all of which will cover GUI work.


Q:

Asserting that typeclass holds for all results of type family application

I've got a type family defined as follows:
type family Vec a (n :: Nat) where
  Vec a Z = a
  Vec a (S n) = (a, Vec a n)

I'd like to assert that the result of applying this type family always fulfills the SymVal class constraint from the SBV package:
forall a . (SymVal a) => SymVal (Vec a n)

There is SymVal instances a,b, so whenever SymVal a holds, then SymVal (Vec a n) should hold, for any value of n. How can I ensure GHC sees that SymVal is always implemented for the result of the type family application?
However, I don't know how to express this. Do I write an instance? A deriving clause? I'm not creating a new type, simply mapping numbers to existing ones.
Or am I totally on the wrong track? Should I be using a data family, or functional dependencies?

A:

Can't be done. You just gotta put the constraint everywhere. It's a real bummer.

A:

I don't know the precise context in which you require these SymVal (Vec a n) instances, but generally speaking if you have a piece of code that requires the instance SymVal (Vec a n) then you should add it as a context:
foo :: forall (a :: Type) (n :: Nat). SymVal (Vec a n) => ...

When foo is called with a specific n, the constraint solver will reduce the type family application and use the instances
instance ( SymVal p, SymVal q ) => SymVal (p,q)

At the end of that process, the constraint solver will want an instance for SymVal a. So you'll be able to call foo:

if you specify a given value for n, allowing the type family applications to fully reduce, and use a type a which has an instance for SymVal:

bar :: forall (a :: Type). SymVal a => ...
bar = ... foo @a @(S (S (S Z))) ...

baz :: ...
baz = ... foo @Float @(S Z) ... -- Float has a SymVal instance

defer instance search by providing the same context:

quux :: forall (a :: Type) (n :: Nat). SymVal (Vec a n) => ...
quux = ... foo @a @n ...

GHC can't automatically deduce SymVal (Vec a n) from SymVal a, because without further context it cannot reduce the type family application, and thus doesn't know which instance to choose. If you want GHC to be able to perform this deduction, you would have to pass n explicitly as an argument. This can be emulated with singletons :
deduceSymVal :: forall (a :: Type) (n :: Nat). Sing n -> Dict (SymVal a) -> Dict (SymVal (Vec a n))
deduceSymVal sz@SZ Dict =
  case sz of
    ( _ :: Sing Z )
      -> Dict
deduceSymVal ( ss@(SS sm) ) Dict
  = case ss of
      ( _ :: Sing (S m) ) ->
        case deduceSymVal @a @m sm Dict of
          Dict -> Dict

(Note that these obnoxious case statements would be eliminated with type applications in patterns, mais c'est la vie.)
You can then use this function to allow GHC to deduce a SymVal (Vec a n) constraint from a SymVal a constraint, as long as you are able to provide a singleton for n (which amounts to passing n explicitly as opposed to being parametric over it):
flob :: forall (a :: Type) (n :: Nat). (SymVal a, SingI n) => ...
flob = case deduceSymVal @a (sing @n) Dict of
  Dict -- matching on 'Dict' provides a `SymVal (Vec a n)` instance
    -> ... foo @a @n ...


Q:

NSDates and TimeIntervals

I'm struggling to understand how to use NSDates properly.
I have an event that instantiates a timingDate = [NSDate date];
I then later on what to record the time intervals betweeen user's touches.
So I want to find the interval between the timingDate and the user touch in milliseconds.
Then I want to reset the timingDate to be equal to the touchTime so that the next time the screen is touched I can find the differnce between the previous touch and the present touch. I hope that makes sense.  But I am going around in circles because I don't understand how to use NSDates or NSIntervals.  The properties interval touchTime and timingDate are all currently NSDate types - Is this right?
So I've tried a lot of different things like
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    touchTime = timingDate;
    interval  = [[NSDate date] timeIntervalSinceDate:timingDate]; // should be the time difference from when the timingDate was first set and when the user touched the screen.
    touchTime = [[[NSDate date]timeIntervalSinceDate:timingDate]doubleValue];
    timingDate = [NSDate dateWithTimeIntervalSinceReferenceDate:touchTime];
    NSLog(@"Time taken Later: %f", [[NSDate date]timeIntervalSinceDate:timingDate]);
  }

A:

Your code is a bit complex! You just need to calculate the difference between timingDate and the time that the touch occurred, and then set timingDate to the current time so that you can perform this calculation on every touch event.
To find the difference between timingDate and the first touch, you can use NSDate's timeIntervalSinceDate with the current time. This will return an NSTimeInterval value, which represents a time value in seconds with sub-millisecond precision. Here's an example:
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:timingDate];
NSLog(@"Time taken: %f seconds / %f milliseconds",timeInterval,timeInterval*1000);

Then, in order to set your timingDate to the current time, simply use timingDate = currentDate;. This will allow you to continuously measure the time difference between touches.


Q:

Is there a "what links here" feature for GitHub?

I know its issue management system has something similar implemented. From another issue, if we link to another issue (on GitHub of course) the latter will show the source from where it was linked:

However, a better example of a web site that implements that feature really well would be Wikipedia:

The reason I am looking for this: I am interested in learning about other GitHub projects that are based off a project. For e.g.
ng-annotate is a npm project (hosted on GitHub). grunt-ng-annotate is, I believe, based on it. However, in the latter project there is a link saying ng-annotate, but it links to the npm page, which links to the first project I've mentioned.
I am interested in learning of any other projects that are based off ng-annotate.

A:

After googling "find related github projects", I find this service: gazer.
It seems working perfectly.
In your case, ng-annotate related github projects yield many results.


Q:

Are there nontrivial perfect powers of integers that are nontrivial repdigits?

For example, $6^5=7776$ is close, but not quite a repdigit. Heuristically, it seems to me that there should not be any, because the longer a number with  (effectively) random digits is, the less the odds of that number being a repdigit become. So as the integer power in question gets bigger, the odds of it being a repdigit fall off quickly.

A:

I can eliminate a few cases.  Repdigits look like $a(111\cdots1)$.  If $a=2$, then you have
$$2(111\cdots1) = b^k.$$
Since the second factor is odd, at most one factor of $2$ appears in $b^k$, a contradiction since $k>1.$
Similarly $a$ can't be $6.$
If $a=4$, then similar reasoning forces $k=2$ and $b=2c.$ Then you have
$$4(111\cdots1) = (2c)^2$$
$$111\cdots1 = c^2$$
which is impossible the left side is congruent to $3$ modulo $4.$
If $a=8$, it (similarly) forces $k=3$ the equation reduces to
$$111\cdots1 = c^3.$$
This was proved impossible here:
https://mathoverflow.net/questions/132011/can-repunits-be-perfect-cubes
So $a$ can't be even.
Now things get fuzzy.  If $a$ is odd and prime, it seems like writing
$$p(111\cdots1) = b^k$$
should get us somewhere.  Certainly it shows that $p^{k-1}$ divides $111\cdots1.$  But I'm stuck there.   That would eliminate $3, 5,$ and $7$.
That's all I got.


Q:

No puedo trabajar con las propiedades text en Atom, aparecen deshabilitadas

 background-color: red;
  text-align: center;
  text-decoration: overline;
  text-indent: inherit;
  text-overflow: inherit;

en la imagen se ve: ( puede que sea un package que sea necesario, no me había pasado esto antes)

A:

Me sucedió lo mismo hace algún tiempo.
Atom toma por defecto la extensión de tu archivo (.css .html .php, etc) y así mismo aplica a la sintaxis unos colores preestablecidos.
Si esto no sucede de forma automática, o está como texto plano, puedes cambiarlo de la siguiente manera.
Abajo del todo a la derecha vas a ver la sección donde se especifica el lenguaje a usar y por tanto a marcar (en el ejemplo, plain text)

Haciendo clic sobre esa opción, puedes cambiar el tipo de lenguaje que se va a aplicar en la sintaxis, puedes ver que son varios.

Por último, escoge el que deseas usar (puedes hacer este cambio manualmente las veces que desees). Como recomendación, y en caso de no ser así, deja por defecto Auto Detect

Fuente

Actualización

Me quedó vagando tu pregunta en la mente, y me doy cuenta que no había intentado reproducir exactamente tu código CSS en mi editor Atom; para sorpresa mía, ocurre lo mismo que en tu imagen:

Esto sucede porque Atom (por defecto) resalta en color (en archivos CSS en este caso) únicamente las clases, los valores de color (hexadecimal, RGBA, etc), los valores de número (px, % , .rem, etc), valores de duración (s, ms, etc), las pseudo-clases y los pseudo-elementos (:hover, :focus, ::after, ::before, etc) entre otros.
No resalta ni da color a propiedades con valores como display, none, relative, auto, absolute y muchos más valores de tipo "texto".
Puedes validarlo tú mismo, por ejemplo, viendo en Atom la hoja de estilos de Bootstrap.


Q:

How to Connect to Azure database using the standard dotnet web template

I am super excited to start developing .NET on my Mac but getting frustrated trying to figure it all out. So I have a WebApplication created by calling yo aspnet and out of the box it works great. It comes with a connection to a local db stored in the project. Where I am having trouble is connecting it to a remote DB hosted in my azure portal.
My Connection string below directly from my azure portal. I have updated my appsettings.json "DefaultConnection" property to this value (with the username and password missing below) and I am getting errors like "ArgumentException: Keyword not supported: 'server'." I have tried several different connection strings and none are working.
Admittedly I am new to all of this so I am probably missing something simple but in searching online I have yet to find the solution.
Server=tcp:mydbserver.database.windows.net,1433;Initial Catalog=LH;Persist Security Info=False;User ID={your_username};Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;

For reference here is my whole appsettings.json (without username & passwrod...)
{
  "ConnectionStrings": {
    //"DefaultConnection": "Data Source=LH.db"
    "DefaultConnection": "Server=tcp:mydbserver.database.windows.net,1433;Initial Catalog=lighthouseFSQ;Persist Security Info=False;User ID={Username};Password={Password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

Any help is greatly appreciated. FYI I did try this in Windows VS2015 and it worked fine.

A:

By default, the dotnet new -t web tempalte uses SQLite database, so only changing the connection string is not sufficient to change the provider.
You also need to remove the Microsoft.EntityFrameworkCore.Sqlite package from project.json and replace it with Microsoft.EntityFramework.SqlServer (assuming you are using the SQLServer of Azure). Then in your Startup.cs you need to replace the
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));

with
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

and change the namespaces if necessary.
Update
In project.json you just need to change the dependency with Sqlite.
"dependencies": {
  ...
  "Microsoft.EntityFrameworkCore.Sqlite": "1.0.1",
  ...
  }
}

to
"dependencies": {
  ...
  "Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
  ...
  }
}

If there is also a Microsoft.EntityFrameworkCore.Sqlite.Design ch ange that too to Microsoft.EntityFrameworkCore.SqlServer.Design too, it's there for scaffolding etc.


Q:

How do I set Angular 2 ngModel from a firebase observable on a select dropdown

I am trying to set the default value in a select dropdown from a firebase object using angularfire 2. But I don't know how to make it work with setting the default value of the select box. ngModel doesn't allow something like (ngModel)="(default_tax | async)"
code:
public default_tax$:Observable<any>;
public tax$:Observable<Tax>;

ngOnInit(): void {
    this.tax$ = this.db.list(`tax_rates`);
    this.default_tax$ = this.db.object(`settings/default_tax_rate`);
}

template:
<select name="tax_rate" (ngModel)="default_tax.$key" (ngModelChange)="onSelect($event)">
    <option  *ngFor="let tax of (taxes$ | async)" [ngValue]="tax.$key">
    {{tax.name}} - {{tax.rate}}
    </option>
</select>

Firebase object:
account:
    setttings:
         default_tax_rate: "-somekey"
    tax_rates:
         "-somekey":
              "name":"5.5"
         "-someotherkey"
               "anothername":"4.5"

A:

Ok, I found out how to do this. I was writing the ngModel wrong.
WRONG:
(ngModel)="default_tax.$key"
(ngModel)="(default_tax | async)"

CORRECT:
[ngModel]="(default_tax | async)?.$value"

Note that ngModel is wrapped with [] instead of [()] or (). Brackets[] indicate input, where parenthesis() indicate output. Having both [()] is for two-way binding (both input and output).

A great guide to help understand this in more details is http://blog.ng-book.com/the-ultimate-guide-to-forms-in-angular-2/


Q:

Using SQL to work out the average of some, but not all, records

I am trying to work out the SQL to average a series of numbers, but only to include those greater than 0.
For example:
Field
4
5
0
6

SELECT Avg(Field) FROM Table;

gives 3.75. But I want it to ignore the 0 so the average is 5.
SELECT Avg(Field) FROM Table where Field > 0;

works but what if I have more than 1 field:
Field1   Field2
4        2
5        0
0        3
6        4

SELECT Avg(Field1), Avg(Field2) FROM Table;

Using
SELECT Avg(Field1), Avg(Field2) FROM Table where Field1 >0 and Field2>0;

will not work
How do I do that? Note the numbers can be anything from 0 to 100

A:

Just filter out 0 using the where clause.
SELECT Avg(Field) FROM Table Where Field > 0

A:

You can use a conditional expression:
SELECT
  Avg(case when Field1 > 0 then Field1 end),
  Avg(case when Field2 > 0 then Field2 end)
FROM table


Q:

Find number of groups, that can be formed from two lists

Goal of task is to group animals, so the enemies not in the same cage.
There are m pairs (a[i],b[i]) which imply that animals a[i] and b[i] are enemies and should not be kept in one cage.
Given n=3 animals and m=3 pairs of enemies, a=[1,2,3] and b=[3,3,1]
Animal 1 is enemy of animal 3 and 3 is enemy of 1 and 3. There four are possible groupings {1,2},{1},{2},{3}. Note that the intervals are along  the original line of animals numbered from 1 to n i.e [1,2,3]. They can't be reordered or skipped. So grouping {2,1} and {1,3} will be wrong.
I've used just hash map to map out all enemies and go through all animals, but it's not effective.
a = [1,2]  # group a
b = [3,5]  # group b

n = 5  # number of animals

def groupAnimals(n,a,b):
    h = {}
    groups = []
    for index, animal in enumerate(a):
        h[animal] = b[index]
        h[b[index]] = a[index]

    for i in range(1,n+1):
        groups.append([i])
        curr = [i]
        for j in range(i+1,n+1):
            if j - curr[-1] > 1:
                break
            if j in h:
                if h[j] not in curr:
                    curr = curr.copy()
                    curr.append(j)
                    groups.append(curr)
            else:
                curr = curr.copy()
                curr.append(j)
                groups.append(curr)

    return len(groups)

The result of above code is correct, but some test cases are failed.
How to improve the code? Is there better solution?

A:

There are some issues in your code:

What if an animal has more than one enemy? The value of the enemy is overwritten. Try with a = [3,3] and b = [1,5]: h[1] = 3 and h[3] = 5, hence 1 and 3 may be in the same cage but they are enemies;
you are building only a part of the powerset of 1..N because you never skip a j: you build [1], [1,2], [1,2,3], ..., then [2], [2,3], ... but never [1,3]. Proof: try with a=[], b=[] and n=5. You should get 2^5-1 = 31
I don't understand the meaning of
if j - curr[-1] > 1:
    break

It removes acceptable groups, like [1, 2, 4] in your example.

To address the first issue, you have to store the group of enemies (maybe void) for each animal. BTW, instead of playing with indices (enumerate), you can zip a and b to get the enemies by pairs:
def compute_enemies(N, a, b):
    enemies = {}
    for animal, other in zip(a, b):
        enemies.setdefault(animal, set()).add(other)
        enemies.setdefault(other, set()).add(animal)
    return enemies

The setdefault get the set mapped to the key or create a new empty set.
>>> compute_enemies(5, [3, 3], [1 ,5])
{3: {1, 5}, 1: {3}, 5: {3}}

To adress the second issue, you have to compute all subsets of a range(1, N+1). That's the powerset of this range. Here's a recursive definition:

PS([1, ..., N]) = PS([1, ..., N-1]) u {S u {N} for all S in PS([1, ..., N-1])} (all the previous sets, and the same + element {N})
PS([]) = {}

In python:
def powerset(N):
    if N == 0:
        yield set()
    else:
        for s in powerset(N-1):
            yield s
            yield s | {N}

>>> list(powerset(3))
[set(), {3}, {2}, {2, 3}, {1}, {1, 3}, {1, 2}, {1, 2, 3}]

Note: including the empty set and the range itself, you have 2^N subsets. The keyword yield creates a generator (yield has also a role in co-routines, but that's another story), hence the list(...) to collect the elements.
Now, we have to adapt this function to add the enemy parameter. We check if N is an enemy before yielding s | {N}:
def group_animals_aux(N, enemies):
    if N == 0:
        yield set()
    else:
        for s in group_animals_aux(N-1, enemies):
            yield s
            if N not in set(y for x in s for y in enemies.get(x, set())): # union of all sets of enemies
                yield s | {N}

Some details on set(y for x in s for y in enemies.get(x, set())): 1) enemies.get(x, set()) returns either the enemies of x, or an empty set. 2) set(y for x in s for y in ...) takes all elements of s (one of the subsets) (for x in s), then all enemies of this element, and build a new set with all the enemies. Bascially, it perfoms a union of all enemies of animals in the set.
To avoid to repeat this computation, we can carry the enemies of the group along with the group:
def group_animals_aux2(N, enemies):
    if N == 0:
        yield set(), set()
    else:
        for s, e in group_animals_aux2(N-1, enemies):
          yield s, e # s: animals, e: union of all enemies
            if N not in e:
                # add N to the animals, and its enemies to the enemies of the group
                yield s | {N}, e | enemies.get(N, set())

>>> enemies = compute_enemies(5, [3, 3], [1 ,5])
>>> [s for s, _ in group_animals_aux2(5, enemies)]
[set(), {5}, {4}, {4, 5}, {3}, {3, 4}, {2}, {2, 5}, {2, 4}, {2, 4, 5}, {2, 3}, {2, 3, 4}, {1}, {1, 5}, {1, 4}, {1, 4, 5}, {1, 2}, {1, 2, 5}, {1, 2, 4}, {1, 2, 4, 5}]

Let's put the parts together:
def group_animals(N, a, b):
    enemies = compute_enemies(N, a, b)
    return len(list(group_animals_aux2(N, enemies))) - 1 # remove the empty cage

>>> group_animals(5, [3, 3], [1 ,5])
19

Remark 1: given the complexiy of the algorithm O(2^N) I hope that you don't have too many animals, or that these animals have a lot of enemies.
Remark 2: if you were looking for the minimum number of cages to lock your animals, you should consider @tobias_k comment: this is would be the clique cover problem, more precisely a graph coloring problem. See this question and the answer for more information: How to group and merge objects, if some are incompatible with each other?.


Q:

mule filter not stopping flow processing, picks up after choice end tag

In this flow, I have verified that when the filter returns 'false' the flow continues anyway. But the payload is slightly different. I need to stop these messages completely.

<foreach doc:name="For Each">
            <choice doc:name="Choice">
                when expression="#[payload['event'] contains 'delete' ]">
                    <!-- this path is unrelated to this question -->
                </when>
                <otherwise>
                    <flow-ref name="getMessages" doc:name="FlowToGetMessages"/>
<!-- this (below) will extract the single row value (a Map) from the array returned from above flow -->
                    <collection-splitter doc:name="Collection Splitter"/>
                    <expression-filter expression="#[payload['activity'] != null && payload['activity'] != "" ]" doc:name="Block Empty Rows"/>
                    <custom-filter class="package.BlockNullAnnouncementEvents" doc:name="Block null"/>
                </otherwise>
            </choice>
...

The next processor (after the choice) gets
A) a single value if the message passes the filter test BlockNullAnnouncementEvents or
B) an array with one value if the null is present and the filter fails the same test
This appears to me that, if a message fails the filter test, then the result of the call to the flow getMessages is returned to the top of the for-each which passes it on to the next part of the flow after the choice branch that contains the filter.

A:

After its execution the foreach will restore the original message as explained here
If you want the execution to stop you should use a message filter and configure the Throw On Unaccepted to true


Q:

Changing the async wait time in Polymer

Using Polymer's async function is there a way to change the remaining wait time after it's been called? To contextualise usage, a popup modal is currently setup to disappear after 3 seconds once its opened using async, but it needs to extend wait time if the user hovers over it.
Thanks

A:

No, Polymer has no API to change the timeout of an active timer, but you could stop the timer with cancelAsync() and restart it with another call to async().
// initially...
this._timer = this.async(() => ..., 5000);

// on mouse-hover...
this.cancelAsync(this._timer);
this._timer = this.async(() => ..., 2000);


Q:

HierarchicalDataTemplate what is it supposed to do?

Basically i have a eeview that has a bunch of objects in it and the treeview needs to bind the same properties.
here is the code im using and it doesnt seem to work
    <TreeView ItemsSource="{Binding Drives}">
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate>
                <TreeViewItem Header="{Binding Name}" ItemsSource="{Binding Folders}" IsExpanded="{Binding IsExpanded, Mode=TwoWay}">
                    <TreeViewItem.ItemTemplate>
                        <HierarchicalDataTemplate>
                            <StackPanel>
                                <TreeViewItem Header="{Binding Name}" ItemsSource="{Binding Folders}" IsExpanded="{Binding IsExpanded,Mode=TwoWay}">
                                    <TreeViewItem.ItemTemplate>
                                        <HierarchicalDataTemplate>
                                            <TreeViewItem Header="{Binding Name}" ItemsSource="{Binding Folders}" IsExpanded="{Binding IsExpanded,Mode=TwoWay}"/>
                                        </HierarchicalDataTemplate>
                                    </TreeViewItem.ItemTemplate>
                                </TreeViewItem>
                            </StackPanel>
                        </HierarchicalDataTemplate>
                    </TreeViewItem.ItemTemplate>
                </TreeViewItem>
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>

Basically when i get to the third level of treeview items i just get the Namespace+ObjectName.
Isnt the DataTemplate supposed to flow on and on ?

A:

More like this
    <TreeView ItemsSource="{Binding Drives}">
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate ItemsSource="{Binding Folders}">
                <TextBlock Text="{Binding Name}"></TextBlock>
                <HierarchicalDataTemplate.ItemContainerStyle>
                    <Style TargetType="TreeViewItem">
                        <Setter Property="IsExpanded" Value="{Binding IsExpanded,Mode=TwoWay}" />
                    </Style>
                </HierarchicalDataTemplate.ItemContainerStyle>
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>


Q:

Finding $x^4 + y^4 + z^4$ using geometric series

This is a problem from the 2001 Stanford Math Tournament Algebra section.
$$$$Given that $$x+y+z=3$$ $$x^2 + y^2 + z^2 = 5$$$$x^3+y^3+z^3=7$$Find $x^4+y^4+z^4$. $$$$My friend claimed that he was able to solve this question using geometric series, i.e. adding the above three equations together and forming geometric series with three terms, but I can't see how he solved it using that method. I solved it using the method described in the solutions document, but I haven't seen a solution using geometric series. Can anyone find a way to solve the problem using geometric series? Any help with this problem would be great. Thanks for the help.

A:

This is a rather encumbered solution for a not-as-hard problem, and it is the only way I see to make sense of what your friend is saying. On the other hand, it is cool that it let us know about Newton's identities and their proof using generating functions.
Let us form the formal series \begin{align}F(x,y,z,t)&:=(x+y+z)t+(z^2+y^2+z^2)t^2+(x^3+y^3+z^3)t^3+\ldots\\&=3t+5t^2+7t^3+at^4+\ldots,\end{align}
where $a:=x^4+y^4+z^4$ is the number we want to find.
Forming this power series is kind of adding the given equations (as your friend suggested), but we multiply them first by $t,t^2,t^3,...$, respectively, before adding.
Consider the polynomial \begin{align}G(x,y,z,t)&:=-1+(x+y+z)t+(xy+xz+yz)t^2-(xyz)t^3\\&=-1+3t+(xy+xz+yz)t^2-(xyz)t^3\end{align}
We multiply $F$ times $G$. It happens that we get a polynomial:
\begin{align}
FG&=\left(\sum_{k=1}^{\infty}(xt)^k+\sum_{k=1}^{\infty}(yt)^k+\sum_{k=1}^{\infty}(zt)^k\right)G\\
&=-\left(\frac{xt}{1-xt}+\frac{yt}{1-yt}+\frac{yt}{1-xt}\right)(1-xt)(1-yt)(1-zt)\\
&=t\left((-x)(1-yt)(1-zt)+(-y)(1-xt)(1-zt)+(-z)(1-xt)(1-yt)\right)\\
&=-(x+y+z)t+(xy+xz+yz)t^2-(xyz)t^3\\
&=-3t+(xy+xz+yz)t^2-(xyz)t^3
\end{align}
In the second equality we used the sum of the geometric series more or less like your friend said.
Comparing coefficients of the multiplication $FG$ with the result in the last line we get (the Newton's identities for the values in this problem)
\begin{align}
2(xy+xz+yz)&=9-5\\
3xyz&=3(xy+xz+yz)-15+7\\
0&=3(xyz)-5(xy+xz+yz)+21-(x^4+y^4+z^4)
\end{align}
From these, substituting from top to bottom, we find the value of $x^4+y^4+z^4$. Notice that the method allows us to continue using the equalities between coefficients of higher degree in $t$ to compute $x^5+y^5+z^5$, $x^6+y^6+z^6$, and so on ...


Q:

multi thread synchronize two method java

I have a multithreaded server and request are coming to server.
There is a scenario like we have two types of client.
One is customer
Other is admin
Customer can send request
Customer can cancel request
admin can accept request
there are two different function
One is cancel request function which is method A
other is accept request function which is method B
Some time customer request it is marked as pending.
Now admin respond with accept and meanwhile customer cancel
so admin think he accept the request
and customer think he cancel the request.
so is there anyway to synchronize the cancel and accept method.
//Cancel Request
public void A() {
    int currentrequeststate = app.sharedData().getMap("users").get(user_id); //let say this is read as pending
    if (currentrequeststate == RequestState.PENDING) {
        currentrequeststate = RequestState.CANCEL;
        app.sharedData().getMap("users").put(user_id, currentrequeststate);
        //cancel it and sending cancel message
    }
}

//Accept Request
public void B() {
    int currentrequeststate = app.sharedData().getMap("users").get(user_id); //there is a chance this also read as pending
    if (currentrequeststate == RequestState.CANCEL) {
        //sending no trip to accept might be canceled
    } else {
        currentrequeststate = RequestState.ACCEPTED;
        app.sharedData().getMap("users").put(user_id, currentrequeststate);
        //Accept it and sending accept message
    }
}

as there will be multiple thread and both method can be run by differnt thread concurrently.
so there is a chance that both method read current currentrequeststate as pending
the first Method A will cancel the request
the second Method B will accept the request

A:

I am not fully familiar with the exact problem which you're
solving but I would try something along these lines below.

I would use an array str of type String[1] for the statuses, and not just Strings; this way I won't change ever the reference str which I synchronize on (all I change is the String object that str[0] points to).
This also allows me to execute two methods A at the same time by different threads, if they are in the context of different user_ids. My synchronization is on str i.e. per user_id only. I don't block threads on A if they do calls for different user_ids. Actually I think user_id should be parameter of these two methods.
Note how I am comparing Strings (by using equals, not ==)
I assume the PENDING, ACCEPTED, CANCELLED, etc. constants in RequestState are Strings. If this assumption is not true, just rework the code slightly following the same logic.
// Cancel Request
public void A() {
    String[] str = app.sharedData().getMap("users").get(user_id);
    synchronized(str){
        String currentrequeststate = str[0];
        if (RequestState.PENDING.equals(currentrequeststate) {
            str[0] = RequestState.CANCELLED;
            // cancel it and sending cancel message
        }else if (RequestState.ACCEPTED.equals(currentrequeststate)){
            // throw exception here (or take whatever action appropriate)
            // as this request was already accepted by the admin;
            // so it is too late for the user to cancel it
        }
    }
}

// Accept Request
public void B() {
    String[] str = app.sharedData().getMap("users").get(user_id);
    synchronized(str){
        String currentrequeststate = str[0];
        if (RequestState.CANCELLED.equals(currentrequeststate)) {
            // Already cancelled, admin cannot accept it now as it's too late;
            // so take whatever action is appropriate in this case
        } else {
            str[0] = RequestState.ACCEPTED;
            // OK, accept it and sending accept message
        }
    }
}


Q:

fetchRequest question

in core data , I search using fetchRequest and predicate like the following
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
             entityForName:@"Study"
    inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:
                                @"( StudyID == %@ )",self.StudyID]];

NSArray * StudyList  = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

how to check if there a return values or not

A:

Do something like:
if(!StudyList){
    //handle fetch request error here
} else {
    //success!
    if([StudyList count] > 0){ //if array not empty
        //do stuff with StudyList contents here
        NSLog(@"StudyList contents: %@", StudyList);
    }
}

Hope that helps.


Q:

Integral convergence with partial fraction

I think
$$
\int_2^\infty \frac{2x+3}{\left(x^2−1\right)x^2}\ dx
$$
should converge,but after i use partial fraction, i get the following bunch of logarithms and the limit of those diverges:
$$
\frac3x - \frac{\ln(|x+1|) + 4 \ln (|x|) - 5\ln(|x-1|)}{2} + C
$$

A:

The limit of the numerator with the logarithms is an indeterminate form $\infty-\infty$, so you cannot simply conclude that it diverges. You have to investigate further. Note that for $x\geq 2$, you can remove the absolute value signs.
$$\begin{align}
\ln(x+1)+4\ln(x)-5\ln(x-1)&=\ln(x+1)+\ln\left(x^4\right)-\ln\left(\left(x-1\right)^5\right)\\
&=\ln\left(\frac{(x+1)x^4}{(x-1)^5}\right) \\
&=\ln\left(\frac{x^5+x^4}{(x-1)^5}\right) \\
&=\ln\left(\frac{1+\frac{1}{x}}{\left(1-\frac{1}{x}\right)^5}\right)
\end{align}$$
which converges to $\ln(1)=0$ as $x\to\infty$. And $\frac{3}{x}\to 0$ is clear. So the integral is actually convergent and is equal to $-F(2)$ where $F(x)$ is the antiderivative you obtained.


Q:

google-api-php-client download zip from Git has only one directory src/Google

Git : google-api-php-client
I only see
src/Google

how do I download the other directory ?
/example

/style

/tests

Thank you.

A:

Install Git on your computer
Run
git clone https://github.com/google/google-api-php-client

You will have the whole directory structure.


Q:

Firebase does not save data in database

Good morning, could someone tell me what are the ports that realtime database usese? I believe it is not the same as FCM or am I mistaken?
The port 80 and 443 are released, but when I go to send something to the database it does not send if I change to a network where everything is released it sends someone would have any idea what it can be?

A:

If someone wants to release the firebase in the firewall, you have to apply a rule to the following ips:
74.125.0.0/16
35.192.0.0/12