Where can I get a one-off server of Active Directory for Developing against?

Question: We're not a windows shop, but one of our products is going to need to optionally integrate with Active Directory - things like SSO etc.
I'd really rather not go through the rigamarole of setting up a whole server just to develop against it and then leave it hanging around for testing purposes.
Is there a simple cloud-based service where I can purchase a server running active directory for a month or two just for development purposes? I looked into Amazon EC2 but it looks like you may still need to go through a significant set up (I may be wrong on this).
Answer: Even if you find a provider that can do hosted AD, I don't know if you'll be able to avoid the setup and configuration that goes along with it. Active Directory can be configured in so many different ways that adequately testing against it really demands more than just a default, vanilla AD domain. (I've had to deal with far too many applications that made unwarranted assumptions about how Active Directory is structured, and it's infuriating. Accounts aren't always in the default "Users" container! You can have multiple domains in a forest! Sometimes the CN isn't the userid! Aargh!)
Anyway... if you really do want to host AD on a cloud service, it can be done, but it's rare, and it sounds like it's fragile. Here's a link to a discussion on the Amazon Web Services developer forum about using AD on EC2:
http://developer.amazonwebservices.com/connect/message.jspa?messageID=150845
The document provided by garysu22 looks particularly useful, but it's also 25 pages of tweaks and workarounds... so again, lots of setup and configuration.
By the way, I'm concerned that Amazon's whitepaper on hosting AD on EC2, which used to be here...
http://developer.amazonwebservices.com/connect/entry.jspa?externalID=2435
...seems to have gone missing. I'm not sure what that means, but it would make me nervous.
(EDIT: I'm not the only one: http://justinbrodley.com/?p=60)
Now for an answer to a question you didn't ask...
I've developed against Active Directory very successfully using a local virtual machine running Windows Server and AD. I highly recommend it. You'll need a reasonably powerful machine with plenty of memory and storage, of course, but any modern development box should handle it without breaking a sweat.
With this sort of setup, you get all the niceties of a VM environment, like snapshot and rollback (so you can break stuff, even deliberately, and fix it quickly) and easy network isolation (you can make the VM visible to just the host dev box, for example)... and you can make the entire thing go away when you don't need it by just suspending the VM.
Of course, you'll still have to go through the initial AD setup and configuration, but for the kind of AD setup(s) you'll need, that's pretty easy. If you're going to be doing any serious development against AD, that's valuable experience you'll want to have anyway. Active Directory is its own sort of beast, with more than its fair share of idiosyncrasies; the better you understand it, the happier your customers will be.
Good luck!
Comment: Great answer, even though it's unfortunately what I'd rather not hear. I'd vote you up if I had enough reputation to do so. ;)

Thank you at any rate!
Answer: I think you want AD Lightweight Directory Service. You can run it on any server without going through the whole AD setup/hardening process. You won't be able to use all of the AD tools against it (Users and Computers, and Trusts MMC plugins), but it will behave like AD for prototyping and development. If you see posts about ADAM (Active Directory Application Mode), AS LDS is just the latest name of the same idea.


Calling the value of an array in subroutine

Question: I am using Force 2.0 compiler and editor. I want to call the value of the existing array KM(1:M) on the following subroutine to be used in the calculation in the main program EIKM(1:M), but the values obtained are not in accordance with the value of the array. Can you tell me what is wrong and what should I do?
  PROGRAM GENERATES_EIKM

  IMPLICIT NONE

  INTEGER I, M, N
  PARAMETER (M=65, N=3)
  REAL EIKM(1:M)

  REAL ALFA, EPSILON, NU, PI
  REAL U2RMS, KE, KEFISIENSI, KALI, KALE
  REAL KM(1:M), LS

  REAL KMLOW, KMHIGH, DELTAKM

  KMLOW=100
  KMHIGH = 10000
  DELTAKM = (KMHIGH-KMLOW)/(M-1)

  PI = 3.14
  ALFA = 1.453
  EPSILON = 10
  NU = 7
  LS = 23
  KE = ALFA*9*PI/(55*LS)
  KEFISIENSI = (EPSILON**(1/4))/(NU**(-3/4))

  CALL CALLING_THE_VALUE_OF_KM (M)

  WRITE (*,*) 'CHECKING THE VALUE OF KM AT DATA NUMBER 2 : ', KM(2)

  DO I=1,M
     U2RMS = (2/3*KM(I))**2
     KALI = KM(I)/KE
     KALE = KM(I)/KEFISIENSI
     EIKM(I) = ALFA*(U2RMS/KE)*((KALI**4)/((1+KALI**2)**(17/6)))*
 &           EXP(-2*(KALE**2))
     WRITE (*,*) 'THE VALUE OF EIKM AT (I) ', I, EIKM(I)
  END DO

  PAUSE
  END

  SUBROUTINE CALLING_THE_VALUE_OF_KM (M)

  REAL KM(1:M)
  INTEGER I
  REAL KMLOW, KMHIGH, DELTAKM
  KMLOW=100
  KMHIGH = 10000
  DELTAKM = (KMHIGH-KMLOW)/(M-1)

  WRITE(*,*) 'START OF CALLING_THE_VALUE_OF_KM'
  DO I=1,M
     KM(I) = KMLOW + DELTAKM*(I-1)
     WRITE(*,*) I, KM(I)
  END DO
  WRITE(*,*) 'END OF CALLING_THE_VALUE_OF_KM'
  WRITE(*,*) '--------------------'

  RETURN
  END

Comment: Move the `end` which matches the program statement to the end of the source file.  In its place write the word `contains`.  Recompile and fix any errors that the compiler finds.  As your code is structured the compiler can't ensure that the argument passed to the subroutine matches what is expected.
Comment: Furthermore, a beginner in 2016 should not be learning Fortran 77, there are many useful features which have been added to the language in the more recent versions and it simply doesn't make sense to confine yourself to a 40-year old version of the language.  Yes, you still need to know Fortran 77 for integration with the enormous existing codebase, but no, you don't need to confine yourself to writing it.  It's funny, but I never see questions on SO that start *I'm learning Java 2 ...*
Comment: Somebody somewhere seems to still be teaching people F77...
Comment: @HighPerformanceMark i am using fortran 77 language, and in my compiler there is not implicit funtion like 'contains' .This is my first time to make such a program to solve an equation, my supervisor told me to use fortran77 because it can be run in any computer. Please help me Master!!
Comment: You need to start debugging, and those integer/integer may be better as 2.0/3.0 and 1.0+Kali and 17.0/6.0 and -2.0 * probably easiest to say "real PARAMETER :: factor1 = 2.0/3.0" etc . All that stuff that @HighPerformanceMark mentioned are part of a sage approach.
Comment: *i am using fortran 77*  Not if you write `implicit none` you're not.  Strictly speaking that wasn't added until the 90 edition of the language
Answer: I would put IMPLICIT NONE in your subroutine. If M is defined as an integer or not then that would help. You could also put INTENT(IN) on M and see if the compiler also does fortran90. If the subroutine is supposed to output something then you will need that inside the (). You proby want...:
F90:
Subroutine Callingthevalue_of_KM(M, KM)
IMPLICIT NONE
INTEGER            , INTENT(IN   ) :: M
REAL, DIMENSION (M), INTENT(INOUT) :: kM

If that compiles then it must be force 2.0.9+
And then you probably do not need M
Subroutine Callingthevalue_of_KM(KM)
IMPLICIT NONE
REAL, DIMENSION (:), INTENT(INOUT) :: kM
INTEGER                            :: M

M = Size(kM)
... Or do the loops a DO I = 1, SIZE(kM)

F77:
Subroutine Callingthevalue_of_KM(M, KM)
IMPLICIT NONE
INTEGER   M
REAL      kM(M)

In all those cases km will be "returned" via the reference for km, with updates values on km then known by the main.
The other way for kM to be known inside and outside is a COMMON, but I believe it is conceptually easier to shy away from them at this point.
Comment: For the assumed-shape version, more substantial changes (explicit interface provision) are required than just adding `(:)`.
Comment: @Holmz it is not working. For example, the answerr of calling data number 2 is still 0.000 . Please help me master!
Comment: Try this after the call to the subroutine and see what you get....

WRITE (*,*) 'CHECKING THE VALUE OF KM AT DATA NUMBER (1:5) : ', KM(1:5)

Doing it inside the subroutine would also be worthwhile.


Http Trigger Azure Function in Docker with non anonymous authLevel

Question: I am playing around with an Http Triggered Azure Functions in a Docker container. Up to now all tutorials and guides I found on setting this up configure the Azure Function with the authLevel" set to anonymous.
After reading this blog carefully it seems possible (although tricky) to also configure other authentication levels. Unfortunately the promised follow up blogpost has not (yet) been written.
Can anyone help me clarify on how I would go about and set this up?
Comment: They seem to have a backlog item and an open issue for that on Github https://github.com/Azure/azure-functions-core-tools/issues/29
Comment: Thanks for your feedback, although it is not quite the same situation. When running in a Docker container the authorization part works. When I configure the Http trigger with `authLevel` set to `function` and call the function I receive a 401 error. Meaning I need to supply the right key but how do I get access to the key is the question. The same goes for the Admin API. It is there but I cannot get to it because I don't know how to get the OAuth token.
Comment: Sorry than I missed the point in your questions. So you want to set/get the function key right?
Comment: The secrets should reside in a json file in the file system beside the function in the container. There is a post addressing a secret rotation topic mentioning the details. http://fabriccontroller.net/azure-functions-reset-the-secret-of-your-httptrigger-functions/
Comment: @SebastianAchatz, again thanks for the reply. When published to Azure I indeed see the mentioned json files. However they only contain a timestamp (most likely when they were created). In my docker container these json files are missing, and probable could add one if I'd only knew what exactly to put in to them (I am guessing only a timestamp won't cut it, even if so the key will be an encrypted representation of the timestamp and I don't know which encryption technique is used). So this definitely gave me some extra insight but doesn't solve my problem yet.
Comment: @MauritsvanBeusekom Locally in a docker container, even though the authorization works but we don't have any key to access just like the github issue says. After we publish the container to Azure, we can get function keys in portal directly.
Comment: @JerryLiu thank you very much for this reply. If I understand correctly you are saying this is not supported at the moment. I have also left a comment at the github issue to indicate that there are more use-cases for this scenario then mentioned in the original issue.
Comment: @MauritsvanBeusekom It seems this feature is not urgent and won't be added in short term, perhaps it's time to contact the blog author to teach us how to achieve that tricky magic.
Answer: To control the master key the Function host uses on startup - instead of generating random keys - prepare our own host_secrets.json file like
{
    "masterKey": {
        "name": "master",
        "value": "asGmO6TCW/t42krL9CljNod3uG9aji4mJsQ7==",
        "encrypted": false
    },
    "functionKeys": [{
        "name": "default",
        "value": "asGmO6TCW/t42krL9CljNod3uG9aji4mJsQ7==",
        "encrypted": false
    }]
}

and then feed this file into the designated secrets folder of the Function host (Dockerfile):
for V1 Functions (assuming your runtime root is C:\WebHost):
...
ADD host_secrets.json C:\\WebHost\\SiteExtensions\\Functions\\App_Data\\Secrets\\host.json
...

for V2 Functions (assuming your runtime root is C:\runtime):
...
ADD host_secret.json C:\\runtime\\Secrets\\host.json

USER ContainerAdministrator
RUN icacls "c:\runtime\secrets" /t /grant Users:M
USER ContainerUser

ENV AzureWebJobsSecretStorageType=files
...

The function keys can be used to call protected functions like .../api/myfunction?code=asGmO6TCW/t42krL9CljNod3uG9aji4mJsQ7==.
The master key can be used to call Functions Admin API and Key management API.
In my blog I describe the whole journey of bringing V1 and later V2 Functions runtime into Docker containers and host those in Service Fabric.
for V3 Functions on Windows:
ENV FUNCTIONS_SECRETS_PATH=C:\Secrets
ENV AzureWebJobsSecretStorageType=Files
ADD host_secrets.json C:\\Secrets\\host.json

for V3 Functions on Linux:
RUN mkdir /etc/secrets/
ENV FUNCTIONS_SECRETS_PATH=/etc/secrets
ENV AzureWebJobsSecretStorageType=Files
ADD host_secrets.json /etc/secrets/host.json

Comment: @Panzercrisis I attached 2 samples how we now do it for V3 on Windows and Linux
Comment: Could you put the information in the answer itself, and not just referencing your own blog?
Comment: Thanks for the answer, giving +1. Is there any MS documentation related to host_secret.json anywhere?
Comment: @OSP I guess not as this file is only internal to the Functions host
Comment: Sorry, how do you apply this to Linux containers?
Comment: If we force a host.json file with Master keys in the container, then a release in production will have the same master secrets as a developpement or uat releases.  For me this is a very High security risk. Either the developpers have access to master keys or the dev, uat and production container images should be compiled with different host.json files. And in this case this is a risk that what is tested is completely different that what is running in live production environment.
Answer: I found a solution for me, even though this post is out of date. My goal was to run a Http Trigger Azure Function in Docker container with function authLevel. For this I use the following Docker Image: Azure Functions Python from Docker hub.
I pushed my created container to an Azure Container Registry after my repository was ready there. I wanted to run my container serverless via Azure Function. So I had followed the following post and created a new Azure Functions in my Azure Portal.
Thus, the container content corresponds to an Azure Function Image and the operation of the container itself is implemented through Azure by an Azure Function. This way may not always be popular, but offers advantages to host a container there. The container can be easily selected from the Azure Container Registry via Deployment Center.
To make the container image accessible via function authLevel, the Azure Function ~3 cannot create a host key as this is managed within the container. So I proceeded as follows:

Customizing my function.json

"authLevel": "function",
"type": "httpTrigger",

Providing a storage account so that the Azure Function can obtain configurations there. Create there a new container.

azure-webjobs-secrets

Create a directory inside the container with the name of your Azure Function.

my-function-name

A host.json can now be stored in the directory. This contains the master key.

{
    "masterKey":
    {
        "name": "master",
        "value": "myprivatekey",
        "encrypted": false
    },
    "functionKeys": []
}

Now the Azure Function has to be configured to get access to the storage account. The following values must be added to the configuration.

AzureWebJobsStorage = *Storage Account Connection String*
WEBSITE_CONTENTAZUREFILECONNECTIONSTRING = *Storage Account Connection String*
WEBSITE_CONTENTSHARE = *my-function-name*

From now on, the stored Azure Function master key is available. The container API is thus configured via authLevel function and only accessible with the corresponding key.
URL: https://my-function-name.azurewebsites.net/api/helloworld
HEADER: x-functions-key: myprivatekey


How to configure Web Api access as Azure Active Directory Graph API

Question: I have setup WebApi application and under permissions it has access to Windows Azure Active Directory.
The application is able to access the graph api, and there is no prompt for the user to login.
How can I achieve a similar setup for my WebApi? I want only applications that have permissions setup to access it. I set it up this way: http://bitoftech.net/2014/09/12/secure-asp-net-web-api-2-azure-active-directory-owin-middleware-adal/
But unlike when accessing the graph api for "Windows Azure Active Directory", it prompts for a login.
Answer: You need to use a different overload of AcquireTokenAsync if you don't want to be prompted to authenticate. This essentially means using a secret for authentication of your application.
<code>string tenantId = "[your domain, such as contoso.onmicrosoft.com]";
string clientSecret = "[Get this from the CONFIGURE page in the portal]";
string resAzureGraphAPI = "https://graph.windows.net";

var context = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantId));

ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
AuthenticationResult result = await context.AcquireTokenAsync(resAzureGraphAPI, clientCred);
</code>


Model Choice Field - get the id

Question: I am busy trying to get the id only in integer format preferably for the ModelChoiceField. I get the list to display but get's returned in a string format. Please helping me in retrieving the id of ModelChoiceField. I think I need to do this in the view.
forms.py
class ProjectForm(forms.ModelForm):
    items = forms.ModelChoiceField(queryset=Project.objects.all())

    class Meta:
        model = Project
        fields = ['items']

models.py
class Project(models.Model):
    items = models.IntegerField(default=0, blank=True, null=True)

views.py
def ProjectView(request):
    form = ProjectForm(request.POST)

    if request.method == 'POST':
        if form.is_valid():
            save_it = form.save(commit=False)
            save_it.save()
            return HttpResponseRedirect('/')
    else:
        form = ProjectForm()

return render(request, 't.html', {'form': form })

Comment: I don't understand what problem you're trying to solve here.. What list displays where? what is returned in a string format?
Comment: Can you please tell us what you are trying to do here, because your models and your form don't make sense.
Comment: A dropdown list of a list of Projects gets displayed in the items variable. I am trying to get the id of queryset=Project.objects.all() and send it to the model.
Answer: From what I can tell, items should never be an IntegerField. Your usage has it set up to be a ForeignKey to a Project so you should just make that explicit
items = models.ForeignKey('self', null=True, blank=True)

Possibly with a better descriptive name than items.
Then, you don't need to define anything on the form, it just becomes a standard model form, with a standard model form usage.
Comment: Okay, thanks. This is what I tried initially and it worked. But let's say I will use the Project as a Lookup Table for several variables in the Project Model? Then the Lookup Table will not work.
Comment: @CodingBear - That doesn't make any sense... It sounds like you need to rethink about your actual usage and how your models facilitate that.
Comment: Thanks @Sayse. How would I go about implementing a lookup table then?

Model Choice Field - get the id


Display a QDialog on mouse over

Question: I wanted to know how I can display a QDialog on mouse over.
I know how I can setup a context menu but I would like a QDialog on mouse over.
This is what I am doing (which apparently isnt working)
<code>void mouseMoveEvent( QMouseEvent * event )
{
    QPoint p = this->mapFromGlobal(QPoint(0,0));
    d->move(p); //d is the dailog
    d->show();
}
</code>
The dialog opens up on the top left corner of the screen. I want it to open up next to the widget that has the mouseMoveEvent
Answer: Create the QDialog elsewhere, and just call show() on it from the mouseMoveEvent() on the QWidget your hovering over
Comment: Thanks. Now how do I make the QDialog popup from a specific location ?
Comment: Take a look at the QWidget documention http://qt-project.org/doc/qt-5/qwidget.html#pos-prop
Comment: You'll probably want the move() function, and set it to be some offset of the current mouse position (via QCursor::pos())
Comment: I am moving the dialog but it still appears on the top left corner of my screen
Comment: where are you moving it to?
Comment: I want the Qdialog to appear next to the widget that has the overriden mouseMoveEvent. Instead the Qdialog appears way off. I want to set the corrdinates of Qdialog
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/56224/discussion-between-yankee2905-and-rajeshwar).

Display a QDialog on mouse over


how to change font color in selected/focused ListView items?

Question: I am struggling with this which apparently is a very simple effect but incredibly haven't found any intutitive way for doing it in Android.
I have a ListView and I managed to customize the background images so the selected item gets highlighted by getting a new background drawable. This I do creating a new style where I set the android:listSelector attribute to point a StateListDrawable where I have specified which drawables to use for every state.
However each ListView item is a LinearLayout where i have two TextViews. My goal is to be able to change the text color of these child views whenever the parent is selected or pressed, at the same time as the background drawable does. I know there is a ColorStateList but haven't been succesful setting that up.
Has anybody succeed getting something like this to work?
Thanks.
Comment: There wasn't a whole lot of information on this - I had the same problem when using a custom background for a ListView that made it unapparent to the user when they had successfully selected an item. Thankfully [view](http://developer.android.com/reference/android/view/View.html) saved the day. I left an answer below - great question though as I know your question will better the community.
Answer: Neither of these are possible answers when your ListView is compromised of a layout that has multiple views. You need to set your child views to:
android:duplicateParentState="true"

Now you can use the methods others have described above to declare your TextViews' colors using a selector such as:
android:textColor="@drawable/my_row_selector"

and I'm sure you're aware, but the selector can be as simple as:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="@color/white" />
    <item android:color="@color/black" />
</selector>

As you can see, @color values are allowed. Hope this helps.
Also - android:state_pressed is used in conjunction with the AdapterView.OnItemClickListener.
Comment: Thank you. Also works with fancy choiceModes, etc. I just set up my text selector's states to match those in the list selector. `duplicateParentState` was the key.
Comment: @AndrewPK dude you're great!
Comment: it is not working on droid 4.3, 4.4 focus text color is the same as tha normal color
Answer: in your textview propeties
android:textColor="@color/text_selector"

in res/color
text_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="YOUR_CUSTOM_COLOR" />
    <item android:state_selected="true" android:color="YOUR_CUSTOM_COLOR" />
    <item android:color="YOUR_CUSTOM_COLOR" />
</selector>

Comment: In order to work on selection use the following code: `

`
Comment: i tried like that and its work great
Comment: it is not working on droid 4.3, 4.4 focus text color is the same as tha normal color
Answer: In order to make it work on selection use the following code:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="#fff"/>
    <item android:state_activated="true" android:color="#fff"/>
    <item android:color="#000" />
</selector>

Apparently the key is state_activated="true" state.
Answer: When you are deploying the app for Android 11+ (HoneyComb+), you should use

android:state_activated="true"

for selected list state.
For the earlier versions use the combination of:

android:state_checked="true"
android:state_activated="true"

Of course don't forget to include the

android:duplicateParentState="true"

so the view can get the activated/checked state from a parent list view item
Answer: Also you may create a res/color folder and add a file "text_selector.xml" with the following lines:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_activated="true" android:color="#f0f"/>
    <item android:state_pressed="true" android:color="#f0f"/>
    <item android:color="#000"/>
</selector>

After that assign in TextView:
android:textColor="@color/text_selector"

Comment: Great solution, I tried to use a drawable selector which didn't work.
Comment: @Mr.Fish, Thank you!


Whats faster? Separate mysql query or array-rearrangement?

Question: In many of my scripts I deal with the same results from a mysql query.
I was always wondering if its worth the 'work' just to rearrange my result, so I can iterate through it more comfortably or if I shouldn't bother to make a separate mysql call.
I got four examples, which may result in different answers:

First I have an array with data from 5 columns. In one function I
iterate through every single row. In my other function I need only
one (random) row and only 2 fields of it.
In another example, I need all rows in both functions, but in one of
them I need one field as the key in the other one I need only need to
check for the appearance of a random string/int.
In my last example I basically need everything from my query for one of my function. The other functions needs only 1 column less.
And another possibility where I am just wondering whether it would be faster to JOIN one single row from another table and then handle it in php or if I shouldn't bother making a second query for this.

You'll probably say it will depend on the database size, but lets assume I do all these examples in a DB with about 200 rows.
Finally there's to say that I'm aware that I need to code in a way for good readability and however I feel most organized, but this theoretical question just bugs me and I was always wondering whether there is a difference at all and how others handle things like that.
Comment: 10,000 rows is basically NOTHING for a dbms, unless you're running this on a 640k 8088 4.77mhz machine. Ask the question when you're dealing with millions and billions of rows.
Comment: @MarcB: Of course, by then, it'll be too late to refactor.
Comment: errr... are you talking of iterating of all 10000 rows?
Comment: @Col.Shrapnel seeing the problem with big dimensions (re-arranging, iterating) I withdraw the 'big numbers' :)
Comment: and... can you give less vague and more practical examples? what is a random word you are talking about?
Comment: okay okay. I am not of the number itself. I am just wondering is your setup as bad as I suspecting. When you are talking of iterating, are you talking of iterating all the rows in database?
Comment: oh okay. 'random word' was just an example, lets say its an int. keep in mind that its more a general question (hopefully not too broad). about iterating through all the rows, yes sure - how else would you handle say a list of users ?
Comment: it is exact database's purpose to hold a list of users. and it is enrtirely wrong use of database if you are selecting all the rows and then wokring with them in the script.
Comment: Okay, always happy to learn something new, but in which perspective is this wrong when I literally need all the data ? Or how else should I do this then ? I mean, sure I limit the query to a few results per page (pagination like), but that's propably not what you mean.
Comment: that's why I am asking you for the certain example. because "in theory" a database is used to sore the data and to return **only the data required** at the moment.
Answer: I am suspecting this is a question of the "I have no idea" kind.
It is like "I have my car upside down and I want to know how to drive it faster" question. First of all you have to put it normal way and learn the very basics of driving.
Before asking "which is faster way" one have to ask "which is proper way".
And before tagging their question with "optimization" tag one have to have a certain problem which needs to be optimized.
As a general rule, database holds all the data as well as doing all the job of filtering and ordering the data.
So, you have to use SQL commands to retreive required data in the required order.
As a common sense rule, threre is no need to retreive the same data again if you have it already.
I don't know what to answer beside these 2 very basic statements.


reseting the hook_update_n status of a module

Question: I'm extending a module I've previously written and it needs some schema changes which I implement in hook_update_N.
I've updated the module's version from 7.x-1.0 to 7.x-1.1 and implemented the foo_update_7100 and it works fine.
The problem is that I've made a mistake inside foo_update_7100 and now that I've fixed it I cannot rerun the 7100 update. I need to create a 7101 one but that doesn't make sense because all my changes are not committed yet.
I've tried reseting the status of the hook_update_n via:
update system set schema_version=-1 where name='foo';

> Query OK, 1 row affected (0.01 sec)
> Rows matched: 1  Changed: 1  Warnings: 0

Then I do drush cc all but drush updatedb -y still gives me "No database updates required".
How can I solve this instead of simply incrementing the hook_update_N number?
Comment: Try setting it to 0 rather than -1.
Comment: Thanks. That worked. I should have seen the column description which clearly mentions that `-1` means that the module is not installed. Feel free to post that as an answer so I can accept.
Answer: FYI, in Drupal 8, the system table has been removed, and this information is now stored in the key_value table.
UPDATE key_value SET value='i:8000;' WHERE collection = 'system.schema' AND name = 'module_name';

(As noted above, the actual value should be less than the hook_update_N() you want to repeat, but higher than or matching the last update that does not need to be repeated.)
Answer: Setting it to 0 should work. system_schema() says the value should be:

-1 if the module is not installed (its tables do not exist); 0 or the largest N of the module's hook_update_N() function that has either been run or existed when the module was first installed.
Comment: Actually, this would only work if this is the only update hook; typically, this will cause *all* update hooks to run again. It is safer to set the value to 1 below the number of the update hook you need to rerun (and any hooks with subsequent numbers will run as well).
Comment: Is there a reason that `-1` would show up for a module that Drupal says **is** enabled?
Answer: I did this so much that I ended up writing a drush module to roll back the update version in the system table.  Called "uroll" for update rollback.
https://github.com/danshumaker/drush-uroll
Usage:
    drush uroll --module=mycustommodule --version=5
It's super simple but I use it all the time.  This combined with a database backup reload script allows you to rinse and repeat when writing update functions.
Hopefully helpful to you. Good luck.
Comment: D7 only for now.
Comment: @Kamal Sorry I should document it better.  If the current hook your're writting hook_update_N is at 7300 then you would give uroll `--module=mymodule --version=7299`  Which sets the sys table at one before yours. Thus on the next dbup your 7300 gets run.  So, no, don't just give it the last two digits but the whole number past `mymodule_update_` whatever that may be 9123667.. :)  @Eelke has a good description in his answer too.
Comment: Awesome! Drupal 7 or Drupal 8?
Comment: Its a good one. Helped me. Just for clarification if my hook_update_N is like mymodule_update_7000 then in your drush uroll command for version I can put 0. Am I right ?
Answer: For anyone who is still looking for an answer you can achieve this in 3 ways:

SQL: UPDATE system SET schema_version = [N*] WHERE name = '[Name of module]';
Drush: drush ev "drupal_set_installed_schema_version('[Name of module]', [N*])"
Drush uroll drush uroll --module=[Name of module] --version=N*

*N being the update function you want to revert to (i.e the last successful update function)
Answer: To get your update hook to run again, you should set the schema_version to 1 below the sequence number of your hook.
Technically, anything below the hook you wish to rerun and above the update hook you do not need/want to rerun (but at least 0; -1 means the module is not installed) is OK; if there are no other update hooks, that means that even 0 falls between those boundaries, but in the typical case, update hooks are increased by one, so only going 1 lower is the only safe option if you do not want to run more code than the current highest update hook.
The update process simply checks that value, and sees if there are any update hooks with a higher sequence number. If so, it will run them in sequence. (This also means that the installation process sets the schema version to that corresponding to the highest available update hook; it assumes that upon installation, your module will have a state corresponding to that last update hook).


Does the convergence of function for rational and irrational sequences imply its convergence for any real sequence.

Question: Given are the following two statements
($x_r$ denotes a sequence of rational numbers, and $x_i$ denotes a sequence of irrational numbers):
$$1. \forall x_r \to 1 \implies f(x_r)  \to f(1)$$
$$2. \forall x_i \to 1 \implies f(x_i)  \to f(1)$$
Are these sufficient to conclude that $$\forall x_n \to 1 \implies f(x_n)  \to f(1) $$ where $x_n$ denotes sequence of real numbers.
If one needs the $f$, here it is:$$f(x) = \begin{cases} x-1 & x \in \mathbb{Q} \\ 0 & x \in \mathbb{Q}^{c} \end{cases}$$
Answer: Yes, it is.
Hint: Given the sequence $x_n$, suppose there are an infinite number of both rational and irrational terms (else the proof is trivial). Define two subsequences by taking the rational terms in the first one and the irrational terms in the second one, then do the usual $\epsilon$-$\delta$ estimations to prove that the whole sequence indeed converges to $1$.
Answer: You are expressing yourself very poorly, but the idea is correct. Indeed, if $f\colon\mathbb{R}\longrightarrow\mathbb R$ is such that

for every sequence $(x_n)_{n\in\mathbb N}$ of rational numbers, $\lim_{n\to\infty}x_n=1\implies\lim_{n\to\infty}f(x_n)=1$;
for every sequence $(x_n)_{n\in\mathbb N}$ of irrational numbers, $\lim_{n\to\infty}x_n=1\implies\lim_{n\to\infty}f(x_n)=1$

then it is true that, for every sequence $(x_n)_{n\in\mathbb N}$ of real numbers,$$\lim_{n\to\infty}x_n=1\implies\lim_{n\to\infty}f(x_n)=1.$$
In fact, given such a sequence, there are three possibilites:

$x_n\in\mathbb Q$ is $n$ is big enough. Then, for some $N\in\mathbb N$, $n\geqslant N\implies x_n\in\mathbb Q$. Since the limit of the sequence $\bigl(f(x_n)\bigr)_{n\geqslant N}$ is $1$, $\lim_{n\to\infty}f(x_n)=1$.
$x_n\in\mathbb{R}\setminus\mathbb Q$ is $n$ is big enough. Then, for some $N\in\mathbb N$, $n\geqslant N\implies x_n\in\mathbb{R}\setminus\mathbb Q$. Since the limit of the sequence $\bigl(f(x_n)\bigr)_{n\geqslant N}$ is $1$, $\lim_{n\to\infty}f(x_n)=1$.
Otherwise, let $N_1=\{n\in\mathbb{N}\,|\,x_n\in\mathbb{Q}\}$ and let $N_2=\{n\in\mathbb{N}\,|\,x_n\in\mathbb{R}\setminus\mathbb{Q}\}$. Then $\lim_{n\in N_1}x_n=\lim_{n\in N_2}x_n=1$. Therefore, $\lim_{n\in N_1}f(x_n)=\lim_{n\in N_2}f(x_n)=1$ and, since $\mathbb{N}=N_1\cup N_2$, $\lim_{n\in\mathbb N}f(x_n)=1$.
Answer: Yes, this is true.
Let $(x_n)_{n \in \mathbb{N}}$ a sequence with $\lim_{n \to\infty}=1$. Each member of the sequence is rational or irrational.
First, we consider the case that there are only finitely many rational numbers. Then $\lim_{n \to \infty}(f(x_n))=f(1)$ is clear. Analogously for the case that there only finitely many irrational numbers.
Hence, we can consider the two subsequence $(x_{1_i})$ and $(x_{2_r})$ which consist only irrational and rational numbers, respectively.
Now, let $\varepsilon>0$ be arbitrary. As we know $f(x_{1_i})\to f(1)$ and $f(x_{2_r})\to f(1)$ there exist $i_0,r_0 \in \mathbb{N}$ such that
$$
|f(x_{1_i})-f(1)|<\varepsilon
$$
and
$$
|f(x_{2_r})-f(1)|<\varepsilon
$$
holds for all $i>i_0$ or all $r>r_0$ respectively.
Thus, we can conclude that there exists $n_0 \in \mathbb{N}$ such that
$$
|f(x_n)-f(1)|<\varepsilon
$$
holds for all $n>n_0$.


Extract PDF front page and store it as an image field in node

Question: I'm using Document Library module to manage my files and create listings for them.
I've also noticed the existence of PDFPreview module and I'd like to ask if the following is possible:
I'd like to upload a pdf file in a Document Library Document item and with this file to generate an preview image, stored as a new independent field (lets say the Thumbnail image field) in this content type. As things are now the preview replaces the file field which is something that I need to avoid.
Answer: Oh I just realized that another module, the PDF to Image Field module does exactly what I need! Some more details about thsi module (from its project page):

The PDF To ImageField module provides automatic conversion of uploaded PDF files to images. It can be used either to create a snapshot of the front page to use as a preview thumbnail, or to generate a gallery of images from each page in the document.
The module is implemented as an additional widget for File Field where PDFs are uploaded to. It places generated images into a Image Field on the same content type.

At least, I hope this helps other people too.
Comment: Interesting, didn't know you could do this, so it did "help" me ... BTW: hope you'd agree with my edit I just applied, to make it look less like a "link only" answer (which puts such answers at risk of being deleted). If you don't like my edit (or phrasing), rework it as you would want it to look like, ok?
Comment: @Pierre.Vriens Its fine. Glad to help & thanks for time!


Linked Server SQL 2016: Can't update transaction in remote server

Question: I have 2 Windows servers EC2 located in different region. Both of them have public IP so they can communicate with each other.
In order to allow remote query, i created a linked server. Basically, they are in different region so i used their public IP as data source.
1st server IP: 13.xxx.xxx.xxx
2nd server IP: 52.xxx.xxx.xxx
I tested the connection and it was successful. Remote query also worked fine.
For example,
update table set number = 0 from [remote-server-IP].txtoc.dbo.xhead where
code ='1234'
But if i use BEGIN TRANSACTION and COMMIT TRANSACTION like this
BEGIN TRANSACTION
update table set number = 0 from [remote-server-IP].txtoc.dbo.xhead where
code ='1234'
COMMIT TRANSACTION
i got error.
OLE DB provider "SQLNCLI11" for linked server "linkedservername" returned message "No transaction is active.".
Msg 7391, Level 16, State 2, Line 2
The operation could not be performed because OLE DB provider "SQLNCLI11" for linked server "linkedservername" was unable to begin a distributed transaction.
I tried many methods
- Enable Distribute Transaction on both server from Component Service
- Allow them work through Windows Firewall
- Allow all traffic between them (setting in Security group and Windows Firewall)
But none of them worked.
Anyone can shed a light on this, please?
Comment: Anyone has any idea?
Answer: This question is old, and I stumbled across it and am only commenting, not an acceptable answer:
1) Public IPs for SQL are dangerous, you should keep that in mind. Between Regions you can do a route with a VPN at a minimum.
2) Make sure the DTC on the remote server allows remote connections - Start - dcomcnfg - Expand Component Services - Computers - My Computer - Distributed Transaction Coordinator - Local DTC (Properties on this) - Security - Enable Network DTC, Allow Remote Clients, Allow inbound, Allow outbound.
3) If that doesn't solve it try dtcping from Microsoft to troubleshoot further.


A bound for the expectation of the maximum independent random variables

Question: Let $X_1, ..., X_n$ be i.i.d centred scalar random variables with finite variance. I am aware of the following two bounds. First note that
$$ \mathbb{E}\max(|X_1|,..,|X_n|) = \int_0^\sqrt{n}  \mathbb{P}(\max(|X_1|,...,|X_n|) > t) \ dt + \int_\sqrt{n}^\infty \mathbb{P}(\max(|X_1|,...,|X_n|) > t) \ dt$$
Now using Chebyshev we have
$$ \mathbb{P}(\max (|X_1|,..., |X_n|) > t) \leq \frac{n \mathbb{E}|X_1|^2}{t^2} \ .$$
The expectation changes by noting that
$$\mathbb{E}\max(|X_1|,..., |X_n|)^2 \leq \mathbb{E} \sum_{i=1}^n |X_i|^2 = n \mathbb{E} X_1^2 \ .$$
Now returning to the integral we may bound the first term by $\sqrt{n}$ and for the second term we have
$$ \int_\sqrt{n}^\infty \mathbb{P}(\max(|X_1|,...,|X_n|) > t) \ dt \leq n \mathbb{E} X_1^2 \int_{\sqrt{n}}^\infty \frac{dt}{t^2} = \sqrt{n} \mathbb{E} X_1^2 \ .$$
So we achieve a bound
$$ \mathbb{E}\max(|X_1|,..,|X_n|) \leq (1 + \mathbb{E}X_1^2) \sqrt{n} \ .$$
However in this bound I did not use the independence of the random variables, so I suppose there might be a sharper bound.
Another method I have observed, which could possibly be generalized, is the following. Let $X_1$ and $X_2$ be as above. Now
$$ \max(X_1,X_2) = \frac{X_1 + X_2 + |X_2 - X_1|}{2} \ .$$
Now using the fact that the random variables are centred we have
$$ \mathbb{E} \max(X_1, X_2) = \frac{\mathbb{E} |X_1 - X_2|}{2} \leq \mathbb{E} |X_1| \ .$$
However here we are not able to consider the absolute values of the random variables, and even for the case $n = 3$ we already start to get some cross terms which do not vanish by independence.
Any ideas? I am specifically looking for a sharper bound than $O(\sqrt{n})$ in fact any bound of the order $n^\alpha$ where $\alpha < \frac{1}{2}$ would be perfect.
Answer: The bound could have been better. For example, let us just assume that $X_i$'s are identically distributed but not necessarily independent and assume that $ \mathbb{E}(|X_1|^p) < \infty $. Let $ M_n  = \max_{ k \leq n } | X_k| $. For
any $ \epsilon > 0$, we have
\begin{align*}
\mathbb{E}(M_n) & = \int_0^{\epsilon n^{1/p} }  \mathbb{P}(M_n > t) \ dt + \int_{\epsilon n^{1/p} }^\infty \mathbb{P}(M_n  > t) \ dt \\
& \leq \int_0^{\epsilon n^{1/p} }  1 \ dt +  \int_{\epsilon n^{1/p} }^{\infty} n \mathbb{P}(X_1  > t) \ dt \\
& = \epsilon n^{1/p}  + n^{1/p} \int_{\epsilon n^{1/p} }^{\infty} n^{(p-1)/p} \ \mathbb{P}(X_1  > t) \ dt \\
& \leq \epsilon n^{1/p}  + \frac{n^{1/p}}{ \epsilon^{p-1}} \int_{\epsilon n^{1/p} }^{\infty} t^{p-1}  \mathbb{P}(X_1  > t) \ dt .
\end{align*}
Since $ \mathbb{E}(|X_1|^p) < \infty $, we have that $ \int_{\epsilon n^{1/p} }^{\infty} t^{p-1} \mathbb{P}(X_1  > t) \ dt \to 0 $ as $ n \to \infty $. Thus, dividing by $ n^{1/p} $, we have that
\begin{equation*}
\frac{ \mathbb{E}(M_n) }{ n^{1/p}}\leq \epsilon + \frac{1}{\epsilon^{p-1}} \int_{\epsilon n^{1/p} }^{\infty} t^{p-1}  \mathbb{P}(X_1  > t) \ dt .
\end{equation*}
Letting $ n \to \infty $, we have
\begin{equation*}
\limsup_{ n \to \infty} \frac{ \mathbb{E}(M_n) }{ n^{1/p}} \leq \epsilon .
\end{equation*}
Since $ \epsilon > 0 $ is arbitrary, we have that $ \mathbb{E}(M_n)  = o (n^{1/p}) $ as opposed to $ O (n^{1/p}) $ that you get.


Upgrade to .Net Framework 4.0

Question: my current version of .net framework on web server is 2.0 and now i want to run web apps of  .net framework 4.0 on same web server. before doing so i wants experts advice that if i will install .net framework 4.0 on my webserver then my webapplications of .net framework 2.0 will be affected or not and if yes then what should i do to handle both (2.0, 4.0) on my web server at same time.
Thanks
Comment: Check similar answer here: http://stackoverflow.com/questions/3611399/net-4-0-framework-on-same-server-as-net-1-1
Answer: Your existing .Net 2.0 applications which are configured in IIS will not be affected by the install of .Net 4.0. You will have to manually change the application pool(s) to use .Net 4.0.

Upgrade to .Net Framework 4.0


Cubic and linear relationships in multiple regression model

Question: What is the correct way to fit a multiple regression model where I have a combination of cubic and linearly related independent variables?
If I transform the variable showing cubic relationship, how do I transform back the forecasted variable, given that it's the result of both non-transformed and transformed data sets?
Comment: If you don't actually care about the specific parameter values of the functions, and instead want to simply establish whether relationships (linear or non-linear) exist between your variables, I suggest you look at Generalized Additive Modelling, which will flexibly/adaptively accommodate both linear and non-linear effects.
Comment: Its not clear what you're asking... why are you transforming your outcome variable? Its often best to include a term linearly as well as using its square and/or cube.
Comment: I have X1 that shows cubic relationship against Y. However X2 has linear relationship. I want to use a multiple regression model to calculate the coefficients. Should I transform X1 first, then run a multiple linear regression? Or are there other ways to fit X1, X2? If I transform X1 first, how do I transform back the predicted Y variable, given only 1 of the two dependent variables was transformed?
Answer: One way to fit the model is, as you guess in the comment, to transform $X_1$ first, then run a multiple linear regression.  However, you don't have to do any transformation back to the predicted $Y$ value, since the regression is still using the untransformed $Y$ variable as the dependent variable.  Let's say you create $Z = X_1^3$, then the regression becomes $Y = \beta_0 + \beta_1 Z + \beta_2 X_2 + e$.   The estimates and/or predictions you get out of the model with the transformed $X_1$ are still for $Y$.
There are other ways to fit the model, but the choice between fitting methodologies is, in this case, independent of the transform of $X_1$.
Edit: It has occurred to me that you may have meant a cubic relationship where $Y^3 \propto X_1$. This is equivalent to $Y \propto X_1^{1/3}$, and you can still just transform $X_1$ without having to transform $Y$ at all.
Comment: Right, the transformation only applies to X1, during the regression and then for prediction. Thanks. So in case I have a cubic function Y = b0X + b1X^2 + b2X^3, what is the appropriate transformation to linear relationship?
Comment: The relationship isn't linear, so there isn't an appropriate transform.  Just run the multiple linear regression with $X, X^2, X^3$ as your right hand side variables.  If you want to plot, just plot your estimated $Y$ against $X$.  The key is that you can represent $Y$ as a sum of coefficients times some other variables, but the other variables certainly can all be functions of some underlying variable, as in your cubic polynomial.  People run that sort of regression all the time, so I wouldn't worry about it.


How to remove disgusting audio sound from reaper DAW

Question: I'm having some problems with making my sounds not have this disgusting noise in the background which sounds like electrical systems getting fried. How can I get rid of it? Here is an example where you can hear it quite well.

In my example it is mainly at the beginning. You can very slightly hear the sound, during the first part with the horn and the very bass double bass you can hear it as well. It makes it hard to achieve really pristine and high quality sound.
How can I get rid of this annoying sound? I don't even know the name of it...
Answer: I'm not sure if I know the sound you're talking about, but I can say one thing right off the bat: Your mix is extremely loud. I think what you're hearing is distortion caused by some combination of over-compression and actual clipping of the waveform at the top.
If you're using some kind of mastering plug-in, back that off and leave some crest factor and headroom. If not, all your channel faders should come down.
Louder is not better! Too loud is just as bad as too quiet. Compare your mix and loudness to other mixes of the same type of music you are creating. You will find that yours is pushed all the way up to the top as far as it can go, and other mixes are not. Give the listener (and the amplifiers and speakers, etc.) some breathing room to hear the subtleties in your music.
Compare your mix to this recording of Capriccio Espagnol by Rimsky-Korsakov:

I think you'll hear that the levels are much lower than yours, the orchestration is just as "big" and the sound quality is more like what you're looking for.
Comment: Of course Rimsky-Korsakov is widely regarded as one of the finest orchestrators in history. Good example.
Comment: good answer, Todd...except I'd offer that improper gain-staging is the ENTIRETY of this issue.  Levels need to be backed off tremendously.
Answer: What you are hearing is called "digital clipping."  It's because you have pushed the audio level far past where it should be.
This is not a "Reaper DAW" issue, it's a "gain-staging" issue.
Basically, there's two options, depending on how the analysis goes.  First, listen to each instrument on it's own.  If it has that "crackly" sound, then you recorded your instruments at much too high/hot level, and you need to simply re-record.  Those tracks are useless.  If the individual tracks sound ok, then you need to go back to your mix, and pull ALL the faders down by about 1/3.
Comment: "normalize" is basically not to be used, ever.  full stop.  just don't.  It doesn't do what you think it does.
Comment: You should also be careful about using a "Normalize" function. This  linearly boosts the overall level of the whole selected piece of audio all at once. It's useful if the recorded level is a bit too low, but you can overdo it. For instance, you usually don't want to Normalize to 0.0 dB; you want to set it for -2.0 dB or -1.0 dB and inspect the results (and undo them if clipping is introduced). Some DAW software will automatically Normalize the final output of a project by default (when you "Export as MP3" etc.; if so, you may need to turn this feature off and compare the results.
Comment: And on recording and playback, watch all your levels (what we used to call VU meters). Never let anything get into the red. Keep it from the green to the yellow. Any time you see red, it is likely that digital clipping is occurring.
Comment: the "common understanding" these days among "pro" recordists is that you record at -18dB.  When you're in a 24 bit daw at 96k, you don't gain ANYTHING by recording higher.
Comment: Here is a tutorial on Gain Staging. The principles here will apply to any DAW, not just Reaper.

Gain Staging In Your DAW Software, Sound on Sound Magazine, September 2013. http://www.soundonsound.com/sos/sep13/articles/level-headed.htm


Stretching on Ukulele: How Far is Fair?

Question: I've noticed that I play a lot of chords on ukulele with larger intervals in them, and often the chord voicings have big stretches from the lowest notes to the highest notes.
Obviously, I know beginners often struggle with chord shapes, but for more intermediate to advanced players, how far can most players reach over the fingerboard? Or in more precise words, what's the practical limit on how big a chord can be before it gets unplayable to most people?
As an example, if I asked a friend to play the D above middle C and the E♭ a minor ninth above it, would that be doable?
For simplicity, let's limit the question to the standard soprano size ukulele. If you want to get specific with tunings, C standard with a high G, since that's the most common one.
Comment: Since the same pitch can be played in more than one spot, I would use specific fret/string (TAB) instead of the pitch names.
Comment: @user45266 - But isn't there more than one often-used tuning for a ukulele?
Comment: @NickGrooves Actually, there's only one place to play the D above middle C on the ukulele fretboard, and therefore only one reasonable place to play the E♭. That's why I picked that example. D on the C string, E♭on the A string.
Comment: Fair, and I've edited to address tuning, but AFAIK C Standard (aka C6) and D standard (D6) are the two common tunings, and both only have one place to play the D4. Unless you're talking about low G tunings...
Comment: @user45266 While I understand your comment about the D above middle C, other players may not (especially if they don't read music, which many guitar and uke players don't) and besides the term "middle C" is somewhat relative for transposing instruments. Guitar, for example, is technically treble clef down one octave so "middle C" is not actually middle C ... if you follow my meaning.
Comment: @user45266 Something isn't adding up here ... There's only one D that can't be played anywhere else and that's the second fret of the C string ... but the Eb on your A string is more than a minor second away (which would equate to the third fret of the C string).
Comment: @user45266 You're talking about an octave + m2 (aka m9) interval. This would span frets 2 (D), 3,4,5, 6 (Eb) and is totally reachable but not quite what you said. If you want a true minor second (half step) play D on the E string (10th fret) spanning frets 6 (Eb), 7,8,9, 10 (D).  Or an even better way, play one of them on the octave-up G string: you can play Eb @ A string, fret 6 *with* D @ G string, fret 7.
Comment: Arrgh, how did I miss that? Yeah, I meant minor ninth. Sorry about that, guys. Edited.
Comment: @NickGrooves Although I'm pretty sure that any ukulele player who's heard of middle C knows that it's on the open C string.
Comment: @user45266 Being specific is always best for clarity. Sorry this has become such a point of contention. Regarding the m9th, you're welcome.
Answer: Since standard ukulele tuning has the same intervals as guitar (strings 1-4, frets 5 and up), I write with the same guidelines in mind. If your intended audience is "beginners," stick to basic C-A-G-E-D shapes (open / cowboy chords). If you're writing for intermediate players then barre chords and a five-fret span seem fair. Always keep in mind not only does the chord have to be reachable on its own, but in sequence from the previous / following chords.
It's a serious question. My composition professor in college told us that composers are not required to be able to play their work in order to write their work ... but you want someone to play it :)
If you play the instrument, and you can grab it, then chances are good that others can, too.
Comment: Your statement of "Since standard ukulele tuning has the same intervals as guitar" doesn't quite sound right: the "standard" guitar tuning is EADGBE, while the most common ukulele tuning I've heard of is gCEA, complete with going *down* instead of up for the first two strings.
Comment: @NickGrooves I'm not sure guitar is a great choice of analogy, though, because since the ukulele's frets are closer together, for the purposes of stretching the two aren't the same. I'd love to see a guitarist play [1-1-9-9] as a chord shape. And as for *"you still have human hands with the same capabilities as 'most' other players"*: that's what I'm saying; because I play in such an unconventional manner, I'm not sure whether my hands do in fact have the same capabilities as other players. That's why I'm asking the question.
Comment: When you say 5-fret span, do you mean five frets over to the right of a note (E to A on the same string)? Also, *"If you play the instrument, and you can grab it, then chances are good that others can, too"* I'm not sure whether I'm a good representation of others' ability; I play the instrument very differently from most people.
Comment: @Dekkadeci Sorry it doesn't sound right to you, but it is :)  Capo your standard-tuned guitar at fret 5 and you'll have (low to high) G, C, E, A. The fact that a uke's G string is an octave up has no bearing on the chord shapes (which is the subject of this thread) aside from inverting any notes on said string (like on a 12-string guitar; one wouldn't argue a 12-string is tuned differently than a 6-string, it's the same intervals). Any chord played on a standard-tuned ukulele may be played on the guitar without changing any fingering and *vice versa.*
Comment: @user45266 You may play it differently than most, in your opinion (and you may be right) but you still have human hands with the same capabilities as "most" other players. A five-fret span (two whole steps a.k.a. Major 3rd) is very common for intermediate and above guitarists on any string at any fret position, and since uke frets are so close together this is easily achieved. For example, guitar frets 6-7-8-9-10 = uke frets 1-2-3-4-5
Comment: @user45266 As I said, uke frets are "so close together this is easily achieved." Your original question is subjective, and I gave you a realistic answer based upon decades of playing and teaching experience. I even showed you two easy ways to play the minor 2nd interval in my comments on your OP. I never said a guitarist would play a 1-1-9-9 chord shape, nor have I ever seen that chord in a ukulele book. Your question is not about exceptional players, it's about **a friend** and **practical limit** which means average or "most other players."

Stretching on Ukulele: How Far is Fair?


How to display the number of data based on today date

Question: <?php

   $connection=mysqli_connect("localhost","root","","halcondentalclinic");
                             $queryss="SELECT datetreat FROM alltreatment WHERE datetreat order by date(now())";

                             $query_runsss=mysqli_query($connection,$queryss);

                             $rowsss=mysqli_num_rows($query_runsss);
                             echo '
'.$rowsss.'
';
                            ?>

This is the datetreat table in my database

This is the output of my dashboard but I want to display the number of the treated patient on today's date but on my dashboard, the output is 4 but my expected output is 1 because of the data based on the today's date
Comment: `WHERE datetreat` doesn't do anything useful. If you want to restrict it to today, then you need to compare `datetreat` to something else. e.g. write `WHERE datetreat = date(now())` would make sense. P.S. your question has nothing to do with Javascript or HTML, I've amended your tags.
Answer: WHERE datetreat doesn't do anything useful. If you want to restrict it to today, then you need to compare datetreat to something else. e.g.
WHERE datetreat = date(now())

would make sense


What are these specific part of technique in the Gran Jota called?

Question: Here where there seems to be some sort of slapping of the bridge.

And this which I cannot even describe.

I would like to know what these techniques are called.
Answer: This is called the tambor (also spelled tambour) effect, allegedly used to mimic the sound of a heartbeat and typically notated with X's as noteheads. Here's a brief video.
Comment: It's marked 'tamb' on the original dots. Hitting specific strings rather than the bridge. I use a similar technique with bass guitar, giving a rather different sound to the usual pluck/snap/pop.


Product to sum formulas

Question: Write the product as a sum.
cos 4x cos 2x
this is what i tried
2{cos2xcosx} = 2[1/2 cos(2x+1x)+ cos(2-1)]
             = 1[cos(3x)+cos(1x)]
             = cos 3x + cos x
Comment: What is the problem? Also use [$\LaTeX$](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) to write math.
Answer: There is an identity:
$$\cos\alpha \cdot \cos\beta = \frac{\cos(\alpha-\beta) + \cos(\alpha+\beta)}{2}$$
You can find other useful formulas here.
Welcome to the site!
Answer: Hint:
$$\cos (4x + 2x) = \cos 4x \cos 2x - \sin 4x \sin 2x
\\
\cos(4x-2x) = \cos 4x \cos 2x + \sin 4x \sin 2x
$$
Now make the half sum of these two, and you will get your result. Welcome!

Product to sum formulas


Delete files and subfolders in the folders "tmp" and "cache"

Question: I want to use this script below to clean out "tmp" and "cache" folders in websites like "C:\Storage\Websites\Site1".
It tries to delete files and subfolders in "C:\Storage\Websites\Site1\tmp" and "C:\Storage\Websites\Site1\cache".
Which is right, but it also tries to delete files and subfolders in, for example, "C:\Storage\Websites\Site1\MySpecialLittleProgram\tmp" and, for example, "C:\Storage\Websites\Site1\MySpecialLittleProgram\cache".
Which is wrong. It should only clean up the "tmp" and "cache" folder in the root of the website and not in other subfolders.
If I delete the /s parameter in 'dir /a:d /b /s tmp cache' it will not find anything.
How can I do this part?
(I have deleted the /q parameter in the file deleting part and the folder removing part if anyone copies my script.)
@echo off

call:CleanUp "C:\Storage\Websites"

echo.&pause&goto:eof

::--------------------------------------------------------
::-- Function section starts below here
::--------------------------------------------------------

:CleanUp
    IF EXIST %~1 (
        cd /d %~1
        FOR /f "tokens=*" %%i in ('dir /a:d /b /s tmp cache') DO (

            echo %%i

            ::DELETING FILES I FOLDERS AND SUBFOLDERS
            del %%i /s

            ::DELETING NOW EMPTY FOLDERS AND SUBFOLDERS
            FOR /D %%p IN ("%%i\*.*") DO rmdir "%%p" /s
        )
    )
goto:eof

UPDATE:
I updated my code to be (it is working now):
@echo off

call:CleanUp "C:\Storage\Web"
call:CleanUp "C:\Storage\Web-IIS"

goto:eof

::--------------------------------------------------------
::-- Function section starts below here
::--------------------------------------------------------

:CleanUp
IF EXIST %~1 (
   cd /d %~1

   FOR /f "tokens=*" %%i in ('dir /a:d /b') DO (
      IF EXIST %%i\tmp (
         del %%i\tmp /s /q
         FOR /D %%p IN ("%%i\tmp\*.*") DO rmdir "%%p" /s /q
      )

      IF EXIST %%i\cache (
         del %%i\cache /s /q
         FOR /D %%p IN ("%%i\cache\*.*") DO rmdir "%%p" /s /q
      )
   )
)
goto:eof

Answer: This should remove the files in those two locations:
@echo off
del "C:\Storage\Websites\Site1\tmp\*.*" /a /s
del "C:\Storage\Websites\Site1\cache\*.*" /a /s

From your comment, this may be what you need to do: remove the echo keyword after testing it to see the commands on the console that would be executed.
@echo off
cd /d "C:\Storage\Websites"
for /d %%a in (*) do (
   for %%b in (tmp cache) do (
      pushd "%%~fa\%%b" 2>nul && (echo rd /s /q "%%~fa\%%b" 2>nul & popd)
   )
)
pause

Comment: I have MANY sites therefore I need a script like the one I have written. It only needs to delete "tmp" and "cache" in the root of the website. It also (wrongly) deletes matching folders in subfolders like "C:\Storage\Websites\Site1\SUBFOLDER\tmp\" or "C:\Storage\Websites\Site1\SUBFOLDER\cache\".

Can you improve my existing script so it works? :-)
Comment: Explain where your list of many sites is coming from and where the folders can be - it will help to understand how to fix your issue. It's seldom useful to read code that doesn't work - because it doesn't work.
Answer: I suggest to use rmdir or rd for this task:
rd "C:\Storage\Websites\Site1\tmp" /S /Q
md "C:\Storage\Websites\Site1\tmp"

rd "C:\Storage\Websites\Site1\cache" /S /Q
md "C:\Storage\Websites\Site1"

Command rd with options /S for all subdirectories and /Q for quiet deletes also tmp and cache, but those 2 directories can be easily recreated using command md although I'm quite sure that this would not be really necessary here as the application creating tmp and cache would do it also automatically.
If that is not what you want, please show as directory listings with files and folders in one of the two directories before cleanup and after cleanup.


Botão carregar + Dados do Banco de Dados MYSQL substituindo "Select * From tabela limit 18"

Question: Estou querendo configurar um botão para que sempre quando eu aperta no botão CARREGAR + o limit 18 acrescente sempre +18.
EXEMPLO:
$sql = "SELECT * FROM portfolio ORDER BY id DESC limit 18";
BOTÃO CLICKADO
$sql = "SELECT * FROM portfolio ORDER BY id DESC limit 36";
BOTÃO CLICKADO
$sql = "SELECT * FROM portfolio ORDER BY id DESC limit 54";
Eu coloquei esse limit para arrumar o layout e aparecer apenas 18 blocos no meu site e ir carregando sempre +18 ao aperta no botão.
CODIGO:

      <?php
$servidor = 'localhost';
$banco      = 'apixel_galeria';
$usuario  = 'root';
$senha    = '';
$link     = @mysql_connect($servidor, $usuario, $senha);
$db          = mysql_select_db($banco,$link);
if(!$link)
{
    echo "erro ao conectar ao banco de dados!";exit();
}

$sql = "SELECT * FROM portfolio ORDER BY id DESC limit 18";
$query = mysql_query($sql);

while($sql = mysql_fetch_array($query)){
$id = $sql["id"];
$nome = $sql["nome"];
$tipo = $sql["tipo"];
$desc = $sql["desc"];
$menu = $sql["menu"];
$imageM = $sql["imageM"];
$imageF = $sql["imageF"];
    ?>
          <div class="element-item <?php echo "$menu";?>" data-category="transition">

                                <img src="<?php echo "$imageM"?>" alt="project 2">

<?php echo "$nome"?>

<?php echo "$tipo"?>

VEJA

        <?php
}
?>

            <button class="button bt1" style="width: 262px; height: 50px; border: 1px solid rgb(84, 128, 128); position: relative; top: 30%; left: 50%; transform: translateX(-50%); cursor: pointer;  background-color: white;">

CARREGAR

+
</button>

Comment: Não faz sentido isso, você estará pegando todos os valores já obtidos anteriormente a cada clique. Mantenha o limite e mude o WHERE para > que o último ID pego no clique anterior. Claro que aí vai ter que mudar a lógica da página para carregar dinamicamente, ou fazer paginado.
Comment: O que você quer se chama PAGINAÇÃO. Veja [**este tutorial**](https://daltonmenezes.wordpress.com/2010/06/17/paginacao-de-resultados-com-php-e-mysql-aprenda-definitivamente-no-passo-a-passo/) e veja se te ajuda.
Comment: então amigo, é dinamicamente, ao aperta ele ja carrega em baixo as outras.
Comment: Bacco não entendi como vou fazer isso rs, poderia me explicar?
Comment: Pois não vejo um where no meu codigo.
Answer: Boa tarde amigo ,
EDIT --
Pelo seu comentaria acima,você quer que os dados sejam carregados dinamicamente , certo ?
Então voce vai precisar sober sobre um pouco de ajax.
Edit --
Abaixo , segue um pequeno exemplo , lembrando que nao validei tudo e nem formatei o html , é um exemplo simples .
Na pagina pegaPortifolio.php , você fará o o select no banco  , trazendo os resultados dos dados  , com um limit definido por você.
pagina : pegaPortifolio.php
    <?php

function fn_conexao(){

    $dbuser = "admin";
    $dbpass = "1234";

    try {

        $pdo = new PDO('mysql:host=localhost;dbname=seu_banco',  $dbuser, $dbpass);
        $pdo -> setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
        $pdo->exec("SET CHARACTER SET utf8");//corrige os acentos na hora de gravar no BD
    } catch(Exception $e) {

        echo 'Erro na conexao: ' . $e->getMessage();
    }

    return $pdo;
}

function dados($pdo){

    try {

            if(!isset($_GET['id']) or $_GET['id'] == null){

                $id = 0; //se o GET nao for enviado o for enviado como nullo , a variável ID pega o valor de 0

            }else {

                $id = $_GET['id']; //pega o valor passado via GET
            }

            $arr = array();

          //aqui , coloquei o limit como 2 para ficar mais facil os testes
            $sql = "SELECT * from portifolio where id > $id limit 2";
            $stmt = $pdo->prepare($sql);
            $stmt->execute();
            $linha = $stmt->fetchAll(PDO::FETCH_ASSOC);

            if($stmt->rowCount() >= 1){

                return $linha; //retorna o resultado da query

            }else {

                return 0;

            }
        } catch(Exception $e) {

            print 'Erro ao inserir os dados no banco: ' . $e->getMessage();
            $conexao = desconecta($conexao);

        }
}

$conexao = fn_conexao();
$dados = dados($conexao);

$dados = json_encode($dados); //converte o resultado para json

print $dados; //imprime os dados na tela
?>

Na sua pagina que exibira o protifolio , você ira fazer uma requisição para pegar os dados retornados em json.
portifolio.php

<input type="hidden" value="0" id="ultimo_id">

<button type="button" onClick="pegaDados();">CARREGA +</button>

Dados:

Como pode ver ,passo o valor do ultimo id buscado , entao , na sua pagina que montará o retorno json (pegaPortifolio.php) , voce faz um _get['id'] e usa ele no where ( select * from portifolio where id > $id limit 18) . Assim , ele pega os dados em seguenquecia  , limitando-se a 18 resultados.
Agora , você tem que organizar o resultado do json para poder exibir na sua tela. Recomendo tbm , verificar quantos registros você possui na sua tabela de  "portifolio" , para quando nao ter mas registros para buscar , o botão CARREGA+ seja desabilitado.
Com o javascript não posso ajudar muito pois nao tenho tanto conhecimento sobre o mesmo , mas testei em minha maquina e o mesmo rodou normal .
Comment: Henrique estou usando o plugim isotope jquery para criar uma galeria que puxe do banco de dados, então ela vai ser dinamicamente, quando clickar ele vai aparecer +18 blocos puxados do BD
Comment: para atribuir ao meu código preciso mudar algo?
Comment: no caso aonde está o url: "http://main.xfiddle.com/code_27238237.php?id="+id, eu faço o _get['id'] ??????
Comment: essa function eu faço dentro do pegaPortifolio.php ???
Comment: Boa tarde  , isso. Na pagina pegaPortifolio.php vc faz o $id = $_GET['id'] . Ja na pagina portifolio.php , vc coloca a funcao javascript que manda a requisição para a pagina pegaPortifolio.php
Comment: eu to com problema para entender :/. como vou fazer
Comment: vc poderia fazer o pegaPortifolio.php e portifolio.php de como ficaria no meu codigo?
No meu BD - é banco apixel_galeria TABELA: portfolio
Comment: Boa tarde @kaiquemix , editei o codigo  , deixei bem comentado ele. Faça os teste , as adaptações,  que acredito que vai solucionar seu problema.
Comment: no inspecionar elemento ta aparecendo isso:
Failed to load resource: the server responded with a status of 404 (Not Found)
GET http://localhost/pixelsbd/json.php?id=0 404 (Not Found)

quando clico no botão careggar mais não acontece nada
Comment: Veja o nome do arquivo e o caminho dele.Isso ai é de arquivo nao encontrado
Comment: sim era o portfolio e nao portifolio heehe
bom agora ta aparecendo só isso:
GET http://localhost/pixelsbd/json.php?id=0 404 (Not Found)
Comment: ta dando erro nessa url... oq eu boto nela?
Comment: Como você nomeou o arquivo que pega os dados do banco  ? No exemplo , eu o chamei de 'json.php' e o deixei no  mesmo diretorio do arquivo que o chama. Verifique o nome do arquivo na sua pagina portifolio.php nessa parte : "url:seu_arquivo.php"
Comment: o portfolio é o index.php
e esse pegarportfolio coloquei dentro de uma pasta ajax/pegarportfolio.php
Comment: coloquei assim,       url: "ajax/pegaPortifolio.php?id="+id,
agora não esta acontecendo nada e não mostra nada no console
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/32395/discussion-between-henrique-felix-and-kaiquemix).


Adwords conversion tracking on Ubercart store with payment gateway?

Question: is it possible to implement Adwords conversion tracking so that it takes into account conversion that come through payment portal (Customer leaves site for a moment and returns after payment, usually conversion is not tracked due leaving site for a moment)?
I have injected adwords tracking code to order completion page but it tracks only orders that come with billing option (customer does not leave the site).
If this is not possible, is it possible to inject code to order review page, if so how? (This is bad as some customers wont complete order so leads to false conversions. Also we are planning skipping order review page for billing)
Answer: You have to make users come back to your site adding this query string in the URL:
<code>?utm_nooverride=1
</code>
Then Google will discard referral modification caused by leaving the site.
See this question.
You will have to deal with your payment gateway to modify the return URL, I think.


difference between CGRectMake and setContentSize scrollVew

Question: what is the difference between this two instruction
scrollView.frame=CGRectMake(0, -100, 960, 100);
[scrollView setContentSize:CGSizeMake(960, 100)];
Answer:
scrollView.frame=CGRectMake(0, -100, 960, 100);

Sets the frame of the UIScrollView. Which means you set the origin and the visible size of UiScrollView on your view.

[scrollView setContentSize:CGSizeMake(960, 100)];

Sets the Content size of your UIScrollView. You use a UIScrollView, because you have more content to display than you can show within the frame of your view. Therefore you have to set the size of the contentView, which you scroll up and down.
Take a look at the Apple docs:Creating and Configuring Scroll Views
Comment: thinks it is helpful and prisize


For df in vector creates vector, but I want a dataframe

Question: I am using  for dfx in MyDFvector  to create a variable,
but it is returning  Vector[Vector]  but I want just a DataFrame.
Any help?
recreate minimal problem
using DataFrames

# create some DataFrames
mydfbase = DataFrame(a=[41, 41, 41, 41, 41, 41])
mydf1 = DataFrame(a=1:6)
mydf2 = DataFrame(a=7:12)
mydf3 = DataFrame(a=13:18)

# put into a vector
MyDFvector = [mydf1, mydf2, mydf3]
println(typeof(MyDFvector))

#
RawDiff = [mydfbase.a  .-  dfx.a for dfx in MyDFvector]
println(typeof(RawDiff))
println(RawDiff)

mydfWant = DataFrame(a=[40, 39, 38, 37, 36, 35], b=[34, 33, 32, 31, 30, 29], c=[28, 27, 26, 25, 24, 23])
println(typeof(mydfWant))
println(mydfWant)

'= = = = = = = = = = = Terminal output
What I got-->
Vector{DataFrame}
Vector{Vector{Int64}}
[[40, 39, 38, 37, 36, 35], [34, 33, 32, 31, 30, 29], [28, 27, 26, 25, 24, 23]]

What I Want-->  (any generated column names)
DataFrame
6×3 DataFrame
 Row │ a      b      c
     │ Int64  Int64  Int64
─────┼─────────────────────
   1 │    40     34     28
   2 │    39     33     27
   3 │    38     32     26
   4 │    37     31     25
   5 │    36     30     24
   6 │    35     29     23

Answer: Seems the following will get you to mydfWant:
julia> DataFrame(stack(RawDiff), :auto)
6×3 DataFrame
 Row │ x1     x2     x3
     │ Int64  Int64  Int64
─────┼─────────────────────
   1 │    40     34     28
   2 │    39     33     27
   3 │    38     32     26
   4 │    37     31     25
   5 │    36     30     24
   6 │    35     29     23

For a lot of useful help in Julia, pressing '?' in the REPL and then a function or a type is very helpful (for example the function stack in this answer).
Comment: Tkx a bunch.  Without using the word stack, is there some google phrase that I could have used to get close to solving this myself?  Or a reference site?
Comment: There are other methods to go about creating this DataFrame. For example, creating a Dict for the vectors and then constructing the dataframe from the Dict. Of course, the usual time spent with Julia makes things clearer over time.


Renaming a folder and not losing the link between the branch and the trunk

Question: I had two working copies: of a trunk and of a branch:

trunk -> App 1.0
branches -> 1.2 -> App 1.0

I needed to rename App 1.0 to Application ("1.0" being an archaism from the days where versioning was done "manually" and SVN was underused to put it mildly; I'm trying to set it right now, although I haven't had much experience with source control).
I did TortoiseSVN -> Rename on my 1.2\App 1.0 and trunk\App 1.0 local disk folders (working copies), and I renamed the folders in the repository as well (via the Repo-browser).
And yet code file abc.cs in the 1.2 branch still "thinks" that its base is the old file: App 1.0/abc.cs.
Diff with previous version gives me an error ("Subversion reported an error: Unable to find repository location for 1.2\App 1.0\abc.cs in revision 604").
See the revision graph for this file:

(I edited out the actual name of the application for reasons easy to understand.)
Propagating trunk modifications by merging them into the branch is now a bit troublesome.
What's more, my collegue still has an App 1.0 working copy (hasn't comitted nor updated it yet), so I'm somewhat afraid that we're about to mess things up, and I'm not sure how to go on from here.
The question is: where did I do wrong, and how do I fix that (both for me as well as my collegue)?
I guess that renaming both folders independently was the mistake that broke history tracing (no direct connection between 637 and 639 on the picture now, while that's what I would need); I'm just not sure what I should have done instead, and neither how to fix it.
Answer: The issue was caused by renaming both the working copy and the repo folder without communicating either change (as you thought).
As per the thread here, you could have renamed the repo folder, then updated the working copy, or used the command line interface.
Answer: Try to check out a fresh working copy - it may be possible that everything is OK in the repository...


Old network login passed to IIS

Question: Let me start by saying that I am not a server guy - I am a developer. But I develop and manage an ASP.NET application that uses Windows authentication. I've run into the problem I am about to describe before, and I would just like to understand how to remedy it since I am the one who always gets the original support request.
A user, let's call her JaneDoe, has just gotten married and her login has been changed to JaneJones. We have an application that uses Windows authentication to store the user's login name to a table and then redirects the user to another non-Windows authenticated site with a GUID which points to the table entry we just made. When the user reaches the second site, we read in the login name from the database using the GUID that was passed. Then, we look up the login name in another database where we track application permissions.
The problem is that the user is logging into her workstation as JaneJones, but the Windows authenticated site is still receiving a login name of JaneDoe. Is this a domain controller issue? Is it a workstation issue? What's the best way to resolve this?
Comment: Could it be a browser cookie issue?
Comment: @Jon - I doubt it. I am certain our help desk team has probably already had this user clear her cookies and reboot her workstation - all the normal baseline attempts at fixing weird issues. I think it has something to do with her network credentials being cached out on the network possibly, but that is why I am trying to see if anyone is familiar with this very specific scenario. I will double check on the cookie clearing though JIC.
Answer: Are you sure Login name was changed and not the display name? You can check her log on name on her pc by
Start -> Run -> cmd  ->OK
In the CMD window type
<code>  set username
</code>
This shows her windows userid. If normal Windows authenication is used with IE, this is the user id being presented to Webserver. If you IIS logging, this is the same ID you will see in the log.
Answer: If you've confirmed that the username really was changed (see ggonsalv's suggestion), double check to make sure the user didn't check the IE box to save the password.  Follow these steps:

Control Panel
User Accounts
Click the Advanced Tab
Manage Passwords

If you see the server address you're trying to connect to in there, select it, and click remove.
Answer: Yep, I've seen this before with IIS 6. Turns out there's a token cache external to the W3WP instance, so restarting that (i.e. recycling) doesn't help; I can't remember the details, but either an IISReset or a whole-server restart is required to clear it.

Old network login passed to IIS


Marcar um campo checkbox, se uma ou duas opções forem escolhidas no campo select

Question: Tenho um campo de seleção com 4 opções.
Se for escolhido a opção 1, quero que marque um campo checkbox (BRANCO)
Como faço
Comment: Julio, considere colocar mais detalhes na sua pergunta, dessa forma que você colocou fica difícil ajudar
Comment: PERGUNTA ALTERADA !
Answer: Tenta com um JS tipo isso
<code>$('select[name="opcoes"]').on('change', function(){
  $('.checks').find('input[type="checkbox"]').each(function(){
    $(this).prop('checked', false);
  });
  if($(this).val() !== ''){
    $('input[data-id="'+$(this).val()+'"]').prop('checked', true);
  }
});
</code>
Fiz um fiddle pra demonstrar
Comment: Muito bom !!!!!
Comment: @JúlioRicardo Não esquece de marcar a resposta como correta, assim tu ajuda outras pessoas no futuro que tenham o mesmo problema no futuro
Comment: ;-)........... !


Multiple comparison issue in multivariate logistic regression

Question: I am assessing a bunch of risk factors related to HIV infection by logistic regression.
First I will conduct a couple of chi square tests or t-tests to see if each factor is associated with HIV infection or not.
Then I will pick those factors with p value less than 0.1 out of the bivariate analysis above and include them in the multivariable logistic regression model (adjusted model).
In this case, is multiple comparison a concern for me? Why and why not?
Comment: Is your overall goal prediction of future cases, or trying to draw causal inferences that may guide future efforts at prevention? If your goal is the later, then you should be much more concerned with theoretical justifications of variable inclusion rather than statistical ones - i.e. accounting for bias is much more important than p-values for determining what should be in the model.
Answer: Testing each of the risk factors individually is probably not the best idea: what if a combination of two predictors that individually are not good, predict very well together? There are many methods available to do more proper variable selection, most of them some form of penalized regression, like (adaptive) lasso.
Apart from that: If you are willing to throw variables back out after adding them to the logistic regression, it doesn't really matter whether you do multiple testing correction or not: the unconditional strong association of a variable is not necessarily a good predictor of the conditional association (that is: conditional on all the other predictors included in the model). If you insist on doing this univariate variable selection: pick any criterion that gives you a reasonable set of variables (e.g.: the 20 variables with the smallest univariate p-values, or all variables that have p-values less than a threshold you think is nice), fit the model with those 20 variables (assuming you have enough data) and then throw the ones that don't perform conditionally in the model, back out.
Be aware, though: I did not tell you to do it this way. My advice is to use a proper variable selection method.


Why images in drawable folder are not showing in my Android compilation of Xamarin.Forms?

Question: I try to compile my Xamarin.Forms app and the images in the drawable folder can´t be loaded... The screen shows all the elements except images or icons.
I also get the error that says "obj/bin/debug/packaged_resources" doesn´t exist... It seems that this file is not being generated. I´m temporally avoiding this error by copy-pasting this file from another version of the app in my version control, but like I said before, images are not showing.
I have also checked the correct name of the image files to be compatible.
I have tried lots of purposes in Xamarin forums and cannot solve the problem. Any help would be appreciated. Thanks.
Comment: There're so many possibilities may cause your failure at showing an image. Without any code or image of your drawable folder etc...we can only guess, for the first thing, have you checked your resources' names? Do you have some  invalid characters like "-" in your resource's name? Please check this case: [Naming rules for Android resources](http://stackoverflow.com/questions/5949395/naming-rules-for-android-resources).
Comment: @GraceFeng-MSFT I´m trying with "Build action: Android resource" property in each image in drawable folder... It has to work like this, but is frustrating...
Comment: I have had this problem since I upgraded to VS 2017.  VS 2017 doesn't display errors when generating the resource file.  I normally open the solution back in VS 2015 and it will give me the correct error.
Comment: please share some code where you are trying to display images
Comment: try deleting your bin and obj folder and doing a clean build
Comment: Thank you all for the help... I have checked my resource names: all of them are correct now without capital letters or numbers and no "-" charachters...   I´m trying to display images by xaml like this:    I have also tryed deleting my bin and obj folder and still getting the same error...
Comment: The images are showing fine in the UWP and the iOS version.
Comment: @Saizant, not sure what happened, have you tried embedded resource?
Answer: Please add the file with the help of "Add file" context not copying directly or dragging in to the resource folder..
Also rebuild the project after adding those image files..
Answer: I had the same issue. If you exclude image in one of the drawable folder and then include then it become visible in preview as well.


PHP OOP Design Pattern

Question: I recently read an article on Wikipedia about Design Pattern
So far I've done this, but it returns Fatal error: Maximum function nesting level of '100' reached, aborting!
Logically I know, it will return nesting error, But, I don't understand how is the best step.
class Main {
    $this->Aa = new Aa;
    $this->Bb = new Bb;
    $this->Cc = new Cc;
    }
class Aa extends Main {
    function blahA() {
        // blah blah
        }
    function testA() {
        $ret[] = $this->blahA(); // Call inside class
        $ret[] = $this->Bb->blahB(); // Call outside class
        $ret[] = $this->Cc->blahC(); // Call outside class
        return $ret;
        }
    }
class Bb extends Main {
    function blahB() {
        // blah blah
        }
    function testB() {
        $ret[] = $this->blahB(); // Call inside class
        $ret[] = $this->Aa->blahA(); // Call outside class
        $ret[] = $this->Cc->blahC(); // Call outside class
        return $ret;
        }
    }
class Cc extends Main {
    function blahC() {
        // blah blah
        }
    function testC() {
        $ret[] = $this->blahC(); // Call inside class
        $ret[] = $this->Aa->blahA(); // Call outside class
        $ret[] = $this->Bb->blahB(); // Call outside class
        return $ret;
        }
    }

Basically i want to manage my classes design, in order the method in Aa class is also reusable in Bb class and vice versa.
I curious, how to build the relationship like my classes above, How to extends the class to get above pattern? And what is the name of this pattern? please also give me a link that i can learn from.
Many Thanks,
Comment: How in the world did reading about design patterns lead you to this monstrosity?  I think you need to read http://en.wikipedia.org/wiki/Anti-pattern next.
Comment: What's the name of this pattern? I'm curious, really
Comment: Use wikipedia only for first entry research. Then get the books an article is based on after you've found out it's the right topic.
Answer: Consider creating Aa and Bb separately and using Dependency Injection so each class will have a reference to the other. You should make sure the two classes are not too tightly coupled though.
The Gang of Four (GoF) Design patterns book mentioned in the comments is a good one, but the Head First Design Patterns is a bit easier (also very enjoyable) for beginners.
Here is an example. Notice there are better ways to set a property in PHP, I put a setter function just to be explicit. Refer to this question for more info.
class Main {
    $this->Aa = new Aa;
    $this->Bb = new Bb;
    $this->Cc = new Cc;

    // Can use properties instead of setters
    $this->Aa->setB(Bb);
    $this->Aa->setC(Cc);

    $this->Bb->setA(Aa);
    $this->Bb->setC(Cc);

    $this->Bb->setA(Aa);
    $this->Bb->setC(Bb);
    }

class Aa {                // No need to extend Main, right?
    function blahA() {
        // blah blah
        }
    // Dependency injection, Bb is now a member of this class
    // Consider doing this with PHP properties instead
    // Using setter function to be more explicit
    function setB(Bb b) {
        this->Bb = b;
        }
    // Dependency injection, Cc is now a member of this class
    // Consider doing this with PHP properties instead
    // Using setter function to be more explicit
    function setC(Cc c) {
        this->Cc = c;
        }
    function testA() {
        $ret[] = $this->blahA(); // Call inside class
        $ret[] = $this->Bb->blahB(); // Call outside class
        $ret[] = $this->Cc->blahC(); // Call outside class
        return $ret;
        }
    }
// Class Bb ...
// Class Cc ...

Comment: by the way, further reading: http://en.wikipedia.org/wiki/Inversion_of_control. And read de [Gof](http://en.wikipedia.org/wiki/Design_Patterns) if you want to know about (real) patterns
Comment: I agree. For something like this, Dependence Injection is what you would want.
Comment: @Brady : thanks, would you mind to show me, an example code? :-)
Comment: @naticap, Dependency Injection is a fancy way of saying using a setter on the objects. I'll add a little example.

PHP OOP Design Pattern


Keras: How to get layer index when already know layer name?

Question: I already knew the name of a layer of a model, now I want to know that layer's index.
Is there any available function to do that?
Thank you all.
Answer: Suppose your model is model and the layerName is name of the layer.
index = None
for idx, layer in enumerate(model.layers):
    if layer.name == layerName:
        index = idx
        break

Here index is the idx of required name.
Answer: The answer of Akhilesh as function:
def getLayerIndexByName(model, layername):
    for idx, layer in enumerate(model.layers):
        if layer.name == layername:
            return idx

Answer: An easy way of doing that is as follows:
layer_names = [layer.name for layer in model.layers]
layer_idx = layer_names.index(your_layer_name)

If you are doing visualization in keras, you can also achieve that as follows:
from vis.utils import utils
layer_idx = utils.find_layer_idx(model, your_layer_name)