Connect4 on Android, timing issue

Question: I'm developing a simple Connect4 game in Android.
Currently I'm using a minimax algorithm with alpha-beta pruning and bit-board state representation so the search is very effective and fast.
The skill is set by setting the maximum depth the algorithm should reach during its DFS search inside the game tree.
I noticed that the time required to choose a move depends on how far we are in the game: at the beginning it takes more time (as there are many possibilities to explore), in mid-game it take a reasonable amount of time and near the end is very fast.
My problem is that if I set a given skill the user has to wait to much on the first/second/third moves. I'd like to speed-up the aperture but I suspect it depends even on the hardware itself how I want to implement the speed-up process.
Can I set a timeout for the thread running the DSF mimimax?
Answer: The simplest way to circumvent this issue is to use an opening book for the first few moves. An opening book is a set of predetermined moves for a given scenario. Since there are relatively few possibly board states for the opening moves, you can easily compile a database of all possibly moves for the first three turns, and call upon it instead of actually doing the search. Thus you no longer require a time out and you sped up the search with zero cost to accuracy.

Connect4 on Android, timing issue


Why does hook_menu() not show my items in menu?

Question: Here's my code and I can't get why hook_menu doesn't work. My block menu doesn't showing in menu. As I understood this code (hook_menu()) should show link in which for will work drupal_post_form using function instance_export_form.
So I mean that when I follow admin/config/content/instances_export I get just content menu list, not a form which I need
    <?php

function instances_export_block_info()
{
    $blocks['instances_export'] = array(
        'info'  => t('Instance export'),
        'cache' => DRUPAL_CACHE_PER_ROLE,
    );

    return $blocks;
}

function instance_export_menu()
{
    $items = array();

    $items['admin/config/content/instance_export/settings'] = array(
        'access arguments' => array('administer site configuration'),
        'title'            => 'Configure export',
        'description'      => 'Chose what you want to export and where',
        'page callback'    => 'drupal_get_form',
    );

    $items['admin/config/content/instances_export'] = array(
        'title'            => 'Form to export data',
        'page callback'    => 'drupal_post_form',
        'page arguments'   => array('instance_export_form'),
        'access arguments' => array('administer site configuration'),
    );

    return $items;
}

Here info file
 name = Instance export and import module
    description = Allow to export synchronize few instance of Drupal
    core = 7.x
    version = «7.x-1.0»
    configure = admin/config/content/instances_export
    files[]=instance_export.module

Comment: Welcome to Drupal Answers :) "Doesn't work" isn't a reasonable problem statement, it's ambiguous and doesn't provide any real information about the issue. Please take some time to write a **detailed** question, which covers specifically what "doesn't work" means in this context. Please be sure to include what you _expect_ to happen, what _actually_ happens, error messages you see, and so on. Once there's enough info for someone unfamiliar with your site to be able to help, please flag for re-opening. Many thanks
Comment: @Clive actually doesn't work is quite clear for understating. the hook_menu must show custom elements in menu. doesn't work in this case means, that it doesn't show my items in menu
Comment: Trust me, it isn't clear at all. Why would you expect the above code to produce a block, for example? There's no `hook_block_view()` implementation. What's `drupal_post_form`? Why are you passing page arguments to one router item and not the other? And so on. To be useful to the knowledge repository, questions need to have no ambiguity at all. Only you can provide the context to make this a good question for that repository, which for the free expert help you're going to get, is a pretty fair trade-off.
Comment: As I understood this code (hook_menu()) should show link in which for will work drupal_post_form using function instance_export_form
Comment: Don't tell me, edit the question and put this in the form of prose
Comment: So i mean that when i follow admin/config/content/instances_export i get just content menu list, not a form which I need
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/42205/discussion-between-tgg132-and-clive).
Comment: See @Clive comment: You are using `drupal_post_form()` as page callback, but Drupal doesn't have that function. Since you had time to correct the shown code, I take you are actually using that code, which contains a typo.
Answer: There are a few things that look out of place there:

Your module name is instance_export so you should not use instance_export_form as a function name because Drupal will think that you are defining hook_form() and you will run into problems. Best to use function names that are less likely to clash with other modules.
The menu item admin/config/content/instance_export/settings is using drupal_get_form() as the callback but isn't passing in any form ID as 'page arguments'
The menu item admin/config/content/instances_export uses the page callback drupal_post_form(), which is not a Drupal function. I assume you want drupal_get_form() here also.

Something like this should work better:
function instance_export_menu() {
  $items = array();

  $items['admin/config/content/instance_export/settings'] = array(
    'title'            => 'Configure export',
    'description'      => 'Chose what you want to export and where',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('instance_export_settings_form'),
    'access arguments' => array('administer site configuration'),
  );

  $items['admin/config/content/instances_export'] = array(
    'title'            => 'Form to export data',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('instance_export_export_form'),
    'access arguments' => array('administer site configuration'),
  );

  return $items;
}

Note that I made up a form function for the first menu item (instance_export_settings_form) and changes the one for the second menu item (instance_export_export_form). This would be whatever you want your functions to be.
Also, if you want these pages to be tabs in your module's admin area do it like this instead:
function instance_export_menu() {
  $items = array();

  $items['admin/config/content/instance_export'] = array(
    'title'            => 'Configure export',
    'description'      => 'Chose what you want to export and where',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('instance_export_settings_form'),
    'access arguments' => array('administer site configuration'),
  );

  $items['admin/config/content/instance_export/settings'] = array(
    'title'            => 'Configure export',
    'type'             => MENU_DEFAULT_LOCAL_TASK,
  );

  $items['admin/config/content/instances_export/export'] = array(
    'title'            => 'Form to export data',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('instance_export_export_form'),
    'access arguments' => array('administer site configuration'),
    'type'             => MENU_LOCAL_TASK,
  );

  return $items;
}

I'm assuming that your hook_block_info() is not relevant to this question.
Comment: I made some assumptions on what you are trying to achieve. This code assumes that you want 2 administration forms, one for export settings and one that is the export form itself.


Customize datagrid to show connectivity between tasks

Question: I have made a program in Flex for creating simple schedules, similar to MS Project or Vico Control. I have one problem that I would like to solve. (You can see it here: OnTime Project Scheduling tool made in Flex
The tasks of the schedule are represented as Gantt Chart, for which I created a itemRenderer inside one of the rows in the DataGrid. The tasks are shown as gantt diagrams, but I would also like to show the connectivity between tasks.
Please take a look at the image below, to see what I am trying to accomplish here: (above is the image of how datagrid looks now, and below is the thing I would like to add)
alt text http://img202.imageshack.us/img202/1399/gantt.jpg
Any suggestions as to how I could do this inside DataGrid's item renderer?
Thanx a lot
Ladislav
Comment: See below. I told you we'd talk.
Answer: OK, here's what you need to do.

In your dataProvider, have one field be an object (you should make it a class) that contains the following properties:
start:Number (percentage)
length:Number (percentage)
index:int
[optionial props isFirst:Boolean, isLast:Boolean]
Create an itemRenderer using a container (let's say a Canvas) and using the graphics class draw a rectangle, the left edge of which corresponds to the start property. This will be a percentage of the width of the itemRender and can be determined from the unscaledWidth in the updateDisplayList protected method of the class, which you will override. Similarly, the width of the rectangle corresponds to the length property of your object, as a percentage of the width of the Canvas. Give it any height you like.
Draw the connectors. Use the graphics class again to draw the horizontal lines in and out of the sides of the rectangle. Give these a constant length. Draw lines from the ends of the horizontal lines: up to 0 for the left-side one, down to this.height for the right-side one.
Figure out how far you need to draw the intermediate connector for it to appear to connect to the line above it. This only needs to be done for the top of the itemRenderer.
If isStart=true (index of object is 0), don't draw anything on the left or top of the rectangle. If isEnd=true (index of object is ArrayCollection.length -1), don't draw anything on the right or bottom.

And you're done. You will need to understand how to draw with the graphics object, but this is pretty easy and is something you should have in your repertoire anyway.
Comment: Hey Robusto,

will try to make it work, and let you know you of the result, thanx
Ladislav


How to execute a particular part of code asynchronously in a class

Question: I am creating a speech recognition Engine that's going to respond to user Commands.I have created a Button to enable and disable Speech recognition as per user convenience.I have used Dispose() of Speech engine to disable speech recoginition.here is the code
<code>private  void button1_Click(object sender, RoutedEventArgs e)
    {
        engineOn = !engineOn;
        if (engineOn)
        {
            speechEngine = speech.createSpeechEngine();     //speech is a class that creates and returns a new speech engine.
            speechEngine.AudioLevelUpdated += new EventHandler<AudioLevelUpdatedEventArgs>(speechEngine_AudioLevelUpdated);
            // use the system's default microphone
            speechEngine.SetInputToDefaultAudioDevice();
            speechEngine.LoadGrammar(new DictationGrammar());

            // start listening
            speechEngine.RecognizeAsync(RecognizeMode.Multiple);
        }
        else
        {
             SpeechClass.myEngine.Dispose();
        }

    }
</code>
But Disposal of speech object takes time.How to do that asynchronously?
is is there any other way to turn Speech recognition on and off?  thanks in advance.
Comment: Have you looked at RecognizeAsyncStop method? http://msdn.microsoft.com/en-us/library/system.speech.recognition.speechrecognitionengine.recognizeasyncstop.aspx
Answer: You just use RecogniseAsync / RecogniseAsyncStop to turn it off and on again:
http://msdn.microsoft.com/en-us/library/system.speech.recognition.speechrecognitionengine.aspx
Alternatively, you could try loading an empty grammar list so essentially the kinect has nothing to listen out for.
Additionally, I'd avoid disposing the object altogether unless you no longer want to use (e.g. When the application is shutting down). There are major overheads associated with the disposing of the object (particularly the speechrecognitionengine), then recreating it again.


Automatically mount drives when debian server reboots

Question: I have a Debian server (which is a AWS EC2 Instance) and I have multiple AWS volumes attached to the server, which are all mounted in /mnt. However if I ever reboot the server (which happens whenever I create an AMI image), when it reboots all the drives are no longer mounted. I can easily remount them but I am a little concerned that it may get rebooted by someone else in the future so I was wondering if there was a way to automate the mounting.
Comment: Note: I'm aware of the no-reboot option when making AMIs, but that's not the point ;)
Comment: Is this a virtual server?
Comment: Ah yes, sorry AWS = Amazon Web Services. So yea! Does it make a difference though?
Comment: @Downvoter, care to share a reason?
Answer: This is configured in /etc/fstab using the auto option.
Comment: `auto` is included in `defaults`.
Answer: Check out the /etc/fstab file. man fstab for more information about setting it up.


How to use an interface on an empty object which gets populated at a later stage

Question: I'm not really sure how to describe this.
But I want to define an empty object which I want to populate with data. Now on forehand I know what I want the object ultimately should look like:
interface BodyInterface {
  name: string;
  lastName: string;
}

Some data is coming from a form submit, which looks like this:
// data is formdata which looks like:
// name: "foo"
// lastName: "bar"

Now to add that into an object what I want to use later:
const body = {}; // <- how do I use the BodyInterface on this body

someArray.forEach(({ name, value }) => {
  body[name] = data.get(name).value as string;
});

How do I do that?
Answer: This can be achieved using as:
const body:BodyInterface  = {} as BodyInterface;

Comment: Worth noting that you will lose some typing by doing this. Typescript won't know if you missed a property.
Answer: Rohan Agarwal will work, but important to note that Typescript will no longer warn you of missing properties.
A version of this is to use a Partial.
const body:BodyInterface  = Partial<BodyInterface>;

It's similar, typescript will typecheck all the properties, also not warn you of missing ones but now you have a type that actually represents that knowledge.
It's not easy to convert this to a non-partial version of BodyInterface though.
In my pre-typescript and early typescript code I would also often gradually build up objects before returning them from my functions. I found that if I want to work with typescript and get the most value, it's better to stop this practice altogether. Build up your individual properties in variables instead, and as a very last step build the entire BodyInterface all at once.
This requires changing habits, but you will get the most value out of what Typescript can do for you.
Comment: Thank you. Perhaps a bit bold, but may I ask for an example of how you'd build that object?
Comment: @Remi I basically end with something like: `const body:BodyInterface = { thisProperty, theOtherOne, ...AllTheOtherProperties }` as the last step, or `return { thisProperty, etc }`


Namer Server Propagation DELAY / Private DNS

Question: I have the below setup at my registrar .
Main DOmain = abc.com
Second Domain = def.com
Third DOmain = ghi.com
As such , I have configured the below DNS / Host settings .
abc.com
NameServer : ns1.myhost.com & ns2.myhost.com
Hosts : ns1.abc.com & ns2.abc.com (both are pointing to my two IP addresses at my host.)
def.com
NameServer : ns1.abc.com & ns2.abc.com
ghi.com
NameServer : ns1.abc.com & ns2.abc.com
H/e it's been 72 Hrs since the initial changes and STILL the DNS Propagation is shown incomplete as per the below sites.
http://dnscheck.pingdom.com/?
https://www.nexcess.net/resources/tools/global-dns-checker

My registrar is GoDaddy , And I initially (day1) replicated the same host entries on BOTH abc.com & def.com . H/e I found out and then setup the servers as above 50 Hrs ago.

** The records at ICANN is showing the NEW dns zone files :-)
Thanks & Best Regards,
Lakshitha Ab
Comment: Without the actual domain names to check the public records all anyone can realistically do is guess.  What are you expecting to see but not seeing?  'Incomplete' is a bit vague.
Comment: Main Domain (abc.com)  = hostmeraki.com

Second Domain (def.com) = codemeraki.com

Third Domain (ghi.com) = rbnsrilanka.org & rbnsrilanka.com

* By Incomplete , I'm referring to the fact that the NS records shown on the DNS Check sites I've mentioned reflect the OLD ns records I've configured for the respective domains (faceshared) .

But on the ICANN WHOIS page all the correct records (ns.hostmeraki.com) is showen.
Answer: You have changed the NS records in the delegation information (in the parent zone, managed through your registrar) but the authoritative NS records (in your own zone) do not match.
Always make sure to verify that your changes are correct (by querying the authoritative servers) before you start to wait for caches to expire.
dig +trace +add example.com NS will demonstrate this type of error.

When following the chain of delegations the problem is quite clear in all three cases:
Delegation information
codemeraki.com.         172800  IN      NS      ns2.hostmeraki.com.
codemeraki.com.         172800  IN      NS      ns1.hostmeraki.com.

Authoritative information
codemeraki.com.         86400   IN      NS      ns2.faceresellerasia1.com.
codemeraki.com.         86400   IN      NS      ns1.faceresellerasia1.com.

Delegation information
rbnsrilanka.org.        86400   IN      NS      ns2.hostmeraki.com.
rbnsrilanka.org.        86400   IN      NS      ns1.hostmeraki.com.

Authoritative information
rbnsrilanka.org.        86400   IN      NS      ns1.faceresellerasia1.com.
rbnsrilanka.org.        86400   IN      NS      ns2.faceresellerasia1.com.

Delegation information
rbnsrilanka.com.        172800  IN      NS      ns2.hostmeraki.com.
rbnsrilanka.com.        172800  IN      NS      ns1.hostmeraki.com.

Authoritative information
rbnsrilanka.com.        86400   IN      NS      ns2.faceresellerasia1.com.
rbnsrilanka.com.        86400   IN      NS      ns1.faceresellerasia1.com.

Comment: Awesome !! Thanks a lot I got the issue sorted DNS propagation in the correct way has begun :)


Why does it matter how we end up a shoot or a pass, in terms of the footwork involved?

Question: I have generally seen in many of the youtube videos, which attempt to teach how to hit a knuckleball perfectly, they tell that after striking the ball, one should not take the foot too far ahead, rather stop it almost instantly. For some specific type of passes like the ping, the driven ball, etc a similar advice is given.
What I want to ask is why does it matter to instantly stop our foot movement after the impact with the ball during a shoot or a pass?
The reason why I am asking this is that sometimes I think that after we have struck the ball, the ball will do what it has to just because of the impact of our foot at the moment of shooting, not because how we end up our shoot or if we arrest our foot movement or not.
I hope I'm clear with my question, and also that it's not a stupid question. However, I know that if I take my foot along with the ball after striking it, it will not go as I wish (in case of knuckleball). So I want to ask why that is so.
Comment: Perfectly clear and interesting question which also produced an excellent answer. Don't see any reasons why it should be voted to close.
Comment: Well, no, it's not perfectly clear, if someone with an excellent grasp of English has to ask that it be edited to make it more clear. If you think it's so abundant unambiguous, you should edit so we don't need to closevote.
Comment: I'm not downvoting because you're obviously making an effort to get the point across and establish a good question, but I'm voting to close because I've tried twice and still can't decipher exactly what you're asking so that I can edit to make it clearer for others.
Comment: I want to know why is it necessary for someone like me, who wants to know how to strike a knuckleball perfectly, to just stop my foot as soon as I strike it?
Answer: If I understand your question right, I think it is matter of physics.
What you are saying would make sense if the foot and the ball are perfectly hard objects: when they collide, there is only one point of impact so it would not matter what your foot does after the impact.
But as the foot and the ball are soft materials, there is not only one point of impact but several ones. Also, the foot and the ball stay in contact for a short moment.
You can find extreme slowmotion videos like this one where you can see that the ball and the foot are in contact for a few frames.
How your foot moves after the first impact is very important because it will apply the desired effect; if your foot doesn't execute the right movement after the first contact it could do some unwanted other contacts that will add unwanted effects on the ball.
Answer: The accepted answer to this question does a good job at explaining the physics behind why these kinds of rules exist, but I'd like to add that in some scenario's, the followthrough serves as a psychological trick for the player: if you're concentrating about not making your foot swing after hitting a knuckleball, that might very well change the way you think about the shot itself, and thus help as a memorisation tool of how to hit the ball for your brain.
Comment: That's right, the same way that in throwing sports like darts or pétanque, it is advised to keep the correct movement even once the object has left the hand.


Custom node template with related node teasers

Question: I have a custom node (article) template file working fine, and I want to show related nodes (events) in their teaser format. I have been doing this in my node--article.tpl.php file like this:
foreach ($field_related_event as $event_node){
    print render(node_view(node_load($event_node['nid']), 'teaser'));
}

I wanted to add a second teaser format for events (teaser_fancy) and downloaded "Entity view modes" thinking I would be able to do something like this:
foreach ($field_related_event as $event_node){
    print render(node_view(node_load($event_node['nid']), 'teaser_fancy'));
}

But now I read that node_view can only use teaser and full, and it's probably not a good idea to render relationships in my template this way. What's the recommended way to go about this? Should I create an Events Fancy view and use views_embed_view instead?
Answer: A valid "view_mode" should work with node_view and that approach looks reasonable.
However, if it's proving problematic, you can also use Views with views_embed_view
e.g
print views_embed_view('viewname', 'display_id', $node->nid); // node id contextual filter

Comment: Thanks that's what I suspected. Do you think there is a big downside to using rendering the way I am is I want all related items?


How can I change the C++ standard used by the Code Runner extension for VS Code?

Question: I'm trying to use C++20 in VS Code with the Code Runner extension, which allows me to run code using ctrl+alt+n.
I have installed MinGW64 through the MSYS2 installer.
My compiler version is 12.0.2.

In my c_cpp_properties.json file, I have set cppStandard to c++20.
For good measure, in my settings.json file, I added "C_Cpp.default.cppStandard": "c++20".
In my tasks.json file, I have added "-std=c++20" to the args field.

When I type __cplusplus in my C++ file and hover my mouse over it, the hover info says "# define __cplusplus 202002L".
But the Code Runner extension is still not using C++20. Why? How can I make it use C++20?
Answer: You need to edit the code-runner.executorMap setting to add the C++ standard selection flag there. Perhaps something like this:
"code-runner.executorMap": {
  "cpp": "cd $dir && g++ -std=c++20 $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt"
}

You're seeing "# define __cplusplus 202002L" in your hover info because that's controlled by the vscode-cpptools extension- a separate extension from the Code Runner extension, which reads your c_cpp_properties-related settings.
tasks.json is a VS Code feature, which I assume you're using to define a build task. I think there's usually not much reason to have both a build task in the tasks.json as well as usage of Code Runner, because Code Runner will handle building and running (but it's really only good for extremely simple use-cases).
As far as I know, the Code Runner extension doesn't care about your tasks.json tasks, or your vscode-cpptools settings.
Loosely related issue ticket: Update default settings of code-runner.executorMap to support c++11 or higher versions #397.


Why we use init() rather Constructor

Question: why do we need init() rather than a constructor?
Please answer in reference of Servlet and Applet.
How does the init() of Applet differ from Servlet?
Comment: That are 2 questions. You should ask one question in a question.
Comment: possible duplicate of [Servlet constructor and init() method](http://stackoverflow.com/questions/143386/servlet-constructor-and-init-method)
Answer: The init() method creates and loads the servlet. But the servlet instance is first created through the constructor (done by Servlet container). We cannot write constructors of a servlet class with arguments in servlet (It will throw Exception). So, They provided a init() method that accepts an ServletConfig object as an argument. ServletConfig object supplies a servlet with information about its initialization (init) parameters. Servlet class cannot declare a constructor with ServletConfig object as a argument and cannot access ServletConfig object.
More info at: http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets6.html
Comment: Based on your reference I'd change `creates and loads` by `initializes` or `prepares`.
Comment: The above is correct, I'd add that splitting object creation and initialization allows the servlet container to re-use the same servlet instance for different requests, reducing time and memory consumption.
Comment: @madth3: what about `applet`s?
Comment: more or less the same reason: http://www.javaworld.com/javaworld/javaqa/1999-10/04-qa-appletconst.html
Answer: You need both, but they perform different activities, your constructor executes at the time the object is created through a call to new, but for some type of objects where you don't control their creation, or you would rather execute some code not only after the object is created but is fully intialized, then you need an special method that someone is going to call to signal that the object is ready.
That is the case specially for objects that are not managed by you, but the server, framework or whoever manages these objects.
You should see this methods as a commodity provided for you on the top of the code that this object will execute on the constructor
Answer: It's a design choice. The servlet spec says that you must provide a no-arg constructor and you can override the init() method to perform initialization tasks.  They could have chosen to do otherwise and require servlets to have a single argument constructor (ServletConfig) that optionally throws ServletException.  Technically, there is no problem with that as reflection API allows you to invoke any constructor declared in a class.
However having an init() method allows servlet containers to pre-instantiate objects and delay their initialization.  It helps separate different stages of the lifecycle.
Personally, I don't think this is a strong design choice.  It would have been much more convenient to let the web application provide servlet container with pre-instantiated servlets rather than having to let the container call the constructors of various servlets.
Comment: BTW, as long as your initialization code does not depend on the ServletContext or servlet config, you can put code in the no-arg constructor.
Answer: init() method is invoked only once and therefore only one instance of the controls will be created.

Why we use init() rather Constructor


php recursive merge

Question: I need to merge some arrays in some different way and I use array_merge_recursive.
However there is something that I need to change and I don't know how.
Here is quote from php.net

If, however, the arrays have the same numeric key, the later value
  will not overwrite the original value, but will be appended.

I want this value, NOT to be appended, I want not to append exact values in the new array.Hope you've understood this.
Example:
$array = array(
   'some'  => array(
       'other'    => 'key',
   ),
);

$array2 = array();
$array2['some']['other'] = 'key2';

If I use array_merge_recursive It will result this:
Array (
    [some] => Array
        (
            [other] => Array
                (
                    [0] => key
                    [1] => key2
                )
        ) )

I want if it matches the same result, not to append it.Yes I know, you would say, then use array_merge, but it doesn't work well, too.
If I use this:
$array = array(
   'some'  => array(
       'other'    => 'key',
   ),
);

$array2 = array();
$array2['some']['other2'] = 'key2';

print_r(array_merge($array, $array2));

It will remove $array[some][other] from the list and leave only $array[some][other2].I don't know which is better, since no one makes it better.
Comment: How deep is the nesting in your array? Just one level?
Comment: So tell us what your result should be?
Comment: @Alex: What do you expect for executing that: $array = array(
   'some'  => array(
       'other'    => 'key',
   ),
);
$array2['some']['other'] = 'key2'; when using array_merge_recursive?
Comment: Well It may be unlimited.I won't use it only for 1 level.
Comment: @scube the result should be (if using array_merge) NOT to remove the prevous items from the first array.

The second example shows:

Array
(
    [some] => Array
        (
            [other2] => key2
        )

)

And I want to show:

Array
(
    [some] => Array
        (
            [other]  => key
            [other2] => key2
        )

)
Comment: Well I wanted to explain that recursive doesn't fit what I need.Maybe the title confised you.Sorry.
Answer: For PHP >= 5.3 just use array_replace_recursive
Answer: try this
<?php
function mymerge(&$a,$b){ //$a will be result. $a will be edited. It's to avoid a lot of copying in recursion
    foreach($b as $child=>$value){
        if(isset($a[$child])){
            if(is_array($a[$child]) && is_array($value)){ //merge if they are both arrays
                mymerge($a[$child],$value);
            }
            //else ignore, you can add your own logic, i.e when 1 of them is array
        }
        else
            $a[$child]=$value; //add if not exists
    }

    //return $a;
}

Comment: This answer may not be correct probably. Because I tested your answer and results is not like what I expected.
Can you please take a look at this link ?
[link](https://stackoverflow.com/a/25712428)
Answer: An other alternative, the array_merge_deep from drupal:
function array_merge_deep($arrays) {
  $result = array();
  foreach ($arrays as $array) {
    foreach ($array as $key => $value) {
      // Renumber integer keys as array_merge_recursive() does. Note that PHP
      // automatically converts array keys that are integer strings (e.g., '1')
      // to integers.
      if (is_integer($key)) {
        $result[] = $value;
      }
      // Recurse when both values are arrays.
      elseif (isset($result[$key]) && is_array($result[$key]) && is_array($value)) {
        $result[$key] = array_merge_deep(array($result[$key], $value));
      }
      // Otherwise, use the latter value, overriding any previous value.
      else {
        $result[$key] = $value;
      }
    }
  }
  return $result;
}

Answer: I wrote my merge class for it:
<?php

class ArrayMerge
{

    /**
     * @param array $a
     * @param array $b
     *
     * @return array
     */
    public function merge ( $a, $b ) {
        foreach ( $b as $k => $v ) {
            if ( is_array( $v ) ) {
                if ( isset( $a[ $k ] ) ) {
                    if ( $this->isDeep( $v ) ) {
                        $a[ $k ] = $this->merge( $a[ $k ], $v );
                    } else {
                        $a[ $k ] = array_merge( $a[ $k ], $v );
                    }
                } else {
                    $a[ $k ] = $v;
                }
            } else {
                $a[ $k ] = $v;
            }
        }
        return $a;
    }

    /**
     * @param array $array
     *
     * @return bool
     */
    private function isDeep ( $array ) {
        foreach ( $array as $elm ) {
            if ( is_array( $elm ) ) {
                return TRUE;
            }
        }
        return FALSE;
    }

}

Answer: I started from RiaD's version and added object handling. Need testing and feedback
function recursiveMerge(&$a,$b){ //$a will be result. $a will be edited. It's to avoid a lot of copying in recursion
        if(is_array($b) || is_object($b)){
            foreach($b as $child=>$value){
                if(is_array($a)){
                    if(isset($a[$child]))
                        recursiveMerge($a[$child],$value);
                    else
                        $a[$child]=$value;
                }
                elseif(is_object($a)){
                    if(isset($a->{$child}))
                        recursiveMerge($a->{$child},$value);
                    else
                        $a->{$child}=$value;
                }
            }
        }
        else
            $a=$b;
    }

php recursive merge


Clonning/Duplicating and filling data in Layout dynamically through JAVA from Firebase - Android

Question: I want to clone/Duplicate a linear_layout, through java from Firebase reatime-database.

I the screenshot I have a child history which contains user_id's and it's childs and so on. I want to put it dynamically in this layout.

I have statically copied the layout three times, but I want to make it dynamic, same as the size of the history table entries with current user id.
Also I do have a class User with getter setter and constructor.
Answer: To get the user ids under the history node and use them to add a User object to the database, please use the following code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("history").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String key = ds.getKey();

            DatabaseReference keyRef = rootRef.child("users").child(key);
            User user = new User(/* ... */); //Pass data to the constructor
            keyRef.setValue(user);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage());
    }
};
uidRef.addListenerForSingleValueEvent(valueEventListener);

Comment: Hi Hafeez! Have you tried my solution above, does it work?
Comment: Hi Alex Mamo, yup it's helpful, but my main target of the question is how can i put it to the repeating XML dynamically, though your answer helped in retrieving data from firebase.
Comment: Good to hear that :) There was nothing specified in your question about "repeating XML dynamically" but this sounds basically as another question. In order to follow the rules of this comunity, please post another fresh question, so me and other users can help you.
Comment: "Clonning/Duplicating and filling data in Layout dynamically through JAVA from Firebase - Android" That's the question, do you really think you answered me to the point? Ok, if the community allow only questions, that should be answered in a single scenario, then help me out in repeating my xml layout, as i mentioned in the question.
Comment: You should make your own attempt given the information in the answer, and ask another question if something else comes up.
Comment: It's up to you to decide if my answer was helpful, so you can accept it or not.
Comment: I am afraid, i can't, sorry... And thanks for your kind words!


Internal/External JS don't work with Drupal, but works fine in static HTML/JSFiddle

Question: Continued from here Applied JS to Drupal theme doesn't work correctly, but it works fine outside Drupal
Working JSFiddle: http://jsfiddle.net/tbq8eo8b/10/ (it calculates total, in Drupal it calculates zeros - why?)
Raw:
<code>$(document).ready(function () {
    var $selects = $("select").change(function (e) {
        var total = 0;
        $selects.each(function() {
            var val = this.value.match(/\$(\d+)/);
            total += val ? +val[1] : 0;
        });
        $(".total").val(total);
    });
});
</code>
Drupal:
<code>(function ($) {
Drupal.behaviors.totalAmount = {
attach: function(context, settings) {

/*Add your js code here */
    var $selects = $("select").change(function (e) {
        var total = 0;
        $selects.each(function() {
            var val = this.value.match(/\$(\d+)/);
            total += val ? +val[1] : 0;
        });
        $(".total").val(total);
    });
}
};
})(jQuery);
</code>
2nd attempt with internal Drupal:
<code>  <script src="http://code.jquery.com/jquery-1.9.0.js"></script>
  <script>
  $(document).ready(function () {
    var $selects = $("select").change(function (e) {
        var total = 0;
        $selects.each(function() {
            var val = this.value.match(/^\$(\d+)$/);
            total += val ? +val[1] : 0;
        });
        $(".total").val(total);
    });
});
  </script>
</code>
As you see the code is identical (except Drupal wrappings), so why it's not working on Drupal? Why it prints zeros in .total field, but in JSFiddle it works fine?
Comment: Add `console.log(this.value);` just before or after `var val = this.value.match(/^\$(\d+)$/);` and tell us what's there. Similarly, `console.log($selects.count);` before ` $selects.each(function() {`, please :)
Comment: It just prints single numbers per line like 1, 2, or '(an empty string)'. And the $selects.count line gives 'undefined'.
Comment: Try removing $ sign before selects variable as it is not needed in js and may be confusing there.
Comment: It still prints zeros. And no errors. So it's same with or without $.
Comment: OK, and what's in `console.log( val ? +val[1] : 0 );`? I have my suspicion now, but I need to know this one thing, to confirm or discard it before I'll post answerer.
Comment: 4 zeros '0' per line for every select list action. Unless I included in wrong place that console.log line.
Comment: @OptimusPrime OK, my suspicion was wrong. I know, not helpful for you. Sorry.
Comment: @OptimusPrime: How are the select field's options set up? In your fiddle example, the select options have no "internal" value but in webforms options must be set as key|value and `this.value` would than return the key. - EDIT: To clarify, in the fiddle it reads `$200` but webform would produce something like `$200`.
Comment: Have you tried assigning the `select` lists to a variable first, before you actually use it in a `.change()` statement? That `$selects gives undefined` line is a pretty big clue to me that the variable is not initialized yet. Or you may want to be a bit more explicit about the selectors, like `$('#content select')` or something like that. My advice is start very simple! Then work your way up. Debug your steps.
Comment: Can you share code examples of how you think it should look via jsfiddle? Honestly I don't get it what's wrong with Drupal running this script, it works fine outside it.
Comment: Did you see my updated answer? It works in my test environment now.
Answer: I've rebuilt the scenario and my guess now is that you don't want the value of the select field but the option text for your parsing purpose. Thus, the script should probably be something like this:
<code>(function ($) {
Drupal.behaviors.totalAmount = {
attach: function(context, settings) {

    /*Add your js code here */
    var selects = $("select").change(function (e) {
        var total = 0;
        selects.each(function() {
          var val = $("#"+this.id+"  option[value='"+this.value+"']").text().match(/\$(\d+)/);
          total += val ? +val[1] : 0;
        });
        $(".total").val(total);
    });
}
};
})(jQuery);
</code>
This is how it looks like working:

This is how the first select's options are setup as a webform component

To retrieve prices, one would need to change the regex line to
<code>var val = $("#"+this.id+" option[value='"+this.value+"']").text().match(/\$(\d+(\.\d{2})?)/);
</code>
Working example:

To have the total always be display with trailing zeros, replace the last script line with
<code>$(".total").val(total.toFixed(2));
</code>
To make the script also work with thousands separator, change the script into
<code>(function ($) {
Drupal.behaviors.totalAmount = {
attach: function(context, settings) {

/*Add your js code here */
    var selects = $("select").change(function (e) {
        var total = 0;
        selects.each(function() {
                var val = $("#"+this.id+" option[value='"+this.value+"']").text().match(/\$(\d{1,3}(,\d{3})*(\.\d{2})?)/);
                        total += val ? +parseFloat(val[1].replace(/,/g,'')) : 0;
        });
        $(".total").val('$'+total.toFixed(2));
    });
}
};
})(jQuery);
</code>
Comment: First, the key line is `var val = $("#"+this.id+"  option[value='"+this.value+"']").text().match(/\$(\d+)/);` where I get the option element (child of select) which has the selected value, retrieve the text content and then do the regex. The regex currently only looks for integers as `\d+`stands for any number of following digits (no period). You would need to change that to `\d+(\.d{2})?` for price tags.
Comment: Wow thanks for helping. I'm about to test it out. I avoid the values, because the end-user would be creating those forms from time to time with various settings and fields and who knows what values they will use and etc.
Comment: Woah, looks like it works great. I still don't get it what you did. Also any ideas when selecting $42.30 it gives in total amount only 42, why it strips 30 cents?
Comment: I still get the same. Does it work for you if you replace it?
Comment: See updated answer for the replacement line and a screenshot. I forgot a backslash in my last comment (sorry).
Comment: Thanks very much, it works now, but there's another issue. It doesn't pickup in thousands because they have commas e.g. $1,123.50 But it all works up to $999.99
Comment: Thousands separator in javascript is not as straight forward as decimal point, but it's possible. Drawback: you need to replace the commas which turns the value into a string, so we would need parseFloat to turn it back in to a number. See updated answer.
Comment: All works great. Cheers.


Updating UI / runOnUiThread / final variables: How to write lean code that does UI updating when called from another Thread

Question: I have been reading up on the UI updating when I found out that, like WinForms, Android need to do UI updates on from the main thread (too bad, I was hoping someone could once and for all solve that irritating problem).
Anyways, I need to pass that to the UI thread. Some suggest the use of the runOnUiThread method and that might have worked, if it wasn't for that irritating "final" that then came into play.
I have an Interface, with a method I cannot change. It looks like this:
<code>@Override
public void connStateChange(ClientHandler clientHandler)
</code>
That method is called when I get a change in the connection status (network). When I do, I need to do some stuff, and in this case it is adding some text to a TextView.
So I tried this, but of course the variable "clientHandler" isn't final:
<code>@Override
public void connStateChange(ClientHandler clientHandler) {

   runOnUiThread(new Runnable()
   {
      public void run()
      {
        tv.append(clientHandler.getIP() + ", " + clientHandler.state.toString() + "\n");
        if (clientHandler.state == State.Connected)
        {
            tv.append("Loginserver hittad");
        }
      }
   });
}
</code>
How do I in a nice, clean and efficient way write code in this example to update the UI? I need access to all my variables etc...
Answer: Try it:
<code>@Override
public void connStateChange(ClientHandler clientHandler) {
    final ClientHandler temporaryHander = clientHandler;
    runOnUiThread(new Runnable() {
         public void run() {
               tv.append(temporaryHandler.getIP() + ", " + temporaryHandler.state.toString() + "\n");
               if (temporaryHandler.state == State.Connected) {
                    tv.append("Loginserver hittad");
               }
         }
    });
}
</code>
By the way, code becomes more readable, if you declare not anonim class right in the method, but declare inner class out of methods. Consider it as pattern Command.
Example of more clean and reusable code.
<code>@Override
public void connStateChange(ClientHandler clientHandler) {
    final ClientHandler temporaryHander = clientHandler;
    runOnUiThread(new MyRunnableCommand(temporaryHandler));
}

private class MyRunnableCommand implements Runnable {

     private ClientHandler clientHandler;

     public MyRunnableCommand(ClientHandler clientHandler) {
         this.clientHandler = clientHandler;
     }

     @Override
     public void run() {
               tv.append(clientHandler.getIP() + ", " + clientHandler.state.toString() + "\n");
               if (clientHandler.state == State.Connected) {
                    tv.append("Loginserver hittad");
               }
         }

}
</code>
Though the Runnable implementation itself was inflated a little, code became more re-usable and easy to read.
Comment: I actually feel that anon classes, directly in the methods, are much clearer than anything else I have come across. However, Im not sure what a Command pattern is, so I will look into it.
Comment: As you wish. As for me, I tend to write reusable and Spartan code. Inner-in-class classes are more flexible than inner-in-methods ones. Also, method becomes more compact.
Comment: Can you link to some example that is clear, so that I get the difference? Cause I dont think I am =)
Comment: Sorry, no links :) I'll re-write the answer.


Intercept in Multiple logistic regression

Question: I've run a multivariable logistic regression on 8 variables and my results are a bit puzzling.
The intercept (that is the log odds when the other covariates = 0) is significant (p<0.001), but the p-values of all my other covariates is non-significant.
My question for performing this regression is to answer the question: what variables predict the use of Tool X? The nonsignificant coefficients for all of the variables mean they don't predict the use, but it doesn't make sense that if you don't have these variables, it will suddenly be able to predict usage?
I don't think I have a strong grasp of multivariable logistic regression, so I would be very grateful if anyone can give some advice on this matter.
Answer: As you put it, the intercept is the log-odds when all covariate values equal 0. See this page, for example.
The standard test for "significance" of an intercept is whether its value differs significantly from 0. So what you have found is that the log-odds of using Tool X are different from 0--that is, odds are different from 1--when all covariates in your model have values of 0. So to that extent you can make a reasonable prediction about log-odds--not "without" those variables, but with their values all at 0. As the page linked in the previous paragraph notes, this is different from some "average" odds of using Tool X absent information about the covariates.
Note, however, that even variables with "nonsignificant" coefficients can be helpful in making predictions. This is even the case in standard linear regression, and it's particularly so in logistic regression with its inherent omitted-variable bias.
Answer: It can be illuminating to look at a logistic regression for, say, disease ($D$) with two dichotomous explanatory variables, say $E$
[1=exposed, 0=unexposed] and $G$ [1=female, 0=male].
If one considers : $p=pr(D) : logit(p) = \beta_0 +\beta_1 E + \beta_2 G + \beta_3 GE$, then $\beta_0$ is the log odds of disease for unexposed men and $\beta_1$ is the log odds ratio specific to men.
If however, one considers $logit(p) = \beta_0 +\beta_1 E + \beta_2 G$ then $\beta_0$ does not have a simple or useful interpretation. Here $\beta_1$ is the log odds ratio assumed common to men and woman.
Additive models [i.e. models without products of the explanatory variables] can have many caveats in the interpretations of the regression coefficients.
As well, the fit of your model with 8 explanatory variables may be facing issues of multicollinearity. Sometimes, it can be best to try a much simpler non-additive model to understand the issues at play.


Is it possible to do OAuth authentication identifying yourself as someone else?

Question: I'm writing a web app that connects to social media services (Facebook, LinkedIn, etc.) to collect a person's contacts for publicity purposes. The person wants this service and is paying for it, and recognizes my company and app name when it pops an OAuth dialog that says Contact Manager from Company Y would like to access your connections. Do you want to allow this?
However, now I want to license my app to a publicity agency which would use the app to manage contacts for their clients. The app would then have to send an OAuth request to their client, except that the client hired the agency not me, and they won't recognize my company and app name.
So the question is: can my app identify itself on behalf of the agency, and say to the user Contact Manager from Your PR Agency would like to access your connections. Do you want to allow this? so that the person reading this will know that the request is coming from someone they know, instead of me, whom they don't know?
Answer: Normally you will need to register different applications and create application keys for each of your agencies in order to be able to do this, since OAuth providers generally display the application name to the user.
Comment: Ugh, that's not going to be very scalable, but I guess it will be serviceable in the early days. Thanks.
Comment: Well, you could make clear to the users on behalf of which agency your application is authorizing before redirecting... so they will accept to login to your application (domain name).
Comment: I could call the app "Contact Manager by Agency X", but that only works for Agency X, not the many other agencies I want to have. But what I don't get is whether my application can dynamically substitute another name for "Agency X", based on runtime data about which agency is currently using my app to query *their* client for data.
Comment: In order to use OAuth, you generally need to register your application with your provider. It will give you an application key and secret to work with. The problem is that during the login they will generally display the URL (Google) and/or the name (Facebook) of the registered application. No dynamic changing of the displayed information is allowed for security purposes. The same information will always be displayed for a single app. But, if you register multiple apps, you could dynamically change the keys and host your application on the same server.
Comment: This makes sense. I guess I can manually register agencies until such time as the volume becomes a problem. I wonder if there's a way to programmatically register an application. Probably this is much too easy to abuse though.
Comment: I don't know if such possibility is provided by the Google APIs. Facebook probably does not and won't provide - it is my opinion. They could control the abuse for such cases by limiting the volume and controlling the user who registers these applications ...


How can I display the time passed since a comment was created instead of the creation date?

Question: how to personalize my comments ?

I want to display since when the comment was created instead of the date.
I want to display the comment ID with the link "permalink".

Can you help me ? Thank you
comment--field-article-commentaire.html.twig :

          {{ drupal_entity('user', comment.uid.target_id, 'comment') }}

            {{ permalink }}

            {{ author }}

            le {{ created }}

      {{ content.field_article_commentaire }}

        {{ content.flag_report_comment }}

        {{ content.links }}

Here is the current view of my comments :
https://ibb.co/QF051yV
I would like to display the date like this :
https://ibb.co/QCQbmG2
Answer: Twig's date extension does exactly what you ask:
{{ created | time_diff }}

However, this extension isn't in Drupal by default, assuming you're using Composer you need to add this extension to your project by running:
composer require twig/extensions


What is this C++ Syntax when declaring a class?

Question: I occasionally run into this type of syntax when looking through open source code and was wondering what it's for, or what it's even called for that matter.
I have crawled the internet many a times before but simple contrived examples never had it nor explained it.
It looks like this
class SomeIdentifier ClassName {
...
}

My question is what is SomeIdentifier ?
Comment: example please. I think it is just some macros though.
Comment: This is not a valid C++ syntax (unless you are talking about some compiler-specific declaration specifier). Are you sure you reproduced the syntax you saw correctly?
Answer: Generally this would be something like that
#define SomeIdentifier __declspec(dllexport)

It is for support of MS dlls where you must specify explicitly every class
that is used in interface.
And SomeIdentifier would be something like
FOO_BAR_EXPORT
Comment: Yes that makes perfect sense in my context! Thanks
Answer: You probably missed a ':' between SomeIdentifier and ClassName
It might be like this:
class SomeIndentifier : ClassName{

};

Well, this means the class SomeIdentifier privately inheirits class ClassName!
Google out 'Inheritance in C++' for more..
Comment: Sorry I should of mentioned that it is not when a class is inheriting from a base class. That is why it is quite confusing me.


How can I prevent a 4-part harmony from sounding muddy?

Question: This is my 4-part harmony version of the first two phrases of the traditional song "Angels we have Heard on High".

When I play it back, it sounds very thick and muddy, which is not what I hear with the same sound font in the Bach chorales I studied (so it can't be the sound font causing the problem). What am I doing wrong?
Comment: Just noticed I made an error in my transcription. In your soprano, m.3 beat 4, is the Bb correct? I've always sung it with a C there.
Comment: It sounds fine to me. Can you be more specific about where it sounds thick and muddy?
Comment: Maybe not the cause of 'muddiness', but I seem to remember a 'rule' that says after an octave jump (bass line), the next notes should go back in between those octave notes.
Comment: @Aaron More in the second phrase than the first, but I can't seem to pinpoint an exact place where I feel that it sounds muddy.
Comment: @Aaron I transcribed the melody by ear, so it might be my transcription that contains an error.
Comment: Actually, the Bb is fine. It might be "wrong", but it works really well.
Comment: @Aaron "Actually, the Bb is fine. [etc.]": By this do you mean that having the B-flat there makes a perfectly good melody even though it is not the usual version of the melody?  If so, I agree.  OprenStein: in addition to that note being a C, the following three notes are a third higher the first time (so the last four are C-C-B flat-A) and then as you have them the second time (C-A-F-G).
Comment: Welcome! Please take a moment to read about [how to avoid subjective answers](https://music.stackexchange.com/help/dont-ask) (might want to check out [the topics covered here](https://music.stackexchange.com/help/on-topic) too). I know it's hard to describe musical issues, but I wonder whether you can add more detail to what you mean by "thick and muddy," or pinpoint any moments. Otherwise, it's just kind of an open invitation for all suggestions, which is kind of too broad for here.
Comment: For me a general concept to keep in mind is that intervals between low voices should be wider and then closer between high voices. Also the parallel 4ths in bar 1 don't help. In bar 4 everything below the soprano is at middle C or lower and there is some crossing of voices as well.
Comment: This is more a comment about style, though it may help your perception of "muddiness" too: This piece has a dramatic, sweeping chorus full of possibilities. The verses (using the traditional chords/cadence) aren't as interesting, but they can effectively and powerfully lead to the chorus, at which time the harmony "expands" both upwards and downwards. In other words, I'd be stingy with harmony/movement in the verse, and use that to lead and contrast with the chorus.
Answer: The first obvious issue is that the tenor and alto spend almost the whole first bar moving in parallel fourths. Using parallel fourths is one thing, but doing it in such an extreme way means the two voices basically blend to a single, overpowering one. You don't want the middle voices to team up in this way, they should generally be subordinate to the main voices. Especially with this being the first bar, it changes the whole perception/expectation/calibration of the listener, so even if the rest is fine then it probably won't come across.
Oh, and the melody itself joins the parallelism with that A-C in octaves. This should have been an obvious issue to you.
Then bar two starts with quaver-movement in all the accompaniment voices under the dotter crotchet in the main voice. To me, that dotted note has a pivotal role in the melody, and it's a point of rest, moreso than the minim on beat 3. With so much movement below it that definitely isn't the case anymore. Now, this could be fine – I'm not really sure if my interpretation of the melody is best. But you should have a good reason for doing that, and I don't see any here.
Aaron talked at length about bar 3. Honestly I find the mentioned doubled notes far less problematic than the other issues.
What does not work for my ears though is the subdominant in first inversion on beat 4, leading into... a sixth-only suspension of the dominant also in first inversion? IDK, is that even a thing? I'd say what definitely clashes is the sustained A in the melody with the G-A-B♭ in the tenor. And beat two seems to still try being a C chord, but for that of course the doubled B♭ puts the seventh way out of proportion, all the while there's still an A sounding in the soprano. No, bar 4 really isn't working for me, I guess you must have meant it completely different – but then you failed to make your intention clear in the score.

I wouldn't say any of those things are, per se, typical muddiness-causers. However, all together they are definitely prone to causing that effect, via at least two mechanisms:

The voices don't have proper roles. That makes it confusing to the ear what should be tracked how.
You have chords with either questionable inversion or unnecessary dissonance, that neither build up proper tension nor resolve to anywhere nor create any distinctive, interesting sounds.

In summary, this arrangement sounds like the voices occasionaly don't know what they're doing.
Answer: To my ear, there are two problems, both in measure 3:

On beat 2, the doubled G (i.e., the fifth of the chord) in the bass and soprano.
On beat 3.5, the doubled E (i.e., the leading tone of the tonic key) in the bass and alto.

Allowing those are "the problems", try the following revision to measure 3, and see if that fixes the muddiness.

Soprano: no change
Alto: all 1/4 notes, F4-G4-D4-F4
Tenor: beats 1 & 2 no change; beats 3 & 4, eighth notes, A4-Bb4-C5-D5
Bass: all 1/4 notes, F3-E3-F3-D3
Comment: Is it me or are all the voicings unnecessarily close? I.e., the basses are high and the sopranos are low and the middle voices are squeezed in between.
Comment: @ToddWilcox that is the usual cause of "muddy" texture -- close voicings in the middle to lower register.
Comment: I'm reading this without listening to it, so take this with a grain of salt, but the E you're calling attention to isn't functioning as a leading tone, so the rule about not doubling it doesn't apply.  And the doubling of the G on beat 2 is probably less of a problem than the fact that the bass has G at all.  Second inversion chords normally appear only immediately before a dominant chord (I6/4-V-I).
Comment: @phoog I wasn't applying a rule; I was responding to what I heard. Leading tone function aside, the two E's just didn't sound good to me. Ditto the Gs.
Comment: Looking back at this, after a few months. I thought that you were supposed to unconditionally double the 5th of a 6/4 chord?
Comment: @phoog The cadential 6/4 isn't the only classical use of the 6/4. You can use passing 6/4's(Eg: I-V6/4-I6), or an auxiliary 6/4 over a stationary bass(Eg: I-IV6/4-I). You can also use it to arpeggiate a chord by going through all of it's inversions(Eg: I-I6-I6/4). I think my V6/4 chord fits as a passing chord, but I might be wrong. Feel free to correct me.
Comment: @OprenStein Short of knowing the rule, I was just responding to what I heard.
Answer: I do not know if this is the cause of your problem (which is also hard to determine if we do not know the SF you use), but you should try to keep an eye on voices moving in the same direction. Try to remove the diminuition and have a look at a reduced version:

Look at this slight alteration for an example how this could be done:

Here's the MuseScore file for you to experiment with:
http://petzel.at/ex.mscz
Comment: Aren't the parallel fourths of the A/T in the first and third bars still not ideal?
Comment: @AndyBonner Yes, sure (I did not claim to find all problems with the part). These parallel 4ths in the first measure actually include a wrong resolution of a tritone bb-e -> a-d.
Comment: @Lazy "wrong resolution" LOL
Comment: @FidRewe Do you have any point to make?
Answer: One source of the muddiness is in the tenor and bass voice spacing. If you rewrite the tenor voice at pitch this will become immediately evident to you. In general, however, I would say that the reasons are primarily poor spacing choices and poor part writing. The separate voices merge into an indistinct mass of sounds. Recommend rewriting the lower 3 voices. Also, if this is a text setting, keep the text in the score. This will keep you "honest" in your musical choices in terms of desired effect, singability, how the indiv. tessituras of the parts relate to the actual sound of the voice, overall setting of the text to music etc.
Answer: The problem here is very conceptual. Bach composed his 4-voice hymn arrangements primarily as basso continuo (b.c., figured bass), so staring with the undelying harmony. Also, his b.c. has a lot of specific rules, in particular what we call the "rule of the octave" and also very big attention to final harmonies of phrases (usually sticking to some early baroque traditions) and to cadences, preference of counter-motion etc. Another thing is that his approach was very rhythmical in the sense that the b.c. is not only a sequence of harmonies, but it also pays attention to the position within the bar, phrase or the whole hymn.
This itself usually very vell gives the specific voices, because a lot of underlying rules apply (e.g.: no parallel pure fifths, special treatment of 64 chords, parallel fourths allowed only in specific cases -- usually when dealing with a 5 6 ascending or 6 65 descending b.c., avoiding all voices raising or lowering, going into octaves and fifths with opposite motion, proper resolution of , but all of this with a lot of exceptions, some rules treated more importantly than others). All these rules mean that a lot of snippets of the inner voices are quite fixed, and you can only possibly place them in either A or T.
It's impossible to grasp all the rules he applied (our current age probably doesn't even know all of them), and it's very difficult to write down the intricacies. But the problem is that if you start from the voices and not from the harmonic and melodic (in all voices) rules, you IMHO can't really mimick Bach's music's clarity.
Answer: Your Bass and Tenor are actually too close, lots of 3rds. Remember that the little 8 below the Tenor clef means it sounds an octave lower, not where it is written.
Small intervals in the medium-low register cause muddiness. That is why the distance between Bass and Tenor is, in general practice, bigger than between the 3 upper voices. My teacher used to say that the 'rule of octave' (not more than an octave of separation between voices) is not strict between Bass and Tenor.
Think of a piano. If you play C-E-G chord in the left hand territory, sounds muddy. But with the right hand is ok. That is why the left hand usually plays 4ths, 5ths and octaves, and smaller intervals are up, in the territory of the right hand.


Recyclerview items are automatically getting clicked on scrolling

Question: When i scroll recyclerview. items in it are automatically getting clicked. how to fix this problem.
this is my recyclerview (OnItemTouchListner).on scrolling items automatically
get clicked
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
                @Override
                public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
                    View view=rv.findChildViewUnder(e.getX(),e.getY());
                    String profile=null;
                    if(view!=null){
                        int position=rv.getChildAdapterPosition(view);

                        try {
                            JSONObject jsonObject=new JSONObject(arrayList.get(position));
                            profile=jsonObject.getString("profile");
                        } catch (JSONException e1) {
                            e1.printStackTrace();
                        }
                        Intent intent=new Intent(getActivity(),ProfileActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        Bundle bundle=new Bundle();
                        bundle.putInt("position",position+1);
                        bundle.putString("profile",profile);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                    return false;
                }

                @Override
                public void onTouchEvent(RecyclerView rv, MotionEvent e) {

                }

                @Override
                public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

                }
            });

Comment: You need to provide more details and the relevant code. This is neither helpful to anyone nor can anyone answer your questions
Comment: add code and description to question.
Comment: Provide your click listener method code
Comment: i update my question
Answer: You can use
holder.yourLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            try {
                        JSONObject jsonObject=new JSONObject(arrayList.get(position));
                        profile=jsonObject.getString("profile");
                    } catch (JSONException e1) {
                        e1.printStackTrace();
                    }
                    Intent intent=new Intent(getActivity(),ProfileActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    Bundle bundle=new Bundle();
                    bundle.putInt("position",position+1);
                    bundle.putString("profile",profile);
                    intent.putExtras(bundle);
                    mContext.startActivity(intent);

        }
    });

Comment: why items were getting clicked on scrolling in my previous code
Comment: because when you scroll, you touch the cell of the recyclerview. you used recyclerview.addOnItemTouchListener. you scroll, you touch, so it works. user recyclerview.setOnClickListener instead. recommened to use click listener within the adapter class.


Scaling UI with DPI change of non MFC application

Question: My application is a plug-in developed in VC++ (win32). The solutions I could find didn't work for me.
I have two options :

To disable DPI changes for my DLL plugin. That means my plug-in will not be affected with DPI changes.
To scale all the controls according to the DPI change.

Please help.
Thanks.
Comment: The question isn't very clear.  What application does your plugin plug in to?  You cannot disable DPI changes--the user can change the DPI at any time--but unless a program declares that it understands DPI, recent versions of Windows will hide DPI changes from the application and do the scaling on its behalf.  This can be useful for simple applications that haven't done the work of being DPI aware, but that setting applies process wide.  You can't turn it on just for your DLL.  If your code runs inside another application that is DPI aware, then your only choice is to be DPI-aware.
Comment: And what's the question ?
Comment: Sorry if I am unable to express my question. My problem will be resolved if any of the two options is solved.
My question is :
1. How can I restrict my UI from DPI change (if possible)?
2. How can I scale my UI elements according to the DPI change.

If any more inputs the problem is required please let me know. My application is a DLL or say a maya plg-in.
Comment: My query is simple but I think I have not made it much clear. Please consider it again for review :

1. Disable DPI affect on my application UI when some one re-configures the DPI.
    Help required : If possible, how to do that pro-grammatically.

2. Scale the UI of my application according to the DPI change.

    Help required : How to determine the current DPI and how to scale the UI accordingly? Is it necessary to scale every component or any other way to scale them automatically.

@Michael Walz : I think the question is now explained. Please let me know your thoughts on this.
Comment: I wonder if there is any answer to my question.
Answer:
1. Disable DPI affect on my application UI when some one re-configures the DPI. Help required : If possible, how to do that pro-grammatically.

This is not possible. Adrian already told you that. DPI is a user setting, not an application setting. If the user wants to change their DPI, they can do so. They can also apply backwards-compatibility hacks that turn off high DPI for a particular application, but that functionality is not available to applications. As the developer, you're expected to make sure that you support high DPI environments, not disable it.
The only thing you can do as an app developer is to fail to indicate that your application is DPI-aware. This is roughly equivalent to walking around with an "IDIOT" sign taped to your forehead. You might find that people are slightly more accommodating of your shortcomings, but they won't have much respect for you and probably won't care to hang out with you very often. Windows will do much the same thing: it will hide the truth from you about the user's actual DPI settings (you can't handle the truth) and instead it will scale up your interface automatically to match. The effect is an ugly one.
Of course, you also say that you're creating a plug-in DLL, which changes things. DLLs can't alter the DPI-awareness of the entire process because that is determined by the host application. If the host application indicates that it is high DPI aware, then your DLL must also be high DPI aware. This is an all or nothing setting, just like the "IDIOT" sign.

2. Scale the UI of my application according to the DPI change. Help required : How to determine the current DPI and how to scale the UI accordingly? Is it necessary to scale every component or any other way to scale them automatically.

In order to correctly determine the current DPI settings, you need to indicate to Windows that you're not an idiot your application is high DPI aware. As discussed above, if you do not do this, Windows will assume that you cannot handle the truth and lie to you. But as we also established above, this probably does not apply to you because you're creating a DLL that runs in the context of another process that is already establishing itself as high DPI aware.
So, what you need to do is determine the DPI scale factor. You need that to scale your user interface elements accordingly when running in high DPI environments. The baseline DPI setting is taken to be 96. The following code scales a SIZE structure (that defines a width and height) relative to that baseline:
void ScaleDpi(SIZE& size)
{
    // Determine the current screen DPI.
    const HDC hDC = GetDC(NULL);
    const int dpiX = GetDeviceCaps(hDC, LOGPIXELSX);
    const int dpiY = GetDeviceCaps(hDC, LOGPIXELSY);
    ReleaseDC(NULL, hDC);

    // Perform the scaling.
    size.cx = MulDiv(size.cx, dpiX, 96);
    size.cy = MulDiv(size.cy, dpiY, 96);
}

However, if you follow good design practices, you may not need to scale every control manually. When defining windows and dialogs in a resource file (e.g., using the Visual Studio Dialog Editor), you specify the layout in logical units (known as DLUs, or dialog units). These units are independent of any particular DPI setting and are therefore preferable to using something like pixels. A simple dialog with a few controls therefore requires no special scaling effort. You'll only need to perform manual scaling if you're creating and/or laying out controls at run-time.
You'll find more tips and techniques on how to write high DPI aware applications on MSDN, in the Writing High-DPI Win32 Applications article. And I don't link this just to say RTFM—it's actually extremely helpful, and I highly recommend reading it all.
The folks who make the RealWorld Icon and Cursor editors also maintain a helpful article on their site: DPI-aware applications in Windows Vista and Windows 7.


Dúvida classe Random em Java

Question: Galera estou tentando criar um sistema de números da mega sena. Basicamente eu tenho que ter um cliente(id) que ira gerar 6 números aleatórios.
public class Cliente implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String nome;
    private String email;
    private int numeros;

Eu criei a classe cliente que tem nome, email e numeros.
public class Random1 {

    public static void main(String[] args) {

        Random gerador = new Random();

        for (int i = 0; i < 6; i++) {
            System.out.println(gerador.nextInt(59));
        }

E criei a classe random, a dúvida e a seguinte, como eu faço para cada jogo criado de 6 números, ficarem atrelados a um ID na tabela cliente?
Comment: 1) Só pra você saber, `Random1` é um péssimo nome em termos de modelagem de classes, não diz nada sobre o que a classe é ou faz. 2) A forma de gerar está errada, porque está deixando repetir números. 3) Em termos de mapeamento objeto-relacional não faz sentido ter um campo `int numeros`, seria um array ou lista de números com tamanho fixo em 6, e na verdade mesmo isso está errado porque um cliente poderia fazer várias apostas portanto deveria ter o conceito de `Aposta` cada uma com seis números. Pra finalizar, por normalização de BD não convém manter os seis números numa só coluna da tabela.
Comment: Enfim, orientação a objetos é uma coisa, banco de dados relacional outra, ORM é a ideia de relacionar esses dois mundos (que no seu caso fatalmente vai envolver mais de uma tabela e chaves estrangeiras) e pessoalmente acho que deveria ser estudada depois que já tem uma boa noção dos dois primeiros. Mas cada um é cada um. Também uma estudada em como levantar requisitos.
Comment: Sua maior dúvida é gerar os 6 números aleatórios ou é salvá-los no banco de dados?
Comment: @Piovezan Obrigado pelas dicas amigo, como estou me formando ainda, me falta bastante conhecimento mesmo.
Comment: @VictorStafusa isso amigo, eu consigo gerar os números com a classe random, porém eu não conseguir atrelar os números gerados a uma classe cliente entende?
Answer: Um jeito mais didatico de resolver isso é assim:
public class Cliente implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String nome;
    private String email;
    private int numero1;
    private int numero2;
    private int numero3;
    private int numero4;
    private int numero5;
    private int numero6;

    public Cliente(int[] numeros){
        int numero1 = numeros[0];
        int numero2 = numeros[1];
        int numero3 = numeros[2];
        int numero4 = numeros[3];
        int numero5 = numeros[4];
        int numero6 = numeros[5];
    }
}

public class Random1 {
    public static void main(String[] args) {

        Random gerador = new Random();

        int[] valoresSorteados = new int[6];
        for (int i = 0; i < 6; i++) {
            int valorRandom = gerador.nextInt(59);
            System.out.println(valorRandom);
            valoresSorteados[i] = valorRandom;
        }
        Cliente cliente = new Cliente(valoresSorteados);
    }
}

Mas vale notar o seguinte, para um codigo de estudos qualquer coisa atende, em um projeto de verdade diversos problemas com essa implementação vão aparecer, como por exemplo confiar que vai vir um array de 6 posições no contrutor da classe cliente, por isso é sempre bom tentar seguir as boas praticas de codigo do mercado.
Se isso for so para estudar orientação a objetos recomendo voce remover a parte do banco de dados para ficar mais facil, depois que voce resolver o problema da logica que voce precisa é so salvar no banco, va por partes

Dúvida classe Random em Java


Correct way to write values which have a certainty of 95 percent?

Question: Instead of perusing through many more textbooks, I thought it's easier to ask here. Say I would like to express the mean for a variable with a certainty of 95 percent, how exactly do ("should") I do this?
Maybe like:

$x_{P = 95\%} = 373.334$ mm $\pm 8.82$ or
$x (P = 95\%) = 373.334$ mm $\pm 8.82$

I know I could always write
$x = 373.334$ mm $\pm 8.82$ with a probability of \SI{95}{\percent} but I'd prefer a more compact way.
Comment: Are these "certainties" confidence or credibility intervals? If so, just call them that (and drop the notion of "certainty" in the former case and append "given the posterior is correct" in the second).
Comment: OK but which of the two?
Comment: No, they are anything but synonyms. See here http://stats.stackexchange.com/questions/2272/whats-the-difference-between-a-confidence-interval-and-a-credible-interval Should you choose to follow @Alexis's sugestion make sure you understand what a confidence intreval is and how it's interpreted, it certainly isn't certainty.Here's a good start http://stats.stackexchange.com/questions/26450/why-does-a-95-ci-not-imply-a-95-chance-of-containing-the-mean
Comment: Thanks for the explanation. I think when you use or list a CI is definitely worthwhile to read and comprehend the meaning of it, particularly because it can neither be interpreted to mean "95% certainty" nor even "95% probability". @Dikran's explanation is so complicated because it has to be, as a CI is a surprisingly subtle thing to grasp.
Comment: @Momo Yes they are.
Comment: @Momo Woops sorry I thought you used that synonymously. They are confidence intervals.
Comment: I wasn't aware of the term *credibility interval* before. I meant to address CIs. Using "certainty" in the op, I must say this was probably (75%) all because of the "lost in translation" effect. I had **p**robablity in mind. Besides .... well to make it short, the style of writing of the user in your second linked post is way too complicated for my lack of enthusiasm.
Answer: It is not clear what you mean by certainty? Do you mean confidence? Credibility? Something else? Where does the "8.82" in your example come from?
For confidence intervals a fairly standard notation is along the lines of (I am using three significant figures, but your precision may be more or less):
The mean was 373 (95%CI: 365, 382).
There are variations on this. You might read a recent article in a popular journal in your field to see how folks are reporting their confidence (or other) intervals.
Comment: Hm, interesting, so far I only found your variant of expressing it...


True/False exposed Views checkbox for Computed Field

Question: Imagine a user has ten fields of type "List(text)" which each have for their widget "Check boxes/radio buttons". Each one is displayed to the user as a single value checkbox which asks the user to state whether they agree with something or not.
A distinct Computed Field of data type TinyInt uses custom PHP to examine the values of these List(text) fields checkboxes. If all are checked the Computed Field is set to have the value of 1. If any or all are unchecked the Computed Field is set to have the value of 0.
(Ideally I would like the Computed Field to be of Boolean type - so simple TRUE/FALSE - but this does not seem possible out of the box. Anyway, the real question is the following.)
In a View with exposed fields, how can you use the Computed Field as an exposed field that offers the user a single checkbox: "Find all users where the Computed Field value is 1: [•]".
If this isn't directly possible, I'm happy to have a workaround that involves creating a distinct (hidden) field in the user profile and then uses this for the Views exposed filter search. But I can't think of a way to do this right now... Thanks.
Comment: Can you tell what is happening when you expose the field now and filter all values equal to 1?
Comment: Sorry AltaGrade I don't quite understand what you're asking...
Answer:
Change exposed computed field's filter type to "Grouped filters",
Widget type to "Radios",
Check "Allow multiple selections" checkbox,
Expose one option equal to 1 with your choice of label

See screenshot:

The view export:
<code><?php

$view = new view();
$view->name = 'computed_field_test';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Computed Field Test';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Computed Field Test';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['exposed_form']['options']['autosubmit'] = TRUE;
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: List 1 */
$handler->display->display_options['fields']['field_list_1']['id'] = 'field_list_1';
$handler->display->display_options['fields']['field_list_1']['table'] = 'field_data_field_list_1';
$handler->display->display_options['fields']['field_list_1']['field'] = 'field_list_1';
/* Field: Content: List 2 */
$handler->display->display_options['fields']['field_list_2']['id'] = 'field_list_2';
$handler->display->display_options['fields']['field_list_2']['table'] = 'field_data_field_list_2';
$handler->display->display_options['fields']['field_list_2']['field'] = 'field_list_2';
/* Field: Content: Computed */
$handler->display->display_options['fields']['field_computed']['id'] = 'field_computed';
$handler->display->display_options['fields']['field_computed']['table'] = 'field_data_field_computed';
$handler->display->display_options['fields']['field_computed']['field'] = 'field_computed';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'page' => 'page',
);
/* Filter criterion: Content: Computed (field_computed) */
$handler->display->display_options['filters']['field_computed_value']['id'] = 'field_computed_value';
$handler->display->display_options['filters']['field_computed_value']['table'] = 'field_data_field_computed';
$handler->display->display_options['filters']['field_computed_value']['field'] = 'field_computed_value';
$handler->display->display_options['filters']['field_computed_value']['exposed'] = TRUE;
$handler->display->display_options['filters']['field_computed_value']['expose']['operator_id'] = 'field_computed_value_op';
$handler->display->display_options['filters']['field_computed_value']['expose']['label'] = 'Computed (field_computed)';
$handler->display->display_options['filters']['field_computed_value']['expose']['operator'] = 'field_computed_value_op';
$handler->display->display_options['filters']['field_computed_value']['expose']['identifier'] = 'field_computed_value';
$handler->display->display_options['filters']['field_computed_value']['expose']['multiple'] = TRUE;
$handler->display->display_options['filters']['field_computed_value']['is_grouped'] = TRUE;
$handler->display->display_options['filters']['field_computed_value']['group_info']['identifier'] = 'field_computed_value';
$handler->display->display_options['filters']['field_computed_value']['group_info']['optional'] = FALSE;
$handler->display->display_options['filters']['field_computed_value']['group_info']['widget'] = 'radios';
$handler->display->display_options['filters']['field_computed_value']['group_info']['multiple'] = TRUE;
$handler->display->display_options['filters']['field_computed_value']['group_info']['group_items'] = array(
  1 => array(
    'title' => 'Find all users where the Computed Field value is 1',
    'operator' => '=',
    'value' => array(
      'value' => '1',
      'min' => '',
      'max' => '',
    ),
  ),
  2 => array(
    'title' => '',
    'operator' => '=',
    'value' => array(
      'value' => '',
      'min' => '',
      'max' => '',
    ),
  ),
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'computed-field-test';
$handler->display->display_options['menu']['type'] = 'normal';
$handler->display->display_options['menu']['title'] = 'Computed Field Test';
$handler->display->display_options['menu']['name'] = 'devel';
</code>
Comment: Thank you. I have configured the view as per your answer, but it is showing a radio button, not a checkbox. Screenshots: Views config: http://prntscr.com/j0g83t Views config preview: http://prntscr.com/j0g919 Views final output http://prntscr.com/j0g8dk Any ideas why this might be?
Comment: did you make sure the "Allow multiple selections" is checked and "Optional" is unchecked?
Comment: @penname I added PHP export of the view I used for creating the screenshots. Please compare it with yours. If still have issues, please export your view and post it in here.
Comment: Yes. The View is configured exactly as you said (and as I showed in the screenshots, which are on the LightShot https://prnt.sc/ site if you were hesitant to click on the links). May I ask, which version of Views and Drupal are you using? Do you have any other relevant modules installed?
Comment: Ok, thank you for the export. I will create a fresh dev site and test.
Comment: Latest Drupal core, and Views module only. No other relevant modules...


Which steps are required to avoid my server being considered as spam sender?

Question: I'm looking to set up a webmail server that will be used by a lots of users that will receive and send emails. They will also have the possibility to forward emails they receive.
I'd like to know which steps are recommanded/required to indicate to others Mail services (GMail, Outlook, etc) that my server is not used as a spam sender (disclaimer : IT's NOT ! :p) but a legitimate one.
I know I have to define a SPF TXT records for example, but what others steps would you recommend me to do ?
For example, is there a formula like having a proportional number of servers based on the amount of email sent (for having a different IP address) ? (something like sending a maximum of 1M emails / per IP / per day ?)
Something else I'm missing ?
I tried to search online, but I mostly find how to avoid emails sent with scripts (like PHP) being put in the SPAM folder.
I'm looking for a server/dns configuration side.
Thanks a lot for your help/tips, I appreciate !
Answer: The first step is to make sure you don't have an open relay. You can test that here. Other measures will also have to be taken, but those settings will be dependent on the mailserver you're running.
Comment: Thanks for this answer, I already knew about this server but didn't knew about being an open relay, very interesting! And about the servers in question, do you recommand me to take 1/2/n amazon ec2 instances or is it ok (or the same) to take a private server? I can't make my mind regarding if Amazon is better (reliable network = less spam quality mail) or bad (lot's of server, probably lost of spammers) ?
Comment: I haven't worked much with amazon, but do run a mailserver. Mailservers can be a headache esp with spam, so if you have the opportunity to get somebody else to manage it, I'd recommend that route.
Answer:
Ensure your server is not an open relay, meaning that it must not relay to arbitrary destinations for arbitrary senders without authentication.
Make sure that your SMTP software is configured to send an appropriate FQDN along with its HELO/EHLO statement.  Configuration will depend on the SMTP server you are running, but you need to make sure it is identifying itself with a publicly-resolvable fully qualified domain name.
Make sure you have an A/AAAA record in DNS for the FQDN noted in step 2, with the correct IP mapped to your server.
Make sure there is a PTR record corresponding to your A/AAAA record.
Make sure that the SPF record(s) for any domain that will send through your server are configured to allow that server as a sender.
Potentially set up DKIM, depending on your server software and requirements.
If you run into trouble, check your server's external IP(s) against various online blacklists.
MOST IMPORTANTLY: If you can use an external service for SMTP like MailGun, SendGrid, etc, consider doing so.  SMTP is one of those things like DNS in that for most people/businesses, running it themselves is really more trouble than it's worth.


R language-read the value in excel and check

Question: I am new to R language.
I have a dataset, the first column is the name and second is the value.
I want to read each value in the second column and check if the value falls into a certain range.
For example,
Name value
AA    123

and the range in (100,150)
which function can be used?
Thank you in advance.
Comment: Welcome to stack overflow. It's customary around here to show what you have tried, and how it failed. Can you show us that?
Comment: `100 < df$value & value < df$150` (strict inequalities, since the nomenclature of your `(100,150)` suggests *open* ends ... perhaps I'm reading into that too much :-)
Answer: you can use this code:
for(i in 1:nrow(df)){
  if(df[i,2]<150){
    if(df[i,2]>100){
      print(df[i,])
    }
  }
}

that the df is your dataset
Comment: Hi, you might like to add a comment on what the output will be, and how that might meet the need of the original post (which to be fair was a little vague).
Comment: She wanted to filter her output based on the data in the second column so that if it were between 100 and 150, it would show the whole row. I did this with this simple code, Now she can put the output in a new ِdataset.
Answer: It is not entirely clear what the desired result is.
Option 1 could be a new column is created that records (e.g. TRUE/FALSE) whether an observation (row) is in the limits. For example, with tidyverse style code to create a column called "is_valid":
df %>% mutate(is_valid = ...)
Option 2 could be filtering the data to create a subset that has only the desired observations, e.g. with tidyverse style code.
df %>% filter(value <= 150) %>% filter(value >= 100)
In any case, I'd recommend spending some time to learn how to do this in a tidyverse way with dplyr (google the free online book R for Data Science).


How to get a Python os.PathLike object from a NamedTemporaryFile using the tempfile module?

Question: I'm trying to call a Python (3.8) function using the pdfkit library that requires a list of file objects. I only have strings, so I need to write each string to a temporary file that I will delete after the function returns. I can roll my own solution for this, but it would be much more convenient (and portable) if I could use the tempfile module for this. Unfortunately, when I wrap each string with a NamedTemporaryFile, my function complains with a TypeError that I must supply something that is os.PathLike, not _TemporaryFileWrapper.
Is it possible to get something from the tempfile module that is suitable for this purpose?
from tempfile import NamedTemporaryFile
import pdfkit

the_files = []

for html in my_html_strings:
    tmp_file = NamedTemporaryFile(mode='w', suffix='.html')
    tmp_file.write(html)
    the_files.append(tmp_file)

pdf_data = pdfkit.from_file(the_files, False) # raises

And the stack trace:
  File "...", line 68, in my_code
    pdf_data = pdfkit.from_file(section_files, False, options=opts)
  File ".../lib/python3.8/site-packages/pdfkit/api.py", line 46, in from_file
    r = PDFKit(input, 'file', options=options, toc=toc, cover=cover, css=css,
  File ".../lib/python3.8/site-packages/pdfkit/pdfkit.py", line 41, in __init__
    self.source = Source(url_or_file, type_)
  File ".../lib/python3.8/site-packages/pdfkit/source.py", line 12, in __init__
    self.checkFiles()
  File ".../lib/python3.8/site-packages/pdfkit/source.py", line 28, in checkFiles
    if not os.path.exists(path):
  File "/usr/lib/python3.8/genericpath.py", line 19, in exists
    os.stat(path)
TypeError: stat: path should be string, bytes, os.PathLike or integer, not _TemporaryFileWrapper

Comment: Can you post the complete traceback
Answer: You don't need a PathLike. You just need a string representing the file path. For a NamedTemporaryFile, that string is its name attribute:
namedtempfile.name

Almost everything that takes an os.PathLike is supposed to take a plain string too.
If for some weird reason you find yourself in a situation where you really need a PathLike and a string actually doesn't work, you can wrap the string in a pathlib.Path:
import pathlib
pathlike = pathlib.Path(nametempfile.name)

This is not such a situation.


Woocommerce storefront theme Product Search Bar to page center

Question: I have a WordPress e-commerce site graceamaron.com
in the site a search bar is located at top of the page at right side. But I want it in center. How do I change the order of the columns inside the header using CSS.
Simplified example:
header {
  width: 100%;
  background-color: firebrick;
  display: flex;
}

.logo,
.search{
  width: 25%;
}
.nav {
  width: 50%;
}

logo

Home contact ...

    <input type="text" placeholder="search">

Present my site screenshot (search bar at right side)

and this is the way I want (page center)
Answer: Since this is WordPress and you are not able to change the HTML layout I've done the following CSS fix.
I added display: flex to the wrapper of the 3 blocks inside the header. Then I added order attributes
to the elements to order them to my liking, then I also added width and replaced margin with padding so it doesn't force any element to go on the next line.
/* Header Wrapper */
.site-header .col-full {
    display: flex;
}

/* Site Logo */
.site-header .site-branding {
    order: 1;
    width: 25%!important;
    margin-right: 0!important;
    padding-right: 10px;
}

/* Searchfield */
.site-header .site-search {
    order: 2;
    width: 50%!important;
    padding-right: 20px;
}

/* Navigation */
.site-header .secondary-navigation {
    order: 3;
    width: 25%!important;
    margin: 0!important;
}

Results
Comment: Just noticed I entered the wrong ID, I approved your edit
Comment: Hello @Fuziion ,
giving styles by id is not working, I tried to change it from `#site-header` to `.site-header` then it's working.
Comment: Hello @Fuziion I have edited your answer to mark it as ANSWER. Presently it is being reviewed.