text:
Q: Problem in passing value of JTable cell of one JFrame form to another form's JTextField
I have two JFrame Forms-SelectContactsfrm.java and Taskfrm.java. There is JTable in SelectContactsfrm file to show the contacts.When user select a contact from JTable and when he/she press OK button,selected values should be copied into Taskfrm.java's JTextField.
Taskfrm.java's JTextField's name is-txtContacts and access modifier is-public
Below is the code which I wrote on SelectContactsfrm's OK button's actionPerformed.Button name-btnOK
private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {
    // Code to get the selected rows value and paste Contact's full name in Taskfrm's txtContacts JTextField:

    selrow=ctable.getSelectedRow();
    selcol=ctable.getSelectedColumn();
    Object value=ctable.getModel().getValueAt(selrow,1);
    new Taskfrm().txtContacts.setText(value.toString());

    //Just to check whether I get the correct values or not.
    System.out.println("selrow=="+selrow);
    System.out.println("selcol=="+selcol);
    System.out.println("txtContacts=="+value);

}

I can see the correct selected values in output but didnt get why this value has not been set in Taskfrm's JTextField.In Taskfrm's constructor only initComponents() is there.Is there any way to attach class files here instead of pasting?

A: It depends on how Taskfrm is set up and what is in it's constructor.
I tried something like this and it works
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class ClassA extends JFrame {
    JTextField text;

    public ClassA() {
        JLabel l = new JLabel("Name: ");
        text = new JTextField(20);
        JButton b = new JButton("Send");
        setLayout(null);
        l.setBounds(10, 10, 100, 20);
        text.setBounds(120, 10, 150, 20);
        b.setBounds(120, 40, 80, 20);
        add(l);
        add(text);
        add(b);
        setVisible(true);
        setSize(300, 100);
        b.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new ClassB().text.setText(ClassA.this.text.getText());
            }
        });
    }

    public static void main(String a[]) {
        new ClassA();
    }
}

class ClassB extends JFrame {
    JTextField text;

    public ClassB() {
        JLabel l = new JLabel("Name: ");
        text = new JTextField(20);

        setLayout(null);
        l.setBounds(10, 10, 100, 20);
        text.setBounds(120, 10, 150, 20);

        add(l);
        add(text);

        setVisible(true);
        setSize(300, 100);

    }
}

A: set its visibility and made changes in Taskfrm's constructor.Now its working.
new Taskfrm(value);
new Taskfrm(value).setVisible(true);


text:
Q: How to make HTML tooltips appear when hovering over a point in multiple axis? Although similar To this mouseover question, need solution using matplotlib mpld3 HTML tools. This code displays two plots, but only the second one has mouseover annotations. How to get tooltips on both plots?
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import mpld3
from mpld3 import plugins

# Define some CSS to control our custom labels
css = """
table
{
  border-collapse: collapse;
}
th
{
  color: #ffffff;
  background-color: #000000;
}
td
{
  background-color: #cccccc;
}
table, th, td
{
  font-family:Arial, Helvetica, sans-serif;
  border: 1px solid black;
  text-align: right;
}
"""

fig, ax1 = plt.subplots()
ax1.grid(True, alpha=0.3)

N = 100
r = range(N)
df1 = pd.DataFrame(index=r)
df2 = pd.DataFrame(index=r)

r2 = range(N/2)
df1['x'] = r
df1['y'] = r2 + list(reversed(r2))

df2['x'] = range(N)
df2['y'] = [ i*0.1 for i in list(reversed(r2))+r2 ]

labels1 = []
labels2 = []

for i in range(N):
    label1 = df1.ix[[i], :].T
    label2 = df2.ix[[i], :].T

    label1.columns = ['Row {0}'.format(i)]
    label2.columns = ['Row1 {0}'.format(i)]
    # .to_html() is unicode; so make leading 'u' go away with str()
    html1 = str(label1.to_html())
    html2 = str(label2.to_html())
    labels1.append(html1)
    labels2.append(html2)

points1 = ax1.plot(df1.x, df1.y, marker='o', ls='-', lw=4, color='b',
                 mec='k', alpha=.6, label='Line1')

ax2 = ax1.twinx()
ax2.patch.set_alpha(0)

points2 = ax2.plot(df2.x, df2.y, marker='o', ls='-', lw=4, color='r',
                 mec='k', alpha=.6, label='Line2')

ax1.set_xlabel('x')
ax1.set_ylabel('y1')
ax1.set_title('HTML tooltips', size=20)

ax2.set_ylabel('y2')
lns = points1 + points2

labs = [l.get_label() for l in lns]
plt.legend(lns, labs, loc=0)

tooltip1 = plugins.PointHTMLTooltip(points1[0], labels1,
                                   voffset=10, hoffset=10, css=css)

tooltip2 = plugins.PointHTMLTooltip(points2[0], labels2,
                                   voffset=10, hoffset=10, css=css)

plugins.connect(fig, tooltip1, tooltip2)

displayHTML(mpld3.fig_to_html(fig))

redpajama_set_name: RedPajamaStackExchange


text:
Q: gmaps4rails replaceMarkers not working (javascript) stack details
ruby 1.9.2p180,
rails 3.0.9,
gmaps4rails 1.0.2,
jquery.json-2.3.min.js
Background
I am a newbie to gmaps4rails and really like the gem. All is working well so far, but I am trying to update markers dynamically for the first time. I am doing the following in application.js:
var markers_json = $.toJSON(markers_array);
Gmaps.map.replaceMarkers(markers_json);

This does not work and gives the following error
Uncaught TypeError: Cannot read property 'position' of undefined
extendBoundsWithMarkers in gmaps4rails.googlemaps.js:204
Gmaps4Rails.adjustMapToBounds in gmaps4rails.base.js:443
Gmaps4Rails.create_markers in gmaps4rails.base.js:321
Gmaps4Rails.addMarkers in gmaps4rails.base.js:389
Gmaps4Rails.replaceMarkers in gmaps4rails.base.js:381

Investigation done so far

*

*Confirmed that the initial creation of the map is done by providing the markers as a json string.

*Confirmed that I am giving a json string of the same format in the replaceMarkers call

*Confirmed that in the source, when addMarkers is called on initial page load, the markers are in the form of an object array, but the replaceMarkers call (as I mentioned above) contains a JSON string
Other attempts
Tried to pass the markers without converting to JSON
Gmaps.map.replaceMarkers(markers_array);

but that didn't work as well.

A: I broke my brain over this for quite a while being new to both JS and Rails ... I was unable to get my head around converting from a RAILS jSON string created in my controller to a JavaScript array of JSON objects.
I tried just grabbing the string generated by _to_gmaps4rails but it was full of escaped characters. I now know this was due to changes in Rails to prevent scripts from getting inserted by data.
I tried lots of things, like parsing the JSON on the browser side, passing the data elements individually, etc.
Turns out all I needed was the raw() function which prevented the string from being escaped. Here's my working code:
in my controller:
@markers = plots.to_gmaps4rails do |plot, marker|
    escaped_comment = ERB::Util.html_escape plot.comment
    marker.infowindow render_to_string(:partial => 'my_partial', :locals => { :plot => plot})
    marker.picture ( {
        "picture" => ActionController::Base.helpers.asset_path(plot.marker) ,          # string,  mandatory
        "width" =>   64,          # integer, mandatory
        "height" => 32,          # integer, mandatory
    })
    marker.title   plot.title
    marker.json({ :id => plot.id, :comment => escaped_comment})
end

in my JS (returned from format.js Ajax call):
markers = <%=raw(@markers)%>
Gmaps.map.replaceMarkers(markers)

Hope this helps someone else!

A: This issue is resolved by upgrading to gmaps4rails 1.3.0.
Another problem I faced was to make sure that the replaceMarkers method is given an array of markers, not a JSON string
Note that when you are creating a new map (on the server side), you must give a JSON string for the markers.
When you are calling replaceMarkers on the client side (in JS), you must give an array of marker objects.


text:
Q: Is there a presentation mode on mac? When watching a video, or making a presentation, is there an option or a tool to disable all screensaving, energy savings and all? Regardless of if the power is plugged, I'd like to keep the screen fully on.
I know I can manually adjust the settings everytime. But is there a "presentation" mode, in addition to "battery" and "power adapter" modes?
Or a tool to achieve this?
Thanks

A: The best 3rd-party based solution for you is to use Caffeine.

About Caffeine:   A tiny program that
  puts an icon in the right side of your
  menu bar. Click it to prevent your Mac
  from automatically going to sleep,
  dimming the screen or starting screen
  savers. Click it again to go back.
  Hold down the Command key while
  clicking to show the menu.

A: Nothing built-in to the OS, but MarcoPolo can be used to do what you want.


text:
Q: Pandas: Querying a DataFrame - multiple criteria I have a large DataFrame for which two of the columns are:

*

*a question code (e.g Q453)

*True or False to denote whether or not the question was answered correctly

I do not know all the possible question codes and each question has been answered multiple times. Something like:
Q666    True
Q463    True
Q056    True
Q666    False
I wish to know which question is the easiest, precisely which question has the highest ratio of attempts to correct answers.
What are the steps to achieve this using pandas?

A: I just made a sample of data from your post. Is this what you're looking for?
I made the true/false indicators lowercase strings; not sure what they are stored as in your file. If you're on python2, i believe you can change from io import StringIO to from StringIO import StringIO.
In [105]: import pandas as pd
     ...: from io import StringIO
     ...:
     ...: data = """Q666 True
     ...:
     ...: Q463 True
     ...:
     ...: Q056 True
     ...:
     ...: Q666 False
     ...: Q666 True
     ...:
     ...:
     ...: Q463 True
     ...:
     ...: Q056 True
     ...: Q666 False
     ...: Q463 False
     ...: Q666 False"""
     ...:

In [106]: df = pd.read_csv(StringIO(data), sep=" ", header=None)

In [107]: df.columns = [['question', 'answer']]

In [108]: df['answer'] = df['answer'].astype("str").apply(lambda x: x.lower())

In [109]: df
Out[109]:
  question answer
0     Q666   true
1     Q463   true
2     Q056   true
3     Q666  false
4     Q666   true
5     Q463   true
6     Q056   true
7     Q666  false
8     Q463  false
9     Q666  false

Assign a constant value to to dataframe so we can count groupby our conditions, then move the multiindex back to where we need it.
In [110]: piv = (df
     ...:        .assign(val = 1)
     ...:        .groupby(["question", "answer"])
     ...:        .count()
     ...:        .unstack()['val'])

It's easy from here...
In [111]: piv['ratio'] = piv['true'] / piv.sum(axis=1)

In [112]: piv.sort_values("ratio")
Out[112]:
answer    false  true     ratio
question
Q666        3.0   2.0  0.400000
Q463        1.0   2.0  0.666667
Q056        NaN   2.0  1.000000


text:
Q: Eager Load from Entity Framework SP Im trying to populate my domain models and child entities with 1 SQL Store Proceedure execution. Perhaps this is answered here. Im pretty certain it's not possible but I though I would throw the question out there to find possible work arounds.
I have quite complex domain models and im looking for a more efficient way of loading my data rather than query a customer and then lazy load its children. I have presented a simple example of what im trying to achive below;
public class Customer{
   public int Id { get; set; }
   public virtual Address Address { get; set; }
}

public class Address{
   public int Id { get; set; }
}

var customer = this.Database.SqlQuery< Customer >("exec SP_Name")

I know in EF5 you can return multiple data contexts but im hopeful I can resolve muliple child entities.
I hope ive made sense. Im lacking alot of sleep so apologies if it doesn't. Following a sport in a timezone 10 hours behind makes it difficult! :(

A: Stored procedures in EF don't offer eager loading. They can only load single level of entities. You can either use stored procedure with multiple result sets as mentioned in linked article but that works only with EDMX and you must execute mapped function import instead of SqlQuery. You can also simply use eager loading with LINQ query instead of stored procedure to avoid lazy loading:
var customers = context.Set<Customer>()
                       .Include(c => c.Address)
                       .FirstOrDefault(c => c.Name == someName);


text:
Q: Processing algorithm doesen't work in standalone script - PyQGIS 3.4 I am trying to execute the processing algorithm extractbylocation. Anyway, firstly I run that algorithm in QGIS3 and then just copy the code from the processing history and changes paths to variables. I have some features with invalid geometries (in QGIS in the settings it is set for processing to ignore that features),so that is maybe my problem. In order to avoid that I deleted all the features with invalid geometries and the problem is still there.
So my code looks like this:
input_path = 'C:/Users/file.shp'
output_path = 'C:/Users/file_out.shp
crs = QgsCoordinateReferenceSystem("epsg:4326")
input = QgsVectorLayer(input_path, "links", "ogr")
input.setCrs(crs)

#deleting features with invalid geometries
for f in input.getFeatures():
    geom = f.geometry()
    if geom.isGeosValid():
        print('valid')
    else:
        input.deleteFeature(f.id())
        print('not valid')

sys.path.append('C:/Program Files/QGIS 3.4/apps/qgis/python/plugins')
import processing
from processing.core.Processing import Processing
Processing.initialize()
QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())

processing.run("native:extractbylocation",
               {'INPUT': input, 'PREDICATE': [1],
                'INTERSECT': 'C:/Users/points.shp', #I also tried to put here the QgsVectorLayer object instead of path
                'OUTPUT': outputh_path})

I got the error next to the output line in the processing algorithm.
 File "path_to_my_file_py", line 49,    'OUTPUT': outputh_path})
 File "path_to_my_file_py", line 84, in run
return Processing.runAlgorithm(algOrName, parameters, onFinish, feedback, context)
 File "path_to_processing_file_py", line 194, in runAlgorithm
raise QgsProcessingException(msg)
_core.QgsProcessingException: There were errors executing the algorithm.

And btw this code works at python console in qgis.

A: I also found my scripts worked fine in the QGIS 3 Python Console, but when run in standalone PyQIS v3 they do not work. I found it does not accept strings as inputs and the only workaround is to keep trying the different field types the algorithm accepts as inputs (like you suggested using QgsVectorLayer), but even then, depending on the algorithm, it still sometimes doesn't work.
You can find all of the different types it accepts by running the command ~~~
processing.algorithmHelp("qgis:extractbylocation") ~~~ in the QGIS Python console.
I have the same problems with developing new standalone scripts in QGIS 3.x which I did not have with QGIs 2.x. I am unsure whether it is my coding or there is a problem with the PyQGIS v3. This is further compounded by a lack of easy to understand documentation on running PyQIS 3 in standalone mode.


text:
Q: Django class based view to query database from form and display results So I am completely new to Django, I want to have a user enter a keyword into an HTML form then have each row from the database where an attribute matches that keyword displayed on the page. I've tried various ways of doing this and am not sure what I am doing wrong. Any help would be appreciated.
search.html

    <form method="GET" action="{% url 'search' %}">

            <input type="text" name="make" placeholder="Car Make" />

                <button type="submit" class="btn btn-danger"> Go </button>

    </form>

{% if results %}

        Car Make
        Car Model
        Car Type
        Number of Seats
        Price

    {% for item in results%}

        {{item.makename}}
        {{item.model}}
        {{item.seriesname}}
        {{item.seatingcapacity}}
        {{item.pricenew}}

    {% endfor %}

{% endif %}

views.py
class SearchView(TemplateView):

    template_name = 'carproject/search.html'
    model = Vehicles

    def get(self, request):
        form = AdvancedSearch()
        return render(request, self.template_name, {'form': form})

    def search(self, request):
        makequery = self.request.GET.get['make']
        if makequery:
            results = self.Vehicles.objects.filter(makename__icontains(makequery))
        return render(request, self.template_name, {'results': results})

Models.py
class Vehicles(models.Model):
    carid = models.IntegerField(db_column='CarID', primary_key=True)
    makename = models.CharField(db_column='MakeName', max_length=45)
    model = models.CharField(db_column='Model', max_length=45)
    seriesname = models.CharField(db_column='SeriesName', max_length=45)
    seriesyear = models.TextField(db_column='SeriesYear')
    pricenew = models.IntegerField(db_column='PriceNew')
    fuelsystem = models.CharField(db_column='FuelSystem', max_length=45)
    enginesize = models.CharField(db_column='EngineSize', max_length=10)
    tankcapacity = models.CharField(db_column='TankCapacity', max_length=10)
    power = models.CharField(db_column='Power', max_length=10)
    seatingcapacity = models.IntegerField(db_column='SeatingCapacity')
    standardtransmission = models.CharField(db_column='StandardTransmission', max_length=45)
    bodytype = models.CharField(db_column='BodyType', max_length=45)
    drive = models.CharField(db_column='Drive', max_length=3)
    wheelbase = models.CharField(db_column='WheelBase', max_length=10)
    class Meta:
        managed = False
        db_table = 'vehicles'

A: You can just do Vehicles.objects.filter(makename__icontains=request.GET.get("make","somevalueasdefault")) in your get function. Maybe I am missing something, but I am not sure why you have rendered the view like that in a class-based view. Just as an example, you can do like below.
class SearchView(TemplateView):
    template_name = "carproject/search.html"

    def get(self, kwargs):
      context = super(SearchView, self).get_context_data(**kwargs)
      context['queryset'] = Vehicles.objects.filter(makename__icontains=request.GET.get("make","sdefault"))
      return context


text:
Q: Django 1.5 + TastyPie 0.10 Gives "cannot import name ModelResource" After update Django & Tastypie I receive a "cannot import name ModelResource".  How can I fix this issue?
I am currently trying to update a Django install to Django 1.5, and also up to the latest version of Tastypie.  I've done this twice before (once on my dev MacBook Pro and again on a pre-release server, identical to the one I'm upgrading now).  Both times I remember having trouble, but both times I just got it working... I don't know how!
It has now happened a third time, and my frantic "uninstall then reinstall until it works" strategy has so far failed.  I'm running an Apache server, though so it my pre-production that is working (I have checked that all django & module versions match).
Has anyone run into this issue and is away of the magic sequence to fix this?
Full Trackback follow:
Environment:

Request Method: GET
Request URL: http://10.32.232.50/

Django Version: 1.5.2
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'django.contrib.admindocs',
 'django_extensions',
 'floppyforms',
 'crispy_forms',
 'tastypie',
 'userProfile',
 'modeling',
 'aliance',
 'launchpad',
 'visitorlog',
 'experience_controller')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')

Traceback:
File "C:\Python27\lib\site-packages\django-1.5.2-py2.7.egg\django\core\handlers\base.py" in get_response
  103.                     resolver_match = resolver.resolve(request.path_info)
File "C:\Python27\lib\site-packages\django-1.5.2-py2.7.egg\django\core\urlresolvers.py" in resolve
  319.             for pattern in self.url_patterns:
File "C:\Python27\lib\site-packages\django-1.5.2-py2.7.egg\django\core\urlresolvers.py" in url_patterns
  347.         patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Python27\lib\site-packages\django-1.5.2-py2.7.egg\django\core\urlresolvers.py" in urlconf_module
  342.             self._urlconf_module = import_module(self.urlconf_name)
File "C:\Python27\lib\site-packages\django-1.5.2-py2.7.egg\django\utils\importlib.py" in import_module
  35.     __import__(name)
File "c:\AbacusCore\abacus\urls.py" in <module>
  3. from api import *
File "c:\AbacusCore\abacus\api.py" in <module>
  4. from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS
File "C:\Python27\lib\site-packages\django_tastypie-0.10.0-py2.7.egg\tastypie\resources.py" in <module>
  19. from tastypie.authentication import Authentication
File "C:\Python27\lib\site-packages\django_tastypie-0.10.0-py2.7.egg\tastypie\authentication.py" in <module>
  14. from tastypie.compat import User, username_field
File "C:\Python27\lib\site-packages\django_tastypie-0.10.0-py2.7.egg\tastypie\compat.py" in <module>
  14.         User = get_user_model()
File "C:\Python27\lib\site-packages\django-1.5.2-py2.7.egg\django\contrib\auth\__init__.py" in get_user_model
  127.     user_model = get_model(app_label, model_name)
File "C:\Python27\lib\site-packages\django-1.5.2-py2.7.egg\django\db\models\loading.py" in get_model
  230.             self._populate()
File "C:\Python27\lib\site-packages\django-1.5.2-py2.7.egg\django\db\models\loading.py" in _populate
  75.                     self.load_app(app_name)
File "C:\Python27\lib\site-packages\django-1.5.2-py2.7.egg\django\db\models\loading.py" in load_app
  96.             models = import_module('.models', app_name)
File "C:\Python27\lib\site-packages\django-1.5.2-py2.7.egg\django\utils\importlib.py" in import_module
  35.     __import__(name)
File "c:\AbacusCore\visitorlog\models.py" in <module>
  6. from tastypie.resources import ModelResource

Exception Type: ImportError at /
Exception Value: cannot import name ModelResource

A: Is your installation of tastypie  in your PYTHONPATH?

If you open up a command prompt (make sure you're in the right virtual env if you use that) and run:
bash: echo $PYTHONPATH

or, from a python debugger open at the exception point:
>>>import os
>>>os.environ['PYTHONPATH'].split(os.pathsep)

then make sure that the directory you've installed tastypie into, is in one of the directories listed.


text:
Q: Recover lost NTFS partition on SSD About 2 month ago I upgraded my Dell Latitude E6500 laptop with a Corsair Force F120 SSD drive. Everything worked well until about a week or so back.
I started the computer and was faced with a beep and a message saying "No boot sector on Internal HDD (IRRT). No bootable devices". Since I figured that the boot sector had somehow got corrupt I tried booting from the Windows 7 dvd in order to repair the boot sector. But the Windows 7 installation program only found a blank drive with 111GB of unallocated space. I panicked and brought the drive with me to work to let a colleague have a look at it. We made a disk image of the entire drive and ran the drive through Testdisk in Linux. Testdisk did not find any partitions. It appears that the drive has been completely erased...
What has happened? What is causing this behavior on an SSD?

A: Corsair F Series drives have a firmware problem that arises if you change system states. From another forum: "It runs fine as long as you don't try to put the laptop to sleep, wake it up, or change the hardware profile (say, by docking or undocking it)".  Allegedly there is a firmware update to 2.0 which may address it along with having the latest BIOS and having AHCI set (vs IDE) in your BIOS.  See http://forum.corsair.com/v3/showthread.php?t=90759

A: Call the vendor for support and/or RMA, and stand by for a restore from backup.  (You do have a backup, right?)

A: Sounds like something that happened to me:
A systemcrash rendered the partition on the harddrive useless. I rebooted and startet up Knoppix to investigate further. I wasn't able to find partitions.
What had happened was that (after being unable to find something he thought was useful) a trim command got issued and the "useless" data got purged.
Problem with SSD is that SSD self is the problem. Many SSD failures are in fact unrecoverable - because if the remapping tables get trashed - the media data is effectively randomized - and mixed up with blocks which were marked as corrupted and unusable even before the SSD failed.
Hope you have a backup.

A: This type of thing happens when the controller screws up somehow.  The flash memory itself is fine, most likely, as well as the data on it but you can't get to it without a functional controller.  Usually the only way to restore controller functionality is to re-flash the drive's firmware, which incidentally wipes out all your data.  This is why I tell everyone who uses an SSD to be extra sure you do backups.
SSD manufacturers need to come up with a way to re-flash a controller without causing it to wipe the drive clean.


text:
Q: I don't understand why a class is "public" I'm beginning to learn C# and I come from a C++ background. The example page I was supposed to create by these instructions looks like
using System.Web;
using System.Web.Mvc;

namespace MvcMovie.Controllers
{
    public class HelloWorldController : Controller
    {
        //
        // GET: /HelloWorld/

        public string Index()
        {
            return "This is my <b>default</b> action...";
        }

        //
        // GET: /HelloWorld/Welcome/

        public string Welcome()
        {
            return "This is the Welcome action method...";
        }
    }
}

My main question is why the HelloWorldController class is prefixed by public. I understand that HelloWorldController is derived from Controller, but why does a class need to be public in the first place? My understanding of the words public and private is that they only have meaning if they're functions inside a class, and that public are the ones that can be used by instances of that class. Also, where is my main.cs in this Visual Studio ASP.NET MVC project that I created?

A: The purpose of public and private on a class differs from that on methods.
Classes (C# Programming Guide)
public class Customer
{
    //Fields, properties, methods and events go here...
}

The class keyword is preceded by the access level. Because public is
  used in this case, anyone can create objects from this class.

Access Modifiers (C# Programming Guide)
public class Bicycle
{
    public void Pedal() { }
}

The type or member can be accessed by any other code in the same
  assembly or another assembly that references it.

A: A private class wouldn't be able to be used by anything, unless it were within another class.  C# doesn't allow un-nested classes to be private, as nothing could use it.
However, there is another option: you could mark the class as internal instead.  internal restricts access to within the current assembly.

A: The keyword indicates who is allowed to create instances (objects) from this class. Private would be used if you have classes nested inside each other, and you don't won't it accessible from outside the class.
From MSDN

The class keyword is preceded by the access level. Because public is used in this case, anyone can create objects from this class. The name of the class follows the class keyword. The remainder of the definition is the class body, where the behaviour and data are defined. Fields, properties, methods, and events on a class are collectively referred to as class members.


text:
Q: Is it ok to to delete and repost a duplicate question? I asked a question that has been marked as a duplicate. I read a lot of similar questions and explanations in advance but I couldn't find a solution. In the question that should answer my question the asker used a different (not working) approach. There is even an answer that would work for my case however I'd rather consider it as a workaround than a solution since I have seen examples using my approach.
So I would like your opinion in that case. Would it be ok to repost my question while explaining why other answers didn't help me? I edited my question but I think it's not getting any attention anymore. Naturally I will remove the old question.

A:
Is it ok to delete and repost a duplicate question ?

*

*Short answer : No

*Long answer : Keep in mind that if the question was closed as duplicate in the first place it doesn't belong here since it's a double. If you post the same question, chances are it will be re-closed for the same reasons. Now, if you ask a similar question with a different approach and explain why other questions were not helpful to you then I guess it is ok to re-post it but guess it is not the same question anymore...this is why you should refer to the short answer.

A: As has been said in the comments, you have to be careful when doing what you suggest. Do it to many times and the system flags you and you get a question ban.
There is an issue on SO with duplicate questions. Once they get marked as a duplicate the amount of attention paid to them -even if you do edit them - drops off sharply .
Your preferred solution would be to edit and flag for Mod attention. However if this doesn't work then you have 2 options.
One: try and get whatever solution was posted to the 'dupe' question so that it fits your needs. Hard, but if it's close not impossible.
Two: Leave your question up, it's a duplicate yes but the system knows how to handle duplicates. Next, sit down and think about your question, think of any phraseology or approach that you could take to make your question clearer and less like the dupe.
Then when you write your new question include the research you did. Point out how much effort you have put into it. Use links and say things like:

"I found this question here and it was good, but ultimately my question is different in X way".

If people can see the effort put into it. Can see that you did the research and it's clear to them why it's not a duplicate then they are much more likely to help you.
Remember that all the work done here is on a volunteer basis. We like helping by answering questions, IF we feel like we are actually just answering the question; not doing work for someone for free.

A: As you are speaking of https://stackoverflow.com/questions/16001470/c-bad-acces-on-vector-begin-using-object-pointers, that question has been already closed as duplicate.
In this case, when the question is edited, it is automatically added to the review queue for questions to be re-opened. Instead of editing the question to add you disagree with the decision to mark it as duplicate, you should edit it to say that you tried the answers given for the other question, but none of them worked for you; you could also made clear in what your question is different from the other, for example adding details about your case (e.g. "I am using quinoa, and not whole grain.").
Deleting a question is a bad idea, on the trilogy sites, since that could cause you to be question-banned. If that happens, you are not anymore allowed to ask questions, and you should gain reputation by answering questions.


text:
Q: GIS data backup strategy Is there any backup strategy for GIS data?
Say .mxd, shape files, data base connection files, feature layers, geo-database etc.
According to ideal methodology:
1.On external hard drive : best to take backup of all folders and sub folders.
2.Working on ArcGIS JSAPI so taking daily backup on CVS
Similar fashion what would be the recommended backup strategy for GIS Data?
We are using ESRI and open source platform (Desktop and server based + spatial database)
Any help would be great!!

A: Is there any backup strategy for GIS data?
No, the way it should be is a project has an assigned number for record keeping - the server has this Job_Number and all files emails,quotes,GIS_raw_data, processed data and finally the delivered data/map/pdf/website
This ensures that the ENTIRE project can be easily retrieved.
Backup vs Archive
Backups should be done regularly (weekly min for no production work and every day for production).
It depends on your environment (how big/small) how this implemented.
Archive are when jobs are finished and invoiced (payment is received)
This is then moved to the archive folder where it is backed-up on to external hard-drive and DAT tape - one of these media is then removed from the site (in cases of fire/theft).
Advantages - Windows has a very good 'previous versions' this needs to be set up on the server. It will give users the instant result (time saver) when they click 'previous versions'

Dis-advantages
Cost - it takes money to have a very good back-up and archive process - Staff need to be trained and the process must be en-forced heavy to work effectively and as it should.
(i.e. no leaving files on a local drive and the local drive fails)
Time is the other factor - time to plan/implement/train - also backup of terabytes of data can be time consuming - backups can run into each other if not.

A: For the External hard drive I do not recommend the WD Elements prodocts It is a 2 TB with USB 2.0  ! Had one crashed and fried. Have had it for a year.
Second - best to have at least one external hard drive in case if one fried, or stolen or if your office/building burns down, then you have plan B that you have a second external hard drive at home for protection.
That is my backup strategy.


text:
Q: Extended Kendo Calender how to bring kendocalender extended this way?
I use mvc4/razor
I have only this in my calendar.cshtml
<div class ="kendocalender">
  @(Html.Kendo().Calendar()
     .Name("Calendarname")
     .HtmlAttributes(new { style = "width: 180px;height:200px;font-size:13px" })
  )
</div>

This is my controller actionresult in calendarcontroller
public ActionResult Calendar()
{
    return View();
}

A: Make static method in static class - extension method
public static MvcHtmlString KendoCalender<TModel>(this HtmlHelper<TModel> htmlHelper, string name, object htmlAttributes)
{
     string calenderControl = htmlHelper.Kendo().Editor()
                    .Name(name)
                    .HtmlAttributes(htmlAttributes)
                    .ToHtmlString();

     return MvcHtmlString.Create(calenderControl);
}

include namespace in the View, and then you can call it from View by this code.
@Html.KendoCalender("CalenderName", new { style = "width: 180px;height:200px;font-size:13px" })

No need to add controller action method for that!!


text:
Q: Select multiple distinct fields, and summing another field I have a table where I have 6 columns.  5 of these columns I have to make sure that I don't have any duplicates.  So I used the statement:
SELECT SUB_ACCT_NO_PAJ, CustomerType, POST_DTE_PAJ, IA_DateYear, ADJ_RSN_PAJ, count(*) AS [aCount]
INTO TempTable1
FROM All_Adjustments
GROUP BY SUB_ACCT_NO_PAJ, CustomerType, POST_DTE_PAJ, IA_DateYear, ADJ_RSN_PAJ,

My problem is that the sixth column, POST_AMT_PAJ, needs to be totaled for each of these rows.  So if any of the rows had been exact duplicates in the other fields, then I need to take each of the POST_AMT_PAJ from them and total them for the new table.
Any help is appreciated! Thanks!
Editing to demonstrate better
All Adjustments:
SUB_ACCT   |    Customer Type   |   POST_DTE   |  Dateyear   |  POST_AMT
------------------------------------------------------------------------
  1        |         R          |    July 3    |    2010     |     5
  1        |         R          |    July 3    |    2010     |     8
  2        |         L          |    June 2    |    2008     |    14
  2        |         R          |    June 2    |    2009     |    12

Would go to...
SUB_ACCT   |    Customer Type   |   POST_DTE   |  Dateyear   |  POST_AMT
------------------------------------------------------------------------
  1        |         R          |    July 3    |    2010     |    13
  2        |         L          |    June 2    |    2008     |    14
  2        |         R          |    June 2    |    2009     |    12

A: To get the total of a column, use SUM:
SELECT
    SUB_ACCT_NO_PAJ,
    CustomerType,
    POST_DTE_PAJ,
    IA_DateYear,
    ADJ_RSN_PAJ,
    SUM(POST_AMT_PAJ) AS POST_AMT_PAJ_total
    COUNT(*) AS [aCount]
INTO TempTable1
FROM All_Adjustments
GROUP BY
    SUB_ACCT_NO_PAJ,
    CustomerType,
    POST_DTE_PAJ,
    IA_DateYear,
    ADJ_RSN_PAJ

A: Try this:
SELECT
 SUB_ACCT_NO_PAJ,
 CustomerType, POST_DTE_PAJ,
 IA_DateYear,
 Sum(ADJ_RSN_PAJ) as 'Total_Adj_Rsn_Paj',
 count(*) AS [aCount]
INTO TempTable1
FROM All_Adjustments
GROUP BY SUB_ACCT_NO_PAJ, CustomerType, POST_DTE_PAJ, IA_DateYear

Since ADJ_RSN_PAJ would then be in an aggregate function, it should not cause your Group By clause to blow up.
NOTE: This is completely from memory, so you may need to do some tweeking (I don't actually have  SQL Server I can play with- even for syntax checking...)


text:
Q: Functors and iteration trough vector I'm trying to get into 'modern' C++, so I'm trying to learn how to properly use functors, and, subsequently, lambdas.
I think I've understood basic principle behind it, but I'm having trouble to understand how to acquire any element from a vector that is passed to my algorithm.
So, let's say I wish to create a Fibonacci sequence of length N...
struct Adder {
    int operator()(int a, int b) {return a+b;}
};
const int N = 10;

int main() {

    std::vector<int> vec = {0, 1};
    vec.resize(N);

    //Old Way
    for(int i = 2; i < vec.size(); i++) {
        vec[i] = vec[i-1] + vec[i-2];
    }

    std::transform(vec.begin(), vec.end(), vec.begin(), [](int i){return i*3;});    //single operator given to function, works

//    std::transform(vec.begin()+2, vec.end(), vec.begin(), /*here two calls are needed , for a and b operators*/);

    return 0;
}

Basically my question is how to activate functor defined in struct Adder? What is the proper way to pass two operators to him?

A: Adder::operator() should be const.  And your Adder functor is unnecessary.  Just use std::plus<>.
Since C++17, we have the transform overload that accepts two sequences.  So we can do: (you can use Adder{} in place of std::plus<>{} if you want)
std::transform(vec.begin(), vec.end() - 2, vec.begin() + 1, vec.begin() + 2, std::plus<>{});

Minimal example: (live demo)
#include <algorithm>
#include <iostream>
#include <vector>

constexpr int N = 10;

int main()
{
    std::vector<int> vec{0, 1};
    vec.resize(N);

    std::transform(vec.begin(), vec.end() - 2, vec.begin() + 1, vec.begin() + 2, std::plus<>{});

    for (int x : vec)
        std::cout << x << " ";
    std::cout << "\n";
}


text:
Q: Calculating the Inverse Fourier Transform of $\frac{1}{\sqrt{2\pi}k}\sin k$ This used to be part of a longer question that I posted earlier but since that question seemed to long I decided to split it up.

Given the function
$$f(x) = \begin{cases} \frac{1}{2},  & \text{if $\lvert x\rvert \le
1$} \\ 0, & \text{else} \end{cases}$$
I calculated the fourier transform $\hat{f}(x)=\frac{1}{\sqrt{2
\pi}}\int_{-\infty}^{+\infty}f(x)e^{ikx}dx$ to be:
$$\hat{f}(k)=\frac{1}{\sqrt{2\pi}k}\sin k$$
I want to show that the inverse transform $\frac{1}{\sqrt{2
\pi}}\int_{-\infty}^{+\infty}\hat{f}(k)e^{-ikx}dx$ yields the function
  $f(x)$ I began with.

My attempt:
$$f(x)=\frac{1}{\sqrt{2\pi}}\int_{-\infty}^{+\infty}\frac{1}{\sqrt{2\pi}k}\sin k  \cdot e^{-ikx}dk \\ \iff f(x)=\frac{1}{2\pi}\int\frac{1}{k}\sin{(k)} \space e^{-ikx}dk$$
We are given a hint: "Re-express $\frac{1}{k}$ as a derivative in front of the integral". I have no clue how to use this though.
Can someone help me solve the inverse transform integral?

A: Perhaps what the hint means is
$$
f(x)=\frac{-1}{2\pi\mathrm{i}}\frac{\partial}{\partial x}\int_{-\infty}^\infty dk\frac{\sin k}{k^2}e^{-\mathrm{i}kx}=\frac{1}{2\pi}\frac{\partial}{\partial x}\int_{-\infty}^\infty dk\frac{\sin k}{k^2}\sin(kx)\ ,
$$
where I use the fact that $e^{-\mathrm{i}kx}=\cos (kx)-\mathrm{i}\sin (k x)$ and the integrand with $\cos$ is odd (and thus gives a zero integral). The remaining integrand is now even, so
$$
f(x)=\frac{2}{2\pi}\frac{\partial}{\partial x}\int_{0}^\infty dk\frac{\sin k}{k^2}\sin(kx)\ .
$$
The integral can be evaluated to be $\pi x/2$ for $|x|<1$, and a constant for $|x|>1$. Therefore, by taking the derivative w.r.t. $x$, you get back what you started with.

A: The inversion integral can be evaluated as a Cauchy principal value integral
$$
     \lim_{R\rightarrow\infty}\frac{1}{\sqrt{2\pi}}\int_{-R}^{R}\frac{1}{\sqrt{2\pi}}\frac{\sin k}{k}e^{ikx}dk
$$
The above will converge in $L^2(\mathbb{R})$ to the original function, and will converge pointwise to the mean of the left- and right-hand limits of the original function. Because $\sin(k)/k$ is even, the above may be written as
\begin{align}
     &\lim_{R\rightarrow\infty}\frac{1}{\sqrt{2\pi}}\int_{-R}^{R}\frac{1}{\sqrt{2\pi}}\frac{\sin k}{k}\cos(kx)dk \\
    & =\lim_{R\rightarrow\infty}\frac{1}{\pi}\int_{0}^{R}\frac{\sin(k)}{k}\cos(kx)dk \\
    & =\lim_{R\rightarrow\infty}\frac{1}{\pi}\int_{0}^{R}\frac{\sin(k+kx)+\sin(k-kx)}{2k}dk \\
    & =\lim_{R\rightarrow\infty}\frac{1}{2\pi}\left[\int_{0}^{R(1+x)}\frac{\sin(u)}{u}du+\int_{0}^{R(1-x)}\frac{\sin(u)}{u}du\right]
\end{align}
If $x > 1$, the above gives
$$
        \frac{1}{2\pi}\left[\int_{0}^{\infty}\frac{\sin(u)}{u}du+\int_{0}^{-\infty}\frac{\sin(u)}{u}du\right]=0.
$$
The same is true if $x < -1$. If $-1 < x < 1$, the value is
$$
        \frac{1}{2\pi}\left[2\int_{0}^{\infty}\frac{\sin(u)}{u}du\right]
     = \frac{1}{2\pi}\left[2\frac{\pi}{2}\right] = \frac{1}{2}.
$$
For $x=-1$ or $x=1$, the value is $\frac{1}{4}$, which is the mean of the left- and right-hand limits of $\frac{1}{2}\chi_{[-1,1]}$ at $x=\pm 1$.


text:
Q: When I reload solr admin .Error loading class 'solr.SortableIntField' just happend I did the project follow the 'Django by examples',when i adding a search engine with Solr and Haystack,some wrong happend in building indexes.
  When  i run the following command:
python manage.py build_solr_schema

I got the following XML
    <?xml version="1.0" ?>

<!--

 Licensed to the Apache Software Foundation (ASF) under one or more
Save the following output to 'schema.xml' and place it in your Solr configuration directory.
 contributor license agreements.  See the NOTICE file distributed with
--------------------------------------------------------------------------------------------
 this work for additional information regarding copyright ownership.

 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

<schema name="default" version="1.5">
  <types>
    <fieldtype name="string"  class="solr.StrField" sortMissingLast="true" omitNorms="true"/>
    <fieldType name="boolean" class="solr.BoolField" sortMissingLast="true" omitNorms="true"/>
    <fieldtype name="binary" class="solr.BinaryField"/>

It's not complete, and I copy the whole XML to the solr/blog/config/schema.xml
Then I went to http://loaclhost:8984/solr to reload my core
but it's not work

What should I do to resolve it?


text:
Q: Informatica Expression IIF I have this set of codes in my Informatica expression
IIF(V_TR = 'TT'
OR
V_TR = 'TV'
OR
V_TR = 'VC'
OR
V_TR = 'TI'
OR
V_TR = 'TL'
OR
V_TR = 'NC'
OR
V_TR = 'CE'
OR
V_TR = 'D1'
OR
V_TR = 'DM'
OR
V_TR = 'N1'
OR
V_TR = 'NA'
OR
V_TR= 'U1'
OR
V_TR = 'UA', 'Y', 'N')

I know what the code means but what exactly does it do in the expression? DOes it serve as a filter to filter out all these values?

A: Without more context of what the expression and business needs of the expression it will be impossible to give more than guesses.
The 2 main ideas I can think of are:

*

*The Y or N value are used later in a filter transform

*The Y or N value is the desired output value based upon the input ports given the expression.

A: If the input port gets any of the value in OR clause it will return 'Y' else 'N'.


text:
Q: Azure blob storage download to stream returning "" asp.net I am currently trying to download a file from Azure blob storage using the DownloadToStream method to download the contents of a blob as a text string.
However I am not getting anything back but an empty string.
Here is my code that I use to connect to the azure blob container and retrieve the blob file.
    public static string DownLoadFroalaImageAsString(string blobStorageName, string companyID)
    {
        // Retrieve storage account from connection string.
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
            CloudConfigurationManager.GetSetting("StorageConnectionString"));

        // Create the blob client.
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

        // Retrieve reference to a previously created container.
        CloudBlobContainer container = blobClient.GetContainerReference(companyID.ToLower());

        //retrieving the actual filename of the blob
        string removeString = "BLOB/";
        string trimmedString = blobStorageName.Remove(blobStorageName.IndexOf(removeString), removeString.Length);

        // Retrieve reference to a blob named "trimmedString"
        CloudBlockBlob blockBlob2 = container.GetBlockBlobReference(trimmedString);

        string text;
        using (var memoryStream = new MemoryStream())
        {
            blockBlob2.DownloadToStream(memoryStream);
            text = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
        }
        return text;
    }

I was following along this documentation however I cannot seem to get it to work. Any help would be greatly appreciated.

A: If you want to get the text from the blob, you can use DownloadTextAsync()
var text = await blockBlob2.DownloadTextAsync();

If you want to return file stream back to an API respoinse, you can use FileStreamResult which is IActionResult.
var stream = await blockBlob2.OpenReadAsync();
return File(stream, blockBlob2.Properties.ContentType, "name");

A:
However I am not getting anything back but an empty string.

I test your supplied code on my side, it works correctly. I assume that the test blob content is empty in your case. We could trouble shooting with following ways:
1.please have a try to check the Length of memoryStream. If length equal 0 we could know that the blob content is empty.
using (var memoryStream = new MemoryStream())
{
    blockBlob2.DownloadToStream(memoryStream);
    var length = memoryStream.Length;
    text = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
 }

2.We could upload a blob with content to container, we could do that with Azure portal or  Microsoft Azure storage explorer easily. And please have a try test it with uploaded blob.


text:
Q: Apple Automator: where does it store a new filename? I have a line of code (that I can run successfully in Terminal) I'd like to incorporate into an Automator workflow but I can't work out how to reference the filename. I've set up my workflow as a Folder Action and applied it to the correct folder so dragging a new file to that folder triggers the workflow (this part is working correctly).
My line of code is
sudo xattr -rd com.apple.quarantine [PATHNAME_TO_FILE]
It sets the preferences on the file to obviate Apple's quarantine process run by the Logic program, allowing a third-party file to pass muster.
What does Automator want me to use as [PATHNAME_TO_FILE]? I've tried "$@", "$#", "$0", "$1", "$2", etc, etc. but had no luck.

A: If you've set up an Automator workflow as a Folder Action and have added a Run Shell Script action, you'd set Shell: [/bin/bash] and Pass input: [as arguments] and use the following example shell script code:
for f in "$@"
do
    xattr -rd com.apple.quarantine "$f"
done

Note: You should not need to use sudo as you've shown in your OP.

Update to address comment:
If the target of the watched folder is /Library/Audio/Plug-Ins/Components, as in the root of the Macintosh HD, then you'll need to take a different approach.
Set up an Automator workflow as a Folder Action adding a Run AppleScript action, replacing the default code with the example AppleScript code shown below.
Testing under macOS Catalina 10.15.6 the Automator workflow Folder Action, described immediately above, worked for me when adding file(s)/folder(s) to /Library/Audio/Plug-Ins/Components, as in the root of the Macintosh HD.

*

*Note: Upon manually placing file(s)/folder(s) into the target watched folder and authenticating that action, I was then prompted to re-enter my credentials so the do shell script command would run as if using sudo on the command line in Terminal on the xattr command
.

Example AppleScript code:
on run {input}
    set itemList to {}
    repeat with aItem in input
        set end of itemList to quoted form of (POSIX path of aItem) & space
    end repeat
    set shellCMD to "xattr -rd com.apple.quarantine " & itemList as string
    do shell script shellCMD with administrator privileges
end run


text:
Q: How to test significance from GPA v hours worked/week in college survey data? I created a survey and posted on the university meme site, got 200 responses. The goal of this survey was to determine relationship between GPA and hours/week worked in a job for full time uni students. I already filtered out the data to exclude things like jobs which you can study on job vs not, no freshmen, etc. Here is just an initial scatterplot.
What are some tests I can do to test for relations between gpa and hrs/week worked for
1. Both stem and non-stem majors and
2. for differences in dirstribution for non-stem and stem majors?
There's a paper which found students who work 12-15hrs/week have slightly higher grades than those who don't, so I thinking about looking at how they analyzed data. Also thinking about checking out 2D Kolmogorov Smirnov test, if it's applicable.


text:
Q: Formula for calculating weighting percentages given individual grades and final grade I was wondering what the general formula is for calculating the weight (%) of each category in a gradebook given the individual grade for each category and the final grade. For example, lets say category 1 was a 96%, category 2 was a 93% and category 3 was a 89% and the total was 92.7%, what formula could I use to determine that category 1 and 3 were worth 30% and category 2 was worth 40%. I am looking for a formula that scales up, meaning for n categories given individuals and the final grade the weight of each category can be calculated.
Thanks

A: This is exactly what you can do by solving a linear system of equations (LSE). In your example you have three unknowns (the three weights). Now in order to solve for those 3 unknowns you need three equations. Meaning you need at least two other set of grades, where a set is made up of one grade for each category and the final grade.
In linear algebra notation it would look like this:
$$\begin{bmatrix}
g_{11} & g_{12} & g_{13}\\
g_{21} & g_{22} & g_{23}\\
g_{31} & g_{32} & g_{33}
\end{bmatrix}\begin{bmatrix}w1\\
w2\\
w3\end{bmatrix} = \begin{bmatrix}g_{1f}\\g_{2f}\\g_{3f}\end{bmatrix}$$
$$Gw=g_f$$
Where $g_{ij}$ is the grade of the $i$th student and in the $j$th category, $w_j$ is the weight of the $j$th category and $g_{if}$ if the final grade of the $i$th student. Assume the matrix of grades $G$ is invertible, you can calculate the weights $w$ by solving the LSE:
$$w = G^{-1}g_f.$$

A: What you are essentially after is a regression. In mathematical terms, you have
$$\sum w_i x_i = S$$
$$\sum w_i = 1$$
With only this much data, you cannot analytically solve this system. There isn't a unique solution for $n > 2$. Since there isn't a way to solve it analytically, you will have to follow an iterative process so that at the end of each step, the weights refine and bring the sum closer and closer to $S$. Which solution you end up on depends on your initial guess for the weights
Let us consider the function
$$f(\bar{w}) = \sum_{i=1}^nw_ix_i - S$$
We take an initial guess as $w^{(0)}_i = \frac{1}{n} \forall i \in \{1,2...,n\}$
Now,$\nabla f = \bar{x}$
Let the next guess be $\bar{w}^{(1)} = \bar{w}^{(0)} - (\bar{x}^T\bar{x})^{-1}\bar{x}^Tf(\bar{w}^{0})$
And keep refining till you get close to within a given error of $S$


text:
Q: Sql query with dynamic questions outerjoined to a table (need to filter data) I have three tables. A [customer] table, [dynamicquestions] table, and [dynamicanswers] table.
The customer table contains customer submitted data.
The dynamicquestions table contains the dynamic questions the customer needs to answer.
And the dynamicanswers table are the answers the customer submitted. (these answers are keyed to the dynamicquestions table and keyed to the customer table.
What I am doing is dynamically creating unique column names for these dynamic questions. And then pivoting the dynamic answers into the dynamically created column names.
This all works. My problem, is I want to filter and a customer that has submitted an answer to two dynamic questions.
for example: if there are dynamic questions "how old are you" and "what state do you live in". I want to get everyone that answered "30" and "Texas".
Below is an example query with an "OR statement But I need it to be some sort of "Get both if the customer answered "30" and "Texas".
DECLARE @docDates VARCHAR(MAX)
SELECT @docDates = STUFF((
SELECT DISTINCT ', ' + QUOTENAME(CONVERT(varchar, REPLACE(QAPanelName,'QA_','')) + CONVERT(varchar, LEN(Orderbynumber)) + CONVERT(varchar, Orderbynumber) + CONVERT(varchar, ControlID) + '_' + QuestionColumnName)
FROM DynamicAnswers RIGHT OUTER JOIN DynamicQuestions ON DynamicAnswers.FK_Answers_ControlID = DynamicQuestions.ControlID
WHERE FK_DynamicQuestions_Topic = 56
ORDER BY ', '  + QUOTENAME(CONVERT(varchar, REPLACE(QAPanelName,'QA_','')) + CONVERT(varchar, LEN(Orderbynumber)) + CONVERT(varchar, Orderbynumber) + CONVERT(varchar, ControlID) + '_' + QuestionColumnName)
FOR XML PATH('')
)
, 1, 1, '')

--------------------------------------------

DECLARE @sql NVARCHAR(MAX)

SET @sql = 'SELECT DISTINCT * FROM (SELECT  Country,eMail,ShortTalk,InvoiceNum, CONVERT(varchar, REPLACE(QAPanelName,''QA_'','''')) + CONVERT(varchar, LEN(Orderbynumber)) + CONVERT(varchar, Orderbynumber) + CONVERT(varchar, ControlID) + ''_'' + QuestionColumnName AS FK_Answers_ControlID, DynamicAnswers.Answer
FROM             customer LEFT OUTER JOIN DynamicQuestions INNER JOIN DynamicAnswers ON DynamicQuestions.ControlID = DynamicAnswers.FK_Answers_ControlID
                 ON DynamicAnswers.FK_Answers_customer = customer.InvoiceNum
WHERE( DynamicQuestions.FK_DynamicQuestions_Topic = 56  AND  (Deleted = 0 AND customer.SubmissionConfirmed = 1  AND FK_customer_Topic = 56  AND (Cancelled = 0)  AND ( (DynamicQuestions.ControlID = 42 AND DynamicAnswers.Answer = ''30'')  OR (DynamicQuestions.ControlID = 43 AND DynamicAnswers.Answer = ''Texas'') ) AND FK_DynamicQuestions_Topic = 56 ) )) AS[SubTable]
PIVOT
(
MAX(Answer)
FOR[FK_Answers_ControlID] IN(' + @docDates + ')
) AS[Pivot]; '
EXEC sp_executesql @sql


text:
Q: Android Theme.NoTitleBar doesnot work I am have a facebook like sliding menu bar in my app in which the two content and main layout of the app is handled by a Custom layout class.
I want to remove the titlebar of my app
Issue:
Even though I place

android:Theme.Light.NoTitleBar

in my manifest there is a blank space of title bar. Due to which my whole layout is pushed downwards.
I have tried using

requestWindowFeature(Window.FEATURE_NO_TITLE);

and

getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

but still the titlebar space is not removed.
This is how the app looks like

I think this is caused due to the Custom LinearLayout class which holds the main sliding layout. But I am unable to remove the titlebar space from the custom layout class.
Suggest a better solution.
Custom Layout Class
   public class MainLayout extends LinearLayout {
        public MainLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
        public MainLayout(Context context) {
            super(context);
        }

        // Overriding LinearLayout core methods
        // layout based on the children
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);

            mainLayoutWidth = MeasureSpec.getSize(widthMeasureSpec);
            menuRightMargin = mainLayoutWidth * 10 / 100;
        }

        @Override
        protected void onAttachedToWindow() {
            super.onAttachedToWindow();
            menu = this.getChildAt(0);
            content = this.getChildAt(1);
            content.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    return MainLayout.this.onContentTouch(v, event);
                }
            });

@Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        if(changed) {
           LayoutParams contentLayoutParams = (LayoutParams)content.getLayoutParams();
            contentLayoutParams.height = this.getHeight();
            contentLayoutParams.width = this.getWidth(); LayoutParams menuLayoutParams = (LayoutParams)menu.getLayoutParams();
        menuLayoutParams.width = this.getWidth() - menuRightMargin;
        }

        menu.layout(left, top, right - menuRightMargin, bottom);
        content.layout(left + contentXOffset, top, right + contentXOffset, bottom);

      }
     }

A: u can specify directly in the manifest file of the activity
<activity android:name=".MainActivity"
      android:label="@string/app_name"
      android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen">

A: Finally I was able to remove the titlebar space.
As it turns out, including this tag
android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen"

on application in manifest made the app fullscreen and corrected the issue. But I wanted the status bar to be visible in my app.
So I had to compromise the status bar on the android versions in which the titlebar space was not reduced and let it be same on other versions.
So here is how I resolved it.
in Manifest, I kept the code as it is
android:theme="@android:style/Theme.Light.NoTitleBar"

to remove the titlebar in the app
and in the activity which used the custom linear layout I checked the android version and kept the app fullscreen on versions less than and equal to Gingerbread.
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD)
{
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}

A: Try this in your manifest file
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"

A: Add the android:theme property to your AndroidManifest.xml:
       <application android:theme="@android:style/Theme.NoTitleBar">

A: Hope this may help you.
this.requestWindowFeature(Window.FEATURE_NO_TITLE);

// Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);

A: It seems that Theme.NoTitleBar only works when applied to the whole application, not the activity itself. So put it in the application tag (in the manifest):
<application android:theme="@android:style/Theme.NoTitleBar">

Then, add any custom style you have to each activity.
Hope it helps.

A: In value\style.xml
define name and themes
e.g,

Then goto your androidmainfest.xml
add within activity like..
   android:theme="@style/NoActionBar"


text:
Q: Why is empty weak_ptr required to store null pointer, while empty shared_ptr is allowed to store non-null pointer? Naive thinking
I expected the following assertion (1) to hold true for every valid value of original argument:
#include <memory>
#include <cassert>

void foo(std::shared_ptr<int> original)
{
    std::weak_ptr<int>    weak{original};
    std::shared_ptr<int>  restored{weak.lock()};  // lock() explicitly to avoid exception

    assert( restored == original );         // (1)
}

In other words, I thought that weak_ptr is supposed to be able to store the value of a shared_ptr in non-owning manner and then restore that original value later, when locked. Assuming the pointed object is still alive, of course.
Reality
Obviously I was wrong, as the following test turned out to fail the assertion:
void test()
{
    int                       x = 42;
    std::shared_ptr<int>      empty_but_nonnull{std::shared_ptr<char>{}, &x};
    foo(empty_but_nonnull);
}

Wording and test explained
shared_ptr can own one object, but store a pointer to some other object.
shared_ptr is called empty if it owns no object.
shared_ptr is called null if it points to no object.
A shared_ptr can be empty, but non-null. Such behavior is explicitly mentioned and allowed by the standard:

[util.smartptr.shared.const]:
17. [Note 2: This constructor allows creation of an empty shared_ptr instance with a non-null stored pointer.
— end note]

Empty but non-null shared_ptr can be dereferenced, it is implicitly converted to true in conditional expressions, etc. No mention of the program being ill-formed whatsoever. So it seems to be perfectly legit and usable. It just says: "I'm pointing to an object that doesn't require any lifetime management, possibly to a global object with static storage duration, so what?".
However, an empty weak_ptr cannot be non-null. It is explicitly required by the standard to be null (emphasis mine):

[util.smartptr.weak.const]:
4. template<class Y> weak_ptr(const shared_ptr<Y>& r) noexcept;
Effects: If r is empty, constructs an empty weak_ptr object that stores a null pointer value

Which means that constructing a weak_ptr from an empty shared_ptr loses the pointer stored in original shared_ptr, forcing every empty weak_ptr to be null. After that, any attempt to reconstruct the original shared_ptr would obviously fail.
The Question
What's the rationale behind the emphasized part of the quoted clause on weak_ptr? Why shouldn't weak_ptr store the same pointer as the original shared_ptr?
It's just that my original naive thinking doesn't seem that illogical to me...

Edit: Example edited to eliminate any possible exception and undefined behavior.

A: shared_ptr<T> hold a pointer to a T and owns some object of type U which may or may not be the same as T. This feature exist to allow the shared_ptr<T> to point to some object that is a component of the U object that it owns. For example, you can create a shared_ptr<derived_class> and convert it to a shared_ptr<base_class> while still owning a derived_class. Or you can have a shared_ptr<some_struct> and create a shared_ptr<some_structs_member> which still owns a some_struct. Being able to do these things is the feature's purpose.
You will note that in the above cases, the object being pointed to is owned by the object being owned. That is, if the owned U object is destroyed, the T pointer held by the shared_ptr is no longer valid.
weak_ptr<T> is not a tool that is meant to be used to reconstitute a shared_ptr<T>. It is a tool that has one purpose: if a shared_ptr still exists which owns the memory weakly owned by the weak_ptr<T>, then you may extract a shared_ptr<T> from it.
weak_ptr<T>::lock does not care about the T pointer (it does preserve it, but it doesn't care about it); it only cares about ownership. Successfully locking a weak_ptr means that the object being managed is still alive. And the only definition of "successfully locking" is whether the shared_ptr<T> is nullptr. With the exception of use_count there is no observable difference between a non-null shared_ptr<T> that owns a U and a non-null shared_ptr<T> that doesn't own a U.
Remember: the expectation is that the T being stored is an object that is owned by U. Therefore, if a weak_ptr<T> is going to claim weak ownership over a shared_ptr<T>, and it finds that the shared_ptr<T> does not own anything... it assumes that the T is also destroyed. Because that's what the feature is for.
Now, could the constructor of shared_ptr<T> from a shared_ptr<U> also check to see if the shared_ptr<U> it is given actually owns something and throw an exception in that case? It could, but C++ is not a safe language. Furthermore, the only exceptions shared_ptr<T> constructors emit (other than implementation-defined ones) are from failure to allocate memory or failure to lock a weak_ptr<T>.
So at the end of the day, the standard assumes you know what you're doing when creating the shared_ptr.


text:
Q: Sypder 5.0.1 fails to load when launching Spyder, it shows the loading screen but eventually it stops and I get the following error message. Any ideas?
No QCoreApplication instance found. Application patches not applied. You have to call load_stylesheet function after instantiation of QApplication to take effect.
Traceback (most recent call last):
  File "/home/hagymasbab/.local/lib/python3.9/site-packages/spyder/app/mainwindow.py", line 2161, in create_window
    main.setup()
  File "/home/hagymasbab/.local/lib/python3.9/site-packages/spyder/app/mainwindow.py", line 903, in setup
    plugin_instance = plugin_class(self, configuration=CONF)
  File "/home/hagymasbab/.local/lib/python3.9/site-packages/spyder/api/plugins.py", line 1405, in __init__
    super().__init__(parent, configuration=configuration)
  File "/home/hagymasbab/.local/lib/python3.9/site-packages/spyder/api/plugins.py", line 826, in __init__
    self._container = container = self.CONTAINER_CLASS(
  File "/home/hagymasbab/.local/lib/python3.9/site-packages/spyder/plugins/console/widgets/main_widget.py", line 122, in __init__
    self.shell = InternalShell(  # TODO: Move to use SpyderWidgetMixin?
  File "/home/hagymasbab/.local/lib/python3.9/site-packages/spyder/plugins/console/widgets/internalshell.py", line 153, in __init__
    super().__init__(parent, get_conf_path('history_internal.py'),
  File "/home/hagymasbab/.local/lib/python3.9/site-packages/spyder/plugins/console/widgets/shell.py", line 665, in __init__
    ShellBaseWidget.__init__(self, parent, history_filename,
  File "/home/hagymasbab/.local/lib/python3.9/site-packages/spyder/plugins/console/widgets/shell.py", line 75, in __init__
    self.history = self.load_history()
  File "/home/hagymasbab/.local/lib/python3.9/site-packages/spyder/plugins/console/widgets/shell.py", line 503, in load_history
    if rawhistory[1] != self.INITHISTORY[1]:
IndexError: list index out of range

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/hagymasbab/.local/bin/spyder", line 8, in <module>
    sys.exit(main())
  File "/home/hagymasbab/.local/lib/python3.9/site-packages/spyder/app/start.py", line 213, in main
    mainwindow.main(options, args)
  File "/home/hagymasbab/.local/lib/python3.9/site-packages/spyder/app/mainwindow.py", line 2311, in main
    mainwindow = create_window(app, splash, options, args)
  File "/home/hagymasbab/.local/lib/python3.9/site-packages/spyder/app/mainwindow.py", line 2163, in create_window
    if main.console is not None:
  File "/home/hagymasbab/.local/lib/python3.9/site-packages/spyder/app/mainwindow.py", line 1180, in __getattr__
    return self.get_plugin(self._INTERNAL_PLUGINS_MAPPING[attr])
  File "/home/hagymasbab/.local/lib/python3.9/site-packages/spyder/app/mainwindow.py", line 169, in get_plugin
    raise SpyderAPIError(
spyder.api.exceptions.SpyderAPIError: Plugin "internal_console" not found!

Versions: Spyder: 5.0.1, pyqt5: 5.12.3
Please mind that this is NOT the latest version of pyqt5. However, if I upgrade it to 5.15.4, Spyder won't even start loading, it dies with this:
Traceback (most recent call last):
  File "/usr/local/lib/python3.9/dist-packages/qtpy/QtWebEngineWidgets.py", line 22, in <module>
    from PyQt5.QtWebEngineWidgets import QWebEnginePage
ImportError: libQt5QuickWidgets.so.5: cannot open shared object file: No such file or directory

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/hagymasbab/.local/bin/spyder", line 8, in <module>
    sys.exit(main())
  File "/home/hagymasbab/.local/lib/python3.9/site-packages/spyder/app/start.py", line 209, in main
    from spyder.app import mainwindow
  File "/home/hagymasbab/.local/lib/python3.9/site-packages/spyder/app/mainwindow.py", line 60, in <module>
    from qtpy import QtWebEngineWidgets  # analysis:ignore
  File "/usr/local/lib/python3.9/dist-packages/qtpy/QtWebEngineWidgets.py", line 26, in <module>
    from PyQt5.QtWebKitWidgets import QWebPage as QWebEnginePage
ModuleNotFoundError: No module named 'PyQt5.QtWebKitWidgets'

I'm using the latest version of qtpy (1.9.0).
EDIT:
Here is the output of the ldd command:
linux-vdso.so.1 (0x00007ffd139c9000)
libQt5Quick.so.5 => /home/hagymasbab/.local/lib/python3.9/site-packages/PyQt5/Qt5/lib/libQt5Quick.so.5 (0x00007f72ed4b6000)
libQt5QmlModels.so.5 => /home/hagymasbab/.local/lib/python3.9/site-packages/PyQt5/Qt5/lib/libQt5QmlModels.so.5 (0x00007f72ed236000)
libQt5Qml.so.5 => /home/hagymasbab/.local/lib/python3.9/site-packages/PyQt5/Qt5/lib/libQt5Qml.so.5 (0x00007f72ecbba000)
libQt5Widgets.so.5 => /home/hagymasbab/.local/lib/python3.9/site-packages/PyQt5/Qt5/lib/libQt5Widgets.so.5 (0x00007f72ec358000)
libQt5Gui.so.5 => /home/hagymasbab/.local/lib/python3.9/site-packages/PyQt5/Qt5/lib/libQt5Gui.so.5 (0x00007f72eba27000)
libQt5Network.so.5 => /home/hagymasbab/.local/lib/python3.9/site-packages/PyQt5/Qt5/lib/libQt5Network.so.5 (0x00007f72eb677000)
libQt5Core.so.5 => /home/hagymasbab/.local/lib/python3.9/site-packages/PyQt5/Qt5/lib/libQt5Core.so.5 (0x00007f72eae81000)
libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f72eae36000)
libGL.so.1 => /usr/lib/x86_64-linux-gnu/libGL.so.1 (0x00007f72eadaf000)
libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f72eabe2000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f72eaa9e000)
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f72eaa82000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f72ea8bd000)
librt.so.1 => /lib/x86_64-linux-gnu/librt.so.1 (0x00007f72ea8b2000)
libz.so.1 => /lib/x86_64-linux-gnu/libz.so.1 (0x00007f72ea895000)
libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f72ea88f000)
libgssapi_krb5.so.2 => /usr/lib/x86_64-linux-gnu/libgssapi_krb5.so.2 (0x00007f72ea83a000)
libicui18n.so.56 => /home/hagymasbab/.local/lib/python3.9/site-packages/PyQt5/Qt5/lib/libicui18n.so.56 (0x00007f72ea3a1000)
libicuuc.so.56 => /home/hagymasbab/.local/lib/python3.9/site-packages/PyQt5/Qt5/lib/libicuuc.so.56 (0x00007f72e9fe9000)
libicudata.so.56 => /home/hagymasbab/.local/lib/python3.9/site-packages/PyQt5/Qt5/lib/libicudata.so.56 (0x00007f72e8606000)
libgthread-2.0.so.0 => /usr/lib/x86_64-linux-gnu/libgthread-2.0.so.0 (0x00007f72e8601000)
libglib-2.0.so.0 => /usr/lib/x86_64-linux-gnu/libglib-2.0.so.0 (0x00007f72e84d0000)
/lib64/ld-linux-x86-64.so.2 (0x00007f72ede01000)
libGLdispatch.so.0 => /usr/lib/x86_64-linux-gnu/libGLdispatch.so.0 (0x00007f72e8418000)
libGLX.so.0 => /usr/lib/x86_64-linux-gnu/libGLX.so.0 (0x00007f72e83e4000)
libkrb5.so.3 => /usr/lib/x86_64-linux-gnu/libkrb5.so.3 (0x00007f72e830a000)
libk5crypto.so.3 => /usr/lib/x86_64-linux-gnu/libk5crypto.so.3 (0x00007f72e82da000)
libcom_err.so.2 => /lib/x86_64-linux-gnu/libcom_err.so.2 (0x00007f72e82d4000)
libkrb5support.so.0 => /usr/lib/x86_64-linux-gnu/libkrb5support.so.0 (0x00007f72e82c3000)
libpcre.so.3 => /lib/x86_64-linux-gnu/libpcre.so.3 (0x00007f72e8250000)
libX11.so.6 => /usr/lib/x86_64-linux-gnu/libX11.so.6 (0x00007f72e810d000)
libkeyutils.so.1 => /lib/x86_64-linux-gnu/libkeyutils.so.1 (0x00007f72e8106000)
libresolv.so.2 => /lib/x86_64-linux-gnu/libresolv.so.2 (0x00007f72e80ec000)
libxcb.so.1 => /usr/lib/x86_64-linux-gnu/libxcb.so.1 (0x00007f72e80bf000)
libXau.so.6 => /usr/lib/x86_64-linux-gnu/libXau.so.6 (0x00007f72e80ba000)
libXdmcp.so.6 => /usr/lib/x86_64-linux-gnu/libXdmcp.so.6 (0x00007f72e7eb4000)
libbsd.so.0 => /usr/lib/x86_64-linux-gnu/libbsd.so.0 (0x00007f72e7e9d000)
libmd.so.0 => /usr/lib/x86_64-linux-gnu/libmd.so.0 (0x00007f72e7e90000)

A: Problem solved! After issuing
spyder --reset

it loads again flawlessly. Still no idea, why...


text:
Q: Message part request was not recognized I have developed a Webservice . It was working fine with SOAP UI
When the client tested it through APIGEE , it started giving
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
      <soap:Fault>
        <faultcode>soap:Client</faultcode>
        <faultstring>Message part request was not recognized.  (Does it exist in service WSDL?)</faultstring>
      </soap:Fault>
  </soap:Body>
</soap:Envelope>

Could anybody please tell me what might cause this ??

A: I am not sure, I got to this page googling for facing the same issue, the only answer I have found is here: http://prystash.blogspot.co.uk/2010/06/wsdls-and-message-parts-not-recognized.html, quoting:

The element declaration contained a reference to a complexType
  instead of having the complexType defined within, or as part of, the
  element declaration.


text:
Q: foursquare authorize url is not loading in android webview My login webview is not loading in android.But months ago it was fine.
 I also wrote a project for accessing foursquare from android.
 https://github.com/goutomroy/DroidSquare/blob/master/README.md
 When I am trying to load webview, I found message :
 "The connection to the server was unsuccessful"
 Where is my fault ?
@SuppressLint("SetJavaScriptEnabled")
private void setUpWebView() {

    String URL_LOGIN = "https://foursquare.com/oauth2/authenticate?"
            + "client_id="+ FoursquareConstants.CLIENT_ID
            + "&response_type=code"
            + "&display=touch"
            + "&redirect_uri=" + FoursquareConstants.URL_CALLBACK;

    CookieSyncManager.createInstance(activity);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.acceptCookie();
    cookieManager.removeAllCookie();

    webView = new WebView(getContext());
    WebSettings settings = webView.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setDomStorageEnabled(true);
    settings.setLoadWithOverviewMode(true);
    settings.setUseWideViewPort(true);
    settings.setBuiltInZoomControls(true);
    settings.setPluginState(PluginState.ON);
    webView.setVerticalScrollBarEnabled(true);
    webView.setHorizontalScrollBarEnabled(true);
    webView.setWebViewClient(new FoursquareWebViewClient());
    webView.loadUrl(URL_LOGIN);
    setContentView(webView);
}

 class FoursquareWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        return false;
    }
    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        Log.d("onReceivedError", errorCode +" : "+description+ " : " + failingUrl);
        super.onReceivedError(view, errorCode, description, failingUrl);

        dismissProgressDialog();
        LoginDialog.this.dismiss();
        responseHandler.onError(description);
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {

        Log.d("onPageStarted", url);
        super.onPageStarted(view, url, favicon);

        if(flag)
            return;
        else if (url.startsWith(FoursquareConstants.URL_CALLBACK)) {
            flag = true;
            String urls[] = url.split("=");
            responseHandler.onSuccess(urls[1]);
            LoginDialog.this.dismiss();
            return;
        }

        else
            showOrUpdateProgressDialog("Loading...");

    }

    @Override
    public void onPageFinished(WebView view, String url) {
        Log.d("onPageFinished", url);
        super.onPageFinished(view, url);

        dismissProgressDialog();
    }

     @Override
     public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
         Log.d("onReceivedSslError", "error");
         handler.proceed(); // Ignore SSL certificate errors
     }
}

A: You should check for the internet permission at manifest file
<manifest xlmns:android...>
...
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>


text:
Q: how do i combine variables? im making a program and i need to combine a lot of variables, most of them strings but i have some int, by doing this
name = "#{variable1}#{variable2}"
name2 = "#{variable2}#{variable1}"

it´s a simple example with just two variables but thats the idea, what im trying to make. i am doing all the possibilities one by one, even when is more than two variables but there are many combinations. Is there an easy way to do it or i have to do it one by one?Also, do i need to write the quotation marks separately or that way is fine?

A: Is this what you had in mind?
variable1 = "cat"
variable2 = 9
variable3 = "lives"
arr = [variable1, variable2, variable3]
  #=> ["cat", 9, "lives"]
arr.join
  #=> "cat9lives"

A: Put all or some of these variables into an array which will produce the combinations easier.
s1 = 'a'
s2 = 'b'
s3 = 'c'
 n = 8
[s1, s2, s3, n].combination(3).map(&:join)
=> ["abc", "ab8", "ac8", "bc8"]

Above example assumes that you will pick any of 3 variables from the array and calculate the combinations. You may want to adjust that number to meet your needs.

A: The whole idea of programming is not doing all possibilities one by one. "there are many combinations": they look like permutations to me. If that is the case:
var1 = "aa"
var2 = "bb"
var3 = 2

res = [var1, var2, var3].permutation.map{|perm| perm.join}
p res #=> ["aabb2", "aa2bb", "bbaa2", "bb2aa", "2aabb", "2bbaa"]


text:
Q: Android - How to call sounds from imageViews correctly with a method? I just try to play some sounds in android studio by clicking on pictures (imageViews).
I gave each picture a tag in the xml file:
<ImageView
            android:id="@+id/imageView3"
            android:onClick="playPhrase"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:tag="internet"
            app:srcCompat="@drawable/rouven" />

In the main Activity i have this code but it keeps crashing:
public class MainActivity extends AppCompatActivity {

    public void playPhrase(View view) {
        Button buttonPressed = (Button) view;
        Log.i("Button pressed", buttonPressed.getTag().toString());
        MediaPlayer mediaPlayer = MediaPlayer.create(this,
                getResources().getIdentifier(buttonPressed.getTag().toString(),
                "raw", getPackageName()));
        mediaPlayer.start();
    }
}

Can't i call this method like that? How to solve that? Im a beginner :-)
Thanks for your help
Carlo

A: 1   put a music  file to the /res/raw , such as in.wav, in.mp3 media file (here name it as in)
2   change the code to:
 public void playPhrase(View view) {
    MediaPlayer mediaPlayer = MediaPlayer.create(this,
                R.raw.in);
    mediaPlayer.start();
}


text:
Q: apt-get upgrade to a certain state Let's say I have two servers, a test server and a production server. First I do apt-get upgrade on the test server. Then after extensive testing two weeks later I want the production server to be at the exact same state packagewise. Is it possible to somehow apt-get upgrade to a certain state instead of always latest?

A: OP didn't tell what distribution on the server is in use. So by default I'll consider it's Debian since apt was "invented" by Debian, and the needed service is only available for Debian.
While for a single package forcing the version with = is fine and handy especially to revert it (if still available), for a collection of packages it can quickly become a nightmare because of unmet dependencies.
What can be done is to use a repository URL built from https://snapshot.debian.org/. This service holds a copy of all package versions made since 2009 and is officially available since 2010:

The snapshot service also enables administrators to install a
  predictable, tested set of packages by using a view of the archive on
  a given date. This feature allows administrators to test an upgrade
  path in a staging environment and then repeat the procedure in their
  production environment with assurance that they are performing exactly
  the tested upgrade. As the snapshot covers the entire archive and all
  suites this can be applied to environments that wish to track testing
  in a controlled manner as well as those with more stringent change
  control who wish to fully audit all stable updates before rolling them
  out.

A first requirement is to have https transport available: apt-get install apt-transport-https (sorry it might pull a few dependencies which might have been upgraded meanwhile).
Let's suppose you want the packages from two weeks ago, ie 2018-12-07. Following the instructions on the site, you can browse:
https://snapshot.debian.org/archive/debian/20181207/

Which will point to a more fine-tuned URL, probably in UTC time. You can then navigate there "through time" to suit your needs, probably with a few "next change".
Once the time is fine, just use this as a base deb URL., in a sources.list file:
eg /etc/apt/sources.d/snapshot-20181207.list with for example content:
deb https://snapshot.debian.org/archive/debian/20181207T090635Z/ stretch main

Since the snapshots are in the past, with older package versions, if the default choice is left to apt, it will use newer versions anyway instead and always ignore those available there. the -t flag of apt is of no use for this, because it's still the same release. So apt's preferences have to be tweaked. Have an entry in a file ending in .pref in /etc/apt/preferences.d/, eg /etc/apt/preferences.d/00-snapshot-20181207.list (order of preferences can matter here):
Package: *
Pin: origin "snapshot.debian.org"
Pin-Priority: 900

This will put all packages from snapshot.debian.org at priority 900 which is higher than 500 for default (and newer) packages, giving it priority over other repositories, including security which is the main source of updates in a short time lapse. Since it's still lower priority than when adding -t stable, one can compare the difference between the upgrade to the state at 2018-12-07 or to today.
Using 1001 would even allow (and force) to downgrade packages, which can be dangerous (eg, but not limited to: when a file was moved from a package to an other due to packaging changes, this file can be lost when downgrading) but can still be useful.
If apt-get update complains about an expired Release file, which it will after 12 days, as explained on the site, you'll have to either use apt-get -o Acquire::Check-Valid-Until=false update or (since Debian 9) add a [check-valid-until=no] in the source entry, to disable the check. That's why https transport is used: to have an other security layer anyway. So replace contents of snapshot-20181207.list with:
deb [check-valid-until=no] https://snapshot.debian.org/archive/debian/20181207T090635Z/ stretch main

UPDATE: security is in a separate snapshot archive: debian-security. So this entry (or one to an other date) should also be added:
deb [check-valid-until=no] https://snapshot.debian.org/archive/debian-security/20181206T212649Z/ stretch/updates main

Now, doing the usual apt-get update and apt-get upgrade should upgrade all packages to the 2018-12-07 versions.

A: Yes, this is possible. See https://askubuntu.com/questions/92019/how-to-install-specific-ubuntu-packages-with-exact-version
In short, if you want to upgrade foo to version 2.5, instead of running apt upgrade foo, you would run apt upgrade foo=2.5
This means you will want to get a dump of the installed versions on your test server, then use that information to get the production server to the same state.


text:
Q: How to delete image from Firebase Storage? Can you help delete an image from Firebase Storage. String deleteImage holds the full url of where the image is located in the Firebase storage.
My code is as follows, but it does not delete the image:
StorageReference deleteFile = storageReference.child(deleteImage);
            deleteFile.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    Toast.makeText(EditProfile.this, "Previous Image Deleted", Toast.LENGTH_SHORT).show();
                }
            });

A: You need to use this method call:
StorageReference photoRef = mFirebaseStorage.getReferenceFromUrl(mImageUrl);

Then delete as you were:
photoRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
    @Override
    public void onSuccess(Void aVoid) {
        // File deleted successfully
        Log.d(TAG, "onSuccess: deleted file");
    }
    }).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        // Uh-oh, an error occurred!
        Log.d(TAG, "onFailure: did not delete file");
    }
});

A: Use the function getReferenceFromUrl(URL)
FirebaseStorage firebaseStorage = FirebaseStorage.getInstance();
                    StorageReference storageReference = firebaseStorage.getReferenceFromUrl(pd.getUrl());
                    storageReference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            Log.e("Picture","#deleted");
                        }
                    });


text:
Q: Why does Windows' performance degrade over time even when it isn't used? I know that similar questions have been asked before (like this and this), but none of them answer my question. My problem is, as stated in the title, that when Windows isn't in use (some months) its performance degrades. (Boot time goes from ½ minute to 2 minutes) If I boot Windows every day for a week, the boot time shrinks, but I have disabled defragmentation.
The other answers indicate that it might be fragmentation or bit rot. I know for sure that i can't be fragmentation since the hard drive is not use when not booting Windows (except for benchmarking from Linux). However, when benchmarking the drive under Linux (always booting from a separate drive), the drive's performance doesn't drop over time.
Edit:
The computer I described in the question runs Windows 8, however I've also experienced this on Windows 7.

A: Windows uses something called prefetch which is basically a cache of the process you use the most. If it were to expire, Windows would have to build it from scratch again.
I personally haven't experienced something like this, I use Windows roughtly once every month and it takes the same time to boot always and the performance once it's loaded is the same (it's Windows 8.1 though, I don't exactly know the inner workings of it or prefetch).


text:
Q: will float or floats? What's the difference between 1 and 2 below?

1. Oil will float on water.
2. Oil floats on water.

The Longman Dictionary of Contemporary English says of the first "used to say what always happens in a particular situation or what is generally true". How then does it differ from the second in terms of meaning and use?

A: In CGEL, Huddleston & Pullum actually address this issue, under Dynamic modality – Propensity:

Oil will float on water
Here we are concerned with characteristic or habitual behaviour of
  animates or general properties of inanimates. A simple present could
  be substituted with little effect: this usage is therefore fairly
  sharply distinct from futurity, though in many cases there is a
  connection through conditional circumstance.... [If s]trong stress [is
  put] on the auxiliary [it] conveys the speaker's emotive response to
  the situation – usually exasperation, disapproval, resignation ...

A: They are essentially interchangeable.  There is a subtle difference, however.
"Oil will float on water" is sometimes used to mean that the fact is sometimes true but not always.
For example, "The wolf is a carnivore, but in times of famine, the wolf will eat berries".
The second form, "oil floats on water," doesn't allow for that possibility.


text:
Q: Ubuntu 18.04 mouse freezing every now and then I am having a major problem, mouse freezes every now and then for few seconds until some event occurs, soon some event occurs mouse resumes then again after some time it freezes, my mouse is logitech wireless, laptop Dell.
Steps I tried,

*

*Dist Upgrade.


text:
Q: Approximation of integral using series expansion of the integrand. I have a smooth function $x \rightarrow f_\epsilon (x)$ on $x\in[-1\ldots 1]$ (dependent on the continuous parameter $\epsilon$) and I want to approximate the integral
$$
    I=\int_{-1}^1 f_\epsilon (x) dx
$$
Assume I know the analytic (and finite) values of the integrals
$$
    I_0=\int_{-1}^1 f_0 (x) dx
$$
and
$$
    I_i=\int_{-1}^1 f_{\epsilon,i} (x) dx
$$
where $f_{\epsilon,i}$ is the $i$th term in a series expansion of $f_{\epsilon}$ about $x=0$, i.e.
$$
    f_{\epsilon}(x) = \sum_{i=1}  f_{\epsilon,i}(x)
$$
Since $x=-1\ldots 1$, the expansion in $x$ is not necessarily a good one. But assume the $f_{\epsilon,i}$ are such that the series of $I_i$ converges (for all $\epsilon$) continuously against $I$ nevertheless.
The convergence of $I$ (depending on $\epsilon$) can be slow, however. To which extent can I use the additional knowledge of $I_0$ to improve an approximation of $I$ based on a finite number of terms of it's expansion. The goal is to have a continuous approximation of $I$ as a function of $\epsilon$.
For clarity consider the example
$$
    f_\epsilon (x) = \frac{1}{\sqrt{1+\epsilon-x}}
$$
where $\epsilon >0$.
I get a (finite) series expansion (expanding $f_\epsilon$ about $x=0$ and integrating)
$$
    J(\epsilon) = \frac{1}{64 (1+\epsilon)^{9/2}}(151+544\epsilon+784\epsilon^2+512\epsilon^3+128\epsilon^4)
$$
In this case I also know the full $I$ (for comparison):
$$
    I(\epsilon) = 2\left[\sqrt{2+\epsilon}-\sqrt{\epsilon}\right]
$$
and the result for $\epsilon=0$:
$$
    I_0 = 2\sqrt{2}
$$
The convergence is bad for small values of $\epsilon$
I can however construct approximations which are exact at $\epsilon =0$ and have good convergence for large $\epsilon$
$$
    I = g(\epsilon) I_0 (\epsilon) + (1-g(\epsilon)) J(\epsilon)
$$
where $0\leq g(\epsilon)\leq 1$ with $g(0)=1$ and $g(\infty)=0$ is a continuous function of $\epsilon$. However there is a lot of freedom in the choice of $g$. So I wonder if I can construct $g$ such that it yields (fast) convergence for all $\epsilon$, if I increase the number of terms in the series contribution $J$.


text:
Q: What is the maximum error? Three positive numbers, each less than 100 are rounded to the first decimal place and then multiplied together, using differential, how I estimate the maximum error?

A: Say that your numbers are $x,y,z$ and they are multiplied together so $A=x y z$. To me the simplest way is to go through logarithmic differentiation to get $$\frac {\Delta A}{A}=\frac {\Delta x}{x}+\frac {\Delta y}{y}+\frac {\Delta z}{z}$$ and the maximum relative error on $A$ will correspond to $$\left|\frac{\text{$\Delta $x}}{x}\right|+\left|\frac{\text{$\Delta $y}}{y}\right|+\left|\frac{\text{$\Delta $z}}{z}\right|$$ From what you said,$\Delta x=\Delta y=\Delta y=0.05$ (numbers rounded to the fist decimal place). So it seems to me that the maximum error on $A$ is given by $$(\Delta A)_{max}=0.05(xy+xz+yz)$$


text:
Q: How to send data between two Android-devices without server through the Internet? Is there any way to communicate between Android devices directly?  How to implement Server-type node on clients side?

A: If you are talking about p2p connections using wifi and/or hotspot of the phone, the link below may help:
https://developer.android.com/guide/topics/connectivity/wifip2p.html


text:
Q: Find the length x such that the two distances in the triangle are the same I have been working on the following problem
Statement

Assume you have a right angle triangle $\Delta ABC$ with cateti $a$, $b$ and hypotenuse $c = \sqrt{a^2 + b^2}$. Find or construct a point $D$ on the hypothenuse such that the distance $|CD| = |DE|$, where $E$ is positioned on $AB$ in such a way that $DE\parallel BC$ ($DE$ is parallel to $BC$).

Background
My background for wanting such a distance is that I want to create a semicircle from C onto the line $AB$. This can be made clearer in the image below

To be able to make sure the angles is right, I needed the red and blue line to be of same length. This lead to this problem
Solution
Using similar triangles one arrives at the three equations
$$
\begin{align*}
\frac{\color{blue}{\text{blue}}}{a - x} & = \frac{b}{a} \\
\frac{\color{red}{\text{red}}}{x} & = \frac{c}{a} \\
\color{red}{\text{red}} & = \color{blue}{\text{blue}}
\end{align*}
$$
Where one easily can solve for $\color{blue}{\text{blue}}$, $\color{red}{\text{red}}$, $x$.
Question
I feel my solution is quite barbaric and I feel that there is a better way to solve this problem. Is there another shorter, better, more intuitive solution. Or perhaps there exists a a way to construct the point $D$ in a simpler matter?

A:
Let the angle bisector of $\angle ACB$ intersect side $\overline{AB}$ at point $E$.
Let the measure of $\angle ACB$ be $\alpha$.
Then $m \angle ACE = \dfrac{\alpha}{2}$.
Let the line perpendicular to side $\overline{AB}$ at point $E$ intersect side
$\overline{AC}$ at point $D$.
Since $\overline{ED}$ is parallel to $\overline{BC}$, then
$\angle ADE \cong \angle ACB$.
By the exterior angle theorem, $m\angle DEC = \dfrac{\alpha}{2}$.
Hence $\triangle EDC$ is isoceles.
So $CD = DE$.
(Added later). Assuming that the sides have lengths of $x$ and $y$, and that
$r = \sqrt{x^2+y^2}$, the lengths of the segments are displayed below.

A: Let $$CD=DE=y$$ then we get $$\frac{b}{c}=\frac{y}{c-y}$$ so $$y=\frac{bc}{b+c}$$

A: The curve that traces out the points that are equidistant to $C$ and the line extension of $AB$ is a parabola with focus $C$ and directrix $AB$.
Choosing a convenient coordinate system (parallel to $AB$ with $B$ as the origin), I get the equation $y = \frac{x^2}{2b} + \frac{b}{2}$, which you want to intersect with the line $y = \frac{b}{a}x + b$.
Solving, I get that the point $D$ has $(x,y)$ coordinates of $x = \frac{b(b - c)}{a}$ and $y = \frac{bc(c - b)}{a^2}$.

A: Not sure if this is less barbaric but using simple trig: $DE=(a-x)\tan A$, $DC=\frac{x}{\cos A}$ so the equation to solve is $$(a-x)\frac{b}{a}=\frac{x\sqrt{a^2+b^2}}{a}$$ or $$x=\frac{ab}{\sqrt{a^2+b^2}+b}$$
Just another idea to construct point $E$: since $\triangle{DCE}$ is isosceles, it's easy to find $\angle{ACE}=(90°-A)/2$


text:
Q: Database unique name and ticker I have created a SQLITE database that has some financial data in it as well as a stock ticker. The database looks like this:

Since the ticker of a stock (as well as the name) is unique, is it possible to only have the ticker in the database once for each particular company? Or would I need it to be an entry for each row (i.e. six entries for this company)
If it is the case I need six entries, is there a way to duplicate this using SQL commands? Since in the CSV file this data gets loaded in, the ticker is only there once, since it is unique.
Eventually I want to be able to do a WHERE clause on the ticker /company name to get the relevant information for that company.
When I run the WHERE clause query I get a KeyError:1
df = pd.read_sql_query("SELECT SALES, EBITDA FROM financials WHERE Ticker = 'HK001'", cnx)

It works fine if I omit the WHERE clause.
Thanks.
UPDATE: Following the comments:
cur.execute('DROP TABLE IF EXISTS financials')
cur.execute('''
CREATE TABLE "financials"(
    "Ticker" REAL,
    "Sales" REAL,
    "EBITDA" REAL,
    "index" REAL,
    "year" REAL,
    "Capitalization" REAL,
    "Entreprise Value (EV)" REAL,
    "P/E ratio" REAL,
    "Yield" REAL
)

update financials
set ticker = (
  select f.ticker
  from financials f
  where f.ticker is not null and f.rowid < financials.rowid
  order by f.rowid desc limit 1
)
where ticker is null)
''')

I'm not sure where the code from the update financials should go.

A: This statement:
SELECT SALES, EBITDA FROM financials WHERE Ticker = 'HK001'

is correct, but it will return only the row where Ticker = 'HK001'.
The best that you can do is update the table by filling the Ticker column with the correct value:
update financials
set ticker = (
  select f.ticker
  from financials f
  where f.ticker is not null and f.rowid < financials.rowid
  order by f.rowid desc limit 1
)
where ticker is null


text:
Q: What is the proper way to add a reference to Android Studio v0.8.10 I'm trying to add the GooglePlayServices SDK to a project following the directions here, however these instructions are specific to Eclipse. I have also found IntellJ instructions that are similar however not close enough.
Is there are quick tutorial specific to this version (yes I have looked)?
Thanks
EDIT:
I apologise that I was so vague in my question but I literally had to get this asked before going to a meeting. The reason I suspected that Google Play Services wasn't in Android Studio is because when I push the project to an emulator I get the following error:
Google Play Store is missing.
I/myLogs﹕ No valid Google Play Services APK found.

Is there something I can do to push the APK to the device?

A: To add GooglePlayServices to Android Studio, just use this page and select "Using Android Studio" from the dropdown. Start by adding the gradle dependency.
dependencies {
    ...
    compile 'com.google.android.gms:play-services:5.+'
}

Then add this to your manifest.
<meta-data android:name="com.google.android.gms.version"
       android:value="@integer/google_play_services_version" />