text:
Q: Print the name of selected item from dropdownlist to a label What can I do to make my selections appear on the label instantly?  I know the combobox but I couldn't figure out how dropdownlist works. I tried this:
protected void Page_Load(object sender, EventArgs e)
    {
        var items = new List<string> { "111", "222", "333" };
        ddChoose.DataSource = items;
        ddChoose.DataBind();
    }

 protected void ddChoose_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddChoose.SelectedIndex == 0)
        {
            lbl1.Text = "111";
        }
        if (ddChoose.SelectedIndex == 1)
        {
            lbl1.Text = "222";
        }
    }

A: Basically dropdown was bind again on each postback event . Change load event code in this way to prevent re-binding to dropdown:
if (!IsPostBack)
{
            var items = new List<string> { "111", "222", "333" };
            DropDownList1.DataSource = items;
            DropDownList1.DataBind();
}

Make sure AutoPostBack property of dropdown is set to True.

A: Default.aspx
<form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="ddChoose" AutoPostBack="true" runat="server" OnSelectedIndexChanged="ddChoose_OnSelectedIndexChanged"></asp:DropDownList>
        <asp:Label ID="lbl1" runat="server" Text="Label"></asp:Label>
    </div>
</form>

Default.aspx.cs
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            var items = new List<string> { "111", "222", "333" };
            ddChoose.DataSource = items;
            ddChoose.DataBind();
        }
    }

    protected void ddChoose_OnSelectedIndexChanged(object sender, EventArgs e)
    {
        lbl1.Text = ddChoose.Text;
    }


text:
Q: Set android widget visibility dynamycally Okay i have one EditText and one spinner.
My goal is if item 1 on spinner selected the EditText visibility is true, and if item 2 selected EditText visibility is false. what the code for reach that goal ?
i use spiner get selected id like this :
String tipe = spiner.getSelectedItem().toString();
if (tipe=="item2"){
//edittext.visible = false; <-- i don't know how to make/what code this visibility become false
}

A: Use the below
if (tipe.equals("item2")){ // .equals to compare strings
   edittext.setVisibiluty(View.INVISIBLE); //set the visibility
}

Use the below according to your needs
visible   0  Visible on screen; the default value.
invisible 1  Not displayed, but taken into account during layout (space is left for it).
gone      2  Completely hidden, as if the view had not been added.

http://developer.android.com/reference/android/view/View.html#setVisibility(int)

A: use equals() method for comparing of Two String. It will check the content of the String
String tipe = spiner.getSelectedItem().toString();
if (tipe.equals("item2")){
// do what u want here
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: GetConsumingEnumerable() blocks after completing of adding I have async processing of some collection with id's. Simplified code below
Task.Factory
        .StartNew(() => {
            foreach (long id in ids.GetConsumingEnumerable())
            {
              //processing code here
            }
        });

And another thread that calls CompleteAdding on ids after certain condition. But worker thread remains blocked after that. To be precise, worker thread blocks on in operator of foreach statement.
How could i resolve that? Any help appreciated.

A: Try this
var local = ids.GetConsumingEnumerable();
Task.Factory
        .StartNew(() => {
            foreach (long id in local)
            {
              //processing code here
            }
        });


text:
Q: how to have a property list of dictionaries and how to append dictionary to that ? (Objective C) How can i have a property list of dictionaries, and how can I append a new dictionary to the property list?

A: Property list is a storage format for data -- plists aren't directly useful, but requires that you read them into data structures that you can use like NSArray and NSDictionary. A simple way to read a property list into mutable containers is to use NSPropertyListSerialization's +propertyListFromData:mutabilityOption:format:errorDescription: and specify NSPropertyListMutableContainers for the mutability option.
Also, there's an entire manual devoted to property lists.


text:
Q: Script does not working for loaded element I created a form with checkbox + wrapper, i.e :
<form>

      <input type="checkbox" name="item[]" value="1">
  </dv>

      <input type="checkbox" name="item[]" value="2">

      <input type="checkbox" name="item[]" value="3">

</form>

and this toggle check is working:
$(".input-wrapper").on("click", function () {
       var $checkbox = $(this).find(':checkbox');
       $checkbox.prop('checked', !$checkbox[0].checked);
 });

But when I load other checkbox from ajax, i.e:
$.post(
     '/my/url',
     {...my data...},
      function(data){
           if(data != 'failed'){
               //return new checkbox + wrapper too and append it at the end of the form
                $('form').append(data);
           }
      }
 );

the Toggle check is not working just for the loaded/appended element.
How to fix this ? how to properly create a script that affect all the element even for the loaded one ?
thanks.

A: The way you're binding the click listener will bind to all .input-wrapper elements currently  in the DOM.
You may either bind the new ones for clicks separately, or delegate the listener to a parent object that will stay in the DOM (e.g. $(document).on("click", ".input-wrapper", function (){//Do Stuff});)

A: Try this slight modification:
$("form").on("click", ".input-wrapper", function () {
    var $checkbox = $(this).find(':checkbox');
    $checkbox.prop('checked', !$checkbox[0].checked);
});

and let me know how it goes.


text:
Q: Wifi not working after today's (14 July 16) update Today I had an Ubuntu update. After I restarted, I noticed the wifi no longer works.
In System Settings -> Software & Updates -> Additional Drivers, I noticed that under the Broadcom wireless network adapter, it says "This device is not working." So I tried
sudo apt-get purge bcmwl-kernel-source

Then when I try
sudo apt-get install bcmwl-kernel-source

I get the following
WARNING: The following packages cannot be authenticated!
  bcmwl-kernel-source
Install these packages without verification? [y/N] y
Err http://ppa.launchpad.net/inaddy/lp1415880/ubuntu/ vivid/main bcmwl-kernel-source amd64 6.30.223.248+bdcom-0ubuntu3~lp1415880~1
  404  Not Found
E: Failed to fetch http://ppa.launchpad.net/inaddy/lp1415880/ubuntu/pool/main/b/bcmwl/bcmwl-kernel-source_6.30.223.248+bdcom-0ubuntu3~lp1415880~1_amd64.deb  404  Not Found

E: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?

So then I try sudo apt-get update, which gives
$ sudo apt-get update
Ign http://dl.google.com stable InRelease
Hit http://archive.scrapy.org scrapy InRelease
Hit http://dl.google.com stable Release.gpg
Hit http://us.archive.ubuntu.com vivid InRelease
Hit http://security.ubuntu.com vivid-security InRelease
Hit http://dl.google.com stable Release
Hit http://us.archive.ubuntu.com vivid-updates InRelease
Ign http://linux.dropbox.com vivid InRelease
Hit http://us.archive.ubuntu.com vivid-backports InRelease
Hit http://dl.google.com stable/main amd64 Packages
Hit http://ppa.launchpad.net vivid InRelease
Hit http://linux.dropbox.com vivid Release.gpg
Ign http://ppa.launchpad.net vivid InRelease
Hit http://linux.dropbox.com vivid Release
Get:1 http://linux.dropbox.com vivid/main amd64 Packages [1,148 B]
Hit http://ppa.launchpad.net vivid InRelease
Get:2 http://linux.dropbox.com vivid/main i386 Packages [1,148 B]
Hit http://archive.scrapy.org scrapy/main amd64 Packages
Hit http://archive.scrapy.org scrapy/main i386 Packages
Ign http://archive.scrapy.org scrapy/main Translation-en_US
Ign http://archive.scrapy.org scrapy/main Translation-en
Hit http://security.ubuntu.com vivid-security/main Sources
Hit http://security.ubuntu.com vivid-security/restricted Sources
Ign http://ppa.launchpad.net vivid Release.gpg
Hit http://security.ubuntu.com vivid-security/universe Sources
Hit http://security.ubuntu.com vivid-security/multiverse Sources
Hit http://security.ubuntu.com vivid-security/main amd64 Packages
Hit http://ppa.launchpad.net vivid/main amd64 Packages
Hit http://security.ubuntu.com vivid-security/restricted amd64 Packages
Hit http://security.ubuntu.com vivid-security/universe amd64 Packages
Hit http://security.ubuntu.com vivid-security/multiverse amd64 Packages
Hit http://ppa.launchpad.net vivid/main i386 Packages
Hit http://security.ubuntu.com vivid-security/main i386 Packages
Hit http://security.ubuntu.com vivid-security/restricted i386 Packages
Hit http://security.ubuntu.com vivid-security/universe i386 Packages
Hit http://ppa.launchpad.net vivid/main Translation-en
Hit http://security.ubuntu.com vivid-security/multiverse i386 Packages
Hit http://security.ubuntu.com vivid-security/main Translation-en
Hit http://security.ubuntu.com vivid-security/multiverse Translation-en
Hit http://ppa.launchpad.net vivid/main amd64 Packages
Hit http://security.ubuntu.com vivid-security/restricted Translation-en
Hit http://security.ubuntu.com vivid-security/universe Translation-en
Hit http://ppa.launchpad.net vivid/main i386 Packages
Ign http://dl.google.com stable/main Translation-en_US
Ign http://dl.google.com stable/main Translation-en
Hit http://ppa.launchpad.net vivid/main Translation-en
Hit http://us.archive.ubuntu.com vivid-backports/restricted Sources
Hit http://us.archive.ubuntu.com vivid-backports/multiverse Sources
Ign http://ppa.launchpad.net vivid Release
Hit http://us.archive.ubuntu.com vivid-backports/restricted amd64 Packages
Ign http://ppa.launchpad.net vivid/main amd64 Packages/DiffIndex
Hit http://us.archive.ubuntu.com vivid-backports/multiverse amd64 Packages
Hit http://us.archive.ubuntu.com vivid-backports/restricted i386 Packages
Ign http://ppa.launchpad.net vivid/main i386 Packages/DiffIndex
Hit http://us.archive.ubuntu.com vivid-backports/multiverse i386 Packages
Hit http://us.archive.ubuntu.com vivid-backports/multiverse Translation-en
Hit http://us.archive.ubuntu.com vivid-backports/restricted Translation-en
Hit http://us.archive.ubuntu.com vivid/main Sources
Hit http://us.archive.ubuntu.com vivid/restricted Sources
Hit http://us.archive.ubuntu.com vivid/universe Sources
Hit http://us.archive.ubuntu.com vivid/multiverse Sources
Hit http://us.archive.ubuntu.com vivid/main amd64 Packages
Hit http://us.archive.ubuntu.com vivid/restricted amd64 Packages
Hit http://us.archive.ubuntu.com vivid/universe amd64 Packages
Hit http://us.archive.ubuntu.com vivid/multiverse amd64 Packages
Hit http://us.archive.ubuntu.com vivid/main i386 Packages
Hit http://us.archive.ubuntu.com vivid/restricted i386 Packages
Hit http://us.archive.ubuntu.com vivid/universe i386 Packages
Hit http://us.archive.ubuntu.com vivid/multiverse i386 Packages
Hit http://us.archive.ubuntu.com vivid/main Translation-en
Ign http://linux.dropbox.com vivid/main Translation-en_US
Hit http://us.archive.ubuntu.com vivid/multiverse Translation-en
Hit http://us.archive.ubuntu.com vivid/restricted Translation-en
Hit http://us.archive.ubuntu.com vivid/universe Translation-en
Hit http://us.archive.ubuntu.com vivid-updates/main Sources
Hit http://us.archive.ubuntu.com vivid-updates/restricted Sources
Ign http://linux.dropbox.com vivid/main Translation-en
Hit http://us.archive.ubuntu.com vivid-updates/universe Sources
Hit http://us.archive.ubuntu.com vivid-updates/multiverse Sources
Hit http://us.archive.ubuntu.com vivid-updates/main amd64 Packages
Hit http://us.archive.ubuntu.com vivid-updates/restricted amd64 Packages
Hit http://us.archive.ubuntu.com vivid-updates/universe amd64 Packages
Hit http://us.archive.ubuntu.com vivid-updates/multiverse amd64 Packages
Hit http://us.archive.ubuntu.com vivid-updates/main i386 Packages
Hit http://us.archive.ubuntu.com vivid-updates/restricted i386 Packages
Hit http://us.archive.ubuntu.com vivid-updates/universe i386 Packages
Hit http://us.archive.ubuntu.com vivid-updates/multiverse i386 Packages
Hit http://us.archive.ubuntu.com vivid-updates/main Translation-en
Hit http://us.archive.ubuntu.com vivid-updates/multiverse Translation-en
Hit http://us.archive.ubuntu.com vivid-updates/restricted Translation-en
Hit http://us.archive.ubuntu.com vivid-updates/universe Translation-en
Hit http://us.archive.ubuntu.com vivid-backports/main Sources
Hit http://us.archive.ubuntu.com vivid-backports/universe Sources
Hit http://us.archive.ubuntu.com vivid-backports/main amd64 Packages
Hit http://us.archive.ubuntu.com vivid-backports/universe amd64 Packages
Hit http://us.archive.ubuntu.com vivid-backports/main i386 Packages
Hit http://us.archive.ubuntu.com vivid-backports/universe i386 Packages
Hit http://us.archive.ubuntu.com vivid-backports/main Translation-en
Hit http://us.archive.ubuntu.com vivid-backports/universe Translation-en
Ign http://ppa.launchpad.net vivid/main Translation-en_US
Ign http://ppa.launchpad.net vivid/main Translation-en
Err http://ppa.launchpad.net vivid/main amd64 Packages
  404  Not Found
Err http://ppa.launchpad.net vivid/main i386 Packages
  404  Not Found
Fetched 2,296 B in 4s (552 B/s)
W: Failed to fetch http://ppa.launchpad.net/inaddy/lp1415880/ubuntu/dists/vivid/main/binary-amd64/Packages  404  Not Found

W: Failed to fetch http://ppa.launchpad.net/inaddy/lp1415880/ubuntu/dists/vivid/main/binary-i386/Packages  404  Not Found

E: Some index files failed to download. They have been ignored, or old ones used instead.

Does anyone know what might be wrong?


text:
Q: Why is the x-axis labeling irregular in the plot.zph function? I am using the survival package in R to run cox proportional hazards models. My question is about the plot.zph function.
This code
plot(zph[1], lwd = 2) +
  abline(0, 0, col = 1, lty = 3, lwd = 2) +
  abline(
    h = cox.ph.mod$coef[1],
    col = 3,
    lwd = 2,
    lty = 2
)

produces this plot:

My question is just about the irregular spacing of the x-axis. The tick marks are not evenly spaced, the labeling is irregular, and the distance between tick marks seems off. For example the space between 32 and 35 appears larger than the space between 35 and 39. This doesn't seem to be just a me problem; the plots in this tutorial seem to have the same issue: http://www.sthda.com/english/wiki/cox-model-assumptions
I'm assuming this does not severely impact the interpretation of the plot, but I am curious a) why this is happening, b) if it's a problem or if it's by design, and c) if it impacts interpretation in any way.
Thanks!

A: This is by design. The transform argument to cox.zph() allows different transformations of the time axis. This is discussed in Chapter 6 of Therneau and Grambsch.
The default Kaplan-Meier ("km") choice transforms time to correspond to probabilities of survival.* You can choose instead to space evenly by observation times ("rank"), use the original time scale ("identity"), its log transformation ("log"), or any specific transformation you wish.
The Kaplan-Meier transformation is the default because it's less sensitive to censoring patterns than the rank transformation and it tends to spread residuals (calculated at event times) more evenly across the plot from left to right. For example, in a frequent situation with just a few individuals having events at late times, with an "identity" transformation you would have a lot of events bunched together at early times and events at very late times would visually overwhelm the display of the smoothed curve.
The transformations can affect the p-values returned by the test, as the test is effectively for a trend in scaled Schoenfeld residuals with respect to the transformed time axis. Therneau and Grambsch show how different choices for time transformation correspond to different tests that have been proposed for proportional hazards.

*"Consider a plot of t versus (1 - KM(t-)), and replace each time point by its vertical position on the plot." Page 136, Therneau and Grambsch.


text:
Q: web.xml error-pages are not working, why? I'm running out of ideas by now, and don't know what else to try. The point is not even one error-page is working, I just would like to know, what am I doing wrong?, here is the code:
<error-page>
    <exception-type>javax.faces.application.ViewExpiredException</exception-type>
    <location>/sessionexpired.xhtml</location>
</error-page>
<error-page>
    <error-code>500</error-code>
    <location>/500.xhtml</location>
</error-page>

When having this code in my web.xml I get this message:

XML read error: no element found

What this message means? how can I solve this? Thanks.
BTW, I have also tried to use filters to handle the ViewExpiredException, then it works the first time when I send the POST message and redirects to the sessionexpired.xhtml. But if I click backward and then make the POST call again BAM! I get again the ViewExpiredException.
UPDATE 30-NOV-2011 --[ALTERNATE SOLUTION]-------------------------------------
After a while I found that in order to make it work you have to specify the loation to .html or .jsp files, so it would end up being:
<error-page>
    <exception-type>javax.faces.application.ViewExpiredException</exception-type>
    <location>/sessionexpired.html</location>
</error-page>
<error-page>
    <error-code>500</error-code>
    <location>/500.jsp</location>
</error-page>

A: Well, for those that are strugling with this issue using Glassfish 3.1, you can handle that problem by following this article to the letter, even thought I changed at the end to use sendRedirect() instead of the JSF navigator to render the sessionexpired.xhtml file, but that's your choice, it works fine. Here you go:
http://weblogs.java.net/blog/edburns/archive/2009/09/03/dealing-gracefully-viewexpiredexception-jsf2

A:
When having this code in my web.xml I get this message:
 XML read error: no element found

As per the comments it turns out that you're seeing this in the browser instead of the expected error page. I initially interpreted it being mentiond by your IDE/editor due to a syntax error in web.xml. Your question wasn't entirely clear on that.
Well, the solution to that is easy: make sure that the <location> of the <error-page> matches the URL pattern of the FacesServlet. Easiest would be to just map the FacesServlet on an URL pattern of *.xhtml.

BTW, I have also tried to use filters to handle the ViewExpiredException, then it works the first time when I send the POST message and redirects to the sessionexpired.xhtml. But if I click backward and then make the POST call again BAM! I get again the ViewExpiredException.

This is just caused by the page being requested from the browser cache instead of straight from the server. See also this answer for a concrete solution: browser back + viewscope beans.

A: After you change the web.xml, have you do the ear or war redeployment?
Some of the application server might cache the old copy of web.xml if you directly go to server to modify the file.
Hopefully it can work.  :)


text:
Q: How do you input multiple SELECT outputs into a FROM clause in MySQL? I want to do something similar to the following in MySQL, but every permutation I try gives me errors.
SELECT five,six FROM (SELECT 5 AS five),(SELECT 6 AS six);

I was under the impression that SELECT's output table's, so that I could use SELECT whereever I could insert a table.
Can someone explain the subtleties of the structre of MySQL that prevents this statement from working as well as providing me a solution that does?
I know that it's got to be simple, but I haven't been able to find an answer to this anywhere.

A: Try adding aliases:

SELECT five, six FROM (SELECT 5 AS five) AS a, ( SELECT 6 AS six) AS b

A: I don't know what you're trying to accomplish but this works
select five,six from (select 5 as five, 6 as six) as t;

It's obvious useless cause it's the same of
select 5 as five, 6 as six

but I hope that it helps you.


text:
Q: How to write a unit test for datetime functions I have the following function below that returns the time as 00:00:00.
How can I write a unit test to verify this works?
def get_date() -> datetime:
    return datetime.combine(datetime.today(), datetime.min.time())
print(get_date())

A: You can do two things here:

*

*Convert the datetime object to a string and assert against it:
assertEqual("00:00:00", get_date().time().isoformat())

and If you want to assert against date:
assertEqual(datetime.today().strftime('%Y-%m-%d'), get_date().date().isoformat())

*Directly assert datetime objects:
assertEqual(datetime.min.time(), get_date().time())
assertEqual(datetime.today().date(), get_date().date())


text:
Q: Efficient Subtotaling of columns in a pandas dataframe I've been toying around with an idea for a program at work that automates our end of the month reports. Currently, it creates all the reports for us in Excel format and then we manually use Excel's subtotal feature to subtotal its columns and format the data into a table.
My idea is to subtotal each of the columns by customer, like so:

Patient
Date
Rx#
Description
Qty
Price

EXAMPLE, JOHN
2/1/2021
357649
Aspirin
30
6.99

EXAMPLE, JOHN
2/1/2021
357650
Drug
30
13.99

EXAMPLE, JOHN
2/1/2021
357651
Tylenol
30
7.99

EXAMPLE, JOHN Subtotal

28.97

EXAMPLE, SUSAN
2/12/2021
357652
Expensive Drug
30
51.99

EXAMPLE, SUSAN
2/12/2021
357653
Drug
30
13.99

EXAMPLE, SUSAN
2/12/2021
357654
Tylenol
30
7.99

EXAMPLE, SUSAN Subtotal

73.97

With the exisiting dataframe looking like:

Patient
Date
Rx#
Description
Qty
Price

EXAMPLE, JOHN
2/1/2021
357649
Aspirin
30
6.99

EXAMPLE, JOHN
2/1/2021
357650
Drug
30
13.99

EXAMPLE, JOHN
2/1/2021
357651
Tylenol
30
7.99

EXAMPLE, SUSAN
2/12/2021
357652
Expensive Drug
30
51.99

EXAMPLE, SUSAN
2/12/2021
357653
Drug
30
13.99

EXAMPLE, SUSAN
2/12/2021
357654
Tylenol
30
7.99

Is this possible with groupby()? It seems to have an option to group by rows rather than columns. The bigger issue I see is inserting into the existing dataframe, as it seems that pandas is more designed for manipulating/performing operations on large datasets rather than inserting/adding information.

A: # Calculate sums
df_subtotal = df.groupby('Patient', as_index=False)[['Price']].agg('sum')
# Manipulate string Patient
df_subtotal['Patient'] = df_subtotal['Patient'] + ' subtotal'
# Join dataframes
df_new = pd.concat([df, df_subtotal], axis=0, ignore_index=True)
# Sort
df_new = df_new.sort_values(['Patient', 'Date'])


text:
Q: Django: Uploaded file locked. Can't rename I'm trying to rename a file after it's uploaded in the model's save method. I'm renaming the file to a combination the files primary key and a slug of the file title.
I have it working when a file is first uploaded, when a new file is uploaded, and when there are no changes to the file or file title.
However, when the title of the file is changed, and the system tries to rename the old file to the new path I get the following error:
WindowsError at /admin/main/file/1/
(32, 'The process cannot access the file because it is being used by another process')

I don't really know how to get around this. I've tried just coping the file to the new path. This works, but I don't know I can delete the old version.
Shortened Model:
class File(models.Model):
    nzb = models.FileField(upload_to='files/')
    name = models.CharField(max_length=256)
    name_slug = models.CharField(max_length=256, blank=True, null=True, editable=False)

    def save(self):
        # Create the name slug.
        self.name_slug = re.sub('[^a-zA-Z0-9]', '-', self.name).strip('-').lower()
        self.name_slug = re.sub('[-]+', '-', self.name_slug)

        # Need the primary key for naming the file.
        super(File, self).save()

        # Create the system paths we need.
        orignal_nzb = u'%(1)s%(2)s' % {'1': settings.MEDIA_ROOT, '2': self.nzb}
        renamed_nzb = u'%(1)sfiles/%(2)s_%(3)s.nzb' % {'1': settings.MEDIA_ROOT, '2': self.pk, '3': self.name_slug}

        # Rename the file.
        if orignal_nzb not in renamed_nzb:
            if os.path.isfile(renamed_nzb):
                os.remove(renamed_nzb)

            # Fails when name is updated.
            os.rename(orignal_nzb, renamed_nzb)

        self.nzb = 'files/%(1)s_%(2)s.nzb' % {'1': self.pk, '2': self.name_slug}

        super(File, self).save()

I suppose the question is, does anyone know how I can rename an uploaded file when the uploaded file isn't be re-uploaded? That's the only time it appears to be locked/in-use.

Update:
Tyler's approach is working, except when a new file is uploaded the primary key is not available and his technique below is throwing an error.
if not instance.pk:
    instance.save()

Error:
maximum recursion depth exceeded while calling a Python object

Is there any way to grab the primary key?

A: I think you should look more closely at the upload_to field.  This would probably be simpler than messing around with renaming during save.
http://docs.djangoproject.com/en/dev/ref/models/fields/#filefield

This may also be a callable, such as a
  function, which will be called to
  obtain the upload path, including the
  filename. This callable must be able
  to accept two arguments, and return a
  Unix-style path (with forward slashes)
  to be passed along to the storage
  system. The two arguments that will be
  passed are:

A: My other answer is deprecated, use this instead:
class File(models.Model):
    nzb = models.FileField(upload_to=get_filename)
    ...
    def get_filename(instance, filename):
        if not instance.pk:
            instance.save()
        # Create the name slug.
        name_slug = re.sub('[^a-zA-Z0-9]', '-', instance.name).strip('-').lower()
        name_slug = re.sub('[-]+', '-', name_slug)

        filename = u'filess/%(2)s_%(3)s.nzb' % {'2': instance.pk, '3': name_slug}

        return filename

As of 1.0, upload_to can be callable, in which case it is expected to return the filename, including path (relative to MEDIA_ROOT).

A: Once uploaded, all you have is an image object in memory, right?
You could save this object yourself in the folder of your choice, and then edit the database entry by hand.
You'd be bypassing the whole Django ORM, and is not something I'd do unlessI couldn't find a more Django way.


text:
Q: Which programming design pattern would suit this project? Hello I'm looking for some guidance in choosing a programming design pattern to fit my current project.
I'm been trying for months to find a nice project to start using patterns properly and a little project I've just started seems to provide the perfect platform to learn from.
Basically I'm creating a Telegram Bot that will respond to users commands. That's not the part I'm having problems with, it's how best to structure my code so that adding new commands is clean and well structured.
I don't need anyone to write any code for me, but is there a design pattern I could implement that would suit?
Here's what I'm currently doing in puesudo (BTW I'm using Laravel) code:
//routes.php

  Route::post('inbound', ['uses' => 'inboundController@marshall']);

 //inboundController.php

   public function marshall($inboundMessage){

    //Extract the command from the inbound message eg "start"
    $command = extractfromtext($text);

    //Get the user id from the person who sent the message
    $userID = extractIdfromtext($text);

    //Compare the command in a switch statement

    switch ($command){

    case (start):
        return $result = new commandStart($userID)->fire();
        break;
    case (demo):
        return $result = new commandDemo($userID)->fire();
        break;
    case (another):
        return $result = new commandAnother($userID)->fire();
        break;
    default:
       break;

    }

   }

//Each command has it's own class:
//Class commandStart

   public function __construct($userID){
       $this->userID = $userID
   }

   publin fuction fire(){

     //send a picture to the userID

   }

//Class commandDemo

   public function __construct($userID){
       $this->userID = $userID
   }

   publin fuction fire(){

     //send a message to the userID

   }

//Class commandAnother

   public function __construct($userID){
       $this->userID = $userID
   }

   publin fuction fire(){

     //send a video to the userID

   }

This works fine, but I feel that

*

*I'm repeating a lot of code (bad)

*Adding new commands means editing the "inbound class" file continuously. I think this breaks the open closed principle in SOLID.

*The switch statement has a "code smell" to me.

I get very confused by all the names of the different type of patterns. Would someone advise me, which one would suit this scenario? I'm very happy to go and research  about it and how it's implemented, but I don't want to go off on a goose chase and pick an unsuitable one because I don't know any better!
Thank you.

Edit: It seems in my attempt to make the problem generic I made it too obtuse. I am already using MVC with Larvel. That is not the problem I think - I would like to know which design pattern would allow me to add more commands easily and cleanly - hopefully not having to use a switch statement.
After reading some of the replies, I think I'm starting to get the idea of what to do. Out of interest - is the structure suggested below an actual design pattern or just good structured code?

A: on top of what arkascha sad I would also recommend you to use an abstract class for your commands
abstract class Command {

    public function __construct( $params ){
        // do some common things with $params
        $this->do_command();
    }

    protected function do_command(){
         // empty function which will be overwritten by child classes
    }

}

and your child classes would be like
class FooCommand extends Command {

    public function __construct( $params ){
        parent::__construct( $params );
        // do something as well
    }

    // can be public
    public function do_command(){
         echo __CLASS__, '::FOO';
    }
}

class BarCommand extends Command {

    // or without __constructor as mentioned by scrowler if you dont
    // need to do additional coding with __contructor params

    // can be protected
    protected function do_command(){
         echo __CLASS__, '::BAR';
    }
}

class BazCommand extends Command {

    public function __construct( $params ){
        parent::__construct( $params );
        // do something as well
    }

    // it cannot be private
    private function do_command(){
         echo __CLASS__, '::BAZ';
    }
}

A: Please take a look at the Command design pattern. You could also use a Abstract Factory Pattern as previously suggested to instantiate the command to be executed.
To elaborate a little more on my answer.
Lets call the inbound controller our client class. The responsability of a controller is to capture a request and route it to the proper action, in this case fire a command.
But if you take a look at the code, the controller is actually deciding what type of command to instantiate base in some input that it's receiving. If for some reason the constructor of the command class changes, then you'll also have to change the code in your inbound controller class, as it is now also responsible from instantiating the command object to be executed.
If you implement a Abstract Factory and injected to your controller, then you pass the input necessary to your factory to decide which command should be instantiated and handed to the controller. The controller just fires the command that it receives from the factory, without having to worry how the command was instantiated or what type of command it is. The controller gets a request to execute a command, delegates instantiation of the command to the factory, and once the command is handed to the controller by the factory, it is executed.
Single responsibility principle at it's best. The abstract factory is responsible of instantiating the commands. The controller is responsible of handling the request, in this case, executing the command returned by the factory.
By taking a look at the code one can already see he is using somehow the Command design pattern. Here is a definition from wikipedia: Command design pattern

A: What you implement in your code is a MVC router. Currently you hard code routes. Instead you can also rely on autoloading to pick the right class for your controller instantiation. A fallback if the class does not exist will make things robust. Two advantages:

*

*easy to extend, you only have to add the controller class in a file named by naming conventions

*you do not have to touch the router at all when you add another controller
You will find many examples about that on the internet. The autoloading feature also is well documented.
Have fun!


text:
Q: MongoDB error message I am trying to run MongoDB in my terminal, and it gives me this message:

MongoDB shell version: 3.2.10
  connecting to: test
  2016-10-10T17:22:31.427+0100 E QUERY    [thread1] SyntaxError: missing ) after argument list @/Users//.mongorc.js:5:30
The ".mongorc.js" file located in your home folder could not be executed"

How can I fix this?

A: There's a syntax error in you .mongorc.js file. This file is executed before starting mongo shell, and generally used for customizing the shell, using aliases, etc.
Do the following, open ~/.mongorc.js file, check for any syntax error and correct it.
You can also omit running .mongorc.js file by adding --norc flag: mongo --norc.
edit: I leave a link for more info about mongorc.js, here.


text:
Q: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2 "No such file or directory") CentOS I am unable to start mysql after a lot of attempt. We are using MariaDB.
I am getting "ERROR! MySQL server PID file could not be found!" When i am trying to restart.
Following is the output after entering mysqld command

160918  4:15:32 [Warning] Can't create test file
  /var/lib/mysql/my-domain.lower-test
160918  4:15:32 [Note] InnoDB: Using mutexes to ref count buffer pool
  pages
160918  4:15:32 [Note] InnoDB: The InnoDB memory heap is disabled
160918  4:15:32 [Note] InnoDB: Mutexes and rw_locks use GCC atomic
  builtins
160918  4:15:32 [Note] InnoDB: Memory barrier is not used
160918  4:15:32 [Note] InnoDB: Compressed tables use zlib 1.2.3
160918  4:15:32 [Note] InnoDB: Using Linux native AIO
160918  4:15:32 [Note] InnoDB: Using CPU crc32 instructions
160918  4:15:32 [Note] InnoDB: Initializing buffer pool, size = 128.0M
160918  4:15:32 [Note] InnoDB: Completed initialization of buffer pool
160918  4:15:32 [ERROR] InnoDB: ./ibdata1 can't be opened in
  read-write mode
160918  4:15:32 [ERROR] InnoDB: The system tablespace must be
  writable!
160918  4:15:32 [ERROR] Plugin 'InnoDB' init function returned error.
160918  4:15:32 [ERROR] Plugin 'InnoDB' registration as a STORAGE
  ENGINE failed.
160918  4:15:32 [ERROR] mysqld: File '/var/lib/mysql/aria_log_control'
  not found (Errcode: 13 "Permission denied")
160918  4:15:32 [ERROR] mysqld: Got error 'Can't open file' when
  trying to use aria control file '/var/lib/mysql/aria_log_control'
160918  4:15:32 [ERROR] Plugin 'Aria' init function returned error.
160918  4:15:32 [ERROR] Plugin 'Aria' registration as a STORAGE ENGINE
  failed.
160918  4:15:32 [Note] Plugin 'FEEDBACK' is disabled.
160918  4:15:32 [ERROR] Can't open the mysql.plugin table. Please run
  mysql_upgrade to create it.
160918  4:15:32 [ERROR] Unknown/unsupported storage engine: InnoDB
160918  4:15:32 [ERROR] Aborting
160918  4:15:32 [Note] mysqld: Shutdown complete

What could be possible going wrong ?


text:
Q: UIScrollView and CATiledLayer I am using a CATiledLayer as content of UIScrollView, but seems I can not get the correct (sometimes) [scrollView contentSize] and [scrollView contentOffset] from CATiledLayer's delegate method :
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx

I know CATiledLayer uses this method to render tile in a background thread. And I need to use contentSize and contentOffset to calculate some data (some coordinates). The app ran fine on simulator but on device, it sometimes got the wrong contentSize and contentOffset

A: CATiledLayer does not calculate these values for you, you have to set them.
note that for the tile size it does not apply contentScale. So on Retina the individual tiles are half as big as you specify.
If you still want an answer for this you have to clarify the question.


text:
Q: "Was selected" - an action or a status? CONTEXT: Tracking when a user selected values on a computer program.
The word "on" has to be used differently to portray action ("was turned on") vs status ("was on"). But a problem occurs when applying this to the word "selected": "became selected" portrays action, but the phrase "was selected" seems ambiguous.
For example, the sentence "We know that that option was selected on Tuesday" could mean 2 things:

*

*An action was performed on Tuesday to select that option.

*All throughout Tuesday, that option was selected, and so it must have become selected BEFORE Tuesday.

Is there another succinct way to describe option 2, since "was selected" is ambiguous?
Thanks!


text:
Q: Cannot install bcrypt-ruby on vagrant machine I have followed the instructions for setting up a vagrant rails dev box from https://github.com/rails/rails-dev-box. Unfortunately when I attempt to bundle I get the following:
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    /home/vagrant/.rvm/rubies/ruby-2.0.0-p353/bin/ruby extconf.rb
creating Makefile

make "DESTDIR=" clean
sh: 1: make: not found

make "DESTDIR="
sh: 1: make: not found

make failed, exit code 127

Gem files will remain installed in /home/vagrant/.rvm/gems/ruby-2.0.0-p353/gems/bcrypt-ruby-3.0.1 for inspection.
Results logged to /home/vagrant/.rvm/gems/ruby-2.0.0-p353/extensions/x86-linux/2.0.0/bcrypt-ruby-3.0.1/gem_make.out

An error occurred while installing bcrypt-ruby (3.0.1), and Bundler cannot
continue.
Make sure that `gem install bcrypt-ruby -v '3.0.1'` succeeds before bundling.

When I try and run that gem install command I get the same issue. I have done some searching and am at a loss. Any input is greatly appreciated.

A: This bcrypt-ruby gem is trying to compile native (c, c++) code.
It looks like your VM is missing some tools required to compile this native code.
Get a shell to the VM:
vagrant ssh

Then installing these packages should solve the issue:
sudo apt-get install make g++ gcc libssl-dev

Run bundle install after that.


text:
Q: Calling node-oracledb's createPool Method I am creating a RESTful API that uses Node.js and Express. My application uses an Oracle database so I installed the node-oracledb module from npm. I've looked through the documentation and viewed some of the samples presented in the module's github page; however, I don't see any examples where a connection pool is used. Correct me if I'm wrong, but for applications that will make many calls to the database the recommendation is to use connection pools as opposed to using standalone connections. Below is a sample of the code I wrote:
createPool = function(poolAttrs, fetchPool){
  oracledb.createPool(poolAttrs, function(error, pool){
    if(error){
      console.error(`Could not create pool using specified attributes: `, error.message);
    }
    else{
      console.log(`Pool created successfully using poolAlias: ${poolAttrs.poolAlias}`);
      fetchPool(pool);
    }
  });
};

createConnection = function(poolAlias, connection){
  oracledb.getConnection(poolAlias, function(error, conn){
    if(error){
      console.error(`Could not get connection: `, error.message);
    } else {
      console.log(`New connection obtained: ${conn}`);
      connection(conn);
    }
  });
};

executeQuery = function(queryString, poolAlias){
  console.log(queryString);
  var conn = createConnection(poolAlias, function connection(conn){
    conn.execute(queryString, function(error, result){
      if(error){
        console.error(`Could not execute query: `, error.message);
      } else {
        console.log(result);
      }
      conn.close(function(error){
        if(error){
          console.error(`Could not close connection.`);
        } else {
          console.log(`Connection successfully closed.`);
        }
      })
    });
  });
}

closePool = function(pool){
  pool.close(60, function(error){
    if(error){
      console.error(`Could not close connection pool ${pool.poolAlias}`, error.message);
    } else {
      console.log(`Pool closed successfully.`);
    }
  });
};

createPool(attrs, function fetchPool(pool){
  var poolAlias = pool.poolAlias;
  console.log(poolAlias);
});

executeQuery(queryString, attrs.poolAlias);

When I run this code I get the following error:
Could not get connection:  NJS-047: poolAlias "amDBpool" not found in the connection pool cache

I know why the error is happening. As my understanding of callbacks go, I know that calling the asynchronous createPool() function with the fetchPool(pool) callback registers this callback (fetchPool) in the callback stack. All synchronous code will execute before it. So when I call executeQuery and the function reaches the line of execution where it calls createConnection(poolAlias...) the poolAlias variable is null since the createPool function is still waiting in the callback stack to execute. Hence, no pool with the alias "poolAlias" exists and the call fails. I know that I could stick the call to createPool inside the executeQuery method, but wouldn't that try to create a new pool every time I execute a query? My question is, is there a way to test inside the executeQuery method that the pool exists, and if it does then not try to recreate it. Other than this, the only other way to do this would be with an Promises or Async/Await right?

A: The node-oracledb examples using a connection pool are the connectionpool.js and examples/webap.js files.  Yes, a connection pool would be a good idea in a web service. Also I recommend using the async/await style of programming.
You can see the examples creates a connection pool before doing anything else:
await oracledb.createPool({
  user: dbConfig.user,
  password: dbConfig.password,
  connectString: dbConfig.connectString
});

The returned pool from the oracledb.createPool() call is ignored because the pool is later accessed via the pool cache since no credentials are passed to getConnection():
let connection = await oracledb.getConnection();

This uses the default pool alias (which happens to be the string "default"), so no alias is specified when the pool is created or used.
Documentation and tips on using node-oracledb connection pools is in Connection Pooling.
You may be interested in Creating a REST API with Node.js and Oracle Database,
A node-oracledb Web Service in Docker and Demo: GraphQL with Oracle Database and node-oracledb


text:
Q: Custom SimpleMembershipProvider not initialized correctly I have a custom SimpleMembershipProvider that is implemented in an application service layer. The provider has some of its own properties as well as those inherited from base classes. Although the overridden Initialize method is called on the provider, and it executes without any exceptions, inherited properties get incorrect default values such as zero or Int32.MaxValue. I need them to be initialized to the values provided in the configuration. How can I achieve this?
The configuration looks like this:
<membership defaultProvider="AbcMembershipProvider">
  <providers>
    <clear/>
    <add name="AbcMembershipProvider"
         type="Abc.Services.AbcMembershipServices, Abc.Services"
         connectionStringName="Membership"
         applicationName="ABC"
         enablePasswordRetrieval="false"
         enablePasswordReset="true"
         requiresQuestionAndAnswer="false"
         requiresUniqueEmail="true"
         passwordFormat="Hashed"
         maxInvalidPasswordAttempts="3"
         passwordAttemptWindow="10"
         passwordValidityPeriod="30" />
  </providers>
</membership>

The provider overrides the Initialize method like this:
public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
{
    if (config.ContainsKey("passwordValidityPeriod"))
    {
        int.TryParse(config["passwordValidityPeriod"], out _passwordValidityPeriod);
        config.Remove("passwordValidityPeriod");
    }
    base.Initialize(name, config);
}

During service startup, the SimpleMembershipProvider is initialised as follows:
if (!WebSecurity.Initialized)
        WebSecurity.InitializeDatabaseConnection("Membership", "SystemUser", "UserId", "UserName", false);

The Initialize method is called by the Membership system during the WebSecurity.InitializeDatabaseConnection() call

A: Looking at the source code, the reason this occurs is because various MembershipProvider properties are given a default value by SimpleMembershipProvider when the Provider has been initialized. For example:
// Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized
public override int MaxInvalidPasswordAttempts
{
    get { return InitializeCalled ? Int32.MaxValue : PreviousProvider.MaxInvalidPasswordAttempts; }
}

The way round it is to override these properties in the custom provider.


text:
Q: Is there anything like emacs tramp for shell (bash/zsh)? Say, we have a server where we use "userx" to deploy stuff and do some maintenance task. This user is being used by multiple team members. So, if I can not really modify the .bashrc or .zshrc the way I want it.
On the other hand, I am quite impressed by Emacs tramp. It lets me have my own Emacs configuration on my local system.

A: You can create your own .sabyarc file (writable by you, readable by userx) and source it each time you log in as the user. Or, you can use a group for the maintenance task, so all the users involved can configure their own .rc files.


text:
Q: Как привязать колёсико мыши к полосе прокрутки в pygame Я написал класс полосы прокрутки, в котором я хочу привязать колесо мыши к полосе прокрутки, но всё безуспешно. Я попробовал задавать новое положение элементов(кнопок) и координаты самого ползунка, исходя от текущей Y координаты последнего элемента, но у меня выходит так, что ползунок идёт то очень быстро, то очень медленно. Так вот, я хочу чтобы, когда я прокручиваю элементы(кнопки) при помощи колёсика мыши, вместе с ним также двигался ползунок с элементами.
p.s. Я смотрел как это реализовано в pygame_menu и tkinter, но ничего так и не понял
Вот сам класс(он ещё толком не дописан, поскольку я наткнулся на эту проблему):
class ScrollBar:
VERTICAL = "Y"
HORIZONTAL = "X"

def __init__(self, screen, buttons: Button, direction, x=0, y=0, width=100, height=100, color=(105, 105, 105),
             slider_color=(50, 50, 50)):
    self.screen = screen
    self.buttons = buttons
    self.direction = direction
    self.BAR_X = x
    self.BAR_Y = y
    self.BAR_WIDTH = 20
    self.BAR_HEIGHT = height
    self.width = width
    self.height = height
    self.color = color
    self.slider_color = slider_color
    self.SLIDER_WIDTH = 20
    self.SLIDER_HEIGHT = 20
    self.bar_rect = pygame.Rect(self.BAR_X, self.BAR_Y, self.BAR_WIDTH, self.BAR_HEIGHT)
    self.SLIDER = pygame.Rect(self.BAR_X, self.BAR_Y, self.SLIDER_WIDTH, self.SLIDER_HEIGHT)

#метод входа в класс
def pack(self):

    self.draw_bar()

    if not self.buttons is None and len(self.buttons) > 0 and self.buttons != []:
        for button in self.buttons:
            if button.y + button.height >= self.BAR_Y and button.y <= self.BAR_Y + self.height:
                button.draw(self.screen)

        if pygame.Rect(self.BAR_X, self.BAR_Y, self.BAR_WIDTH + self.buttons[0].width, self.height).collidepoint(*pygame.mouse.get_pos()):
            self.scroll_mouse_wheel()
        self.scroll_bar()

def draw_bar(self):
    pygame.draw.rect(self.screen, self.color, self.bar_rect)
    pygame.draw.rect(self.screen, self.slider_color, self.SLIDER)

#сам скроллбар
def scroll_bar(self):
    MOUSE_CLICK = pygame.mouse.get_pressed()

    self.SLIDER_HEIGHT = (1 / len(self.buttons) if len(self.buttons) > 0 else 1) * (self.BAR_Y + self.height)
    if self.SLIDER_HEIGHT < 20:
        self.SLIDER_HEIGHT = 20
    self.SLIDER.height = self.SLIDER_HEIGHT

    if self.cursor_in_scrollbar():
        if MOUSE_CLICK[0] == 1:

            self.SLIDER.y = self.get_slider_y()
            speed_y = self.get_slider_speed_y()
            for i in range(len(self.buttons)):
                self.buttons[i].y = (i * self.buttons[-1].height) + self.BAR_Y - speed_y

def add_buttons(self, buttons: Button):
    self.buttons.extend(buttons)

def get_buttons(self):
    return self.buttons

#прокрутка элементов при помощи колёсика мыши
def scroll_mouse_wheel(self):

    for event in pygame.event.get():
        if (event.type == pygame.MOUSEBUTTONDOWN and event.button == 4) or (
                event.type == pygame.KEYDOWN and event.key == pygame.K_UP):
            self.move_buttons_up()
            #устанавливаю новое значение координаты Y для ползунка
            self.SLIDER.y = self.get_slider_y_for_mousewheel()

        if (event.type == pygame.MOUSEBUTTONDOWN and event.button == 5) or (
                event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN):
            self.move_buttons_down()
            #устанавливаю новое значение координаты Y для ползунка
            self.SLIDER.y = self.get_slider_y_for_mousewheel()

def move_buttons_up(self):
    for index, button in enumerate(self.buttons):
        button.y += button.height
        if index <= self.BAR_Y < button.y:
            for button1 in self.buttons:
                button1.y -= button1.height

def move_buttons_down(self):
    for index, button in enumerate(self.buttons):
        button.y -= button.height
        if index + 2 > len(self.buttons) and button.y + button.height < self.height:
            for button1 in self.buttons:
                button1.y += button1.height

#получаю новую Y координату для ползунка, если прокручивать при помощи мыши
def get_slider_y(self):
    return max(self.BAR_Y, min(self.BAR_Y + self.height - self.SLIDER.height, pygame.mouse.get_pos()[1]))

#вот тут и находиться сама проблема, я не понимаю как рассчитать новую Y координату для ползунка
#мне толком не понятно, что взять для расчётов новой Y координаты для ползунка. Это или Y координата
#первого или последнего элемента(кнопки), или вообще что-то другое
def get_slider_y_for_mousewheel(self):
    button = self.buttons[-1]
    return max(self.BAR_Y, min(self.BAR_Y + self.height - self.SLIDER.height, (self.BAR_Y + self.height) - (button.y + button.height) / len(self.buttons)))

#получение новой координаты для текущего элемента
def get_slider_speed_y(self):
    try:
        scroll_height = self.height - self.SLIDER.height
        scroll_rel = (self.SLIDER.y - self.BAR_Y) / scroll_height
        offset = (len(self.buttons) * self.buttons[-1].height - self.height) * scroll_rel
    except ZeroDivisionError:
        offset = 0
    return offset

def cursor_in_scrollbar(self):
    return self.bar_rect.collidepoint(*pygame.mouse.get_pos())

Правка 1:
def get_slider_y_for_mousewheel(self):
    button = self.buttons[-1]
    elements_on_screen = (self.BAR_Y + self.height) / button.height
    speed_y = (self.BAR_Y + self.height) - (button.y + button.height) * elements_on_screen / len(self.buttons)
    return max(self.BAR_Y, min(self.BAR_Y + self.height - self.SLIDER.height, speed_y))

Я чувствую что я на правильном пути, но всё же что-то не так. Элементы прокручиваются нормально вместе со скроллбаром, но он слегка не доходит до своей границы. Подскажите пожалуйста чему должно быть равно speed_y для корректной работы?

A: Ваш вопрос дублировался в английской версии и был решен, посмотрите тут


text:
Q: How to keep animated div within container I have 4 tile divs in another container div.
When a div is clicked the other 3 disappear.
I'm trying to get the div that was clicked on the fill the container div after it was clicked but its not working out.
How can i get the div to animate towards the empty space left by the divs I minimized?
this is my code only difference is the position of the div's since JsFiddle's result window is smaller than my browser:

Welcome to TalposMedia

Profile

Contact

Showcase

Resume

https://jsfiddle.net/w15ond4L/

A:     $target.animate({
        height  : '+=335px',
        width   : '100%',
        top     : 0,
        left    : 0


text:
Q: merge 2 sorted list with all elements Homework I have a homework ,and which I have tried to solve for serveral hours.
Description:we have 2 sorted array list ,the length of list a is n, the length of list b is m;we assume   a and b are already sorted, and that the lists a and b do not contain duplicates.And I thought as following   ,but I always get a error:index out of bound .
public static List<Integer> union(List<Integer> list1, List<Integer> list2 ) {
    List<Integer> union = new ArrayList<>();
    int n1 = 0;
    int n2 = 0;

    for (int i = 0; i < list1+list2; i++) {
       ....
}

A: If you loop till m + n one of the array which might have a lesser size than the other will get exhausted and hence the array index out of bound. Instead you can use a while loop which will loop only till the minimum size of the two lists and later, since the list is sorted you can add all the remaining elements from the bigger of the two lists into the union
// iterate till the minimum of two lists

while(index1 < a.size() && index2 < b.size()) {
  if (a.get( index1 ) > b.get( index2 )) {
    union.add(i++, b.get( index2++ ));
  }
  else {
    union.add(i++, a.get( index1++ ));
  }
}

//add the elements of the bigger list to the union

while(index1 < a.size()) {
  union.add(i++ ,a.get( index1++ ));
}

while(index2 < b.size()){
  union.add(i++, b.get( index2++ ));
}

A: public static List<Integer> union(List<Integer> one, List<Integer> two) {
    List<Integer> res = new ArrayList<>(one.size() + two.size());

    for (int i = 0, a1 = 0, a2 = 0; i < one.size() + two.size(); i++) {
        if (a1 == one.size())
            res.add(two.get(a2++));
        else if (a2 == two.size())
            res.add(one.get(a1++));
        else
            res.add(one.get(a1) <= two.get(a2) ? one.get(a1++) : two.get(a2++));
    }

    return res;
}


text:
Q: How to setText on the ArrayList of Button in Android I am making a random number generator app in this app we will take the random number range like 0-100 then when we click on the generate button it will set the number on the button.
Manually we can set that value of random number and set it on button. If i set the random number 4 will always correct it  means the fourth button will always be correct.
Now I want to make the shuffle of random number on button so I create the Random number Array and ArrayList of button so I add it on the ArrayList but I don't know how to set the value of random number array on arraylist of button.
If there is an other way to solve this problem then guide me.
public class MainActivity extends AppCompatActivity {

Button genbtn,optbtn1,optbtn2,optbtn3,optbtn4;
EditText mintext,maxtext;
Random rand[]=new Random[4];
int minrange,maxrange;
ArrayList <Button>shufflearray=new ArrayList<Button>();
int random[]=new int[4];

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    genbtn=(Button)findViewById(R.id.gen);

    shufflearray.add((Button)findViewById(R.id.opt1));
    shufflearray.add((Button)findViewById(R.id.opt2));
    shufflearray.add((Button)findViewById(R.id.opt3));
    shufflearray.add((Button)findViewById(R.id.opt4));
    mintext=(EditText)findViewById(R.id.min);
    maxtext=(EditText)findViewById(R.id.max);

    genbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            minrange=Integer.parseInt(mintext.getText().toString());
            maxrange=Integer.parseInt(maxtext.getText().toString());
            for(int i=0;i<rand.length;i++){
                random[i]=rand[i].nextInt(maxrange-minrange)+maxrange;
            }
            for(int i=0;i<shufflearray.size();i++) {
            }
        }
    });

}

A: You can use Random function like this .
int rand = (int)(Math.random());
it will give you a random number which you can pass to the array list .


text:
Q: Metadata Property not showing in search results I created a column named "Issue Category" in a issue tracker list. And then, I created a new metadata property with the same name . After that I done two full crawls, but I could't see search results for "IssueCategory:EE" .
metadata property:

crawl property:

search result:

newest:
When I saw the crawl log , I find a record that 'The SharePoint item being crawled returned an error when attempting to download the item.' on the site. But is not from my list url. The error page is searchadministration.aspx .

A: In order to make this work, you need to set up a search schema in the site collection.
On the Managed Properties page, in the Managed property field, type the name of the site column that you want to find the managed property name of.

When that is done, do the full crawl again and see if you get results from that property.
Reference: How to display values from custom managed properties in search results - option 1

A: Ensure below:

*

*Managed properties are properly mapped to required crawled properties

*Do a full crawl

*Ensure that the display template (if edited by adding the new managed property) is uploaded and published

*Ensure that the "Update" link in the notification bar is clicked in Result types screen (better to check both at spweb and spsite levels)

*Clear browser cache

Perform a search now and see if the new MP is coming up.
If still they are not showing up, use the Search SearchQueryToolv2.6 to query and find if the Search API is throwing them up. If all seems fine then do below
Final nail in the coffin would be restarting the SP Timer and SP Administration services. (This step made my changes reflect. Though for others, it worked at step 5)


text:
Q: Winforms - Store data based on Gender i have created two tables in database...i used a combo box of gender....I want to save male data in male table and female data in female table using windows forms. It is saving data in both the tables but I only need to store it in their respective tables. I want to save data when i select male from gender combo-box in male table and I want to save data when i select female from gender combo-box in female table Any help would be welcomed.

A: We suppose this class for your Gender stuff:
public class MyGender
{
    public char FemaleOrMale { get; set; }
    public string Name {get;set;}
}

You create a new class, per instance:
public class ComboBoxItem
{
    public string Name { get; set; }
    public string Value { get; set; }
    public Object Tag { get; set; }
}

After you pouplate this one:
List<MyGender> myList = new List<MyGender>();
myList.Add(new MyGender() { FemaleOrMale = 'F', Name = "Stephanie" });
myList.Add(new MyGender() { FemaleOrMale = 'M', Name = "David"});

foreach (MyGender myGender in myList)
{
    myComboBox.Items.Add(new ComboBoxItem() { Name = myGender.Name, Value= myGender.FemaleOrMale.ToString(), Tag = myGender });
}
myComboBox.DisplayMember = "Name";
myComboBox.ValueMember = "Value";

And on selection changed of your combobox, you add per instance this code:
private void OnMySelectionChanged()
{
    ComboBoxItem c = (ComboBoxItem)myComboBox.SelectedItem;
    MyGender myGender = (MyGender)c.Tag;
    if(myGender.FemaleOrMale == 'F')
    {
        //Here Female
    }
    else
    {
        //Here Male
    }
}


text:
Q: Creating a Database Server for home use in SQL Server 2005 Express I am looking to create a database server that can be used to store data using a VB.net application. When I initially installed SQL Server 2005 Express edition, I believe I installed this using the LocalDB option.
As it stands my application is a simple tool which utilises the Process.Start command under certain situations, depending on user input, to launch Game Servers for use at a gaming LAN I assist in running.
I wish to progress the application by being able to update, delete and query a database created in SQL Server 2005 Express. I understand the use of connection strings etc, however I am wondering if the installation using LocalDB will mean that I cannot connect to the server to process the data I require.
Can I continue to use the LocalDB option and create a Database Server for specific use using my application or is a different installation option required?
Secondly, can someone point me in the right direction of how to create a new Server for this purpose? All of my searches so far have provided results for creating a database only, and not the server.

A: I have a couple questions about what you are trying to do.
First, why are you installing SQL Server 2005?  It was released almost a decade ago.
I would go with 2012 express edition.
http://www.microsoft.com/en-us/download/details.aspx?id=29062
Second, install the management tools.  SSMS is a nice GUI to do work in.
Third, If you are spinning up anything other than express, there are licensing costs which are quite high.  9K for standard and 25K for enterprise per socket or such.
Here are the versions and features list from microsoft.
http://technet.microsoft.com/en-us/library/ms144275.aspx
Last but not least, having the express edition on another computer is fine.  However, you will have to use a network protocol such as TCP/IP instead of shared memory.
It will take longer to send Tabular Data Stream (TDS) to the other computer versus talking to memory on the same computer.
http://social.msdn.microsoft.com/Forums/sqlserver/en-US/c4f06669-41fd-42e6-b4a9-564cf04ca9f7/how-to-choose-between-shared-memory-named-pipes-tcpip-via?forum=sqlgetstarted
Good luck with your project.

A: You can use a local instance of SQL Server just fine, if you want to set up a separate server for some reason then you'll need either a 2nd machine on which to install SQL Server, or to spin up a virtual machine.  If running Windows 8 (and barring hardware limitations) you have Hyper-V at your fingertips.

A: This is not a complete answer for you but may give you some things to think about.
First you might want to think about your choice of database.  If you don't have a compelling reason for using 2005 you will probably at least want to move to SQL Express 2008.
Second, to answer the part about creating a server...  A server is something that serves data.  In a general sense a computer configured to be contacted by external machines and respond with data is a server.  A web server runs a program like IIS or Apache to respond with web pages.  A database server contains a database and allows connections to that database. So as long as you install the database on a computer and configure it to allow external connections, you have your database server.
In MS SQL there are several things that need to be set up to allow a database to accept external connections.  One is that the SQL Server Browser service will need to be active.  Another is that the database itself will need to be configured to allow external connections (SQL Authentication type probably).
Hope this helps.
Addition:
SQL Remote Connection Configuration
Disclaimer, I don't have SQL Express 2005 installed but I think the settings are found in the same place in 2008.  If the info here is not exact to SQL Express 2005, the general terminology used here should be enough to get you headed in the right direction to find the specifics.
While viewing the database in Server Management Studio or Enterprise Manager, right click the database server instance name (the root of the tree) and select properties.  There should be a section title Connections and within this section there should be an option "Allow remote connections to this server".  Make sure it is checked.  The other setting you need in this properties menu is under the security area.  There is a radio button for "Windows Authentication Mode" and "SQL Server and Windows Authentication Mode", you want the second that allows both.
The next step you have may be to create a new user, add a password, and connect the user to the database.  That will give you the credentials you will use in your database connection string while programming.  I usually add new users through the security section of the database then set the User Roles for each database that I need to connect to.  It is good practice to limit the permissions to those needed by the application.  Typically this is read and write, but sometimes you can get away with just read.  The less the better.


text:
Q: Why does this trigonometric identity problem work?
Why do I multiply by 1 + sin (theta)? If I multiply on one side, shouldn't I multiply on the other side too? Sorry for the weird formatting. I'm still learning how to use MathJax.

A: You are multiplying by 1 since
$$\frac{1+\sin(\theta)}{1+\sin(\theta)}=1$$
And
$$x\cdot1=x\cdot\frac{y}{y}=x$$
And from there on you are just rewriting your fraction.

A: $$\frac ab=\frac cd\iff ad=bc.$$
This directly leads to
$$1-\sin^2\theta=\cos^2\theta.$$

A: The proof above is making use of the identity
$$1-\sin^2x=\cos^2x$$
As we have a $\cos x$ in the numerator of the second given expression (on the right hand side of the equality) it make sense to try to create a $\cos x$ or a power of $\cos x$ in the numerator of our expression, which can easily be done as they have demonstrated.
Is that helpful?


text:
Q: eclipse debugging 'source no found' There are already several 'Source not found' questions this forum. But none of them is like mine.
I try to debug ftp4j in eclipse and eclipse tells me 'Source not found'. i have already download the jar and source files.

I have set the source attachement of ftp4j.

eclipse debugging still need source. I surf here, it seem eclipse need something like junit-4.11-source.jar. if so ,  but there is not ftp4j-1.7.2-source.jar in ftp-1.7.2.zip.
If all my words are not wrong, can i make  ftp4j-1.7.2-source.jar ? and how?

A: What is going wrong
The reason your source is not being recognized is because it is in a subfolder called src.
What you want a sources.jar file the same structure as the runtime file, but including the .java files in the same folders as the .class files were in the runtime jar.
Runtime jar
/packages/yourclasses.class
/package2/anotherclasses.class

Source jar
/packages/yourclasses.java
/package2/anotherclasses.java

To create this from the provided zip file,

*

*extract the source

*go into the src folder

*create a -sources.jar file

Example command lines for windows with a JDK installed
jar xf ftp4j.zip
cd ftp4j-1.7.2\src
jar cf ftp4j-sources.jar .

A further note
If you don't have the source code, you can always add a de-compiler to eclipse.
See http://sourceforge.net/projects/jadclipse/
If you install this to your eclipse it sometimes helps when you don't have the original source code.
Of course sometimes you can't debug  into the decompiled code, due to line numbers not matching up properly.


text:
Q: ObjectDisposedException error in Release, but not in Debug I am writing an F# app and want to log certain information during its execution. To do so, I set the Console output to a .txt file. I do so as follows:
type VMwareInterface(serviceUrl:string, userName:string, password:string, baseSnapshotName:string) =
    let vimClient = new VimClientImpl()
    let vimSession = vimClient.Login(serviceUrl, userName, password)

    // Logging
    let fileStream = new System.IO.FileStream(@"./VMInteractorLog.txt", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write)
    let streamWriter = new System.IO.StreamWriter(fileStream)
    do System.Console.SetOut(streamWriter)

    [...]

    override x.Finalize () =
        vimClient.Logout()
        streamWriter.Close()

    [...]

And I log stuff the following way:
System.Console.WriteLine("ERROR isolating the single VM matching name " + vmName)

When I run the application in debug, all is well. The file is created, written to and closed properly. Unfortunately, when I run it in release, I get the following error:
System.ObjectDisposedException: Cannot access a closed file.
    at System.IO.__Error.FileNotOpen()
    at System.IO.FileStream.Flush(Boolean flushToDisk)
    at System.IO.FileStream.Flush()
    at System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder)
    at System.IO.StreamWriter.Dispose(Boolean disposing)
    at System.IO.StreamWriter.Close()

What could cause this?
EDIT:
Just wanted to add that the file is properly created in release, but it is not written to prior to getting the mentioned error.
EDIT2:
I have implemented the IDisposable interface as follows:
let mutable disposed = false

let cleanup (disposing:bool) =
    if not disposed then
        disposed <- true

    if disposing then
        vimClient.Logout()
        streamWriter.Close()
        fileStream.Close()

interface System.IDisposable with
    member x.Dispose() =
        cleanup(true)
        System.GC.SuppressFinalize(x)

override x.Finalize () =
    cleanup(false)

This has removed the error I was getting, though the file is still not written to (the file is blank after running my F# app.

A: Its not a good idea to reference managed objects from the finalizer as the GC may have already collected them. Finalizers are only necessary when allocating unmanaged memory like an IntPtr and you want to make sure its always released. The correct way to implement a type that creates disposables internally (like your FileStream) is to use the dispose pattern. This gives the user of the type the opportunity to release resources in a timely fashion.
In summary VMwareInterface should implement IDisposable using the pattern above. The Finalizer override is not needed.
EDIT: Corrected your indentation.
let cleanup (disposing:bool) =
    if not disposed then
        disposed <- true
        if disposing then
            vimClient.Logout()
            streamWriter.Close()
            fileStream.Close()


text:
Q: service fabric actor timeout I have a service fabric OWIN based API which is calling a service fabric actor.
API waits for the actor to complete the work before returning the response. Sometimes the actor can take long time to complete.
The default timeout for Actor is 5 mins and I've tried to increase the operation timeout using :
[assembly: FabricTransportServiceRemotingProvider(MaxMessageSize = 1073741824, OperationTimeoutInSeconds = 600)]

in both the API and the actor. But it is throwing timeout error exactly after 5 mins. is there any other way I can increase the timeout of the service fabric service/actor?
below is the error I'm receiving at API end:
"This can happen if message is dropped when service is busy or its long running operation and taking more time than configured Operation Timeout."

A: What if the job takes even longer than expected? Have you considered making this asynchronous / event driven?
For example:

*

*Call BeginProcessing, schedule a Reminder inside the Actor. Return a Job-token.

*Reminder fires, processing starts.

*Processing completes.

*Notify caller (using SignalR or similar), or expose a GetJobProgress endpoint on a JobMonitorActor. Use Job-token for correlation.


text:
Q: Unable to change default geodatabase with arcpy.env.workspace Even after I set the path for the default database with arcpy environment variable, ArcMap does not change the default database directory?
At first my arcpy.env.workspace looks like below:
>>> arcpy.env.workspace
u'C:\\Users\\g.bharani@cgiar.org\\Documents\\ArcGIS\\Default1.gdb'

The Default1.gdb is highlighted by bold font.
Now I will try to set Gurminder as default gdb through the arcpy.env.workspace variable.
>>> arcpy.env.workspace
u'C:\\Users\\g.bharani@cgiar.org\\Documents\\ArcGIS\\Default1.gdb'
>>> arcpy.env.workspace = r"C:\Users\g.bharani@cgiar.org\Documents\ArcGIS\Gurminder.gdb"
>>> arcpy.env.workspace
u'C:\\Users\\g.bharani@cgiar.org\\Documents\\ArcGIS\\Gurminder.gdb'

Even after refreshing the Catalog the default gdb is still Default1.gdb, the Catalog looks like following:

Because of this I am not able to store data in my customized default directory.
The results of clip, resample and other tools are still getting stored in Default1.gdb although I have change the arcpy.env.workspace to Gurminder.gdb
Why is it happening so?

A: The arcpy.env.workspace is used to set the current working directory or current workspace environment from which you can read and write your data. It will not change the default workspace.
If you need to change the default working space, check Setting the default geodatabase.
Also, check if period "." and "@" in your path can cause a problem or not.


text:
Q: How to inherit styles from another styled component and turning regular component into styled component at the same time? I am using StyledComponents stying framework and This is my regular react component
const SelectButton = ({className,children, ...rest}) => {
  return (
     <select className = {className}{...rest}>
             {children}
          </select>
  );
}

I want to turn this component into styled component by calling styled() function and for that purpose I have attached className prop to DOM element of my react component (SelectButton).
export const StyledSelectButton = styled(SelectButton);

But instead of putting the css in this styled component, I want to inherit from different styled component which is StyledButton.js, which has following css properties.
export const StyledButton = styled(Button).attrs(({ type }) => ({
  type: type || "button",
}))
  display: inline-block;
  height: auto;
  padding: 0.8rem 2rem;
  border: none;
  border-radius: 6px;
  font-weight: 500;
  font-size: 1.6rem;
  text-decoration: none;
  text-transform: capitalize;
  cursor: pointer;
  overflow: hidden;
  background-color: ${({ primary }) => (primary ? "#646ff0" : "#cccdde")};
  color: ${({ primary }) => (primary ? "white" : "#646681")};
  .__select {
    color: #585858;
    font-family: Poppins;
    padding: 1rem;
    border: none;
    background-color: #cccdde;
    width: 150px;
    cursor: pointer;
  };

How can I achieve that?
I have tried doing this way , but I am repeating my code.
export const StyledSelectButton = styled(SelectButton)
  display: inline-block;
  height: auto;
  padding: 0.8rem 2rem;
  border: none;
  border-radius: 6px;
  font-weight: 500;
  font-size: 1.6rem;
  text-decoration: none;
  text-transform: capitalize;
  cursor: pointer;
  overflow: hidden;
  background-color: ${({ primary }) => (primary ? "#646ff0" : "#cccdde")};
  color: ${({ primary }) => (primary ? "white" : "#646681")};
  &__select {
    color: #585858;
    font-family: Poppins;
    padding: 1rem;
    border: none;
    background-color: #cccdde;
    width: 150px;
    cursor: pointer;
  }

A: You can do something like this,
import styled, {css} from "styled-components";
import { StyledButton } from './Button';

  const style = css`
  color: #585858;
  font-family: Poppins;
  padding: 1rem;
  border: none;
  background-color: #cccdde;
  width: 150px;
  cursor: pointer;
`;

Using function declaration method:
export function StyledSelectButton({ className, children, ...rest }){
   return (
     <select className={className} {...rest}>
       {children}
     </select>
   );
 };

To turn this component into a styled component, pass it to the styled() function.
StyledSelectButton = styled(StyledButton).attrs((props) => ({
    as: "select"
}))`
  ${style}
`;


text:
Q: Hover over tag "button" should display Interesting/Ignore text everywhere If you visit a Tag Wiki page (nginx example), hovering over any of the tags within a question will bring up a sub-menu allowing you to add the tag to Interesting/Ignore. I think any tag displayed anywhere should have this ability.

A: Completed a while back with Tag Favorites and Tag Subscriptions


text:
Q: Globally filter the whole site by tag I am looking for an easy way to allow visitors of our Drupal 6-based website to filter all displayed obejcts globally by a tag from a given taxonomy ("featured topics"). This way a user could eg. select the tag "marketing" from a drop-down-list, which is located somewhere near the navigation, and the system would filter all pages, lists and views by the selected tag, across the session, until the user unsets the filter. Having a filter set should be reflected by the theme, but that would be the next task, I guess.
Does anybody know a module which does something like that or could help me here? Is there any easy way to get this functionality (without hacking my way deeply through drupal's guts in weeks of hard work)?
Thank you in advance!
Daniel

A: There are literally hundreds of modules that offer "filter by tag features". I am not aware of one that does what you wish as turnkey, but I am confident there is one that has exactly your interface and workflow, either OOTB, or configurable.
If you were considering views (you were, weren't you?) views offers so called "exposed filters" which allow any filter (filters being: created by Foo, edited after 24-dec, or _has tag Bar), where your users can select such filters from e.g. a dropdown box.


text:
Q: git submodue fatal: unable to fork repo in bitbucket pipelines My bitbucket repository contains submodule pointing to another bitbucket repository. When I try to install submodules with git submodule update --init command. Bitbucket pipeline throws git error fatal: unable to fork repository. Any idea how to fix it ?

A: Thanks to this article I was able to solve my problem.
Step 1
Make sure that you build has installed git and ssh client. Because, I was using git docker/compose:1.24.0 image. I had to run this command in my bitbucket-pipipelines.yaml file.
- apk add git
- apk add openssh-client

Step 2
Create SSH keys for the main repository. In bitbucket got to your repository and then click  Repository settings > SSH keys > Generate keys  and click Copy public key.
Step 3
Add SSH public key to the target (submodule) repository. In bitbucket got to your submodule repository and then click Repository settings > Access keys and click Add key button and add the key obtained in Step 2.
Now your pipeline should fetch depending submodule without any problem.


text:
Q: Validations: When mapping ranges of dates, how to only map a range when card does not match another card I'm setting up a validation, where a person can only add a price if that period does not have a price yet. So for everything works as expected and my form return a validation error when it is supposed to.
A problem arrises when I would like to check if there is a card (e.g. discount card). ==> as a period is allowed to overlap if the card does not match.
validator
class AccommodationPriceAvailabilityValidator < ActiveModel::EachValidator

  def validate_each(record, attribute, value)
    accommodation_prices = AccommodationPrice.where("accommodation_category_id =?", record.accommodation_category_id)
    accommodation_price = AccommodationPrice.where("id=?", record.id)

    if accommodation_price.empty?

      #below code works, without checking the card =>
      date_ranges = accommodation_prices.map { |b| (b.start_date..b.end_date)}

      #attempt below to include the card, but not working =>
      date_ranges = accommodation_prices.where.not(:card => record.card).map { |b| (b.start_date..b.end_date)}

      #rest of the code
      date_ranges.each do |range|
        if range.include? value
          record.errors.add(attribute, "is overlapping with another period")
        end
      end
    else
      date_ranges = accommodation_prices.where.not('id=?', record.id).map { |b| b.start_date..b.end_date }
      date_ranges.each do |range|
        if range.include? value
          record.errors.add(attribute, "is overlapping with another period")
        end
      end
    end
  end
end

A: If by "not working" you mean your query is not retrieving all therecords you want, it is because you are adding a condition to an Activerecord which is already filtered by another where statement.
class AccommodationPrice < ApplicationRecord
  has_one :accommodation_category

  scope :without_card, -> (card) { where().not(card: card) }
  scope :all_except, -> (id) { where().not(id: id) }

  def self.by_category(id)
    where(accommodation_category_id: id)
  end

  def range
    start_date..end_date
  end
end

class AccommodationCategory < ApplicationRecord
  belongs_to :accommodation_price
end

class AccommodationPriceAvailabilityValidator < ActiveModel::EachValidator

  def validate_each(record, attribute, value)
    accommodation_prices = AccommodationPrice.by_category(record.accommodation_category_id)
    accommodation_price = AccommodationPrice.find(record.id)

    if accommodation_price
      accomodations_filtered = accommodation_prices.all_except(record.id)
    else
      accomodations_filtered = AccommodationPrice.without_card(record.card)
    end

    to_accomodation_date_ranges(accomodations_filtered).each do |range|
      if range.include? value
        record.errors.add(attribute, "is overlapping with another period")
      end
    end
  end

  private

  def to_accomodation_date_ranges(accomodation_prices)
    accomodation_prices.map { |b| b.range }
  end
end


text:
Q: performance: variables inside object vs variables inside function I am creating a hybrid mobile application using javascript.
In order to support multiple languages, I created an object called "exchange" that contains the translations of variables, where "exchange" contains more than 200 variable.
My question is that in scale of performance, what's best to use:
1- variables inside object like this:
var exchange = {
    USERNAME_PASSWORD_UNMATCHED: "الاسم و كلمة المرور غير متطابقين",
    NOT_APPROVED: " بانتظار تأكيد صلاحية الوصف",
    ERROR_CONNECT: "فشل الاتصال بالخادم",
    RE_LOGIN: "الرجاء اعادة الدخول",
    INVALID_ACCESS_TOKEN: "رمز المرور غير صحيح",
.
.
.
};

or
2- variables inside function like this
 var exchange = {
    get_variable:function(name){
    switch(name){
        case "USERNAME_PASSWORD_UNMATCHED": return "الاسم و كلمة المرور غير متطابقين"; break;
        case "NOT_APPROVED":return " بانتظار تأكيد صلاحية الوصف";
        case "ERROR_CONNECT":return "فشل الاتصال بالخادم";
        case "RE_LOGIN":return "الرجاء اعادة الدخول";
        case "INVALID_ACCESS_TOKEN":return "رمز المرور غير صحيح";
    }
}
    };

A: I argue that with simple js structures like you provided, difference between the two is minimal. Although, I would prefer solution #1 over #2 because it is much simpler (to my eyes) and easy to access.
I also traced performance of the two with jsperf and there was practically, no difference.
You can view the results here: jsperf-exchange-translation-perf
Here is also the code used for test:
Preparation:
// Keys
var keys = [
   "USERNAME_PASSWORD_UNMATCHED",
   "NOT_APPROVED",
   "ERROR_CONNECT",
   "RE_LOGIN",
   "INVALID_ACCESS_TOKEN"
];

// Random number between keys range
var getRandomKey = function() {
    return Math.floor(Math.random() * ((keys.length - 1) - 0 + 1)) + 0;
};

Test case #1:
var exchange = {
    USERNAME_PASSWORD_UNMATCHED: "الاسم و كلمة المرور غير متطابقين",
    NOT_APPROVED: " بانتظار تأكيد صلاحية الوصف",
    ERROR_CONNECT: "فشل الاتصال بالخادم",
    RE_LOGIN: "الرجاء اعادة الدخول",
    INVALID_ACCESS_TOKEN: "رمز المرور غير صحيح"
};

for(var i = 0; i < 10000; i++) {
   console.log(exchange[getRandomKey()]);
}

Test case #2:
var exchange = {
    get_variable:function(name){
    switch(name){
        case "USERNAME_PASSWORD_UNMATCHED": return "الاسم و كلمة المرور غير متطابقين"; break;
        case "NOT_APPROVED":return " بانتظار تأكيد صلاحية الوصف"; break;
        case "ERROR_CONNECT":return "فشل الاتصال بالخادم"; break;
        case "RE_LOGIN":return "الرجاء اعادة الدخول"; break;
        case "INVALID_ACCESS_TOKEN":return "رمز المرور غير صحيح";
    }
    }
};

for(var i = 0; i < 10000; i++) {
   console.log(exchange.get_variable(getRandomKey()));
}

Results:
Test case #1:
2.51 ops/sec

Test case #2:
2.46 ops/sec

Special note: Because I used console.log etc. There is a possibility that jsperf will return different results based on the traffic the CPU has which is performing the tests. Running tests multiple times reveals that there is much variance.
So I would conclude by saying, the access performance of the solution doesn't make much difference, but using solution #1 over #2 would make sense because the latter only complicates retrieval of object values which is easy in javascript by default using exchange["USERNAME_PASSWORD_UNMATCHED"]


text:
Q: Form submit button in JavaScript In my project, I added some JavaScript to avoid users clicking the same button many times. There is one page where it fetches data from the registration page. Each data row I put add an unfriend button (disabled). Once the user clicks add, the prompt box appears to ask the user to enter a subject and click ok. After clicking ok, the unfriend button will be clickable.
Here is my problem: once clicking the add button, the prompt appears and after clicking ok, the data does not insert into the database.
If I click the unfriend button it inserts into the database. I want the data submitted whenever the user clicks the add button. I think it's because this form has two submit buttons but I don't know how to distinguish between them.
Here is the code:
<?php

session_start();
$mysqli = new MySQLi('127.0.0.1','root','','learning_malaysia');
$sql = "SELECT * FROM tutor_register INNER JOIN tutorskill ON tutor_register.register_ID = tutorskill.register_ID";
$result = mysqli_query($mysqli,$sql);

?>
<html>
<script>
function myFunction(form){
    var subject = prompt("Please enter Subject that want to study");
    if (subject != null){
        form['subject'].value = subject;
        form['btn'].disabled = false;
        form['add'].disabled = true;
        form['add'].value = "request sent";

        form['add'].submit();
        return false;
    }
    form['add'].disabled = false;
    form['btn'].disabled = true;
    form['add'].value = "Add friend";
    return true;
}
</script>
<body>
<?php

if(mysqli_num_rows($result)>0)
{
    while($row = mysqli_fetch_array($result))
    {
        $register_ID = $row["register_ID"];
        $username = $row['username'];
?>

<form method="post" id="form" enctype="multipart/form-data" autocomplete="off">
  <td><input type="submit" value="unfriend" id="btn" disabled />
      <input type="hidden" name="id" value="<?php echo $row['register_ID'];?>" />
      <input type="hidden" id="subject" name="subject" data-uid=<?php echo $_SESSION['sid'] ;?>/>
      <input type="submit" onclick="return myFunction(this.form);" name="addfriend" data-type='addfriend' id="add" class="btn" value="add"  />
  </td>
</form>
<?php
    }
}
?>
<?php

if(isset($_POST['subject']) and $_POST['id']) {
    $user_id = $_SESSION['sid'];
    $friend_id = $_POST['id'];
    $status = "yes";
    $subject = $_POST['subject'];
    $sql = "INSERT INTO friends(user_id,status,subject,friend_id)" ."VALUES('$user_id','yes','$subject','$friend_id') ";

    if($mysqli->query($sql) === true) {
        $_SESSION['status'] = "yes";
        $_SESSION['friend_id'] = $friend_id;
        $_SESSION['user_id'] = $user_id;
    } else {
    }
}
?>
    </body>
</html>

A: Both of your buttons have type="submit" so both would submit the form. Since you have no js code to handle the unfriend it would simply submit the form with the values as you are experiencing.
The other button has the function myFunction handling the click which does return false. Do not return false. You are doing:
form['add'].submit();
return false;

in the form submit function ... both of these are not needed since the button will submit the form if no false is returned from that handler.

A: You can have two input buttons that are both of type="submit". You just need to distinguish the two server side by using say the name attribute. Also, in myFunction submit the form using form.submit() and not form['add'].submit().
https://html.spec.whatwg.org/multipage/forms.html#the-form-element
Two submit buttons in one form


text:
Q: Using unicode (Hebrew characters) with regular expression I wrote script that find expressions in web page:
import sre, urllib2, sys, BaseHTTPServer
# -*- coding: utf-8 -*-
address = sys.argv[1]
web_handle = urllib2.urlopen(address)
website_text = website_handle.read()
matches = sre.findall(u"עברית", website_text)
for item in matches:
    print iten

This script works if I use a "regular" regular expression (without Hebrew characters) and doesn't match anything if I use them.
What am I doing wrong?
edit
example:
url = https://en.wikipedia.org/wiki/Category:Countries

A: You need to ensure that the input string is also in UTF8 format.
Use unicode function with utf-8 as second argument:
website_text = unicode(website_text, "utf-8")

Everything should be in consistent encoding for unicode to work in Python 2.


text:
Q: enterprise alternatives to WPAD proxy configuration? We have 40+ sites in 20+ countries. We use egress filtering and force most users through proxy servers via WPAD.
WPAD is great and works 99.9% for us. However, we have had a few cases where WPAD support issues has caused browsers (only MSIE - on rare occasions) or 3rd party apps (WebEX voip) to fail to work as they do not correctly figure out where the local proxy is - try direct - and fail.
So are there any other mechanisms for enabling enterprises with a plethora of egress points/proxies to be able to support all browsers (ie not just MSIE) and other web-clients - besides WPAD? As I mentioned, WPAD actually works 99.9% for us, but the trouble with that situation is that people only "see" the failures - and grizzling begins...
PS: no, "use DHCP" is not a different option. That is merely an alternative mechanism to deliver WPAD (the primary being DNS). Just thought I'd answer that before someone else does ;-)
Thanks
Jason

A: Your only choices that I'm aware of are:

*

*Configure the client software to "know" where the proxy is "by hand". This is probably a losing battle, since you can't possibly anticipate all potential client software. You end up with a mess of scripts, registry merges, MSI transforms, and a whole host of glue-and-tape to try and pre-configure client software, and then something new slips in under the radar and doesn't work.

*Use standard automated configuration mechanisms like Windows Proxy Auto-Detect (WPAD). As you're seeing, this is not 100% reliable.

*Use a client-side "shim" into the TCP/IP stack, such as Microsoft's "Firewall Client" for ISA Server. The only product that does this that I'm aware of is the Microsoft ISA Server / Firewall Client product. This works very, very well, but is highly proprietary and Windows-specific.

*Use transparent proxying hardware / software to cause traffic to be proxied. This works well in many cases (using ebtables under Linux you can actually create a layer 2 HTTP proxy that's totally transparent  to clients, for example), but has the side-effect of preventing the use of HTTP proxy authentication (since the browser / client doesn't know it's being proxied -- it won't handle it properly).
It's a "pick your poison" type of scenario.


text:
Q: separate first word in a string in python re I need to separate strings into two groups; the first word and the second word or group of words. The words are separated by an underscore and when I use my current code, if there are more than one underscores, it only separates off the last. Here is the code I currently have:
for record in reader:
s = record['trial']
patternsubgen = re.compile(r'(\w+)\(\w+\)\_(\w+)')
source = "Footit"
if patternsubgen.search(s):
    resultsubgen = patternsubgen.search(s)
    genussubgen = resultsubgen.group(1)
    speciessubgen = resultsubgen.group(2)
    subgen = '%s %s' % (genussubgen, speciessubgen)
    #print(subgen)
else:
    pattern = re.compile(r'(\w+)\_(\w+)')
    if pattern.search(s):
        result = pattern.search(s)
        genus = result.group(1)
        species = result.group(2)
        new = '%s %s' % (genus, species)
        print(new)

Here are some examples of the strings:
Aphis(Aphis)_asclepiadis, Cinara_011, Clydesmithia_canadensis_1a,

what I need is:
Aphis asclepiadis,
Cinara 011,
Clydesmithia canadensis_1a,

what I am getting is:
Aphis asclepiadis,
Cinara 011,
Clydesmithia_canadensis 1a

A: Code
Option 1
See regex in use here
(\w+?(?=[(_])).*?_(\w+)

Replacement
$1 $2

Option 2
See regex in use here
([^_\W]+).*?[)_](\w+)

Replacement
$1 $2

Results
Input
Aphis(Aphis)_asclepiadis, Cinara_011, Clydesmithia_canadensis_1a,
Aphis(Aphis)test_asclepiadis, Cinara_011, Clydesmithia_canadensis_1a_test,

Output
Option 1
Aphis asclepiadis, Cinara 011, Clydesmithia canadensis_1a,
Aphis asclepiadis, Cinara 011, Clydesmithia canadensis_1a_test,

Option 2
Aphis _asclepiadis, Cinara 011, Clydesmithia canadensis_1a,
Aphis test_asclepiadis, Cinara 011, Clydesmithia canadensis_1a_test,

Explanation
Option 1

*

*(\w+?(?=[(_])) Capture the following into capture group 1

*

*\w+? Match one or more word characters, but as few as possible

*(?=[(_]) Positive lookahead ensuring what follows matches a character in the set (_

*.*? Match any character any number of times, but as few as possible

*_ Match the underscore character _ literally

*(\w+) Capture any word character one or more times into capture group 2

Option 2

*

*([^_\W]+) Capture one or more word characters except _ into capture group 1

*.*? Match any character any number of times, but as few as possible

*[)_] Match either ) or _ literally

*(\w+) Capture one or more word characters into capture group 2

A: For the given strings, you could use
\b([^_\W]+)(?:\([^()]+\))?_(\w+)\b

See a demo on regex101.com.

In Python:

import re

strings = 'Aphis(Aphis)_asclepiadis, Cinara_011, Clydesmithia_canadensis_1a,'

rx = re.compile(r'\b([^_\W]+)(?:\([^()]+\))?_(\w+)\b')

strings = rx.sub("\g<1> \g<2>", strings)
print(strings)
# Aphis asclepiadis, Cinara 011, Clydesmithia canadensis_1a,

A: There are already good regex answers. You can achieve your goal with str.split alone, though. It accepts an argument specifying the maximum number of splits:
records = ["Aphis(Aphis)_asclepiadis", "Cinara_011", "Clydesmithia_canadensis_1a"]

for record in records:
    left, right = record.split('_', 1) # Split no more than once.
    left = left.split('(')[0]          # Remove anything after '('
    print(' '.join([left, right]))
# Aphis asclepiadis
# Cinara 011
# Clydesmithia canadensis_1a

By the way, you shouldn't call re.compile inside the loop. It's an expensive operation and the pattern doesn't change between records.

A: Requirements are not clear enough, hence some ambiguous use cases. But looking at your own code and subject string together, I'd offer such Regular Expression:
\(\w+\)_(\w+)|_(\w+)

RegEx live demo
Python live demo


text:
Q: Remove shortened name chat pinging This is a not duplicate; I am asking that this "feature" be removed.
This Q now has more votes than the previous request, thus making this one more valuable.

Pinging the name @nick, in chat, also pings all users whose names start with "nick" (like my own).
Not only do I get pings while in the chatroom, I also receive notifications on my phone about new pings.

In the case of "nick", and room 17 (Javascript), 3 users will get pinged:

*

*nick

*NickAlexeev

*NickDugger (me)

There are other cases of this happening as well, and sometimes with names not as common as above.
The importance of this feature was before there was auto-completion, which even mobile now has: http://i.imgur.com/dYwLA1N.png
Typing in the first few letters and using autocompletion will spell out their full username. This should be encouraged, and this short-name matching should be removed.

tldr; Pinging users with a shortened version of their name causes irritation and should be removed.


text:
Q: symfony route change not taking effect this is my controller:
/**
 * \brief Change Password of currently logged in user

 * @Route("/changePw", name="changePw" )
 * @Template()
 */
public function changePwAction(Request $req)
{
    //controller code here
}

When I change the line
* @Route("/changePw", name="changePw" )

to:
* @Route("/changePw2", name="changePw2" )

This change does not take effect and the page still loads from /changePw
I thought that might be cache. So I tried:
php app/console cache:clear --env=dev

which didn't help either. It seems to be something obvious, but as I'm new to symfony I can not figure it out.

A: You should not need to clear the dev cache for routing changes, if you are accessing the site using the app.php however and not app_dev.php then you will need to clear the prod cache for this to work. php app/console cache:clear --env=prod


text:
Q: Scipy fisher_exact test taking a very long time I'm using scipy version 1.0.0.
import scipy as sp
x = [[5829225, 5692693], [5760959, 5760959]]
sp.stats.fisher_exact(x)

For the values above scipy does not return anything but waits.
What can be the reason for that?
How can I fix it?
However in R it returns a p-value almost immediately.
a = matrix(c(5829225,5692693,5760959,5760959), nrow=2)
fisher.test(a)

A: From the notes in the documentation:

The calculated odds ratio is different from the one R uses. This scipy implementation returns the (more common) "unconditional Maximum Likelihood Estimate", while R uses the "conditional Maximum Likelihood Estimate".
For tables with large numbers, the (inexact) chi-square test implemented in the function chi2_contingency can also be used.

(Emphasis mine)
Like DSM's comment mentioned, it's probably just very slow for your large values. And since the notes call out large values, you might try the alternative they suggest:
>>> chi2, p, dof, expected = sp.stats.chi2_contingency(x)
>>> p
6.140729432506709e-178


text:
Q: Defaulting unset values with out a if Statement I think there a easier way to perform the same function but without if statements.
if (isset($_GET['limit']))
 {
  $limit = $_GET['limit'];
 }
else
 {
   $limit = 10;
 }

A: short if ?
$limit = isset($_GET['limit']) ? $_GET['limit'] :  10;

A: $limit = $_GET['limit'] ?: 10;

This assumes PHP 5.3(?) or higher, though.

A: If there is I'd be open to hearing it...
...But I think your best bet is just a short hand if/else statement instead. Not that it really makes any difference.
$limit = (isset($_GET['limit']) ? $_GET['limit'] :  10;

More info here - http://www.lizjamieson.co.uk/9/short-if-statement-in-php/

A: $limit = isset($_GET['limit']) ? $_GET['limit'] : 10;

A: You can use ternary comparison operator:
$limit = (isset($_GET['limit'])) ? $_GET['limit'] : 10;

A: You can write the shorter ?: expression
$limit = isset($_GET['limit']) ? $_GET['limit'] : 10;

Or better yet just write your own function
$limit = updateMyGetVar('limit', 10);

function updateMyGetVar($var, $default = NULL){
  if (isset($_GET[$var]))
  {
    return $_GET[$var];
  }
  else
  {
    return $default;
  }
}