text:
Q: How to change default colors in materializecss? I just added materializecss to my ASP.NET MVC project, but I can't seem to change the default color scheme. Referring to here, I need to change the default color scheme from green to blue.
I added this to my '_project_variables.scss' file, but it doesn't work:
$primary-color: color("materialize-blue", "lighten-2") !default;

Is there another step that is not outlined on their website? What else do I need to do?

A: There a few ways to do this.
1) Edit _variables.scss directly
Change the color values on lines 37 & 41 for primary and secondary (currently teal and pink).
2) Override with  _custom-variables.scss
In materialize.scss, add a link to your own custom scss file BEFORE _variables.scss:
// Variables;
@import "../custom-components/custom-variables";
@import "components/variables";


text:
Q: Await doesn't give a result Ok, I have some code to present. Here is extension method for NetworkStream object.
public async static Task<byte[]> ReadDataAsync(this NetworkStream clientStream)
{
    byte[] data = {};

    var buffer = new byte[1024];
    if (clientStream.CanRead)
    {
        using (var ms = new MemoryStream())
        {
            try
            {
                int bytesRead;
                while (clientStream.DataAvailable &&
                  (bytesRead = await clientStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                {
                    await ms.WriteAsync(buffer, 0, bytesRead);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return data;
            }

            data = ms.ToArray();
        }
    }
    else
    {
        Console.WriteLine("Closing clientStream.");
        clientStream.Close();
    }
    return data;
}

And the code where I am trying to call this method.
public async static Task Preform(Socket client)
{
    var stream = new NetworkStream(client);
    var data = await stream.ReadDataAsync();
    var message = await MessageFabrique.DeserializeMessage(data);

    ServerCollections.Instance.ServerIssueQueue.Add(new ServerIssue
    {
        Message = message,
        ClientStream = stream
    });
}

ReadDataAsync method always returns me to an empty array. And at the moment when i'm trying to deserialize data there is an exception - because data[0]. Please help me. Why is this happening, if await guarantees me the result, when it needed?

A: clientStream.DataAvailable does not mean data might show up in the future. It means data is available right now for reading. Get rid of it and just read, the read will block till data shows up or will return 0 when the stream hits it's end.

A: Scott's answer is right, but .Net already takes care of you...
You might consider Stream.CopyToAsync
await clientStream.CopyToAsync(ms)

for code with considerably less places to go wrong.

A: In addition to the other answers, you might also want to create a synchronization context. See this article for details.
The summary is that async/await works differently in console applications than it does in a UI application. WPF and WebForms applications have a synchronization context by default but console applications don't. The result (which is actually remarkably "poorly advertised" in the documentation) is that the behavior of async/await is much less predictable in a console application than it is in a UI application, and that this might make it not work "as advertised" under certain circumstances.
For example, in a UI application "async" doesn't necessarily mean that the code runs on a background thread. It's the equivalent of "come back to me later when I'm ready." As an analogy, consider going out to eat with 10 people: when the waiter comes by, the first person he asks to order isn't ready. Two bad solutions here would be to a) bring in a second waiter to either wait for the first guy to become ready or take the other 9 people's orders) or b) wait until the first guy's ready to start taking orders. The optimal thing is to take the other 9 people's orders and then come back to the first guy hoping he'll be ready by that time. At risk of oversimplifying this is basically how async works in a UI (unless you're explicitly putting the code on a background thread with something like Task.Run). However, in a console application when you use async there's no guarantee as to where the code will actually run.
If, however, you add a synchronization context as described in the the article I link to it'll behave in a much more predictable manner.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problems with automatic merging of Visual Studio Projects (unresolved conflicts) in Git/GitHub A friend and I just started using git in conjunction with GitHub to help us manage our C# w/XNA project we are working on in Visual Studio 2010. Everything works correctly when only one person is making changes to the file, and his work pushes and merges correctly with the central repository. However, when we have two different people working on the code and making changes at the same time, the last person to push always has to deal with a manual merge when trying to pull the first person's changes, as the automatic one fails.
    This happens even if the changes we made were unrelated (I.E. One person adds a completely random, unused class and the other adds a second random, unused variable a different, unused class). We have probably spent a combined 3 hours or so fooling with this issue to no avail. I know that there are programs one can use to help facilitate manual merges, but I wanted to make sure that it wasn't some setting causing this issue.
Thanks!
EDIT: We are now using a .gitignore file in our repository(this one here), and it seems as though we've made some progress. Now when the second person pulls to merge before pushing his changes, it does seem to make the change on his local copy (meaning his project file registers the change I made previously), but he is still unable to merge fully as he gets the following error when he performs a git pull:
warning: Cannot merge binary files: collision/collision.suo (HEAD vs db023c2075...)
Auto-Merging collision/collision.suo
CONFLICT (content): Merge conflict in collision/collision.suo
Automatic merge failed. Fix conflicts then commit the result.
I have checked and the .suo extension is included in the ignore file, so I am at a loss as to what is causing this issue. Any further help would be greatly appreciated, and thanks to those who have posted already.

A: Alright! We finally solved the issue. Apparently the problem was with the .gitignore file and how it was created. I had just made a file in notepad before, but I guess it wasn't being picked up. All I did was recreate it in the git bash using the following:
touch .gitignore
then adding it and committing. Thanks for all of the suggestions all, definitely got me going in the right direction.

A: You probably are not ignoring binary and local configuration files. You have to create the .gitignore file and list in it what you don't want to add to the repo.
You can find more information here


text:
Q: PHP code on one server throws error on other it runs I am encoutering the following situation:
This code:

<?php
while ( have_posts() ): the_post();
global $product;
?>

        <a href="<?php echo get_permalink(); ?>">
            <span class="et_shop_image" style="background-image: url('<?php  echo the_post_thumbnail_url('woocommerce_thumbnail'); ?>')">
                <?php   if ( $product->is_on_sale() ) : ?>
                    <?php echo apply_filters( 'woocommerce_sale_flash', '' . esc_html__( 'Sale!', 'woocommerce' ) . '',  $product ); ?>
                <?php endif;?>

            <?php echo the_title(); ?>

            <?php echo $product->get_price_html();?>

<?php
endwhile;
wp_reset_query();
?>

Works on one server (test server) but in the other (live server - physical an other server) the following error occurs:
[Thu Nov 04 17:50:01.638110 2021] [proxy_fcgi:error] [pid 1520496:tid 140160309864192] [client 80.57.194.158:58615] AH01071: Got error 'PHP message: PHP Fatal error:  Uncaught Error: Call to a member function is_on_sale() on null in /inc/template/producten.php:16
Stack trace:
#0 /facetwp-org/includes/class-renderer.php(544) : eval()'d code(2): include()
#1 /facetwp-org/includes/class-renderer.php(544): eval()
#2 /facetwp-org/includes/class-renderer.php(218): FacetWP_Renderer->get_template_html()
#3 /plugins/facetwp-org/includes/class-display.php(77): FacetWP_Renderer->render()
#4 /wp-includes/shortcodes.php(356): FacetWP_Display->shortcode()
#5 [internal function]: do_shortcode_tag()
#6

It is a wordpress site (test server = plesk php 7.4) live server = directadmin php 7.4 - do not know if this info is needed.


text:
Q: Mixing global functions and class member functions C++ Is it bad to call global functions from member functions of a class?  I mean is this ok...
class MyClass
{
    void print_numb();
};

int get_numb()
{
   return 10;
}

void MyClass::print_numb()
{
     cout << get_numb() << endl;
}

A: If get_numb() is only used by a source file implementing MyClass then I'd put it in an anonymous namespace in that source file:
namespace /*no name here means the namespace is anonymous*/ {
    int get_numb()
    {
       return 10;
    }
}

That hides it away. I prefer that to a static private function in the class since it reduces the amount of stuff in the class declaration.

A: It is absolutely OK from the technical point of view: free-standing functions, global and static, are part of the language. There is no reason not to use them.
It is also OK stylistically: the Standard C++ Library provides free-standing functions, so the designers of the language were definitely OK with the idea of mixing member and non-member functions.
Of course you should take advantage of the C++ features that let you isolate your functions from functions in the libraries to which you link - by reducing their visibility to a single translation unit, or by placing them in a namespace.


text:
Q: Adding HTML and CSS in Wordpress editor? I am using a child theme of "freestore". (https://en-gb.wordpress.org/themes/freestore/)
I am attempting to add some content to one of my pages using simple HTML and CSS.
I've managed to successfully change CSS styles in the theme via the style.css, however I am trying to add my own HTML and then CSS to style it.
I have created the page 'home' and through the wordpress tinymce text editor I can add my HTML fine. When I try to add the CSS via my style.css, it doesn't apply the styles. I can however add the styles inline, but I would like to add the styles externally.
Example:
On the wordpress text editor I would add the line:

TEXT

In my style.css file I would add:
#cssTest {
    background-color: red;
}

The CSS style is not applied. However adding the following to the HTML editor will work fine:

TEXT

My question is either:

*

*How can I apply my styles via an external stylesheet?

*Should I be creating my own template for that page and adding the HTML there?

A: check if child themes style.css has Text Domain:  freestore-child parentthemename-child. Any css id/class element you add would be implemented.
Best way would be to create custom.css file and enque it in your child theme's functions.php via wp_enqueue_style function.
I believe it's best practice to create page template for specific pages like home.

A: Most likely there is a CSS rule that belongs to your original theme which is more  "specific" than the rule you are trying to apply. To check this, inspect the element with the browser tools and look which CSS rule is applied to that element.
If that rule would for example be
.content main .section_1 .gxt1 {
  background-color: black;
}

, you'd have to overwrite it adding a rule which has a higher specifity, like
.content main .section_1 .gxt1 #cssTest {
  background-color: red;
}

If the original rule contains an !important, you also have to add !important. So to overwrite
.content main .section_1 .gxt1 {
  background-color: black !important;
}

, you would need something like
.content main .section_1 .gxt1 #cssTest {
  background-color: red !important;
}


text:
Q: Understanding counter and dictionary comprehensions in python I have tried to find an explanation but couldn't, so my apologies if this is a silly question.
Having data x:
 x = [(1, {'gender': 'male'}),
      (2, {'gender': 'female'}),
      (3, {'gender': 'male'}),
      (4, {'gender': 'female'}),
      (5, {'gender': 'male'})]
      ...

A plausible solution for counting the occurrences of each gender would be:
from collections import Counter
Counter([d['gender'] for n, d in x)])

Returning:
Counter({'female':2, 'male':3})

Now I am trying to understand how "d['gender'] for n, d " works within "Counter([d['gender'] for n, d in x)]".
What exactly is "n" in this case?
Many thanks for any pointers.

A: x is a list, so for <whatever> in x iterates through x and assigns each element to <whatever>.
The elements of x are tuples, so you can use tuple assignment to assign each item in the tuple to a different variable. for n, d in x means that n is assigned the first item in the tuple, and d is assigned the second item.
So the first iteration does
n, d = (1, {'gender': 'male'})

This sets n = 1 and d = {'gender': 'male'}.
the next iteration does
n, d = (2, {'gender': 'female'})

This sets n = 2 and d = {'gender': 'female'}. And so on through the entire list.
Finally, the list comprehension returns a list of d['gender'], which is the gender element from the dictionaries.
n is not used, it was just needed as a placeholder so that d could be assigned to the second item in the tuples. It could also have been written as:
[el[1]['gender'] for el in x]


text:
Q: Jquery drag and drop issue with div drag In my html code my code structure is
<form name="mainform" class="mainclass">

some content and form elements here

some content and form elements here

some content and form elements here

some content and form elements here

</form>

I need to drag this #lunch div and need to drop in between #dv1 or #dv2, or #dv3. The main divs (#dv1,2,3) no need to drag.
I used the following jquery code
$(function() {
    $(".mainclass div").sortable({
        opacity: 0.8,
        cursor: 'move',
        update: function() {}
    });
});

But it is not drag.
If i use this below code --> The elements inside the div is draggable and not able to drop.
$(function() {
    $("#ln_brk").sortable({
        opacity: 0.8,
        cursor: 'move',
        update: function() {}
    });
});

What I am doing wrong? and How to achieve this? Please help me.

A: You have used too many brackets in your code here:
$(function() {
   $(".mainclass div").sortable({
       opacity: 0.8,
       cursor: 'move',
       update: function() {}
   });
});

});

Remove the last line of the snippet above.

A: You can use html drag and drop.
<form name="mainform" class="mainclass">

some content and form elements here

some content and form elements here

some content and form elements here

some content and form elements here

    </form>

Fiddle : http://plnkr.co/edit/3OMfqActNAm0eccllte4?p=preview


text:
Q: re.search() hung This code snippet intends to search for a regex match on each line of the supplied file. re.search() gets hung at a line containing "#" character 3e+5 times in the file.

What could be the solution to this problem?
import re
print "Started..."
exp = "(.*)\$\$\$Uniqueterm:(.*)"
with open("sample.txt", 'r') as file:
    for line in file:
        if re.search(exp, line):
            print "Found match: " + re.search(exp,line).groups()[1].strip()
    print "File finished..."

Sample input file (sample.txt):
abc
pqr
##### (3e+5 times '#' in a single line)
xyz
$$$Uniqueterm: Match it
qaz

Expected Output:
Match it

A: You're using re.search with a regex that starts with (.*). re.search looks for a match at any starting position, meaning it has to start a search from every possible starting index until it finds a match or runs out of positions to search from. The leading (.*) forces a scan of the entire string starting from the search start position, for every starting position.
It's classic catastrophic backtracking, just with part of the backtracking implicit in the use of re.search instead of built into the regex itself. You could adjust the regex to eliminate the catastrophic backtracking, but why use a regex at all? Basic methods like str.split or str.find can do the job just fine. Jean-François Fabre's answer shows one way to do it.

A: regex engine can reach high complexties, specially when it must backtrack, like in your case.
So when the expression to search for is long and you have groups that must be computed with a lot of trial & error (i.e. backtracking), the search can take ages (see a famous example of regex failure on StackOverflow network).

On July 20, 2016 we experienced a 34 minute outage starting at 14:44 UTC. It took 10 minutes to identify the cause, 14 minutes to write the code to fix it, and 10 minutes to roll out the fix to a point where Stack Overflow became available again.
The direct cause was a malformed post that caused one of our regular expressions to consume high CPU on our web servers. The post was in the homepage list, and that caused the expensive regular expression to be called on each home page view.
  ...
This regular expression has been replaced with a substring function.

I'd propose a workaround since you don't really need regex here, using str.split would do and is fast, since it just searches for the substring (O(N) approach) then creates 2 strings, which is equivalent of what you're trying to do with regular expressions:
a = "foo$$$Uniqueterm:bar"
g1,g2 = a.split("$$$Uniqueterm:")
print(g1,g2)

result
foo bar


text:
Q: addtionalProperties is not getting validated (flasgger==0.9.2)  schema:
   type: object
     additionalProperties:
        type: string

but even {"key1":12,"asd":2121} is giving 200 response..its getting accepted...but this should not get accepted according to the schema


text:
Q: Is it possible to display user images with javascript without having to save them to some backend? I want to display user images without having to save them online.
I have the user's absolute path to the image on their computer but when I try to display that it treats it as a relative path.
Is it possible to display an image with only frontend work and no backend? I want my app to be as trustworthy as possible so I don't want to save the user's images online.

A: @JamacCrew, Welcome to StackOverflow!
Your application cannot have access to the machine of a user so you cannot display images stored on their machines. You don't want to save the images on your server, so your user will have to give you the link to the images that are stored on a platform like dropbox or google. You can then save these links in your database and use them to display the images.


text:
Q: How can I give blur effect in android studio? How can I do to give the lighting effect to the edges of the letter in android studio? The card I use is an image and I want to give it the border and lighting
I tried to put in an image but it is too complicated for me


text:
Q: CakePHP 2.0 Form Validation I have a simple create new account page with username, email, confirm email, password, and confirm passwords fields.  All of the validations goes under the User model and currently all the input fields are required.
Once the user logs in, there's a setting page where they can update their email and password.  The input fields are email, confirm email, password, and confirm password (same input fields as the create an account page sans username field).  However, I want the validations to be different under settings with none of the fields being required.  How would I approach this problem without affecting the validation rules for the create new account page?  Your help is much appreciated.

A: It doesn't seem like you really need ANY of the fields "required" as CakePHP thinks of it.
"Required" as far as CakePHP is concerned means that that field MUST be submitted any and every time that model is saved.  It has nothing to do with whether or not there is content in the field (which is 'notEmpty').
So - for your case, you could probably just set up the normal data validation rules for each field (ie minLength, notEmpty, valid email...etc etc, etc, and be just fine for both pages.  Any data that's submitted must pass the validation - and if it's not submitted, no big deal.
You could always set:
'required' => 'create' //or update

if you need to verify that that field exists in the data for a save or update... but I've personally never found that necessary and have created many pages like you've described.
Per the book [here]:

required => true does not mean the same as the validation rule
  notEmpty(). required => true indicates that the array key must be
  present - it does not mean it must have a value. Therefore validation
  will fail if the field is not present in the dataset, but may
  (depending on the rule) succeed if the value submitted is empty ('').

A: You can use 'on', like this:
array(
        'rule' => 'required',
        'on'   => 'create' // or 'update'
)

Or you can try unseting validations in the controller, but the first is cleaner.


text:
Q: Gmail show inbox and sent emails in propper order I'm trying to create a logic that pulls from Gmail latest unique threads using Gmail API. For this i'm using search query that looks like this:
subject:(-"***") (label:sent OR label:inbox)

And it works fine in Google's email dashboard. For my dashboard it shows different result. I'm using methods listThreads and listMessages.
For listThreads if thread started long ago i wont see this thread in latest messages if i or other person continue this thread (reply on an email, for example), so i have to search it on the next pages. However on Google's dashboard it will be displayed on the first page.
For listMessages threads will be displayed in propper order but if this thread has 2 or more messages Gmail API will return 2 or more douplicated threds.
Is there a way i can preoritize sorting by latest message date when i use listThreads method. Or specify my search query to return messages with unique threadId for listMessages. Or there is a different way to implement my logic?
p.s. If i use in:inbox in search query for listThreads method, I'm getting propper results, but no inbox messages which is desirable.
Here is an image example for listThreads method:

And for ListMessages:
{
   "id": "163d68e0ac012e74",
   "threadId": "163d67b14457c9bd"
  },
  {
   "id": "163d688dbe1c6a5e",
   "threadId": "163d67b14457c9bd"
  },
  {
   "id": "163d68743cb38393",
   "threadId": "163d67b14457c9bd"
  },
  {
   "id": "163d684f32417253",
   "threadId": "163d67b14457c9bd"
  },
  {
   "id": "163d67b14457c9bd",
   "threadId": "163d67b14457c9bd"
  },

As you can see they have same threadId


text:
Q: Python: Update Tkinter while using Multiprocessing I am having the following issue:
I am trying to use concurrent.futures.ProcessPoolExecutor(), or anything similar, and show the progress of each process on a tkinter widget.
There is this answer:
Python Tkinter multiprocessing progress but I can not quite make it to work.
The following simplified version of my code seems to work only when using ThreadPoolExecutor() which I do not want.
Thanks in advance for any help!
import concurrent.futures
import tkinter
import tkinter.ttk
import multiprocessing
import random
import time

class App:
    def __init__(self, root):
        self.root = root

        self.processes = 5
        self.percentage = []
        self.changing_labels = []
        self.queues = []
        self.values = []

        for i in range(self.processes):
            temp_percentage = tkinter.StringVar()
            temp_percentage.set("0 %")
            self.percentage.append(temp_percentage)

            temp_changing_label = tkinter.Label(self.root, textvariable=temp_percentage)
            temp_changing_label.pack()
            self.changing_labels.append(temp_changing_label)

            self.queues.append(multiprocessing.Queue())
            # Just same values that I want to do calculations on
            temp_value = []
            for ii in range(12):
                temp_value.append(random.randrange(10))
            self.values.append(temp_value.copy())

        self.start_processing()

    def start_processing(self):
        def save_values(my_values):     # Save my new calculated values on the same file or different file
            with open(f"example.txt", "a") as file:
                for v in my_values:
                    file.write(str(v))
                    file.write(" ")
                file.write("\n")

        def work(my_values, my_queue):  # Here I do all my work
            # Some values to calculate my progress so that I can update my Labels
            my_progress = 0
            step = 100 / len(my_values)
            # Do some work on the values
            updated_values = []
            for v in my_values:
                time.sleep(0.5)
                updated_values.append(v + 1)

                my_progress += step
                my_queue.put(my_progress)   # Add current progress to queue

            save_values(updated_values)     # Save it before exiting

        # This Part does no work with ProcessPoolExecutor, with ThreadPoolExecutor it works fine
        with concurrent.futures.ProcessPoolExecutor() as executor:
            results = [executor.submit(work, self.values[i], self.queues[i])
                       for i in range(self.processes)]
            # Run in a loop and update Labels or exit when done
            while True:
                results_done = [result.done() for result in results]

                if False in results_done:
                    for i in range(self.processes):
                        if results_done[i] is False:
                            if not self.queues[i].empty():
                                temp_queue = self.queues[i].get()
                                self.percentage[i].set(f"{temp_queue:.2f} %")
                        else:
                            self.percentage[i].set("100 %")
                        self.root.update()
                else:
                    break
        # Close window at the very end
        self.root.destroy()

def main():  # Please do not change my main unless it is essential
    root = tkinter.Tk()
    my_app = App(root)
    root.mainloop()

if __name__ == "__main__":
    main()

A: The problem is caused by an exception being thrown inside the new processes. To see this exception, you can call the Future.result function, which raises the exception, e.g.
print([result.result() for result in results])

This gives the error AttributeError: Can't pickle local object 'App.start_processing.<locals>.work', so the problem is that work was defined inside another function.
After moving the work and save_values functions out of the start_processing method, the error changes to RuntimeError: Queue objects should only be shared between processes through inheritance. This can be fixed by using a multiprocessing.Manager to create the queues:

class App:
    def __init__(self, root):
        ...

        with multiprocessing.Manager() as manager:
            for i in range(self.processes):
                ...

                self.queues.append(manager.Queue())
            ...
            self.start_processing()

The print([result.result() for result in results]) debugging line can now be removed.
The full code is as follows:
import concurrent.futures
import tkinter
import tkinter.ttk
import multiprocessing
import random
import time

class App:
    def __init__(self, root):
        self.root = root

        self.processes = 5
        self.percentage = []
        self.changing_labels = []
        self.queues = []
        self.values = []

        with multiprocessing.Manager() as manager:
            for i in range(self.processes):
                temp_percentage = tkinter.StringVar()
                temp_percentage.set("0 %")
                self.percentage.append(temp_percentage)

                temp_changing_label = tkinter.Label(self.root, textvariable=temp_percentage)
                temp_changing_label.pack()
                self.changing_labels.append(temp_changing_label)

                self.queues.append(manager.Queue())
                # Just same values that I want to do calculations on
                temp_value = []
                for ii in range(12):
                    temp_value.append(random.randrange(10))
                self.values.append(temp_value.copy())

            self.start_processing()

    @staticmethod
    def save_values(my_values):  # Save my new calculated values on the same file or different file
        with open(f"example.txt", "a") as file:
            for v in my_values:
                file.write(str(v))
                file.write(" ")
            file.write("\n")

    @classmethod
    def work(cls, my_values, my_queue):  # Here I do all my work
        # Some values to calculate my progress so that I can update my Labels
        my_progress = 0
        step = 100 / len(my_values)
        # Do some work on the values
        updated_values = []
        for v in my_values:
            time.sleep(0.5)
            updated_values.append(v + 1)

            my_progress += step
            my_queue.put(my_progress)  # Add current progress to queue

        cls.save_values(updated_values)  # Save it before exiting

    def start_processing(self):

        # This Part does no work with ProcessPoolExecutor, with ThreadPoolExecutor it works fine
        with concurrent.futures.ProcessPoolExecutor() as executor:
            results = [executor.submit(self.work, self.values[i], self.queues[i])
                       for i in range(self.processes)]
            # Run in a loop and update Labels or exit when done
            while True:
                results_done = [result.done() for result in results]

                if False in results_done:
                    for i in range(self.processes):
                        if results_done[i] is False:
                            if not self.queues[i].empty():
                                temp_queue = self.queues[i].get()
                                self.percentage[i].set(f"{temp_queue:.2f} %")
                        else:
                            self.percentage[i].set("100 %")
                        self.root.update()
                else:
                    break
        # Close window at the very end
        self.root.destroy()

def main():  # Please do not change my main unless it is essential
    root = tkinter.Tk()
    my_app = App(root)
    root.mainloop()

if __name__ == "__main__":
    main()

PS: I would recommend not all(results_done) rather than False in results_done, and not results_done[i] rather than results_done[i] is False.


text:
Q: How to run C# application EXE with normal user account? I don't want to provide Admin user name and password when UAC is on I am working on the C# application. I am logged in to my machine with normal user account who don't have admin rights and UAC is set to highest level (Always notify me). When I try to run the application it ask me admin user name and password.I don't want to turn off the UAC. I have changed manifest file value to
<requestedExecutionLevel  level="asInvoker" uiAccess="false" />

or
  <requestedExecutionLevel  level="highestAvailable" uiAccess="false" />

But that din't help me. How can I run my application without full admin rights user? Any help on this is appreciated.
Thanks:
Mayuresh

A: From Project -> Project Properties and Application tab, just check whether your app.manifest file got referred under Icon and Manifest field or not, since it may be embedded also.


text:
Q: Get Value from Array as Array Key How do I recursively get value from array where I need to explode a key?
I know, it's not good the question, let me explain.
I got an array
[
  "abc" => "def",
  "hij" => [
              "klm" => "nop",
              "qrs" => [
                          "tuv" => "wxy"
                       ]
           ]
]

So, inside a function, I pass:
function xget($section) {
    return $this->yarray["hij"][$section];
}

But when I want to get tuv value with this function, I want to make section as array, example:
To get hij.klm value (nop), I would do xget('klm'), but to get hij.klm.qrs.tuv, I can't do xget(['qrs', 'tuv']), because PHP consider $section as key, and does not recursively explode it. There's any way to do it without using some ifs and $section[$i] ?

A: function xget($section) {
    return $this->yarray["hij"][$section];
}

that one is static function right?
you can do that also for this
function xget($section) {
    if(isset($this->yarray["hij"][$section])){
         return $this->yarray["hij"][$section];
    }elseif(isset($this->yarray["hij"]["klm"]["qrs"][$section])){
         return $this->yarray["hij"]["klm"]["qrs"][$section];
    }
}

as long as the key name between two of them are not the same.

A: You could use array_walk_recursive to find tuv's value regardless of the nested structure:
$tuv_val='';
function find_tuv($k,$v)
{
   global $tuv_val;
   if ($k=='tuv')
      $tuv_val=$v;
}
array_walk_recursive($this->yarray,"find_tuv");
echo "the value of 'tuv' is $tuv_val";

A: try my code
<?php

    $array = array(
            'aaa' => 'zxc',
            'bbb' => 'asd',
            'ccc' => array(
                    'ddd' => 'qwe',
                    'eee' => 'tyu',
                    'fff' => array(
                                'ggg' => 'uio',
                                'hhh' => 'hjk',
                                'iii' => 'bnm',
                            ),
                ),
        );

    $find = '';

    function xget($key){
        $GLOBALS['find'] = $key;
        $find = $key;
        array_walk_recursive($GLOBALS['array'],'walkingRecursive');
    }

    function walkingRecursive($value, $key)
    {
        if ($key==$GLOBALS['find']){
            echo $value;
        }
    }

    xget('ggg');
?>


text:
Q: Javascript If Else If statement issues I am having an issue with an If Else If statement in my code.  Basically, I have four four element arrays (Table1, Table2, Table3, Table4).  The value of a variable (frameSizeClass) taken from drop down menu will determine which of the arrays to use (via the If Else If statement), and another variable will determine which element in the array to return to a text box.
What is happening is that regardless of what the value of frameSizeClass is, it acts as if the variable=1, and return values from array Table1.  If I comment out the other portions of the If Else If and test the individual If statements, they work, but not as a combined If Else If.  I'm at a loss and would welcome any help.  Code is below.
    if (frameSizeClass = 1){
        baseLubeIntVal = greaseTable1[ratedSpeedClass];
    } else if (frameSizeClass = 2){
        baseLubeIntVal = greaseTable2[ratedSpeedClass];
    } else if (frameSizeClass = 3){
        baseLubeIntVal = greaseTable3[ratedSpeedClass];
    } else if (frameSizeClass = 4){
        baseLubeIntVal = greaseTable4[ratedSpeedClass];
    }

A: In most programming languages the = operator means assignment and == means equal.
The correct code would look like this
if (frameSizeClass == 1){
    baseLubeIntVal = greaseTable1[ratedSpeedClass];
} else if (frameSizeClass == 2){
    baseLubeIntVal = greaseTable2[ratedSpeedClass];
} else if (frameSizeClass == 3){
    baseLubeIntVal = greaseTable3[ratedSpeedClass];
} else if (frameSizeClass == 4){
    baseLubeIntVal = greaseTable4[ratedSpeedClass];
}


text:
Q: What about SoftwareBusinessOverflow.com? I'm running a small one person shareware company. So i'm interested a lot in questions around the software industries business aspects. A lot of them are so specialized to software that i thought they belong somewhere here but stackoverflow and serverfault are closing them regularly?
Do you see a need for this?
At the moment the only forum i know is the paid newsgroup from the "Association of shareware professionals - ASP".

A: Isn't this what the two Stack Exchange startup oriented sites are for?
http://answers.onstartups.com/
http://startups.com/


text:
Q: Macbook air 2015 trackpad short I recently spilled some water on my macbook and it stopped working. I opened it up and cleaned all corrosion I found. Thankfully, it booted up but I noticed that the trackpad and keyboard were not working. The trackpad got very hot to the touch. A chip on the trackpad board was getting very hot as soon as it boots up. The chip that gets scorching hot is shown in the image below:

Now the reason I'm stumped is because I replaced the trackpad with a new one, and the new one gets hot in the exact same place as the old one. So I guess this is caused by some other problem other than the trackpad itself. I am very unsure what it could be though which is why I'm asking here. To make sure it wasn't caused by the keyboard I ran it with the keybard ribbon cable disconnected but the short is still there. Also I should note that when it is connected the keyboard caps lock light flickers.
In order to not do further damage I've been running it with the ribbon cable for the trackpad disconnected. I would run it like this forever if I could but I believe this causes the SMC to freak out, so now my system is very slow and has the fan on full blast constantly.


text:
Q: Move Developer Folder I want to free some space on my SSD.
Is there a way to move the Developer folder from my root drive to another one without breaking anything?

A: Some files in the /Developer path are referenced when you launch specific functions within  Xcode. If you need to recover space and absolutely has to move /Developer, you could try

*

*Move the /Developer folder to the alternate path and symlink it so
that Xcode still finds it at /. Note: I haven't tried it with Xcode 4.x, so please share if this works.

*alternative is to do a clean uninstall using 'sudo
/Library/uninstall-devtools' and custom reinstall Xcode by
specifying a different path.

A: It might not hurt anything, or it might. A better (if more time-consuming) solution might be to delete your existing Developer folder, then re-install the dev tools to the drive you want them to be on. This will ensure that everything that has to be in /Developer is there.


text:
Q: How to optimize code and load UIPickerView with data fast? I'm creating UIPickerView with 2 components, for minutes and seconds. I've created picker in UI and want to fill it with data and below is code how I fill it with numbers from 0 - 59. I want to make it look like circular thats why kSizeOfPicker is 60000. When user press the button window with picker appears but it slows app very much, because this
code is in viewDidLoad. How can I fix it?
NSString *stringValue = [[NSString alloc] init];

for(int i=0; i<kSizeOfPicker; i++)
{
    stringValue = [NSString stringWithFormat:@"%d", i%60];

    [_minutesArray addObject:stringValue];
    [_secondsArray addObject:stringValue];
}

and here are data source and delegate methods:
#pragma mark - UIPickerView DataSource Methods

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent :    (NSInteger)component
{

if (component==0)
{
    return [_minutesArray count];
}
else
{
    return [_secondsArray count];
}

}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
NSString *title;
switch (component)
{

    case 0:
        title = [NSString stringWithFormat:@"%@ minutes", [_minutesArray objectAtIndex:row]];

        return title;
        break;
    case 1:
        title = [NSString stringWithFormat:@"%@ seconds", [_secondsArray objectAtIndex:row]];
        return title;
        break;
}
return nil;
}

#pragma mark - UIPickerView Delegate Methods

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{

if (component == 0)
    _firstComponent = [_minutesArray objectAtIndex:row];

else
    _secondComponent = [_secondsArray objectAtIndex:row];

}

A: You don't need prepare all data in NSArray to archive circular pickerview.
Following code virtually prepares +-50 duplicate datasets around selected row.
In pickerView:didSelectRow:inComponent: delegate method, you can reset selected row.
@interface MyViewController () <UIPickerViewDataSource, UIPickerViewDelegate>
@property (weak, nonatomic) IBOutlet UIPickerView *pickerView;
@property (assign, nonatomic) NSUInteger minutes;
@property (assign, nonatomic) NSUInteger seconds;
@end

@implementation MyViewController

#define VALUE_THRESHOLD 60
#define PICKER_DUPLICATES 100
#define CENTER_ROW (VALUE_THRESHOLD * PICKER_DUPLICATES / 2)

- (void)viewDidLoad {
    [super viewDidLoad];
    [_pickerView selectRow:_minutes + CENTER_ROW inComponent:0 animated:NO];
    [_pickerView selectRow:_seconds + CENTER_ROW inComponent:1 animated:NO];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return VALUE_THRESHOLD * PICKER_DUPLICATES;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return [NSString stringWithFormat:@"%d", row % VALUE_THRESHOLD];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    NSInteger actualRow = row % VALUE_THRESHOLD;

    // reset to center dataset
    [pickerView selectRow: actualRow + CENTER_ROW inComponent:component animated:NO];

    // do anything what you want;
    if(component == 0) {
        _minutes = actualRow;
    }
    else {
        _seconds = actualRow;
    }
}

@end

A: If the problem is loading time due to heavy data than either you can put these code in view did appear or you can put the code in Dispatch queue , It will not block your main thread and let your screen loads quickly.
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
    //Background Thread
    // here you can do your heavy operation
    dispatch_async(dispatch_get_main_queue(), ^(void){
        //Update your UI
    });
});

Or if you want to display time only than you can use UIDatePicker and set its mode :
Date Picker Mode
The mode of the date picker.
typedef enum {
   UIDatePickerModeTime,
   UIDatePickerModeDate,
   UIDatePickerModeDateAndTime,
   UIDatePickerModeCountDownTimer
} UIDatePickerMode;

Hope it helps you.
Thank you.

A: Use UIDatePicker instead of 60000 iterations it will make your life easier. Set its mode to Time.


text: Q: Automatically Zip SQL Backup Files I have a windows server 2012 server pulling a backup of my database every day but need to compress it.  Can I use Task Scheduler to automatically zip my SQL file and delete the larger original file?


text:
Q: How to read byte array from serial port in C# I have a problem with C# serial port programming
my aim send ByteArray to serial port and than get as ByteArray.
but I can not get from serial port. I tried:
string gelen = port.ReadExisting();
   int asd = port.ReadByte();
   string qwe = port.ReadLine();

Could any one tell me what's wrong?
 Thanks
my code:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO.Ports;

    namespace serial_port_app
    {

        public partial class Form1 : Form
        {

            public Form1()
            {
                InitializeComponent();

            }

            private void button1_Click(object sender, EventArgs e)
            {

                int text1, text2,text3,text4,text5, text6;

                Int32.TryParse(textBox1.Text, out text1);
                byte byteValue1 = Convert.ToByte(text1);

                Int32.TryParse(textBox2.Text, out text2);
                byte byteValue2 = Convert.ToByte(text2);

                Int32.TryParse(textBox3.Text, out text3);
                byte byteValue3 = Convert.ToByte(text3);

                Int32.TryParse(textBox4.Text, out text4);
                byte byteValue4 = Convert.ToByte(text4);

                Int32.TryParse(textBox5.Text, out text5);
                byte byteValue5 = Convert.ToByte(text5);

                Int32.TryParse(textBox6.Text, out text6);
                byte byteValue6 = Convert.ToByte(text6);

                byte[] byteArray = new byte[6];

                byteArray[0]=byteValue1;
                byteArray[1]=byteValue2;
                byteArray[2]=byteValue3;
                byteArray[3]=byteValue4;
                byteArray[4]=byteValue5;
                byteArray[5]=byteValue6;

                SerialPort port = new SerialPort("COM1", 9600, Parity.None, 8,      StopBits.One);

                port.Open();
                port.Write(byteArray,0,6);

>>>>>>>>>>>>>   string text = port.ReadExisting();
>>>>>>>>>>>>>   int asd = port.ReadByte();
>>>>>>>>>>>>>   string qwe = port.ReadLine();

                int n=dataGridView1.Rows.Add();

                    dataGridView1.Rows[n].Cells[1].Value = text;
                    dataGridView1.Rows[n].Cells[2].Value = asd;
                    dataGridView1.Rows[n].Cells[3].Value = qwe;
                    dataGridView1.Rows[n].Cells[4].Value = text4;
                    dataGridView1.Rows[n].Cells[5].Value = text5;
                    dataGridView1.Rows[n].Cells[6].Value = text6;

                    if ((n % 2) == 0)
                        dataGridView1.Rows[n].DefaultCellStyle.BackColor = Color.LightBlue;
                    else
                        dataGridView1.Rows[n].DefaultCellStyle.BackColor = Color.LightGreen;

                    port.Close();
            }

EDIT for correct answer:
delete:
string text = port.ReadExisting();
int asd = port.ReadByte();
string qwe = port.ReadLine();

and add:
port.DtrEnable = true;
 port.RtsEnable = true;

 int bytes = port.BytesToRead;
 byte[] buffer = new byte[bytes];
 port.Read(buffer, 0, bytes);

A: To get a Byte array rather than a String use BytesToRead and Read(Byte[], Int32, Int32)


text:
Q: How can I use a core html web template to view in Symfony framework with route? I tried it many time, but not able to execute it.
Already I have a static website and it not working if I change its extension to twig format, like index.html to index.html.twig.(css and javascript not working if I use twig)

A: To include css and js files the easiest (but not recommended) way is to put css and js files inside /web/ directory and in template file include it by relative path (when "web" directory is treated as main site directory).
If You want to read about proper way of doing it look:

*

*How to include CSS file in Symfony 2 and Twig?

*http://symfony.com/doc/current/cookbook/assetic/asset_management.html


text:
Q: How to implement ORDER BY from a Spring Data JPA GROUP BY query Based on question How to return a custom object from a Spring Data JPA GROUP BY query, my custom query is working, as follows:
@Query("select new br.com.cwidevs.dto.Goleador(j.id, sum(pj.gols)) from PartidaJogador pj join pj.id.jogador j group by j.id")
public List<Goleador> getGoleadores();

Here is the simple bean class:
public class Goleador {

    private Long jogador;

    private Long totalGols;
}

At this point, how to implement ORDER BY? Can I achieve thi with Sort?

A: Try this:
@Entity
public class Goleador {
    //...
}

@Entity
public class PartidaJogador {
    //...

    @ManyToOne
    private Goleador jogador;

    private Long gols;

    //...
}

// DTO as Projection
public interface GoleadorWithGols {
    Goleador getGoleador();
    Long getTotalGols()
}

public interface GoleadorRepo extends JpaRepository<Goleador, Long> {
    @Query("select j as goleador, sum(pj.gols) as totalGols from PartidaJogador pj join pj.jogador j group by j order by totalGols")
    List<GoleadorWithGols> getGoleadores();
}

Here we use a projection GoleadorWithGols as DTO to get necessary data.
More info is here.

A: JpaRepository extends PagingAndSortingRepository so you can definetly use Sort
Add parameter to your method public List<Goleador> getGoleadores(Sort sort); when you call it just specify by which column you want to sort your query and you should be good.
repoGoleador.getGoleadores(new Sort("jogador"));

A: I just solved this problem :
Class-based Projections doesn't work with query
native(@Query(value = "SELECT ...", nativeQuery = true))

So I recommend to define custom DTO using interface .
Before using DTO should verify the query syntactically correct or not.


text:
Q: Select Encadeado Ola, estou com uma dúvida quanto a um select encadeado. Encontrei muitos exemplos com
select * from (select campo from tabela)

Porém quero definir os campos da minha consulta, como abaixo:
select campo1,campo2,(select campo1 from tabela2) from tabela1

O ponto é que dentro do select preciso de um where com uma coluna exibida
select campo1,campo2,(select campo1 from tabela2 where id=campo1) from tabela1

Como posso indexar a buscar por outra coluna?

A: Pelo nome dos campos acredito que tabela1 e tabela2 são a mesma tabela.
Sendo assim você precisa definir um alias para elas pra que o sql consiga diferenciar o campo de uma para outra.
SELECT T1.campo1,
       T1.campo2,
       (select T2.campo1 from tabela2 T2 where T1.id=T2.campo1) as campo3
FROM tabela1 T1

Editado
Considerando as informações da resposta abaixo,
SELECT T1.id,
       T1.id venda,
       (select T2.nome from tabela2 T2 where T1.id = T2.id) as nome
FROM tabela1 T1

A: Para que isso seja possível você precisa ter em mente que a informação do subselet precisa retornar apenas um valor. Você não pode retornar dois valores no mesmo alias e poderá receber o erro: MySQL error 1241: Operand should contain 1 column(s).
SELECT
    cod,
    nome,
    desc,
    (SELECT
        SUM(dado)
    FROM
        tabela_auxiliar
    WHERE
        cod = 1) as Vendeu,
   (SELECT
        SUM(dado)
    FROM
        tabela_auxiliar
    WHERE
        cod = 2) as Estocou
FROM
    tabela_principal;

No caso da sua "subconsulta" select campo1 from tabela2 where id=campo1 se tiver retornando dois valores irá ocorrer o erro descrito acima,por este motivo sera um alias para Estocou e outro para Vendeu.


text:
Q: How to make multiline graph with matplotlib subplots and pandas? I'm fairly new at coding (completely self taught), and have started using it at at my job as a research assistant in a cancer lab. I need some help setting up a few line graphs in matplot lab.
I have a dataset that includes nextgen sequencing data for about 80 patients. on each patient, we have different timepoints of analysis, different genes detected (out of 40), and the associated %mutation for the gene.
My goal is to write two scripts, one that will generate a "by patient" plot, that will  be a linegraph with y-%mutation, x-time of measurement, and will have a different color line for all lines made by each of the patient's associated genes. The second plot will be a "by gene", where I will have one plot contain different color lines that represent each of the different patient's x/y values for that specific gene.
Here is an example dataframe for 1 genenumber for the above script:
gene    yaxis   xaxis   pt# gene#
ASXL1-3 34  1   3   1
ASXL1-3 0   98  3   1
IDH1-3  24  1   3   11
IDH1-3  0   98  3   11
RUNX1-3 38  1   3   21
RUNX1-3 0   98  3   21
U2AF1-3 33  1   3   26
U2AF1-3 0   98  3   26

I have setup a groupby script that when I iterate over it, gives me a dataframe for every gene-timepoint for each patient.
grouped = df.groupby('pt #')
for groupObject in grouped:
    group = groupObject[1]

For patient 1, this gives the following output:
        y     x   gene  patientnumber patientgene  genenumber  dxtotransplant  \
0    40.0  1712  ASXL1              1     ASXL1-1           1            1857
1    26.0  1835  ASXL1              1     ASXL1-1           1            1857
302   7.0  1835  RUNX1              1     RUNX1-1          21            1857

I need help writing a script that will create either of the plots described above. using the bypatient example, my general idea is that I need to create a different subplot for every gene a patient has, where each subplot is the line graph represented by that one gene.
Using matplotlib this is about as far as I have gotten:
plt.figure()

grouped = df.groupby('patient number')

for groupObject in grouped:
    group = groupObject[1]
    df = group #may need to remove this
    for element in range(len(group)):
        xs = np.array(df[df.columns[1]]) #"x" column
        ys= np.array(df[df.columns[0]]) #"y" column
        gene = np.array(df[df.columns[2]])[element] #"gene" column
        plt.subplot(1,1,1)
        plt.scatter(xs,ys, label=gene)
        plt.plot(xs,ys, label=gene)
        plt.legend()
    plt.show()

This produces the following output:

In this output, the circled line is not supposed to be connected to the other 2 points. In this case, this is patient 1, who has the following datapoint:
x       y   gene
1712    40  ASXL1
1835    26  ASXL1
1835    7   RUNX1

Using seaborn I have gotten close to my desired graph using this code:
grouped = df.groupby(['patientnumber'])
for groupObject in grouped:
    group = groupObject[1]
    g = sns.FacetGrid(group, col="patientgene", col_wrap=4, size=4, ylim=(0,100))
    g = g.map(plt.scatter, "x", "y", alpha=0.5)
    g = g.map(plt.plot, "x", "y", alpha=0.5)
    plt.title= "gene:%s"%element

Using this code I get the following:
If I adjust the line:
g = sns.FacetGrid(group, col="patientnumber", col_wrap=4, size=4, ylim=(0,100))

I get the following result:

As you can see in the 2d example, the plot is treating every point on my plot as if they are from the same line (but they are actually 4 separate lines).
How I can tweak my iterations so that each patient-gene is treated as a separate line on the same graph?

A: I wrote a subplot function that may give you a hand. I modified the data a tad to help illustrate the plotting functionality.
gene,yaxis,xaxis,pt #,gene #
ASXL1-3,34,1,3,1
ASXL1-3,3,98,3,1
IDH1-3,24,1,3,11
IDH1-3,7,98,3,11
RUNX1-3,38,1,3,21
RUNX1-3,2,98,3,21
U2AF1-3,33,1,3,26
U2AF1-3,0,98,3,26
ASXL1-3,39,1,4,1
ASXL1-3,8,62,4,1
ASXL1-3,0,119,4,1
IDH1-3,27,1,4,11
IDH1-3,12,62,4,11
IDH1-3,1,119,4,11
RUNX1-3,42,1,4,21
RUNX1-3,3,62,4,21
RUNX1-3,1,119,4,21
U2AF1-3,16,1,4,26
U2AF1-3,1,62,4,26
U2AF1-3,0,119,4,26

This is the subplotting function...with some extra bells and whistles :)
def plotByGroup(df, group, xCol, yCol, title = "", xLabel = "", yLabel = "", lineColors = ["red", "orange", "yellow", "green", "blue", "purple"], lineWidth = 2, lineOpacity = 0.7, plotStyle = 'ggplot', showLegend = False):
    """
    Plot multiple lines from a Pandas Data Frame for each group using DataFrame.groupby() and MatPlotLib PyPlot.
    @params
        df          - Required  - Data Frame    - Pandas Data Frame
        group       - Required  - String        - Column name to group on
        xCol        - Required  - String        - Column name for X axis data
        yCol        - Required  - String        - Column name for y axis data
        title       - Optional  - String        - Plot Title
        xLabel      - Optional  - String        - X axis label
        yLabel      - Optional  - String        - Y axis label
        lineColors  - Optional  - List          - Colors to plot multiple lines
        lineWidth   - Optional  - Integer       - Width of lines to plot
        lineOpacity - Optional  - Float         - Alpha of lines to plot
        plotStyle   - Optional  - String        - MatPlotLib plot style
        showLegend  - Optional  - Boolean       - Show legend
    @return
        MatPlotLib Plot Object

    """
    # Import MatPlotLib Plotting Function & Set Style
    from matplotlib import pyplot as plt
    matplotlib.style.use(plotStyle)
    figure = plt.figure()                   # Initialize Figure
    grouped = df.groupby(group)             # Set Group
    i = 0                                   # Set iteration to determine line color indexing
    for idx, grp in grouped:
        colorIndex = i % len(lineColors)    # Define line color index
        lineLabel = grp[group].values[0]    # Get a group label from first position
        xValues = grp[xCol]                 # Get x vector
        yValues = grp[yCol]                 # Get y vector
        plt.subplot(1,1,1)                  # Initialize subplot and plot (on next line)
        plt.plot(xValues, yValues, label = lineLabel, color = lineColors[colorIndex], lw = lineWidth, alpha = lineOpacity)
        # Plot legend
        if showLegend:
            plt.legend()
        i += 1
    # Set title & Labels
    axis = figure.add_subplot(1,1,1)
    axis.set_title(title)
    axis.set_xlabel(xLabel)
    axis.set_ylabel(yLabel)
    # Return plot for saving, showing, etc.
    return plt

And to use it...
import pandas

# Load the Data into Pandas
df = pandas.read_csv('data.csv')

#
# Plotting - by Patient
#

# Create Patient Grouping
patientGroup = df.groupby('pt #')

# Iterate Over Groups
for idx, patientDF in patientGroup:
    # Let's give them specific titles
    plotTitle = "Gene Frequency over Time by Gene (Patient %s)" % str(patientDf['pt #'].values[0])
    # Call the subplot function
    plot = plotByGroup(patientDf, 'gene', 'xaxis', 'yaxis', title = plotTitle, xLabel = "Days", yLabel = "Gene Frequency")
    # Add Vertical Lines at Assay Timepoints
    timepoints = set(patientDf.xaxis.values)
    [plot.axvline(x = timepoint, linewidth = 1, linestyle = "dashed", color='gray', alpha = 0.4) for timepoint in timepoints]
    # Let's see it
    plot.show()

And of course, we can do the same by gene.
#
# Plotting - by Gene
#

# Create Gene Grouping
geneGroup   = df.groupby('gene')

# Generate Plots for Groups
for idx, geneDF in geneGroup:
    plotTitle = "%s Gene Frequency over Time by Patient" % str(geneDf['gene'].values[0])
    plot = plotByGroup(geneDf, 'pt #', 'xaxis', 'yaxis', title = plotTitle, xLab = "Days", yLab = "Frequency")
    plot.show()

If this isn't what you're looking for, provide a clarification and I'll take another crack at it.


text:
Q: What is the probability of 12 friends each having birthday on different months of each other. What is the probability of 12 friends each having birthday on different months of each other. Twelve people having birthday on every month of the year.
We are a group of 12 friends and each one of us, have a birthday on a different month, so we cover the whole year. What is the probability of that?
Thanks
Leo

A: The probability is low.
Suppose we write the months of the birthdays of each person in a list, starting with person 1, then person 2 and so on (assuming the people are numbered in some way). We get $12^{12}$ possible lists, we assume they are all equally likely, which is not the case in real life since some months are shorter, and even ignoring this, births seem to be more popular in certain parts of the year.
In this case there are $12!$ acceptable lists, that is $12!$ lists in which each month appears.
Hence the probability is $\frac{12!}{12^{12}}\approx 0.000053723217$

A: If you would like an alternative answer to Gamamals that is equivalent but more intuitive, I think, consider the following. Number you and your friends from 1 to 12, where you are #1. The probability that #2's birth month is different from your own is 11/12. The probability that #3's birth month is different from your own and #2 is then 10/12. Keep iterating this, then the probability you all have distinct birth months can be solved by multiplying those probabilities (as all birth months must be distinct to span all 12 months):
$$ \frac{11}{12} \times \frac{10}{12} \times \frac{9}{12} \times \frac{8}{12} \times \frac{7}{12} \times \frac{6}{12} \times \frac{5}{12} \times \frac{4}{12} \times \frac{3}{12} \times \frac{2}{12} \times \frac{1}{12} = \frac{11!}{12^{11}} = \frac{12!}{12^{12}} $$
where the last equality comes from multiplying both the numerator and the denominator by 12. I hope this serves as an alternative (and perhaps more intuitive) way to come by Gamamal's answer.


text:
Q: How to change header section text color in InAppSettingsKit class? I'm using InAppSettingsKit for my app but I'm having problems changing the text color of my section headers in my grouped tableview. I've tried using the following code but it doesn't work:
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
    {
        UIView *tempView=[[UIView alloc]initWithFrame:CGRectMake(0,200,300,244)];
        tempView.backgroundColor=[UIColor clearColor];

        UILabel *tempLabel=[[UILabel alloc]initWithFrame:CGRectMake(15,0,300,44)];
        tempLabel.backgroundColor=[UIColor clearColor];
        tempLabel.shadowColor = [UIColor blackColor];
        tempLabel.shadowOffset = CGSizeMake(0,2);
        tempLabel.textColor = [UIColor redColor]; //here u can change the text color of header
        tempLabel.font = [UIFont fontWithName:@"Helvetica" size:fontSizeForHeaders];
        tempLabel.font = [UIFont boldSystemFontOfSize:fontSizeForHeaders];
            tempLabel.text=@"Header Text";

        [tempView addSubview:tempLabel];

        [tempLabel release];
        return tempView;
    }

The InAppSettingsKit code looks like so:
- (NSString *)tableView:(UITableView*)tableView titleForHeaderInSection:(NSInteger)section {
    NSString *header = [self.settingsReader titleForSection:section];
    if (0 == header.length) {
        return nil;
    }
    return header;
}

- (UIView *)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section {
    NSString *key  = [self.settingsReader keyForSection:section];
    if ([self.delegate respondsToSelector:@selector(tableView:viewForHeaderForKey:)]) {
        return [self.delegate tableView:_tableView viewForHeaderForKey:key];
    } else {
        return nil;

}
}

How would I implement the first code into their code? I need to change the text color of those titles. Thanks.

A: Implement -tableView:viewForHeaderForKey: in your IASKSettingsDelegate. The implementation would be identical to your -tableView:viewForHeaderInSection: code except that you'd need to check the key to determine the text of the label (if you have multiple headers).


text:
Q: JS for loop resetting to 0 between loops for no reason I have the following for loop in my Javascript:
  for (x=0;x<newPlayer.length;x++){
    console.log(newPlayer.length,x);
    console.log("bigloopstart");
    $(".timeline-grid").append(
      "

        <div class='timeline-icon ` + eventDate + "'>" + iconhtml + `

` + eventOldTeam[x] + `

`
    );
    console.log(newPlayer.length,x);
    for (i=0,t=activeplayers.length;i<t;i++){
      if (newPlayer[x].name == activeplayers[i].name){
        activeplayers.splice(i,1);
        console.log("smallloop");
        break;
      }
    }
    console.log(newPlayer.length,x);
    console.log("bigloopend");
  }

In the case I'm testing it with, newPlayer has length 2. The loop runs through twice, but then runs a third time, spitting out an error because it can't read the properties of the nonexistent third object in the array.
It seems that for some reason x is resetting to 0 after the second loop:

I even tried putting the x++ inside the loop:
  for (x=0;x<newPlayer.length;){
    console.log(newPlayer.length,x);
    console.log("bigloopstart");
    $(".timeline-grid").append(
      "

        <div class='timeline-icon ` + eventDate + "'>" + iconhtml + `

` + eventOldTeam[x] + `

`
    );
    console.log(newPlayer.length,x);
    for (i=0,t=activeplayers.length;i<t;i++){
      if (newPlayer[x].name == activeplayers[i].name){
        activeplayers.splice(i,1);
        console.log("smallloop");
        break;
      }
    }
    x++;
    console.log(newPlayer.length,x);
    console.log("bigloopend");
  }

but then the console looks like this:

It seems that between the second and third loops x is being reset to 0 and I have no idea why. Any pointers?


text:
Q: simple-xml NodeBuilder No Class Def Found Error on Raspberry Pi running Kura I have an OSGi bundle that uses SimpleXML as an imported jar (The SimpleXML jar is well defined on the bundle class path and is included in the exported bundle), the bundle works fine in the Kura emulator inside Eclipse, But when the bundle is deployed to Raspberry Pi, starting the bundle will throw an error:
java.lang.NoClassDefFoundError: Could not initialize class org.simpleframework.xml.stream.NodeBuilder

Anyone has encountered this problem?
-- UPDATE: I got it to work by exporting and importing SimpleXML from my Bundle and having a simpleXML Bundle active as well on the device. (Which I don't think is the solution, but is working for now). Ideally the SimpleXML jar should work without being exposed outside my bundle.
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Test
Bundle-SymbolicName: org.eclipse.kura.test.implementation
Bundle-Version: 1.0.0.qualifier
Bundle-RequiredExecutionEnvironment: JavaSE-1.7
Export-Package: org.eclipse.kura.test.implementation,
 org.simpleframework.xml,
 org.simpleframework.xml.convert,
 org.simpleframework.xml.core,
 org.simpleframework.xml.filter,
 org.simpleframework.xml.strategy,
 org.simpleframework.xml.stream,
 org.simpleframework.xml.transform,
 org.simpleframework.xml.util
Bundle-ClassPath: .,
 jar/org.simpleframework.simple-xml.2.3.jar
Import-Package: org.eclipse.kura.test.api,
 org.osgi.framework;version="1.7.0",
 org.osgi.service.component;version="1.2.0",
 org.simpleframework.xml,
 org.simpleframework.xml.convert,
 org.simpleframework.xml.core,
 org.simpleframework.xml.filter,
 org.simpleframework.xml.strategy,
 org.simpleframework.xml.stream,
 org.simpleframework.xml.transform,
 org.simpleframework.xml.util
Service-Component: OSGI-INF/component.xml
Require-Bundle: slf4j.api
Bundle-ActivationPolicy: lazy


text:
Q: Авторизация ВК через Selenium Делаю парсер для вк и наткнулся на проблему с авторизацией, т.е selenium выдаёт:
OpenQA.Selenium.ElementNotInteractableException: "element not interactable"

Код:
    program.driver.Url = ("https://vk.com/");
    wait.Until(ExpectedConditions.ElementExists(By.CssSelector(@"form#index_login_form > input#index_email:nth-child(7)")));
    Console.WriteLine("Сайт VK загружен");

    program.driver.FindElement(By.Name(@"email")).SendKeys(phone_number);

Думал, что страница до конца не загружается, но нет. Что делать?


text:
Q: What's the fastest way to open LogCat view? Most of the times I run a Project I need to open/maximize LogCat and then minimize it.
Usually it takes a few clicks with the mouse.
Click the LogCat icon on the Debug perspective ctrl+M to maximize it and then click the minimize icon.
Wonder if there is a faster way, hope without the need to click the mouse.

A: Go to Window -> Preferences.
Then go to General -> Keys.
Find the entry "Show View (View: Logcat)"
Go to Binding and hit a key (such as F10).
Personally, I use two screens for developing. Main Window on the main screen and Logcat, File Explorer and Console on the second one.

A: *

*Press Shift Twice

*Type logcat

*Press Enter

A: If I understand your problem correctly, you already have the LogCat view open. But, when you want to maximize it, its a pain to double click it every time.
Solution:
Use Ctrl+F7 to shift between the views like "LogCat", "Console", "Editor" etc. Then when you are at particular view, just use Ctrl+M to maximize the view in full screen.
I think you will like some of the Shortcuts mentioned here: http://www.rapidsnail.com/Developer/topic/2012/76/27/60320/ask-next-eclipse-the-commonly-used-shortcut-key.aspx

A: Window -> Show View -> Other -> Android -> LogCat

A: I personally think Eclipse is not the best place to watch logcat (it is already as heavy as it gets by default, and you put more into it...).
So, I recommend good old command line (Linux):
$ adb logcat -v time

I have created a logcat colorizer to help distinguish the important stuff:
https://bitbucket.org/brunobraga/logcat-colorize


text:
Q: CONCAT n VALUES I have multiple fields name as this
custom_1_field
custom_2_field
custom_3_field
.
.
custom_N_field

I never know how much custom_N_fields. I need to concat all of them.
I can concate with this code if i kwow how much fields i have
CONCAT_WS(' ',custom_1_field,CONCAT('
',custom_2_field)) AS new_field

But if i don't know how much N custom_N_fields I have, what can i do?
There are something like CONCAT custom_N_fields where 'N' it's any number?
EDIT: i use php+sql
Thanks

A: It's pretty weird, but this should do it - look up the list of fields first and then each one that matches your pattern gets put in the CONCAT(...) column:
<?php
$sql = 'SELECT CONCAT_WS(" "';
$q = mysqli_query($conn, 'DESCRIBE tablename');
while ($row = mysqli_fetch_array($q, MYSQLI_ASSOC))
    if (preg_match("/custom_\d+_field/", $row['Field']))
        $sql .= ",".$row['Field'];
$sql .= ') AS new_field';
# $sql .= "FROM someTable WHERE x = y";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($q, MYSQLI_ASSOC)) {
    # do stuff with $row['new_field']
}
?>

Looks like you want to do something with
 tags in there as well - it should be relatively trivial to extend the example to do that.

A: If you don't like the SQL answer I suggested above, you could very easily (much
more easily!) solve the problem within PHP (or whatever programming platform you are using).  Simply do your query and grab the list of fields from the resulting query on the first fetch and then construct your string from those fields.  Something like this:
$sql = 'SELECT ...';
$results = mysqli_query($conn, $sql);
$field_list = array();
while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
    if (!$field_list) {
        $field_list = preg_grep('/^custom_\d+_field$/', array_keys($row));
    }
    // work with $row until you need the concatenated field...
    // then use this snippet to construct the concatenated field
    $newstr = $sep = '';
    foreach ($field_list as $f) {
        $newstr = $sep.$row[$f];
        $sep = ' '; // this will be put in front of all the rest of the fields
    }
    // now echo your $newstr or whatever you want to do with it
}

I would be interested in feedback from others on the construction of the string using $sep as I have done it - it's a construction I use often and it feels inelegant and inefficient and I'd be interested in a better way to do it.


text:
Q: Do $L^P$ functions form a metric space? I have a general question about $L^P$ functions.
I have heard that $L^P$ functions form a vector space. My question is can we make them form a metric space too? And what is/are the possible metric/s ? I am mostly concerned with functions in complex plane and a possible metric in terms of a norm in the vector space.
Thanks a lot in advance.

A: In a metric space, it is required that $d(u, v) = 0$ iff $u = v$. This is not immediately true for functions in $L^p$, for if $u \ne v$ but $u = v$ [a.e], then $\|u - v\|_p = 0$. This is easy to fix, however.
Instead of considering individual functions in $L^p$, you consider the equivalence classes of the relation $u \sim v \iff u = v \text{ [a.e.]}$. When you talk about a function $u$ in the metric space $L^p$, you're really talking about the equivalence class of all functions that are equal to $u$ [a.e.]. This is how you ensure that $d(u, v) = 0 \iff u = v$.


text:
Q: Simulate dynamically subdomains with .htaccess with a different database but same code base in Drupal Sorry about my english level.
I researched so much, and i found that can i use ".htaccess" to get redirection to subdomain folder and this is OK.
In Drupal i need to create a folder for each subdomain in "/sites/sub.example.com/" and copy "default.settings.php" from default folder "/sites/default/default.setting.php" and rename it to "settings.php", after that, enable "$databases" variable in the same file, when it's done, i need to add a wildcard and modify "hosts" file.
Well, i should "automate" all this, but i don't know if it's is more hard because it's important hold the server safety with writing permissions or try another way, someone could advise me.
Im working on OSX and Drupal 7.x (recent release)
Thank you very much.

A: For each site that you want to use separate database, create own sites/ directory with settings.php. For example, if you want to have one database for example.com, another one for sub1.example.com and third one for sub2.example.com, all using same code base, setup your files like this:
sites/example.com/settings.php
sites/sub1.example.com/settings.php
sites/sub2.example.com/settings.php
each settings.php using different database credentials.
Read more here - https://drupal.org/documentation/install/multi-site
Also, if you want to automate this and if there is supposed to be bigger number of sites to be managed, consider deploying aegir - http://www.aegirproject.org.
I hope I understood your question correctly.


text:
Q: How to set a scope to click on Annotation on an iOS map I'm developing an iOS game with a Mapview, where I want to select an opponent from the multiple annotations on Map then I'll hit him. In the Map first user will select a range where he/she will find opponent and at that time some area(in particular angle) of map will fade in (pls see image),
So the trouble which I have is I want to enable only those user/annotation which are in no-shaded area, this area will be an angle of 60 degrees, currently I'm using just an Imageview over the map to show the shaded area.
How can I achieve this, Every suggestion would be appreciated.

A: Try this:
Convert all your Annotations lat, lat to x,y & find point inside the triangle. If so add those annotations.
determine whether point lies inside triangle


text:
Q: Wordpress admin_post callback not firing This seems to be working on other sites I create however, my callback doesn't seem to fire. All I get is a white screen. Its like the callback does not exists.
I have checked has_action('admin_post_process_submission') and that returns true.
The plugin file itself returns other functionality absolutely fine.
I've been staring at JS for the last week or two so is there something I'm missing?
<?php class KnpvForm extends KnpvEndPoints {

function __construct()  {

    parent::__construct();

    //Actions for processing the form <<< does not seem
    add_action( 'admin_post_process_submission', array($this, 'knpv_admin_process_submission'));

    //A filter which seems to work fine.
    add_filter( 'tiny_mce_before_init', array($this, 'knpv_mce_butttons'), 10, 2 );

}

/**
 * I expect this function to just print some words.
 */
public function knpv_admin_process_submission(){

    echo '<pre>';
    print_r('some words');
    echo '</pre>';

}

} ?>


text:
Q: javascript error- Chrome say it's not a function I have a js file and a html. From the html I call the function on click.
My Problem is- The specification_none works, But Chrome prompts the following error:

Uncaught TypeError: specification_existing is not a function

So what is the Problem? Why doesn't the other function work?
Here is my code:

$( document ).ready(function() {

        if ($('#radio_specification_none').attr("checked")){

            $("#specification_existing_box").hide();    // hide existing_spec
            $("#specification_new_box").hide();         // hide new_spec

            $('#specification_existing_box')[0].selectedIndex = 0;          // set existing specifications to default value

            $('#specification_existing_box').prop('required', false);        // set existing spec. size the required attribute to false
            $('#specification_new_box').prop('required', false);        // set for new spec. the required attribute to false
        }
        if ($('#radio_specification_existing').attr("checked")){

            $("#specification_existing_box").show();            // hide existing_spec
            $("#specification_new_box").hide();                 // hide create new_spec

            $('#specification_existing_box').prop('required', true);        // set for new_spec the required attribute to true
            $('#specification_new_box').prop('required', false);            // set for new_spec the required attribute to false
        }
        if ($('#radio_specification_new').attr("checked")){

            $("#specification_new_box").show();                // show new_spec
            $("#specification_existing_box").hide();           // hide existing_spec

            $('#specification_existing_box')[0].selectedIndex = 0;          // set existing specifications to default value

            $('#specification_existing_box').prop('required', false);        // set for new_spec the required attribute to false
            $('#specification_new_box').prop('required', true);             // set for new_spec the required attribute to true
        }

    // ---- show and hide sizes ----- //

    // children sizes (default)
    $('#radio_child').change(function(){
        if (!$('#radio_child').checked){        // change if other user pick other button; this one is then false

            $("#child_sizes").show();           // show child sizes
            $("#konfektion_sizes").hide();      // hide adult sizes
        }

        $('#select_konfektion_sizes')[0].selectedIndex = 0;     // set adult size to "Wählen..."

        $('#select_child_sizes').prop('required',true);         // set for child size the required attribute to true
        $('#select_konfektion_sizes').prop('required',false);   // set for adult size the required attribute to false
    });
    // adult sizes
    $('#radio_adult').change(function(){        // change if other user pick other button; this one is then false
        if (!$('#radio_adult').checked){

            $("#child_sizes").hide();           // hide child sizes
            $("#konfektion_sizes").show();      // show adult sizes
        }

        $('#select_child_sizes')[0].selectedIndex = 0;          // set children size to default value

        $('#select_child_sizes').prop('required',false);        // set for child size the required attribute to false
        $('#select_konfektion_sizes').prop('required',true);    // set for adult size the required attribute to true
    });

    // triggers
    $('#radio_child').trigger('change');                        // trigger change (child radio) for one time, if document load

});

function specification_none(element){

  alert("specification_none");

    // change the checked attribute
    $(element).prop('checked', "checked");
    $('#specification_existing_box').prop('checked', "");
    $('#specification_new_box').prop('checked', "");

    //hide other specifications
    $("#specification_existing_box").hide();    // hide existing_spec
    $("#specification_new_box").hide();         // hide new_spec

    // set existing specifications to default value
    $('#specification_existing_box')[0].selectedIndex = 0;

    // set the required attribute from THIS input to true
    $('#specification_none_box').prop('required', true);
    // set the required attribute from the other inputs to false
    $('#specification_existing_box').prop('required', false);
    $('#specification_new_box').prop('required', false);
}

function specification_existing(element){

  alert("specification_existing");

    // change the checked attribute
    $(element).prop('checked', "checked");
    $('#specification_none_box').prop('checked', "");
    $('#specification_new_box').prop('checked', "");

    // show existing box
    $("#specification_existing_box").show();    // hide existing_spec

    //hide other specifications
    $("#specification_none_box").hide();    // hide existing_spec
    $("#specification_new_box").hide();         // hide new_spec

    // set the required attribute from THIS input to true
    $('#specification_existing_box').prop('required', true);
    // set the required attribute from the other inputs to false
    $('#specification_none_box').prop('required', false);
    $('#specification_new_box').prop('required', false);
}

function specification_new(element){

  alert("specification_new");

    // change the checked attribute
    $(element).prop('checked', "checked");
    $('#specification_existing_box').prop('checked', "");
    $('#specification_none_box').prop('checked', "");

    //hide other specifications
    $("#specification_existing_box").hide();    // hide existing_spec
    $("#specification_none_box").hide();         // hide new_spec

    // set existing specifications to default value
    $('#specification_existing_box')[0].selectedIndex = 0;

    // set the required attribute from THIS input to true
    $('#specification_new_box').prop('required', true);
    // set the required attribute from the other inputs to false
    $('#specification_existing_box').prop('required', false);
            $('#specification_none_box').prop('required', false);
}

Besonderheit:

                    <input type="radio" id="radio_specification_new" name="specification" class="custom-control-input" onclick="specification_new(this)">
                    neue erstellen

                    <input type="radio" id="radio_specification_existing" name="specification" class="custom-control-input" onclick="specification_existing(this)" {% if clothing_info[0].clothes_specification_id != 1 %} checked="checked" {% else %}  {% endif %}>
                    vorhandene

                    <input type="radio" id="radio_specification_none" name="specification" class="custom-control-input" onclick="specification_none(this)" {% if clothing_info[0].clothes_specification_id == 1 %} checked="checked" {% else %}  {% endif %}>
                    keine

Can someone help me out here

A: I cant figure out why this is not working. I made a running version and it runs great.
But since you use the onclick props of the HTML elements, there can be allot of things going wrong here. Since you are using jQuery consider binding the callbacks via jQuery's .click() method (see below).
This method can reduce errors coming with scoping etc greatly and you don't have to pollute the global JS space.
Potentially you have some script thats just sets the function specification_existing to anything else like this:
specification_existing = 'accidentally changed specification_existing'
This is also indicated by the error you get:

*

*... is not a function indicates that the "variable" exsists, but is not a callable function

*... is not defined indicates that the "variable" you try to call is unknown
Here are some things that could help you allot with this kind of problems:

*

*keep your global space clean. exec your code in (function(){/* your code */})() or similar fashion.

*always declare and init variables (var myLocalVar) or use strict mode

*try to not mix JS code into your HTML. Use jQuery or better the vanilla JS API: jQuery.on('click', ()=>{[...]}) element.addEventListener('click', ()=>{[...]})

$(function(){
  function specification_none(element) {
    console.log('specification_none')

      // change the checked attribute
      $(element).prop('checked', "checked");
      $('#specification_existing_box').prop('checked', "");
      $('#specification_new_box').prop('checked', "");

      //hide other specifications
      $("#specification_existing_box").hide(); // hide existing_spec
      $("#specification_new_box").hide(); // hide new_spec

      // set existing specifications to default value
      //$('#specification_existing_box')[0].selectedIndex = 0;

      // set the required attribute from THIS input to true
      $('#specification_none_box').prop('required', true);
      // set the required attribute from the other inputs to false
      $('#specification_existing_box').prop('required', false);
      $('#specification_new_box').prop('required', false);
  }

  function specification_existing(element) {
    console.log('specification_existing')
      // change the checked attribute
      $(element).prop('checked', "checked");
      $('#specification_none_box').prop('checked', "");
      $('#specification_new_box').prop('checked', "");

      // show existing box
      $("#specification_existing_box").show(); // hide existing_spec

      //hide other specifications
      $("#specification_none_box").hide(); // hide existing_spec
      $("#specification_new_box").hide(); // hide new_spec

      // set the required attribute from THIS input to true
      $('#specification_existing_box').prop('required', true);
      // set the required attribute from the other inputs to false
      $('#specification_none_box').prop('required', false);
      $('#specification_new_box').prop('required', false);
  }

  function specification_new(element) {
    console.log('specification_new')

      // change the checked attribute
      $(element).prop('checked', "checked");
      $('#specification_existing_box').prop('checked', "");
      $('#specification_none_box').prop('checked', "");

      //hide other specifications
      $("#specification_existing_box").hide(); // hide existing_spec
      $("#specification_none_box").hide(); // hide new_spec

      // set existing specifications to default value
      //$('#specification_existing_box')[0].selectedIndex = 0;

      // set the required attribute from THIS input to true
      $('#specification_new_box').prop('required', true);
      // set the required attribute from the other inputs to false
      $('#specification_existing_box').prop('required', false);
      $('#specification_none_box').prop('required', false);
  }

  $('#radio_specification_new').click(specification_new)
  $('#radio_specification_existing').click(specification_existing)
  $('#radio_specification_none').click(specification_none)
})

Besonderheit:

                  <input type="radio" id="radio_specification_new" name="specification" class="custom-control-input">
                  neue erstellen

                  <input type="radio" id="radio_specification_existing" name="specification" class="custom-control-input" {% if clothing_info[0].clothes_specification_id !=1 %} checked="checked" {% else %} {% endif %}>
                  vorhandene

                  <input type="radio" id="radio_specification_none" name="specification" class="custom-control-input" {% if clothing_info[0].clothes_specification_id==1 %} checked="checked" {% else %} {% endif %}>
                  keine


text:
Q: What does the notation $\min_x$ mean? I have a problem in which I need to find $\min_x(f(x))$. What does this notation mean?

A: In the contexts I've seen, $\min_x(f(x))$ , means "the minimum of $f(x)$ over all $x$".

A: It means the minimum of the function $f$ when $x$ is varying over the domain of $f$.

A: $\min_{x\in A}f(x)$ it's just another way to write $\min\{f(x):x\in A\}$


text:
Q: Cannot set global variable in postman script When I log in to a Fortinet device via API, It returns a variable called fpc-sid.  This is their version of an authtoken.
When I attempt to put this on a global variable on the test section in the login request it returns the fpc-sid and then I get:
"ReferenceError: sid is not defined"

For some reason, I think it doesn't like the "-", but not sure.
How can I set fps-sid as a global variable?
var jsonData = JSON.parse(responseBody);
postman.setGlobalVariable("fpc-sid", jsonData.fpc-sid);

A: var jsonData = JSON.parse(responseBody);
postman.setGlobalVariable("fpc-sid", jsonData.fpc-sid);

Property cannot be accessed like that when it is not a valid identifier. use it by name as :
var jsonData = JSON.parse(responseBody);
postman.setGlobalVariable("fpc-sid", jsonData['fpc-sid']);

Read: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
Also use the pm object pm.globals.set() for setting variable as Danny mentioned. This is the new syntax, this will make it more future proof


text:
Q: onSaveInstanceState - WHEN can I be sure that it is called? I have an activity and I have a fragment stack in it and sometimes, this stack get's lost... Although I save and restore it...
I know following:

*

*onSaveInstanceState is not called:
a) if the user navigates back, which makes sense...
b) if the activity is finished

*onSaveInstanceState is called:
a) on screen rotation
I discovered through debugging, that I can't be sure, if onSaveInstanceState is called, if screen turns black...
My app is an app, that you use for logging, meaning, you put your phone aside and come back every now and then and fill out your log... So sometimes, my activity is recreated with an empty bundle and onSaveInstanceState was not called, although my app was in the foreground and only the screen turned off...
Questions
1) what can I do to solve that problem? Do I really have to save my fragment states and the stack persistantly?
2) on screen rotation, I can be SURE that onSaveInstanceState is called, can I? Are there any other circumstances, where I can rely on onSaveInstanceState?

A: 1) Im reffering to this thread: android life cycle you should use onPause() because you can't be sure if the app is just paused or beeing killed.

2) from developer.android.com ( Activity)

Be aware that these semantics will change slightly between
  applications targeting platforms starting with HONEYCOMB vs. those
  targeting prior platforms. Starting with Honeycomb, an application is
  not in the killable state until its onStop() has returned. This
  impacts when onSaveInstanceState(Bundle) may be called (it may be
  safely called after onPause() and allows and application to safely
  wait until onStop() to save persistent state.


text:
Q: For loop multiple items PHP I want to output the question number (vraag) with a for loop so it gets 5 elements from the database (from 1 to 5).
Then I want to get the answer from the user input (A/B/C/D)
Get the answer values from the database based on the question number with the user input value.
The problem is, it only outputs the first element and the rest of the output is empty.
Included is a picture of the database information.Database
for($i = 1; $i < 6; $i++){
            $vraag = $i;
            $answer = '$answer'.$i;
            $answerNumber = $_POST['question-'.$i.'-answers'];
            $query = $db->prepare("SELECT * FROM vraag WHERE vraagnummer = :VRAAG AND antwoord = :ANTWOORD");
            $query->bindparam(":VRAAG",$vraag);
            $query->bindparam(":ANTWOORD",$answerNumber);
            $query->execute();
            $has_author = $query->fetch();

            $VN = $has_author['vraagnummer'];
            $A = $has_author['antwoord'];
            $PA = $has_author['puntenA'];
            $PB = $has_author['puntenB'];
            $PC = $has_author['puntenC'];
            $PD = $has_author['puntenD'];
            echo $VN;
            echo $A;
            echo '
';
            echo '
';
            echo 'A'.$PA.'
';
            echo 'B'.$PB.'
';
            echo 'C'.$PC.'
';
            echo 'D'.$PD.'
';
        }

A: To display whole result of database you need to use a while loop as
while ($has_author = $query->fetch()) {
    $VN = $has_author['vraagnummer'];
    $A = $has_author['antwoord'];
    $PA = $has_author['puntenA'];
    $PB = $has_author['puntenB'];
    $PC = $has_author['puntenC'];
    $PD = $has_author['puntenD'];
    echo $VN;
    echo $A;
    echo '
';
    echo '
';
    echo 'A' . $PA . '
';
    echo 'B' . $PB . '
';
    echo 'C' . $PC . '
';
    echo 'D' . $PD . '
';
}


text:
Q: Parse HTML snippet with awk I am trying to parse an HTML document with awk.
The document contains several
</div blocks

    287,489 people

    5 links

I am using
awk  '/
/,/<\/div>/'
to receive all such div's.
How I can get 287,489 number from first one?
Actually awk  '/<\/span>/,/people/' doesn't work correctly.

A: With gawk, and assuming that the only digits and commas within each

 block occur in the numeric portion of interest
awk -v RS='<[/]?div[^>]*>' '/span/ && /people/{gsub(/[^[:digit:],]/, ""); print}' file.txt


text:
Q: C# datatable from sql join 2 columns same name I have a sql select like so which returns a datatable:
select * from table1 a join table2 b on a.id=b.id

Both table1 and table2 have a column named itemno .
How do i reference the 2 separate columns? Normally I would use something like:
datarow["itemno"].ToString(); <=first column named itemno only
datarow["b.itemno"].ToString(); <= fail

However this only seems to get the first column named itemno.
Is there a way to reference the second column named itemno without changing my sql statement? (I know i can change my sql statement, take out the * and put in column aliases).

A: You can reference the columns by index instead:
datarow[0].ToString();

I'd much prefer aliasing them though to be honest.

A: Given an SQL query like this
select a.id, b.id, a.columnA,a.columnB,a.itemno,b.itemno
from table1 a
join table2 b on a.id=b.id

Your C# code would/could look like this to read all rows and all columns:
using (SqlCommand getAllColumns = new SqlCommand("select a.id, b.id,a.columnA,a.columnB,a.itemno,b.itemno from table1 a join table2 b on a.id=b.id", conn))
                    {
                        using (var drreader = getAllColumns.ExecuteReader())
                        {
                            DataTable tb = new DataTable();
                            tb.BeginLoadData();
                            tb.Load(drreader);
                            tb.EndLoadData();
                            foreach(DataRow row in tb.Rows.Cast<DataRow>().ToList())
                            {
                                 // assuming these are all varchar columns
                                 string idA = (string)row["id"];
                                 string idB = (string)row["id1"];
                                 string columnA = (string)row["columnA"];
                                 string columnB = (string)row["columnB"];
                                 string columnAItemNo = (string)row["itemno"]; //fetches the first itemno column, a.itemno in this case
                                 string columnBItemNo = (string)row["itemno1"]; //fetches the second itemno column, b.itemno in this case

                            }
                        }
                    }

I use this on .NET Framework 4.5. If you want to verify or debug this, put a breakpoint on the foreach line and inspect the DataTable object. The second itemno column should be titled differently compared to the first one.


text:
Q: SELECT clause column causes index not being used I tried to index a table today and noticed something awkward and couldn't understand the reason (even if it seems so simple?). I have a table like this:
CREATE TABLE [X].[A](
    [TableName] [varchar](250) NOT NULL,
    [Header] [varchar](4000) NOT NULL,
    [Trailer] [varchar](4000) NOT NULL,
    [FileName] [varchar](50) NOT NULL,
    [StartDate] [date] NOT NULL,
    [EndDate] [date] NOT NULL
) ON [PRIMARY]

Let's assume that I have a query like this (I simplified it a bit):
SELECT
    Header
FROM
    X.A ht (NOLOCK)
WHERE
    ht.TableName = 'asd' AND
    '2017-05-29' BETWEEN ht.StartDate AND ht.EndDate

I wanted to put an index to (TableName, StartDate, EndDate) since they are in the where clause. My index is below:
CREATE NONCLUSTERED INDEX [NonClusteredIndex-20170530-113847] ON [X].[A]
(
    [TableName] ASC,
    [StartDate] ASC,
    [EndDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
GO

But I noticed that my query was not using the index and it does a Table Scan, but when I change the SELECT clause like the following:
SELECT
    TableName
FROM
    X.A ht (NOLOCK)
WHERE
    ht.TableName = 'asd' AND
    '2017-05-29' BETWEEN ht.StartDate AND ht.EndDate

It does use my index and does Index Seek which is what I want. What's going on?

A: In a really simplified example, if your table had data like this:
ID | TableName | Header | Trailer | FileName | StartDate  | EndDate
---+-----------+--------+---------+----------+------------+------------
 1 |    asd    |   H1   |    T1   |    F1    | 2017-05-28 | 2017-05-30
 2 |    asd    |   H2   |    T2   |    F2    | 2017-05-28 | 2017-05-30
 3 |    asd    |   H3   |    T3   |    F3    | 2017-05-28 | 2017-05-30
 4 |    asd    |   H4   |    T4   |    F4    | 2017-05-28 | 2017-05-30
 5 |    asd    |   H5   |    T5   |    F5    | 2017-05-28 | 2017-05-30
 6 |    asd    |   H6   |    T6   |    F6    | 2017-05-28 | 2017-05-30
 7 |    asd    |   H7   |    T7   |    F7    | 2017-05-28 | 2017-05-30
 8 |    xyz    |   H1   |    T1   |    F1    | 2017-05-28 | 2017-05-30

Then your index would look something like this
TableName | StartDate  | EndDate    | ID |
----------+------------+------------+----+-
   asd    | 2017-05-28 | 2017-05-30 |  1 |
   asd    | 2017-05-28 | 2017-05-30 |  2 |
   asd    | 2017-05-28 | 2017-05-30 |  3 |
   asd    | 2017-05-28 | 2017-05-30 |  4 |
   asd    | 2017-05-28 | 2017-05-30 |  5 |
   asd    | 2017-05-28 | 2017-05-30 |  6 |
   asd    | 2017-05-28 | 2017-05-30 |  7 |
   xyz    | 2017-05-28 | 2017-05-30 |  8 |

In this case you can get back all the columns required for this query:
SELECT
    TableName
FROM
    X.A ht (NOLOCK)
WHERE
    ht.TableName = 'asd' AND
    '2017-05-29' BETWEEN ht.StartDate AND ht.EndDate

But, if you want to select Header then you can't just use the index (since Header) is not stored in the index, for each row you have to find the clustering key (which in this simple example is ID), then lookup the corresponding row in the main table to get the value of Header. This (Index Seek + Key Lookup) is an expensive operation, and since you have to do this for 9 rows, and the original table only includes 10, it is probably more efficient to simple search the main table in the first place and not use the index (Clustered Index Scan).
Had you been looking up a very small number of records, like xyd, then it is likely that an index seek along with key lookup would have been chosen. I don't think there is a simple cut off for how many records are needed to switch between the two methods, but in an answer to another question I found a cut off value of 3.7% of records, on a fairly small table. I expect as the table size increases this percentage decreases.

A: Your index covers the columns you are filtering on, but not the columns that you want to return.  This means that the query still has to scan the table to get the RowID of the rows that match your filtering in order to return your Header value.
If you add an include to your index that covers the Header column you should get the seek you are after:
create nonclustered index [NonClusteredIndex-20170530-113847]
on [X].[A]([TableName] asc,[StartDate] asc,[EndDate] asc)
include([Header])
with (pad_index = off,statistics_norecompute = off,sort_in_tempdb = off,drop_existing = off,online = off,allow_row_locks = on,allow_page_locks = on)